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   /// Vectorize Load and Store instructions with the base address given in \p
528   /// Addr, optionally masking the vector operations if \p BlockInMask is
529   /// non-null. Use \p State to translate given VPValues to IR values in the
530   /// vectorized loop.
531   void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
532                                   VPValue *Def, VPValue *Addr,
533                                   VPValue *StoredValue, VPValue *BlockInMask,
534                                   bool ConsecutiveStride, bool Reverse);
535 
536   /// Set the debug location in the builder \p Ptr using the debug location in
537   /// \p V. If \p Ptr is None then it uses the class member's Builder.
538   void setDebugLocFromInst(const Value *V,
539                            Optional<IRBuilder<> *> CustomBuilder = None);
540 
541   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
542   void fixNonInductionPHIs(VPTransformState &State);
543 
544   /// Returns true if the reordering of FP operations is not allowed, but we are
545   /// able to vectorize with strict in-order reductions for the given RdxDesc.
546   bool useOrderedReductions(RecurrenceDescriptor &RdxDesc);
547 
548   /// Create a broadcast instruction. This method generates a broadcast
549   /// instruction (shuffle) for loop invariant values and for the induction
550   /// value. If this is the induction variable then we extend it to N, N+1, ...
551   /// this is needed because each iteration in the loop corresponds to a SIMD
552   /// element.
553   virtual Value *getBroadcastInstrs(Value *V);
554 
555   /// Add metadata from one instruction to another.
556   ///
557   /// This includes both the original MDs from \p From and additional ones (\see
558   /// addNewMetadata).  Use this for *newly created* instructions in the vector
559   /// loop.
560   void addMetadata(Instruction *To, Instruction *From);
561 
562   /// Similar to the previous function but it adds the metadata to a
563   /// vector of instructions.
564   void addMetadata(ArrayRef<Value *> To, Instruction *From);
565 
566 protected:
567   friend class LoopVectorizationPlanner;
568 
569   /// A small list of PHINodes.
570   using PhiVector = SmallVector<PHINode *, 4>;
571 
572   /// A type for scalarized values in the new loop. Each value from the
573   /// original loop, when scalarized, is represented by UF x VF scalar values
574   /// in the new unrolled loop, where UF is the unroll factor and VF is the
575   /// vectorization factor.
576   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
577 
578   /// Set up the values of the IVs correctly when exiting the vector loop.
579   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
580                     Value *CountRoundDown, Value *EndValue,
581                     BasicBlock *MiddleBlock);
582 
583   /// Create a new induction variable inside L.
584   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
585                                    Value *Step, Instruction *DL);
586 
587   /// Handle all cross-iteration phis in the header.
588   void fixCrossIterationPHIs(VPTransformState &State);
589 
590   /// Create the exit value of first order recurrences in the middle block and
591   /// update their users.
592   void fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR, VPTransformState &State);
593 
594   /// Create code for the loop exit value of the reduction.
595   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
596 
597   /// Clear NSW/NUW flags from reduction instructions if necessary.
598   void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
599                                VPTransformState &State);
600 
601   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
602   /// means we need to add the appropriate incoming value from the middle
603   /// block as exiting edges from the scalar epilogue loop (if present) are
604   /// already in place, and we exit the vector loop exclusively to the middle
605   /// block.
606   void fixLCSSAPHIs(VPTransformState &State);
607 
608   /// Iteratively sink the scalarized operands of a predicated instruction into
609   /// the block that was created for it.
610   void sinkScalarOperands(Instruction *PredInst);
611 
612   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
613   /// represented as.
614   void truncateToMinimalBitwidths(VPTransformState &State);
615 
616   /// This function adds
617   /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
618   /// to each vector element of Val. The sequence starts at StartIndex.
619   /// \p Opcode is relevant for FP induction variable.
620   virtual Value *
621   getStepVector(Value *Val, Value *StartIdx, Value *Step,
622                 Instruction::BinaryOps Opcode = Instruction::BinaryOpsEnd);
623 
624   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
625   /// variable on which to base the steps, \p Step is the size of the step, and
626   /// \p EntryVal is the value from the original loop that maps to the steps.
627   /// Note that \p EntryVal doesn't have to be an induction variable - it
628   /// can also be a truncate instruction.
629   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
630                         const InductionDescriptor &ID, VPValue *Def,
631                         VPValue *CastDef, VPTransformState &State);
632 
633   /// Create a vector induction phi node based on an existing scalar one. \p
634   /// EntryVal is the value from the original loop that maps to the vector phi
635   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
636   /// truncate instruction, instead of widening the original IV, we widen a
637   /// version of the IV truncated to \p EntryVal's type.
638   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
639                                        Value *Step, Value *Start,
640                                        Instruction *EntryVal, VPValue *Def,
641                                        VPValue *CastDef,
642                                        VPTransformState &State);
643 
644   /// Returns true if an instruction \p I should be scalarized instead of
645   /// vectorized for the chosen vectorization factor.
646   bool shouldScalarizeInstruction(Instruction *I) const;
647 
648   /// Returns true if we should generate a scalar version of \p IV.
649   bool needsScalarInduction(Instruction *IV) const;
650 
651   /// If there is a cast involved in the induction variable \p ID, which should
652   /// be ignored in the vectorized loop body, this function records the
653   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
654   /// cast. We had already proved that the casted Phi is equal to the uncasted
655   /// Phi in the vectorized loop (under a runtime guard), and therefore
656   /// there is no need to vectorize the cast - the same value can be used in the
657   /// vector loop for both the Phi and the cast.
658   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
659   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
660   ///
661   /// \p EntryVal is the value from the original loop that maps to the vector
662   /// phi node and is used to distinguish what is the IV currently being
663   /// processed - original one (if \p EntryVal is a phi corresponding to the
664   /// original IV) or the "newly-created" one based on the proof mentioned above
665   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
666   /// latter case \p EntryVal is a TruncInst and we must not record anything for
667   /// that IV, but it's error-prone to expect callers of this routine to care
668   /// about that, hence this explicit parameter.
669   void recordVectorLoopValueForInductionCast(
670       const InductionDescriptor &ID, const Instruction *EntryVal,
671       Value *VectorLoopValue, VPValue *CastDef, VPTransformState &State,
672       unsigned Part, unsigned Lane = UINT_MAX);
673 
674   /// Generate a shuffle sequence that will reverse the vector Vec.
675   virtual Value *reverseVector(Value *Vec);
676 
677   /// Returns (and creates if needed) the original loop trip count.
678   Value *getOrCreateTripCount(Loop *NewLoop);
679 
680   /// Returns (and creates if needed) the trip count of the widened loop.
681   Value *getOrCreateVectorTripCount(Loop *NewLoop);
682 
683   /// Returns a bitcasted value to the requested vector type.
684   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
685   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
686                                 const DataLayout &DL);
687 
688   /// Emit a bypass check to see if the vector trip count is zero, including if
689   /// it overflows.
690   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
691 
692   /// Emit a bypass check to see if all of the SCEV assumptions we've
693   /// had to make are correct. Returns the block containing the checks or
694   /// nullptr if no checks have been added.
695   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
696 
697   /// Emit bypass checks to check any memory assumptions we may have made.
698   /// Returns the block containing the checks or nullptr if no checks have been
699   /// added.
700   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
701 
702   /// Compute the transformed value of Index at offset StartValue using step
703   /// StepValue.
704   /// For integer induction, returns StartValue + Index * StepValue.
705   /// For pointer induction, returns StartValue[Index * StepValue].
706   /// FIXME: The newly created binary instructions should contain nsw/nuw
707   /// flags, which can be found from the original scalar operations.
708   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
709                               const DataLayout &DL,
710                               const InductionDescriptor &ID) const;
711 
712   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
713   /// vector loop preheader, middle block and scalar preheader. Also
714   /// allocate a loop object for the new vector loop and return it.
715   Loop *createVectorLoopSkeleton(StringRef Prefix);
716 
717   /// Create new phi nodes for the induction variables to resume iteration count
718   /// in the scalar epilogue, from where the vectorized loop left off (given by
719   /// \p VectorTripCount).
720   /// In cases where the loop skeleton is more complicated (eg. epilogue
721   /// vectorization) and the resume values can come from an additional bypass
722   /// block, the \p AdditionalBypass pair provides information about the bypass
723   /// block and the end value on the edge from bypass to this loop.
724   void createInductionResumeValues(
725       Loop *L, Value *VectorTripCount,
726       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
727 
728   /// Complete the loop skeleton by adding debug MDs, creating appropriate
729   /// conditional branches in the middle block, preparing the builder and
730   /// running the verifier. Take in the vector loop \p L as argument, and return
731   /// the preheader of the completed vector loop.
732   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
733 
734   /// Add additional metadata to \p To that was not present on \p Orig.
735   ///
736   /// Currently this is used to add the noalias annotations based on the
737   /// inserted memchecks.  Use this for instructions that are *cloned* into the
738   /// vector loop.
739   void addNewMetadata(Instruction *To, const Instruction *Orig);
740 
741   /// Collect poison-generating recipes that may generate a poison value that is
742   /// used after vectorization, even when their operands are not poison. Those
743   /// recipes meet the following conditions:
744   ///  * Contribute to the address computation of a recipe generating a widen
745   ///    memory load/store (VPWidenMemoryInstructionRecipe or
746   ///    VPInterleaveRecipe).
747   ///  * Such a widen memory load/store has at least one underlying Instruction
748   ///    that is in a basic block that needs predication and after vectorization
749   ///    the generated instruction won't be predicated.
750   void collectPoisonGeneratingRecipes(VPTransformState &State);
751 
752   /// Allow subclasses to override and print debug traces before/after vplan
753   /// execution, when trace information is requested.
754   virtual void printDebugTracesAtStart(){};
755   virtual void printDebugTracesAtEnd(){};
756 
757   /// The original loop.
758   Loop *OrigLoop;
759 
760   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
761   /// dynamic knowledge to simplify SCEV expressions and converts them to a
762   /// more usable form.
763   PredicatedScalarEvolution &PSE;
764 
765   /// Loop Info.
766   LoopInfo *LI;
767 
768   /// Dominator Tree.
769   DominatorTree *DT;
770 
771   /// Alias Analysis.
772   AAResults *AA;
773 
774   /// Target Library Info.
775   const TargetLibraryInfo *TLI;
776 
777   /// Target Transform Info.
778   const TargetTransformInfo *TTI;
779 
780   /// Assumption Cache.
781   AssumptionCache *AC;
782 
783   /// Interface to emit optimization remarks.
784   OptimizationRemarkEmitter *ORE;
785 
786   /// LoopVersioning.  It's only set up (non-null) if memchecks were
787   /// used.
788   ///
789   /// This is currently only used to add no-alias metadata based on the
790   /// memchecks.  The actually versioning is performed manually.
791   std::unique_ptr<LoopVersioning> LVer;
792 
793   /// The vectorization SIMD factor to use. Each vector will have this many
794   /// vector elements.
795   ElementCount VF;
796 
797   /// The vectorization unroll factor to use. Each scalar is vectorized to this
798   /// many different vector instructions.
799   unsigned UF;
800 
801   /// The builder that we use
802   IRBuilder<> Builder;
803 
804   // --- Vectorization state ---
805 
806   /// The vector-loop preheader.
807   BasicBlock *LoopVectorPreHeader;
808 
809   /// The scalar-loop preheader.
810   BasicBlock *LoopScalarPreHeader;
811 
812   /// Middle Block between the vector and the scalar.
813   BasicBlock *LoopMiddleBlock;
814 
815   /// The unique ExitBlock of the scalar loop if one exists.  Note that
816   /// there can be multiple exiting edges reaching this block.
817   BasicBlock *LoopExitBlock;
818 
819   /// The vector loop body.
820   BasicBlock *LoopVectorBody;
821 
822   /// The scalar loop body.
823   BasicBlock *LoopScalarBody;
824 
825   /// A list of all bypass blocks. The first block is the entry of the loop.
826   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
827 
828   /// The new Induction variable which was added to the new block.
829   PHINode *Induction = nullptr;
830 
831   /// The induction variable of the old basic block.
832   PHINode *OldInduction = nullptr;
833 
834   /// Store instructions that were predicated.
835   SmallVector<Instruction *, 4> PredicatedInstructions;
836 
837   /// Trip count of the original loop.
838   Value *TripCount = nullptr;
839 
840   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
841   Value *VectorTripCount = nullptr;
842 
843   /// The legality analysis.
844   LoopVectorizationLegality *Legal;
845 
846   /// The profitablity analysis.
847   LoopVectorizationCostModel *Cost;
848 
849   // Record whether runtime checks are added.
850   bool AddedSafetyChecks = false;
851 
852   // Holds the end values for each induction variable. We save the end values
853   // so we can later fix-up the external users of the induction variables.
854   DenseMap<PHINode *, Value *> IVEndValues;
855 
856   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
857   // fixed up at the end of vector code generation.
858   SmallVector<PHINode *, 8> OrigPHIsToFix;
859 
860   /// BFI and PSI are used to check for profile guided size optimizations.
861   BlockFrequencyInfo *BFI;
862   ProfileSummaryInfo *PSI;
863 
864   // Whether this loop should be optimized for size based on profile guided size
865   // optimizatios.
866   bool OptForSizeBasedOnProfile;
867 
868   /// Structure to hold information about generated runtime checks, responsible
869   /// for cleaning the checks, if vectorization turns out unprofitable.
870   GeneratedRTChecks &RTChecks;
871 };
872 
873 class InnerLoopUnroller : public InnerLoopVectorizer {
874 public:
875   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
876                     LoopInfo *LI, DominatorTree *DT,
877                     const TargetLibraryInfo *TLI,
878                     const TargetTransformInfo *TTI, AssumptionCache *AC,
879                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
880                     LoopVectorizationLegality *LVL,
881                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
882                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
883       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
884                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
885                             BFI, PSI, Check) {}
886 
887 private:
888   Value *getBroadcastInstrs(Value *V) override;
889   Value *getStepVector(
890       Value *Val, Value *StartIdx, Value *Step,
891       Instruction::BinaryOps Opcode = Instruction::BinaryOpsEnd) override;
892   Value *reverseVector(Value *Vec) override;
893 };
894 
895 /// Encapsulate information regarding vectorization of a loop and its epilogue.
896 /// This information is meant to be updated and used across two stages of
897 /// epilogue vectorization.
898 struct EpilogueLoopVectorizationInfo {
899   ElementCount MainLoopVF = ElementCount::getFixed(0);
900   unsigned MainLoopUF = 0;
901   ElementCount EpilogueVF = ElementCount::getFixed(0);
902   unsigned EpilogueUF = 0;
903   BasicBlock *MainLoopIterationCountCheck = nullptr;
904   BasicBlock *EpilogueIterationCountCheck = nullptr;
905   BasicBlock *SCEVSafetyCheck = nullptr;
906   BasicBlock *MemSafetyCheck = nullptr;
907   Value *TripCount = nullptr;
908   Value *VectorTripCount = nullptr;
909 
910   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
911                                 ElementCount EVF, unsigned EUF)
912       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
913     assert(EUF == 1 &&
914            "A high UF for the epilogue loop is likely not beneficial.");
915   }
916 };
917 
918 /// An extension of the inner loop vectorizer that creates a skeleton for a
919 /// vectorized loop that has its epilogue (residual) also vectorized.
920 /// The idea is to run the vplan on a given loop twice, firstly to setup the
921 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
922 /// from the first step and vectorize the epilogue.  This is achieved by
923 /// deriving two concrete strategy classes from this base class and invoking
924 /// them in succession from the loop vectorizer planner.
925 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
926 public:
927   InnerLoopAndEpilogueVectorizer(
928       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
929       DominatorTree *DT, const TargetLibraryInfo *TLI,
930       const TargetTransformInfo *TTI, AssumptionCache *AC,
931       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
932       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
933       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
934       GeneratedRTChecks &Checks)
935       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
936                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
937                             Checks),
938         EPI(EPI) {}
939 
940   // Override this function to handle the more complex control flow around the
941   // three loops.
942   BasicBlock *createVectorizedLoopSkeleton() final override {
943     return createEpilogueVectorizedLoopSkeleton();
944   }
945 
946   /// The interface for creating a vectorized skeleton using one of two
947   /// different strategies, each corresponding to one execution of the vplan
948   /// as described above.
949   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
950 
951   /// Holds and updates state information required to vectorize the main loop
952   /// and its epilogue in two separate passes. This setup helps us avoid
953   /// regenerating and recomputing runtime safety checks. It also helps us to
954   /// shorten the iteration-count-check path length for the cases where the
955   /// iteration count of the loop is so small that the main vector loop is
956   /// completely skipped.
957   EpilogueLoopVectorizationInfo &EPI;
958 };
959 
960 /// A specialized derived class of inner loop vectorizer that performs
961 /// vectorization of *main* loops in the process of vectorizing loops and their
962 /// epilogues.
963 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
964 public:
965   EpilogueVectorizerMainLoop(
966       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
967       DominatorTree *DT, const TargetLibraryInfo *TLI,
968       const TargetTransformInfo *TTI, AssumptionCache *AC,
969       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
970       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
971       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
972       GeneratedRTChecks &Check)
973       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
974                                        EPI, LVL, CM, BFI, PSI, Check) {}
975   /// Implements the interface for creating a vectorized skeleton using the
976   /// *main loop* strategy (ie the first pass of vplan execution).
977   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
978 
979 protected:
980   /// Emits an iteration count bypass check once for the main loop (when \p
981   /// ForEpilogue is false) and once for the epilogue loop (when \p
982   /// ForEpilogue is true).
983   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
984                                              bool ForEpilogue);
985   void printDebugTracesAtStart() override;
986   void printDebugTracesAtEnd() override;
987 };
988 
989 // A specialized derived class of inner loop vectorizer that performs
990 // vectorization of *epilogue* loops in the process of vectorizing loops and
991 // their epilogues.
992 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
993 public:
994   EpilogueVectorizerEpilogueLoop(
995       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
996       DominatorTree *DT, const TargetLibraryInfo *TLI,
997       const TargetTransformInfo *TTI, AssumptionCache *AC,
998       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
999       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
1000       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
1001       GeneratedRTChecks &Checks)
1002       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
1003                                        EPI, LVL, CM, BFI, PSI, Checks) {}
1004   /// Implements the interface for creating a vectorized skeleton using the
1005   /// *epilogue loop* strategy (ie the second pass of vplan execution).
1006   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
1007 
1008 protected:
1009   /// Emits an iteration count bypass check after the main vector loop has
1010   /// finished to see if there are any iterations left to execute by either
1011   /// the vector epilogue or the scalar epilogue.
1012   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
1013                                                       BasicBlock *Bypass,
1014                                                       BasicBlock *Insert);
1015   void printDebugTracesAtStart() override;
1016   void printDebugTracesAtEnd() override;
1017 };
1018 } // end namespace llvm
1019 
1020 /// Look for a meaningful debug location on the instruction or it's
1021 /// operands.
1022 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
1023   if (!I)
1024     return I;
1025 
1026   DebugLoc Empty;
1027   if (I->getDebugLoc() != Empty)
1028     return I;
1029 
1030   for (Use &Op : I->operands()) {
1031     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1032       if (OpInst->getDebugLoc() != Empty)
1033         return OpInst;
1034   }
1035 
1036   return I;
1037 }
1038 
1039 void InnerLoopVectorizer::setDebugLocFromInst(
1040     const Value *V, Optional<IRBuilder<> *> CustomBuilder) {
1041   IRBuilder<> *B = (CustomBuilder == None) ? &Builder : *CustomBuilder;
1042   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
1043     const DILocation *DIL = Inst->getDebugLoc();
1044 
1045     // When a FSDiscriminator is enabled, we don't need to add the multiply
1046     // factors to the discriminators.
1047     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1048         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
1049       // FIXME: For scalable vectors, assume vscale=1.
1050       auto NewDIL =
1051           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1052       if (NewDIL)
1053         B->SetCurrentDebugLocation(NewDIL.getValue());
1054       else
1055         LLVM_DEBUG(dbgs()
1056                    << "Failed to create new discriminator: "
1057                    << DIL->getFilename() << " Line: " << DIL->getLine());
1058     } else
1059       B->SetCurrentDebugLocation(DIL);
1060   } else
1061     B->SetCurrentDebugLocation(DebugLoc());
1062 }
1063 
1064 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
1065 /// is passed, the message relates to that particular instruction.
1066 #ifndef NDEBUG
1067 static void debugVectorizationMessage(const StringRef Prefix,
1068                                       const StringRef DebugMsg,
1069                                       Instruction *I) {
1070   dbgs() << "LV: " << Prefix << DebugMsg;
1071   if (I != nullptr)
1072     dbgs() << " " << *I;
1073   else
1074     dbgs() << '.';
1075   dbgs() << '\n';
1076 }
1077 #endif
1078 
1079 /// Create an analysis remark that explains why vectorization failed
1080 ///
1081 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1082 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1083 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1084 /// the location of the remark.  \return the remark object that can be
1085 /// streamed to.
1086 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1087     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1088   Value *CodeRegion = TheLoop->getHeader();
1089   DebugLoc DL = TheLoop->getStartLoc();
1090 
1091   if (I) {
1092     CodeRegion = I->getParent();
1093     // If there is no debug location attached to the instruction, revert back to
1094     // using the loop's.
1095     if (I->getDebugLoc())
1096       DL = I->getDebugLoc();
1097   }
1098 
1099   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1100 }
1101 
1102 /// Return a value for Step multiplied by VF.
1103 static Value *createStepForVF(IRBuilder<> &B, Type *Ty, ElementCount VF,
1104                               int64_t Step) {
1105   assert(Ty->isIntegerTy() && "Expected an integer step");
1106   Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
1107   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1108 }
1109 
1110 namespace llvm {
1111 
1112 /// Return the runtime value for VF.
1113 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
1114   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1115   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1116 }
1117 
1118 static Value *getRuntimeVFAsFloat(IRBuilder<> &B, Type *FTy, ElementCount VF) {
1119   assert(FTy->isFloatingPointTy() && "Expected floating point type!");
1120   Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
1121   Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
1122   return B.CreateUIToFP(RuntimeVF, FTy);
1123 }
1124 
1125 void reportVectorizationFailure(const StringRef DebugMsg,
1126                                 const StringRef OREMsg, const StringRef ORETag,
1127                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1128                                 Instruction *I) {
1129   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1130   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1131   ORE->emit(
1132       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1133       << "loop not vectorized: " << OREMsg);
1134 }
1135 
1136 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1137                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1138                              Instruction *I) {
1139   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1140   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1141   ORE->emit(
1142       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1143       << Msg);
1144 }
1145 
1146 } // end namespace llvm
1147 
1148 #ifndef NDEBUG
1149 /// \return string containing a file name and a line # for the given loop.
1150 static std::string getDebugLocString(const Loop *L) {
1151   std::string Result;
1152   if (L) {
1153     raw_string_ostream OS(Result);
1154     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1155       LoopDbgLoc.print(OS);
1156     else
1157       // Just print the module name.
1158       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1159     OS.flush();
1160   }
1161   return Result;
1162 }
1163 #endif
1164 
1165 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1166                                          const Instruction *Orig) {
1167   // If the loop was versioned with memchecks, add the corresponding no-alias
1168   // metadata.
1169   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1170     LVer->annotateInstWithNoAlias(To, Orig);
1171 }
1172 
1173 void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
1174     VPTransformState &State) {
1175 
1176   // Collect recipes in the backward slice of `Root` that may generate a poison
1177   // value that is used after vectorization.
1178   SmallPtrSet<VPRecipeBase *, 16> Visited;
1179   auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1180     SmallVector<VPRecipeBase *, 16> Worklist;
1181     Worklist.push_back(Root);
1182 
1183     // Traverse the backward slice of Root through its use-def chain.
1184     while (!Worklist.empty()) {
1185       VPRecipeBase *CurRec = Worklist.back();
1186       Worklist.pop_back();
1187 
1188       if (!Visited.insert(CurRec).second)
1189         continue;
1190 
1191       // Prune search if we find another recipe generating a widen memory
1192       // instruction. Widen memory instructions involved in address computation
1193       // will lead to gather/scatter instructions, which don't need to be
1194       // handled.
1195       if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1196           isa<VPInterleaveRecipe>(CurRec))
1197         continue;
1198 
1199       // This recipe contributes to the address computation of a widen
1200       // load/store. Collect recipe if its underlying instruction has
1201       // poison-generating flags.
1202       Instruction *Instr = CurRec->getUnderlyingInstr();
1203       if (Instr && Instr->hasPoisonGeneratingFlags())
1204         State.MayGeneratePoisonRecipes.insert(CurRec);
1205 
1206       // Add new definitions to the worklist.
1207       for (VPValue *operand : CurRec->operands())
1208         if (VPDef *OpDef = operand->getDef())
1209           Worklist.push_back(cast<VPRecipeBase>(OpDef));
1210     }
1211   });
1212 
1213   // Traverse all the recipes in the VPlan and collect the poison-generating
1214   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1215   // VPInterleaveRecipe.
1216   auto Iter = depth_first(
1217       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
1218   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1219     for (VPRecipeBase &Recipe : *VPBB) {
1220       if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1221         Instruction *UnderlyingInstr = WidenRec->getUnderlyingInstr();
1222         VPDef *AddrDef = WidenRec->getAddr()->getDef();
1223         if (AddrDef && WidenRec->isConsecutive() && UnderlyingInstr &&
1224             Legal->blockNeedsPredication(UnderlyingInstr->getParent()))
1225           collectPoisonGeneratingInstrsInBackwardSlice(
1226               cast<VPRecipeBase>(AddrDef));
1227       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1228         VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1229         if (AddrDef) {
1230           // Check if any member of the interleave group needs predication.
1231           const InterleaveGroup<Instruction> *InterGroup =
1232               InterleaveRec->getInterleaveGroup();
1233           bool NeedPredication = false;
1234           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1235                I < NumMembers; ++I) {
1236             Instruction *Member = InterGroup->getMember(I);
1237             if (Member)
1238               NeedPredication |=
1239                   Legal->blockNeedsPredication(Member->getParent());
1240           }
1241 
1242           if (NeedPredication)
1243             collectPoisonGeneratingInstrsInBackwardSlice(
1244                 cast<VPRecipeBase>(AddrDef));
1245         }
1246       }
1247     }
1248   }
1249 }
1250 
1251 void InnerLoopVectorizer::addMetadata(Instruction *To,
1252                                       Instruction *From) {
1253   propagateMetadata(To, From);
1254   addNewMetadata(To, From);
1255 }
1256 
1257 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1258                                       Instruction *From) {
1259   for (Value *V : To) {
1260     if (Instruction *I = dyn_cast<Instruction>(V))
1261       addMetadata(I, From);
1262   }
1263 }
1264 
1265 namespace llvm {
1266 
1267 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1268 // lowered.
1269 enum ScalarEpilogueLowering {
1270 
1271   // The default: allowing scalar epilogues.
1272   CM_ScalarEpilogueAllowed,
1273 
1274   // Vectorization with OptForSize: don't allow epilogues.
1275   CM_ScalarEpilogueNotAllowedOptSize,
1276 
1277   // A special case of vectorisation with OptForSize: loops with a very small
1278   // trip count are considered for vectorization under OptForSize, thereby
1279   // making sure the cost of their loop body is dominant, free of runtime
1280   // guards and scalar iteration overheads.
1281   CM_ScalarEpilogueNotAllowedLowTripLoop,
1282 
1283   // Loop hint predicate indicating an epilogue is undesired.
1284   CM_ScalarEpilogueNotNeededUsePredicate,
1285 
1286   // Directive indicating we must either tail fold or not vectorize
1287   CM_ScalarEpilogueNotAllowedUsePredicate
1288 };
1289 
1290 /// ElementCountComparator creates a total ordering for ElementCount
1291 /// for the purposes of using it in a set structure.
1292 struct ElementCountComparator {
1293   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1294     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1295            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1296   }
1297 };
1298 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1299 
1300 /// LoopVectorizationCostModel - estimates the expected speedups due to
1301 /// vectorization.
1302 /// In many cases vectorization is not profitable. This can happen because of
1303 /// a number of reasons. In this class we mainly attempt to predict the
1304 /// expected speedup/slowdowns due to the supported instruction set. We use the
1305 /// TargetTransformInfo to query the different backends for the cost of
1306 /// different operations.
1307 class LoopVectorizationCostModel {
1308 public:
1309   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1310                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1311                              LoopVectorizationLegality *Legal,
1312                              const TargetTransformInfo &TTI,
1313                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1314                              AssumptionCache *AC,
1315                              OptimizationRemarkEmitter *ORE, const Function *F,
1316                              const LoopVectorizeHints *Hints,
1317                              InterleavedAccessInfo &IAI)
1318       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1319         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1320         Hints(Hints), InterleaveInfo(IAI) {}
1321 
1322   /// \return An upper bound for the vectorization factors (both fixed and
1323   /// scalable). If the factors are 0, vectorization and interleaving should be
1324   /// avoided up front.
1325   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1326 
1327   /// \return True if runtime checks are required for vectorization, and false
1328   /// otherwise.
1329   bool runtimeChecksRequired();
1330 
1331   /// \return The most profitable vectorization factor and the cost of that VF.
1332   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1333   /// then this vectorization factor will be selected if vectorization is
1334   /// possible.
1335   VectorizationFactor
1336   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1337 
1338   VectorizationFactor
1339   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1340                                     const LoopVectorizationPlanner &LVP);
1341 
1342   /// Setup cost-based decisions for user vectorization factor.
1343   /// \return true if the UserVF is a feasible VF to be chosen.
1344   bool selectUserVectorizationFactor(ElementCount UserVF) {
1345     collectUniformsAndScalars(UserVF);
1346     collectInstsToScalarize(UserVF);
1347     return expectedCost(UserVF).first.isValid();
1348   }
1349 
1350   /// \return The size (in bits) of the smallest and widest types in the code
1351   /// that needs to be vectorized. We ignore values that remain scalar such as
1352   /// 64 bit loop indices.
1353   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1354 
1355   /// \return The desired interleave count.
1356   /// If interleave count has been specified by metadata it will be returned.
1357   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1358   /// are the selected vectorization factor and the cost of the selected VF.
1359   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1360 
1361   /// Memory access instruction may be vectorized in more than one way.
1362   /// Form of instruction after vectorization depends on cost.
1363   /// This function takes cost-based decisions for Load/Store instructions
1364   /// and collects them in a map. This decisions map is used for building
1365   /// the lists of loop-uniform and loop-scalar instructions.
1366   /// The calculated cost is saved with widening decision in order to
1367   /// avoid redundant calculations.
1368   void setCostBasedWideningDecision(ElementCount VF);
1369 
1370   /// A struct that represents some properties of the register usage
1371   /// of a loop.
1372   struct RegisterUsage {
1373     /// Holds the number of loop invariant values that are used in the loop.
1374     /// The key is ClassID of target-provided register class.
1375     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1376     /// Holds the maximum number of concurrent live intervals in the loop.
1377     /// The key is ClassID of target-provided register class.
1378     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1379   };
1380 
1381   /// \return Returns information about the register usages of the loop for the
1382   /// given vectorization factors.
1383   SmallVector<RegisterUsage, 8>
1384   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1385 
1386   /// Collect values we want to ignore in the cost model.
1387   void collectValuesToIgnore();
1388 
1389   /// Collect all element types in the loop for which widening is needed.
1390   void collectElementTypesForWidening();
1391 
1392   /// Split reductions into those that happen in the loop, and those that happen
1393   /// outside. In loop reductions are collected into InLoopReductionChains.
1394   void collectInLoopReductions();
1395 
1396   /// Returns true if we should use strict in-order reductions for the given
1397   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1398   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1399   /// of FP operations.
1400   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1401     return !Hints->allowReordering() && RdxDesc.isOrdered();
1402   }
1403 
1404   /// \returns The smallest bitwidth each instruction can be represented with.
1405   /// The vector equivalents of these instructions should be truncated to this
1406   /// type.
1407   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1408     return MinBWs;
1409   }
1410 
1411   /// \returns True if it is more profitable to scalarize instruction \p I for
1412   /// vectorization factor \p VF.
1413   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1414     assert(VF.isVector() &&
1415            "Profitable to scalarize relevant only for VF > 1.");
1416 
1417     // Cost model is not run in the VPlan-native path - return conservative
1418     // result until this changes.
1419     if (EnableVPlanNativePath)
1420       return false;
1421 
1422     auto Scalars = InstsToScalarize.find(VF);
1423     assert(Scalars != InstsToScalarize.end() &&
1424            "VF not yet analyzed for scalarization profitability");
1425     return Scalars->second.find(I) != Scalars->second.end();
1426   }
1427 
1428   /// Returns true if \p I is known to be uniform after vectorization.
1429   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1430     if (VF.isScalar())
1431       return true;
1432 
1433     // Cost model is not run in the VPlan-native path - return conservative
1434     // result until this changes.
1435     if (EnableVPlanNativePath)
1436       return false;
1437 
1438     auto UniformsPerVF = Uniforms.find(VF);
1439     assert(UniformsPerVF != Uniforms.end() &&
1440            "VF not yet analyzed for uniformity");
1441     return UniformsPerVF->second.count(I);
1442   }
1443 
1444   /// Returns true if \p I is known to be scalar after vectorization.
1445   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1446     if (VF.isScalar())
1447       return true;
1448 
1449     // Cost model is not run in the VPlan-native path - return conservative
1450     // result until this changes.
1451     if (EnableVPlanNativePath)
1452       return false;
1453 
1454     auto ScalarsPerVF = Scalars.find(VF);
1455     assert(ScalarsPerVF != Scalars.end() &&
1456            "Scalar values are not calculated for VF");
1457     return ScalarsPerVF->second.count(I);
1458   }
1459 
1460   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1461   /// for vectorization factor \p VF.
1462   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1463     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1464            !isProfitableToScalarize(I, VF) &&
1465            !isScalarAfterVectorization(I, VF);
1466   }
1467 
1468   /// Decision that was taken during cost calculation for memory instruction.
1469   enum InstWidening {
1470     CM_Unknown,
1471     CM_Widen,         // For consecutive accesses with stride +1.
1472     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1473     CM_Interleave,
1474     CM_GatherScatter,
1475     CM_Scalarize
1476   };
1477 
1478   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1479   /// instruction \p I and vector width \p VF.
1480   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1481                            InstructionCost Cost) {
1482     assert(VF.isVector() && "Expected VF >=2");
1483     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1484   }
1485 
1486   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1487   /// interleaving group \p Grp and vector width \p VF.
1488   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1489                            ElementCount VF, InstWidening W,
1490                            InstructionCost Cost) {
1491     assert(VF.isVector() && "Expected VF >=2");
1492     /// Broadcast this decicion to all instructions inside the group.
1493     /// But the cost will be assigned to one instruction only.
1494     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1495       if (auto *I = Grp->getMember(i)) {
1496         if (Grp->getInsertPos() == I)
1497           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1498         else
1499           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1500       }
1501     }
1502   }
1503 
1504   /// Return the cost model decision for the given instruction \p I and vector
1505   /// width \p VF. Return CM_Unknown if this instruction did not pass
1506   /// through the cost modeling.
1507   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1508     assert(VF.isVector() && "Expected VF to be a vector VF");
1509     // Cost model is not run in the VPlan-native path - return conservative
1510     // result until this changes.
1511     if (EnableVPlanNativePath)
1512       return CM_GatherScatter;
1513 
1514     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1515     auto Itr = WideningDecisions.find(InstOnVF);
1516     if (Itr == WideningDecisions.end())
1517       return CM_Unknown;
1518     return Itr->second.first;
1519   }
1520 
1521   /// Return the vectorization cost for the given instruction \p I and vector
1522   /// width \p VF.
1523   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1524     assert(VF.isVector() && "Expected VF >=2");
1525     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1526     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1527            "The cost is not calculated");
1528     return WideningDecisions[InstOnVF].second;
1529   }
1530 
1531   /// Return True if instruction \p I is an optimizable truncate whose operand
1532   /// is an induction variable. Such a truncate will be removed by adding a new
1533   /// induction variable with the destination type.
1534   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1535     // If the instruction is not a truncate, return false.
1536     auto *Trunc = dyn_cast<TruncInst>(I);
1537     if (!Trunc)
1538       return false;
1539 
1540     // Get the source and destination types of the truncate.
1541     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1542     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1543 
1544     // If the truncate is free for the given types, return false. Replacing a
1545     // free truncate with an induction variable would add an induction variable
1546     // update instruction to each iteration of the loop. We exclude from this
1547     // check the primary induction variable since it will need an update
1548     // instruction regardless.
1549     Value *Op = Trunc->getOperand(0);
1550     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1551       return false;
1552 
1553     // If the truncated value is not an induction variable, return false.
1554     return Legal->isInductionPhi(Op);
1555   }
1556 
1557   /// Collects the instructions to scalarize for each predicated instruction in
1558   /// the loop.
1559   void collectInstsToScalarize(ElementCount VF);
1560 
1561   /// Collect Uniform and Scalar values for the given \p VF.
1562   /// The sets depend on CM decision for Load/Store instructions
1563   /// that may be vectorized as interleave, gather-scatter or scalarized.
1564   void collectUniformsAndScalars(ElementCount VF) {
1565     // Do the analysis once.
1566     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1567       return;
1568     setCostBasedWideningDecision(VF);
1569     collectLoopUniforms(VF);
1570     collectLoopScalars(VF);
1571   }
1572 
1573   /// Returns true if the target machine supports masked store operation
1574   /// for the given \p DataType and kind of access to \p Ptr.
1575   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1576     return Legal->isConsecutivePtr(DataType, Ptr) &&
1577            TTI.isLegalMaskedStore(DataType, Alignment);
1578   }
1579 
1580   /// Returns true if the target machine supports masked load operation
1581   /// for the given \p DataType and kind of access to \p Ptr.
1582   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1583     return Legal->isConsecutivePtr(DataType, Ptr) &&
1584            TTI.isLegalMaskedLoad(DataType, Alignment);
1585   }
1586 
1587   /// Returns true if the target machine can represent \p V as a masked gather
1588   /// or scatter operation.
1589   bool isLegalGatherOrScatter(Value *V) {
1590     bool LI = isa<LoadInst>(V);
1591     bool SI = isa<StoreInst>(V);
1592     if (!LI && !SI)
1593       return false;
1594     auto *Ty = getLoadStoreType(V);
1595     Align Align = getLoadStoreAlignment(V);
1596     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1597            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1598   }
1599 
1600   /// Returns true if the target machine supports all of the reduction
1601   /// variables found for the given VF.
1602   bool canVectorizeReductions(ElementCount VF) const {
1603     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1604       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1605       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1606     }));
1607   }
1608 
1609   /// Returns true if \p I is an instruction that will be scalarized with
1610   /// predication. Such instructions include conditional stores and
1611   /// instructions that may divide by zero.
1612   /// If a non-zero VF has been calculated, we check if I will be scalarized
1613   /// predication for that VF.
1614   bool isScalarWithPredication(Instruction *I) const;
1615 
1616   // Returns true if \p I is an instruction that will be predicated either
1617   // through scalar predication or masked load/store or masked gather/scatter.
1618   // Superset of instructions that return true for isScalarWithPredication.
1619   bool isPredicatedInst(Instruction *I, bool IsKnownUniform = false) {
1620     // When we know the load is uniform and the original scalar loop was not
1621     // predicated we don't need to mark it as a predicated instruction. Any
1622     // vectorised blocks created when tail-folding are something artificial we
1623     // have introduced and we know there is always at least one active lane.
1624     // That's why we call Legal->blockNeedsPredication here because it doesn't
1625     // query tail-folding.
1626     if (IsKnownUniform && isa<LoadInst>(I) &&
1627         !Legal->blockNeedsPredication(I->getParent()))
1628       return false;
1629     if (!blockNeedsPredicationForAnyReason(I->getParent()))
1630       return false;
1631     // Loads and stores that need some form of masked operation are predicated
1632     // instructions.
1633     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1634       return Legal->isMaskRequired(I);
1635     return isScalarWithPredication(I);
1636   }
1637 
1638   /// Returns true if \p I is a memory instruction with consecutive memory
1639   /// access that can be widened.
1640   bool
1641   memoryInstructionCanBeWidened(Instruction *I,
1642                                 ElementCount VF = ElementCount::getFixed(1));
1643 
1644   /// Returns true if \p I is a memory instruction in an interleaved-group
1645   /// of memory accesses that can be vectorized with wide vector loads/stores
1646   /// and shuffles.
1647   bool
1648   interleavedAccessCanBeWidened(Instruction *I,
1649                                 ElementCount VF = ElementCount::getFixed(1));
1650 
1651   /// Check if \p Instr belongs to any interleaved access group.
1652   bool isAccessInterleaved(Instruction *Instr) {
1653     return InterleaveInfo.isInterleaved(Instr);
1654   }
1655 
1656   /// Get the interleaved access group that \p Instr belongs to.
1657   const InterleaveGroup<Instruction> *
1658   getInterleavedAccessGroup(Instruction *Instr) {
1659     return InterleaveInfo.getInterleaveGroup(Instr);
1660   }
1661 
1662   /// Returns true if we're required to use a scalar epilogue for at least
1663   /// the final iteration of the original loop.
1664   bool requiresScalarEpilogue(ElementCount VF) const {
1665     if (!isScalarEpilogueAllowed())
1666       return false;
1667     // If we might exit from anywhere but the latch, must run the exiting
1668     // iteration in scalar form.
1669     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1670       return true;
1671     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1672   }
1673 
1674   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1675   /// loop hint annotation.
1676   bool isScalarEpilogueAllowed() const {
1677     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1678   }
1679 
1680   /// Returns true if all loop blocks should be masked to fold tail loop.
1681   bool foldTailByMasking() const { return FoldTailByMasking; }
1682 
1683   /// Returns true if the instructions in this block requires predication
1684   /// for any reason, e.g. because tail folding now requires a predicate
1685   /// or because the block in the original loop was predicated.
1686   bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
1687     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1688   }
1689 
1690   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1691   /// nodes to the chain of instructions representing the reductions. Uses a
1692   /// MapVector to ensure deterministic iteration order.
1693   using ReductionChainMap =
1694       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1695 
1696   /// Return the chain of instructions representing an inloop reduction.
1697   const ReductionChainMap &getInLoopReductionChains() const {
1698     return InLoopReductionChains;
1699   }
1700 
1701   /// Returns true if the Phi is part of an inloop reduction.
1702   bool isInLoopReduction(PHINode *Phi) const {
1703     return InLoopReductionChains.count(Phi);
1704   }
1705 
1706   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1707   /// with factor VF.  Return the cost of the instruction, including
1708   /// scalarization overhead if it's needed.
1709   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1710 
1711   /// Estimate cost of a call instruction CI if it were vectorized with factor
1712   /// VF. Return the cost of the instruction, including scalarization overhead
1713   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1714   /// scalarized -
1715   /// i.e. either vector version isn't available, or is too expensive.
1716   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1717                                     bool &NeedToScalarize) const;
1718 
1719   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1720   /// that of B.
1721   bool isMoreProfitable(const VectorizationFactor &A,
1722                         const VectorizationFactor &B) const;
1723 
1724   /// Invalidates decisions already taken by the cost model.
1725   void invalidateCostModelingDecisions() {
1726     WideningDecisions.clear();
1727     Uniforms.clear();
1728     Scalars.clear();
1729   }
1730 
1731 private:
1732   unsigned NumPredStores = 0;
1733 
1734   /// \return An upper bound for the vectorization factors for both
1735   /// fixed and scalable vectorization, where the minimum-known number of
1736   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1737   /// disabled or unsupported, then the scalable part will be equal to
1738   /// ElementCount::getScalable(0).
1739   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1740                                            ElementCount UserVF);
1741 
1742   /// \return the maximized element count based on the targets vector
1743   /// registers and the loop trip-count, but limited to a maximum safe VF.
1744   /// This is a helper function of computeFeasibleMaxVF.
1745   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1746   /// issue that occurred on one of the buildbots which cannot be reproduced
1747   /// without having access to the properietary compiler (see comments on
1748   /// D98509). The issue is currently under investigation and this workaround
1749   /// will be removed as soon as possible.
1750   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1751                                        unsigned SmallestType,
1752                                        unsigned WidestType,
1753                                        const ElementCount &MaxSafeVF);
1754 
1755   /// \return the maximum legal scalable VF, based on the safe max number
1756   /// of elements.
1757   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1758 
1759   /// The vectorization cost is a combination of the cost itself and a boolean
1760   /// indicating whether any of the contributing operations will actually
1761   /// operate on vector values after type legalization in the backend. If this
1762   /// latter value is false, then all operations will be scalarized (i.e. no
1763   /// vectorization has actually taken place).
1764   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1765 
1766   /// Returns the expected execution cost. The unit of the cost does
1767   /// not matter because we use the 'cost' units to compare different
1768   /// vector widths. The cost that is returned is *not* normalized by
1769   /// the factor width. If \p Invalid is not nullptr, this function
1770   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1771   /// each instruction that has an Invalid cost for the given VF.
1772   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1773   VectorizationCostTy
1774   expectedCost(ElementCount VF,
1775                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1776 
1777   /// Returns the execution time cost of an instruction for a given vector
1778   /// width. Vector width of one means scalar.
1779   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1780 
1781   /// The cost-computation logic from getInstructionCost which provides
1782   /// the vector type as an output parameter.
1783   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1784                                      Type *&VectorTy);
1785 
1786   /// Return the cost of instructions in an inloop reduction pattern, if I is
1787   /// part of that pattern.
1788   Optional<InstructionCost>
1789   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1790                           TTI::TargetCostKind CostKind);
1791 
1792   /// Calculate vectorization cost of memory instruction \p I.
1793   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1794 
1795   /// The cost computation for scalarized memory instruction.
1796   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1797 
1798   /// The cost computation for interleaving group of memory instructions.
1799   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1800 
1801   /// The cost computation for Gather/Scatter instruction.
1802   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1803 
1804   /// The cost computation for widening instruction \p I with consecutive
1805   /// memory access.
1806   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1807 
1808   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1809   /// Load: scalar load + broadcast.
1810   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1811   /// element)
1812   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1813 
1814   /// Estimate the overhead of scalarizing an instruction. This is a
1815   /// convenience wrapper for the type-based getScalarizationOverhead API.
1816   InstructionCost getScalarizationOverhead(Instruction *I,
1817                                            ElementCount VF) const;
1818 
1819   /// Returns whether the instruction is a load or store and will be a emitted
1820   /// as a vector operation.
1821   bool isConsecutiveLoadOrStore(Instruction *I);
1822 
1823   /// Returns true if an artificially high cost for emulated masked memrefs
1824   /// should be used.
1825   bool useEmulatedMaskMemRefHack(Instruction *I);
1826 
1827   /// Map of scalar integer values to the smallest bitwidth they can be legally
1828   /// represented as. The vector equivalents of these values should be truncated
1829   /// to this type.
1830   MapVector<Instruction *, uint64_t> MinBWs;
1831 
1832   /// A type representing the costs for instructions if they were to be
1833   /// scalarized rather than vectorized. The entries are Instruction-Cost
1834   /// pairs.
1835   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1836 
1837   /// A set containing all BasicBlocks that are known to present after
1838   /// vectorization as a predicated block.
1839   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1840 
1841   /// Records whether it is allowed to have the original scalar loop execute at
1842   /// least once. This may be needed as a fallback loop in case runtime
1843   /// aliasing/dependence checks fail, or to handle the tail/remainder
1844   /// iterations when the trip count is unknown or doesn't divide by the VF,
1845   /// or as a peel-loop to handle gaps in interleave-groups.
1846   /// Under optsize and when the trip count is very small we don't allow any
1847   /// iterations to execute in the scalar loop.
1848   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1849 
1850   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1851   bool FoldTailByMasking = false;
1852 
1853   /// A map holding scalar costs for different vectorization factors. The
1854   /// presence of a cost for an instruction in the mapping indicates that the
1855   /// instruction will be scalarized when vectorizing with the associated
1856   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1857   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1858 
1859   /// Holds the instructions known to be uniform after vectorization.
1860   /// The data is collected per VF.
1861   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1862 
1863   /// Holds the instructions known to be scalar after vectorization.
1864   /// The data is collected per VF.
1865   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1866 
1867   /// Holds the instructions (address computations) that are forced to be
1868   /// scalarized.
1869   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1870 
1871   /// PHINodes of the reductions that should be expanded in-loop along with
1872   /// their associated chains of reduction operations, in program order from top
1873   /// (PHI) to bottom
1874   ReductionChainMap InLoopReductionChains;
1875 
1876   /// A Map of inloop reduction operations and their immediate chain operand.
1877   /// FIXME: This can be removed once reductions can be costed correctly in
1878   /// vplan. This was added to allow quick lookup to the inloop operations,
1879   /// without having to loop through InLoopReductionChains.
1880   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1881 
1882   /// Returns the expected difference in cost from scalarizing the expression
1883   /// feeding a predicated instruction \p PredInst. The instructions to
1884   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1885   /// non-negative return value implies the expression will be scalarized.
1886   /// Currently, only single-use chains are considered for scalarization.
1887   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1888                               ElementCount VF);
1889 
1890   /// Collect the instructions that are uniform after vectorization. An
1891   /// instruction is uniform if we represent it with a single scalar value in
1892   /// the vectorized loop corresponding to each vector iteration. Examples of
1893   /// uniform instructions include pointer operands of consecutive or
1894   /// interleaved memory accesses. Note that although uniformity implies an
1895   /// instruction will be scalar, the reverse is not true. In general, a
1896   /// scalarized instruction will be represented by VF scalar values in the
1897   /// vectorized loop, each corresponding to an iteration of the original
1898   /// scalar loop.
1899   void collectLoopUniforms(ElementCount VF);
1900 
1901   /// Collect the instructions that are scalar after vectorization. An
1902   /// instruction is scalar if it is known to be uniform or will be scalarized
1903   /// during vectorization. collectLoopScalars should only add non-uniform nodes
1904   /// to the list if they are used by a load/store instruction that is marked as
1905   /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1906   /// VF values in the vectorized loop, each corresponding to an iteration of
1907   /// the original scalar loop.
1908   void collectLoopScalars(ElementCount VF);
1909 
1910   /// Keeps cost model vectorization decision and cost for instructions.
1911   /// Right now it is used for memory instructions only.
1912   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1913                                 std::pair<InstWidening, InstructionCost>>;
1914 
1915   DecisionList WideningDecisions;
1916 
1917   /// Returns true if \p V is expected to be vectorized and it needs to be
1918   /// extracted.
1919   bool needsExtract(Value *V, ElementCount VF) const {
1920     Instruction *I = dyn_cast<Instruction>(V);
1921     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1922         TheLoop->isLoopInvariant(I))
1923       return false;
1924 
1925     // Assume we can vectorize V (and hence we need extraction) if the
1926     // scalars are not computed yet. This can happen, because it is called
1927     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1928     // the scalars are collected. That should be a safe assumption in most
1929     // cases, because we check if the operands have vectorizable types
1930     // beforehand in LoopVectorizationLegality.
1931     return Scalars.find(VF) == Scalars.end() ||
1932            !isScalarAfterVectorization(I, VF);
1933   };
1934 
1935   /// Returns a range containing only operands needing to be extracted.
1936   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1937                                                    ElementCount VF) const {
1938     return SmallVector<Value *, 4>(make_filter_range(
1939         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1940   }
1941 
1942   /// Determines if we have the infrastructure to vectorize loop \p L and its
1943   /// epilogue, assuming the main loop is vectorized by \p VF.
1944   bool isCandidateForEpilogueVectorization(const Loop &L,
1945                                            const ElementCount VF) const;
1946 
1947   /// Returns true if epilogue vectorization is considered profitable, and
1948   /// false otherwise.
1949   /// \p VF is the vectorization factor chosen for the original loop.
1950   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1951 
1952 public:
1953   /// The loop that we evaluate.
1954   Loop *TheLoop;
1955 
1956   /// Predicated scalar evolution analysis.
1957   PredicatedScalarEvolution &PSE;
1958 
1959   /// Loop Info analysis.
1960   LoopInfo *LI;
1961 
1962   /// Vectorization legality.
1963   LoopVectorizationLegality *Legal;
1964 
1965   /// Vector target information.
1966   const TargetTransformInfo &TTI;
1967 
1968   /// Target Library Info.
1969   const TargetLibraryInfo *TLI;
1970 
1971   /// Demanded bits analysis.
1972   DemandedBits *DB;
1973 
1974   /// Assumption cache.
1975   AssumptionCache *AC;
1976 
1977   /// Interface to emit optimization remarks.
1978   OptimizationRemarkEmitter *ORE;
1979 
1980   const Function *TheFunction;
1981 
1982   /// Loop Vectorize Hint.
1983   const LoopVectorizeHints *Hints;
1984 
1985   /// The interleave access information contains groups of interleaved accesses
1986   /// with the same stride and close to each other.
1987   InterleavedAccessInfo &InterleaveInfo;
1988 
1989   /// Values to ignore in the cost model.
1990   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1991 
1992   /// Values to ignore in the cost model when VF > 1.
1993   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1994 
1995   /// All element types found in the loop.
1996   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1997 
1998   /// Profitable vector factors.
1999   SmallVector<VectorizationFactor, 8> ProfitableVFs;
2000 };
2001 } // end namespace llvm
2002 
2003 /// Helper struct to manage generating runtime checks for vectorization.
2004 ///
2005 /// The runtime checks are created up-front in temporary blocks to allow better
2006 /// estimating the cost and un-linked from the existing IR. After deciding to
2007 /// vectorize, the checks are moved back. If deciding not to vectorize, the
2008 /// temporary blocks are completely removed.
2009 class GeneratedRTChecks {
2010   /// Basic block which contains the generated SCEV checks, if any.
2011   BasicBlock *SCEVCheckBlock = nullptr;
2012 
2013   /// The value representing the result of the generated SCEV checks. If it is
2014   /// nullptr, either no SCEV checks have been generated or they have been used.
2015   Value *SCEVCheckCond = nullptr;
2016 
2017   /// Basic block which contains the generated memory runtime checks, if any.
2018   BasicBlock *MemCheckBlock = nullptr;
2019 
2020   /// The value representing the result of the generated memory runtime checks.
2021   /// If it is nullptr, either no memory runtime checks have been generated or
2022   /// they have been used.
2023   Value *MemRuntimeCheckCond = nullptr;
2024 
2025   DominatorTree *DT;
2026   LoopInfo *LI;
2027 
2028   SCEVExpander SCEVExp;
2029   SCEVExpander MemCheckExp;
2030 
2031 public:
2032   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
2033                     const DataLayout &DL)
2034       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
2035         MemCheckExp(SE, DL, "scev.check") {}
2036 
2037   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
2038   /// accurately estimate the cost of the runtime checks. The blocks are
2039   /// un-linked from the IR and is added back during vector code generation. If
2040   /// there is no vector code generation, the check blocks are removed
2041   /// completely.
2042   void Create(Loop *L, const LoopAccessInfo &LAI,
2043               const SCEVUnionPredicate &UnionPred) {
2044 
2045     BasicBlock *LoopHeader = L->getHeader();
2046     BasicBlock *Preheader = L->getLoopPreheader();
2047 
2048     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
2049     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
2050     // may be used by SCEVExpander. The blocks will be un-linked from their
2051     // predecessors and removed from LI & DT at the end of the function.
2052     if (!UnionPred.isAlwaysTrue()) {
2053       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
2054                                   nullptr, "vector.scevcheck");
2055 
2056       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
2057           &UnionPred, SCEVCheckBlock->getTerminator());
2058     }
2059 
2060     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
2061     if (RtPtrChecking.Need) {
2062       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
2063       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
2064                                  "vector.memcheck");
2065 
2066       MemRuntimeCheckCond =
2067           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
2068                            RtPtrChecking.getChecks(), MemCheckExp);
2069       assert(MemRuntimeCheckCond &&
2070              "no RT checks generated although RtPtrChecking "
2071              "claimed checks are required");
2072     }
2073 
2074     if (!MemCheckBlock && !SCEVCheckBlock)
2075       return;
2076 
2077     // Unhook the temporary block with the checks, update various places
2078     // accordingly.
2079     if (SCEVCheckBlock)
2080       SCEVCheckBlock->replaceAllUsesWith(Preheader);
2081     if (MemCheckBlock)
2082       MemCheckBlock->replaceAllUsesWith(Preheader);
2083 
2084     if (SCEVCheckBlock) {
2085       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2086       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
2087       Preheader->getTerminator()->eraseFromParent();
2088     }
2089     if (MemCheckBlock) {
2090       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2091       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
2092       Preheader->getTerminator()->eraseFromParent();
2093     }
2094 
2095     DT->changeImmediateDominator(LoopHeader, Preheader);
2096     if (MemCheckBlock) {
2097       DT->eraseNode(MemCheckBlock);
2098       LI->removeBlock(MemCheckBlock);
2099     }
2100     if (SCEVCheckBlock) {
2101       DT->eraseNode(SCEVCheckBlock);
2102       LI->removeBlock(SCEVCheckBlock);
2103     }
2104   }
2105 
2106   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2107   /// unused.
2108   ~GeneratedRTChecks() {
2109     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
2110     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
2111     if (!SCEVCheckCond)
2112       SCEVCleaner.markResultUsed();
2113 
2114     if (!MemRuntimeCheckCond)
2115       MemCheckCleaner.markResultUsed();
2116 
2117     if (MemRuntimeCheckCond) {
2118       auto &SE = *MemCheckExp.getSE();
2119       // Memory runtime check generation creates compares that use expanded
2120       // values. Remove them before running the SCEVExpanderCleaners.
2121       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2122         if (MemCheckExp.isInsertedInstruction(&I))
2123           continue;
2124         SE.forgetValue(&I);
2125         I.eraseFromParent();
2126       }
2127     }
2128     MemCheckCleaner.cleanup();
2129     SCEVCleaner.cleanup();
2130 
2131     if (SCEVCheckCond)
2132       SCEVCheckBlock->eraseFromParent();
2133     if (MemRuntimeCheckCond)
2134       MemCheckBlock->eraseFromParent();
2135   }
2136 
2137   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2138   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2139   /// depending on the generated condition.
2140   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2141                              BasicBlock *LoopVectorPreHeader,
2142                              BasicBlock *LoopExitBlock) {
2143     if (!SCEVCheckCond)
2144       return nullptr;
2145     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2146       if (C->isZero())
2147         return nullptr;
2148 
2149     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2150 
2151     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2152     // Create new preheader for vector loop.
2153     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2154       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2155 
2156     SCEVCheckBlock->getTerminator()->eraseFromParent();
2157     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2158     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2159                                                 SCEVCheckBlock);
2160 
2161     DT->addNewBlock(SCEVCheckBlock, Pred);
2162     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2163 
2164     ReplaceInstWithInst(
2165         SCEVCheckBlock->getTerminator(),
2166         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2167     // Mark the check as used, to prevent it from being removed during cleanup.
2168     SCEVCheckCond = nullptr;
2169     return SCEVCheckBlock;
2170   }
2171 
2172   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2173   /// the branches to branch to the vector preheader or \p Bypass, depending on
2174   /// the generated condition.
2175   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2176                                    BasicBlock *LoopVectorPreHeader) {
2177     // Check if we generated code that checks in runtime if arrays overlap.
2178     if (!MemRuntimeCheckCond)
2179       return nullptr;
2180 
2181     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2182     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2183                                                 MemCheckBlock);
2184 
2185     DT->addNewBlock(MemCheckBlock, Pred);
2186     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2187     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2188 
2189     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2190       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2191 
2192     ReplaceInstWithInst(
2193         MemCheckBlock->getTerminator(),
2194         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2195     MemCheckBlock->getTerminator()->setDebugLoc(
2196         Pred->getTerminator()->getDebugLoc());
2197 
2198     // Mark the check as used, to prevent it from being removed during cleanup.
2199     MemRuntimeCheckCond = nullptr;
2200     return MemCheckBlock;
2201   }
2202 };
2203 
2204 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2205 // vectorization. The loop needs to be annotated with #pragma omp simd
2206 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2207 // vector length information is not provided, vectorization is not considered
2208 // explicit. Interleave hints are not allowed either. These limitations will be
2209 // relaxed in the future.
2210 // Please, note that we are currently forced to abuse the pragma 'clang
2211 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2212 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2213 // provides *explicit vectorization hints* (LV can bypass legal checks and
2214 // assume that vectorization is legal). However, both hints are implemented
2215 // using the same metadata (llvm.loop.vectorize, processed by
2216 // LoopVectorizeHints). This will be fixed in the future when the native IR
2217 // representation for pragma 'omp simd' is introduced.
2218 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2219                                    OptimizationRemarkEmitter *ORE) {
2220   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2221   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2222 
2223   // Only outer loops with an explicit vectorization hint are supported.
2224   // Unannotated outer loops are ignored.
2225   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2226     return false;
2227 
2228   Function *Fn = OuterLp->getHeader()->getParent();
2229   if (!Hints.allowVectorization(Fn, OuterLp,
2230                                 true /*VectorizeOnlyWhenForced*/)) {
2231     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2232     return false;
2233   }
2234 
2235   if (Hints.getInterleave() > 1) {
2236     // TODO: Interleave support is future work.
2237     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2238                          "outer loops.\n");
2239     Hints.emitRemarkWithHints();
2240     return false;
2241   }
2242 
2243   return true;
2244 }
2245 
2246 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2247                                   OptimizationRemarkEmitter *ORE,
2248                                   SmallVectorImpl<Loop *> &V) {
2249   // Collect inner loops and outer loops without irreducible control flow. For
2250   // now, only collect outer loops that have explicit vectorization hints. If we
2251   // are stress testing the VPlan H-CFG construction, we collect the outermost
2252   // loop of every loop nest.
2253   if (L.isInnermost() || VPlanBuildStressTest ||
2254       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2255     LoopBlocksRPO RPOT(&L);
2256     RPOT.perform(LI);
2257     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2258       V.push_back(&L);
2259       // TODO: Collect inner loops inside marked outer loops in case
2260       // vectorization fails for the outer loop. Do not invoke
2261       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2262       // already known to be reducible. We can use an inherited attribute for
2263       // that.
2264       return;
2265     }
2266   }
2267   for (Loop *InnerL : L)
2268     collectSupportedLoops(*InnerL, LI, ORE, V);
2269 }
2270 
2271 namespace {
2272 
2273 /// The LoopVectorize Pass.
2274 struct LoopVectorize : public FunctionPass {
2275   /// Pass identification, replacement for typeid
2276   static char ID;
2277 
2278   LoopVectorizePass Impl;
2279 
2280   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2281                          bool VectorizeOnlyWhenForced = false)
2282       : FunctionPass(ID),
2283         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2284     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2285   }
2286 
2287   bool runOnFunction(Function &F) override {
2288     if (skipFunction(F))
2289       return false;
2290 
2291     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2292     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2293     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2294     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2295     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2296     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2297     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2298     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2299     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2300     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2301     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2302     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2303     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2304 
2305     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2306         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2307 
2308     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2309                         GetLAA, *ORE, PSI).MadeAnyChange;
2310   }
2311 
2312   void getAnalysisUsage(AnalysisUsage &AU) const override {
2313     AU.addRequired<AssumptionCacheTracker>();
2314     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2315     AU.addRequired<DominatorTreeWrapperPass>();
2316     AU.addRequired<LoopInfoWrapperPass>();
2317     AU.addRequired<ScalarEvolutionWrapperPass>();
2318     AU.addRequired<TargetTransformInfoWrapperPass>();
2319     AU.addRequired<AAResultsWrapperPass>();
2320     AU.addRequired<LoopAccessLegacyAnalysis>();
2321     AU.addRequired<DemandedBitsWrapperPass>();
2322     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2323     AU.addRequired<InjectTLIMappingsLegacy>();
2324 
2325     // We currently do not preserve loopinfo/dominator analyses with outer loop
2326     // vectorization. Until this is addressed, mark these analyses as preserved
2327     // only for non-VPlan-native path.
2328     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2329     if (!EnableVPlanNativePath) {
2330       AU.addPreserved<LoopInfoWrapperPass>();
2331       AU.addPreserved<DominatorTreeWrapperPass>();
2332     }
2333 
2334     AU.addPreserved<BasicAAWrapperPass>();
2335     AU.addPreserved<GlobalsAAWrapperPass>();
2336     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2337   }
2338 };
2339 
2340 } // end anonymous namespace
2341 
2342 //===----------------------------------------------------------------------===//
2343 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2344 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2345 //===----------------------------------------------------------------------===//
2346 
2347 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2348   // We need to place the broadcast of invariant variables outside the loop,
2349   // but only if it's proven safe to do so. Else, broadcast will be inside
2350   // vector loop body.
2351   Instruction *Instr = dyn_cast<Instruction>(V);
2352   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2353                      (!Instr ||
2354                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2355   // Place the code for broadcasting invariant variables in the new preheader.
2356   IRBuilder<>::InsertPointGuard Guard(Builder);
2357   if (SafeToHoist)
2358     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2359 
2360   // Broadcast the scalar into all locations in the vector.
2361   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2362 
2363   return Shuf;
2364 }
2365 
2366 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2367     const InductionDescriptor &II, Value *Step, Value *Start,
2368     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2369     VPTransformState &State) {
2370   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2371          "Expected either an induction phi-node or a truncate of it!");
2372 
2373   // Construct the initial value of the vector IV in the vector loop preheader
2374   auto CurrIP = Builder.saveIP();
2375   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2376   if (isa<TruncInst>(EntryVal)) {
2377     assert(Start->getType()->isIntegerTy() &&
2378            "Truncation requires an integer type");
2379     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2380     Step = Builder.CreateTrunc(Step, TruncType);
2381     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2382   }
2383 
2384   Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
2385   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2386   Value *SteppedStart =
2387       getStepVector(SplatStart, Zero, Step, II.getInductionOpcode());
2388 
2389   // We create vector phi nodes for both integer and floating-point induction
2390   // variables. Here, we determine the kind of arithmetic we will perform.
2391   Instruction::BinaryOps AddOp;
2392   Instruction::BinaryOps MulOp;
2393   if (Step->getType()->isIntegerTy()) {
2394     AddOp = Instruction::Add;
2395     MulOp = Instruction::Mul;
2396   } else {
2397     AddOp = II.getInductionOpcode();
2398     MulOp = Instruction::FMul;
2399   }
2400 
2401   // Multiply the vectorization factor by the step using integer or
2402   // floating-point arithmetic as appropriate.
2403   Type *StepType = Step->getType();
2404   Value *RuntimeVF;
2405   if (Step->getType()->isFloatingPointTy())
2406     RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, VF);
2407   else
2408     RuntimeVF = getRuntimeVF(Builder, StepType, VF);
2409   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2410 
2411   // Create a vector splat to use in the induction update.
2412   //
2413   // FIXME: If the step is non-constant, we create the vector splat with
2414   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2415   //        handle a constant vector splat.
2416   Value *SplatVF = isa<Constant>(Mul)
2417                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2418                        : Builder.CreateVectorSplat(VF, Mul);
2419   Builder.restoreIP(CurrIP);
2420 
2421   // We may need to add the step a number of times, depending on the unroll
2422   // factor. The last of those goes into the PHI.
2423   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2424                                     &*LoopVectorBody->getFirstInsertionPt());
2425   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2426   Instruction *LastInduction = VecInd;
2427   for (unsigned Part = 0; Part < UF; ++Part) {
2428     State.set(Def, LastInduction, Part);
2429 
2430     if (isa<TruncInst>(EntryVal))
2431       addMetadata(LastInduction, EntryVal);
2432     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2433                                           State, Part);
2434 
2435     LastInduction = cast<Instruction>(
2436         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2437     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2438   }
2439 
2440   // Move the last step to the end of the latch block. This ensures consistent
2441   // placement of all induction updates.
2442   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2443   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2444   auto *ICmp = cast<Instruction>(Br->getCondition());
2445   LastInduction->moveBefore(ICmp);
2446   LastInduction->setName("vec.ind.next");
2447 
2448   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2449   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2450 }
2451 
2452 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2453   return Cost->isScalarAfterVectorization(I, VF) ||
2454          Cost->isProfitableToScalarize(I, VF);
2455 }
2456 
2457 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2458   if (shouldScalarizeInstruction(IV))
2459     return true;
2460   auto isScalarInst = [&](User *U) -> bool {
2461     auto *I = cast<Instruction>(U);
2462     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2463   };
2464   return llvm::any_of(IV->users(), isScalarInst);
2465 }
2466 
2467 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2468     const InductionDescriptor &ID, const Instruction *EntryVal,
2469     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2470     unsigned Part, unsigned Lane) {
2471   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2472          "Expected either an induction phi-node or a truncate of it!");
2473 
2474   // This induction variable is not the phi from the original loop but the
2475   // newly-created IV based on the proof that casted Phi is equal to the
2476   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2477   // re-uses the same InductionDescriptor that original IV uses but we don't
2478   // have to do any recording in this case - that is done when original IV is
2479   // processed.
2480   if (isa<TruncInst>(EntryVal))
2481     return;
2482 
2483   if (!CastDef) {
2484     assert(ID.getCastInsts().empty() &&
2485            "there are casts for ID, but no CastDef");
2486     return;
2487   }
2488   assert(!ID.getCastInsts().empty() &&
2489          "there is a CastDef, but no casts for ID");
2490   // Only the first Cast instruction in the Casts vector is of interest.
2491   // The rest of the Casts (if exist) have no uses outside the
2492   // induction update chain itself.
2493   if (Lane < UINT_MAX)
2494     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2495   else
2496     State.set(CastDef, VectorLoopVal, Part);
2497 }
2498 
2499 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2500                                                 TruncInst *Trunc, VPValue *Def,
2501                                                 VPValue *CastDef,
2502                                                 VPTransformState &State) {
2503   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2504          "Primary induction variable must have an integer type");
2505 
2506   auto II = Legal->getInductionVars().find(IV);
2507   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2508 
2509   auto ID = II->second;
2510   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2511 
2512   // The value from the original loop to which we are mapping the new induction
2513   // variable.
2514   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2515 
2516   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2517 
2518   // Generate code for the induction step. Note that induction steps are
2519   // required to be loop-invariant
2520   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2521     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2522            "Induction step should be loop invariant");
2523     if (PSE.getSE()->isSCEVable(IV->getType())) {
2524       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2525       return Exp.expandCodeFor(Step, Step->getType(),
2526                                LoopVectorPreHeader->getTerminator());
2527     }
2528     return cast<SCEVUnknown>(Step)->getValue();
2529   };
2530 
2531   // The scalar value to broadcast. This is derived from the canonical
2532   // induction variable. If a truncation type is given, truncate the canonical
2533   // induction variable and step. Otherwise, derive these values from the
2534   // induction descriptor.
2535   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2536     Value *ScalarIV = Induction;
2537     if (IV != OldInduction) {
2538       ScalarIV = IV->getType()->isIntegerTy()
2539                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2540                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2541                                           IV->getType());
2542       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2543       ScalarIV->setName("offset.idx");
2544     }
2545     if (Trunc) {
2546       auto *TruncType = cast<IntegerType>(Trunc->getType());
2547       assert(Step->getType()->isIntegerTy() &&
2548              "Truncation requires an integer step");
2549       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2550       Step = Builder.CreateTrunc(Step, TruncType);
2551     }
2552     return ScalarIV;
2553   };
2554 
2555   // Create the vector values from the scalar IV, in the absence of creating a
2556   // vector IV.
2557   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2558     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2559     for (unsigned Part = 0; Part < UF; ++Part) {
2560       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2561       Value *StartIdx;
2562       if (Step->getType()->isFloatingPointTy())
2563         StartIdx = getRuntimeVFAsFloat(Builder, Step->getType(), VF * Part);
2564       else
2565         StartIdx = getRuntimeVF(Builder, Step->getType(), VF * Part);
2566 
2567       Value *EntryPart =
2568           getStepVector(Broadcasted, StartIdx, Step, ID.getInductionOpcode());
2569       State.set(Def, EntryPart, Part);
2570       if (Trunc)
2571         addMetadata(EntryPart, Trunc);
2572       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2573                                             State, Part);
2574     }
2575   };
2576 
2577   // Fast-math-flags propagate from the original induction instruction.
2578   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2579   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2580     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2581 
2582   // Now do the actual transformations, and start with creating the step value.
2583   Value *Step = CreateStepValue(ID.getStep());
2584   if (VF.isZero() || VF.isScalar()) {
2585     Value *ScalarIV = CreateScalarIV(Step);
2586     CreateSplatIV(ScalarIV, Step);
2587     return;
2588   }
2589 
2590   // Determine if we want a scalar version of the induction variable. This is
2591   // true if the induction variable itself is not widened, or if it has at
2592   // least one user in the loop that is not widened.
2593   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2594   if (!NeedsScalarIV) {
2595     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2596                                     State);
2597     return;
2598   }
2599 
2600   // Try to create a new independent vector induction variable. If we can't
2601   // create the phi node, we will splat the scalar induction variable in each
2602   // loop iteration.
2603   if (!shouldScalarizeInstruction(EntryVal)) {
2604     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2605                                     State);
2606     Value *ScalarIV = CreateScalarIV(Step);
2607     // Create scalar steps that can be used by instructions we will later
2608     // scalarize. Note that the addition of the scalar steps will not increase
2609     // the number of instructions in the loop in the common case prior to
2610     // InstCombine. We will be trading one vector extract for each scalar step.
2611     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2612     return;
2613   }
2614 
2615   // All IV users are scalar instructions, so only emit a scalar IV, not a
2616   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2617   // predicate used by the masked loads/stores.
2618   Value *ScalarIV = CreateScalarIV(Step);
2619   if (!Cost->isScalarEpilogueAllowed())
2620     CreateSplatIV(ScalarIV, Step);
2621   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2622 }
2623 
2624 Value *InnerLoopVectorizer::getStepVector(Value *Val, Value *StartIdx,
2625                                           Value *Step,
2626                                           Instruction::BinaryOps BinOp) {
2627   // Create and check the types.
2628   auto *ValVTy = cast<VectorType>(Val->getType());
2629   ElementCount VLen = ValVTy->getElementCount();
2630 
2631   Type *STy = Val->getType()->getScalarType();
2632   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2633          "Induction Step must be an integer or FP");
2634   assert(Step->getType() == STy && "Step has wrong type");
2635 
2636   SmallVector<Constant *, 8> Indices;
2637 
2638   // Create a vector of consecutive numbers from zero to VF.
2639   VectorType *InitVecValVTy = ValVTy;
2640   Type *InitVecValSTy = STy;
2641   if (STy->isFloatingPointTy()) {
2642     InitVecValSTy =
2643         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2644     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2645   }
2646   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2647 
2648   // Splat the StartIdx
2649   Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2650 
2651   if (STy->isIntegerTy()) {
2652     InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2653     Step = Builder.CreateVectorSplat(VLen, Step);
2654     assert(Step->getType() == Val->getType() && "Invalid step vec");
2655     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2656     // which can be found from the original scalar operations.
2657     Step = Builder.CreateMul(InitVec, Step);
2658     return Builder.CreateAdd(Val, Step, "induction");
2659   }
2660 
2661   // Floating point induction.
2662   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2663          "Binary Opcode should be specified for FP induction");
2664   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2665   InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2666 
2667   Step = Builder.CreateVectorSplat(VLen, Step);
2668   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2669   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2670 }
2671 
2672 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2673                                            Instruction *EntryVal,
2674                                            const InductionDescriptor &ID,
2675                                            VPValue *Def, VPValue *CastDef,
2676                                            VPTransformState &State) {
2677   // We shouldn't have to build scalar steps if we aren't vectorizing.
2678   assert(VF.isVector() && "VF should be greater than one");
2679   // Get the value type and ensure it and the step have the same integer type.
2680   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2681   assert(ScalarIVTy == Step->getType() &&
2682          "Val and Step should have the same type");
2683 
2684   // We build scalar steps for both integer and floating-point induction
2685   // variables. Here, we determine the kind of arithmetic we will perform.
2686   Instruction::BinaryOps AddOp;
2687   Instruction::BinaryOps MulOp;
2688   if (ScalarIVTy->isIntegerTy()) {
2689     AddOp = Instruction::Add;
2690     MulOp = Instruction::Mul;
2691   } else {
2692     AddOp = ID.getInductionOpcode();
2693     MulOp = Instruction::FMul;
2694   }
2695 
2696   // Determine the number of scalars we need to generate for each unroll
2697   // iteration. If EntryVal is uniform, we only need to generate the first
2698   // lane. Otherwise, we generate all VF values.
2699   bool IsUniform =
2700       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF);
2701   unsigned Lanes = IsUniform ? 1 : VF.getKnownMinValue();
2702   // Compute the scalar steps and save the results in State.
2703   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2704                                      ScalarIVTy->getScalarSizeInBits());
2705   Type *VecIVTy = nullptr;
2706   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2707   if (!IsUniform && VF.isScalable()) {
2708     VecIVTy = VectorType::get(ScalarIVTy, VF);
2709     UnitStepVec = Builder.CreateStepVector(VectorType::get(IntStepTy, VF));
2710     SplatStep = Builder.CreateVectorSplat(VF, Step);
2711     SplatIV = Builder.CreateVectorSplat(VF, ScalarIV);
2712   }
2713 
2714   for (unsigned Part = 0; Part < UF; ++Part) {
2715     Value *StartIdx0 = createStepForVF(Builder, IntStepTy, VF, Part);
2716 
2717     if (!IsUniform && VF.isScalable()) {
2718       auto *SplatStartIdx = Builder.CreateVectorSplat(VF, StartIdx0);
2719       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2720       if (ScalarIVTy->isFloatingPointTy())
2721         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2722       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2723       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2724       State.set(Def, Add, Part);
2725       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2726                                             Part);
2727       // It's useful to record the lane values too for the known minimum number
2728       // of elements so we do those below. This improves the code quality when
2729       // trying to extract the first element, for example.
2730     }
2731 
2732     if (ScalarIVTy->isFloatingPointTy())
2733       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2734 
2735     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2736       Value *StartIdx = Builder.CreateBinOp(
2737           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2738       // The step returned by `createStepForVF` is a runtime-evaluated value
2739       // when VF is scalable. Otherwise, it should be folded into a Constant.
2740       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2741              "Expected StartIdx to be folded to a constant when VF is not "
2742              "scalable");
2743       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2744       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2745       State.set(Def, Add, VPIteration(Part, Lane));
2746       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2747                                             Part, Lane);
2748     }
2749   }
2750 }
2751 
2752 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2753                                                     const VPIteration &Instance,
2754                                                     VPTransformState &State) {
2755   Value *ScalarInst = State.get(Def, Instance);
2756   Value *VectorValue = State.get(Def, Instance.Part);
2757   VectorValue = Builder.CreateInsertElement(
2758       VectorValue, ScalarInst,
2759       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2760   State.set(Def, VectorValue, Instance.Part);
2761 }
2762 
2763 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2764   assert(Vec->getType()->isVectorTy() && "Invalid type");
2765   return Builder.CreateVectorReverse(Vec, "reverse");
2766 }
2767 
2768 // Return whether we allow using masked interleave-groups (for dealing with
2769 // strided loads/stores that reside in predicated blocks, or for dealing
2770 // with gaps).
2771 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2772   // If an override option has been passed in for interleaved accesses, use it.
2773   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2774     return EnableMaskedInterleavedMemAccesses;
2775 
2776   return TTI.enableMaskedInterleavedAccessVectorization();
2777 }
2778 
2779 // Try to vectorize the interleave group that \p Instr belongs to.
2780 //
2781 // E.g. Translate following interleaved load group (factor = 3):
2782 //   for (i = 0; i < N; i+=3) {
2783 //     R = Pic[i];             // Member of index 0
2784 //     G = Pic[i+1];           // Member of index 1
2785 //     B = Pic[i+2];           // Member of index 2
2786 //     ... // do something to R, G, B
2787 //   }
2788 // To:
2789 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2790 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2791 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2792 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2793 //
2794 // Or translate following interleaved store group (factor = 3):
2795 //   for (i = 0; i < N; i+=3) {
2796 //     ... do something to R, G, B
2797 //     Pic[i]   = R;           // Member of index 0
2798 //     Pic[i+1] = G;           // Member of index 1
2799 //     Pic[i+2] = B;           // Member of index 2
2800 //   }
2801 // To:
2802 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2803 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2804 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2805 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2806 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2807 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2808     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2809     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2810     VPValue *BlockInMask) {
2811   Instruction *Instr = Group->getInsertPos();
2812   const DataLayout &DL = Instr->getModule()->getDataLayout();
2813 
2814   // Prepare for the vector type of the interleaved load/store.
2815   Type *ScalarTy = getLoadStoreType(Instr);
2816   unsigned InterleaveFactor = Group->getFactor();
2817   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2818   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2819 
2820   // Prepare for the new pointers.
2821   SmallVector<Value *, 2> AddrParts;
2822   unsigned Index = Group->getIndex(Instr);
2823 
2824   // TODO: extend the masked interleaved-group support to reversed access.
2825   assert((!BlockInMask || !Group->isReverse()) &&
2826          "Reversed masked interleave-group not supported.");
2827 
2828   // If the group is reverse, adjust the index to refer to the last vector lane
2829   // instead of the first. We adjust the index from the first vector lane,
2830   // rather than directly getting the pointer for lane VF - 1, because the
2831   // pointer operand of the interleaved access is supposed to be uniform. For
2832   // uniform instructions, we're only required to generate a value for the
2833   // first vector lane in each unroll iteration.
2834   if (Group->isReverse())
2835     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2836 
2837   for (unsigned Part = 0; Part < UF; Part++) {
2838     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2839     setDebugLocFromInst(AddrPart);
2840 
2841     // Notice current instruction could be any index. Need to adjust the address
2842     // to the member of index 0.
2843     //
2844     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2845     //       b = A[i];       // Member of index 0
2846     // Current pointer is pointed to A[i+1], adjust it to A[i].
2847     //
2848     // E.g.  A[i+1] = a;     // Member of index 1
2849     //       A[i]   = b;     // Member of index 0
2850     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2851     // Current pointer is pointed to A[i+2], adjust it to A[i].
2852 
2853     bool InBounds = false;
2854     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2855       InBounds = gep->isInBounds();
2856     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2857     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2858 
2859     // Cast to the vector pointer type.
2860     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2861     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2862     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2863   }
2864 
2865   setDebugLocFromInst(Instr);
2866   Value *PoisonVec = PoisonValue::get(VecTy);
2867 
2868   Value *MaskForGaps = nullptr;
2869   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2870     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2871     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2872   }
2873 
2874   // Vectorize the interleaved load group.
2875   if (isa<LoadInst>(Instr)) {
2876     // For each unroll part, create a wide load for the group.
2877     SmallVector<Value *, 2> NewLoads;
2878     for (unsigned Part = 0; Part < UF; Part++) {
2879       Instruction *NewLoad;
2880       if (BlockInMask || MaskForGaps) {
2881         assert(useMaskedInterleavedAccesses(*TTI) &&
2882                "masked interleaved groups are not allowed.");
2883         Value *GroupMask = MaskForGaps;
2884         if (BlockInMask) {
2885           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2886           Value *ShuffledMask = Builder.CreateShuffleVector(
2887               BlockInMaskPart,
2888               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2889               "interleaved.mask");
2890           GroupMask = MaskForGaps
2891                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2892                                                 MaskForGaps)
2893                           : ShuffledMask;
2894         }
2895         NewLoad =
2896             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2897                                      GroupMask, PoisonVec, "wide.masked.vec");
2898       }
2899       else
2900         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2901                                             Group->getAlign(), "wide.vec");
2902       Group->addMetadata(NewLoad);
2903       NewLoads.push_back(NewLoad);
2904     }
2905 
2906     // For each member in the group, shuffle out the appropriate data from the
2907     // wide loads.
2908     unsigned J = 0;
2909     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2910       Instruction *Member = Group->getMember(I);
2911 
2912       // Skip the gaps in the group.
2913       if (!Member)
2914         continue;
2915 
2916       auto StrideMask =
2917           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2918       for (unsigned Part = 0; Part < UF; Part++) {
2919         Value *StridedVec = Builder.CreateShuffleVector(
2920             NewLoads[Part], StrideMask, "strided.vec");
2921 
2922         // If this member has different type, cast the result type.
2923         if (Member->getType() != ScalarTy) {
2924           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2925           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2926           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2927         }
2928 
2929         if (Group->isReverse())
2930           StridedVec = reverseVector(StridedVec);
2931 
2932         State.set(VPDefs[J], StridedVec, Part);
2933       }
2934       ++J;
2935     }
2936     return;
2937   }
2938 
2939   // The sub vector type for current instruction.
2940   auto *SubVT = VectorType::get(ScalarTy, VF);
2941 
2942   // Vectorize the interleaved store group.
2943   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2944   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2945          "masked interleaved groups are not allowed.");
2946   assert((!MaskForGaps || !VF.isScalable()) &&
2947          "masking gaps for scalable vectors is not yet supported.");
2948   for (unsigned Part = 0; Part < UF; Part++) {
2949     // Collect the stored vector from each member.
2950     SmallVector<Value *, 4> StoredVecs;
2951     for (unsigned i = 0; i < InterleaveFactor; i++) {
2952       assert((Group->getMember(i) || MaskForGaps) &&
2953              "Fail to get a member from an interleaved store group");
2954       Instruction *Member = Group->getMember(i);
2955 
2956       // Skip the gaps in the group.
2957       if (!Member) {
2958         Value *Undef = PoisonValue::get(SubVT);
2959         StoredVecs.push_back(Undef);
2960         continue;
2961       }
2962 
2963       Value *StoredVec = State.get(StoredValues[i], Part);
2964 
2965       if (Group->isReverse())
2966         StoredVec = reverseVector(StoredVec);
2967 
2968       // If this member has different type, cast it to a unified type.
2969 
2970       if (StoredVec->getType() != SubVT)
2971         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2972 
2973       StoredVecs.push_back(StoredVec);
2974     }
2975 
2976     // Concatenate all vectors into a wide vector.
2977     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2978 
2979     // Interleave the elements in the wide vector.
2980     Value *IVec = Builder.CreateShuffleVector(
2981         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2982         "interleaved.vec");
2983 
2984     Instruction *NewStoreInstr;
2985     if (BlockInMask || MaskForGaps) {
2986       Value *GroupMask = MaskForGaps;
2987       if (BlockInMask) {
2988         Value *BlockInMaskPart = State.get(BlockInMask, Part);
2989         Value *ShuffledMask = Builder.CreateShuffleVector(
2990             BlockInMaskPart,
2991             createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2992             "interleaved.mask");
2993         GroupMask = MaskForGaps ? Builder.CreateBinOp(Instruction::And,
2994                                                       ShuffledMask, MaskForGaps)
2995                                 : ShuffledMask;
2996       }
2997       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2998                                                 Group->getAlign(), GroupMask);
2999     } else
3000       NewStoreInstr =
3001           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
3002 
3003     Group->addMetadata(NewStoreInstr);
3004   }
3005 }
3006 
3007 void InnerLoopVectorizer::vectorizeMemoryInstruction(
3008     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
3009     VPValue *StoredValue, VPValue *BlockInMask, bool ConsecutiveStride,
3010     bool Reverse) {
3011   // Attempt to issue a wide load.
3012   LoadInst *LI = dyn_cast<LoadInst>(Instr);
3013   StoreInst *SI = dyn_cast<StoreInst>(Instr);
3014 
3015   assert((LI || SI) && "Invalid Load/Store instruction");
3016   assert((!SI || StoredValue) && "No stored value provided for widened store");
3017   assert((!LI || !StoredValue) && "Stored value provided for widened load");
3018 
3019   Type *ScalarDataTy = getLoadStoreType(Instr);
3020 
3021   auto *DataTy = VectorType::get(ScalarDataTy, VF);
3022   const Align Alignment = getLoadStoreAlignment(Instr);
3023   bool CreateGatherScatter = !ConsecutiveStride;
3024 
3025   VectorParts BlockInMaskParts(UF);
3026   bool isMaskRequired = BlockInMask;
3027   if (isMaskRequired)
3028     for (unsigned Part = 0; Part < UF; ++Part)
3029       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
3030 
3031   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
3032     // Calculate the pointer for the specific unroll-part.
3033     GetElementPtrInst *PartPtr = nullptr;
3034 
3035     bool InBounds = false;
3036     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
3037       InBounds = gep->isInBounds();
3038     if (Reverse) {
3039       // If the address is consecutive but reversed, then the
3040       // wide store needs to start at the last vector element.
3041       // RunTimeVF =  VScale * VF.getKnownMinValue()
3042       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
3043       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), VF);
3044       // NumElt = -Part * RunTimeVF
3045       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
3046       // LastLane = 1 - RunTimeVF
3047       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
3048       PartPtr =
3049           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
3050       PartPtr->setIsInBounds(InBounds);
3051       PartPtr = cast<GetElementPtrInst>(
3052           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
3053       PartPtr->setIsInBounds(InBounds);
3054       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
3055         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
3056     } else {
3057       Value *Increment =
3058           createStepForVF(Builder, Builder.getInt32Ty(), VF, Part);
3059       PartPtr = cast<GetElementPtrInst>(
3060           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
3061       PartPtr->setIsInBounds(InBounds);
3062     }
3063 
3064     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
3065     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
3066   };
3067 
3068   // Handle Stores:
3069   if (SI) {
3070     setDebugLocFromInst(SI);
3071 
3072     for (unsigned Part = 0; Part < UF; ++Part) {
3073       Instruction *NewSI = nullptr;
3074       Value *StoredVal = State.get(StoredValue, Part);
3075       if (CreateGatherScatter) {
3076         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
3077         Value *VectorGep = State.get(Addr, Part);
3078         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
3079                                             MaskPart);
3080       } else {
3081         if (Reverse) {
3082           // If we store to reverse consecutive memory locations, then we need
3083           // to reverse the order of elements in the stored value.
3084           StoredVal = reverseVector(StoredVal);
3085           // We don't want to update the value in the map as it might be used in
3086           // another expression. So don't call resetVectorValue(StoredVal).
3087         }
3088         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
3089         if (isMaskRequired)
3090           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
3091                                             BlockInMaskParts[Part]);
3092         else
3093           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
3094       }
3095       addMetadata(NewSI, SI);
3096     }
3097     return;
3098   }
3099 
3100   // Handle loads.
3101   assert(LI && "Must have a load instruction");
3102   setDebugLocFromInst(LI);
3103   for (unsigned Part = 0; Part < UF; ++Part) {
3104     Value *NewLI;
3105     if (CreateGatherScatter) {
3106       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
3107       Value *VectorGep = State.get(Addr, Part);
3108       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
3109                                          nullptr, "wide.masked.gather");
3110       addMetadata(NewLI, LI);
3111     } else {
3112       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
3113       if (isMaskRequired)
3114         NewLI = Builder.CreateMaskedLoad(
3115             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
3116             PoisonValue::get(DataTy), "wide.masked.load");
3117       else
3118         NewLI =
3119             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
3120 
3121       // Add metadata to the load, but setVectorValue to the reverse shuffle.
3122       addMetadata(NewLI, LI);
3123       if (Reverse)
3124         NewLI = reverseVector(NewLI);
3125     }
3126 
3127     State.set(Def, NewLI, Part);
3128   }
3129 }
3130 
3131 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
3132                                                VPReplicateRecipe *RepRecipe,
3133                                                const VPIteration &Instance,
3134                                                bool IfPredicateInstr,
3135                                                VPTransformState &State) {
3136   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3137 
3138   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
3139   // the first lane and part.
3140   if (isa<NoAliasScopeDeclInst>(Instr))
3141     if (!Instance.isFirstIteration())
3142       return;
3143 
3144   setDebugLocFromInst(Instr);
3145 
3146   // Does this instruction return a value ?
3147   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3148 
3149   Instruction *Cloned = Instr->clone();
3150   if (!IsVoidRetTy)
3151     Cloned->setName(Instr->getName() + ".cloned");
3152 
3153   // If the scalarized instruction contributes to the address computation of a
3154   // widen masked load/store which was in a basic block that needed predication
3155   // and is not predicated after vectorization, we can't propagate
3156   // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
3157   // instruction could feed a poison value to the base address of the widen
3158   // load/store.
3159   if (State.MayGeneratePoisonRecipes.count(RepRecipe) > 0)
3160     Cloned->dropPoisonGeneratingFlags();
3161 
3162   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
3163                                Builder.GetInsertPoint());
3164   // Replace the operands of the cloned instructions with their scalar
3165   // equivalents in the new loop.
3166   for (unsigned op = 0, e = RepRecipe->getNumOperands(); op != e; ++op) {
3167     auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
3168     auto InputInstance = Instance;
3169     if (!Operand || !OrigLoop->contains(Operand) ||
3170         (Cost->isUniformAfterVectorization(Operand, State.VF)))
3171       InputInstance.Lane = VPLane::getFirstLane();
3172     auto *NewOp = State.get(RepRecipe->getOperand(op), InputInstance);
3173     Cloned->setOperand(op, NewOp);
3174   }
3175   addNewMetadata(Cloned, Instr);
3176 
3177   // Place the cloned scalar in the new loop.
3178   Builder.Insert(Cloned);
3179 
3180   State.set(RepRecipe, Cloned, Instance);
3181 
3182   // If we just cloned a new assumption, add it the assumption cache.
3183   if (auto *II = dyn_cast<AssumeInst>(Cloned))
3184     AC->registerAssumption(II);
3185 
3186   // End if-block.
3187   if (IfPredicateInstr)
3188     PredicatedInstructions.push_back(Cloned);
3189 }
3190 
3191 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3192                                                       Value *End, Value *Step,
3193                                                       Instruction *DL) {
3194   BasicBlock *Header = L->getHeader();
3195   BasicBlock *Latch = L->getLoopLatch();
3196   // As we're just creating this loop, it's possible no latch exists
3197   // yet. If so, use the header as this will be a single block loop.
3198   if (!Latch)
3199     Latch = Header;
3200 
3201   IRBuilder<> B(&*Header->getFirstInsertionPt());
3202   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3203   setDebugLocFromInst(OldInst, &B);
3204   auto *Induction = B.CreatePHI(Start->getType(), 2, "index");
3205 
3206   B.SetInsertPoint(Latch->getTerminator());
3207   setDebugLocFromInst(OldInst, &B);
3208 
3209   // Create i+1 and fill the PHINode.
3210   //
3211   // If the tail is not folded, we know that End - Start >= Step (either
3212   // statically or through the minimum iteration checks). We also know that both
3213   // Start % Step == 0 and End % Step == 0. We exit the vector loop if %IV +
3214   // %Step == %End. Hence we must exit the loop before %IV + %Step unsigned
3215   // overflows and we can mark the induction increment as NUW.
3216   Value *Next = B.CreateAdd(Induction, Step, "index.next",
3217                             /*NUW=*/!Cost->foldTailByMasking(), /*NSW=*/false);
3218   Induction->addIncoming(Start, L->getLoopPreheader());
3219   Induction->addIncoming(Next, Latch);
3220   // Create the compare.
3221   Value *ICmp = B.CreateICmpEQ(Next, End);
3222   B.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3223 
3224   // Now we have two terminators. Remove the old one from the block.
3225   Latch->getTerminator()->eraseFromParent();
3226 
3227   return Induction;
3228 }
3229 
3230 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3231   if (TripCount)
3232     return TripCount;
3233 
3234   assert(L && "Create Trip Count for null loop.");
3235   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3236   // Find the loop boundaries.
3237   ScalarEvolution *SE = PSE.getSE();
3238   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3239   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3240          "Invalid loop count");
3241 
3242   Type *IdxTy = Legal->getWidestInductionType();
3243   assert(IdxTy && "No type for induction");
3244 
3245   // The exit count might have the type of i64 while the phi is i32. This can
3246   // happen if we have an induction variable that is sign extended before the
3247   // compare. The only way that we get a backedge taken count is that the
3248   // induction variable was signed and as such will not overflow. In such a case
3249   // truncation is legal.
3250   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3251       IdxTy->getPrimitiveSizeInBits())
3252     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3253   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3254 
3255   // Get the total trip count from the count by adding 1.
3256   const SCEV *ExitCount = SE->getAddExpr(
3257       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3258 
3259   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3260 
3261   // Expand the trip count and place the new instructions in the preheader.
3262   // Notice that the pre-header does not change, only the loop body.
3263   SCEVExpander Exp(*SE, DL, "induction");
3264 
3265   // Count holds the overall loop count (N).
3266   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3267                                 L->getLoopPreheader()->getTerminator());
3268 
3269   if (TripCount->getType()->isPointerTy())
3270     TripCount =
3271         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3272                                     L->getLoopPreheader()->getTerminator());
3273 
3274   return TripCount;
3275 }
3276 
3277 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3278   if (VectorTripCount)
3279     return VectorTripCount;
3280 
3281   Value *TC = getOrCreateTripCount(L);
3282   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3283 
3284   Type *Ty = TC->getType();
3285   // This is where we can make the step a runtime constant.
3286   Value *Step = createStepForVF(Builder, Ty, VF, UF);
3287 
3288   // If the tail is to be folded by masking, round the number of iterations N
3289   // up to a multiple of Step instead of rounding down. This is done by first
3290   // adding Step-1 and then rounding down. Note that it's ok if this addition
3291   // overflows: the vector induction variable will eventually wrap to zero given
3292   // that it starts at zero and its Step is a power of two; the loop will then
3293   // exit, with the last early-exit vector comparison also producing all-true.
3294   if (Cost->foldTailByMasking()) {
3295     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3296            "VF*UF must be a power of 2 when folding tail by masking");
3297     assert(!VF.isScalable() &&
3298            "Tail folding not yet supported for scalable vectors");
3299     TC = Builder.CreateAdd(
3300         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3301   }
3302 
3303   // Now we need to generate the expression for the part of the loop that the
3304   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3305   // iterations are not required for correctness, or N - Step, otherwise. Step
3306   // is equal to the vectorization factor (number of SIMD elements) times the
3307   // unroll factor (number of SIMD instructions).
3308   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3309 
3310   // There are cases where we *must* run at least one iteration in the remainder
3311   // loop.  See the cost model for when this can happen.  If the step evenly
3312   // divides the trip count, we set the remainder to be equal to the step. If
3313   // the step does not evenly divide the trip count, no adjustment is necessary
3314   // since there will already be scalar iterations. Note that the minimum
3315   // iterations check ensures that N >= Step.
3316   if (Cost->requiresScalarEpilogue(VF)) {
3317     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3318     R = Builder.CreateSelect(IsZero, Step, R);
3319   }
3320 
3321   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3322 
3323   return VectorTripCount;
3324 }
3325 
3326 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3327                                                    const DataLayout &DL) {
3328   // Verify that V is a vector type with same number of elements as DstVTy.
3329   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3330   unsigned VF = DstFVTy->getNumElements();
3331   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3332   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3333   Type *SrcElemTy = SrcVecTy->getElementType();
3334   Type *DstElemTy = DstFVTy->getElementType();
3335   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3336          "Vector elements must have same size");
3337 
3338   // Do a direct cast if element types are castable.
3339   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3340     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3341   }
3342   // V cannot be directly casted to desired vector type.
3343   // May happen when V is a floating point vector but DstVTy is a vector of
3344   // pointers or vice-versa. Handle this using a two-step bitcast using an
3345   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3346   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3347          "Only one type should be a pointer type");
3348   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3349          "Only one type should be a floating point type");
3350   Type *IntTy =
3351       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3352   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3353   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3354   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3355 }
3356 
3357 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3358                                                          BasicBlock *Bypass) {
3359   Value *Count = getOrCreateTripCount(L);
3360   // Reuse existing vector loop preheader for TC checks.
3361   // Note that new preheader block is generated for vector loop.
3362   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3363   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3364 
3365   // Generate code to check if the loop's trip count is less than VF * UF, or
3366   // equal to it in case a scalar epilogue is required; this implies that the
3367   // vector trip count is zero. This check also covers the case where adding one
3368   // to the backedge-taken count overflowed leading to an incorrect trip count
3369   // of zero. In this case we will also jump to the scalar loop.
3370   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
3371                                             : ICmpInst::ICMP_ULT;
3372 
3373   // If tail is to be folded, vector loop takes care of all iterations.
3374   Value *CheckMinIters = Builder.getFalse();
3375   if (!Cost->foldTailByMasking()) {
3376     Value *Step = createStepForVF(Builder, Count->getType(), VF, UF);
3377     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3378   }
3379   // Create new preheader for vector loop.
3380   LoopVectorPreHeader =
3381       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3382                  "vector.ph");
3383 
3384   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3385                                DT->getNode(Bypass)->getIDom()) &&
3386          "TC check is expected to dominate Bypass");
3387 
3388   // Update dominator for Bypass & LoopExit (if needed).
3389   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3390   if (!Cost->requiresScalarEpilogue(VF))
3391     // If there is an epilogue which must run, there's no edge from the
3392     // middle block to exit blocks  and thus no need to update the immediate
3393     // dominator of the exit blocks.
3394     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3395 
3396   ReplaceInstWithInst(
3397       TCCheckBlock->getTerminator(),
3398       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3399   LoopBypassBlocks.push_back(TCCheckBlock);
3400 }
3401 
3402 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3403 
3404   BasicBlock *const SCEVCheckBlock =
3405       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3406   if (!SCEVCheckBlock)
3407     return nullptr;
3408 
3409   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3410            (OptForSizeBasedOnProfile &&
3411             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3412          "Cannot SCEV check stride or overflow when optimizing for size");
3413 
3414 
3415   // Update dominator only if this is first RT check.
3416   if (LoopBypassBlocks.empty()) {
3417     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3418     if (!Cost->requiresScalarEpilogue(VF))
3419       // If there is an epilogue which must run, there's no edge from the
3420       // middle block to exit blocks  and thus no need to update the immediate
3421       // dominator of the exit blocks.
3422       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3423   }
3424 
3425   LoopBypassBlocks.push_back(SCEVCheckBlock);
3426   AddedSafetyChecks = true;
3427   return SCEVCheckBlock;
3428 }
3429 
3430 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3431                                                       BasicBlock *Bypass) {
3432   // VPlan-native path does not do any analysis for runtime checks currently.
3433   if (EnableVPlanNativePath)
3434     return nullptr;
3435 
3436   BasicBlock *const MemCheckBlock =
3437       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3438 
3439   // Check if we generated code that checks in runtime if arrays overlap. We put
3440   // the checks into a separate block to make the more common case of few
3441   // elements faster.
3442   if (!MemCheckBlock)
3443     return nullptr;
3444 
3445   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3446     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3447            "Cannot emit memory checks when optimizing for size, unless forced "
3448            "to vectorize.");
3449     ORE->emit([&]() {
3450       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3451                                         L->getStartLoc(), L->getHeader())
3452              << "Code-size may be reduced by not forcing "
3453                 "vectorization, or by source-code modifications "
3454                 "eliminating the need for runtime checks "
3455                 "(e.g., adding 'restrict').";
3456     });
3457   }
3458 
3459   LoopBypassBlocks.push_back(MemCheckBlock);
3460 
3461   AddedSafetyChecks = true;
3462 
3463   // We currently don't use LoopVersioning for the actual loop cloning but we
3464   // still use it to add the noalias metadata.
3465   LVer = std::make_unique<LoopVersioning>(
3466       *Legal->getLAI(),
3467       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3468       DT, PSE.getSE());
3469   LVer->prepareNoAliasMetadata();
3470   return MemCheckBlock;
3471 }
3472 
3473 Value *InnerLoopVectorizer::emitTransformedIndex(
3474     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3475     const InductionDescriptor &ID) const {
3476 
3477   SCEVExpander Exp(*SE, DL, "induction");
3478   auto Step = ID.getStep();
3479   auto StartValue = ID.getStartValue();
3480   assert(Index->getType()->getScalarType() == Step->getType() &&
3481          "Index scalar type does not match StepValue type");
3482 
3483   // Note: the IR at this point is broken. We cannot use SE to create any new
3484   // SCEV and then expand it, hoping that SCEV's simplification will give us
3485   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3486   // lead to various SCEV crashes. So all we can do is to use builder and rely
3487   // on InstCombine for future simplifications. Here we handle some trivial
3488   // cases only.
3489   auto CreateAdd = [&B](Value *X, Value *Y) {
3490     assert(X->getType() == Y->getType() && "Types don't match!");
3491     if (auto *CX = dyn_cast<ConstantInt>(X))
3492       if (CX->isZero())
3493         return Y;
3494     if (auto *CY = dyn_cast<ConstantInt>(Y))
3495       if (CY->isZero())
3496         return X;
3497     return B.CreateAdd(X, Y);
3498   };
3499 
3500   // We allow X to be a vector type, in which case Y will potentially be
3501   // splatted into a vector with the same element count.
3502   auto CreateMul = [&B](Value *X, Value *Y) {
3503     assert(X->getType()->getScalarType() == Y->getType() &&
3504            "Types don't match!");
3505     if (auto *CX = dyn_cast<ConstantInt>(X))
3506       if (CX->isOne())
3507         return Y;
3508     if (auto *CY = dyn_cast<ConstantInt>(Y))
3509       if (CY->isOne())
3510         return X;
3511     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
3512     if (XVTy && !isa<VectorType>(Y->getType()))
3513       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
3514     return B.CreateMul(X, Y);
3515   };
3516 
3517   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3518   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3519   // the DomTree is not kept up-to-date for additional blocks generated in the
3520   // vector loop. By using the header as insertion point, we guarantee that the
3521   // expanded instructions dominate all their uses.
3522   auto GetInsertPoint = [this, &B]() {
3523     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3524     if (InsertBB != LoopVectorBody &&
3525         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3526       return LoopVectorBody->getTerminator();
3527     return &*B.GetInsertPoint();
3528   };
3529 
3530   switch (ID.getKind()) {
3531   case InductionDescriptor::IK_IntInduction: {
3532     assert(!isa<VectorType>(Index->getType()) &&
3533            "Vector indices not supported for integer inductions yet");
3534     assert(Index->getType() == StartValue->getType() &&
3535            "Index type does not match StartValue type");
3536     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3537       return B.CreateSub(StartValue, Index);
3538     auto *Offset = CreateMul(
3539         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3540     return CreateAdd(StartValue, Offset);
3541   }
3542   case InductionDescriptor::IK_PtrInduction: {
3543     assert(isa<SCEVConstant>(Step) &&
3544            "Expected constant step for pointer induction");
3545     return B.CreateGEP(
3546         ID.getElementType(), StartValue,
3547         CreateMul(Index,
3548                   Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
3549                                     GetInsertPoint())));
3550   }
3551   case InductionDescriptor::IK_FpInduction: {
3552     assert(!isa<VectorType>(Index->getType()) &&
3553            "Vector indices not supported for FP inductions yet");
3554     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3555     auto InductionBinOp = ID.getInductionBinOp();
3556     assert(InductionBinOp &&
3557            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3558             InductionBinOp->getOpcode() == Instruction::FSub) &&
3559            "Original bin op should be defined for FP induction");
3560 
3561     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3562     Value *MulExp = B.CreateFMul(StepValue, Index);
3563     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3564                          "induction");
3565   }
3566   case InductionDescriptor::IK_NoInduction:
3567     return nullptr;
3568   }
3569   llvm_unreachable("invalid enum");
3570 }
3571 
3572 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3573   LoopScalarBody = OrigLoop->getHeader();
3574   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3575   assert(LoopVectorPreHeader && "Invalid loop structure");
3576   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3577   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3578          "multiple exit loop without required epilogue?");
3579 
3580   LoopMiddleBlock =
3581       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3582                  LI, nullptr, Twine(Prefix) + "middle.block");
3583   LoopScalarPreHeader =
3584       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3585                  nullptr, Twine(Prefix) + "scalar.ph");
3586 
3587   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3588 
3589   // Set up the middle block terminator.  Two cases:
3590   // 1) If we know that we must execute the scalar epilogue, emit an
3591   //    unconditional branch.
3592   // 2) Otherwise, we must have a single unique exit block (due to how we
3593   //    implement the multiple exit case).  In this case, set up a conditonal
3594   //    branch from the middle block to the loop scalar preheader, and the
3595   //    exit block.  completeLoopSkeleton will update the condition to use an
3596   //    iteration check, if required to decide whether to execute the remainder.
3597   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3598     BranchInst::Create(LoopScalarPreHeader) :
3599     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3600                        Builder.getTrue());
3601   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3602   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3603 
3604   // We intentionally don't let SplitBlock to update LoopInfo since
3605   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3606   // LoopVectorBody is explicitly added to the correct place few lines later.
3607   LoopVectorBody =
3608       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3609                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3610 
3611   // Update dominator for loop exit.
3612   if (!Cost->requiresScalarEpilogue(VF))
3613     // If there is an epilogue which must run, there's no edge from the
3614     // middle block to exit blocks  and thus no need to update the immediate
3615     // dominator of the exit blocks.
3616     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3617 
3618   // Create and register the new vector loop.
3619   Loop *Lp = LI->AllocateLoop();
3620   Loop *ParentLoop = OrigLoop->getParentLoop();
3621 
3622   // Insert the new loop into the loop nest and register the new basic blocks
3623   // before calling any utilities such as SCEV that require valid LoopInfo.
3624   if (ParentLoop) {
3625     ParentLoop->addChildLoop(Lp);
3626   } else {
3627     LI->addTopLevelLoop(Lp);
3628   }
3629   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3630   return Lp;
3631 }
3632 
3633 void InnerLoopVectorizer::createInductionResumeValues(
3634     Loop *L, Value *VectorTripCount,
3635     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3636   assert(VectorTripCount && L && "Expected valid arguments");
3637   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3638           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3639          "Inconsistent information about additional bypass.");
3640   // We are going to resume the execution of the scalar loop.
3641   // Go over all of the induction variables that we found and fix the
3642   // PHIs that are left in the scalar version of the loop.
3643   // The starting values of PHI nodes depend on the counter of the last
3644   // iteration in the vectorized loop.
3645   // If we come from a bypass edge then we need to start from the original
3646   // start value.
3647   for (auto &InductionEntry : Legal->getInductionVars()) {
3648     PHINode *OrigPhi = InductionEntry.first;
3649     InductionDescriptor II = InductionEntry.second;
3650 
3651     // Create phi nodes to merge from the  backedge-taken check block.
3652     PHINode *BCResumeVal =
3653         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3654                         LoopScalarPreHeader->getTerminator());
3655     // Copy original phi DL over to the new one.
3656     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3657     Value *&EndValue = IVEndValues[OrigPhi];
3658     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3659     if (OrigPhi == OldInduction) {
3660       // We know what the end value is.
3661       EndValue = VectorTripCount;
3662     } else {
3663       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3664 
3665       // Fast-math-flags propagate from the original induction instruction.
3666       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3667         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3668 
3669       Type *StepType = II.getStep()->getType();
3670       Instruction::CastOps CastOp =
3671           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3672       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3673       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3674       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3675       EndValue->setName("ind.end");
3676 
3677       // Compute the end value for the additional bypass (if applicable).
3678       if (AdditionalBypass.first) {
3679         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3680         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3681                                          StepType, true);
3682         CRD =
3683             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3684         EndValueFromAdditionalBypass =
3685             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3686         EndValueFromAdditionalBypass->setName("ind.end");
3687       }
3688     }
3689     // The new PHI merges the original incoming value, in case of a bypass,
3690     // or the value at the end of the vectorized loop.
3691     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3692 
3693     // Fix the scalar body counter (PHI node).
3694     // The old induction's phi node in the scalar body needs the truncated
3695     // value.
3696     for (BasicBlock *BB : LoopBypassBlocks)
3697       BCResumeVal->addIncoming(II.getStartValue(), BB);
3698 
3699     if (AdditionalBypass.first)
3700       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3701                                             EndValueFromAdditionalBypass);
3702 
3703     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3704   }
3705 }
3706 
3707 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3708                                                       MDNode *OrigLoopID) {
3709   assert(L && "Expected valid loop.");
3710 
3711   // The trip counts should be cached by now.
3712   Value *Count = getOrCreateTripCount(L);
3713   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3714 
3715   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3716 
3717   // Add a check in the middle block to see if we have completed
3718   // all of the iterations in the first vector loop.  Three cases:
3719   // 1) If we require a scalar epilogue, there is no conditional branch as
3720   //    we unconditionally branch to the scalar preheader.  Do nothing.
3721   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3722   //    Thus if tail is to be folded, we know we don't need to run the
3723   //    remainder and we can use the previous value for the condition (true).
3724   // 3) Otherwise, construct a runtime check.
3725   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3726     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3727                                         Count, VectorTripCount, "cmp.n",
3728                                         LoopMiddleBlock->getTerminator());
3729 
3730     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3731     // of the corresponding compare because they may have ended up with
3732     // different line numbers and we want to avoid awkward line stepping while
3733     // debugging. Eg. if the compare has got a line number inside the loop.
3734     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3735     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3736   }
3737 
3738   // Get ready to start creating new instructions into the vectorized body.
3739   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3740          "Inconsistent vector loop preheader");
3741   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3742 
3743   Optional<MDNode *> VectorizedLoopID =
3744       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3745                                       LLVMLoopVectorizeFollowupVectorized});
3746   if (VectorizedLoopID.hasValue()) {
3747     L->setLoopID(VectorizedLoopID.getValue());
3748 
3749     // Do not setAlreadyVectorized if loop attributes have been defined
3750     // explicitly.
3751     return LoopVectorPreHeader;
3752   }
3753 
3754   // Keep all loop hints from the original loop on the vector loop (we'll
3755   // replace the vectorizer-specific hints below).
3756   if (MDNode *LID = OrigLoop->getLoopID())
3757     L->setLoopID(LID);
3758 
3759   LoopVectorizeHints Hints(L, true, *ORE);
3760   Hints.setAlreadyVectorized();
3761 
3762 #ifdef EXPENSIVE_CHECKS
3763   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3764   LI->verify(*DT);
3765 #endif
3766 
3767   return LoopVectorPreHeader;
3768 }
3769 
3770 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3771   /*
3772    In this function we generate a new loop. The new loop will contain
3773    the vectorized instructions while the old loop will continue to run the
3774    scalar remainder.
3775 
3776        [ ] <-- loop iteration number check.
3777     /   |
3778    /    v
3779   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3780   |  /  |
3781   | /   v
3782   ||   [ ]     <-- vector pre header.
3783   |/    |
3784   |     v
3785   |    [  ] \
3786   |    [  ]_|   <-- vector loop.
3787   |     |
3788   |     v
3789   \   -[ ]   <--- middle-block.
3790    \/   |
3791    /\   v
3792    | ->[ ]     <--- new preheader.
3793    |    |
3794  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3795    |   [ ] \
3796    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3797     \   |
3798      \  v
3799       >[ ]     <-- exit block(s).
3800    ...
3801    */
3802 
3803   // Get the metadata of the original loop before it gets modified.
3804   MDNode *OrigLoopID = OrigLoop->getLoopID();
3805 
3806   // Workaround!  Compute the trip count of the original loop and cache it
3807   // before we start modifying the CFG.  This code has a systemic problem
3808   // wherein it tries to run analysis over partially constructed IR; this is
3809   // wrong, and not simply for SCEV.  The trip count of the original loop
3810   // simply happens to be prone to hitting this in practice.  In theory, we
3811   // can hit the same issue for any SCEV, or ValueTracking query done during
3812   // mutation.  See PR49900.
3813   getOrCreateTripCount(OrigLoop);
3814 
3815   // Create an empty vector loop, and prepare basic blocks for the runtime
3816   // checks.
3817   Loop *Lp = createVectorLoopSkeleton("");
3818 
3819   // Now, compare the new count to zero. If it is zero skip the vector loop and
3820   // jump to the scalar loop. This check also covers the case where the
3821   // backedge-taken count is uint##_max: adding one to it will overflow leading
3822   // to an incorrect trip count of zero. In this (rare) case we will also jump
3823   // to the scalar loop.
3824   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3825 
3826   // Generate the code to check any assumptions that we've made for SCEV
3827   // expressions.
3828   emitSCEVChecks(Lp, LoopScalarPreHeader);
3829 
3830   // Generate the code that checks in runtime if arrays overlap. We put the
3831   // checks into a separate block to make the more common case of few elements
3832   // faster.
3833   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3834 
3835   // Some loops have a single integer induction variable, while other loops
3836   // don't. One example is c++ iterators that often have multiple pointer
3837   // induction variables. In the code below we also support a case where we
3838   // don't have a single induction variable.
3839   //
3840   // We try to obtain an induction variable from the original loop as hard
3841   // as possible. However if we don't find one that:
3842   //   - is an integer
3843   //   - counts from zero, stepping by one
3844   //   - is the size of the widest induction variable type
3845   // then we create a new one.
3846   OldInduction = Legal->getPrimaryInduction();
3847   Type *IdxTy = Legal->getWidestInductionType();
3848   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3849   // The loop step is equal to the vectorization factor (num of SIMD elements)
3850   // times the unroll factor (num of SIMD instructions).
3851   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3852   Value *Step = createStepForVF(Builder, IdxTy, VF, UF);
3853   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3854   Induction =
3855       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3856                               getDebugLocFromInstOrOperands(OldInduction));
3857 
3858   // Emit phis for the new starting index of the scalar loop.
3859   createInductionResumeValues(Lp, CountRoundDown);
3860 
3861   return completeLoopSkeleton(Lp, OrigLoopID);
3862 }
3863 
3864 // Fix up external users of the induction variable. At this point, we are
3865 // in LCSSA form, with all external PHIs that use the IV having one input value,
3866 // coming from the remainder loop. We need those PHIs to also have a correct
3867 // value for the IV when arriving directly from the middle block.
3868 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3869                                        const InductionDescriptor &II,
3870                                        Value *CountRoundDown, Value *EndValue,
3871                                        BasicBlock *MiddleBlock) {
3872   // There are two kinds of external IV usages - those that use the value
3873   // computed in the last iteration (the PHI) and those that use the penultimate
3874   // value (the value that feeds into the phi from the loop latch).
3875   // We allow both, but they, obviously, have different values.
3876 
3877   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3878 
3879   DenseMap<Value *, Value *> MissingVals;
3880 
3881   // An external user of the last iteration's value should see the value that
3882   // the remainder loop uses to initialize its own IV.
3883   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3884   for (User *U : PostInc->users()) {
3885     Instruction *UI = cast<Instruction>(U);
3886     if (!OrigLoop->contains(UI)) {
3887       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3888       MissingVals[UI] = EndValue;
3889     }
3890   }
3891 
3892   // An external user of the penultimate value need to see EndValue - Step.
3893   // The simplest way to get this is to recompute it from the constituent SCEVs,
3894   // that is Start + (Step * (CRD - 1)).
3895   for (User *U : OrigPhi->users()) {
3896     auto *UI = cast<Instruction>(U);
3897     if (!OrigLoop->contains(UI)) {
3898       const DataLayout &DL =
3899           OrigLoop->getHeader()->getModule()->getDataLayout();
3900       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3901 
3902       IRBuilder<> B(MiddleBlock->getTerminator());
3903 
3904       // Fast-math-flags propagate from the original induction instruction.
3905       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3906         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3907 
3908       Value *CountMinusOne = B.CreateSub(
3909           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3910       Value *CMO =
3911           !II.getStep()->getType()->isIntegerTy()
3912               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3913                              II.getStep()->getType())
3914               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3915       CMO->setName("cast.cmo");
3916       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3917       Escape->setName("ind.escape");
3918       MissingVals[UI] = Escape;
3919     }
3920   }
3921 
3922   for (auto &I : MissingVals) {
3923     PHINode *PHI = cast<PHINode>(I.first);
3924     // One corner case we have to handle is two IVs "chasing" each-other,
3925     // that is %IV2 = phi [...], [ %IV1, %latch ]
3926     // In this case, if IV1 has an external use, we need to avoid adding both
3927     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3928     // don't already have an incoming value for the middle block.
3929     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3930       PHI->addIncoming(I.second, MiddleBlock);
3931   }
3932 }
3933 
3934 namespace {
3935 
3936 struct CSEDenseMapInfo {
3937   static bool canHandle(const Instruction *I) {
3938     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3939            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3940   }
3941 
3942   static inline Instruction *getEmptyKey() {
3943     return DenseMapInfo<Instruction *>::getEmptyKey();
3944   }
3945 
3946   static inline Instruction *getTombstoneKey() {
3947     return DenseMapInfo<Instruction *>::getTombstoneKey();
3948   }
3949 
3950   static unsigned getHashValue(const Instruction *I) {
3951     assert(canHandle(I) && "Unknown instruction!");
3952     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3953                                                            I->value_op_end()));
3954   }
3955 
3956   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3957     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3958         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3959       return LHS == RHS;
3960     return LHS->isIdenticalTo(RHS);
3961   }
3962 };
3963 
3964 } // end anonymous namespace
3965 
3966 ///Perform cse of induction variable instructions.
3967 static void cse(BasicBlock *BB) {
3968   // Perform simple cse.
3969   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3970   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3971     if (!CSEDenseMapInfo::canHandle(&In))
3972       continue;
3973 
3974     // Check if we can replace this instruction with any of the
3975     // visited instructions.
3976     if (Instruction *V = CSEMap.lookup(&In)) {
3977       In.replaceAllUsesWith(V);
3978       In.eraseFromParent();
3979       continue;
3980     }
3981 
3982     CSEMap[&In] = &In;
3983   }
3984 }
3985 
3986 InstructionCost
3987 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3988                                               bool &NeedToScalarize) const {
3989   Function *F = CI->getCalledFunction();
3990   Type *ScalarRetTy = CI->getType();
3991   SmallVector<Type *, 4> Tys, ScalarTys;
3992   for (auto &ArgOp : CI->args())
3993     ScalarTys.push_back(ArgOp->getType());
3994 
3995   // Estimate cost of scalarized vector call. The source operands are assumed
3996   // to be vectors, so we need to extract individual elements from there,
3997   // execute VF scalar calls, and then gather the result into the vector return
3998   // value.
3999   InstructionCost ScalarCallCost =
4000       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
4001   if (VF.isScalar())
4002     return ScalarCallCost;
4003 
4004   // Compute corresponding vector type for return value and arguments.
4005   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
4006   for (Type *ScalarTy : ScalarTys)
4007     Tys.push_back(ToVectorTy(ScalarTy, VF));
4008 
4009   // Compute costs of unpacking argument values for the scalar calls and
4010   // packing the return values to a vector.
4011   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
4012 
4013   InstructionCost Cost =
4014       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
4015 
4016   // If we can't emit a vector call for this function, then the currently found
4017   // cost is the cost we need to return.
4018   NeedToScalarize = true;
4019   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4020   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4021 
4022   if (!TLI || CI->isNoBuiltin() || !VecFunc)
4023     return Cost;
4024 
4025   // If the corresponding vector cost is cheaper, return its cost.
4026   InstructionCost VectorCallCost =
4027       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
4028   if (VectorCallCost < Cost) {
4029     NeedToScalarize = false;
4030     Cost = VectorCallCost;
4031   }
4032   return Cost;
4033 }
4034 
4035 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
4036   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
4037     return Elt;
4038   return VectorType::get(Elt, VF);
4039 }
4040 
4041 InstructionCost
4042 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
4043                                                    ElementCount VF) const {
4044   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4045   assert(ID && "Expected intrinsic call!");
4046   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
4047   FastMathFlags FMF;
4048   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
4049     FMF = FPMO->getFastMathFlags();
4050 
4051   SmallVector<const Value *> Arguments(CI->args());
4052   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
4053   SmallVector<Type *> ParamTys;
4054   std::transform(FTy->param_begin(), FTy->param_end(),
4055                  std::back_inserter(ParamTys),
4056                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
4057 
4058   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
4059                                     dyn_cast<IntrinsicInst>(CI));
4060   return TTI.getIntrinsicInstrCost(CostAttrs,
4061                                    TargetTransformInfo::TCK_RecipThroughput);
4062 }
4063 
4064 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
4065   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
4066   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
4067   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
4068 }
4069 
4070 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
4071   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
4072   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
4073   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
4074 }
4075 
4076 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
4077   // For every instruction `I` in MinBWs, truncate the operands, create a
4078   // truncated version of `I` and reextend its result. InstCombine runs
4079   // later and will remove any ext/trunc pairs.
4080   SmallPtrSet<Value *, 4> Erased;
4081   for (const auto &KV : Cost->getMinimalBitwidths()) {
4082     // If the value wasn't vectorized, we must maintain the original scalar
4083     // type. The absence of the value from State indicates that it
4084     // wasn't vectorized.
4085     // FIXME: Should not rely on getVPValue at this point.
4086     VPValue *Def = State.Plan->getVPValue(KV.first, true);
4087     if (!State.hasAnyVectorValue(Def))
4088       continue;
4089     for (unsigned Part = 0; Part < UF; ++Part) {
4090       Value *I = State.get(Def, Part);
4091       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
4092         continue;
4093       Type *OriginalTy = I->getType();
4094       Type *ScalarTruncatedTy =
4095           IntegerType::get(OriginalTy->getContext(), KV.second);
4096       auto *TruncatedTy = VectorType::get(
4097           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
4098       if (TruncatedTy == OriginalTy)
4099         continue;
4100 
4101       IRBuilder<> B(cast<Instruction>(I));
4102       auto ShrinkOperand = [&](Value *V) -> Value * {
4103         if (auto *ZI = dyn_cast<ZExtInst>(V))
4104           if (ZI->getSrcTy() == TruncatedTy)
4105             return ZI->getOperand(0);
4106         return B.CreateZExtOrTrunc(V, TruncatedTy);
4107       };
4108 
4109       // The actual instruction modification depends on the instruction type,
4110       // unfortunately.
4111       Value *NewI = nullptr;
4112       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
4113         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
4114                              ShrinkOperand(BO->getOperand(1)));
4115 
4116         // Any wrapping introduced by shrinking this operation shouldn't be
4117         // considered undefined behavior. So, we can't unconditionally copy
4118         // arithmetic wrapping flags to NewI.
4119         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
4120       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
4121         NewI =
4122             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
4123                          ShrinkOperand(CI->getOperand(1)));
4124       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
4125         NewI = B.CreateSelect(SI->getCondition(),
4126                               ShrinkOperand(SI->getTrueValue()),
4127                               ShrinkOperand(SI->getFalseValue()));
4128       } else if (auto *CI = dyn_cast<CastInst>(I)) {
4129         switch (CI->getOpcode()) {
4130         default:
4131           llvm_unreachable("Unhandled cast!");
4132         case Instruction::Trunc:
4133           NewI = ShrinkOperand(CI->getOperand(0));
4134           break;
4135         case Instruction::SExt:
4136           NewI = B.CreateSExtOrTrunc(
4137               CI->getOperand(0),
4138               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4139           break;
4140         case Instruction::ZExt:
4141           NewI = B.CreateZExtOrTrunc(
4142               CI->getOperand(0),
4143               smallestIntegerVectorType(OriginalTy, TruncatedTy));
4144           break;
4145         }
4146       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
4147         auto Elements0 =
4148             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
4149         auto *O0 = B.CreateZExtOrTrunc(
4150             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
4151         auto Elements1 =
4152             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
4153         auto *O1 = B.CreateZExtOrTrunc(
4154             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
4155 
4156         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
4157       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
4158         // Don't do anything with the operands, just extend the result.
4159         continue;
4160       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
4161         auto Elements =
4162             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
4163         auto *O0 = B.CreateZExtOrTrunc(
4164             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
4165         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
4166         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
4167       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
4168         auto Elements =
4169             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
4170         auto *O0 = B.CreateZExtOrTrunc(
4171             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
4172         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
4173       } else {
4174         // If we don't know what to do, be conservative and don't do anything.
4175         continue;
4176       }
4177 
4178       // Lastly, extend the result.
4179       NewI->takeName(cast<Instruction>(I));
4180       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
4181       I->replaceAllUsesWith(Res);
4182       cast<Instruction>(I)->eraseFromParent();
4183       Erased.insert(I);
4184       State.reset(Def, Res, Part);
4185     }
4186   }
4187 
4188   // We'll have created a bunch of ZExts that are now parentless. Clean up.
4189   for (const auto &KV : Cost->getMinimalBitwidths()) {
4190     // If the value wasn't vectorized, we must maintain the original scalar
4191     // type. The absence of the value from State indicates that it
4192     // wasn't vectorized.
4193     // FIXME: Should not rely on getVPValue at this point.
4194     VPValue *Def = State.Plan->getVPValue(KV.first, true);
4195     if (!State.hasAnyVectorValue(Def))
4196       continue;
4197     for (unsigned Part = 0; Part < UF; ++Part) {
4198       Value *I = State.get(Def, Part);
4199       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
4200       if (Inst && Inst->use_empty()) {
4201         Value *NewI = Inst->getOperand(0);
4202         Inst->eraseFromParent();
4203         State.reset(Def, NewI, Part);
4204       }
4205     }
4206   }
4207 }
4208 
4209 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
4210   // Insert truncates and extends for any truncated instructions as hints to
4211   // InstCombine.
4212   if (VF.isVector())
4213     truncateToMinimalBitwidths(State);
4214 
4215   // Fix widened non-induction PHIs by setting up the PHI operands.
4216   if (OrigPHIsToFix.size()) {
4217     assert(EnableVPlanNativePath &&
4218            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4219     fixNonInductionPHIs(State);
4220   }
4221 
4222   // At this point every instruction in the original loop is widened to a
4223   // vector form. Now we need to fix the recurrences in the loop. These PHI
4224   // nodes are currently empty because we did not want to introduce cycles.
4225   // This is the second stage of vectorizing recurrences.
4226   fixCrossIterationPHIs(State);
4227 
4228   // Forget the original basic block.
4229   PSE.getSE()->forgetLoop(OrigLoop);
4230 
4231   // If we inserted an edge from the middle block to the unique exit block,
4232   // update uses outside the loop (phis) to account for the newly inserted
4233   // edge.
4234   if (!Cost->requiresScalarEpilogue(VF)) {
4235     // Fix-up external users of the induction variables.
4236     for (auto &Entry : Legal->getInductionVars())
4237       fixupIVUsers(Entry.first, Entry.second,
4238                    getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4239                    IVEndValues[Entry.first], LoopMiddleBlock);
4240 
4241     fixLCSSAPHIs(State);
4242   }
4243 
4244   for (Instruction *PI : PredicatedInstructions)
4245     sinkScalarOperands(&*PI);
4246 
4247   // Remove redundant induction instructions.
4248   cse(LoopVectorBody);
4249 
4250   // Set/update profile weights for the vector and remainder loops as original
4251   // loop iterations are now distributed among them. Note that original loop
4252   // represented by LoopScalarBody becomes remainder loop after vectorization.
4253   //
4254   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4255   // end up getting slightly roughened result but that should be OK since
4256   // profile is not inherently precise anyway. Note also possible bypass of
4257   // vector code caused by legality checks is ignored, assigning all the weight
4258   // to the vector loop, optimistically.
4259   //
4260   // For scalable vectorization we can't know at compile time how many iterations
4261   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4262   // vscale of '1'.
4263   setProfileInfoAfterUnrolling(
4264       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4265       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4266 }
4267 
4268 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4269   // In order to support recurrences we need to be able to vectorize Phi nodes.
4270   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4271   // stage #2: We now need to fix the recurrences by adding incoming edges to
4272   // the currently empty PHI nodes. At this point every instruction in the
4273   // original loop is widened to a vector form so we can use them to construct
4274   // the incoming edges.
4275   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4276   for (VPRecipeBase &R : Header->phis()) {
4277     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
4278       fixReduction(ReductionPhi, State);
4279     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
4280       fixFirstOrderRecurrence(FOR, State);
4281   }
4282 }
4283 
4284 void InnerLoopVectorizer::fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR,
4285                                                   VPTransformState &State) {
4286   // This is the second phase of vectorizing first-order recurrences. An
4287   // overview of the transformation is described below. Suppose we have the
4288   // following loop.
4289   //
4290   //   for (int i = 0; i < n; ++i)
4291   //     b[i] = a[i] - a[i - 1];
4292   //
4293   // There is a first-order recurrence on "a". For this loop, the shorthand
4294   // scalar IR looks like:
4295   //
4296   //   scalar.ph:
4297   //     s_init = a[-1]
4298   //     br scalar.body
4299   //
4300   //   scalar.body:
4301   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4302   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4303   //     s2 = a[i]
4304   //     b[i] = s2 - s1
4305   //     br cond, scalar.body, ...
4306   //
4307   // In this example, s1 is a recurrence because it's value depends on the
4308   // previous iteration. In the first phase of vectorization, we created a
4309   // vector phi v1 for s1. We now complete the vectorization and produce the
4310   // shorthand vector IR shown below (for VF = 4, UF = 1).
4311   //
4312   //   vector.ph:
4313   //     v_init = vector(..., ..., ..., a[-1])
4314   //     br vector.body
4315   //
4316   //   vector.body
4317   //     i = phi [0, vector.ph], [i+4, vector.body]
4318   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4319   //     v2 = a[i, i+1, i+2, i+3];
4320   //     v3 = vector(v1(3), v2(0, 1, 2))
4321   //     b[i, i+1, i+2, i+3] = v2 - v3
4322   //     br cond, vector.body, middle.block
4323   //
4324   //   middle.block:
4325   //     x = v2(3)
4326   //     br scalar.ph
4327   //
4328   //   scalar.ph:
4329   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4330   //     br scalar.body
4331   //
4332   // After execution completes the vector loop, we extract the next value of
4333   // the recurrence (x) to use as the initial value in the scalar loop.
4334 
4335   // Extract the last vector element in the middle block. This will be the
4336   // initial value for the recurrence when jumping to the scalar loop.
4337   VPValue *PreviousDef = PhiR->getBackedgeValue();
4338   Value *Incoming = State.get(PreviousDef, UF - 1);
4339   auto *ExtractForScalar = Incoming;
4340   auto *IdxTy = Builder.getInt32Ty();
4341   if (VF.isVector()) {
4342     auto *One = ConstantInt::get(IdxTy, 1);
4343     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4344     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4345     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4346     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
4347                                                     "vector.recur.extract");
4348   }
4349   // Extract the second last element in the middle block if the
4350   // Phi is used outside the loop. We need to extract the phi itself
4351   // and not the last element (the phi update in the current iteration). This
4352   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4353   // when the scalar loop is not run at all.
4354   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4355   if (VF.isVector()) {
4356     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4357     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
4358     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4359         Incoming, Idx, "vector.recur.extract.for.phi");
4360   } else if (UF > 1)
4361     // When loop is unrolled without vectorizing, initialize
4362     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
4363     // of `Incoming`. This is analogous to the vectorized case above: extracting
4364     // the second last element when VF > 1.
4365     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4366 
4367   // Fix the initial value of the original recurrence in the scalar loop.
4368   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4369   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
4370   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4371   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
4372   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4373     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4374     Start->addIncoming(Incoming, BB);
4375   }
4376 
4377   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4378   Phi->setName("scalar.recur");
4379 
4380   // Finally, fix users of the recurrence outside the loop. The users will need
4381   // either the last value of the scalar recurrence or the last value of the
4382   // vector recurrence we extracted in the middle block. Since the loop is in
4383   // LCSSA form, we just need to find all the phi nodes for the original scalar
4384   // recurrence in the exit block, and then add an edge for the middle block.
4385   // Note that LCSSA does not imply single entry when the original scalar loop
4386   // had multiple exiting edges (as we always run the last iteration in the
4387   // scalar epilogue); in that case, there is no edge from middle to exit and
4388   // and thus no phis which needed updated.
4389   if (!Cost->requiresScalarEpilogue(VF))
4390     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4391       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi))
4392         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4393 }
4394 
4395 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
4396                                        VPTransformState &State) {
4397   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4398   // Get it's reduction variable descriptor.
4399   assert(Legal->isReductionVariable(OrigPhi) &&
4400          "Unable to find the reduction variable");
4401   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4402 
4403   RecurKind RK = RdxDesc.getRecurrenceKind();
4404   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4405   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4406   setDebugLocFromInst(ReductionStartValue);
4407 
4408   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
4409   // This is the vector-clone of the value that leaves the loop.
4410   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4411 
4412   // Wrap flags are in general invalid after vectorization, clear them.
4413   clearReductionWrapFlags(RdxDesc, State);
4414 
4415   // Before each round, move the insertion point right between
4416   // the PHIs and the values we are going to write.
4417   // This allows us to write both PHINodes and the extractelement
4418   // instructions.
4419   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4420 
4421   setDebugLocFromInst(LoopExitInst);
4422 
4423   Type *PhiTy = OrigPhi->getType();
4424   // If tail is folded by masking, the vector value to leave the loop should be
4425   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4426   // instead of the former. For an inloop reduction the reduction will already
4427   // be predicated, and does not need to be handled here.
4428   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
4429     for (unsigned Part = 0; Part < UF; ++Part) {
4430       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4431       Value *Sel = nullptr;
4432       for (User *U : VecLoopExitInst->users()) {
4433         if (isa<SelectInst>(U)) {
4434           assert(!Sel && "Reduction exit feeding two selects");
4435           Sel = U;
4436         } else
4437           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4438       }
4439       assert(Sel && "Reduction exit feeds no select");
4440       State.reset(LoopExitInstDef, Sel, Part);
4441 
4442       // If the target can create a predicated operator for the reduction at no
4443       // extra cost in the loop (for example a predicated vadd), it can be
4444       // cheaper for the select to remain in the loop than be sunk out of it,
4445       // and so use the select value for the phi instead of the old
4446       // LoopExitValue.
4447       if (PreferPredicatedReductionSelect ||
4448           TTI->preferPredicatedReductionSelect(
4449               RdxDesc.getOpcode(), PhiTy,
4450               TargetTransformInfo::ReductionFlags())) {
4451         auto *VecRdxPhi =
4452             cast<PHINode>(State.get(PhiR, Part));
4453         VecRdxPhi->setIncomingValueForBlock(
4454             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4455       }
4456     }
4457   }
4458 
4459   // If the vector reduction can be performed in a smaller type, we truncate
4460   // then extend the loop exit value to enable InstCombine to evaluate the
4461   // entire expression in the smaller type.
4462   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4463     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
4464     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4465     Builder.SetInsertPoint(
4466         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4467     VectorParts RdxParts(UF);
4468     for (unsigned Part = 0; Part < UF; ++Part) {
4469       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4470       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4471       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4472                                         : Builder.CreateZExt(Trunc, VecTy);
4473       for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
4474         if (U != Trunc) {
4475           U->replaceUsesOfWith(RdxParts[Part], Extnd);
4476           RdxParts[Part] = Extnd;
4477         }
4478     }
4479     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4480     for (unsigned Part = 0; Part < UF; ++Part) {
4481       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4482       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4483     }
4484   }
4485 
4486   // Reduce all of the unrolled parts into a single vector.
4487   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4488   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4489 
4490   // The middle block terminator has already been assigned a DebugLoc here (the
4491   // OrigLoop's single latch terminator). We want the whole middle block to
4492   // appear to execute on this line because: (a) it is all compiler generated,
4493   // (b) these instructions are always executed after evaluating the latch
4494   // conditional branch, and (c) other passes may add new predecessors which
4495   // terminate on this line. This is the easiest way to ensure we don't
4496   // accidentally cause an extra step back into the loop while debugging.
4497   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
4498   if (PhiR->isOrdered())
4499     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4500   else {
4501     // Floating-point operations should have some FMF to enable the reduction.
4502     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4503     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4504     for (unsigned Part = 1; Part < UF; ++Part) {
4505       Value *RdxPart = State.get(LoopExitInstDef, Part);
4506       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4507         ReducedPartRdx = Builder.CreateBinOp(
4508             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4509       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
4510         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
4511                                            ReducedPartRdx, RdxPart);
4512       else
4513         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4514     }
4515   }
4516 
4517   // Create the reduction after the loop. Note that inloop reductions create the
4518   // target reduction in the loop using a Reduction recipe.
4519   if (VF.isVector() && !PhiR->isInLoop()) {
4520     ReducedPartRdx =
4521         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
4522     // If the reduction can be performed in a smaller type, we need to extend
4523     // the reduction to the wider type before we branch to the original loop.
4524     if (PhiTy != RdxDesc.getRecurrenceType())
4525       ReducedPartRdx = RdxDesc.isSigned()
4526                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4527                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4528   }
4529 
4530   // Create a phi node that merges control-flow from the backedge-taken check
4531   // block and the middle block.
4532   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4533                                         LoopScalarPreHeader->getTerminator());
4534   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4535     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4536   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4537 
4538   // Now, we need to fix the users of the reduction variable
4539   // inside and outside of the scalar remainder loop.
4540 
4541   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4542   // in the exit blocks.  See comment on analogous loop in
4543   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4544   if (!Cost->requiresScalarEpilogue(VF))
4545     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4546       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst))
4547         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4548 
4549   // Fix the scalar loop reduction variable with the incoming reduction sum
4550   // from the vector body and from the backedge value.
4551   int IncomingEdgeBlockIdx =
4552       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4553   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4554   // Pick the other block.
4555   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4556   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4557   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4558 }
4559 
4560 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4561                                                   VPTransformState &State) {
4562   RecurKind RK = RdxDesc.getRecurrenceKind();
4563   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4564     return;
4565 
4566   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4567   assert(LoopExitInstr && "null loop exit instruction");
4568   SmallVector<Instruction *, 8> Worklist;
4569   SmallPtrSet<Instruction *, 8> Visited;
4570   Worklist.push_back(LoopExitInstr);
4571   Visited.insert(LoopExitInstr);
4572 
4573   while (!Worklist.empty()) {
4574     Instruction *Cur = Worklist.pop_back_val();
4575     if (isa<OverflowingBinaryOperator>(Cur))
4576       for (unsigned Part = 0; Part < UF; ++Part) {
4577         // FIXME: Should not rely on getVPValue at this point.
4578         Value *V = State.get(State.Plan->getVPValue(Cur, true), Part);
4579         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4580       }
4581 
4582     for (User *U : Cur->users()) {
4583       Instruction *UI = cast<Instruction>(U);
4584       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4585           Visited.insert(UI).second)
4586         Worklist.push_back(UI);
4587     }
4588   }
4589 }
4590 
4591 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4592   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4593     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4594       // Some phis were already hand updated by the reduction and recurrence
4595       // code above, leave them alone.
4596       continue;
4597 
4598     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4599     // Non-instruction incoming values will have only one value.
4600 
4601     VPLane Lane = VPLane::getFirstLane();
4602     if (isa<Instruction>(IncomingValue) &&
4603         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4604                                            VF))
4605       Lane = VPLane::getLastLaneForVF(VF);
4606 
4607     // Can be a loop invariant incoming value or the last scalar value to be
4608     // extracted from the vectorized loop.
4609     // FIXME: Should not rely on getVPValue at this point.
4610     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4611     Value *lastIncomingValue =
4612         OrigLoop->isLoopInvariant(IncomingValue)
4613             ? IncomingValue
4614             : State.get(State.Plan->getVPValue(IncomingValue, true),
4615                         VPIteration(UF - 1, Lane));
4616     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4617   }
4618 }
4619 
4620 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4621   // The basic block and loop containing the predicated instruction.
4622   auto *PredBB = PredInst->getParent();
4623   auto *VectorLoop = LI->getLoopFor(PredBB);
4624 
4625   // Initialize a worklist with the operands of the predicated instruction.
4626   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4627 
4628   // Holds instructions that we need to analyze again. An instruction may be
4629   // reanalyzed if we don't yet know if we can sink it or not.
4630   SmallVector<Instruction *, 8> InstsToReanalyze;
4631 
4632   // Returns true if a given use occurs in the predicated block. Phi nodes use
4633   // their operands in their corresponding predecessor blocks.
4634   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4635     auto *I = cast<Instruction>(U.getUser());
4636     BasicBlock *BB = I->getParent();
4637     if (auto *Phi = dyn_cast<PHINode>(I))
4638       BB = Phi->getIncomingBlock(
4639           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4640     return BB == PredBB;
4641   };
4642 
4643   // Iteratively sink the scalarized operands of the predicated instruction
4644   // into the block we created for it. When an instruction is sunk, it's
4645   // operands are then added to the worklist. The algorithm ends after one pass
4646   // through the worklist doesn't sink a single instruction.
4647   bool Changed;
4648   do {
4649     // Add the instructions that need to be reanalyzed to the worklist, and
4650     // reset the changed indicator.
4651     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4652     InstsToReanalyze.clear();
4653     Changed = false;
4654 
4655     while (!Worklist.empty()) {
4656       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4657 
4658       // We can't sink an instruction if it is a phi node, is not in the loop,
4659       // or may have side effects.
4660       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4661           I->mayHaveSideEffects())
4662         continue;
4663 
4664       // If the instruction is already in PredBB, check if we can sink its
4665       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4666       // sinking the scalar instruction I, hence it appears in PredBB; but it
4667       // may have failed to sink I's operands (recursively), which we try
4668       // (again) here.
4669       if (I->getParent() == PredBB) {
4670         Worklist.insert(I->op_begin(), I->op_end());
4671         continue;
4672       }
4673 
4674       // It's legal to sink the instruction if all its uses occur in the
4675       // predicated block. Otherwise, there's nothing to do yet, and we may
4676       // need to reanalyze the instruction.
4677       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4678         InstsToReanalyze.push_back(I);
4679         continue;
4680       }
4681 
4682       // Move the instruction to the beginning of the predicated block, and add
4683       // it's operands to the worklist.
4684       I->moveBefore(&*PredBB->getFirstInsertionPt());
4685       Worklist.insert(I->op_begin(), I->op_end());
4686 
4687       // The sinking may have enabled other instructions to be sunk, so we will
4688       // need to iterate.
4689       Changed = true;
4690     }
4691   } while (Changed);
4692 }
4693 
4694 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4695   for (PHINode *OrigPhi : OrigPHIsToFix) {
4696     VPWidenPHIRecipe *VPPhi =
4697         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4698     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4699     // Make sure the builder has a valid insert point.
4700     Builder.SetInsertPoint(NewPhi);
4701     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4702       VPValue *Inc = VPPhi->getIncomingValue(i);
4703       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4704       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4705     }
4706   }
4707 }
4708 
4709 bool InnerLoopVectorizer::useOrderedReductions(RecurrenceDescriptor &RdxDesc) {
4710   return Cost->useOrderedReductions(RdxDesc);
4711 }
4712 
4713 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4714                                               VPWidenPHIRecipe *PhiR,
4715                                               VPTransformState &State) {
4716   PHINode *P = cast<PHINode>(PN);
4717   if (EnableVPlanNativePath) {
4718     // Currently we enter here in the VPlan-native path for non-induction
4719     // PHIs where all control flow is uniform. We simply widen these PHIs.
4720     // Create a vector phi with no operands - the vector phi operands will be
4721     // set at the end of vector code generation.
4722     Type *VecTy = (State.VF.isScalar())
4723                       ? PN->getType()
4724                       : VectorType::get(PN->getType(), State.VF);
4725     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4726     State.set(PhiR, VecPhi, 0);
4727     OrigPHIsToFix.push_back(P);
4728 
4729     return;
4730   }
4731 
4732   assert(PN->getParent() == OrigLoop->getHeader() &&
4733          "Non-header phis should have been handled elsewhere");
4734 
4735   // In order to support recurrences we need to be able to vectorize Phi nodes.
4736   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4737   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4738   // this value when we vectorize all of the instructions that use the PHI.
4739 
4740   assert(!Legal->isReductionVariable(P) &&
4741          "reductions should be handled elsewhere");
4742 
4743   setDebugLocFromInst(P);
4744 
4745   // This PHINode must be an induction variable.
4746   // Make sure that we know about it.
4747   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4748 
4749   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4750   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4751 
4752   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4753   // which can be found from the original scalar operations.
4754   switch (II.getKind()) {
4755   case InductionDescriptor::IK_NoInduction:
4756     llvm_unreachable("Unknown induction");
4757   case InductionDescriptor::IK_IntInduction:
4758   case InductionDescriptor::IK_FpInduction:
4759     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4760   case InductionDescriptor::IK_PtrInduction: {
4761     // Handle the pointer induction variable case.
4762     assert(P->getType()->isPointerTy() && "Unexpected type.");
4763 
4764     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4765       // This is the normalized GEP that starts counting at zero.
4766       Value *PtrInd =
4767           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4768       // Determine the number of scalars we need to generate for each unroll
4769       // iteration. If the instruction is uniform, we only need to generate the
4770       // first lane. Otherwise, we generate all VF values.
4771       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4772       assert((IsUniform || !State.VF.isScalable()) &&
4773              "Cannot scalarize a scalable VF");
4774       unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
4775 
4776       for (unsigned Part = 0; Part < UF; ++Part) {
4777         Value *PartStart =
4778             createStepForVF(Builder, PtrInd->getType(), VF, Part);
4779 
4780         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4781           Value *Idx = Builder.CreateAdd(
4782               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4783           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4784           Value *SclrGep =
4785               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4786           SclrGep->setName("next.gep");
4787           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4788         }
4789       }
4790       return;
4791     }
4792     assert(isa<SCEVConstant>(II.getStep()) &&
4793            "Induction step not a SCEV constant!");
4794     Type *PhiType = II.getStep()->getType();
4795 
4796     // Build a pointer phi
4797     Value *ScalarStartValue = II.getStartValue();
4798     Type *ScStValueType = ScalarStartValue->getType();
4799     PHINode *NewPointerPhi =
4800         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4801     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4802 
4803     // A pointer induction, performed by using a gep
4804     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4805     Instruction *InductionLoc = LoopLatch->getTerminator();
4806     const SCEV *ScalarStep = II.getStep();
4807     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4808     Value *ScalarStepValue =
4809         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4810     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4811     Value *NumUnrolledElems =
4812         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4813     Value *InductionGEP = GetElementPtrInst::Create(
4814         II.getElementType(), NewPointerPhi,
4815         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4816         InductionLoc);
4817     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4818 
4819     // Create UF many actual address geps that use the pointer
4820     // phi as base and a vectorized version of the step value
4821     // (<step*0, ..., step*N>) as offset.
4822     for (unsigned Part = 0; Part < State.UF; ++Part) {
4823       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4824       Value *StartOffsetScalar =
4825           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4826       Value *StartOffset =
4827           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4828       // Create a vector of consecutive numbers from zero to VF.
4829       StartOffset =
4830           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4831 
4832       Value *GEP = Builder.CreateGEP(
4833           II.getElementType(), NewPointerPhi,
4834           Builder.CreateMul(
4835               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4836               "vector.gep"));
4837       State.set(PhiR, GEP, Part);
4838     }
4839   }
4840   }
4841 }
4842 
4843 /// A helper function for checking whether an integer division-related
4844 /// instruction may divide by zero (in which case it must be predicated if
4845 /// executed conditionally in the scalar code).
4846 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4847 /// Non-zero divisors that are non compile-time constants will not be
4848 /// converted into multiplication, so we will still end up scalarizing
4849 /// the division, but can do so w/o predication.
4850 static bool mayDivideByZero(Instruction &I) {
4851   assert((I.getOpcode() == Instruction::UDiv ||
4852           I.getOpcode() == Instruction::SDiv ||
4853           I.getOpcode() == Instruction::URem ||
4854           I.getOpcode() == Instruction::SRem) &&
4855          "Unexpected instruction");
4856   Value *Divisor = I.getOperand(1);
4857   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4858   return !CInt || CInt->isZero();
4859 }
4860 
4861 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4862                                                VPUser &ArgOperands,
4863                                                VPTransformState &State) {
4864   assert(!isa<DbgInfoIntrinsic>(I) &&
4865          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4866   setDebugLocFromInst(&I);
4867 
4868   Module *M = I.getParent()->getParent()->getParent();
4869   auto *CI = cast<CallInst>(&I);
4870 
4871   SmallVector<Type *, 4> Tys;
4872   for (Value *ArgOperand : CI->args())
4873     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4874 
4875   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4876 
4877   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4878   // version of the instruction.
4879   // Is it beneficial to perform intrinsic call compared to lib call?
4880   bool NeedToScalarize = false;
4881   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4882   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4883   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4884   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4885          "Instruction should be scalarized elsewhere.");
4886   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4887          "Either the intrinsic cost or vector call cost must be valid");
4888 
4889   for (unsigned Part = 0; Part < UF; ++Part) {
4890     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
4891     SmallVector<Value *, 4> Args;
4892     for (auto &I : enumerate(ArgOperands.operands())) {
4893       // Some intrinsics have a scalar argument - don't replace it with a
4894       // vector.
4895       Value *Arg;
4896       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
4897         Arg = State.get(I.value(), Part);
4898       else {
4899         Arg = State.get(I.value(), VPIteration(0, 0));
4900         if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
4901           TysForDecl.push_back(Arg->getType());
4902       }
4903       Args.push_back(Arg);
4904     }
4905 
4906     Function *VectorF;
4907     if (UseVectorIntrinsic) {
4908       // Use vector version of the intrinsic.
4909       if (VF.isVector())
4910         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4911       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4912       assert(VectorF && "Can't retrieve vector intrinsic.");
4913     } else {
4914       // Use vector version of the function call.
4915       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4916 #ifndef NDEBUG
4917       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4918              "Can't create vector function.");
4919 #endif
4920         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4921     }
4922       SmallVector<OperandBundleDef, 1> OpBundles;
4923       CI->getOperandBundlesAsDefs(OpBundles);
4924       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4925 
4926       if (isa<FPMathOperator>(V))
4927         V->copyFastMathFlags(CI);
4928 
4929       State.set(Def, V, Part);
4930       addMetadata(V, &I);
4931   }
4932 }
4933 
4934 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4935   // We should not collect Scalars more than once per VF. Right now, this
4936   // function is called from collectUniformsAndScalars(), which already does
4937   // this check. Collecting Scalars for VF=1 does not make any sense.
4938   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4939          "This function should not be visited twice for the same VF");
4940 
4941   SmallSetVector<Instruction *, 8> Worklist;
4942 
4943   // These sets are used to seed the analysis with pointers used by memory
4944   // accesses that will remain scalar.
4945   SmallSetVector<Instruction *, 8> ScalarPtrs;
4946   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4947   auto *Latch = TheLoop->getLoopLatch();
4948 
4949   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4950   // The pointer operands of loads and stores will be scalar as long as the
4951   // memory access is not a gather or scatter operation. The value operand of a
4952   // store will remain scalar if the store is scalarized.
4953   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4954     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4955     assert(WideningDecision != CM_Unknown &&
4956            "Widening decision should be ready at this moment");
4957     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4958       if (Ptr == Store->getValueOperand())
4959         return WideningDecision == CM_Scalarize;
4960     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4961            "Ptr is neither a value or pointer operand");
4962     return WideningDecision != CM_GatherScatter;
4963   };
4964 
4965   // A helper that returns true if the given value is a bitcast or
4966   // getelementptr instruction contained in the loop.
4967   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4968     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4969             isa<GetElementPtrInst>(V)) &&
4970            !TheLoop->isLoopInvariant(V);
4971   };
4972 
4973   // A helper that evaluates a memory access's use of a pointer. If the use will
4974   // be a scalar use and the pointer is only used by memory accesses, we place
4975   // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4976   // PossibleNonScalarPtrs.
4977   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4978     // We only care about bitcast and getelementptr instructions contained in
4979     // the loop.
4980     if (!isLoopVaryingBitCastOrGEP(Ptr))
4981       return;
4982 
4983     // If the pointer has already been identified as scalar (e.g., if it was
4984     // also identified as uniform), there's nothing to do.
4985     auto *I = cast<Instruction>(Ptr);
4986     if (Worklist.count(I))
4987       return;
4988 
4989     // If the use of the pointer will be a scalar use, and all users of the
4990     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4991     // place the pointer in PossibleNonScalarPtrs.
4992     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4993           return isa<LoadInst>(U) || isa<StoreInst>(U);
4994         }))
4995       ScalarPtrs.insert(I);
4996     else
4997       PossibleNonScalarPtrs.insert(I);
4998   };
4999 
5000   // We seed the scalars analysis with three classes of instructions: (1)
5001   // instructions marked uniform-after-vectorization and (2) bitcast,
5002   // getelementptr and (pointer) phi instructions used by memory accesses
5003   // requiring a scalar use.
5004   //
5005   // (1) Add to the worklist all instructions that have been identified as
5006   // uniform-after-vectorization.
5007   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5008 
5009   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5010   // memory accesses requiring a scalar use. The pointer operands of loads and
5011   // stores will be scalar as long as the memory accesses is not a gather or
5012   // scatter operation. The value operand of a store will remain scalar if the
5013   // store is scalarized.
5014   for (auto *BB : TheLoop->blocks())
5015     for (auto &I : *BB) {
5016       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5017         evaluatePtrUse(Load, Load->getPointerOperand());
5018       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5019         evaluatePtrUse(Store, Store->getPointerOperand());
5020         evaluatePtrUse(Store, Store->getValueOperand());
5021       }
5022     }
5023   for (auto *I : ScalarPtrs)
5024     if (!PossibleNonScalarPtrs.count(I)) {
5025       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5026       Worklist.insert(I);
5027     }
5028 
5029   // Insert the forced scalars.
5030   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5031   // induction variable when the PHI user is scalarized.
5032   auto ForcedScalar = ForcedScalars.find(VF);
5033   if (ForcedScalar != ForcedScalars.end())
5034     for (auto *I : ForcedScalar->second)
5035       Worklist.insert(I);
5036 
5037   // Expand the worklist by looking through any bitcasts and getelementptr
5038   // instructions we've already identified as scalar. This is similar to the
5039   // expansion step in collectLoopUniforms(); however, here we're only
5040   // expanding to include additional bitcasts and getelementptr instructions.
5041   unsigned Idx = 0;
5042   while (Idx != Worklist.size()) {
5043     Instruction *Dst = Worklist[Idx++];
5044     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5045       continue;
5046     auto *Src = cast<Instruction>(Dst->getOperand(0));
5047     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5048           auto *J = cast<Instruction>(U);
5049           return !TheLoop->contains(J) || Worklist.count(J) ||
5050                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5051                   isScalarUse(J, Src));
5052         })) {
5053       Worklist.insert(Src);
5054       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5055     }
5056   }
5057 
5058   // An induction variable will remain scalar if all users of the induction
5059   // variable and induction variable update remain scalar.
5060   for (auto &Induction : Legal->getInductionVars()) {
5061     auto *Ind = Induction.first;
5062     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5063 
5064     // If tail-folding is applied, the primary induction variable will be used
5065     // to feed a vector compare.
5066     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
5067       continue;
5068 
5069     // Returns true if \p Indvar is a pointer induction that is used directly by
5070     // load/store instruction \p I.
5071     auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
5072                                               Instruction *I) {
5073       return Induction.second.getKind() ==
5074                  InductionDescriptor::IK_PtrInduction &&
5075              (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
5076              Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
5077     };
5078 
5079     // Determine if all users of the induction variable are scalar after
5080     // vectorization.
5081     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5082       auto *I = cast<Instruction>(U);
5083       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5084              IsDirectLoadStoreFromPtrIndvar(Ind, I);
5085     });
5086     if (!ScalarInd)
5087       continue;
5088 
5089     // Determine if all users of the induction variable update instruction are
5090     // scalar after vectorization.
5091     auto ScalarIndUpdate =
5092         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5093           auto *I = cast<Instruction>(U);
5094           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5095                  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
5096         });
5097     if (!ScalarIndUpdate)
5098       continue;
5099 
5100     // The induction variable and its update instruction will remain scalar.
5101     Worklist.insert(Ind);
5102     Worklist.insert(IndUpdate);
5103     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5104     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
5105                       << "\n");
5106   }
5107 
5108   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5109 }
5110 
5111 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) const {
5112   if (!blockNeedsPredicationForAnyReason(I->getParent()))
5113     return false;
5114   switch(I->getOpcode()) {
5115   default:
5116     break;
5117   case Instruction::Load:
5118   case Instruction::Store: {
5119     if (!Legal->isMaskRequired(I))
5120       return false;
5121     auto *Ptr = getLoadStorePointerOperand(I);
5122     auto *Ty = getLoadStoreType(I);
5123     const Align Alignment = getLoadStoreAlignment(I);
5124     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
5125                                 TTI.isLegalMaskedGather(Ty, Alignment))
5126                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
5127                                 TTI.isLegalMaskedScatter(Ty, Alignment));
5128   }
5129   case Instruction::UDiv:
5130   case Instruction::SDiv:
5131   case Instruction::SRem:
5132   case Instruction::URem:
5133     return mayDivideByZero(*I);
5134   }
5135   return false;
5136 }
5137 
5138 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5139     Instruction *I, ElementCount VF) {
5140   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5141   assert(getWideningDecision(I, VF) == CM_Unknown &&
5142          "Decision should not be set yet.");
5143   auto *Group = getInterleavedAccessGroup(I);
5144   assert(Group && "Must have a group.");
5145 
5146   // If the instruction's allocated size doesn't equal it's type size, it
5147   // requires padding and will be scalarized.
5148   auto &DL = I->getModule()->getDataLayout();
5149   auto *ScalarTy = getLoadStoreType(I);
5150   if (hasIrregularType(ScalarTy, DL))
5151     return false;
5152 
5153   // Check if masking is required.
5154   // A Group may need masking for one of two reasons: it resides in a block that
5155   // needs predication, or it was decided to use masking to deal with gaps
5156   // (either a gap at the end of a load-access that may result in a speculative
5157   // load, or any gaps in a store-access).
5158   bool PredicatedAccessRequiresMasking =
5159       blockNeedsPredicationForAnyReason(I->getParent()) &&
5160       Legal->isMaskRequired(I);
5161   bool LoadAccessWithGapsRequiresEpilogMasking =
5162       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
5163       !isScalarEpilogueAllowed();
5164   bool StoreAccessWithGapsRequiresMasking =
5165       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
5166   if (!PredicatedAccessRequiresMasking &&
5167       !LoadAccessWithGapsRequiresEpilogMasking &&
5168       !StoreAccessWithGapsRequiresMasking)
5169     return true;
5170 
5171   // If masked interleaving is required, we expect that the user/target had
5172   // enabled it, because otherwise it either wouldn't have been created or
5173   // it should have been invalidated by the CostModel.
5174   assert(useMaskedInterleavedAccesses(TTI) &&
5175          "Masked interleave-groups for predicated accesses are not enabled.");
5176 
5177   if (Group->isReverse())
5178     return false;
5179 
5180   auto *Ty = getLoadStoreType(I);
5181   const Align Alignment = getLoadStoreAlignment(I);
5182   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5183                           : TTI.isLegalMaskedStore(Ty, Alignment);
5184 }
5185 
5186 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5187     Instruction *I, ElementCount VF) {
5188   // Get and ensure we have a valid memory instruction.
5189   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
5190 
5191   auto *Ptr = getLoadStorePointerOperand(I);
5192   auto *ScalarTy = getLoadStoreType(I);
5193 
5194   // In order to be widened, the pointer should be consecutive, first of all.
5195   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
5196     return false;
5197 
5198   // If the instruction is a store located in a predicated block, it will be
5199   // scalarized.
5200   if (isScalarWithPredication(I))
5201     return false;
5202 
5203   // If the instruction's allocated size doesn't equal it's type size, it
5204   // requires padding and will be scalarized.
5205   auto &DL = I->getModule()->getDataLayout();
5206   if (hasIrregularType(ScalarTy, DL))
5207     return false;
5208 
5209   return true;
5210 }
5211 
5212 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5213   // We should not collect Uniforms more than once per VF. Right now,
5214   // this function is called from collectUniformsAndScalars(), which
5215   // already does this check. Collecting Uniforms for VF=1 does not make any
5216   // sense.
5217 
5218   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5219          "This function should not be visited twice for the same VF");
5220 
5221   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5222   // not analyze again.  Uniforms.count(VF) will return 1.
5223   Uniforms[VF].clear();
5224 
5225   // We now know that the loop is vectorizable!
5226   // Collect instructions inside the loop that will remain uniform after
5227   // vectorization.
5228 
5229   // Global values, params and instructions outside of current loop are out of
5230   // scope.
5231   auto isOutOfScope = [&](Value *V) -> bool {
5232     Instruction *I = dyn_cast<Instruction>(V);
5233     return (!I || !TheLoop->contains(I));
5234   };
5235 
5236   // Worklist containing uniform instructions demanding lane 0.
5237   SetVector<Instruction *> Worklist;
5238   BasicBlock *Latch = TheLoop->getLoopLatch();
5239 
5240   // Add uniform instructions demanding lane 0 to the worklist. Instructions
5241   // that are scalar with predication must not be considered uniform after
5242   // vectorization, because that would create an erroneous replicating region
5243   // where only a single instance out of VF should be formed.
5244   // TODO: optimize such seldom cases if found important, see PR40816.
5245   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5246     if (isOutOfScope(I)) {
5247       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5248                         << *I << "\n");
5249       return;
5250     }
5251     if (isScalarWithPredication(I)) {
5252       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5253                         << *I << "\n");
5254       return;
5255     }
5256     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5257     Worklist.insert(I);
5258   };
5259 
5260   // Start with the conditional branch. If the branch condition is an
5261   // instruction contained in the loop that is only used by the branch, it is
5262   // uniform.
5263   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5264   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5265     addToWorklistIfAllowed(Cmp);
5266 
5267   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5268     InstWidening WideningDecision = getWideningDecision(I, VF);
5269     assert(WideningDecision != CM_Unknown &&
5270            "Widening decision should be ready at this moment");
5271 
5272     // A uniform memory op is itself uniform.  We exclude uniform stores
5273     // here as they demand the last lane, not the first one.
5274     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5275       assert(WideningDecision == CM_Scalarize);
5276       return true;
5277     }
5278 
5279     return (WideningDecision == CM_Widen ||
5280             WideningDecision == CM_Widen_Reverse ||
5281             WideningDecision == CM_Interleave);
5282   };
5283 
5284 
5285   // Returns true if Ptr is the pointer operand of a memory access instruction
5286   // I, and I is known to not require scalarization.
5287   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5288     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5289   };
5290 
5291   // Holds a list of values which are known to have at least one uniform use.
5292   // Note that there may be other uses which aren't uniform.  A "uniform use"
5293   // here is something which only demands lane 0 of the unrolled iterations;
5294   // it does not imply that all lanes produce the same value (e.g. this is not
5295   // the usual meaning of uniform)
5296   SetVector<Value *> HasUniformUse;
5297 
5298   // Scan the loop for instructions which are either a) known to have only
5299   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5300   for (auto *BB : TheLoop->blocks())
5301     for (auto &I : *BB) {
5302       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
5303         switch (II->getIntrinsicID()) {
5304         case Intrinsic::sideeffect:
5305         case Intrinsic::experimental_noalias_scope_decl:
5306         case Intrinsic::assume:
5307         case Intrinsic::lifetime_start:
5308         case Intrinsic::lifetime_end:
5309           if (TheLoop->hasLoopInvariantOperands(&I))
5310             addToWorklistIfAllowed(&I);
5311           break;
5312         default:
5313           break;
5314         }
5315       }
5316 
5317       // ExtractValue instructions must be uniform, because the operands are
5318       // known to be loop-invariant.
5319       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
5320         assert(isOutOfScope(EVI->getAggregateOperand()) &&
5321                "Expected aggregate value to be loop invariant");
5322         addToWorklistIfAllowed(EVI);
5323         continue;
5324       }
5325 
5326       // If there's no pointer operand, there's nothing to do.
5327       auto *Ptr = getLoadStorePointerOperand(&I);
5328       if (!Ptr)
5329         continue;
5330 
5331       // A uniform memory op is itself uniform.  We exclude uniform stores
5332       // here as they demand the last lane, not the first one.
5333       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5334         addToWorklistIfAllowed(&I);
5335 
5336       if (isUniformDecision(&I, VF)) {
5337         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5338         HasUniformUse.insert(Ptr);
5339       }
5340     }
5341 
5342   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5343   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5344   // disallows uses outside the loop as well.
5345   for (auto *V : HasUniformUse) {
5346     if (isOutOfScope(V))
5347       continue;
5348     auto *I = cast<Instruction>(V);
5349     auto UsersAreMemAccesses =
5350       llvm::all_of(I->users(), [&](User *U) -> bool {
5351         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5352       });
5353     if (UsersAreMemAccesses)
5354       addToWorklistIfAllowed(I);
5355   }
5356 
5357   // Expand Worklist in topological order: whenever a new instruction
5358   // is added , its users should be already inside Worklist.  It ensures
5359   // a uniform instruction will only be used by uniform instructions.
5360   unsigned idx = 0;
5361   while (idx != Worklist.size()) {
5362     Instruction *I = Worklist[idx++];
5363 
5364     for (auto OV : I->operand_values()) {
5365       // isOutOfScope operands cannot be uniform instructions.
5366       if (isOutOfScope(OV))
5367         continue;
5368       // First order recurrence Phi's should typically be considered
5369       // non-uniform.
5370       auto *OP = dyn_cast<PHINode>(OV);
5371       if (OP && Legal->isFirstOrderRecurrence(OP))
5372         continue;
5373       // If all the users of the operand are uniform, then add the
5374       // operand into the uniform worklist.
5375       auto *OI = cast<Instruction>(OV);
5376       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5377             auto *J = cast<Instruction>(U);
5378             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5379           }))
5380         addToWorklistIfAllowed(OI);
5381     }
5382   }
5383 
5384   // For an instruction to be added into Worklist above, all its users inside
5385   // the loop should also be in Worklist. However, this condition cannot be
5386   // true for phi nodes that form a cyclic dependence. We must process phi
5387   // nodes separately. An induction variable will remain uniform if all users
5388   // of the induction variable and induction variable update remain uniform.
5389   // The code below handles both pointer and non-pointer induction variables.
5390   for (auto &Induction : Legal->getInductionVars()) {
5391     auto *Ind = Induction.first;
5392     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5393 
5394     // Determine if all users of the induction variable are uniform after
5395     // vectorization.
5396     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5397       auto *I = cast<Instruction>(U);
5398       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5399              isVectorizedMemAccessUse(I, Ind);
5400     });
5401     if (!UniformInd)
5402       continue;
5403 
5404     // Determine if all users of the induction variable update instruction are
5405     // uniform after vectorization.
5406     auto UniformIndUpdate =
5407         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5408           auto *I = cast<Instruction>(U);
5409           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5410                  isVectorizedMemAccessUse(I, IndUpdate);
5411         });
5412     if (!UniformIndUpdate)
5413       continue;
5414 
5415     // The induction variable and its update instruction will remain uniform.
5416     addToWorklistIfAllowed(Ind);
5417     addToWorklistIfAllowed(IndUpdate);
5418   }
5419 
5420   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5421 }
5422 
5423 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5424   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5425 
5426   if (Legal->getRuntimePointerChecking()->Need) {
5427     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5428         "runtime pointer checks needed. Enable vectorization of this "
5429         "loop with '#pragma clang loop vectorize(enable)' when "
5430         "compiling with -Os/-Oz",
5431         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5432     return true;
5433   }
5434 
5435   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5436     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5437         "runtime SCEV checks needed. Enable vectorization of this "
5438         "loop with '#pragma clang loop vectorize(enable)' when "
5439         "compiling with -Os/-Oz",
5440         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5441     return true;
5442   }
5443 
5444   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5445   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5446     reportVectorizationFailure("Runtime stride check for small trip count",
5447         "runtime stride == 1 checks needed. Enable vectorization of "
5448         "this loop without such check by compiling with -Os/-Oz",
5449         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5450     return true;
5451   }
5452 
5453   return false;
5454 }
5455 
5456 ElementCount
5457 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
5458   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
5459     return ElementCount::getScalable(0);
5460 
5461   if (Hints->isScalableVectorizationDisabled()) {
5462     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
5463                             "ScalableVectorizationDisabled", ORE, TheLoop);
5464     return ElementCount::getScalable(0);
5465   }
5466 
5467   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
5468 
5469   auto MaxScalableVF = ElementCount::getScalable(
5470       std::numeric_limits<ElementCount::ScalarTy>::max());
5471 
5472   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
5473   // FIXME: While for scalable vectors this is currently sufficient, this should
5474   // be replaced by a more detailed mechanism that filters out specific VFs,
5475   // instead of invalidating vectorization for a whole set of VFs based on the
5476   // MaxVF.
5477 
5478   // Disable scalable vectorization if the loop contains unsupported reductions.
5479   if (!canVectorizeReductions(MaxScalableVF)) {
5480     reportVectorizationInfo(
5481         "Scalable vectorization not supported for the reduction "
5482         "operations found in this loop.",
5483         "ScalableVFUnfeasible", ORE, TheLoop);
5484     return ElementCount::getScalable(0);
5485   }
5486 
5487   // Disable scalable vectorization if the loop contains any instructions
5488   // with element types not supported for scalable vectors.
5489   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
5490         return !Ty->isVoidTy() &&
5491                !this->TTI.isElementTypeLegalForScalableVector(Ty);
5492       })) {
5493     reportVectorizationInfo("Scalable vectorization is not supported "
5494                             "for all element types found in this loop.",
5495                             "ScalableVFUnfeasible", ORE, TheLoop);
5496     return ElementCount::getScalable(0);
5497   }
5498 
5499   if (Legal->isSafeForAnyVectorWidth())
5500     return MaxScalableVF;
5501 
5502   // Limit MaxScalableVF by the maximum safe dependence distance.
5503   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5504   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
5505     unsigned VScaleMax = TheFunction->getFnAttribute(Attribute::VScaleRange)
5506                              .getVScaleRangeArgs()
5507                              .second;
5508     if (VScaleMax > 0)
5509       MaxVScale = VScaleMax;
5510   }
5511   MaxScalableVF = ElementCount::getScalable(
5512       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5513   if (!MaxScalableVF)
5514     reportVectorizationInfo(
5515         "Max legal vector width too small, scalable vectorization "
5516         "unfeasible.",
5517         "ScalableVFUnfeasible", ORE, TheLoop);
5518 
5519   return MaxScalableVF;
5520 }
5521 
5522 FixedScalableVFPair
5523 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5524                                                  ElementCount UserVF) {
5525   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5526   unsigned SmallestType, WidestType;
5527   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5528 
5529   // Get the maximum safe dependence distance in bits computed by LAA.
5530   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5531   // the memory accesses that is most restrictive (involved in the smallest
5532   // dependence distance).
5533   unsigned MaxSafeElements =
5534       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
5535 
5536   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
5537   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
5538 
5539   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
5540                     << ".\n");
5541   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
5542                     << ".\n");
5543 
5544   // First analyze the UserVF, fall back if the UserVF should be ignored.
5545   if (UserVF) {
5546     auto MaxSafeUserVF =
5547         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
5548 
5549     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
5550       // If `VF=vscale x N` is safe, then so is `VF=N`
5551       if (UserVF.isScalable())
5552         return FixedScalableVFPair(
5553             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
5554       else
5555         return UserVF;
5556     }
5557 
5558     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
5559 
5560     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
5561     // is better to ignore the hint and let the compiler choose a suitable VF.
5562     if (!UserVF.isScalable()) {
5563       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5564                         << " is unsafe, clamping to max safe VF="
5565                         << MaxSafeFixedVF << ".\n");
5566       ORE->emit([&]() {
5567         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5568                                           TheLoop->getStartLoc(),
5569                                           TheLoop->getHeader())
5570                << "User-specified vectorization factor "
5571                << ore::NV("UserVectorizationFactor", UserVF)
5572                << " is unsafe, clamping to maximum safe vectorization factor "
5573                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
5574       });
5575       return MaxSafeFixedVF;
5576     }
5577 
5578     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
5579       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5580                         << " is ignored because scalable vectors are not "
5581                            "available.\n");
5582       ORE->emit([&]() {
5583         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5584                                           TheLoop->getStartLoc(),
5585                                           TheLoop->getHeader())
5586                << "User-specified vectorization factor "
5587                << ore::NV("UserVectorizationFactor", UserVF)
5588                << " is ignored because the target does not support scalable "
5589                   "vectors. The compiler will pick a more suitable value.";
5590       });
5591     } else {
5592       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5593                         << " is unsafe. Ignoring scalable UserVF.\n");
5594       ORE->emit([&]() {
5595         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5596                                           TheLoop->getStartLoc(),
5597                                           TheLoop->getHeader())
5598                << "User-specified vectorization factor "
5599                << ore::NV("UserVectorizationFactor", UserVF)
5600                << " is unsafe. Ignoring the hint to let the compiler pick a "
5601                   "more suitable value.";
5602       });
5603     }
5604   }
5605 
5606   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5607                     << " / " << WidestType << " bits.\n");
5608 
5609   FixedScalableVFPair Result(ElementCount::getFixed(1),
5610                              ElementCount::getScalable(0));
5611   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5612                                            WidestType, MaxSafeFixedVF))
5613     Result.FixedVF = MaxVF;
5614 
5615   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5616                                            WidestType, MaxSafeScalableVF))
5617     if (MaxVF.isScalable()) {
5618       Result.ScalableVF = MaxVF;
5619       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5620                         << "\n");
5621     }
5622 
5623   return Result;
5624 }
5625 
5626 FixedScalableVFPair
5627 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5628   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5629     // TODO: It may by useful to do since it's still likely to be dynamically
5630     // uniform if the target can skip.
5631     reportVectorizationFailure(
5632         "Not inserting runtime ptr check for divergent target",
5633         "runtime pointer checks needed. Not enabled for divergent target",
5634         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5635     return FixedScalableVFPair::getNone();
5636   }
5637 
5638   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5639   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5640   if (TC == 1) {
5641     reportVectorizationFailure("Single iteration (non) loop",
5642         "loop trip count is one, irrelevant for vectorization",
5643         "SingleIterationLoop", ORE, TheLoop);
5644     return FixedScalableVFPair::getNone();
5645   }
5646 
5647   switch (ScalarEpilogueStatus) {
5648   case CM_ScalarEpilogueAllowed:
5649     return computeFeasibleMaxVF(TC, UserVF);
5650   case CM_ScalarEpilogueNotAllowedUsePredicate:
5651     LLVM_FALLTHROUGH;
5652   case CM_ScalarEpilogueNotNeededUsePredicate:
5653     LLVM_DEBUG(
5654         dbgs() << "LV: vector predicate hint/switch found.\n"
5655                << "LV: Not allowing scalar epilogue, creating predicated "
5656                << "vector loop.\n");
5657     break;
5658   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5659     // fallthrough as a special case of OptForSize
5660   case CM_ScalarEpilogueNotAllowedOptSize:
5661     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5662       LLVM_DEBUG(
5663           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5664     else
5665       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5666                         << "count.\n");
5667 
5668     // Bail if runtime checks are required, which are not good when optimising
5669     // for size.
5670     if (runtimeChecksRequired())
5671       return FixedScalableVFPair::getNone();
5672 
5673     break;
5674   }
5675 
5676   // The only loops we can vectorize without a scalar epilogue, are loops with
5677   // a bottom-test and a single exiting block. We'd have to handle the fact
5678   // that not every instruction executes on the last iteration.  This will
5679   // require a lane mask which varies through the vector loop body.  (TODO)
5680   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5681     // If there was a tail-folding hint/switch, but we can't fold the tail by
5682     // masking, fallback to a vectorization with a scalar epilogue.
5683     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5684       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5685                            "scalar epilogue instead.\n");
5686       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5687       return computeFeasibleMaxVF(TC, UserVF);
5688     }
5689     return FixedScalableVFPair::getNone();
5690   }
5691 
5692   // Now try the tail folding
5693 
5694   // Invalidate interleave groups that require an epilogue if we can't mask
5695   // the interleave-group.
5696   if (!useMaskedInterleavedAccesses(TTI)) {
5697     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5698            "No decisions should have been taken at this point");
5699     // Note: There is no need to invalidate any cost modeling decisions here, as
5700     // non where taken so far.
5701     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5702   }
5703 
5704   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF);
5705   // Avoid tail folding if the trip count is known to be a multiple of any VF
5706   // we chose.
5707   // FIXME: The condition below pessimises the case for fixed-width vectors,
5708   // when scalable VFs are also candidates for vectorization.
5709   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5710     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5711     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5712            "MaxFixedVF must be a power of 2");
5713     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5714                                    : MaxFixedVF.getFixedValue();
5715     ScalarEvolution *SE = PSE.getSE();
5716     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5717     const SCEV *ExitCount = SE->getAddExpr(
5718         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5719     const SCEV *Rem = SE->getURemExpr(
5720         SE->applyLoopGuards(ExitCount, TheLoop),
5721         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5722     if (Rem->isZero()) {
5723       // Accept MaxFixedVF if we do not have a tail.
5724       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5725       return MaxFactors;
5726     }
5727   }
5728 
5729   // For scalable vectors, don't use tail folding as this is currently not yet
5730   // supported. The code is likely to have ended up here if the tripcount is
5731   // low, in which case it makes sense not to use scalable vectors.
5732   if (MaxFactors.ScalableVF.isVector())
5733     MaxFactors.ScalableVF = ElementCount::getScalable(0);
5734 
5735   // If we don't know the precise trip count, or if the trip count that we
5736   // found modulo the vectorization factor is not zero, try to fold the tail
5737   // by masking.
5738   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5739   if (Legal->prepareToFoldTailByMasking()) {
5740     FoldTailByMasking = true;
5741     return MaxFactors;
5742   }
5743 
5744   // If there was a tail-folding hint/switch, but we can't fold the tail by
5745   // masking, fallback to a vectorization with a scalar epilogue.
5746   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5747     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5748                          "scalar epilogue instead.\n");
5749     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5750     return MaxFactors;
5751   }
5752 
5753   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5754     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5755     return FixedScalableVFPair::getNone();
5756   }
5757 
5758   if (TC == 0) {
5759     reportVectorizationFailure(
5760         "Unable to calculate the loop count due to complex control flow",
5761         "unable to calculate the loop count due to complex control flow",
5762         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5763     return FixedScalableVFPair::getNone();
5764   }
5765 
5766   reportVectorizationFailure(
5767       "Cannot optimize for size and vectorize at the same time.",
5768       "cannot optimize for size and vectorize at the same time. "
5769       "Enable vectorization of this loop with '#pragma clang loop "
5770       "vectorize(enable)' when compiling with -Os/-Oz",
5771       "NoTailLoopWithOptForSize", ORE, TheLoop);
5772   return FixedScalableVFPair::getNone();
5773 }
5774 
5775 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5776     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5777     const ElementCount &MaxSafeVF) {
5778   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5779   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5780       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5781                            : TargetTransformInfo::RGK_FixedWidthVector);
5782 
5783   // Convenience function to return the minimum of two ElementCounts.
5784   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5785     assert((LHS.isScalable() == RHS.isScalable()) &&
5786            "Scalable flags must match");
5787     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5788   };
5789 
5790   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5791   // Note that both WidestRegister and WidestType may not be a powers of 2.
5792   auto MaxVectorElementCount = ElementCount::get(
5793       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5794       ComputeScalableMaxVF);
5795   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5796   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5797                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5798 
5799   if (!MaxVectorElementCount) {
5800     LLVM_DEBUG(dbgs() << "LV: The target has no "
5801                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5802                       << " vector registers.\n");
5803     return ElementCount::getFixed(1);
5804   }
5805 
5806   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5807   if (ConstTripCount &&
5808       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5809       isPowerOf2_32(ConstTripCount)) {
5810     // We need to clamp the VF to be the ConstTripCount. There is no point in
5811     // choosing a higher viable VF as done in the loop below. If
5812     // MaxVectorElementCount is scalable, we only fall back on a fixed VF when
5813     // the TC is less than or equal to the known number of lanes.
5814     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5815                       << ConstTripCount << "\n");
5816     return TripCountEC;
5817   }
5818 
5819   ElementCount MaxVF = MaxVectorElementCount;
5820   if (TTI.shouldMaximizeVectorBandwidth() ||
5821       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5822     auto MaxVectorElementCountMaxBW = ElementCount::get(
5823         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5824         ComputeScalableMaxVF);
5825     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5826 
5827     // Collect all viable vectorization factors larger than the default MaxVF
5828     // (i.e. MaxVectorElementCount).
5829     SmallVector<ElementCount, 8> VFs;
5830     for (ElementCount VS = MaxVectorElementCount * 2;
5831          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5832       VFs.push_back(VS);
5833 
5834     // For each VF calculate its register usage.
5835     auto RUs = calculateRegisterUsage(VFs);
5836 
5837     // Select the largest VF which doesn't require more registers than existing
5838     // ones.
5839     for (int i = RUs.size() - 1; i >= 0; --i) {
5840       bool Selected = true;
5841       for (auto &pair : RUs[i].MaxLocalUsers) {
5842         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5843         if (pair.second > TargetNumRegisters)
5844           Selected = false;
5845       }
5846       if (Selected) {
5847         MaxVF = VFs[i];
5848         break;
5849       }
5850     }
5851     if (ElementCount MinVF =
5852             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5853       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5854         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5855                           << ") with target's minimum: " << MinVF << '\n');
5856         MaxVF = MinVF;
5857       }
5858     }
5859   }
5860   return MaxVF;
5861 }
5862 
5863 bool LoopVectorizationCostModel::isMoreProfitable(
5864     const VectorizationFactor &A, const VectorizationFactor &B) const {
5865   InstructionCost CostA = A.Cost;
5866   InstructionCost CostB = B.Cost;
5867 
5868   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
5869 
5870   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
5871       MaxTripCount) {
5872     // If we are folding the tail and the trip count is a known (possibly small)
5873     // constant, the trip count will be rounded up to an integer number of
5874     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
5875     // which we compare directly. When not folding the tail, the total cost will
5876     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
5877     // approximated with the per-lane cost below instead of using the tripcount
5878     // as here.
5879     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
5880     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
5881     return RTCostA < RTCostB;
5882   }
5883 
5884   // Improve estimate for the vector width if it is scalable.
5885   unsigned EstimatedWidthA = A.Width.getKnownMinValue();
5886   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
5887   if (Optional<unsigned> VScale = TTI.getVScaleForTuning()) {
5888     if (A.Width.isScalable())
5889       EstimatedWidthA *= VScale.getValue();
5890     if (B.Width.isScalable())
5891       EstimatedWidthB *= VScale.getValue();
5892   }
5893 
5894   // When set to preferred, for now assume vscale may be larger than 1 (or the
5895   // one being tuned for), so that scalable vectorization is slightly favorable
5896   // over fixed-width vectorization.
5897   if (Hints->isScalableVectorizationPreferred())
5898     if (A.Width.isScalable() && !B.Width.isScalable())
5899       return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
5900 
5901   // To avoid the need for FP division:
5902   //      (CostA / A.Width) < (CostB / B.Width)
5903   // <=>  (CostA * B.Width) < (CostB * A.Width)
5904   return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
5905 }
5906 
5907 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
5908     const ElementCountSet &VFCandidates) {
5909   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5910   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5911   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5912   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
5913          "Expected Scalar VF to be a candidate");
5914 
5915   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
5916   VectorizationFactor ChosenFactor = ScalarCost;
5917 
5918   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5919   if (ForceVectorization && VFCandidates.size() > 1) {
5920     // Ignore scalar width, because the user explicitly wants vectorization.
5921     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5922     // evaluation.
5923     ChosenFactor.Cost = InstructionCost::getMax();
5924   }
5925 
5926   SmallVector<InstructionVFPair> InvalidCosts;
5927   for (const auto &i : VFCandidates) {
5928     // The cost for scalar VF=1 is already calculated, so ignore it.
5929     if (i.isScalar())
5930       continue;
5931 
5932     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
5933     VectorizationFactor Candidate(i, C.first);
5934 
5935 #ifndef NDEBUG
5936     unsigned AssumedMinimumVscale = 1;
5937     if (Optional<unsigned> VScale = TTI.getVScaleForTuning())
5938       AssumedMinimumVscale = VScale.getValue();
5939     unsigned Width =
5940         Candidate.Width.isScalable()
5941             ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
5942             : Candidate.Width.getFixedValue();
5943     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5944                       << " costs: " << (Candidate.Cost / Width));
5945     if (i.isScalable())
5946       LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
5947                         << AssumedMinimumVscale << ")");
5948     LLVM_DEBUG(dbgs() << ".\n");
5949 #endif
5950 
5951     if (!C.second && !ForceVectorization) {
5952       LLVM_DEBUG(
5953           dbgs() << "LV: Not considering vector loop of width " << i
5954                  << " because it will not generate any vector instructions.\n");
5955       continue;
5956     }
5957 
5958     // If profitable add it to ProfitableVF list.
5959     if (isMoreProfitable(Candidate, ScalarCost))
5960       ProfitableVFs.push_back(Candidate);
5961 
5962     if (isMoreProfitable(Candidate, ChosenFactor))
5963       ChosenFactor = Candidate;
5964   }
5965 
5966   // Emit a report of VFs with invalid costs in the loop.
5967   if (!InvalidCosts.empty()) {
5968     // Group the remarks per instruction, keeping the instruction order from
5969     // InvalidCosts.
5970     std::map<Instruction *, unsigned> Numbering;
5971     unsigned I = 0;
5972     for (auto &Pair : InvalidCosts)
5973       if (!Numbering.count(Pair.first))
5974         Numbering[Pair.first] = I++;
5975 
5976     // Sort the list, first on instruction(number) then on VF.
5977     llvm::sort(InvalidCosts,
5978                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
5979                  if (Numbering[A.first] != Numbering[B.first])
5980                    return Numbering[A.first] < Numbering[B.first];
5981                  ElementCountComparator ECC;
5982                  return ECC(A.second, B.second);
5983                });
5984 
5985     // For a list of ordered instruction-vf pairs:
5986     //   [(load, vf1), (load, vf2), (store, vf1)]
5987     // Group the instructions together to emit separate remarks for:
5988     //   load  (vf1, vf2)
5989     //   store (vf1)
5990     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
5991     auto Subset = ArrayRef<InstructionVFPair>();
5992     do {
5993       if (Subset.empty())
5994         Subset = Tail.take_front(1);
5995 
5996       Instruction *I = Subset.front().first;
5997 
5998       // If the next instruction is different, or if there are no other pairs,
5999       // emit a remark for the collated subset. e.g.
6000       //   [(load, vf1), (load, vf2))]
6001       // to emit:
6002       //  remark: invalid costs for 'load' at VF=(vf, vf2)
6003       if (Subset == Tail || Tail[Subset.size()].first != I) {
6004         std::string OutString;
6005         raw_string_ostream OS(OutString);
6006         assert(!Subset.empty() && "Unexpected empty range");
6007         OS << "Instruction with invalid costs prevented vectorization at VF=(";
6008         for (auto &Pair : Subset)
6009           OS << (Pair.second == Subset.front().second ? "" : ", ")
6010              << Pair.second;
6011         OS << "):";
6012         if (auto *CI = dyn_cast<CallInst>(I))
6013           OS << " call to " << CI->getCalledFunction()->getName();
6014         else
6015           OS << " " << I->getOpcodeName();
6016         OS.flush();
6017         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
6018         Tail = Tail.drop_front(Subset.size());
6019         Subset = {};
6020       } else
6021         // Grow the subset by one element
6022         Subset = Tail.take_front(Subset.size() + 1);
6023     } while (!Tail.empty());
6024   }
6025 
6026   if (!EnableCondStoresVectorization && NumPredStores) {
6027     reportVectorizationFailure("There are conditional stores.",
6028         "store that is conditionally executed prevents vectorization",
6029         "ConditionalStore", ORE, TheLoop);
6030     ChosenFactor = ScalarCost;
6031   }
6032 
6033   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
6034                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
6035              << "LV: Vectorization seems to be not beneficial, "
6036              << "but was forced by a user.\n");
6037   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
6038   return ChosenFactor;
6039 }
6040 
6041 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
6042     const Loop &L, ElementCount VF) const {
6043   // Cross iteration phis such as reductions need special handling and are
6044   // currently unsupported.
6045   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
6046         return Legal->isFirstOrderRecurrence(&Phi) ||
6047                Legal->isReductionVariable(&Phi);
6048       }))
6049     return false;
6050 
6051   // Phis with uses outside of the loop require special handling and are
6052   // currently unsupported.
6053   for (auto &Entry : Legal->getInductionVars()) {
6054     // Look for uses of the value of the induction at the last iteration.
6055     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
6056     for (User *U : PostInc->users())
6057       if (!L.contains(cast<Instruction>(U)))
6058         return false;
6059     // Look for uses of penultimate value of the induction.
6060     for (User *U : Entry.first->users())
6061       if (!L.contains(cast<Instruction>(U)))
6062         return false;
6063   }
6064 
6065   // Induction variables that are widened require special handling that is
6066   // currently not supported.
6067   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
6068         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
6069                  this->isProfitableToScalarize(Entry.first, VF));
6070       }))
6071     return false;
6072 
6073   // Epilogue vectorization code has not been auditted to ensure it handles
6074   // non-latch exits properly.  It may be fine, but it needs auditted and
6075   // tested.
6076   if (L.getExitingBlock() != L.getLoopLatch())
6077     return false;
6078 
6079   return true;
6080 }
6081 
6082 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
6083     const ElementCount VF) const {
6084   // FIXME: We need a much better cost-model to take different parameters such
6085   // as register pressure, code size increase and cost of extra branches into
6086   // account. For now we apply a very crude heuristic and only consider loops
6087   // with vectorization factors larger than a certain value.
6088   // We also consider epilogue vectorization unprofitable for targets that don't
6089   // consider interleaving beneficial (eg. MVE).
6090   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
6091     return false;
6092   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
6093     return true;
6094   return false;
6095 }
6096 
6097 VectorizationFactor
6098 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
6099     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
6100   VectorizationFactor Result = VectorizationFactor::Disabled();
6101   if (!EnableEpilogueVectorization) {
6102     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
6103     return Result;
6104   }
6105 
6106   if (!isScalarEpilogueAllowed()) {
6107     LLVM_DEBUG(
6108         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
6109                   "allowed.\n";);
6110     return Result;
6111   }
6112 
6113   // Not really a cost consideration, but check for unsupported cases here to
6114   // simplify the logic.
6115   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
6116     LLVM_DEBUG(
6117         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
6118                   "not a supported candidate.\n";);
6119     return Result;
6120   }
6121 
6122   if (EpilogueVectorizationForceVF > 1) {
6123     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
6124     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
6125     if (LVP.hasPlanWithVF(ForcedEC))
6126       return {ForcedEC, 0};
6127     else {
6128       LLVM_DEBUG(
6129           dbgs()
6130               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
6131       return Result;
6132     }
6133   }
6134 
6135   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
6136       TheLoop->getHeader()->getParent()->hasMinSize()) {
6137     LLVM_DEBUG(
6138         dbgs()
6139             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
6140     return Result;
6141   }
6142 
6143   auto FixedMainLoopVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
6144   if (MainLoopVF.isScalable())
6145     LLVM_DEBUG(
6146         dbgs() << "LEV: Epilogue vectorization using scalable vectors not "
6147                   "yet supported. Converting to fixed-width (VF="
6148                << FixedMainLoopVF << ") instead\n");
6149 
6150   if (!isEpilogueVectorizationProfitable(FixedMainLoopVF)) {
6151     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
6152                          "this loop\n");
6153     return Result;
6154   }
6155 
6156   for (auto &NextVF : ProfitableVFs)
6157     if (ElementCount::isKnownLT(NextVF.Width, FixedMainLoopVF) &&
6158         (Result.Width.getFixedValue() == 1 ||
6159          isMoreProfitable(NextVF, Result)) &&
6160         LVP.hasPlanWithVF(NextVF.Width))
6161       Result = NextVF;
6162 
6163   if (Result != VectorizationFactor::Disabled())
6164     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6165                       << Result.Width.getFixedValue() << "\n";);
6166   return Result;
6167 }
6168 
6169 std::pair<unsigned, unsigned>
6170 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6171   unsigned MinWidth = -1U;
6172   unsigned MaxWidth = 8;
6173   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6174   for (Type *T : ElementTypesInLoop) {
6175     MinWidth = std::min<unsigned>(
6176         MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6177     MaxWidth = std::max<unsigned>(
6178         MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
6179   }
6180   return {MinWidth, MaxWidth};
6181 }
6182 
6183 void LoopVectorizationCostModel::collectElementTypesForWidening() {
6184   ElementTypesInLoop.clear();
6185   // For each block.
6186   for (BasicBlock *BB : TheLoop->blocks()) {
6187     // For each instruction in the loop.
6188     for (Instruction &I : BB->instructionsWithoutDebug()) {
6189       Type *T = I.getType();
6190 
6191       // Skip ignored values.
6192       if (ValuesToIgnore.count(&I))
6193         continue;
6194 
6195       // Only examine Loads, Stores and PHINodes.
6196       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6197         continue;
6198 
6199       // Examine PHI nodes that are reduction variables. Update the type to
6200       // account for the recurrence type.
6201       if (auto *PN = dyn_cast<PHINode>(&I)) {
6202         if (!Legal->isReductionVariable(PN))
6203           continue;
6204         const RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[PN];
6205         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6206             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6207                                       RdxDesc.getRecurrenceType(),
6208                                       TargetTransformInfo::ReductionFlags()))
6209           continue;
6210         T = RdxDesc.getRecurrenceType();
6211       }
6212 
6213       // Examine the stored values.
6214       if (auto *ST = dyn_cast<StoreInst>(&I))
6215         T = ST->getValueOperand()->getType();
6216 
6217       // Ignore loaded pointer types and stored pointer types that are not
6218       // vectorizable.
6219       //
6220       // FIXME: The check here attempts to predict whether a load or store will
6221       //        be vectorized. We only know this for certain after a VF has
6222       //        been selected. Here, we assume that if an access can be
6223       //        vectorized, it will be. We should also look at extending this
6224       //        optimization to non-pointer types.
6225       //
6226       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6227           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6228         continue;
6229 
6230       ElementTypesInLoop.insert(T);
6231     }
6232   }
6233 }
6234 
6235 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6236                                                            unsigned LoopCost) {
6237   // -- The interleave heuristics --
6238   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6239   // There are many micro-architectural considerations that we can't predict
6240   // at this level. For example, frontend pressure (on decode or fetch) due to
6241   // code size, or the number and capabilities of the execution ports.
6242   //
6243   // We use the following heuristics to select the interleave count:
6244   // 1. If the code has reductions, then we interleave to break the cross
6245   // iteration dependency.
6246   // 2. If the loop is really small, then we interleave to reduce the loop
6247   // overhead.
6248   // 3. We don't interleave if we think that we will spill registers to memory
6249   // due to the increased register pressure.
6250 
6251   if (!isScalarEpilogueAllowed())
6252     return 1;
6253 
6254   // We used the distance for the interleave count.
6255   if (Legal->getMaxSafeDepDistBytes() != -1U)
6256     return 1;
6257 
6258   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6259   const bool HasReductions = !Legal->getReductionVars().empty();
6260   // Do not interleave loops with a relatively small known or estimated trip
6261   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6262   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6263   // because with the above conditions interleaving can expose ILP and break
6264   // cross iteration dependences for reductions.
6265   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6266       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6267     return 1;
6268 
6269   RegisterUsage R = calculateRegisterUsage({VF})[0];
6270   // We divide by these constants so assume that we have at least one
6271   // instruction that uses at least one register.
6272   for (auto& pair : R.MaxLocalUsers) {
6273     pair.second = std::max(pair.second, 1U);
6274   }
6275 
6276   // We calculate the interleave count using the following formula.
6277   // Subtract the number of loop invariants from the number of available
6278   // registers. These registers are used by all of the interleaved instances.
6279   // Next, divide the remaining registers by the number of registers that is
6280   // required by the loop, in order to estimate how many parallel instances
6281   // fit without causing spills. All of this is rounded down if necessary to be
6282   // a power of two. We want power of two interleave count to simplify any
6283   // addressing operations or alignment considerations.
6284   // We also want power of two interleave counts to ensure that the induction
6285   // variable of the vector loop wraps to zero, when tail is folded by masking;
6286   // this currently happens when OptForSize, in which case IC is set to 1 above.
6287   unsigned IC = UINT_MAX;
6288 
6289   for (auto& pair : R.MaxLocalUsers) {
6290     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6291     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6292                       << " registers of "
6293                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6294     if (VF.isScalar()) {
6295       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6296         TargetNumRegisters = ForceTargetNumScalarRegs;
6297     } else {
6298       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6299         TargetNumRegisters = ForceTargetNumVectorRegs;
6300     }
6301     unsigned MaxLocalUsers = pair.second;
6302     unsigned LoopInvariantRegs = 0;
6303     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6304       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6305 
6306     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6307     // Don't count the induction variable as interleaved.
6308     if (EnableIndVarRegisterHeur) {
6309       TmpIC =
6310           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6311                         std::max(1U, (MaxLocalUsers - 1)));
6312     }
6313 
6314     IC = std::min(IC, TmpIC);
6315   }
6316 
6317   // Clamp the interleave ranges to reasonable counts.
6318   unsigned MaxInterleaveCount =
6319       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6320 
6321   // Check if the user has overridden the max.
6322   if (VF.isScalar()) {
6323     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6324       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6325   } else {
6326     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6327       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6328   }
6329 
6330   // If trip count is known or estimated compile time constant, limit the
6331   // interleave count to be less than the trip count divided by VF, provided it
6332   // is at least 1.
6333   //
6334   // For scalable vectors we can't know if interleaving is beneficial. It may
6335   // not be beneficial for small loops if none of the lanes in the second vector
6336   // iterations is enabled. However, for larger loops, there is likely to be a
6337   // similar benefit as for fixed-width vectors. For now, we choose to leave
6338   // the InterleaveCount as if vscale is '1', although if some information about
6339   // the vector is known (e.g. min vector size), we can make a better decision.
6340   if (BestKnownTC) {
6341     MaxInterleaveCount =
6342         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6343     // Make sure MaxInterleaveCount is greater than 0.
6344     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6345   }
6346 
6347   assert(MaxInterleaveCount > 0 &&
6348          "Maximum interleave count must be greater than 0");
6349 
6350   // Clamp the calculated IC to be between the 1 and the max interleave count
6351   // that the target and trip count allows.
6352   if (IC > MaxInterleaveCount)
6353     IC = MaxInterleaveCount;
6354   else
6355     // Make sure IC is greater than 0.
6356     IC = std::max(1u, IC);
6357 
6358   assert(IC > 0 && "Interleave count must be greater than 0.");
6359 
6360   // If we did not calculate the cost for VF (because the user selected the VF)
6361   // then we calculate the cost of VF here.
6362   if (LoopCost == 0) {
6363     InstructionCost C = expectedCost(VF).first;
6364     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
6365     LoopCost = *C.getValue();
6366   }
6367 
6368   assert(LoopCost && "Non-zero loop cost expected");
6369 
6370   // Interleave if we vectorized this loop and there is a reduction that could
6371   // benefit from interleaving.
6372   if (VF.isVector() && HasReductions) {
6373     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6374     return IC;
6375   }
6376 
6377   // Note that if we've already vectorized the loop we will have done the
6378   // runtime check and so interleaving won't require further checks.
6379   bool InterleavingRequiresRuntimePointerCheck =
6380       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6381 
6382   // We want to interleave small loops in order to reduce the loop overhead and
6383   // potentially expose ILP opportunities.
6384   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6385                     << "LV: IC is " << IC << '\n'
6386                     << "LV: VF is " << VF << '\n');
6387   const bool AggressivelyInterleaveReductions =
6388       TTI.enableAggressiveInterleaving(HasReductions);
6389   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6390     // We assume that the cost overhead is 1 and we use the cost model
6391     // to estimate the cost of the loop and interleave until the cost of the
6392     // loop overhead is about 5% of the cost of the loop.
6393     unsigned SmallIC =
6394         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6395 
6396     // Interleave until store/load ports (estimated by max interleave count) are
6397     // saturated.
6398     unsigned NumStores = Legal->getNumStores();
6399     unsigned NumLoads = Legal->getNumLoads();
6400     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6401     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6402 
6403     // There is little point in interleaving for reductions containing selects
6404     // and compares when VF=1 since it may just create more overhead than it's
6405     // worth for loops with small trip counts. This is because we still have to
6406     // do the final reduction after the loop.
6407     bool HasSelectCmpReductions =
6408         HasReductions &&
6409         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
6410           const RecurrenceDescriptor &RdxDesc = Reduction.second;
6411           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
6412               RdxDesc.getRecurrenceKind());
6413         });
6414     if (HasSelectCmpReductions) {
6415       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
6416       return 1;
6417     }
6418 
6419     // If we have a scalar reduction (vector reductions are already dealt with
6420     // by this point), we can increase the critical path length if the loop
6421     // we're interleaving is inside another loop. For tree-wise reductions
6422     // set the limit to 2, and for ordered reductions it's best to disable
6423     // interleaving entirely.
6424     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6425       bool HasOrderedReductions =
6426           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
6427             const RecurrenceDescriptor &RdxDesc = Reduction.second;
6428             return RdxDesc.isOrdered();
6429           });
6430       if (HasOrderedReductions) {
6431         LLVM_DEBUG(
6432             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
6433         return 1;
6434       }
6435 
6436       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6437       SmallIC = std::min(SmallIC, F);
6438       StoresIC = std::min(StoresIC, F);
6439       LoadsIC = std::min(LoadsIC, F);
6440     }
6441 
6442     if (EnableLoadStoreRuntimeInterleave &&
6443         std::max(StoresIC, LoadsIC) > SmallIC) {
6444       LLVM_DEBUG(
6445           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6446       return std::max(StoresIC, LoadsIC);
6447     }
6448 
6449     // If there are scalar reductions and TTI has enabled aggressive
6450     // interleaving for reductions, we will interleave to expose ILP.
6451     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6452         AggressivelyInterleaveReductions) {
6453       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6454       // Interleave no less than SmallIC but not as aggressive as the normal IC
6455       // to satisfy the rare situation when resources are too limited.
6456       return std::max(IC / 2, SmallIC);
6457     } else {
6458       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6459       return SmallIC;
6460     }
6461   }
6462 
6463   // Interleave if this is a large loop (small loops are already dealt with by
6464   // this point) that could benefit from interleaving.
6465   if (AggressivelyInterleaveReductions) {
6466     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6467     return IC;
6468   }
6469 
6470   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6471   return 1;
6472 }
6473 
6474 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6475 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6476   // This function calculates the register usage by measuring the highest number
6477   // of values that are alive at a single location. Obviously, this is a very
6478   // rough estimation. We scan the loop in a topological order in order and
6479   // assign a number to each instruction. We use RPO to ensure that defs are
6480   // met before their users. We assume that each instruction that has in-loop
6481   // users starts an interval. We record every time that an in-loop value is
6482   // used, so we have a list of the first and last occurrences of each
6483   // instruction. Next, we transpose this data structure into a multi map that
6484   // holds the list of intervals that *end* at a specific location. This multi
6485   // map allows us to perform a linear search. We scan the instructions linearly
6486   // and record each time that a new interval starts, by placing it in a set.
6487   // If we find this value in the multi-map then we remove it from the set.
6488   // The max register usage is the maximum size of the set.
6489   // We also search for instructions that are defined outside the loop, but are
6490   // used inside the loop. We need this number separately from the max-interval
6491   // usage number because when we unroll, loop-invariant values do not take
6492   // more register.
6493   LoopBlocksDFS DFS(TheLoop);
6494   DFS.perform(LI);
6495 
6496   RegisterUsage RU;
6497 
6498   // Each 'key' in the map opens a new interval. The values
6499   // of the map are the index of the 'last seen' usage of the
6500   // instruction that is the key.
6501   using IntervalMap = DenseMap<Instruction *, unsigned>;
6502 
6503   // Maps instruction to its index.
6504   SmallVector<Instruction *, 64> IdxToInstr;
6505   // Marks the end of each interval.
6506   IntervalMap EndPoint;
6507   // Saves the list of instruction indices that are used in the loop.
6508   SmallPtrSet<Instruction *, 8> Ends;
6509   // Saves the list of values that are used in the loop but are
6510   // defined outside the loop, such as arguments and constants.
6511   SmallPtrSet<Value *, 8> LoopInvariants;
6512 
6513   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6514     for (Instruction &I : BB->instructionsWithoutDebug()) {
6515       IdxToInstr.push_back(&I);
6516 
6517       // Save the end location of each USE.
6518       for (Value *U : I.operands()) {
6519         auto *Instr = dyn_cast<Instruction>(U);
6520 
6521         // Ignore non-instruction values such as arguments, constants, etc.
6522         if (!Instr)
6523           continue;
6524 
6525         // If this instruction is outside the loop then record it and continue.
6526         if (!TheLoop->contains(Instr)) {
6527           LoopInvariants.insert(Instr);
6528           continue;
6529         }
6530 
6531         // Overwrite previous end points.
6532         EndPoint[Instr] = IdxToInstr.size();
6533         Ends.insert(Instr);
6534       }
6535     }
6536   }
6537 
6538   // Saves the list of intervals that end with the index in 'key'.
6539   using InstrList = SmallVector<Instruction *, 2>;
6540   DenseMap<unsigned, InstrList> TransposeEnds;
6541 
6542   // Transpose the EndPoints to a list of values that end at each index.
6543   for (auto &Interval : EndPoint)
6544     TransposeEnds[Interval.second].push_back(Interval.first);
6545 
6546   SmallPtrSet<Instruction *, 8> OpenIntervals;
6547   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6548   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6549 
6550   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6551 
6552   // A lambda that gets the register usage for the given type and VF.
6553   const auto &TTICapture = TTI;
6554   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) -> unsigned {
6555     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6556       return 0;
6557     InstructionCost::CostType RegUsage =
6558         *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6559     assert(RegUsage >= 0 && RegUsage <= std::numeric_limits<unsigned>::max() &&
6560            "Nonsensical values for register usage.");
6561     return RegUsage;
6562   };
6563 
6564   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6565     Instruction *I = IdxToInstr[i];
6566 
6567     // Remove all of the instructions that end at this location.
6568     InstrList &List = TransposeEnds[i];
6569     for (Instruction *ToRemove : List)
6570       OpenIntervals.erase(ToRemove);
6571 
6572     // Ignore instructions that are never used within the loop.
6573     if (!Ends.count(I))
6574       continue;
6575 
6576     // Skip ignored values.
6577     if (ValuesToIgnore.count(I))
6578       continue;
6579 
6580     // For each VF find the maximum usage of registers.
6581     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6582       // Count the number of live intervals.
6583       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6584 
6585       if (VFs[j].isScalar()) {
6586         for (auto Inst : OpenIntervals) {
6587           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6588           if (RegUsage.find(ClassID) == RegUsage.end())
6589             RegUsage[ClassID] = 1;
6590           else
6591             RegUsage[ClassID] += 1;
6592         }
6593       } else {
6594         collectUniformsAndScalars(VFs[j]);
6595         for (auto Inst : OpenIntervals) {
6596           // Skip ignored values for VF > 1.
6597           if (VecValuesToIgnore.count(Inst))
6598             continue;
6599           if (isScalarAfterVectorization(Inst, VFs[j])) {
6600             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6601             if (RegUsage.find(ClassID) == RegUsage.end())
6602               RegUsage[ClassID] = 1;
6603             else
6604               RegUsage[ClassID] += 1;
6605           } else {
6606             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6607             if (RegUsage.find(ClassID) == RegUsage.end())
6608               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6609             else
6610               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6611           }
6612         }
6613       }
6614 
6615       for (auto& pair : RegUsage) {
6616         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6617           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6618         else
6619           MaxUsages[j][pair.first] = pair.second;
6620       }
6621     }
6622 
6623     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6624                       << OpenIntervals.size() << '\n');
6625 
6626     // Add the current instruction to the list of open intervals.
6627     OpenIntervals.insert(I);
6628   }
6629 
6630   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6631     SmallMapVector<unsigned, unsigned, 4> Invariant;
6632 
6633     for (auto Inst : LoopInvariants) {
6634       unsigned Usage =
6635           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6636       unsigned ClassID =
6637           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6638       if (Invariant.find(ClassID) == Invariant.end())
6639         Invariant[ClassID] = Usage;
6640       else
6641         Invariant[ClassID] += Usage;
6642     }
6643 
6644     LLVM_DEBUG({
6645       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6646       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6647              << " item\n";
6648       for (const auto &pair : MaxUsages[i]) {
6649         dbgs() << "LV(REG): RegisterClass: "
6650                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6651                << " registers\n";
6652       }
6653       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6654              << " item\n";
6655       for (const auto &pair : Invariant) {
6656         dbgs() << "LV(REG): RegisterClass: "
6657                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6658                << " registers\n";
6659       }
6660     });
6661 
6662     RU.LoopInvariantRegs = Invariant;
6663     RU.MaxLocalUsers = MaxUsages[i];
6664     RUs[i] = RU;
6665   }
6666 
6667   return RUs;
6668 }
6669 
6670 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6671   // TODO: Cost model for emulated masked load/store is completely
6672   // broken. This hack guides the cost model to use an artificially
6673   // high enough value to practically disable vectorization with such
6674   // operations, except where previously deployed legality hack allowed
6675   // using very low cost values. This is to avoid regressions coming simply
6676   // from moving "masked load/store" check from legality to cost model.
6677   // Masked Load/Gather emulation was previously never allowed.
6678   // Limited number of Masked Store/Scatter emulation was allowed.
6679   assert(isPredicatedInst(I) &&
6680          "Expecting a scalar emulated instruction");
6681   return isa<LoadInst>(I) ||
6682          (isa<StoreInst>(I) &&
6683           NumPredStores > NumberOfStoresToPredicate);
6684 }
6685 
6686 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6687   // If we aren't vectorizing the loop, or if we've already collected the
6688   // instructions to scalarize, there's nothing to do. Collection may already
6689   // have occurred if we have a user-selected VF and are now computing the
6690   // expected cost for interleaving.
6691   if (VF.isScalar() || VF.isZero() ||
6692       InstsToScalarize.find(VF) != InstsToScalarize.end())
6693     return;
6694 
6695   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6696   // not profitable to scalarize any instructions, the presence of VF in the
6697   // map will indicate that we've analyzed it already.
6698   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6699 
6700   // Find all the instructions that are scalar with predication in the loop and
6701   // determine if it would be better to not if-convert the blocks they are in.
6702   // If so, we also record the instructions to scalarize.
6703   for (BasicBlock *BB : TheLoop->blocks()) {
6704     if (!blockNeedsPredicationForAnyReason(BB))
6705       continue;
6706     for (Instruction &I : *BB)
6707       if (isScalarWithPredication(&I)) {
6708         ScalarCostsTy ScalarCosts;
6709         // Do not apply discount if scalable, because that would lead to
6710         // invalid scalarization costs.
6711         // Do not apply discount logic if hacked cost is needed
6712         // for emulated masked memrefs.
6713         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I) &&
6714             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6715           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6716         // Remember that BB will remain after vectorization.
6717         PredicatedBBsAfterVectorization.insert(BB);
6718       }
6719   }
6720 }
6721 
6722 int LoopVectorizationCostModel::computePredInstDiscount(
6723     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6724   assert(!isUniformAfterVectorization(PredInst, VF) &&
6725          "Instruction marked uniform-after-vectorization will be predicated");
6726 
6727   // Initialize the discount to zero, meaning that the scalar version and the
6728   // vector version cost the same.
6729   InstructionCost Discount = 0;
6730 
6731   // Holds instructions to analyze. The instructions we visit are mapped in
6732   // ScalarCosts. Those instructions are the ones that would be scalarized if
6733   // we find that the scalar version costs less.
6734   SmallVector<Instruction *, 8> Worklist;
6735 
6736   // Returns true if the given instruction can be scalarized.
6737   auto canBeScalarized = [&](Instruction *I) -> bool {
6738     // We only attempt to scalarize instructions forming a single-use chain
6739     // from the original predicated block that would otherwise be vectorized.
6740     // Although not strictly necessary, we give up on instructions we know will
6741     // already be scalar to avoid traversing chains that are unlikely to be
6742     // beneficial.
6743     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6744         isScalarAfterVectorization(I, VF))
6745       return false;
6746 
6747     // If the instruction is scalar with predication, it will be analyzed
6748     // separately. We ignore it within the context of PredInst.
6749     if (isScalarWithPredication(I))
6750       return false;
6751 
6752     // If any of the instruction's operands are uniform after vectorization,
6753     // the instruction cannot be scalarized. This prevents, for example, a
6754     // masked load from being scalarized.
6755     //
6756     // We assume we will only emit a value for lane zero of an instruction
6757     // marked uniform after vectorization, rather than VF identical values.
6758     // Thus, if we scalarize an instruction that uses a uniform, we would
6759     // create uses of values corresponding to the lanes we aren't emitting code
6760     // for. This behavior can be changed by allowing getScalarValue to clone
6761     // the lane zero values for uniforms rather than asserting.
6762     for (Use &U : I->operands())
6763       if (auto *J = dyn_cast<Instruction>(U.get()))
6764         if (isUniformAfterVectorization(J, VF))
6765           return false;
6766 
6767     // Otherwise, we can scalarize the instruction.
6768     return true;
6769   };
6770 
6771   // Compute the expected cost discount from scalarizing the entire expression
6772   // feeding the predicated instruction. We currently only consider expressions
6773   // that are single-use instruction chains.
6774   Worklist.push_back(PredInst);
6775   while (!Worklist.empty()) {
6776     Instruction *I = Worklist.pop_back_val();
6777 
6778     // If we've already analyzed the instruction, there's nothing to do.
6779     if (ScalarCosts.find(I) != ScalarCosts.end())
6780       continue;
6781 
6782     // Compute the cost of the vector instruction. Note that this cost already
6783     // includes the scalarization overhead of the predicated instruction.
6784     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6785 
6786     // Compute the cost of the scalarized instruction. This cost is the cost of
6787     // the instruction as if it wasn't if-converted and instead remained in the
6788     // predicated block. We will scale this cost by block probability after
6789     // computing the scalarization overhead.
6790     InstructionCost ScalarCost =
6791         VF.getFixedValue() *
6792         getInstructionCost(I, ElementCount::getFixed(1)).first;
6793 
6794     // Compute the scalarization overhead of needed insertelement instructions
6795     // and phi nodes.
6796     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6797       ScalarCost += TTI.getScalarizationOverhead(
6798           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6799           APInt::getAllOnes(VF.getFixedValue()), true, false);
6800       ScalarCost +=
6801           VF.getFixedValue() *
6802           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6803     }
6804 
6805     // Compute the scalarization overhead of needed extractelement
6806     // instructions. For each of the instruction's operands, if the operand can
6807     // be scalarized, add it to the worklist; otherwise, account for the
6808     // overhead.
6809     for (Use &U : I->operands())
6810       if (auto *J = dyn_cast<Instruction>(U.get())) {
6811         assert(VectorType::isValidElementType(J->getType()) &&
6812                "Instruction has non-scalar type");
6813         if (canBeScalarized(J))
6814           Worklist.push_back(J);
6815         else if (needsExtract(J, VF)) {
6816           ScalarCost += TTI.getScalarizationOverhead(
6817               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6818               APInt::getAllOnes(VF.getFixedValue()), false, true);
6819         }
6820       }
6821 
6822     // Scale the total scalar cost by block probability.
6823     ScalarCost /= getReciprocalPredBlockProb();
6824 
6825     // Compute the discount. A non-negative discount means the vector version
6826     // of the instruction costs more, and scalarizing would be beneficial.
6827     Discount += VectorCost - ScalarCost;
6828     ScalarCosts[I] = ScalarCost;
6829   }
6830 
6831   return *Discount.getValue();
6832 }
6833 
6834 LoopVectorizationCostModel::VectorizationCostTy
6835 LoopVectorizationCostModel::expectedCost(
6836     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6837   VectorizationCostTy Cost;
6838 
6839   // For each block.
6840   for (BasicBlock *BB : TheLoop->blocks()) {
6841     VectorizationCostTy BlockCost;
6842 
6843     // For each instruction in the old loop.
6844     for (Instruction &I : BB->instructionsWithoutDebug()) {
6845       // Skip ignored values.
6846       if (ValuesToIgnore.count(&I) ||
6847           (VF.isVector() && VecValuesToIgnore.count(&I)))
6848         continue;
6849 
6850       VectorizationCostTy C = getInstructionCost(&I, VF);
6851 
6852       // Check if we should override the cost.
6853       if (C.first.isValid() &&
6854           ForceTargetInstructionCost.getNumOccurrences() > 0)
6855         C.first = InstructionCost(ForceTargetInstructionCost);
6856 
6857       // Keep a list of instructions with invalid costs.
6858       if (Invalid && !C.first.isValid())
6859         Invalid->emplace_back(&I, VF);
6860 
6861       BlockCost.first += C.first;
6862       BlockCost.second |= C.second;
6863       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6864                         << " for VF " << VF << " For instruction: " << I
6865                         << '\n');
6866     }
6867 
6868     // If we are vectorizing a predicated block, it will have been
6869     // if-converted. This means that the block's instructions (aside from
6870     // stores and instructions that may divide by zero) will now be
6871     // unconditionally executed. For the scalar case, we may not always execute
6872     // the predicated block, if it is an if-else block. Thus, scale the block's
6873     // cost by the probability of executing it. blockNeedsPredication from
6874     // Legal is used so as to not include all blocks in tail folded loops.
6875     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6876       BlockCost.first /= getReciprocalPredBlockProb();
6877 
6878     Cost.first += BlockCost.first;
6879     Cost.second |= BlockCost.second;
6880   }
6881 
6882   return Cost;
6883 }
6884 
6885 /// Gets Address Access SCEV after verifying that the access pattern
6886 /// is loop invariant except the induction variable dependence.
6887 ///
6888 /// This SCEV can be sent to the Target in order to estimate the address
6889 /// calculation cost.
6890 static const SCEV *getAddressAccessSCEV(
6891               Value *Ptr,
6892               LoopVectorizationLegality *Legal,
6893               PredicatedScalarEvolution &PSE,
6894               const Loop *TheLoop) {
6895 
6896   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6897   if (!Gep)
6898     return nullptr;
6899 
6900   // We are looking for a gep with all loop invariant indices except for one
6901   // which should be an induction variable.
6902   auto SE = PSE.getSE();
6903   unsigned NumOperands = Gep->getNumOperands();
6904   for (unsigned i = 1; i < NumOperands; ++i) {
6905     Value *Opd = Gep->getOperand(i);
6906     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6907         !Legal->isInductionVariable(Opd))
6908       return nullptr;
6909   }
6910 
6911   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6912   return PSE.getSCEV(Ptr);
6913 }
6914 
6915 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6916   return Legal->hasStride(I->getOperand(0)) ||
6917          Legal->hasStride(I->getOperand(1));
6918 }
6919 
6920 InstructionCost
6921 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6922                                                         ElementCount VF) {
6923   assert(VF.isVector() &&
6924          "Scalarization cost of instruction implies vectorization.");
6925   if (VF.isScalable())
6926     return InstructionCost::getInvalid();
6927 
6928   Type *ValTy = getLoadStoreType(I);
6929   auto SE = PSE.getSE();
6930 
6931   unsigned AS = getLoadStoreAddressSpace(I);
6932   Value *Ptr = getLoadStorePointerOperand(I);
6933   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6934   // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
6935   //       that it is being called from this specific place.
6936 
6937   // Figure out whether the access is strided and get the stride value
6938   // if it's known in compile time
6939   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6940 
6941   // Get the cost of the scalar memory instruction and address computation.
6942   InstructionCost Cost =
6943       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6944 
6945   // Don't pass *I here, since it is scalar but will actually be part of a
6946   // vectorized loop where the user of it is a vectorized instruction.
6947   const Align Alignment = getLoadStoreAlignment(I);
6948   Cost += VF.getKnownMinValue() *
6949           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6950                               AS, TTI::TCK_RecipThroughput);
6951 
6952   // Get the overhead of the extractelement and insertelement instructions
6953   // we might create due to scalarization.
6954   Cost += getScalarizationOverhead(I, VF);
6955 
6956   // If we have a predicated load/store, it will need extra i1 extracts and
6957   // conditional branches, but may not be executed for each vector lane. Scale
6958   // the cost by the probability of executing the predicated block.
6959   if (isPredicatedInst(I)) {
6960     Cost /= getReciprocalPredBlockProb();
6961 
6962     // Add the cost of an i1 extract and a branch
6963     auto *Vec_i1Ty =
6964         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6965     Cost += TTI.getScalarizationOverhead(
6966         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
6967         /*Insert=*/false, /*Extract=*/true);
6968     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6969 
6970     if (useEmulatedMaskMemRefHack(I))
6971       // Artificially setting to a high enough value to practically disable
6972       // vectorization with such operations.
6973       Cost = 3000000;
6974   }
6975 
6976   return Cost;
6977 }
6978 
6979 InstructionCost
6980 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6981                                                     ElementCount VF) {
6982   Type *ValTy = getLoadStoreType(I);
6983   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6984   Value *Ptr = getLoadStorePointerOperand(I);
6985   unsigned AS = getLoadStoreAddressSpace(I);
6986   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
6987   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6988 
6989   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6990          "Stride should be 1 or -1 for consecutive memory access");
6991   const Align Alignment = getLoadStoreAlignment(I);
6992   InstructionCost Cost = 0;
6993   if (Legal->isMaskRequired(I))
6994     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6995                                       CostKind);
6996   else
6997     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6998                                 CostKind, I);
6999 
7000   bool Reverse = ConsecutiveStride < 0;
7001   if (Reverse)
7002     Cost +=
7003         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7004   return Cost;
7005 }
7006 
7007 InstructionCost
7008 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
7009                                                 ElementCount VF) {
7010   assert(Legal->isUniformMemOp(*I));
7011 
7012   Type *ValTy = getLoadStoreType(I);
7013   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7014   const Align Alignment = getLoadStoreAlignment(I);
7015   unsigned AS = getLoadStoreAddressSpace(I);
7016   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7017   if (isa<LoadInst>(I)) {
7018     return TTI.getAddressComputationCost(ValTy) +
7019            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
7020                                CostKind) +
7021            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
7022   }
7023   StoreInst *SI = cast<StoreInst>(I);
7024 
7025   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
7026   return TTI.getAddressComputationCost(ValTy) +
7027          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
7028                              CostKind) +
7029          (isLoopInvariantStoreValue
7030               ? 0
7031               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
7032                                        VF.getKnownMinValue() - 1));
7033 }
7034 
7035 InstructionCost
7036 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
7037                                                  ElementCount VF) {
7038   Type *ValTy = getLoadStoreType(I);
7039   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7040   const Align Alignment = getLoadStoreAlignment(I);
7041   const Value *Ptr = getLoadStorePointerOperand(I);
7042 
7043   return TTI.getAddressComputationCost(VectorTy) +
7044          TTI.getGatherScatterOpCost(
7045              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
7046              TargetTransformInfo::TCK_RecipThroughput, I);
7047 }
7048 
7049 InstructionCost
7050 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
7051                                                    ElementCount VF) {
7052   // TODO: Once we have support for interleaving with scalable vectors
7053   // we can calculate the cost properly here.
7054   if (VF.isScalable())
7055     return InstructionCost::getInvalid();
7056 
7057   Type *ValTy = getLoadStoreType(I);
7058   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7059   unsigned AS = getLoadStoreAddressSpace(I);
7060 
7061   auto Group = getInterleavedAccessGroup(I);
7062   assert(Group && "Fail to get an interleaved access group.");
7063 
7064   unsigned InterleaveFactor = Group->getFactor();
7065   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
7066 
7067   // Holds the indices of existing members in the interleaved group.
7068   SmallVector<unsigned, 4> Indices;
7069   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
7070     if (Group->getMember(IF))
7071       Indices.push_back(IF);
7072 
7073   // Calculate the cost of the whole interleaved group.
7074   bool UseMaskForGaps =
7075       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
7076       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
7077   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
7078       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
7079       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
7080 
7081   if (Group->isReverse()) {
7082     // TODO: Add support for reversed masked interleaved access.
7083     assert(!Legal->isMaskRequired(I) &&
7084            "Reverse masked interleaved access not supported.");
7085     Cost +=
7086         Group->getNumMembers() *
7087         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7088   }
7089   return Cost;
7090 }
7091 
7092 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
7093     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
7094   using namespace llvm::PatternMatch;
7095   // Early exit for no inloop reductions
7096   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
7097     return None;
7098   auto *VectorTy = cast<VectorType>(Ty);
7099 
7100   // We are looking for a pattern of, and finding the minimal acceptable cost:
7101   //  reduce(mul(ext(A), ext(B))) or
7102   //  reduce(mul(A, B)) or
7103   //  reduce(ext(A)) or
7104   //  reduce(A).
7105   // The basic idea is that we walk down the tree to do that, finding the root
7106   // reduction instruction in InLoopReductionImmediateChains. From there we find
7107   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
7108   // of the components. If the reduction cost is lower then we return it for the
7109   // reduction instruction and 0 for the other instructions in the pattern. If
7110   // it is not we return an invalid cost specifying the orignal cost method
7111   // should be used.
7112   Instruction *RetI = I;
7113   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
7114     if (!RetI->hasOneUser())
7115       return None;
7116     RetI = RetI->user_back();
7117   }
7118   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
7119       RetI->user_back()->getOpcode() == Instruction::Add) {
7120     if (!RetI->hasOneUser())
7121       return None;
7122     RetI = RetI->user_back();
7123   }
7124 
7125   // Test if the found instruction is a reduction, and if not return an invalid
7126   // cost specifying the parent to use the original cost modelling.
7127   if (!InLoopReductionImmediateChains.count(RetI))
7128     return None;
7129 
7130   // Find the reduction this chain is a part of and calculate the basic cost of
7131   // the reduction on its own.
7132   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
7133   Instruction *ReductionPhi = LastChain;
7134   while (!isa<PHINode>(ReductionPhi))
7135     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
7136 
7137   const RecurrenceDescriptor &RdxDesc =
7138       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
7139 
7140   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
7141       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
7142 
7143   // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
7144   // normal fmul instruction to the cost of the fadd reduction.
7145   if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
7146     BaseCost +=
7147         TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
7148 
7149   // If we're using ordered reductions then we can just return the base cost
7150   // here, since getArithmeticReductionCost calculates the full ordered
7151   // reduction cost when FP reassociation is not allowed.
7152   if (useOrderedReductions(RdxDesc))
7153     return BaseCost;
7154 
7155   // Get the operand that was not the reduction chain and match it to one of the
7156   // patterns, returning the better cost if it is found.
7157   Instruction *RedOp = RetI->getOperand(1) == LastChain
7158                            ? dyn_cast<Instruction>(RetI->getOperand(0))
7159                            : dyn_cast<Instruction>(RetI->getOperand(1));
7160 
7161   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
7162 
7163   Instruction *Op0, *Op1;
7164   if (RedOp &&
7165       match(RedOp,
7166             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
7167       match(Op0, m_ZExtOrSExt(m_Value())) &&
7168       Op0->getOpcode() == Op1->getOpcode() &&
7169       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7170       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
7171       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
7172 
7173     // Matched reduce(ext(mul(ext(A), ext(B)))
7174     // Note that the extend opcodes need to all match, or if A==B they will have
7175     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
7176     // which is equally fine.
7177     bool IsUnsigned = isa<ZExtInst>(Op0);
7178     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7179     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
7180 
7181     InstructionCost ExtCost =
7182         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
7183                              TTI::CastContextHint::None, CostKind, Op0);
7184     InstructionCost MulCost =
7185         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
7186     InstructionCost Ext2Cost =
7187         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
7188                              TTI::CastContextHint::None, CostKind, RedOp);
7189 
7190     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7191         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7192         CostKind);
7193 
7194     if (RedCost.isValid() &&
7195         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
7196       return I == RetI ? RedCost : 0;
7197   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
7198              !TheLoop->isLoopInvariant(RedOp)) {
7199     // Matched reduce(ext(A))
7200     bool IsUnsigned = isa<ZExtInst>(RedOp);
7201     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7202     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7203         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7204         CostKind);
7205 
7206     InstructionCost ExtCost =
7207         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7208                              TTI::CastContextHint::None, CostKind, RedOp);
7209     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7210       return I == RetI ? RedCost : 0;
7211   } else if (RedOp &&
7212              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
7213     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
7214         Op0->getOpcode() == Op1->getOpcode() &&
7215         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7216         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7217       bool IsUnsigned = isa<ZExtInst>(Op0);
7218       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7219       // Matched reduce(mul(ext, ext))
7220       InstructionCost ExtCost =
7221           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
7222                                TTI::CastContextHint::None, CostKind, Op0);
7223       InstructionCost MulCost =
7224           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7225 
7226       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7227           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7228           CostKind);
7229 
7230       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
7231         return I == RetI ? RedCost : 0;
7232     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
7233       // Matched reduce(mul())
7234       InstructionCost MulCost =
7235           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7236 
7237       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7238           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7239           CostKind);
7240 
7241       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7242         return I == RetI ? RedCost : 0;
7243     }
7244   }
7245 
7246   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
7247 }
7248 
7249 InstructionCost
7250 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7251                                                      ElementCount VF) {
7252   // Calculate scalar cost only. Vectorization cost should be ready at this
7253   // moment.
7254   if (VF.isScalar()) {
7255     Type *ValTy = getLoadStoreType(I);
7256     const Align Alignment = getLoadStoreAlignment(I);
7257     unsigned AS = getLoadStoreAddressSpace(I);
7258 
7259     return TTI.getAddressComputationCost(ValTy) +
7260            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7261                                TTI::TCK_RecipThroughput, I);
7262   }
7263   return getWideningCost(I, VF);
7264 }
7265 
7266 LoopVectorizationCostModel::VectorizationCostTy
7267 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7268                                                ElementCount VF) {
7269   // If we know that this instruction will remain uniform, check the cost of
7270   // the scalar version.
7271   if (isUniformAfterVectorization(I, VF))
7272     VF = ElementCount::getFixed(1);
7273 
7274   if (VF.isVector() && isProfitableToScalarize(I, VF))
7275     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7276 
7277   // Forced scalars do not have any scalarization overhead.
7278   auto ForcedScalar = ForcedScalars.find(VF);
7279   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7280     auto InstSet = ForcedScalar->second;
7281     if (InstSet.count(I))
7282       return VectorizationCostTy(
7283           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7284            VF.getKnownMinValue()),
7285           false);
7286   }
7287 
7288   Type *VectorTy;
7289   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7290 
7291   bool TypeNotScalarized = false;
7292   if (VF.isVector() && VectorTy->isVectorTy()) {
7293     unsigned NumParts = TTI.getNumberOfParts(VectorTy);
7294     if (NumParts)
7295       TypeNotScalarized = NumParts < VF.getKnownMinValue();
7296     else
7297       C = InstructionCost::getInvalid();
7298   }
7299   return VectorizationCostTy(C, TypeNotScalarized);
7300 }
7301 
7302 InstructionCost
7303 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7304                                                      ElementCount VF) const {
7305 
7306   // There is no mechanism yet to create a scalable scalarization loop,
7307   // so this is currently Invalid.
7308   if (VF.isScalable())
7309     return InstructionCost::getInvalid();
7310 
7311   if (VF.isScalar())
7312     return 0;
7313 
7314   InstructionCost Cost = 0;
7315   Type *RetTy = ToVectorTy(I->getType(), VF);
7316   if (!RetTy->isVoidTy() &&
7317       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7318     Cost += TTI.getScalarizationOverhead(
7319         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
7320         false);
7321 
7322   // Some targets keep addresses scalar.
7323   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7324     return Cost;
7325 
7326   // Some targets support efficient element stores.
7327   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7328     return Cost;
7329 
7330   // Collect operands to consider.
7331   CallInst *CI = dyn_cast<CallInst>(I);
7332   Instruction::op_range Ops = CI ? CI->args() : I->operands();
7333 
7334   // Skip operands that do not require extraction/scalarization and do not incur
7335   // any overhead.
7336   SmallVector<Type *> Tys;
7337   for (auto *V : filterExtractingOperands(Ops, VF))
7338     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7339   return Cost + TTI.getOperandsScalarizationOverhead(
7340                     filterExtractingOperands(Ops, VF), Tys);
7341 }
7342 
7343 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7344   if (VF.isScalar())
7345     return;
7346   NumPredStores = 0;
7347   for (BasicBlock *BB : TheLoop->blocks()) {
7348     // For each instruction in the old loop.
7349     for (Instruction &I : *BB) {
7350       Value *Ptr =  getLoadStorePointerOperand(&I);
7351       if (!Ptr)
7352         continue;
7353 
7354       // TODO: We should generate better code and update the cost model for
7355       // predicated uniform stores. Today they are treated as any other
7356       // predicated store (see added test cases in
7357       // invariant-store-vectorization.ll).
7358       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7359         NumPredStores++;
7360 
7361       if (Legal->isUniformMemOp(I)) {
7362         // TODO: Avoid replicating loads and stores instead of
7363         // relying on instcombine to remove them.
7364         // Load: Scalar load + broadcast
7365         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7366         InstructionCost Cost;
7367         if (isa<StoreInst>(&I) && VF.isScalable() &&
7368             isLegalGatherOrScatter(&I)) {
7369           Cost = getGatherScatterCost(&I, VF);
7370           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
7371         } else {
7372           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
7373                  "Cannot yet scalarize uniform stores");
7374           Cost = getUniformMemOpCost(&I, VF);
7375           setWideningDecision(&I, VF, CM_Scalarize, Cost);
7376         }
7377         continue;
7378       }
7379 
7380       // We assume that widening is the best solution when possible.
7381       if (memoryInstructionCanBeWidened(&I, VF)) {
7382         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7383         int ConsecutiveStride = Legal->isConsecutivePtr(
7384             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
7385         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7386                "Expected consecutive stride.");
7387         InstWidening Decision =
7388             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7389         setWideningDecision(&I, VF, Decision, Cost);
7390         continue;
7391       }
7392 
7393       // Choose between Interleaving, Gather/Scatter or Scalarization.
7394       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7395       unsigned NumAccesses = 1;
7396       if (isAccessInterleaved(&I)) {
7397         auto Group = getInterleavedAccessGroup(&I);
7398         assert(Group && "Fail to get an interleaved access group.");
7399 
7400         // Make one decision for the whole group.
7401         if (getWideningDecision(&I, VF) != CM_Unknown)
7402           continue;
7403 
7404         NumAccesses = Group->getNumMembers();
7405         if (interleavedAccessCanBeWidened(&I, VF))
7406           InterleaveCost = getInterleaveGroupCost(&I, VF);
7407       }
7408 
7409       InstructionCost GatherScatterCost =
7410           isLegalGatherOrScatter(&I)
7411               ? getGatherScatterCost(&I, VF) * NumAccesses
7412               : InstructionCost::getInvalid();
7413 
7414       InstructionCost ScalarizationCost =
7415           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7416 
7417       // Choose better solution for the current VF,
7418       // write down this decision and use it during vectorization.
7419       InstructionCost Cost;
7420       InstWidening Decision;
7421       if (InterleaveCost <= GatherScatterCost &&
7422           InterleaveCost < ScalarizationCost) {
7423         Decision = CM_Interleave;
7424         Cost = InterleaveCost;
7425       } else if (GatherScatterCost < ScalarizationCost) {
7426         Decision = CM_GatherScatter;
7427         Cost = GatherScatterCost;
7428       } else {
7429         Decision = CM_Scalarize;
7430         Cost = ScalarizationCost;
7431       }
7432       // If the instructions belongs to an interleave group, the whole group
7433       // receives the same decision. The whole group receives the cost, but
7434       // the cost will actually be assigned to one instruction.
7435       if (auto Group = getInterleavedAccessGroup(&I))
7436         setWideningDecision(Group, VF, Decision, Cost);
7437       else
7438         setWideningDecision(&I, VF, Decision, Cost);
7439     }
7440   }
7441 
7442   // Make sure that any load of address and any other address computation
7443   // remains scalar unless there is gather/scatter support. This avoids
7444   // inevitable extracts into address registers, and also has the benefit of
7445   // activating LSR more, since that pass can't optimize vectorized
7446   // addresses.
7447   if (TTI.prefersVectorizedAddressing())
7448     return;
7449 
7450   // Start with all scalar pointer uses.
7451   SmallPtrSet<Instruction *, 8> AddrDefs;
7452   for (BasicBlock *BB : TheLoop->blocks())
7453     for (Instruction &I : *BB) {
7454       Instruction *PtrDef =
7455         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7456       if (PtrDef && TheLoop->contains(PtrDef) &&
7457           getWideningDecision(&I, VF) != CM_GatherScatter)
7458         AddrDefs.insert(PtrDef);
7459     }
7460 
7461   // Add all instructions used to generate the addresses.
7462   SmallVector<Instruction *, 4> Worklist;
7463   append_range(Worklist, AddrDefs);
7464   while (!Worklist.empty()) {
7465     Instruction *I = Worklist.pop_back_val();
7466     for (auto &Op : I->operands())
7467       if (auto *InstOp = dyn_cast<Instruction>(Op))
7468         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7469             AddrDefs.insert(InstOp).second)
7470           Worklist.push_back(InstOp);
7471   }
7472 
7473   for (auto *I : AddrDefs) {
7474     if (isa<LoadInst>(I)) {
7475       // Setting the desired widening decision should ideally be handled in
7476       // by cost functions, but since this involves the task of finding out
7477       // if the loaded register is involved in an address computation, it is
7478       // instead changed here when we know this is the case.
7479       InstWidening Decision = getWideningDecision(I, VF);
7480       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7481         // Scalarize a widened load of address.
7482         setWideningDecision(
7483             I, VF, CM_Scalarize,
7484             (VF.getKnownMinValue() *
7485              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7486       else if (auto Group = getInterleavedAccessGroup(I)) {
7487         // Scalarize an interleave group of address loads.
7488         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7489           if (Instruction *Member = Group->getMember(I))
7490             setWideningDecision(
7491                 Member, VF, CM_Scalarize,
7492                 (VF.getKnownMinValue() *
7493                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7494         }
7495       }
7496     } else
7497       // Make sure I gets scalarized and a cost estimate without
7498       // scalarization overhead.
7499       ForcedScalars[VF].insert(I);
7500   }
7501 }
7502 
7503 InstructionCost
7504 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7505                                                Type *&VectorTy) {
7506   Type *RetTy = I->getType();
7507   if (canTruncateToMinimalBitwidth(I, VF))
7508     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7509   auto SE = PSE.getSE();
7510   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7511 
7512   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7513                                                 ElementCount VF) -> bool {
7514     if (VF.isScalar())
7515       return true;
7516 
7517     auto Scalarized = InstsToScalarize.find(VF);
7518     assert(Scalarized != InstsToScalarize.end() &&
7519            "VF not yet analyzed for scalarization profitability");
7520     return !Scalarized->second.count(I) &&
7521            llvm::all_of(I->users(), [&](User *U) {
7522              auto *UI = cast<Instruction>(U);
7523              return !Scalarized->second.count(UI);
7524            });
7525   };
7526   (void) hasSingleCopyAfterVectorization;
7527 
7528   if (isScalarAfterVectorization(I, VF)) {
7529     // With the exception of GEPs and PHIs, after scalarization there should
7530     // only be one copy of the instruction generated in the loop. This is
7531     // because the VF is either 1, or any instructions that need scalarizing
7532     // have already been dealt with by the the time we get here. As a result,
7533     // it means we don't have to multiply the instruction cost by VF.
7534     assert(I->getOpcode() == Instruction::GetElementPtr ||
7535            I->getOpcode() == Instruction::PHI ||
7536            (I->getOpcode() == Instruction::BitCast &&
7537             I->getType()->isPointerTy()) ||
7538            hasSingleCopyAfterVectorization(I, VF));
7539     VectorTy = RetTy;
7540   } else
7541     VectorTy = ToVectorTy(RetTy, VF);
7542 
7543   // TODO: We need to estimate the cost of intrinsic calls.
7544   switch (I->getOpcode()) {
7545   case Instruction::GetElementPtr:
7546     // We mark this instruction as zero-cost because the cost of GEPs in
7547     // vectorized code depends on whether the corresponding memory instruction
7548     // is scalarized or not. Therefore, we handle GEPs with the memory
7549     // instruction cost.
7550     return 0;
7551   case Instruction::Br: {
7552     // In cases of scalarized and predicated instructions, there will be VF
7553     // predicated blocks in the vectorized loop. Each branch around these
7554     // blocks requires also an extract of its vector compare i1 element.
7555     bool ScalarPredicatedBB = false;
7556     BranchInst *BI = cast<BranchInst>(I);
7557     if (VF.isVector() && BI->isConditional() &&
7558         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7559          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7560       ScalarPredicatedBB = true;
7561 
7562     if (ScalarPredicatedBB) {
7563       // Not possible to scalarize scalable vector with predicated instructions.
7564       if (VF.isScalable())
7565         return InstructionCost::getInvalid();
7566       // Return cost for branches around scalarized and predicated blocks.
7567       auto *Vec_i1Ty =
7568           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7569       return (
7570           TTI.getScalarizationOverhead(
7571               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
7572           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
7573     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7574       // The back-edge branch will remain, as will all scalar branches.
7575       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7576     else
7577       // This branch will be eliminated by if-conversion.
7578       return 0;
7579     // Note: We currently assume zero cost for an unconditional branch inside
7580     // a predicated block since it will become a fall-through, although we
7581     // may decide in the future to call TTI for all branches.
7582   }
7583   case Instruction::PHI: {
7584     auto *Phi = cast<PHINode>(I);
7585 
7586     // First-order recurrences are replaced by vector shuffles inside the loop.
7587     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7588     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7589       return TTI.getShuffleCost(
7590           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7591           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7592 
7593     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7594     // converted into select instructions. We require N - 1 selects per phi
7595     // node, where N is the number of incoming values.
7596     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7597       return (Phi->getNumIncomingValues() - 1) *
7598              TTI.getCmpSelInstrCost(
7599                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7600                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7601                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7602 
7603     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7604   }
7605   case Instruction::UDiv:
7606   case Instruction::SDiv:
7607   case Instruction::URem:
7608   case Instruction::SRem:
7609     // If we have a predicated instruction, it may not be executed for each
7610     // vector lane. Get the scalarization cost and scale this amount by the
7611     // probability of executing the predicated block. If the instruction is not
7612     // predicated, we fall through to the next case.
7613     if (VF.isVector() && isScalarWithPredication(I)) {
7614       InstructionCost Cost = 0;
7615 
7616       // These instructions have a non-void type, so account for the phi nodes
7617       // that we will create. This cost is likely to be zero. The phi node
7618       // cost, if any, should be scaled by the block probability because it
7619       // models a copy at the end of each predicated block.
7620       Cost += VF.getKnownMinValue() *
7621               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7622 
7623       // The cost of the non-predicated instruction.
7624       Cost += VF.getKnownMinValue() *
7625               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7626 
7627       // The cost of insertelement and extractelement instructions needed for
7628       // scalarization.
7629       Cost += getScalarizationOverhead(I, VF);
7630 
7631       // Scale the cost by the probability of executing the predicated blocks.
7632       // This assumes the predicated block for each vector lane is equally
7633       // likely.
7634       return Cost / getReciprocalPredBlockProb();
7635     }
7636     LLVM_FALLTHROUGH;
7637   case Instruction::Add:
7638   case Instruction::FAdd:
7639   case Instruction::Sub:
7640   case Instruction::FSub:
7641   case Instruction::Mul:
7642   case Instruction::FMul:
7643   case Instruction::FDiv:
7644   case Instruction::FRem:
7645   case Instruction::Shl:
7646   case Instruction::LShr:
7647   case Instruction::AShr:
7648   case Instruction::And:
7649   case Instruction::Or:
7650   case Instruction::Xor: {
7651     // Since we will replace the stride by 1 the multiplication should go away.
7652     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7653       return 0;
7654 
7655     // Detect reduction patterns
7656     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7657       return *RedCost;
7658 
7659     // Certain instructions can be cheaper to vectorize if they have a constant
7660     // second vector operand. One example of this are shifts on x86.
7661     Value *Op2 = I->getOperand(1);
7662     TargetTransformInfo::OperandValueProperties Op2VP;
7663     TargetTransformInfo::OperandValueKind Op2VK =
7664         TTI.getOperandInfo(Op2, Op2VP);
7665     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7666       Op2VK = TargetTransformInfo::OK_UniformValue;
7667 
7668     SmallVector<const Value *, 4> Operands(I->operand_values());
7669     return TTI.getArithmeticInstrCost(
7670         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7671         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7672   }
7673   case Instruction::FNeg: {
7674     return TTI.getArithmeticInstrCost(
7675         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7676         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7677         TargetTransformInfo::OP_None, I->getOperand(0), I);
7678   }
7679   case Instruction::Select: {
7680     SelectInst *SI = cast<SelectInst>(I);
7681     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7682     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7683 
7684     const Value *Op0, *Op1;
7685     using namespace llvm::PatternMatch;
7686     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7687                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7688       // select x, y, false --> x & y
7689       // select x, true, y --> x | y
7690       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7691       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7692       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7693       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7694       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7695               Op1->getType()->getScalarSizeInBits() == 1);
7696 
7697       SmallVector<const Value *, 2> Operands{Op0, Op1};
7698       return TTI.getArithmeticInstrCost(
7699           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7700           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7701     }
7702 
7703     Type *CondTy = SI->getCondition()->getType();
7704     if (!ScalarCond)
7705       CondTy = VectorType::get(CondTy, VF);
7706     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
7707                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7708   }
7709   case Instruction::ICmp:
7710   case Instruction::FCmp: {
7711     Type *ValTy = I->getOperand(0)->getType();
7712     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7713     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7714       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7715     VectorTy = ToVectorTy(ValTy, VF);
7716     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7717                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7718   }
7719   case Instruction::Store:
7720   case Instruction::Load: {
7721     ElementCount Width = VF;
7722     if (Width.isVector()) {
7723       InstWidening Decision = getWideningDecision(I, Width);
7724       assert(Decision != CM_Unknown &&
7725              "CM decision should be taken at this point");
7726       if (Decision == CM_Scalarize)
7727         Width = ElementCount::getFixed(1);
7728     }
7729     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7730     return getMemoryInstructionCost(I, VF);
7731   }
7732   case Instruction::BitCast:
7733     if (I->getType()->isPointerTy())
7734       return 0;
7735     LLVM_FALLTHROUGH;
7736   case Instruction::ZExt:
7737   case Instruction::SExt:
7738   case Instruction::FPToUI:
7739   case Instruction::FPToSI:
7740   case Instruction::FPExt:
7741   case Instruction::PtrToInt:
7742   case Instruction::IntToPtr:
7743   case Instruction::SIToFP:
7744   case Instruction::UIToFP:
7745   case Instruction::Trunc:
7746   case Instruction::FPTrunc: {
7747     // Computes the CastContextHint from a Load/Store instruction.
7748     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7749       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7750              "Expected a load or a store!");
7751 
7752       if (VF.isScalar() || !TheLoop->contains(I))
7753         return TTI::CastContextHint::Normal;
7754 
7755       switch (getWideningDecision(I, VF)) {
7756       case LoopVectorizationCostModel::CM_GatherScatter:
7757         return TTI::CastContextHint::GatherScatter;
7758       case LoopVectorizationCostModel::CM_Interleave:
7759         return TTI::CastContextHint::Interleave;
7760       case LoopVectorizationCostModel::CM_Scalarize:
7761       case LoopVectorizationCostModel::CM_Widen:
7762         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7763                                         : TTI::CastContextHint::Normal;
7764       case LoopVectorizationCostModel::CM_Widen_Reverse:
7765         return TTI::CastContextHint::Reversed;
7766       case LoopVectorizationCostModel::CM_Unknown:
7767         llvm_unreachable("Instr did not go through cost modelling?");
7768       }
7769 
7770       llvm_unreachable("Unhandled case!");
7771     };
7772 
7773     unsigned Opcode = I->getOpcode();
7774     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7775     // For Trunc, the context is the only user, which must be a StoreInst.
7776     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7777       if (I->hasOneUse())
7778         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7779           CCH = ComputeCCH(Store);
7780     }
7781     // For Z/Sext, the context is the operand, which must be a LoadInst.
7782     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7783              Opcode == Instruction::FPExt) {
7784       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7785         CCH = ComputeCCH(Load);
7786     }
7787 
7788     // We optimize the truncation of induction variables having constant
7789     // integer steps. The cost of these truncations is the same as the scalar
7790     // operation.
7791     if (isOptimizableIVTruncate(I, VF)) {
7792       auto *Trunc = cast<TruncInst>(I);
7793       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7794                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7795     }
7796 
7797     // Detect reduction patterns
7798     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7799       return *RedCost;
7800 
7801     Type *SrcScalarTy = I->getOperand(0)->getType();
7802     Type *SrcVecTy =
7803         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7804     if (canTruncateToMinimalBitwidth(I, VF)) {
7805       // This cast is going to be shrunk. This may remove the cast or it might
7806       // turn it into slightly different cast. For example, if MinBW == 16,
7807       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7808       //
7809       // Calculate the modified src and dest types.
7810       Type *MinVecTy = VectorTy;
7811       if (Opcode == Instruction::Trunc) {
7812         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7813         VectorTy =
7814             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7815       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7816         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7817         VectorTy =
7818             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7819       }
7820     }
7821 
7822     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7823   }
7824   case Instruction::Call: {
7825     if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
7826       if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7827         return *RedCost;
7828     bool NeedToScalarize;
7829     CallInst *CI = cast<CallInst>(I);
7830     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7831     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7832       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7833       return std::min(CallCost, IntrinsicCost);
7834     }
7835     return CallCost;
7836   }
7837   case Instruction::ExtractValue:
7838     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7839   case Instruction::Alloca:
7840     // We cannot easily widen alloca to a scalable alloca, as
7841     // the result would need to be a vector of pointers.
7842     if (VF.isScalable())
7843       return InstructionCost::getInvalid();
7844     LLVM_FALLTHROUGH;
7845   default:
7846     // This opcode is unknown. Assume that it is the same as 'mul'.
7847     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7848   } // end of switch.
7849 }
7850 
7851 char LoopVectorize::ID = 0;
7852 
7853 static const char lv_name[] = "Loop Vectorization";
7854 
7855 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7856 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7857 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7858 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7859 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7860 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7861 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7862 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7863 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7864 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7865 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7866 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7867 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7868 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7869 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7870 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7871 
7872 namespace llvm {
7873 
7874 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7875 
7876 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7877                               bool VectorizeOnlyWhenForced) {
7878   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7879 }
7880 
7881 } // end namespace llvm
7882 
7883 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7884   // Check if the pointer operand of a load or store instruction is
7885   // consecutive.
7886   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7887     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7888   return false;
7889 }
7890 
7891 void LoopVectorizationCostModel::collectValuesToIgnore() {
7892   // Ignore ephemeral values.
7893   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7894 
7895   // Ignore type-promoting instructions we identified during reduction
7896   // detection.
7897   for (auto &Reduction : Legal->getReductionVars()) {
7898     RecurrenceDescriptor &RedDes = Reduction.second;
7899     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7900     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7901   }
7902   // Ignore type-casting instructions we identified during induction
7903   // detection.
7904   for (auto &Induction : Legal->getInductionVars()) {
7905     InductionDescriptor &IndDes = Induction.second;
7906     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7907     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7908   }
7909 }
7910 
7911 void LoopVectorizationCostModel::collectInLoopReductions() {
7912   for (auto &Reduction : Legal->getReductionVars()) {
7913     PHINode *Phi = Reduction.first;
7914     RecurrenceDescriptor &RdxDesc = Reduction.second;
7915 
7916     // We don't collect reductions that are type promoted (yet).
7917     if (RdxDesc.getRecurrenceType() != Phi->getType())
7918       continue;
7919 
7920     // If the target would prefer this reduction to happen "in-loop", then we
7921     // want to record it as such.
7922     unsigned Opcode = RdxDesc.getOpcode();
7923     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7924         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7925                                    TargetTransformInfo::ReductionFlags()))
7926       continue;
7927 
7928     // Check that we can correctly put the reductions into the loop, by
7929     // finding the chain of operations that leads from the phi to the loop
7930     // exit value.
7931     SmallVector<Instruction *, 4> ReductionOperations =
7932         RdxDesc.getReductionOpChain(Phi, TheLoop);
7933     bool InLoop = !ReductionOperations.empty();
7934     if (InLoop) {
7935       InLoopReductionChains[Phi] = ReductionOperations;
7936       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7937       Instruction *LastChain = Phi;
7938       for (auto *I : ReductionOperations) {
7939         InLoopReductionImmediateChains[I] = LastChain;
7940         LastChain = I;
7941       }
7942     }
7943     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7944                       << " reduction for phi: " << *Phi << "\n");
7945   }
7946 }
7947 
7948 // TODO: we could return a pair of values that specify the max VF and
7949 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7950 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7951 // doesn't have a cost model that can choose which plan to execute if
7952 // more than one is generated.
7953 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7954                                  LoopVectorizationCostModel &CM) {
7955   unsigned WidestType;
7956   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7957   return WidestVectorRegBits / WidestType;
7958 }
7959 
7960 VectorizationFactor
7961 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7962   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7963   ElementCount VF = UserVF;
7964   // Outer loop handling: They may require CFG and instruction level
7965   // transformations before even evaluating whether vectorization is profitable.
7966   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7967   // the vectorization pipeline.
7968   if (!OrigLoop->isInnermost()) {
7969     // If the user doesn't provide a vectorization factor, determine a
7970     // reasonable one.
7971     if (UserVF.isZero()) {
7972       VF = ElementCount::getFixed(determineVPlanVF(
7973           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7974               .getFixedSize(),
7975           CM));
7976       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7977 
7978       // Make sure we have a VF > 1 for stress testing.
7979       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7980         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7981                           << "overriding computed VF.\n");
7982         VF = ElementCount::getFixed(4);
7983       }
7984     }
7985     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7986     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7987            "VF needs to be a power of two");
7988     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7989                       << "VF " << VF << " to build VPlans.\n");
7990     buildVPlans(VF, VF);
7991 
7992     // For VPlan build stress testing, we bail out after VPlan construction.
7993     if (VPlanBuildStressTest)
7994       return VectorizationFactor::Disabled();
7995 
7996     return {VF, 0 /*Cost*/};
7997   }
7998 
7999   LLVM_DEBUG(
8000       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
8001                 "VPlan-native path.\n");
8002   return VectorizationFactor::Disabled();
8003 }
8004 
8005 Optional<VectorizationFactor>
8006 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
8007   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8008   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
8009   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
8010     return None;
8011 
8012   // Invalidate interleave groups if all blocks of loop will be predicated.
8013   if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
8014       !useMaskedInterleavedAccesses(*TTI)) {
8015     LLVM_DEBUG(
8016         dbgs()
8017         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
8018            "which requires masked-interleaved support.\n");
8019     if (CM.InterleaveInfo.invalidateGroups())
8020       // Invalidating interleave groups also requires invalidating all decisions
8021       // based on them, which includes widening decisions and uniform and scalar
8022       // values.
8023       CM.invalidateCostModelingDecisions();
8024   }
8025 
8026   ElementCount MaxUserVF =
8027       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
8028   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
8029   if (!UserVF.isZero() && UserVFIsLegal) {
8030     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
8031            "VF needs to be a power of two");
8032     // Collect the instructions (and their associated costs) that will be more
8033     // profitable to scalarize.
8034     if (CM.selectUserVectorizationFactor(UserVF)) {
8035       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
8036       CM.collectInLoopReductions();
8037       buildVPlansWithVPRecipes(UserVF, UserVF);
8038       LLVM_DEBUG(printPlans(dbgs()));
8039       return {{UserVF, 0}};
8040     } else
8041       reportVectorizationInfo("UserVF ignored because of invalid costs.",
8042                               "InvalidCost", ORE, OrigLoop);
8043   }
8044 
8045   // Populate the set of Vectorization Factor Candidates.
8046   ElementCountSet VFCandidates;
8047   for (auto VF = ElementCount::getFixed(1);
8048        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
8049     VFCandidates.insert(VF);
8050   for (auto VF = ElementCount::getScalable(1);
8051        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
8052     VFCandidates.insert(VF);
8053 
8054   for (const auto &VF : VFCandidates) {
8055     // Collect Uniform and Scalar instructions after vectorization with VF.
8056     CM.collectUniformsAndScalars(VF);
8057 
8058     // Collect the instructions (and their associated costs) that will be more
8059     // profitable to scalarize.
8060     if (VF.isVector())
8061       CM.collectInstsToScalarize(VF);
8062   }
8063 
8064   CM.collectInLoopReductions();
8065   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
8066   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
8067 
8068   LLVM_DEBUG(printPlans(dbgs()));
8069   if (!MaxFactors.hasVector())
8070     return VectorizationFactor::Disabled();
8071 
8072   // Select the optimal vectorization factor.
8073   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
8074 
8075   // Check if it is profitable to vectorize with runtime checks.
8076   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
8077   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
8078     bool PragmaThresholdReached =
8079         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
8080     bool ThresholdReached =
8081         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
8082     if ((ThresholdReached && !Hints.allowReordering()) ||
8083         PragmaThresholdReached) {
8084       ORE->emit([&]() {
8085         return OptimizationRemarkAnalysisAliasing(
8086                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
8087                    OrigLoop->getHeader())
8088                << "loop not vectorized: cannot prove it is safe to reorder "
8089                   "memory operations";
8090       });
8091       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
8092       Hints.emitRemarkWithHints();
8093       return VectorizationFactor::Disabled();
8094     }
8095   }
8096   return SelectedVF;
8097 }
8098 
8099 VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
8100   assert(count_if(VPlans,
8101                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
8102              1 &&
8103          "Best VF has not a single VPlan.");
8104 
8105   for (const VPlanPtr &Plan : VPlans) {
8106     if (Plan->hasVF(VF))
8107       return *Plan.get();
8108   }
8109   llvm_unreachable("No plan found!");
8110 }
8111 
8112 void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
8113                                            VPlan &BestVPlan,
8114                                            InnerLoopVectorizer &ILV,
8115                                            DominatorTree *DT) {
8116   LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
8117                     << '\n');
8118 
8119   // Perform the actual loop transformation.
8120 
8121   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
8122   VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
8123   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
8124   State.TripCount = ILV.getOrCreateTripCount(nullptr);
8125   State.CanonicalIV = ILV.Induction;
8126   ILV.collectPoisonGeneratingRecipes(State);
8127 
8128   ILV.printDebugTracesAtStart();
8129 
8130   //===------------------------------------------------===//
8131   //
8132   // Notice: any optimization or new instruction that go
8133   // into the code below should also be implemented in
8134   // the cost-model.
8135   //
8136   //===------------------------------------------------===//
8137 
8138   // 2. Copy and widen instructions from the old loop into the new loop.
8139   BestVPlan.execute(&State);
8140 
8141   // 3. Fix the vectorized code: take care of header phi's, live-outs,
8142   //    predication, updating analyses.
8143   ILV.fixVectorizedLoop(State);
8144 
8145   ILV.printDebugTracesAtEnd();
8146 }
8147 
8148 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
8149 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
8150   for (const auto &Plan : VPlans)
8151     if (PrintVPlansInDotFormat)
8152       Plan->printDOT(O);
8153     else
8154       Plan->print(O);
8155 }
8156 #endif
8157 
8158 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
8159     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
8160 
8161   // We create new control-flow for the vectorized loop, so the original exit
8162   // conditions will be dead after vectorization if it's only used by the
8163   // terminator
8164   SmallVector<BasicBlock*> ExitingBlocks;
8165   OrigLoop->getExitingBlocks(ExitingBlocks);
8166   for (auto *BB : ExitingBlocks) {
8167     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
8168     if (!Cmp || !Cmp->hasOneUse())
8169       continue;
8170 
8171     // TODO: we should introduce a getUniqueExitingBlocks on Loop
8172     if (!DeadInstructions.insert(Cmp).second)
8173       continue;
8174 
8175     // The operands of the icmp is often a dead trunc, used by IndUpdate.
8176     // TODO: can recurse through operands in general
8177     for (Value *Op : Cmp->operands()) {
8178       if (isa<TruncInst>(Op) && Op->hasOneUse())
8179           DeadInstructions.insert(cast<Instruction>(Op));
8180     }
8181   }
8182 
8183   // We create new "steps" for induction variable updates to which the original
8184   // induction variables map. An original update instruction will be dead if
8185   // all its users except the induction variable are dead.
8186   auto *Latch = OrigLoop->getLoopLatch();
8187   for (auto &Induction : Legal->getInductionVars()) {
8188     PHINode *Ind = Induction.first;
8189     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8190 
8191     // If the tail is to be folded by masking, the primary induction variable,
8192     // if exists, isn't dead: it will be used for masking. Don't kill it.
8193     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8194       continue;
8195 
8196     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8197           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8198         }))
8199       DeadInstructions.insert(IndUpdate);
8200 
8201     // We record as "Dead" also the type-casting instructions we had identified
8202     // during induction analysis. We don't need any handling for them in the
8203     // vectorized loop because we have proven that, under a proper runtime
8204     // test guarding the vectorized loop, the value of the phi, and the casted
8205     // value of the phi, are the same. The last instruction in this casting chain
8206     // will get its scalar/vector/widened def from the scalar/vector/widened def
8207     // of the respective phi node. Any other casts in the induction def-use chain
8208     // have no other uses outside the phi update chain, and will be ignored.
8209     InductionDescriptor &IndDes = Induction.second;
8210     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8211     DeadInstructions.insert(Casts.begin(), Casts.end());
8212   }
8213 }
8214 
8215 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
8216 
8217 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8218 
8219 Value *InnerLoopUnroller::getStepVector(Value *Val, Value *StartIdx,
8220                                         Value *Step,
8221                                         Instruction::BinaryOps BinOp) {
8222   // When unrolling and the VF is 1, we only need to add a simple scalar.
8223   Type *Ty = Val->getType();
8224   assert(!Ty->isVectorTy() && "Val must be a scalar");
8225 
8226   if (Ty->isFloatingPointTy()) {
8227     // Floating-point operations inherit FMF via the builder's flags.
8228     Value *MulOp = Builder.CreateFMul(StartIdx, Step);
8229     return Builder.CreateBinOp(BinOp, Val, MulOp);
8230   }
8231   return Builder.CreateAdd(Val, Builder.CreateMul(StartIdx, Step), "induction");
8232 }
8233 
8234 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8235   SmallVector<Metadata *, 4> MDs;
8236   // Reserve first location for self reference to the LoopID metadata node.
8237   MDs.push_back(nullptr);
8238   bool IsUnrollMetadata = false;
8239   MDNode *LoopID = L->getLoopID();
8240   if (LoopID) {
8241     // First find existing loop unrolling disable metadata.
8242     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8243       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8244       if (MD) {
8245         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8246         IsUnrollMetadata =
8247             S && S->getString().startswith("llvm.loop.unroll.disable");
8248       }
8249       MDs.push_back(LoopID->getOperand(i));
8250     }
8251   }
8252 
8253   if (!IsUnrollMetadata) {
8254     // Add runtime unroll disable metadata.
8255     LLVMContext &Context = L->getHeader()->getContext();
8256     SmallVector<Metadata *, 1> DisableOperands;
8257     DisableOperands.push_back(
8258         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8259     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8260     MDs.push_back(DisableNode);
8261     MDNode *NewLoopID = MDNode::get(Context, MDs);
8262     // Set operand 0 to refer to the loop id itself.
8263     NewLoopID->replaceOperandWith(0, NewLoopID);
8264     L->setLoopID(NewLoopID);
8265   }
8266 }
8267 
8268 //===--------------------------------------------------------------------===//
8269 // EpilogueVectorizerMainLoop
8270 //===--------------------------------------------------------------------===//
8271 
8272 /// This function is partially responsible for generating the control flow
8273 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8274 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8275   MDNode *OrigLoopID = OrigLoop->getLoopID();
8276   Loop *Lp = createVectorLoopSkeleton("");
8277 
8278   // Generate the code to check the minimum iteration count of the vector
8279   // epilogue (see below).
8280   EPI.EpilogueIterationCountCheck =
8281       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8282   EPI.EpilogueIterationCountCheck->setName("iter.check");
8283 
8284   // Generate the code to check any assumptions that we've made for SCEV
8285   // expressions.
8286   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8287 
8288   // Generate the code that checks at runtime if arrays overlap. We put the
8289   // checks into a separate block to make the more common case of few elements
8290   // faster.
8291   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8292 
8293   // Generate the iteration count check for the main loop, *after* the check
8294   // for the epilogue loop, so that the path-length is shorter for the case
8295   // that goes directly through the vector epilogue. The longer-path length for
8296   // the main loop is compensated for, by the gain from vectorizing the larger
8297   // trip count. Note: the branch will get updated later on when we vectorize
8298   // the epilogue.
8299   EPI.MainLoopIterationCountCheck =
8300       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8301 
8302   // Generate the induction variable.
8303   OldInduction = Legal->getPrimaryInduction();
8304   Type *IdxTy = Legal->getWidestInductionType();
8305   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8306 
8307   IRBuilder<> B(&*Lp->getLoopPreheader()->getFirstInsertionPt());
8308   Value *Step = getRuntimeVF(B, IdxTy, VF * UF);
8309   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8310   EPI.VectorTripCount = CountRoundDown;
8311   Induction =
8312       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8313                               getDebugLocFromInstOrOperands(OldInduction));
8314 
8315   // Skip induction resume value creation here because they will be created in
8316   // the second pass. If we created them here, they wouldn't be used anyway,
8317   // because the vplan in the second pass still contains the inductions from the
8318   // original loop.
8319 
8320   return completeLoopSkeleton(Lp, OrigLoopID);
8321 }
8322 
8323 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8324   LLVM_DEBUG({
8325     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8326            << "Main Loop VF:" << EPI.MainLoopVF
8327            << ", Main Loop UF:" << EPI.MainLoopUF
8328            << ", Epilogue Loop VF:" << EPI.EpilogueVF
8329            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8330   });
8331 }
8332 
8333 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8334   DEBUG_WITH_TYPE(VerboseDebug, {
8335     dbgs() << "intermediate fn:\n"
8336            << *OrigLoop->getHeader()->getParent() << "\n";
8337   });
8338 }
8339 
8340 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8341     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8342   assert(L && "Expected valid Loop.");
8343   assert(Bypass && "Expected valid bypass basic block.");
8344   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
8345   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8346   Value *Count = getOrCreateTripCount(L);
8347   // Reuse existing vector loop preheader for TC checks.
8348   // Note that new preheader block is generated for vector loop.
8349   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8350   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8351 
8352   // Generate code to check if the loop's trip count is less than VF * UF of the
8353   // main vector loop.
8354   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
8355       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8356 
8357   Value *CheckMinIters = Builder.CreateICmp(
8358       P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
8359       "min.iters.check");
8360 
8361   if (!ForEpilogue)
8362     TCCheckBlock->setName("vector.main.loop.iter.check");
8363 
8364   // Create new preheader for vector loop.
8365   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8366                                    DT, LI, nullptr, "vector.ph");
8367 
8368   if (ForEpilogue) {
8369     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8370                                  DT->getNode(Bypass)->getIDom()) &&
8371            "TC check is expected to dominate Bypass");
8372 
8373     // Update dominator for Bypass & LoopExit.
8374     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8375     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8376       // For loops with multiple exits, there's no edge from the middle block
8377       // to exit blocks (as the epilogue must run) and thus no need to update
8378       // the immediate dominator of the exit blocks.
8379       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8380 
8381     LoopBypassBlocks.push_back(TCCheckBlock);
8382 
8383     // Save the trip count so we don't have to regenerate it in the
8384     // vec.epilog.iter.check. This is safe to do because the trip count
8385     // generated here dominates the vector epilog iter check.
8386     EPI.TripCount = Count;
8387   }
8388 
8389   ReplaceInstWithInst(
8390       TCCheckBlock->getTerminator(),
8391       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8392 
8393   return TCCheckBlock;
8394 }
8395 
8396 //===--------------------------------------------------------------------===//
8397 // EpilogueVectorizerEpilogueLoop
8398 //===--------------------------------------------------------------------===//
8399 
8400 /// This function is partially responsible for generating the control flow
8401 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8402 BasicBlock *
8403 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8404   MDNode *OrigLoopID = OrigLoop->getLoopID();
8405   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8406 
8407   // Now, compare the remaining count and if there aren't enough iterations to
8408   // execute the vectorized epilogue skip to the scalar part.
8409   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8410   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8411   LoopVectorPreHeader =
8412       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8413                  LI, nullptr, "vec.epilog.ph");
8414   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8415                                           VecEpilogueIterationCountCheck);
8416 
8417   // Adjust the control flow taking the state info from the main loop
8418   // vectorization into account.
8419   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8420          "expected this to be saved from the previous pass.");
8421   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8422       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8423 
8424   DT->changeImmediateDominator(LoopVectorPreHeader,
8425                                EPI.MainLoopIterationCountCheck);
8426 
8427   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8428       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8429 
8430   if (EPI.SCEVSafetyCheck)
8431     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8432         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8433   if (EPI.MemSafetyCheck)
8434     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8435         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8436 
8437   DT->changeImmediateDominator(
8438       VecEpilogueIterationCountCheck,
8439       VecEpilogueIterationCountCheck->getSinglePredecessor());
8440 
8441   DT->changeImmediateDominator(LoopScalarPreHeader,
8442                                EPI.EpilogueIterationCountCheck);
8443   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
8444     // If there is an epilogue which must run, there's no edge from the
8445     // middle block to exit blocks  and thus no need to update the immediate
8446     // dominator of the exit blocks.
8447     DT->changeImmediateDominator(LoopExitBlock,
8448                                  EPI.EpilogueIterationCountCheck);
8449 
8450   // Keep track of bypass blocks, as they feed start values to the induction
8451   // phis in the scalar loop preheader.
8452   if (EPI.SCEVSafetyCheck)
8453     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8454   if (EPI.MemSafetyCheck)
8455     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8456   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8457 
8458   // Generate a resume induction for the vector epilogue and put it in the
8459   // vector epilogue preheader
8460   Type *IdxTy = Legal->getWidestInductionType();
8461   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8462                                          LoopVectorPreHeader->getFirstNonPHI());
8463   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8464   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8465                            EPI.MainLoopIterationCountCheck);
8466 
8467   // Generate the induction variable.
8468   OldInduction = Legal->getPrimaryInduction();
8469   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8470   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8471   Value *StartIdx = EPResumeVal;
8472   Induction =
8473       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8474                               getDebugLocFromInstOrOperands(OldInduction));
8475 
8476   // Generate induction resume values. These variables save the new starting
8477   // indexes for the scalar loop. They are used to test if there are any tail
8478   // iterations left once the vector loop has completed.
8479   // Note that when the vectorized epilogue is skipped due to iteration count
8480   // check, then the resume value for the induction variable comes from
8481   // the trip count of the main vector loop, hence passing the AdditionalBypass
8482   // argument.
8483   createInductionResumeValues(Lp, CountRoundDown,
8484                               {VecEpilogueIterationCountCheck,
8485                                EPI.VectorTripCount} /* AdditionalBypass */);
8486 
8487   AddRuntimeUnrollDisableMetaData(Lp);
8488   return completeLoopSkeleton(Lp, OrigLoopID);
8489 }
8490 
8491 BasicBlock *
8492 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8493     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8494 
8495   assert(EPI.TripCount &&
8496          "Expected trip count to have been safed in the first pass.");
8497   assert(
8498       (!isa<Instruction>(EPI.TripCount) ||
8499        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8500       "saved trip count does not dominate insertion point.");
8501   Value *TC = EPI.TripCount;
8502   IRBuilder<> Builder(Insert->getTerminator());
8503   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8504 
8505   // Generate code to check if the loop's trip count is less than VF * UF of the
8506   // vector epilogue loop.
8507   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
8508       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8509 
8510   Value *CheckMinIters =
8511       Builder.CreateICmp(P, Count,
8512                          createStepForVF(Builder, Count->getType(),
8513                                          EPI.EpilogueVF, EPI.EpilogueUF),
8514                          "min.epilog.iters.check");
8515 
8516   ReplaceInstWithInst(
8517       Insert->getTerminator(),
8518       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8519 
8520   LoopBypassBlocks.push_back(Insert);
8521   return Insert;
8522 }
8523 
8524 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8525   LLVM_DEBUG({
8526     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8527            << "Epilogue Loop VF:" << EPI.EpilogueVF
8528            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8529   });
8530 }
8531 
8532 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8533   DEBUG_WITH_TYPE(VerboseDebug, {
8534     dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
8535   });
8536 }
8537 
8538 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8539     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8540   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8541   bool PredicateAtRangeStart = Predicate(Range.Start);
8542 
8543   for (ElementCount TmpVF = Range.Start * 2;
8544        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8545     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8546       Range.End = TmpVF;
8547       break;
8548     }
8549 
8550   return PredicateAtRangeStart;
8551 }
8552 
8553 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8554 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8555 /// of VF's starting at a given VF and extending it as much as possible. Each
8556 /// vectorization decision can potentially shorten this sub-range during
8557 /// buildVPlan().
8558 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8559                                            ElementCount MaxVF) {
8560   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8561   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8562     VFRange SubRange = {VF, MaxVFPlusOne};
8563     VPlans.push_back(buildVPlan(SubRange));
8564     VF = SubRange.End;
8565   }
8566 }
8567 
8568 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8569                                          VPlanPtr &Plan) {
8570   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8571 
8572   // Look for cached value.
8573   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8574   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8575   if (ECEntryIt != EdgeMaskCache.end())
8576     return ECEntryIt->second;
8577 
8578   VPValue *SrcMask = createBlockInMask(Src, Plan);
8579 
8580   // The terminator has to be a branch inst!
8581   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8582   assert(BI && "Unexpected terminator found");
8583 
8584   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8585     return EdgeMaskCache[Edge] = SrcMask;
8586 
8587   // If source is an exiting block, we know the exit edge is dynamically dead
8588   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8589   // adding uses of an otherwise potentially dead instruction.
8590   if (OrigLoop->isLoopExiting(Src))
8591     return EdgeMaskCache[Edge] = SrcMask;
8592 
8593   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8594   assert(EdgeMask && "No Edge Mask found for condition");
8595 
8596   if (BI->getSuccessor(0) != Dst)
8597     EdgeMask = Builder.createNot(EdgeMask);
8598 
8599   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8600     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8601     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8602     // The select version does not introduce new UB if SrcMask is false and
8603     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8604     VPValue *False = Plan->getOrAddVPValue(
8605         ConstantInt::getFalse(BI->getCondition()->getType()));
8606     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8607   }
8608 
8609   return EdgeMaskCache[Edge] = EdgeMask;
8610 }
8611 
8612 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8613   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8614 
8615   // Look for cached value.
8616   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8617   if (BCEntryIt != BlockMaskCache.end())
8618     return BCEntryIt->second;
8619 
8620   // All-one mask is modelled as no-mask following the convention for masked
8621   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8622   VPValue *BlockMask = nullptr;
8623 
8624   if (OrigLoop->getHeader() == BB) {
8625     if (!CM.blockNeedsPredicationForAnyReason(BB))
8626       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8627 
8628     // Create the block in mask as the first non-phi instruction in the block.
8629     VPBuilder::InsertPointGuard Guard(Builder);
8630     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8631     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8632 
8633     // Introduce the early-exit compare IV <= BTC to form header block mask.
8634     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8635     // Start by constructing the desired canonical IV.
8636     VPValue *IV = nullptr;
8637     if (Legal->getPrimaryInduction())
8638       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8639     else {
8640       auto *IVRecipe = new VPWidenCanonicalIVRecipe();
8641       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8642       IV = IVRecipe;
8643     }
8644     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8645     bool TailFolded = !CM.isScalarEpilogueAllowed();
8646 
8647     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8648       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8649       // as a second argument, we only pass the IV here and extract the
8650       // tripcount from the transform state where codegen of the VP instructions
8651       // happen.
8652       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8653     } else {
8654       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8655     }
8656     return BlockMaskCache[BB] = BlockMask;
8657   }
8658 
8659   // This is the block mask. We OR all incoming edges.
8660   for (auto *Predecessor : predecessors(BB)) {
8661     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8662     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8663       return BlockMaskCache[BB] = EdgeMask;
8664 
8665     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8666       BlockMask = EdgeMask;
8667       continue;
8668     }
8669 
8670     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8671   }
8672 
8673   return BlockMaskCache[BB] = BlockMask;
8674 }
8675 
8676 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8677                                                 ArrayRef<VPValue *> Operands,
8678                                                 VFRange &Range,
8679                                                 VPlanPtr &Plan) {
8680   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8681          "Must be called with either a load or store");
8682 
8683   auto willWiden = [&](ElementCount VF) -> bool {
8684     if (VF.isScalar())
8685       return false;
8686     LoopVectorizationCostModel::InstWidening Decision =
8687         CM.getWideningDecision(I, VF);
8688     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8689            "CM decision should be taken at this point.");
8690     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8691       return true;
8692     if (CM.isScalarAfterVectorization(I, VF) ||
8693         CM.isProfitableToScalarize(I, VF))
8694       return false;
8695     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8696   };
8697 
8698   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8699     return nullptr;
8700 
8701   VPValue *Mask = nullptr;
8702   if (Legal->isMaskRequired(I))
8703     Mask = createBlockInMask(I->getParent(), Plan);
8704 
8705   // Determine if the pointer operand of the access is either consecutive or
8706   // reverse consecutive.
8707   LoopVectorizationCostModel::InstWidening Decision =
8708       CM.getWideningDecision(I, Range.Start);
8709   bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
8710   bool Consecutive =
8711       Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
8712 
8713   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8714     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
8715                                               Consecutive, Reverse);
8716 
8717   StoreInst *Store = cast<StoreInst>(I);
8718   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8719                                             Mask, Consecutive, Reverse);
8720 }
8721 
8722 VPWidenIntOrFpInductionRecipe *
8723 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8724                                            ArrayRef<VPValue *> Operands) const {
8725   // Check if this is an integer or fp induction. If so, build the recipe that
8726   // produces its scalar and vector values.
8727   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8728   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8729       II.getKind() == InductionDescriptor::IK_FpInduction) {
8730     assert(II.getStartValue() ==
8731            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8732     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8733     return new VPWidenIntOrFpInductionRecipe(
8734         Phi, Operands[0], Casts.empty() ? nullptr : Casts.front());
8735   }
8736 
8737   return nullptr;
8738 }
8739 
8740 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8741     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8742     VPlan &Plan) const {
8743   // Optimize the special case where the source is a constant integer
8744   // induction variable. Notice that we can only optimize the 'trunc' case
8745   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8746   // (c) other casts depend on pointer size.
8747 
8748   // Determine whether \p K is a truncation based on an induction variable that
8749   // can be optimized.
8750   auto isOptimizableIVTruncate =
8751       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8752     return [=](ElementCount VF) -> bool {
8753       return CM.isOptimizableIVTruncate(K, VF);
8754     };
8755   };
8756 
8757   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8758           isOptimizableIVTruncate(I), Range)) {
8759 
8760     InductionDescriptor II =
8761         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8762     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8763     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8764                                              Start, nullptr, I);
8765   }
8766   return nullptr;
8767 }
8768 
8769 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8770                                                 ArrayRef<VPValue *> Operands,
8771                                                 VPlanPtr &Plan) {
8772   // If all incoming values are equal, the incoming VPValue can be used directly
8773   // instead of creating a new VPBlendRecipe.
8774   VPValue *FirstIncoming = Operands[0];
8775   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8776         return FirstIncoming == Inc;
8777       })) {
8778     return Operands[0];
8779   }
8780 
8781   // We know that all PHIs in non-header blocks are converted into selects, so
8782   // we don't have to worry about the insertion order and we can just use the
8783   // builder. At this point we generate the predication tree. There may be
8784   // duplications since this is a simple recursive scan, but future
8785   // optimizations will clean it up.
8786   SmallVector<VPValue *, 2> OperandsWithMask;
8787   unsigned NumIncoming = Phi->getNumIncomingValues();
8788 
8789   for (unsigned In = 0; In < NumIncoming; In++) {
8790     VPValue *EdgeMask =
8791       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8792     assert((EdgeMask || NumIncoming == 1) &&
8793            "Multiple predecessors with one having a full mask");
8794     OperandsWithMask.push_back(Operands[In]);
8795     if (EdgeMask)
8796       OperandsWithMask.push_back(EdgeMask);
8797   }
8798   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8799 }
8800 
8801 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8802                                                    ArrayRef<VPValue *> Operands,
8803                                                    VFRange &Range) const {
8804 
8805   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8806       [this, CI](ElementCount VF) { return CM.isScalarWithPredication(CI); },
8807       Range);
8808 
8809   if (IsPredicated)
8810     return nullptr;
8811 
8812   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8813   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8814              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8815              ID == Intrinsic::pseudoprobe ||
8816              ID == Intrinsic::experimental_noalias_scope_decl))
8817     return nullptr;
8818 
8819   auto willWiden = [&](ElementCount VF) -> bool {
8820     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8821     // The following case may be scalarized depending on the VF.
8822     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8823     // version of the instruction.
8824     // Is it beneficial to perform intrinsic call compared to lib call?
8825     bool NeedToScalarize = false;
8826     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8827     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8828     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8829     return UseVectorIntrinsic || !NeedToScalarize;
8830   };
8831 
8832   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8833     return nullptr;
8834 
8835   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8836   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8837 }
8838 
8839 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8840   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8841          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8842   // Instruction should be widened, unless it is scalar after vectorization,
8843   // scalarization is profitable or it is predicated.
8844   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8845     return CM.isScalarAfterVectorization(I, VF) ||
8846            CM.isProfitableToScalarize(I, VF) || CM.isScalarWithPredication(I);
8847   };
8848   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8849                                                              Range);
8850 }
8851 
8852 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8853                                            ArrayRef<VPValue *> Operands) const {
8854   auto IsVectorizableOpcode = [](unsigned Opcode) {
8855     switch (Opcode) {
8856     case Instruction::Add:
8857     case Instruction::And:
8858     case Instruction::AShr:
8859     case Instruction::BitCast:
8860     case Instruction::FAdd:
8861     case Instruction::FCmp:
8862     case Instruction::FDiv:
8863     case Instruction::FMul:
8864     case Instruction::FNeg:
8865     case Instruction::FPExt:
8866     case Instruction::FPToSI:
8867     case Instruction::FPToUI:
8868     case Instruction::FPTrunc:
8869     case Instruction::FRem:
8870     case Instruction::FSub:
8871     case Instruction::ICmp:
8872     case Instruction::IntToPtr:
8873     case Instruction::LShr:
8874     case Instruction::Mul:
8875     case Instruction::Or:
8876     case Instruction::PtrToInt:
8877     case Instruction::SDiv:
8878     case Instruction::Select:
8879     case Instruction::SExt:
8880     case Instruction::Shl:
8881     case Instruction::SIToFP:
8882     case Instruction::SRem:
8883     case Instruction::Sub:
8884     case Instruction::Trunc:
8885     case Instruction::UDiv:
8886     case Instruction::UIToFP:
8887     case Instruction::URem:
8888     case Instruction::Xor:
8889     case Instruction::ZExt:
8890       return true;
8891     }
8892     return false;
8893   };
8894 
8895   if (!IsVectorizableOpcode(I->getOpcode()))
8896     return nullptr;
8897 
8898   // Success: widen this instruction.
8899   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8900 }
8901 
8902 void VPRecipeBuilder::fixHeaderPhis() {
8903   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8904   for (VPWidenPHIRecipe *R : PhisToFix) {
8905     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8906     VPRecipeBase *IncR =
8907         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8908     R->addOperand(IncR->getVPSingleValue());
8909   }
8910 }
8911 
8912 VPBasicBlock *VPRecipeBuilder::handleReplication(
8913     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8914     VPlanPtr &Plan) {
8915   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8916       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8917       Range);
8918 
8919   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8920       [&](ElementCount VF) { return CM.isPredicatedInst(I, IsUniform); },
8921       Range);
8922 
8923   // Even if the instruction is not marked as uniform, there are certain
8924   // intrinsic calls that can be effectively treated as such, so we check for
8925   // them here. Conservatively, we only do this for scalable vectors, since
8926   // for fixed-width VFs we can always fall back on full scalarization.
8927   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8928     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8929     case Intrinsic::assume:
8930     case Intrinsic::lifetime_start:
8931     case Intrinsic::lifetime_end:
8932       // For scalable vectors if one of the operands is variant then we still
8933       // want to mark as uniform, which will generate one instruction for just
8934       // the first lane of the vector. We can't scalarize the call in the same
8935       // way as for fixed-width vectors because we don't know how many lanes
8936       // there are.
8937       //
8938       // The reasons for doing it this way for scalable vectors are:
8939       //   1. For the assume intrinsic generating the instruction for the first
8940       //      lane is still be better than not generating any at all. For
8941       //      example, the input may be a splat across all lanes.
8942       //   2. For the lifetime start/end intrinsics the pointer operand only
8943       //      does anything useful when the input comes from a stack object,
8944       //      which suggests it should always be uniform. For non-stack objects
8945       //      the effect is to poison the object, which still allows us to
8946       //      remove the call.
8947       IsUniform = true;
8948       break;
8949     default:
8950       break;
8951     }
8952   }
8953 
8954   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8955                                        IsUniform, IsPredicated);
8956   setRecipe(I, Recipe);
8957   Plan->addVPValue(I, Recipe);
8958 
8959   // Find if I uses a predicated instruction. If so, it will use its scalar
8960   // value. Avoid hoisting the insert-element which packs the scalar value into
8961   // a vector value, as that happens iff all users use the vector value.
8962   for (VPValue *Op : Recipe->operands()) {
8963     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8964     if (!PredR)
8965       continue;
8966     auto *RepR =
8967         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8968     assert(RepR->isPredicated() &&
8969            "expected Replicate recipe to be predicated");
8970     RepR->setAlsoPack(false);
8971   }
8972 
8973   // Finalize the recipe for Instr, first if it is not predicated.
8974   if (!IsPredicated) {
8975     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8976     VPBB->appendRecipe(Recipe);
8977     return VPBB;
8978   }
8979   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8980   assert(VPBB->getSuccessors().empty() &&
8981          "VPBB has successors when handling predicated replication.");
8982   // Record predicated instructions for above packing optimizations.
8983   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8984   VPBlockUtils::insertBlockAfter(Region, VPBB);
8985   auto *RegSucc = new VPBasicBlock();
8986   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8987   return RegSucc;
8988 }
8989 
8990 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8991                                                       VPRecipeBase *PredRecipe,
8992                                                       VPlanPtr &Plan) {
8993   // Instructions marked for predication are replicated and placed under an
8994   // if-then construct to prevent side-effects.
8995 
8996   // Generate recipes to compute the block mask for this region.
8997   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8998 
8999   // Build the triangular if-then region.
9000   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
9001   assert(Instr->getParent() && "Predicated instruction not in any basic block");
9002   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
9003   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
9004   auto *PHIRecipe = Instr->getType()->isVoidTy()
9005                         ? nullptr
9006                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
9007   if (PHIRecipe) {
9008     Plan->removeVPValueFor(Instr);
9009     Plan->addVPValue(Instr, PHIRecipe);
9010   }
9011   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
9012   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
9013   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
9014 
9015   // Note: first set Entry as region entry and then connect successors starting
9016   // from it in order, to propagate the "parent" of each VPBasicBlock.
9017   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
9018   VPBlockUtils::connectBlocks(Pred, Exit);
9019 
9020   return Region;
9021 }
9022 
9023 VPRecipeOrVPValueTy
9024 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
9025                                         ArrayRef<VPValue *> Operands,
9026                                         VFRange &Range, VPlanPtr &Plan) {
9027   // First, check for specific widening recipes that deal with calls, memory
9028   // operations, inductions and Phi nodes.
9029   if (auto *CI = dyn_cast<CallInst>(Instr))
9030     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
9031 
9032   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
9033     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
9034 
9035   VPRecipeBase *Recipe;
9036   if (auto Phi = dyn_cast<PHINode>(Instr)) {
9037     if (Phi->getParent() != OrigLoop->getHeader())
9038       return tryToBlend(Phi, Operands, Plan);
9039     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
9040       return toVPRecipeResult(Recipe);
9041 
9042     VPWidenPHIRecipe *PhiRecipe = nullptr;
9043     if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
9044       VPValue *StartV = Operands[0];
9045       if (Legal->isReductionVariable(Phi)) {
9046         RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9047         assert(RdxDesc.getRecurrenceStartValue() ==
9048                Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
9049         PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
9050                                              CM.isInLoopReduction(Phi),
9051                                              CM.useOrderedReductions(RdxDesc));
9052       } else {
9053         PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
9054       }
9055 
9056       // Record the incoming value from the backedge, so we can add the incoming
9057       // value from the backedge after all recipes have been created.
9058       recordRecipeOf(cast<Instruction>(
9059           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
9060       PhisToFix.push_back(PhiRecipe);
9061     } else {
9062       // TODO: record start and backedge value for remaining pointer induction
9063       // phis.
9064       assert(Phi->getType()->isPointerTy() &&
9065              "only pointer phis should be handled here");
9066       PhiRecipe = new VPWidenPHIRecipe(Phi);
9067     }
9068 
9069     return toVPRecipeResult(PhiRecipe);
9070   }
9071 
9072   if (isa<TruncInst>(Instr) &&
9073       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
9074                                                Range, *Plan)))
9075     return toVPRecipeResult(Recipe);
9076 
9077   if (!shouldWiden(Instr, Range))
9078     return nullptr;
9079 
9080   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
9081     return toVPRecipeResult(new VPWidenGEPRecipe(
9082         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
9083 
9084   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
9085     bool InvariantCond =
9086         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
9087     return toVPRecipeResult(new VPWidenSelectRecipe(
9088         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
9089   }
9090 
9091   return toVPRecipeResult(tryToWiden(Instr, Operands));
9092 }
9093 
9094 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
9095                                                         ElementCount MaxVF) {
9096   assert(OrigLoop->isInnermost() && "Inner loop expected.");
9097 
9098   // Collect instructions from the original loop that will become trivially dead
9099   // in the vectorized loop. We don't need to vectorize these instructions. For
9100   // example, original induction update instructions can become dead because we
9101   // separately emit induction "steps" when generating code for the new loop.
9102   // Similarly, we create a new latch condition when setting up the structure
9103   // of the new loop, so the old one can become dead.
9104   SmallPtrSet<Instruction *, 4> DeadInstructions;
9105   collectTriviallyDeadInstructions(DeadInstructions);
9106 
9107   // Add assume instructions we need to drop to DeadInstructions, to prevent
9108   // them from being added to the VPlan.
9109   // TODO: We only need to drop assumes in blocks that get flattend. If the
9110   // control flow is preserved, we should keep them.
9111   auto &ConditionalAssumes = Legal->getConditionalAssumes();
9112   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
9113 
9114   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
9115   // Dead instructions do not need sinking. Remove them from SinkAfter.
9116   for (Instruction *I : DeadInstructions)
9117     SinkAfter.erase(I);
9118 
9119   // Cannot sink instructions after dead instructions (there won't be any
9120   // recipes for them). Instead, find the first non-dead previous instruction.
9121   for (auto &P : Legal->getSinkAfter()) {
9122     Instruction *SinkTarget = P.second;
9123     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
9124     (void)FirstInst;
9125     while (DeadInstructions.contains(SinkTarget)) {
9126       assert(
9127           SinkTarget != FirstInst &&
9128           "Must find a live instruction (at least the one feeding the "
9129           "first-order recurrence PHI) before reaching beginning of the block");
9130       SinkTarget = SinkTarget->getPrevNode();
9131       assert(SinkTarget != P.first &&
9132              "sink source equals target, no sinking required");
9133     }
9134     P.second = SinkTarget;
9135   }
9136 
9137   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
9138   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
9139     VFRange SubRange = {VF, MaxVFPlusOne};
9140     VPlans.push_back(
9141         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
9142     VF = SubRange.End;
9143   }
9144 }
9145 
9146 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
9147     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
9148     const MapVector<Instruction *, Instruction *> &SinkAfter) {
9149 
9150   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
9151 
9152   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
9153 
9154   // ---------------------------------------------------------------------------
9155   // Pre-construction: record ingredients whose recipes we'll need to further
9156   // process after constructing the initial VPlan.
9157   // ---------------------------------------------------------------------------
9158 
9159   // Mark instructions we'll need to sink later and their targets as
9160   // ingredients whose recipe we'll need to record.
9161   for (auto &Entry : SinkAfter) {
9162     RecipeBuilder.recordRecipeOf(Entry.first);
9163     RecipeBuilder.recordRecipeOf(Entry.second);
9164   }
9165   for (auto &Reduction : CM.getInLoopReductionChains()) {
9166     PHINode *Phi = Reduction.first;
9167     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
9168     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9169 
9170     RecipeBuilder.recordRecipeOf(Phi);
9171     for (auto &R : ReductionOperations) {
9172       RecipeBuilder.recordRecipeOf(R);
9173       // For min/max reducitons, where we have a pair of icmp/select, we also
9174       // need to record the ICmp recipe, so it can be removed later.
9175       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9176              "Only min/max recurrences allowed for inloop reductions");
9177       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
9178         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
9179     }
9180   }
9181 
9182   // For each interleave group which is relevant for this (possibly trimmed)
9183   // Range, add it to the set of groups to be later applied to the VPlan and add
9184   // placeholders for its members' Recipes which we'll be replacing with a
9185   // single VPInterleaveRecipe.
9186   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
9187     auto applyIG = [IG, this](ElementCount VF) -> bool {
9188       return (VF.isVector() && // Query is illegal for VF == 1
9189               CM.getWideningDecision(IG->getInsertPos(), VF) ==
9190                   LoopVectorizationCostModel::CM_Interleave);
9191     };
9192     if (!getDecisionAndClampRange(applyIG, Range))
9193       continue;
9194     InterleaveGroups.insert(IG);
9195     for (unsigned i = 0; i < IG->getFactor(); i++)
9196       if (Instruction *Member = IG->getMember(i))
9197         RecipeBuilder.recordRecipeOf(Member);
9198   };
9199 
9200   // ---------------------------------------------------------------------------
9201   // Build initial VPlan: Scan the body of the loop in a topological order to
9202   // visit each basic block after having visited its predecessor basic blocks.
9203   // ---------------------------------------------------------------------------
9204 
9205   auto Plan = std::make_unique<VPlan>();
9206 
9207   // Scan the body of the loop in a topological order to visit each basic block
9208   // after having visited its predecessor basic blocks.
9209   LoopBlocksDFS DFS(OrigLoop);
9210   DFS.perform(LI);
9211 
9212   VPBasicBlock *VPBB = nullptr;
9213   VPBasicBlock *HeaderVPBB = nullptr;
9214   SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
9215   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
9216     // Relevant instructions from basic block BB will be grouped into VPRecipe
9217     // ingredients and fill a new VPBasicBlock.
9218     unsigned VPBBsForBB = 0;
9219     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
9220     if (VPBB)
9221       VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
9222     else {
9223       auto *TopRegion = new VPRegionBlock("vector loop");
9224       TopRegion->setEntry(FirstVPBBForBB);
9225       Plan->setEntry(TopRegion);
9226       HeaderVPBB = FirstVPBBForBB;
9227     }
9228     VPBB = FirstVPBBForBB;
9229     Builder.setInsertPoint(VPBB);
9230 
9231     // Introduce each ingredient into VPlan.
9232     // TODO: Model and preserve debug instrinsics in VPlan.
9233     for (Instruction &I : BB->instructionsWithoutDebug()) {
9234       Instruction *Instr = &I;
9235 
9236       // First filter out irrelevant instructions, to ensure no recipes are
9237       // built for them.
9238       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
9239         continue;
9240 
9241       SmallVector<VPValue *, 4> Operands;
9242       auto *Phi = dyn_cast<PHINode>(Instr);
9243       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
9244         Operands.push_back(Plan->getOrAddVPValue(
9245             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
9246       } else {
9247         auto OpRange = Plan->mapToVPValues(Instr->operands());
9248         Operands = {OpRange.begin(), OpRange.end()};
9249       }
9250       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
9251               Instr, Operands, Range, Plan)) {
9252         // If Instr can be simplified to an existing VPValue, use it.
9253         if (RecipeOrValue.is<VPValue *>()) {
9254           auto *VPV = RecipeOrValue.get<VPValue *>();
9255           Plan->addVPValue(Instr, VPV);
9256           // If the re-used value is a recipe, register the recipe for the
9257           // instruction, in case the recipe for Instr needs to be recorded.
9258           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
9259             RecipeBuilder.setRecipe(Instr, R);
9260           continue;
9261         }
9262         // Otherwise, add the new recipe.
9263         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
9264         for (auto *Def : Recipe->definedValues()) {
9265           auto *UV = Def->getUnderlyingValue();
9266           Plan->addVPValue(UV, Def);
9267         }
9268 
9269         if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
9270             HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
9271           // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
9272           // of the header block. That can happen for truncates of induction
9273           // variables. Those recipes are moved to the phi section of the header
9274           // block after applying SinkAfter, which relies on the original
9275           // position of the trunc.
9276           assert(isa<TruncInst>(Instr));
9277           InductionsToMove.push_back(
9278               cast<VPWidenIntOrFpInductionRecipe>(Recipe));
9279         }
9280         RecipeBuilder.setRecipe(Instr, Recipe);
9281         VPBB->appendRecipe(Recipe);
9282         continue;
9283       }
9284 
9285       // Otherwise, if all widening options failed, Instruction is to be
9286       // replicated. This may create a successor for VPBB.
9287       VPBasicBlock *NextVPBB =
9288           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
9289       if (NextVPBB != VPBB) {
9290         VPBB = NextVPBB;
9291         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
9292                                     : "");
9293       }
9294     }
9295   }
9296 
9297   assert(isa<VPRegionBlock>(Plan->getEntry()) &&
9298          !Plan->getEntry()->getEntryBasicBlock()->empty() &&
9299          "entry block must be set to a VPRegionBlock having a non-empty entry "
9300          "VPBasicBlock");
9301   cast<VPRegionBlock>(Plan->getEntry())->setExit(VPBB);
9302   RecipeBuilder.fixHeaderPhis();
9303 
9304   // ---------------------------------------------------------------------------
9305   // Transform initial VPlan: Apply previously taken decisions, in order, to
9306   // bring the VPlan to its final state.
9307   // ---------------------------------------------------------------------------
9308 
9309   // Apply Sink-After legal constraints.
9310   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
9311     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
9312     if (Region && Region->isReplicator()) {
9313       assert(Region->getNumSuccessors() == 1 &&
9314              Region->getNumPredecessors() == 1 && "Expected SESE region!");
9315       assert(R->getParent()->size() == 1 &&
9316              "A recipe in an original replicator region must be the only "
9317              "recipe in its block");
9318       return Region;
9319     }
9320     return nullptr;
9321   };
9322   for (auto &Entry : SinkAfter) {
9323     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9324     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9325 
9326     auto *TargetRegion = GetReplicateRegion(Target);
9327     auto *SinkRegion = GetReplicateRegion(Sink);
9328     if (!SinkRegion) {
9329       // If the sink source is not a replicate region, sink the recipe directly.
9330       if (TargetRegion) {
9331         // The target is in a replication region, make sure to move Sink to
9332         // the block after it, not into the replication region itself.
9333         VPBasicBlock *NextBlock =
9334             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
9335         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9336       } else
9337         Sink->moveAfter(Target);
9338       continue;
9339     }
9340 
9341     // The sink source is in a replicate region. Unhook the region from the CFG.
9342     auto *SinkPred = SinkRegion->getSinglePredecessor();
9343     auto *SinkSucc = SinkRegion->getSingleSuccessor();
9344     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
9345     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
9346     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
9347 
9348     if (TargetRegion) {
9349       // The target recipe is also in a replicate region, move the sink region
9350       // after the target region.
9351       auto *TargetSucc = TargetRegion->getSingleSuccessor();
9352       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
9353       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
9354       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
9355     } else {
9356       // The sink source is in a replicate region, we need to move the whole
9357       // replicate region, which should only contain a single recipe in the
9358       // main block.
9359       auto *SplitBlock =
9360           Target->getParent()->splitAt(std::next(Target->getIterator()));
9361 
9362       auto *SplitPred = SplitBlock->getSinglePredecessor();
9363 
9364       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
9365       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
9366       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
9367       if (VPBB == SplitPred)
9368         VPBB = SplitBlock;
9369     }
9370   }
9371 
9372   // Now that sink-after is done, move induction recipes for optimized truncates
9373   // to the phi section of the header block.
9374   for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
9375     Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
9376 
9377   // Adjust the recipes for any inloop reductions.
9378   adjustRecipesForReductions(VPBB, Plan, RecipeBuilder, Range.Start);
9379 
9380   // Introduce a recipe to combine the incoming and previous values of a
9381   // first-order recurrence.
9382   for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
9383     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
9384     if (!RecurPhi)
9385       continue;
9386 
9387     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
9388     VPBasicBlock *InsertBlock = PrevRecipe->getParent();
9389     auto *Region = GetReplicateRegion(PrevRecipe);
9390     if (Region)
9391       InsertBlock = cast<VPBasicBlock>(Region->getSingleSuccessor());
9392     if (Region || PrevRecipe->isPhi())
9393       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
9394     else
9395       Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
9396 
9397     auto *RecurSplice = cast<VPInstruction>(
9398         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
9399                              {RecurPhi, RecurPhi->getBackedgeValue()}));
9400 
9401     RecurPhi->replaceAllUsesWith(RecurSplice);
9402     // Set the first operand of RecurSplice to RecurPhi again, after replacing
9403     // all users.
9404     RecurSplice->setOperand(0, RecurPhi);
9405   }
9406 
9407   // Interleave memory: for each Interleave Group we marked earlier as relevant
9408   // for this VPlan, replace the Recipes widening its memory instructions with a
9409   // single VPInterleaveRecipe at its insertion point.
9410   for (auto IG : InterleaveGroups) {
9411     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9412         RecipeBuilder.getRecipe(IG->getInsertPos()));
9413     SmallVector<VPValue *, 4> StoredValues;
9414     for (unsigned i = 0; i < IG->getFactor(); ++i)
9415       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
9416         auto *StoreR =
9417             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
9418         StoredValues.push_back(StoreR->getStoredValue());
9419       }
9420 
9421     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9422                                         Recipe->getMask());
9423     VPIG->insertBefore(Recipe);
9424     unsigned J = 0;
9425     for (unsigned i = 0; i < IG->getFactor(); ++i)
9426       if (Instruction *Member = IG->getMember(i)) {
9427         if (!Member->getType()->isVoidTy()) {
9428           VPValue *OriginalV = Plan->getVPValue(Member);
9429           Plan->removeVPValueFor(Member);
9430           Plan->addVPValue(Member, VPIG->getVPValue(J));
9431           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9432           J++;
9433         }
9434         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9435       }
9436   }
9437 
9438   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9439   // in ways that accessing values using original IR values is incorrect.
9440   Plan->disableValue2VPValue();
9441 
9442   VPlanTransforms::sinkScalarOperands(*Plan);
9443   VPlanTransforms::mergeReplicateRegions(*Plan);
9444 
9445   std::string PlanName;
9446   raw_string_ostream RSO(PlanName);
9447   ElementCount VF = Range.Start;
9448   Plan->addVF(VF);
9449   RSO << "Initial VPlan for VF={" << VF;
9450   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9451     Plan->addVF(VF);
9452     RSO << "," << VF;
9453   }
9454   RSO << "},UF>=1";
9455   RSO.flush();
9456   Plan->setName(PlanName);
9457 
9458   assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
9459   return Plan;
9460 }
9461 
9462 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9463   // Outer loop handling: They may require CFG and instruction level
9464   // transformations before even evaluating whether vectorization is profitable.
9465   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9466   // the vectorization pipeline.
9467   assert(!OrigLoop->isInnermost());
9468   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9469 
9470   // Create new empty VPlan
9471   auto Plan = std::make_unique<VPlan>();
9472 
9473   // Build hierarchical CFG
9474   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9475   HCFGBuilder.buildHierarchicalCFG();
9476 
9477   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9478        VF *= 2)
9479     Plan->addVF(VF);
9480 
9481   if (EnableVPlanPredication) {
9482     VPlanPredicator VPP(*Plan);
9483     VPP.predicate();
9484 
9485     // Avoid running transformation to recipes until masked code generation in
9486     // VPlan-native path is in place.
9487     return Plan;
9488   }
9489 
9490   SmallPtrSet<Instruction *, 1> DeadInstructions;
9491   VPlanTransforms::VPInstructionsToVPRecipes(OrigLoop, Plan,
9492                                              Legal->getInductionVars(),
9493                                              DeadInstructions, *PSE.getSE());
9494   return Plan;
9495 }
9496 
9497 // Adjust the recipes for reductions. For in-loop reductions the chain of
9498 // instructions leading from the loop exit instr to the phi need to be converted
9499 // to reductions, with one operand being vector and the other being the scalar
9500 // reduction chain. For other reductions, a select is introduced between the phi
9501 // and live-out recipes when folding the tail.
9502 void LoopVectorizationPlanner::adjustRecipesForReductions(
9503     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9504     ElementCount MinVF) {
9505   for (auto &Reduction : CM.getInLoopReductionChains()) {
9506     PHINode *Phi = Reduction.first;
9507     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9508     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9509 
9510     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9511       continue;
9512 
9513     // ReductionOperations are orders top-down from the phi's use to the
9514     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9515     // which of the two operands will remain scalar and which will be reduced.
9516     // For minmax the chain will be the select instructions.
9517     Instruction *Chain = Phi;
9518     for (Instruction *R : ReductionOperations) {
9519       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9520       RecurKind Kind = RdxDesc.getRecurrenceKind();
9521 
9522       VPValue *ChainOp = Plan->getVPValue(Chain);
9523       unsigned FirstOpId;
9524       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9525              "Only min/max recurrences allowed for inloop reductions");
9526       // Recognize a call to the llvm.fmuladd intrinsic.
9527       bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
9528       assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
9529              "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9530       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9531         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9532                "Expected to replace a VPWidenSelectSC");
9533         FirstOpId = 1;
9534       } else {
9535         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
9536                 (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
9537                "Expected to replace a VPWidenSC");
9538         FirstOpId = 0;
9539       }
9540       unsigned VecOpId =
9541           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9542       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9543 
9544       auto *CondOp = CM.foldTailByMasking()
9545                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9546                          : nullptr;
9547 
9548       if (IsFMulAdd) {
9549         // If the instruction is a call to the llvm.fmuladd intrinsic then we
9550         // need to create an fmul recipe to use as the vector operand for the
9551         // fadd reduction.
9552         VPInstruction *FMulRecipe = new VPInstruction(
9553             Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
9554         FMulRecipe->setFastMathFlags(R->getFastMathFlags());
9555         WidenRecipe->getParent()->insert(FMulRecipe,
9556                                          WidenRecipe->getIterator());
9557         VecOp = FMulRecipe;
9558       }
9559       VPReductionRecipe *RedRecipe =
9560           new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9561       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9562       Plan->removeVPValueFor(R);
9563       Plan->addVPValue(R, RedRecipe);
9564       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9565       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9566       WidenRecipe->eraseFromParent();
9567 
9568       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9569         VPRecipeBase *CompareRecipe =
9570             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9571         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9572                "Expected to replace a VPWidenSC");
9573         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9574                "Expected no remaining users");
9575         CompareRecipe->eraseFromParent();
9576       }
9577       Chain = R;
9578     }
9579   }
9580 
9581   // If tail is folded by masking, introduce selects between the phi
9582   // and the live-out instruction of each reduction, at the end of the latch.
9583   if (CM.foldTailByMasking()) {
9584     for (VPRecipeBase &R : Plan->getEntry()->getEntryBasicBlock()->phis()) {
9585       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9586       if (!PhiR || PhiR->isInLoop())
9587         continue;
9588       Builder.setInsertPoint(LatchVPBB);
9589       VPValue *Cond =
9590           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9591       VPValue *Red = PhiR->getBackedgeValue();
9592       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9593     }
9594   }
9595 }
9596 
9597 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9598 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9599                                VPSlotTracker &SlotTracker) const {
9600   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9601   IG->getInsertPos()->printAsOperand(O, false);
9602   O << ", ";
9603   getAddr()->printAsOperand(O, SlotTracker);
9604   VPValue *Mask = getMask();
9605   if (Mask) {
9606     O << ", ";
9607     Mask->printAsOperand(O, SlotTracker);
9608   }
9609 
9610   unsigned OpIdx = 0;
9611   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9612     if (!IG->getMember(i))
9613       continue;
9614     if (getNumStoreOperands() > 0) {
9615       O << "\n" << Indent << "  store ";
9616       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9617       O << " to index " << i;
9618     } else {
9619       O << "\n" << Indent << "  ";
9620       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9621       O << " = load from index " << i;
9622     }
9623     ++OpIdx;
9624   }
9625 }
9626 #endif
9627 
9628 void VPWidenCallRecipe::execute(VPTransformState &State) {
9629   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9630                                   *this, State);
9631 }
9632 
9633 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9634   auto &I = *cast<SelectInst>(getUnderlyingInstr());
9635   State.ILV->setDebugLocFromInst(&I);
9636 
9637   // The condition can be loop invariant  but still defined inside the
9638   // loop. This means that we can't just use the original 'cond' value.
9639   // We have to take the 'vectorized' value and pick the first lane.
9640   // Instcombine will make this a no-op.
9641   auto *InvarCond =
9642       InvariantCond ? State.get(getOperand(0), VPIteration(0, 0)) : nullptr;
9643 
9644   for (unsigned Part = 0; Part < State.UF; ++Part) {
9645     Value *Cond = InvarCond ? InvarCond : State.get(getOperand(0), Part);
9646     Value *Op0 = State.get(getOperand(1), Part);
9647     Value *Op1 = State.get(getOperand(2), Part);
9648     Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
9649     State.set(this, Sel, Part);
9650     State.ILV->addMetadata(Sel, &I);
9651   }
9652 }
9653 
9654 void VPWidenRecipe::execute(VPTransformState &State) {
9655   auto &I = *cast<Instruction>(getUnderlyingValue());
9656   auto &Builder = State.Builder;
9657   switch (I.getOpcode()) {
9658   case Instruction::Call:
9659   case Instruction::Br:
9660   case Instruction::PHI:
9661   case Instruction::GetElementPtr:
9662   case Instruction::Select:
9663     llvm_unreachable("This instruction is handled by a different recipe.");
9664   case Instruction::UDiv:
9665   case Instruction::SDiv:
9666   case Instruction::SRem:
9667   case Instruction::URem:
9668   case Instruction::Add:
9669   case Instruction::FAdd:
9670   case Instruction::Sub:
9671   case Instruction::FSub:
9672   case Instruction::FNeg:
9673   case Instruction::Mul:
9674   case Instruction::FMul:
9675   case Instruction::FDiv:
9676   case Instruction::FRem:
9677   case Instruction::Shl:
9678   case Instruction::LShr:
9679   case Instruction::AShr:
9680   case Instruction::And:
9681   case Instruction::Or:
9682   case Instruction::Xor: {
9683     // Just widen unops and binops.
9684     State.ILV->setDebugLocFromInst(&I);
9685 
9686     for (unsigned Part = 0; Part < State.UF; ++Part) {
9687       SmallVector<Value *, 2> Ops;
9688       for (VPValue *VPOp : operands())
9689         Ops.push_back(State.get(VPOp, Part));
9690 
9691       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
9692 
9693       if (auto *VecOp = dyn_cast<Instruction>(V)) {
9694         VecOp->copyIRFlags(&I);
9695 
9696         // If the instruction is vectorized and was in a basic block that needed
9697         // predication, we can't propagate poison-generating flags (nuw/nsw,
9698         // exact, etc.). The control flow has been linearized and the
9699         // instruction is no longer guarded by the predicate, which could make
9700         // the flag properties to no longer hold.
9701         if (State.MayGeneratePoisonRecipes.count(this) > 0)
9702           VecOp->dropPoisonGeneratingFlags();
9703       }
9704 
9705       // Use this vector value for all users of the original instruction.
9706       State.set(this, V, Part);
9707       State.ILV->addMetadata(V, &I);
9708     }
9709 
9710     break;
9711   }
9712   case Instruction::ICmp:
9713   case Instruction::FCmp: {
9714     // Widen compares. Generate vector compares.
9715     bool FCmp = (I.getOpcode() == Instruction::FCmp);
9716     auto *Cmp = cast<CmpInst>(&I);
9717     State.ILV->setDebugLocFromInst(Cmp);
9718     for (unsigned Part = 0; Part < State.UF; ++Part) {
9719       Value *A = State.get(getOperand(0), Part);
9720       Value *B = State.get(getOperand(1), Part);
9721       Value *C = nullptr;
9722       if (FCmp) {
9723         // Propagate fast math flags.
9724         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9725         Builder.setFastMathFlags(Cmp->getFastMathFlags());
9726         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
9727       } else {
9728         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
9729       }
9730       State.set(this, C, Part);
9731       State.ILV->addMetadata(C, &I);
9732     }
9733 
9734     break;
9735   }
9736 
9737   case Instruction::ZExt:
9738   case Instruction::SExt:
9739   case Instruction::FPToUI:
9740   case Instruction::FPToSI:
9741   case Instruction::FPExt:
9742   case Instruction::PtrToInt:
9743   case Instruction::IntToPtr:
9744   case Instruction::SIToFP:
9745   case Instruction::UIToFP:
9746   case Instruction::Trunc:
9747   case Instruction::FPTrunc:
9748   case Instruction::BitCast: {
9749     auto *CI = cast<CastInst>(&I);
9750     State.ILV->setDebugLocFromInst(CI);
9751 
9752     /// Vectorize casts.
9753     Type *DestTy = (State.VF.isScalar())
9754                        ? CI->getType()
9755                        : VectorType::get(CI->getType(), State.VF);
9756 
9757     for (unsigned Part = 0; Part < State.UF; ++Part) {
9758       Value *A = State.get(getOperand(0), Part);
9759       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
9760       State.set(this, Cast, Part);
9761       State.ILV->addMetadata(Cast, &I);
9762     }
9763     break;
9764   }
9765   default:
9766     // This instruction is not vectorized by simple widening.
9767     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
9768     llvm_unreachable("Unhandled instruction!");
9769   } // end of switch.
9770 }
9771 
9772 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9773   auto *GEP = cast<GetElementPtrInst>(getUnderlyingInstr());
9774   // Construct a vector GEP by widening the operands of the scalar GEP as
9775   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
9776   // results in a vector of pointers when at least one operand of the GEP
9777   // is vector-typed. Thus, to keep the representation compact, we only use
9778   // vector-typed operands for loop-varying values.
9779 
9780   if (State.VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
9781     // If we are vectorizing, but the GEP has only loop-invariant operands,
9782     // the GEP we build (by only using vector-typed operands for
9783     // loop-varying values) would be a scalar pointer. Thus, to ensure we
9784     // produce a vector of pointers, we need to either arbitrarily pick an
9785     // operand to broadcast, or broadcast a clone of the original GEP.
9786     // Here, we broadcast a clone of the original.
9787     //
9788     // TODO: If at some point we decide to scalarize instructions having
9789     //       loop-invariant operands, this special case will no longer be
9790     //       required. We would add the scalarization decision to
9791     //       collectLoopScalars() and teach getVectorValue() to broadcast
9792     //       the lane-zero scalar value.
9793     auto *Clone = State.Builder.Insert(GEP->clone());
9794     for (unsigned Part = 0; Part < State.UF; ++Part) {
9795       Value *EntryPart = State.Builder.CreateVectorSplat(State.VF, Clone);
9796       State.set(this, EntryPart, Part);
9797       State.ILV->addMetadata(EntryPart, GEP);
9798     }
9799   } else {
9800     // If the GEP has at least one loop-varying operand, we are sure to
9801     // produce a vector of pointers. But if we are only unrolling, we want
9802     // to produce a scalar GEP for each unroll part. Thus, the GEP we
9803     // produce with the code below will be scalar (if VF == 1) or vector
9804     // (otherwise). Note that for the unroll-only case, we still maintain
9805     // values in the vector mapping with initVector, as we do for other
9806     // instructions.
9807     for (unsigned Part = 0; Part < State.UF; ++Part) {
9808       // The pointer operand of the new GEP. If it's loop-invariant, we
9809       // won't broadcast it.
9810       auto *Ptr = IsPtrLoopInvariant
9811                       ? State.get(getOperand(0), VPIteration(0, 0))
9812                       : State.get(getOperand(0), Part);
9813 
9814       // Collect all the indices for the new GEP. If any index is
9815       // loop-invariant, we won't broadcast it.
9816       SmallVector<Value *, 4> Indices;
9817       for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
9818         VPValue *Operand = getOperand(I);
9819         if (IsIndexLoopInvariant[I - 1])
9820           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
9821         else
9822           Indices.push_back(State.get(Operand, Part));
9823       }
9824 
9825       // If the GEP instruction is vectorized and was in a basic block that
9826       // needed predication, we can't propagate the poison-generating 'inbounds'
9827       // flag. The control flow has been linearized and the GEP is no longer
9828       // guarded by the predicate, which could make the 'inbounds' properties to
9829       // no longer hold.
9830       bool IsInBounds =
9831           GEP->isInBounds() && State.MayGeneratePoisonRecipes.count(this) == 0;
9832 
9833       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
9834       // but it should be a vector, otherwise.
9835       auto *NewGEP = IsInBounds
9836                          ? State.Builder.CreateInBoundsGEP(
9837                                GEP->getSourceElementType(), Ptr, Indices)
9838                          : State.Builder.CreateGEP(GEP->getSourceElementType(),
9839                                                    Ptr, Indices);
9840       assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
9841              "NewGEP is not a pointer vector");
9842       State.set(this, NewGEP, Part);
9843       State.ILV->addMetadata(NewGEP, GEP);
9844     }
9845   }
9846 }
9847 
9848 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9849   assert(!State.Instance && "Int or FP induction being replicated.");
9850   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9851                                    getTruncInst(), getVPValue(0),
9852                                    getCastValue(), State);
9853 }
9854 
9855 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9856   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), this,
9857                                  State);
9858 }
9859 
9860 void VPBlendRecipe::execute(VPTransformState &State) {
9861   State.ILV->setDebugLocFromInst(Phi, &State.Builder);
9862   // We know that all PHIs in non-header blocks are converted into
9863   // selects, so we don't have to worry about the insertion order and we
9864   // can just use the builder.
9865   // At this point we generate the predication tree. There may be
9866   // duplications since this is a simple recursive scan, but future
9867   // optimizations will clean it up.
9868 
9869   unsigned NumIncoming = getNumIncomingValues();
9870 
9871   // Generate a sequence of selects of the form:
9872   // SELECT(Mask3, In3,
9873   //        SELECT(Mask2, In2,
9874   //               SELECT(Mask1, In1,
9875   //                      In0)))
9876   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9877   // are essentially undef are taken from In0.
9878   InnerLoopVectorizer::VectorParts Entry(State.UF);
9879   for (unsigned In = 0; In < NumIncoming; ++In) {
9880     for (unsigned Part = 0; Part < State.UF; ++Part) {
9881       // We might have single edge PHIs (blocks) - use an identity
9882       // 'select' for the first PHI operand.
9883       Value *In0 = State.get(getIncomingValue(In), Part);
9884       if (In == 0)
9885         Entry[Part] = In0; // Initialize with the first incoming value.
9886       else {
9887         // Select between the current value and the previous incoming edge
9888         // based on the incoming mask.
9889         Value *Cond = State.get(getMask(In), Part);
9890         Entry[Part] =
9891             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9892       }
9893     }
9894   }
9895   for (unsigned Part = 0; Part < State.UF; ++Part)
9896     State.set(this, Entry[Part], Part);
9897 }
9898 
9899 void VPInterleaveRecipe::execute(VPTransformState &State) {
9900   assert(!State.Instance && "Interleave group being replicated.");
9901   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9902                                       getStoredValues(), getMask());
9903 }
9904 
9905 void VPReductionRecipe::execute(VPTransformState &State) {
9906   assert(!State.Instance && "Reduction being replicated.");
9907   Value *PrevInChain = State.get(getChainOp(), 0);
9908   RecurKind Kind = RdxDesc->getRecurrenceKind();
9909   bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9910   // Propagate the fast-math flags carried by the underlying instruction.
9911   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
9912   State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
9913   for (unsigned Part = 0; Part < State.UF; ++Part) {
9914     Value *NewVecOp = State.get(getVecOp(), Part);
9915     if (VPValue *Cond = getCondOp()) {
9916       Value *NewCond = State.get(Cond, Part);
9917       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9918       Value *Iden = RdxDesc->getRecurrenceIdentity(
9919           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9920       Value *IdenVec =
9921           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9922       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9923       NewVecOp = Select;
9924     }
9925     Value *NewRed;
9926     Value *NextInChain;
9927     if (IsOrdered) {
9928       if (State.VF.isVector())
9929         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9930                                         PrevInChain);
9931       else
9932         NewRed = State.Builder.CreateBinOp(
9933             (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
9934             NewVecOp);
9935       PrevInChain = NewRed;
9936     } else {
9937       PrevInChain = State.get(getChainOp(), Part);
9938       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9939     }
9940     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9941       NextInChain =
9942           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9943                          NewRed, PrevInChain);
9944     } else if (IsOrdered)
9945       NextInChain = NewRed;
9946     else
9947       NextInChain = State.Builder.CreateBinOp(
9948           (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
9949           PrevInChain);
9950     State.set(this, NextInChain, Part);
9951   }
9952 }
9953 
9954 void VPReplicateRecipe::execute(VPTransformState &State) {
9955   if (State.Instance) { // Generate a single instance.
9956     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9957     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
9958                                     IsPredicated, State);
9959     // Insert scalar instance packing it into a vector.
9960     if (AlsoPack && State.VF.isVector()) {
9961       // If we're constructing lane 0, initialize to start from poison.
9962       if (State.Instance->Lane.isFirstLane()) {
9963         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9964         Value *Poison = PoisonValue::get(
9965             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9966         State.set(this, Poison, State.Instance->Part);
9967       }
9968       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9969     }
9970     return;
9971   }
9972 
9973   // Generate scalar instances for all VF lanes of all UF parts, unless the
9974   // instruction is uniform inwhich case generate only the first lane for each
9975   // of the UF parts.
9976   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9977   assert((!State.VF.isScalable() || IsUniform) &&
9978          "Can't scalarize a scalable vector");
9979   for (unsigned Part = 0; Part < State.UF; ++Part)
9980     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9981       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
9982                                       VPIteration(Part, Lane), IsPredicated,
9983                                       State);
9984 }
9985 
9986 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9987   assert(State.Instance && "Branch on Mask works only on single instance.");
9988 
9989   unsigned Part = State.Instance->Part;
9990   unsigned Lane = State.Instance->Lane.getKnownLane();
9991 
9992   Value *ConditionBit = nullptr;
9993   VPValue *BlockInMask = getMask();
9994   if (BlockInMask) {
9995     ConditionBit = State.get(BlockInMask, Part);
9996     if (ConditionBit->getType()->isVectorTy())
9997       ConditionBit = State.Builder.CreateExtractElement(
9998           ConditionBit, State.Builder.getInt32(Lane));
9999   } else // Block in mask is all-one.
10000     ConditionBit = State.Builder.getTrue();
10001 
10002   // Replace the temporary unreachable terminator with a new conditional branch,
10003   // whose two destinations will be set later when they are created.
10004   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
10005   assert(isa<UnreachableInst>(CurrentTerminator) &&
10006          "Expected to replace unreachable terminator with conditional branch.");
10007   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
10008   CondBr->setSuccessor(0, nullptr);
10009   ReplaceInstWithInst(CurrentTerminator, CondBr);
10010 }
10011 
10012 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
10013   assert(State.Instance && "Predicated instruction PHI works per instance.");
10014   Instruction *ScalarPredInst =
10015       cast<Instruction>(State.get(getOperand(0), *State.Instance));
10016   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
10017   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
10018   assert(PredicatingBB && "Predicated block has no single predecessor.");
10019   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
10020          "operand must be VPReplicateRecipe");
10021 
10022   // By current pack/unpack logic we need to generate only a single phi node: if
10023   // a vector value for the predicated instruction exists at this point it means
10024   // the instruction has vector users only, and a phi for the vector value is
10025   // needed. In this case the recipe of the predicated instruction is marked to
10026   // also do that packing, thereby "hoisting" the insert-element sequence.
10027   // Otherwise, a phi node for the scalar value is needed.
10028   unsigned Part = State.Instance->Part;
10029   if (State.hasVectorValue(getOperand(0), Part)) {
10030     Value *VectorValue = State.get(getOperand(0), Part);
10031     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
10032     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
10033     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
10034     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
10035     if (State.hasVectorValue(this, Part))
10036       State.reset(this, VPhi, Part);
10037     else
10038       State.set(this, VPhi, Part);
10039     // NOTE: Currently we need to update the value of the operand, so the next
10040     // predicated iteration inserts its generated value in the correct vector.
10041     State.reset(getOperand(0), VPhi, Part);
10042   } else {
10043     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
10044     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
10045     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
10046                      PredicatingBB);
10047     Phi->addIncoming(ScalarPredInst, PredicatedBB);
10048     if (State.hasScalarValue(this, *State.Instance))
10049       State.reset(this, Phi, *State.Instance);
10050     else
10051       State.set(this, Phi, *State.Instance);
10052     // NOTE: Currently we need to update the value of the operand, so the next
10053     // predicated iteration inserts its generated value in the correct vector.
10054     State.reset(getOperand(0), Phi, *State.Instance);
10055   }
10056 }
10057 
10058 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
10059   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
10060   State.ILV->vectorizeMemoryInstruction(
10061       &Ingredient, State, StoredValue ? nullptr : getVPSingleValue(), getAddr(),
10062       StoredValue, getMask(), Consecutive, Reverse);
10063 }
10064 
10065 // Determine how to lower the scalar epilogue, which depends on 1) optimising
10066 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
10067 // predication, and 4) a TTI hook that analyses whether the loop is suitable
10068 // for predication.
10069 static ScalarEpilogueLowering getScalarEpilogueLowering(
10070     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
10071     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
10072     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
10073     LoopVectorizationLegality &LVL) {
10074   // 1) OptSize takes precedence over all other options, i.e. if this is set,
10075   // don't look at hints or options, and don't request a scalar epilogue.
10076   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
10077   // LoopAccessInfo (due to code dependency and not being able to reliably get
10078   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
10079   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
10080   // versioning when the vectorization is forced, unlike hasOptSize. So revert
10081   // back to the old way and vectorize with versioning when forced. See D81345.)
10082   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
10083                                                       PGSOQueryType::IRPass) &&
10084                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
10085     return CM_ScalarEpilogueNotAllowedOptSize;
10086 
10087   // 2) If set, obey the directives
10088   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
10089     switch (PreferPredicateOverEpilogue) {
10090     case PreferPredicateTy::ScalarEpilogue:
10091       return CM_ScalarEpilogueAllowed;
10092     case PreferPredicateTy::PredicateElseScalarEpilogue:
10093       return CM_ScalarEpilogueNotNeededUsePredicate;
10094     case PreferPredicateTy::PredicateOrDontVectorize:
10095       return CM_ScalarEpilogueNotAllowedUsePredicate;
10096     };
10097   }
10098 
10099   // 3) If set, obey the hints
10100   switch (Hints.getPredicate()) {
10101   case LoopVectorizeHints::FK_Enabled:
10102     return CM_ScalarEpilogueNotNeededUsePredicate;
10103   case LoopVectorizeHints::FK_Disabled:
10104     return CM_ScalarEpilogueAllowed;
10105   };
10106 
10107   // 4) if the TTI hook indicates this is profitable, request predication.
10108   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
10109                                        LVL.getLAI()))
10110     return CM_ScalarEpilogueNotNeededUsePredicate;
10111 
10112   return CM_ScalarEpilogueAllowed;
10113 }
10114 
10115 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
10116   // If Values have been set for this Def return the one relevant for \p Part.
10117   if (hasVectorValue(Def, Part))
10118     return Data.PerPartOutput[Def][Part];
10119 
10120   if (!hasScalarValue(Def, {Part, 0})) {
10121     Value *IRV = Def->getLiveInIRValue();
10122     Value *B = ILV->getBroadcastInstrs(IRV);
10123     set(Def, B, Part);
10124     return B;
10125   }
10126 
10127   Value *ScalarValue = get(Def, {Part, 0});
10128   // If we aren't vectorizing, we can just copy the scalar map values over
10129   // to the vector map.
10130   if (VF.isScalar()) {
10131     set(Def, ScalarValue, Part);
10132     return ScalarValue;
10133   }
10134 
10135   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
10136   bool IsUniform = RepR && RepR->isUniform();
10137 
10138   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
10139   // Check if there is a scalar value for the selected lane.
10140   if (!hasScalarValue(Def, {Part, LastLane})) {
10141     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
10142     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
10143            "unexpected recipe found to be invariant");
10144     IsUniform = true;
10145     LastLane = 0;
10146   }
10147 
10148   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
10149   // Set the insert point after the last scalarized instruction or after the
10150   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
10151   // will directly follow the scalar definitions.
10152   auto OldIP = Builder.saveIP();
10153   auto NewIP =
10154       isa<PHINode>(LastInst)
10155           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
10156           : std::next(BasicBlock::iterator(LastInst));
10157   Builder.SetInsertPoint(&*NewIP);
10158 
10159   // However, if we are vectorizing, we need to construct the vector values.
10160   // If the value is known to be uniform after vectorization, we can just
10161   // broadcast the scalar value corresponding to lane zero for each unroll
10162   // iteration. Otherwise, we construct the vector values using
10163   // insertelement instructions. Since the resulting vectors are stored in
10164   // State, we will only generate the insertelements once.
10165   Value *VectorValue = nullptr;
10166   if (IsUniform) {
10167     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
10168     set(Def, VectorValue, Part);
10169   } else {
10170     // Initialize packing with insertelements to start from undef.
10171     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
10172     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
10173     set(Def, Undef, Part);
10174     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
10175       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
10176     VectorValue = get(Def, Part);
10177   }
10178   Builder.restoreIP(OldIP);
10179   return VectorValue;
10180 }
10181 
10182 // Process the loop in the VPlan-native vectorization path. This path builds
10183 // VPlan upfront in the vectorization pipeline, which allows to apply
10184 // VPlan-to-VPlan transformations from the very beginning without modifying the
10185 // input LLVM IR.
10186 static bool processLoopInVPlanNativePath(
10187     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
10188     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
10189     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
10190     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
10191     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
10192     LoopVectorizationRequirements &Requirements) {
10193 
10194   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
10195     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
10196     return false;
10197   }
10198   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
10199   Function *F = L->getHeader()->getParent();
10200   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
10201 
10202   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10203       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
10204 
10205   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
10206                                 &Hints, IAI);
10207   // Use the planner for outer loop vectorization.
10208   // TODO: CM is not used at this point inside the planner. Turn CM into an
10209   // optional argument if we don't need it in the future.
10210   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
10211                                Requirements, ORE);
10212 
10213   // Get user vectorization factor.
10214   ElementCount UserVF = Hints.getWidth();
10215 
10216   CM.collectElementTypesForWidening();
10217 
10218   // Plan how to best vectorize, return the best VF and its cost.
10219   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
10220 
10221   // If we are stress testing VPlan builds, do not attempt to generate vector
10222   // code. Masked vector code generation support will follow soon.
10223   // Also, do not attempt to vectorize if no vector code will be produced.
10224   if (VPlanBuildStressTest || EnableVPlanPredication ||
10225       VectorizationFactor::Disabled() == VF)
10226     return false;
10227 
10228   VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10229 
10230   {
10231     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10232                              F->getParent()->getDataLayout());
10233     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
10234                            &CM, BFI, PSI, Checks);
10235     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
10236                       << L->getHeader()->getParent()->getName() << "\"\n");
10237     LVP.executePlan(VF.Width, 1, BestPlan, LB, DT);
10238   }
10239 
10240   // Mark the loop as already vectorized to avoid vectorizing again.
10241   Hints.setAlreadyVectorized();
10242   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10243   return true;
10244 }
10245 
10246 // Emit a remark if there are stores to floats that required a floating point
10247 // extension. If the vectorized loop was generated with floating point there
10248 // will be a performance penalty from the conversion overhead and the change in
10249 // the vector width.
10250 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
10251   SmallVector<Instruction *, 4> Worklist;
10252   for (BasicBlock *BB : L->getBlocks()) {
10253     for (Instruction &Inst : *BB) {
10254       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
10255         if (S->getValueOperand()->getType()->isFloatTy())
10256           Worklist.push_back(S);
10257       }
10258     }
10259   }
10260 
10261   // Traverse the floating point stores upwards searching, for floating point
10262   // conversions.
10263   SmallPtrSet<const Instruction *, 4> Visited;
10264   SmallPtrSet<const Instruction *, 4> EmittedRemark;
10265   while (!Worklist.empty()) {
10266     auto *I = Worklist.pop_back_val();
10267     if (!L->contains(I))
10268       continue;
10269     if (!Visited.insert(I).second)
10270       continue;
10271 
10272     // Emit a remark if the floating point store required a floating
10273     // point conversion.
10274     // TODO: More work could be done to identify the root cause such as a
10275     // constant or a function return type and point the user to it.
10276     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
10277       ORE->emit([&]() {
10278         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
10279                                           I->getDebugLoc(), L->getHeader())
10280                << "floating point conversion changes vector width. "
10281                << "Mixed floating point precision requires an up/down "
10282                << "cast that will negatively impact performance.";
10283       });
10284 
10285     for (Use &Op : I->operands())
10286       if (auto *OpI = dyn_cast<Instruction>(Op))
10287         Worklist.push_back(OpI);
10288   }
10289 }
10290 
10291 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10292     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10293                                !EnableLoopInterleaving),
10294       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10295                               !EnableLoopVectorization) {}
10296 
10297 bool LoopVectorizePass::processLoop(Loop *L) {
10298   assert((EnableVPlanNativePath || L->isInnermost()) &&
10299          "VPlan-native path is not enabled. Only process inner loops.");
10300 
10301 #ifndef NDEBUG
10302   const std::string DebugLocStr = getDebugLocString(L);
10303 #endif /* NDEBUG */
10304 
10305   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
10306                     << L->getHeader()->getParent()->getName() << "\" from "
10307                     << DebugLocStr << "\n");
10308 
10309   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
10310 
10311   LLVM_DEBUG(
10312       dbgs() << "LV: Loop hints:"
10313              << " force="
10314              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10315                      ? "disabled"
10316                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10317                             ? "enabled"
10318                             : "?"))
10319              << " width=" << Hints.getWidth()
10320              << " interleave=" << Hints.getInterleave() << "\n");
10321 
10322   // Function containing loop
10323   Function *F = L->getHeader()->getParent();
10324 
10325   // Looking at the diagnostic output is the only way to determine if a loop
10326   // was vectorized (other than looking at the IR or machine code), so it
10327   // is important to generate an optimization remark for each loop. Most of
10328   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10329   // generated as OptimizationRemark and OptimizationRemarkMissed are
10330   // less verbose reporting vectorized loops and unvectorized loops that may
10331   // benefit from vectorization, respectively.
10332 
10333   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10334     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10335     return false;
10336   }
10337 
10338   PredicatedScalarEvolution PSE(*SE, *L);
10339 
10340   // Check if it is legal to vectorize the loop.
10341   LoopVectorizationRequirements Requirements;
10342   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10343                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10344   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10345     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10346     Hints.emitRemarkWithHints();
10347     return false;
10348   }
10349 
10350   // Check the function attributes and profiles to find out if this function
10351   // should be optimized for size.
10352   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10353       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10354 
10355   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10356   // here. They may require CFG and instruction level transformations before
10357   // even evaluating whether vectorization is profitable. Since we cannot modify
10358   // the incoming IR, we need to build VPlan upfront in the vectorization
10359   // pipeline.
10360   if (!L->isInnermost())
10361     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10362                                         ORE, BFI, PSI, Hints, Requirements);
10363 
10364   assert(L->isInnermost() && "Inner loop expected.");
10365 
10366   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10367   // count by optimizing for size, to minimize overheads.
10368   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10369   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10370     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10371                       << "This loop is worth vectorizing only if no scalar "
10372                       << "iteration overheads are incurred.");
10373     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10374       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10375     else {
10376       LLVM_DEBUG(dbgs() << "\n");
10377       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10378     }
10379   }
10380 
10381   // Check the function attributes to see if implicit floats are allowed.
10382   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10383   // an integer loop and the vector instructions selected are purely integer
10384   // vector instructions?
10385   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10386     reportVectorizationFailure(
10387         "Can't vectorize when the NoImplicitFloat attribute is used",
10388         "loop not vectorized due to NoImplicitFloat attribute",
10389         "NoImplicitFloat", ORE, L);
10390     Hints.emitRemarkWithHints();
10391     return false;
10392   }
10393 
10394   // Check if the target supports potentially unsafe FP vectorization.
10395   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10396   // for the target we're vectorizing for, to make sure none of the
10397   // additional fp-math flags can help.
10398   if (Hints.isPotentiallyUnsafe() &&
10399       TTI->isFPVectorizationPotentiallyUnsafe()) {
10400     reportVectorizationFailure(
10401         "Potentially unsafe FP op prevents vectorization",
10402         "loop not vectorized due to unsafe FP support.",
10403         "UnsafeFP", ORE, L);
10404     Hints.emitRemarkWithHints();
10405     return false;
10406   }
10407 
10408   bool AllowOrderedReductions;
10409   // If the flag is set, use that instead and override the TTI behaviour.
10410   if (ForceOrderedReductions.getNumOccurrences() > 0)
10411     AllowOrderedReductions = ForceOrderedReductions;
10412   else
10413     AllowOrderedReductions = TTI->enableOrderedReductions();
10414   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10415     ORE->emit([&]() {
10416       auto *ExactFPMathInst = Requirements.getExactFPInst();
10417       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10418                                                  ExactFPMathInst->getDebugLoc(),
10419                                                  ExactFPMathInst->getParent())
10420              << "loop not vectorized: cannot prove it is safe to reorder "
10421                 "floating-point operations";
10422     });
10423     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10424                          "reorder floating-point operations\n");
10425     Hints.emitRemarkWithHints();
10426     return false;
10427   }
10428 
10429   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10430   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10431 
10432   // If an override option has been passed in for interleaved accesses, use it.
10433   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10434     UseInterleaved = EnableInterleavedMemAccesses;
10435 
10436   // Analyze interleaved memory accesses.
10437   if (UseInterleaved) {
10438     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10439   }
10440 
10441   // Use the cost model.
10442   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10443                                 F, &Hints, IAI);
10444   CM.collectValuesToIgnore();
10445   CM.collectElementTypesForWidening();
10446 
10447   // Use the planner for vectorization.
10448   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10449                                Requirements, ORE);
10450 
10451   // Get user vectorization factor and interleave count.
10452   ElementCount UserVF = Hints.getWidth();
10453   unsigned UserIC = Hints.getInterleave();
10454 
10455   // Plan how to best vectorize, return the best VF and its cost.
10456   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10457 
10458   VectorizationFactor VF = VectorizationFactor::Disabled();
10459   unsigned IC = 1;
10460 
10461   if (MaybeVF) {
10462     VF = *MaybeVF;
10463     // Select the interleave count.
10464     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10465   }
10466 
10467   // Identify the diagnostic messages that should be produced.
10468   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10469   bool VectorizeLoop = true, InterleaveLoop = true;
10470   if (VF.Width.isScalar()) {
10471     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10472     VecDiagMsg = std::make_pair(
10473         "VectorizationNotBeneficial",
10474         "the cost-model indicates that vectorization is not beneficial");
10475     VectorizeLoop = false;
10476   }
10477 
10478   if (!MaybeVF && UserIC > 1) {
10479     // Tell the user interleaving was avoided up-front, despite being explicitly
10480     // requested.
10481     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10482                          "interleaving should be avoided up front\n");
10483     IntDiagMsg = std::make_pair(
10484         "InterleavingAvoided",
10485         "Ignoring UserIC, because interleaving was avoided up front");
10486     InterleaveLoop = false;
10487   } else if (IC == 1 && UserIC <= 1) {
10488     // Tell the user interleaving is not beneficial.
10489     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10490     IntDiagMsg = std::make_pair(
10491         "InterleavingNotBeneficial",
10492         "the cost-model indicates that interleaving is not beneficial");
10493     InterleaveLoop = false;
10494     if (UserIC == 1) {
10495       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10496       IntDiagMsg.second +=
10497           " and is explicitly disabled or interleave count is set to 1";
10498     }
10499   } else if (IC > 1 && UserIC == 1) {
10500     // Tell the user interleaving is beneficial, but it explicitly disabled.
10501     LLVM_DEBUG(
10502         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10503     IntDiagMsg = std::make_pair(
10504         "InterleavingBeneficialButDisabled",
10505         "the cost-model indicates that interleaving is beneficial "
10506         "but is explicitly disabled or interleave count is set to 1");
10507     InterleaveLoop = false;
10508   }
10509 
10510   // Override IC if user provided an interleave count.
10511   IC = UserIC > 0 ? UserIC : IC;
10512 
10513   // Emit diagnostic messages, if any.
10514   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10515   if (!VectorizeLoop && !InterleaveLoop) {
10516     // Do not vectorize or interleaving the loop.
10517     ORE->emit([&]() {
10518       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10519                                       L->getStartLoc(), L->getHeader())
10520              << VecDiagMsg.second;
10521     });
10522     ORE->emit([&]() {
10523       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10524                                       L->getStartLoc(), L->getHeader())
10525              << IntDiagMsg.second;
10526     });
10527     return false;
10528   } else if (!VectorizeLoop && InterleaveLoop) {
10529     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10530     ORE->emit([&]() {
10531       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10532                                         L->getStartLoc(), L->getHeader())
10533              << VecDiagMsg.second;
10534     });
10535   } else if (VectorizeLoop && !InterleaveLoop) {
10536     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10537                       << ") in " << DebugLocStr << '\n');
10538     ORE->emit([&]() {
10539       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10540                                         L->getStartLoc(), L->getHeader())
10541              << IntDiagMsg.second;
10542     });
10543   } else if (VectorizeLoop && InterleaveLoop) {
10544     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10545                       << ") in " << DebugLocStr << '\n');
10546     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10547   }
10548 
10549   bool DisableRuntimeUnroll = false;
10550   MDNode *OrigLoopID = L->getLoopID();
10551   {
10552     // Optimistically generate runtime checks. Drop them if they turn out to not
10553     // be profitable. Limit the scope of Checks, so the cleanup happens
10554     // immediately after vector codegeneration is done.
10555     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10556                              F->getParent()->getDataLayout());
10557     if (!VF.Width.isScalar() || IC > 1)
10558       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
10559 
10560     using namespace ore;
10561     if (!VectorizeLoop) {
10562       assert(IC > 1 && "interleave count should not be 1 or 0");
10563       // If we decided that it is not legal to vectorize the loop, then
10564       // interleave it.
10565       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10566                                  &CM, BFI, PSI, Checks);
10567 
10568       VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10569       LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT);
10570 
10571       ORE->emit([&]() {
10572         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10573                                   L->getHeader())
10574                << "interleaved loop (interleaved count: "
10575                << NV("InterleaveCount", IC) << ")";
10576       });
10577     } else {
10578       // If we decided that it is *legal* to vectorize the loop, then do it.
10579 
10580       // Consider vectorizing the epilogue too if it's profitable.
10581       VectorizationFactor EpilogueVF =
10582           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10583       if (EpilogueVF.Width.isVector()) {
10584 
10585         // The first pass vectorizes the main loop and creates a scalar epilogue
10586         // to be vectorized by executing the plan (potentially with a different
10587         // factor) again shortly afterwards.
10588         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10589         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10590                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10591 
10592         VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
10593         LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
10594                         DT);
10595         ++LoopsVectorized;
10596 
10597         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10598         formLCSSARecursively(*L, *DT, LI, SE);
10599 
10600         // Second pass vectorizes the epilogue and adjusts the control flow
10601         // edges from the first pass.
10602         EPI.MainLoopVF = EPI.EpilogueVF;
10603         EPI.MainLoopUF = EPI.EpilogueUF;
10604         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10605                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10606                                                  Checks);
10607 
10608         VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
10609         LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
10610                         DT);
10611         ++LoopsEpilogueVectorized;
10612 
10613         if (!MainILV.areSafetyChecksAdded())
10614           DisableRuntimeUnroll = true;
10615       } else {
10616         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10617                                &LVL, &CM, BFI, PSI, Checks);
10618 
10619         VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10620         LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
10621         ++LoopsVectorized;
10622 
10623         // Add metadata to disable runtime unrolling a scalar loop when there
10624         // are no runtime checks about strides and memory. A scalar loop that is
10625         // rarely used is not worth unrolling.
10626         if (!LB.areSafetyChecksAdded())
10627           DisableRuntimeUnroll = true;
10628       }
10629       // Report the vectorization decision.
10630       ORE->emit([&]() {
10631         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10632                                   L->getHeader())
10633                << "vectorized loop (vectorization width: "
10634                << NV("VectorizationFactor", VF.Width)
10635                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10636       });
10637     }
10638 
10639     if (ORE->allowExtraAnalysis(LV_NAME))
10640       checkMixedPrecision(L, ORE);
10641   }
10642 
10643   Optional<MDNode *> RemainderLoopID =
10644       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10645                                       LLVMLoopVectorizeFollowupEpilogue});
10646   if (RemainderLoopID.hasValue()) {
10647     L->setLoopID(RemainderLoopID.getValue());
10648   } else {
10649     if (DisableRuntimeUnroll)
10650       AddRuntimeUnrollDisableMetaData(L);
10651 
10652     // Mark the loop as already vectorized to avoid vectorizing again.
10653     Hints.setAlreadyVectorized();
10654   }
10655 
10656   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10657   return true;
10658 }
10659 
10660 LoopVectorizeResult LoopVectorizePass::runImpl(
10661     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10662     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10663     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10664     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10665     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10666   SE = &SE_;
10667   LI = &LI_;
10668   TTI = &TTI_;
10669   DT = &DT_;
10670   BFI = &BFI_;
10671   TLI = TLI_;
10672   AA = &AA_;
10673   AC = &AC_;
10674   GetLAA = &GetLAA_;
10675   DB = &DB_;
10676   ORE = &ORE_;
10677   PSI = PSI_;
10678 
10679   // Don't attempt if
10680   // 1. the target claims to have no vector registers, and
10681   // 2. interleaving won't help ILP.
10682   //
10683   // The second condition is necessary because, even if the target has no
10684   // vector registers, loop vectorization may still enable scalar
10685   // interleaving.
10686   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10687       TTI->getMaxInterleaveFactor(1) < 2)
10688     return LoopVectorizeResult(false, false);
10689 
10690   bool Changed = false, CFGChanged = false;
10691 
10692   // The vectorizer requires loops to be in simplified form.
10693   // Since simplification may add new inner loops, it has to run before the
10694   // legality and profitability checks. This means running the loop vectorizer
10695   // will simplify all loops, regardless of whether anything end up being
10696   // vectorized.
10697   for (auto &L : *LI)
10698     Changed |= CFGChanged |=
10699         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10700 
10701   // Build up a worklist of inner-loops to vectorize. This is necessary as
10702   // the act of vectorizing or partially unrolling a loop creates new loops
10703   // and can invalidate iterators across the loops.
10704   SmallVector<Loop *, 8> Worklist;
10705 
10706   for (Loop *L : *LI)
10707     collectSupportedLoops(*L, LI, ORE, Worklist);
10708 
10709   LoopsAnalyzed += Worklist.size();
10710 
10711   // Now walk the identified inner loops.
10712   while (!Worklist.empty()) {
10713     Loop *L = Worklist.pop_back_val();
10714 
10715     // For the inner loops we actually process, form LCSSA to simplify the
10716     // transform.
10717     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10718 
10719     Changed |= CFGChanged |= processLoop(L);
10720   }
10721 
10722   // Process each loop nest in the function.
10723   return LoopVectorizeResult(Changed, CFGChanged);
10724 }
10725 
10726 PreservedAnalyses LoopVectorizePass::run(Function &F,
10727                                          FunctionAnalysisManager &AM) {
10728     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10729     auto &LI = AM.getResult<LoopAnalysis>(F);
10730     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10731     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10732     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10733     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10734     auto &AA = AM.getResult<AAManager>(F);
10735     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10736     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10737     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10738 
10739     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10740     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10741         [&](Loop &L) -> const LoopAccessInfo & {
10742       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10743                                         TLI, TTI, nullptr, nullptr, nullptr};
10744       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10745     };
10746     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10747     ProfileSummaryInfo *PSI =
10748         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10749     LoopVectorizeResult Result =
10750         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10751     if (!Result.MadeAnyChange)
10752       return PreservedAnalyses::all();
10753     PreservedAnalyses PA;
10754 
10755     // We currently do not preserve loopinfo/dominator analyses with outer loop
10756     // vectorization. Until this is addressed, mark these analyses as preserved
10757     // only for non-VPlan-native path.
10758     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10759     if (!EnableVPlanNativePath) {
10760       PA.preserve<LoopAnalysis>();
10761       PA.preserve<DominatorTreeAnalysis>();
10762     }
10763     if (!Result.MadeCFGChange)
10764       PA.preserveSet<CFGAnalyses>();
10765     return PA;
10766 }
10767 
10768 void LoopVectorizePass::printPipeline(
10769     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10770   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10771       OS, MapClassName2PassName);
10772 
10773   OS << "<";
10774   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10775   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10776   OS << ">";
10777 }
10778