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/MemorySSA.h"
91 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
92 #include "llvm/Analysis/ProfileSummaryInfo.h"
93 #include "llvm/Analysis/ScalarEvolution.h"
94 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
95 #include "llvm/Analysis/TargetLibraryInfo.h"
96 #include "llvm/Analysis/TargetTransformInfo.h"
97 #include "llvm/Analysis/VectorUtils.h"
98 #include "llvm/IR/Attributes.h"
99 #include "llvm/IR/BasicBlock.h"
100 #include "llvm/IR/CFG.h"
101 #include "llvm/IR/Constant.h"
102 #include "llvm/IR/Constants.h"
103 #include "llvm/IR/DataLayout.h"
104 #include "llvm/IR/DebugInfoMetadata.h"
105 #include "llvm/IR/DebugLoc.h"
106 #include "llvm/IR/DerivedTypes.h"
107 #include "llvm/IR/DiagnosticInfo.h"
108 #include "llvm/IR/Dominators.h"
109 #include "llvm/IR/Function.h"
110 #include "llvm/IR/IRBuilder.h"
111 #include "llvm/IR/InstrTypes.h"
112 #include "llvm/IR/Instruction.h"
113 #include "llvm/IR/Instructions.h"
114 #include "llvm/IR/IntrinsicInst.h"
115 #include "llvm/IR/Intrinsics.h"
116 #include "llvm/IR/LLVMContext.h"
117 #include "llvm/IR/Metadata.h"
118 #include "llvm/IR/Module.h"
119 #include "llvm/IR/Operator.h"
120 #include "llvm/IR/PatternMatch.h"
121 #include "llvm/IR/Type.h"
122 #include "llvm/IR/Use.h"
123 #include "llvm/IR/User.h"
124 #include "llvm/IR/Value.h"
125 #include "llvm/IR/ValueHandle.h"
126 #include "llvm/IR/Verifier.h"
127 #include "llvm/InitializePasses.h"
128 #include "llvm/Pass.h"
129 #include "llvm/Support/Casting.h"
130 #include "llvm/Support/CommandLine.h"
131 #include "llvm/Support/Compiler.h"
132 #include "llvm/Support/Debug.h"
133 #include "llvm/Support/ErrorHandling.h"
134 #include "llvm/Support/InstructionCost.h"
135 #include "llvm/Support/MathExtras.h"
136 #include "llvm/Support/raw_ostream.h"
137 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
138 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
139 #include "llvm/Transforms/Utils/LoopSimplify.h"
140 #include "llvm/Transforms/Utils/LoopUtils.h"
141 #include "llvm/Transforms/Utils/LoopVersioning.h"
142 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
143 #include "llvm/Transforms/Utils/SizeOpts.h"
144 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
145 #include <algorithm>
146 #include <cassert>
147 #include <cstdint>
148 #include <cstdlib>
149 #include <functional>
150 #include <iterator>
151 #include <limits>
152 #include <memory>
153 #include <string>
154 #include <tuple>
155 #include <utility>
156 
157 using namespace llvm;
158 
159 #define LV_NAME "loop-vectorize"
160 #define DEBUG_TYPE LV_NAME
161 
162 #ifndef NDEBUG
163 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
164 #endif
165 
166 /// @{
167 /// Metadata attribute names
168 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
169 const char LLVMLoopVectorizeFollowupVectorized[] =
170     "llvm.loop.vectorize.followup_vectorized";
171 const char LLVMLoopVectorizeFollowupEpilogue[] =
172     "llvm.loop.vectorize.followup_epilogue";
173 /// @}
174 
175 STATISTIC(LoopsVectorized, "Number of loops vectorized");
176 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
177 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
178 
179 static cl::opt<bool> EnableEpilogueVectorization(
180     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
181     cl::desc("Enable vectorization of epilogue loops."));
182 
183 static cl::opt<unsigned> EpilogueVectorizationForceVF(
184     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
185     cl::desc("When epilogue vectorization is enabled, and a value greater than "
186              "1 is specified, forces the given VF for all applicable epilogue "
187              "loops."));
188 
189 static cl::opt<unsigned> EpilogueVectorizationMinVF(
190     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
191     cl::desc("Only loops with vectorization factor equal to or larger than "
192              "the specified value are considered for epilogue vectorization."));
193 
194 /// Loops with a known constant trip count below this number are vectorized only
195 /// if no scalar iteration overheads are incurred.
196 static cl::opt<unsigned> TinyTripCountVectorThreshold(
197     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
198     cl::desc("Loops with a constant trip count that is smaller than this "
199              "value are vectorized only if no scalar iteration overheads "
200              "are incurred."));
201 
202 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
203     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
204     cl::desc("The maximum allowed number of runtime memory checks with a "
205              "vectorize(enable) pragma."));
206 
207 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
208 // that predication is preferred, and this lists all options. I.e., the
209 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
210 // and predicate the instructions accordingly. If tail-folding fails, there are
211 // different fallback strategies depending on these values:
212 namespace PreferPredicateTy {
213   enum Option {
214     ScalarEpilogue = 0,
215     PredicateElseScalarEpilogue,
216     PredicateOrDontVectorize
217   };
218 } // namespace PreferPredicateTy
219 
220 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
221     "prefer-predicate-over-epilogue",
222     cl::init(PreferPredicateTy::ScalarEpilogue),
223     cl::Hidden,
224     cl::desc("Tail-folding and predication preferences over creating a scalar "
225              "epilogue loop."),
226     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
227                          "scalar-epilogue",
228                          "Don't tail-predicate loops, create scalar epilogue"),
229               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
230                          "predicate-else-scalar-epilogue",
231                          "prefer tail-folding, create scalar epilogue if tail "
232                          "folding fails."),
233               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
234                          "predicate-dont-vectorize",
235                          "prefers tail-folding, don't attempt vectorization if "
236                          "tail-folding fails.")));
237 
238 static cl::opt<bool> MaximizeBandwidth(
239     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
240     cl::desc("Maximize bandwidth when selecting vectorization factor which "
241              "will be determined by the smallest type in loop."));
242 
243 static cl::opt<bool> EnableInterleavedMemAccesses(
244     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
245     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
246 
247 /// An interleave-group may need masking if it resides in a block that needs
248 /// predication, or in order to mask away gaps.
249 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
250     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
251     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
252 
253 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
254     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
255     cl::desc("We don't interleave loops with a estimated constant trip count "
256              "below this number"));
257 
258 static cl::opt<unsigned> ForceTargetNumScalarRegs(
259     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
260     cl::desc("A flag that overrides the target's number of scalar registers."));
261 
262 static cl::opt<unsigned> ForceTargetNumVectorRegs(
263     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
264     cl::desc("A flag that overrides the target's number of vector registers."));
265 
266 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
267     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
268     cl::desc("A flag that overrides the target's max interleave factor for "
269              "scalar loops."));
270 
271 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
272     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
273     cl::desc("A flag that overrides the target's max interleave factor for "
274              "vectorized loops."));
275 
276 static cl::opt<unsigned> ForceTargetInstructionCost(
277     "force-target-instruction-cost", cl::init(0), cl::Hidden,
278     cl::desc("A flag that overrides the target's expected cost for "
279              "an instruction to a single constant value. Mostly "
280              "useful for getting consistent testing."));
281 
282 static cl::opt<bool> ForceTargetSupportsScalableVectors(
283     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
284     cl::desc(
285         "Pretend that scalable vectors are supported, even if the target does "
286         "not support them. This flag should only be used for testing."));
287 
288 static cl::opt<unsigned> SmallLoopCost(
289     "small-loop-cost", cl::init(20), cl::Hidden,
290     cl::desc(
291         "The cost of a loop that is considered 'small' by the interleaver."));
292 
293 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
294     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
295     cl::desc("Enable the use of the block frequency analysis to access PGO "
296              "heuristics minimizing code growth in cold regions and being more "
297              "aggressive in hot regions."));
298 
299 // Runtime interleave loops for load/store throughput.
300 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
301     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
302     cl::desc(
303         "Enable runtime interleaving until load/store ports are saturated"));
304 
305 /// Interleave small loops with scalar reductions.
306 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
307     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
308     cl::desc("Enable interleaving for loops with small iteration counts that "
309              "contain scalar reductions to expose ILP."));
310 
311 /// The number of stores in a loop that are allowed to need predication.
312 static cl::opt<unsigned> NumberOfStoresToPredicate(
313     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
314     cl::desc("Max number of stores to be predicated behind an if."));
315 
316 static cl::opt<bool> EnableIndVarRegisterHeur(
317     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
318     cl::desc("Count the induction variable only once when interleaving"));
319 
320 static cl::opt<bool> EnableCondStoresVectorization(
321     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
322     cl::desc("Enable if predication of stores during vectorization."));
323 
324 static cl::opt<unsigned> MaxNestedScalarReductionIC(
325     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
326     cl::desc("The maximum interleave count to use when interleaving a scalar "
327              "reduction in a nested loop."));
328 
329 static cl::opt<bool>
330     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
331                            cl::Hidden,
332                            cl::desc("Prefer in-loop vector reductions, "
333                                     "overriding the targets preference."));
334 
335 cl::opt<bool> EnableStrictReductions(
336     "enable-strict-reductions", cl::init(false), cl::Hidden,
337     cl::desc("Enable the vectorisation of loops with in-order (strict) "
338              "FP reductions"));
339 
340 static cl::opt<bool> PreferPredicatedReductionSelect(
341     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
342     cl::desc(
343         "Prefer predicating a reduction operation over an after loop select."));
344 
345 cl::opt<bool> EnableVPlanNativePath(
346     "enable-vplan-native-path", cl::init(false), cl::Hidden,
347     cl::desc("Enable VPlan-native vectorization path with "
348              "support for outer loop vectorization."));
349 
350 // FIXME: Remove this switch once we have divergence analysis. Currently we
351 // assume divergent non-backedge branches when this switch is true.
352 cl::opt<bool> EnableVPlanPredication(
353     "enable-vplan-predication", cl::init(false), cl::Hidden,
354     cl::desc("Enable VPlan-native vectorization path predicator with "
355              "support for outer loop vectorization."));
356 
357 // This flag enables the stress testing of the VPlan H-CFG construction in the
358 // VPlan-native vectorization path. It must be used in conjuction with
359 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
360 // verification of the H-CFGs built.
361 static cl::opt<bool> VPlanBuildStressTest(
362     "vplan-build-stress-test", cl::init(false), cl::Hidden,
363     cl::desc(
364         "Build VPlan for every supported loop nest in the function and bail "
365         "out right after the build (stress test the VPlan H-CFG construction "
366         "in the VPlan-native vectorization path)."));
367 
368 cl::opt<bool> llvm::EnableLoopInterleaving(
369     "interleave-loops", cl::init(true), cl::Hidden,
370     cl::desc("Enable loop interleaving in Loop vectorization passes"));
371 cl::opt<bool> llvm::EnableLoopVectorization(
372     "vectorize-loops", cl::init(true), cl::Hidden,
373     cl::desc("Run the Loop vectorization passes"));
374 
375 cl::opt<bool> PrintVPlansInDotFormat(
376     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
377     cl::desc("Use dot format instead of plain text when dumping VPlans"));
378 
379 /// A helper function that returns true if the given type is irregular. The
380 /// type is irregular if its allocated size doesn't equal the store size of an
381 /// element of the corresponding vector type.
382 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
383   // Determine if an array of N elements of type Ty is "bitcast compatible"
384   // with a <N x Ty> vector.
385   // This is only true if there is no padding between the array elements.
386   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
387 }
388 
389 /// A helper function that returns the reciprocal of the block probability of
390 /// predicated blocks. If we return X, we are assuming the predicated block
391 /// will execute once for every X iterations of the loop header.
392 ///
393 /// TODO: We should use actual block probability here, if available. Currently,
394 ///       we always assume predicated blocks have a 50% chance of executing.
395 static unsigned getReciprocalPredBlockProb() { return 2; }
396 
397 /// A helper function that returns an integer or floating-point constant with
398 /// value C.
399 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
400   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
401                            : ConstantFP::get(Ty, C);
402 }
403 
404 /// Returns "best known" trip count for the specified loop \p L as defined by
405 /// the following procedure:
406 ///   1) Returns exact trip count if it is known.
407 ///   2) Returns expected trip count according to profile data if any.
408 ///   3) Returns upper bound estimate if it is known.
409 ///   4) Returns None if all of the above failed.
410 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
411   // Check if exact trip count is known.
412   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
413     return ExpectedTC;
414 
415   // Check if there is an expected trip count available from profile data.
416   if (LoopVectorizeWithBlockFrequency)
417     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
418       return EstimatedTC;
419 
420   // Check if upper bound estimate is known.
421   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
422     return ExpectedTC;
423 
424   return None;
425 }
426 
427 // Forward declare GeneratedRTChecks.
428 class GeneratedRTChecks;
429 
430 namespace llvm {
431 
432 /// InnerLoopVectorizer vectorizes loops which contain only one basic
433 /// block to a specified vectorization factor (VF).
434 /// This class performs the widening of scalars into vectors, or multiple
435 /// scalars. This class also implements the following features:
436 /// * It inserts an epilogue loop for handling loops that don't have iteration
437 ///   counts that are known to be a multiple of the vectorization factor.
438 /// * It handles the code generation for reduction variables.
439 /// * Scalarization (implementation using scalars) of un-vectorizable
440 ///   instructions.
441 /// InnerLoopVectorizer does not perform any vectorization-legality
442 /// checks, and relies on the caller to check for the different legality
443 /// aspects. The InnerLoopVectorizer relies on the
444 /// LoopVectorizationLegality class to provide information about the induction
445 /// and reduction variables that were found to a given vectorization factor.
446 class InnerLoopVectorizer {
447 public:
448   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
449                       LoopInfo *LI, DominatorTree *DT,
450                       const TargetLibraryInfo *TLI,
451                       const TargetTransformInfo *TTI, AssumptionCache *AC,
452                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
453                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
454                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
455                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
456       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
457         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
458         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
459         PSI(PSI), RTChecks(RTChecks) {
460     // Query this against the original loop and save it here because the profile
461     // of the original loop header may change as the transformation happens.
462     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
463         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
464   }
465 
466   virtual ~InnerLoopVectorizer() = default;
467 
468   /// Create a new empty loop that will contain vectorized instructions later
469   /// on, while the old loop will be used as the scalar remainder. Control flow
470   /// is generated around the vectorized (and scalar epilogue) loops consisting
471   /// of various checks and bypasses. Return the pre-header block of the new
472   /// loop.
473   /// In the case of epilogue vectorization, this function is overriden to
474   /// handle the more complex control flow around the loops.
475   virtual BasicBlock *createVectorizedLoopSkeleton();
476 
477   /// Widen a single instruction within the innermost loop.
478   void widenInstruction(Instruction &I, VPValue *Def, VPUser &Operands,
479                         VPTransformState &State);
480 
481   /// Widen a single call instruction within the innermost loop.
482   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
483                             VPTransformState &State);
484 
485   /// Widen a single select instruction within the innermost loop.
486   void widenSelectInstruction(SelectInst &I, VPValue *VPDef, VPUser &Operands,
487                               bool InvariantCond, VPTransformState &State);
488 
489   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
490   void fixVectorizedLoop(VPTransformState &State);
491 
492   // Return true if any runtime check is added.
493   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
494 
495   /// A type for vectorized values in the new loop. Each value from the
496   /// original loop, when vectorized, is represented by UF vector values in the
497   /// new unrolled loop, where UF is the unroll factor.
498   using VectorParts = SmallVector<Value *, 2>;
499 
500   /// Vectorize a single GetElementPtrInst based on information gathered and
501   /// decisions taken during planning.
502   void widenGEP(GetElementPtrInst *GEP, VPValue *VPDef, VPUser &Indices,
503                 unsigned UF, ElementCount VF, bool IsPtrLoopInvariant,
504                 SmallBitVector &IsIndexLoopInvariant, VPTransformState &State);
505 
506   /// Vectorize a single PHINode in a block. This method handles the induction
507   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
508   /// arbitrary length vectors.
509   void widenPHIInstruction(Instruction *PN, RecurrenceDescriptor *RdxDesc,
510                            VPWidenPHIRecipe *PhiR, VPTransformState &State);
511 
512   /// A helper function to scalarize a single Instruction in the innermost loop.
513   /// Generates a sequence of scalar instances for each lane between \p MinLane
514   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
515   /// inclusive. Uses the VPValue operands from \p Operands instead of \p
516   /// Instr's operands.
517   void scalarizeInstruction(Instruction *Instr, VPValue *Def, VPUser &Operands,
518                             const VPIteration &Instance, bool IfPredicateInstr,
519                             VPTransformState &State);
520 
521   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
522   /// is provided, the integer induction variable will first be truncated to
523   /// the corresponding type.
524   void widenIntOrFpInduction(PHINode *IV, Value *Start, TruncInst *Trunc,
525                              VPValue *Def, VPValue *CastDef,
526                              VPTransformState &State);
527 
528   /// Construct the vector value of a scalarized value \p V one lane at a time.
529   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
530                                  VPTransformState &State);
531 
532   /// Try to vectorize interleaved access group \p Group with the base address
533   /// given in \p Addr, optionally masking the vector operations if \p
534   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
535   /// values in the vectorized loop.
536   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
537                                 ArrayRef<VPValue *> VPDefs,
538                                 VPTransformState &State, VPValue *Addr,
539                                 ArrayRef<VPValue *> StoredValues,
540                                 VPValue *BlockInMask = nullptr);
541 
542   /// Vectorize Load and Store instructions with the base address given in \p
543   /// Addr, optionally masking the vector operations if \p BlockInMask is
544   /// non-null. Use \p State to translate given VPValues to IR values in the
545   /// vectorized loop.
546   void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
547                                   VPValue *Def, VPValue *Addr,
548                                   VPValue *StoredValue, VPValue *BlockInMask);
549 
550   /// Set the debug location in the builder using the debug location in
551   /// the instruction.
552   void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
553 
554   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
555   void fixNonInductionPHIs(VPTransformState &State);
556 
557   /// Returns true if the reordering of FP operations is not allowed, but we are
558   /// able to vectorize with strict in-order reductions for the given RdxDesc.
559   bool useOrderedReductions(RecurrenceDescriptor &RdxDesc);
560 
561   /// Create a broadcast instruction. This method generates a broadcast
562   /// instruction (shuffle) for loop invariant values and for the induction
563   /// value. If this is the induction variable then we extend it to N, N+1, ...
564   /// this is needed because each iteration in the loop corresponds to a SIMD
565   /// element.
566   virtual Value *getBroadcastInstrs(Value *V);
567 
568 protected:
569   friend class LoopVectorizationPlanner;
570 
571   /// A small list of PHINodes.
572   using PhiVector = SmallVector<PHINode *, 4>;
573 
574   /// A type for scalarized values in the new loop. Each value from the
575   /// original loop, when scalarized, is represented by UF x VF scalar values
576   /// in the new unrolled loop, where UF is the unroll factor and VF is the
577   /// vectorization factor.
578   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
579 
580   /// Set up the values of the IVs correctly when exiting the vector loop.
581   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
582                     Value *CountRoundDown, Value *EndValue,
583                     BasicBlock *MiddleBlock);
584 
585   /// Create a new induction variable inside L.
586   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
587                                    Value *Step, Instruction *DL);
588 
589   /// Handle all cross-iteration phis in the header.
590   void fixCrossIterationPHIs(VPTransformState &State);
591 
592   /// Fix a first-order recurrence. This is the second phase of vectorizing
593   /// this phi node.
594   void fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR, VPTransformState &State);
595 
596   /// Fix a reduction cross-iteration phi. This is the second phase of
597   /// vectorizing this phi node.
598   void fixReduction(VPWidenPHIRecipe *Phi, VPTransformState &State);
599 
600   /// Clear NSW/NUW flags from reduction instructions if necessary.
601   void clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
602                                VPTransformState &State);
603 
604   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
605   /// means we need to add the appropriate incoming value from the middle
606   /// block as exiting edges from the scalar epilogue loop (if present) are
607   /// already in place, and we exit the vector loop exclusively to the middle
608   /// block.
609   void fixLCSSAPHIs(VPTransformState &State);
610 
611   /// Iteratively sink the scalarized operands of a predicated instruction into
612   /// the block that was created for it.
613   void sinkScalarOperands(Instruction *PredInst);
614 
615   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
616   /// represented as.
617   void truncateToMinimalBitwidths(VPTransformState &State);
618 
619   /// This function adds
620   /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
621   /// to each vector element of Val. The sequence starts at StartIndex.
622   /// \p Opcode is relevant for FP induction variable.
623   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
624                                Instruction::BinaryOps Opcode =
625                                Instruction::BinaryOpsEnd);
626 
627   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
628   /// variable on which to base the steps, \p Step is the size of the step, and
629   /// \p EntryVal is the value from the original loop that maps to the steps.
630   /// Note that \p EntryVal doesn't have to be an induction variable - it
631   /// can also be a truncate instruction.
632   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
633                         const InductionDescriptor &ID, VPValue *Def,
634                         VPValue *CastDef, VPTransformState &State);
635 
636   /// Create a vector induction phi node based on an existing scalar one. \p
637   /// EntryVal is the value from the original loop that maps to the vector phi
638   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
639   /// truncate instruction, instead of widening the original IV, we widen a
640   /// version of the IV truncated to \p EntryVal's type.
641   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
642                                        Value *Step, Value *Start,
643                                        Instruction *EntryVal, VPValue *Def,
644                                        VPValue *CastDef,
645                                        VPTransformState &State);
646 
647   /// Returns true if an instruction \p I should be scalarized instead of
648   /// vectorized for the chosen vectorization factor.
649   bool shouldScalarizeInstruction(Instruction *I) const;
650 
651   /// Returns true if we should generate a scalar version of \p IV.
652   bool needsScalarInduction(Instruction *IV) const;
653 
654   /// If there is a cast involved in the induction variable \p ID, which should
655   /// be ignored in the vectorized loop body, this function records the
656   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
657   /// cast. We had already proved that the casted Phi is equal to the uncasted
658   /// Phi in the vectorized loop (under a runtime guard), and therefore
659   /// there is no need to vectorize the cast - the same value can be used in the
660   /// vector loop for both the Phi and the cast.
661   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
662   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
663   ///
664   /// \p EntryVal is the value from the original loop that maps to the vector
665   /// phi node and is used to distinguish what is the IV currently being
666   /// processed - original one (if \p EntryVal is a phi corresponding to the
667   /// original IV) or the "newly-created" one based on the proof mentioned above
668   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
669   /// latter case \p EntryVal is a TruncInst and we must not record anything for
670   /// that IV, but it's error-prone to expect callers of this routine to care
671   /// about that, hence this explicit parameter.
672   void recordVectorLoopValueForInductionCast(
673       const InductionDescriptor &ID, const Instruction *EntryVal,
674       Value *VectorLoopValue, VPValue *CastDef, VPTransformState &State,
675       unsigned Part, unsigned Lane = UINT_MAX);
676 
677   /// Generate a shuffle sequence that will reverse the vector Vec.
678   virtual Value *reverseVector(Value *Vec);
679 
680   /// Returns (and creates if needed) the original loop trip count.
681   Value *getOrCreateTripCount(Loop *NewLoop);
682 
683   /// Returns (and creates if needed) the trip count of the widened loop.
684   Value *getOrCreateVectorTripCount(Loop *NewLoop);
685 
686   /// Returns a bitcasted value to the requested vector type.
687   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
688   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
689                                 const DataLayout &DL);
690 
691   /// Emit a bypass check to see if the vector trip count is zero, including if
692   /// it overflows.
693   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
694 
695   /// Emit a bypass check to see if all of the SCEV assumptions we've
696   /// had to make are correct. Returns the block containing the checks or
697   /// nullptr if no checks have been added.
698   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
699 
700   /// Emit bypass checks to check any memory assumptions we may have made.
701   /// Returns the block containing the checks or nullptr if no checks have been
702   /// added.
703   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
704 
705   /// Compute the transformed value of Index at offset StartValue using step
706   /// StepValue.
707   /// For integer induction, returns StartValue + Index * StepValue.
708   /// For pointer induction, returns StartValue[Index * StepValue].
709   /// FIXME: The newly created binary instructions should contain nsw/nuw
710   /// flags, which can be found from the original scalar operations.
711   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
712                               const DataLayout &DL,
713                               const InductionDescriptor &ID) const;
714 
715   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
716   /// vector loop preheader, middle block and scalar preheader. Also
717   /// allocate a loop object for the new vector loop and return it.
718   Loop *createVectorLoopSkeleton(StringRef Prefix);
719 
720   /// Create new phi nodes for the induction variables to resume iteration count
721   /// in the scalar epilogue, from where the vectorized loop left off (given by
722   /// \p VectorTripCount).
723   /// In cases where the loop skeleton is more complicated (eg. epilogue
724   /// vectorization) and the resume values can come from an additional bypass
725   /// block, the \p AdditionalBypass pair provides information about the bypass
726   /// block and the end value on the edge from bypass to this loop.
727   void createInductionResumeValues(
728       Loop *L, Value *VectorTripCount,
729       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
730 
731   /// Complete the loop skeleton by adding debug MDs, creating appropriate
732   /// conditional branches in the middle block, preparing the builder and
733   /// running the verifier. Take in the vector loop \p L as argument, and return
734   /// the preheader of the completed vector loop.
735   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
736 
737   /// Add additional metadata to \p To that was not present on \p Orig.
738   ///
739   /// Currently this is used to add the noalias annotations based on the
740   /// inserted memchecks.  Use this for instructions that are *cloned* into the
741   /// vector loop.
742   void addNewMetadata(Instruction *To, const Instruction *Orig);
743 
744   /// Add metadata from one instruction to another.
745   ///
746   /// This includes both the original MDs from \p From and additional ones (\see
747   /// addNewMetadata).  Use this for *newly created* instructions in the vector
748   /// loop.
749   void addMetadata(Instruction *To, Instruction *From);
750 
751   /// Similar to the previous function but it adds the metadata to a
752   /// vector of instructions.
753   void addMetadata(ArrayRef<Value *> To, Instruction *From);
754 
755   /// Allow subclasses to override and print debug traces before/after vplan
756   /// execution, when trace information is requested.
757   virtual void printDebugTracesAtStart(){};
758   virtual void printDebugTracesAtEnd(){};
759 
760   /// The original loop.
761   Loop *OrigLoop;
762 
763   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
764   /// dynamic knowledge to simplify SCEV expressions and converts them to a
765   /// more usable form.
766   PredicatedScalarEvolution &PSE;
767 
768   /// Loop Info.
769   LoopInfo *LI;
770 
771   /// Dominator Tree.
772   DominatorTree *DT;
773 
774   /// Alias Analysis.
775   AAResults *AA;
776 
777   /// Target Library Info.
778   const TargetLibraryInfo *TLI;
779 
780   /// Target Transform Info.
781   const TargetTransformInfo *TTI;
782 
783   /// Assumption Cache.
784   AssumptionCache *AC;
785 
786   /// Interface to emit optimization remarks.
787   OptimizationRemarkEmitter *ORE;
788 
789   /// LoopVersioning.  It's only set up (non-null) if memchecks were
790   /// used.
791   ///
792   /// This is currently only used to add no-alias metadata based on the
793   /// memchecks.  The actually versioning is performed manually.
794   std::unique_ptr<LoopVersioning> LVer;
795 
796   /// The vectorization SIMD factor to use. Each vector will have this many
797   /// vector elements.
798   ElementCount VF;
799 
800   /// The vectorization unroll factor to use. Each scalar is vectorized to this
801   /// many different vector instructions.
802   unsigned UF;
803 
804   /// The builder that we use
805   IRBuilder<> Builder;
806 
807   // --- Vectorization state ---
808 
809   /// The vector-loop preheader.
810   BasicBlock *LoopVectorPreHeader;
811 
812   /// The scalar-loop preheader.
813   BasicBlock *LoopScalarPreHeader;
814 
815   /// Middle Block between the vector and the scalar.
816   BasicBlock *LoopMiddleBlock;
817 
818   /// The (unique) ExitBlock of the scalar loop.  Note that
819   /// there can be multiple exiting edges reaching this block.
820   BasicBlock *LoopExitBlock;
821 
822   /// The vector loop body.
823   BasicBlock *LoopVectorBody;
824 
825   /// The scalar loop body.
826   BasicBlock *LoopScalarBody;
827 
828   /// A list of all bypass blocks. The first block is the entry of the loop.
829   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
830 
831   /// The new Induction variable which was added to the new block.
832   PHINode *Induction = nullptr;
833 
834   /// The induction variable of the old basic block.
835   PHINode *OldInduction = nullptr;
836 
837   /// Store instructions that were predicated.
838   SmallVector<Instruction *, 4> PredicatedInstructions;
839 
840   /// Trip count of the original loop.
841   Value *TripCount = nullptr;
842 
843   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
844   Value *VectorTripCount = nullptr;
845 
846   /// The legality analysis.
847   LoopVectorizationLegality *Legal;
848 
849   /// The profitablity analysis.
850   LoopVectorizationCostModel *Cost;
851 
852   // Record whether runtime checks are added.
853   bool AddedSafetyChecks = false;
854 
855   // Holds the end values for each induction variable. We save the end values
856   // so we can later fix-up the external users of the induction variables.
857   DenseMap<PHINode *, Value *> IVEndValues;
858 
859   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
860   // fixed up at the end of vector code generation.
861   SmallVector<PHINode *, 8> OrigPHIsToFix;
862 
863   /// BFI and PSI are used to check for profile guided size optimizations.
864   BlockFrequencyInfo *BFI;
865   ProfileSummaryInfo *PSI;
866 
867   // Whether this loop should be optimized for size based on profile guided size
868   // optimizatios.
869   bool OptForSizeBasedOnProfile;
870 
871   /// Structure to hold information about generated runtime checks, responsible
872   /// for cleaning the checks, if vectorization turns out unprofitable.
873   GeneratedRTChecks &RTChecks;
874 };
875 
876 class InnerLoopUnroller : public InnerLoopVectorizer {
877 public:
878   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
879                     LoopInfo *LI, DominatorTree *DT,
880                     const TargetLibraryInfo *TLI,
881                     const TargetTransformInfo *TTI, AssumptionCache *AC,
882                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
883                     LoopVectorizationLegality *LVL,
884                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
885                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
886       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
887                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
888                             BFI, PSI, Check) {}
889 
890 private:
891   Value *getBroadcastInstrs(Value *V) override;
892   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
893                        Instruction::BinaryOps Opcode =
894                        Instruction::BinaryOpsEnd) override;
895   Value *reverseVector(Value *Vec) override;
896 };
897 
898 /// Encapsulate information regarding vectorization of a loop and its epilogue.
899 /// This information is meant to be updated and used across two stages of
900 /// epilogue vectorization.
901 struct EpilogueLoopVectorizationInfo {
902   ElementCount MainLoopVF = ElementCount::getFixed(0);
903   unsigned MainLoopUF = 0;
904   ElementCount EpilogueVF = ElementCount::getFixed(0);
905   unsigned EpilogueUF = 0;
906   BasicBlock *MainLoopIterationCountCheck = nullptr;
907   BasicBlock *EpilogueIterationCountCheck = nullptr;
908   BasicBlock *SCEVSafetyCheck = nullptr;
909   BasicBlock *MemSafetyCheck = nullptr;
910   Value *TripCount = nullptr;
911   Value *VectorTripCount = nullptr;
912 
913   EpilogueLoopVectorizationInfo(unsigned MVF, unsigned MUF, unsigned EVF,
914                                 unsigned EUF)
915       : MainLoopVF(ElementCount::getFixed(MVF)), MainLoopUF(MUF),
916         EpilogueVF(ElementCount::getFixed(EVF)), EpilogueUF(EUF) {
917     assert(EUF == 1 &&
918            "A high UF for the epilogue loop is likely not beneficial.");
919   }
920 };
921 
922 /// An extension of the inner loop vectorizer that creates a skeleton for a
923 /// vectorized loop that has its epilogue (residual) also vectorized.
924 /// The idea is to run the vplan on a given loop twice, firstly to setup the
925 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
926 /// from the first step and vectorize the epilogue.  This is achieved by
927 /// deriving two concrete strategy classes from this base class and invoking
928 /// them in succession from the loop vectorizer planner.
929 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
930 public:
931   InnerLoopAndEpilogueVectorizer(
932       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
933       DominatorTree *DT, const TargetLibraryInfo *TLI,
934       const TargetTransformInfo *TTI, AssumptionCache *AC,
935       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
936       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
937       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
938       GeneratedRTChecks &Checks)
939       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
940                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
941                             Checks),
942         EPI(EPI) {}
943 
944   // Override this function to handle the more complex control flow around the
945   // three loops.
946   BasicBlock *createVectorizedLoopSkeleton() final override {
947     return createEpilogueVectorizedLoopSkeleton();
948   }
949 
950   /// The interface for creating a vectorized skeleton using one of two
951   /// different strategies, each corresponding to one execution of the vplan
952   /// as described above.
953   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
954 
955   /// Holds and updates state information required to vectorize the main loop
956   /// and its epilogue in two separate passes. This setup helps us avoid
957   /// regenerating and recomputing runtime safety checks. It also helps us to
958   /// shorten the iteration-count-check path length for the cases where the
959   /// iteration count of the loop is so small that the main vector loop is
960   /// completely skipped.
961   EpilogueLoopVectorizationInfo &EPI;
962 };
963 
964 /// A specialized derived class of inner loop vectorizer that performs
965 /// vectorization of *main* loops in the process of vectorizing loops and their
966 /// epilogues.
967 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
968 public:
969   EpilogueVectorizerMainLoop(
970       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
971       DominatorTree *DT, const TargetLibraryInfo *TLI,
972       const TargetTransformInfo *TTI, AssumptionCache *AC,
973       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
974       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
975       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
976       GeneratedRTChecks &Check)
977       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
978                                        EPI, LVL, CM, BFI, PSI, Check) {}
979   /// Implements the interface for creating a vectorized skeleton using the
980   /// *main loop* strategy (ie the first pass of vplan execution).
981   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
982 
983 protected:
984   /// Emits an iteration count bypass check once for the main loop (when \p
985   /// ForEpilogue is false) and once for the epilogue loop (when \p
986   /// ForEpilogue is true).
987   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
988                                              bool ForEpilogue);
989   void printDebugTracesAtStart() override;
990   void printDebugTracesAtEnd() override;
991 };
992 
993 // A specialized derived class of inner loop vectorizer that performs
994 // vectorization of *epilogue* loops in the process of vectorizing loops and
995 // their epilogues.
996 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
997 public:
998   EpilogueVectorizerEpilogueLoop(
999       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
1000       DominatorTree *DT, const TargetLibraryInfo *TLI,
1001       const TargetTransformInfo *TTI, AssumptionCache *AC,
1002       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
1003       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
1004       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
1005       GeneratedRTChecks &Checks)
1006       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
1007                                        EPI, LVL, CM, BFI, PSI, Checks) {}
1008   /// Implements the interface for creating a vectorized skeleton using the
1009   /// *epilogue loop* strategy (ie the second pass of vplan execution).
1010   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
1011 
1012 protected:
1013   /// Emits an iteration count bypass check after the main vector loop has
1014   /// finished to see if there are any iterations left to execute by either
1015   /// the vector epilogue or the scalar epilogue.
1016   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
1017                                                       BasicBlock *Bypass,
1018                                                       BasicBlock *Insert);
1019   void printDebugTracesAtStart() override;
1020   void printDebugTracesAtEnd() override;
1021 };
1022 } // end namespace llvm
1023 
1024 /// Look for a meaningful debug location on the instruction or it's
1025 /// operands.
1026 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
1027   if (!I)
1028     return I;
1029 
1030   DebugLoc Empty;
1031   if (I->getDebugLoc() != Empty)
1032     return I;
1033 
1034   for (Use &Op : I->operands()) {
1035     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1036       if (OpInst->getDebugLoc() != Empty)
1037         return OpInst;
1038   }
1039 
1040   return I;
1041 }
1042 
1043 void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
1044   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
1045     const DILocation *DIL = Inst->getDebugLoc();
1046 
1047     // When a FSDiscriminator is enabled, we don't need to add the multiply
1048     // factors to the discriminators.
1049     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1050         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
1051       // FIXME: For scalable vectors, assume vscale=1.
1052       auto NewDIL =
1053           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1054       if (NewDIL)
1055         B.SetCurrentDebugLocation(NewDIL.getValue());
1056       else
1057         LLVM_DEBUG(dbgs()
1058                    << "Failed to create new discriminator: "
1059                    << DIL->getFilename() << " Line: " << DIL->getLine());
1060     } else
1061       B.SetCurrentDebugLocation(DIL);
1062   } else
1063     B.SetCurrentDebugLocation(DebugLoc());
1064 }
1065 
1066 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
1067 /// is passed, the message relates to that particular instruction.
1068 #ifndef NDEBUG
1069 static void debugVectorizationMessage(const StringRef Prefix,
1070                                       const StringRef DebugMsg,
1071                                       Instruction *I) {
1072   dbgs() << "LV: " << Prefix << DebugMsg;
1073   if (I != nullptr)
1074     dbgs() << " " << *I;
1075   else
1076     dbgs() << '.';
1077   dbgs() << '\n';
1078 }
1079 #endif
1080 
1081 /// Create an analysis remark that explains why vectorization failed
1082 ///
1083 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1084 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1085 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1086 /// the location of the remark.  \return the remark object that can be
1087 /// streamed to.
1088 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1089     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1090   Value *CodeRegion = TheLoop->getHeader();
1091   DebugLoc DL = TheLoop->getStartLoc();
1092 
1093   if (I) {
1094     CodeRegion = I->getParent();
1095     // If there is no debug location attached to the instruction, revert back to
1096     // using the loop's.
1097     if (I->getDebugLoc())
1098       DL = I->getDebugLoc();
1099   }
1100 
1101   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
1102 }
1103 
1104 /// Return a value for Step multiplied by VF.
1105 static Value *createStepForVF(IRBuilder<> &B, Constant *Step, ElementCount VF) {
1106   assert(isa<ConstantInt>(Step) && "Expected an integer step");
1107   Constant *StepVal = ConstantInt::get(
1108       Step->getType(),
1109       cast<ConstantInt>(Step)->getSExtValue() * VF.getKnownMinValue());
1110   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1111 }
1112 
1113 namespace llvm {
1114 
1115 /// Return the runtime value for VF.
1116 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
1117   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1118   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1119 }
1120 
1121 void reportVectorizationFailure(const StringRef DebugMsg,
1122                                 const StringRef OREMsg, const StringRef ORETag,
1123                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1124                                 Instruction *I) {
1125   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1126   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1127   ORE->emit(
1128       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1129       << "loop not vectorized: " << OREMsg);
1130 }
1131 
1132 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1133                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1134                              Instruction *I) {
1135   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1136   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1137   ORE->emit(
1138       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1139       << Msg);
1140 }
1141 
1142 } // end namespace llvm
1143 
1144 #ifndef NDEBUG
1145 /// \return string containing a file name and a line # for the given loop.
1146 static std::string getDebugLocString(const Loop *L) {
1147   std::string Result;
1148   if (L) {
1149     raw_string_ostream OS(Result);
1150     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1151       LoopDbgLoc.print(OS);
1152     else
1153       // Just print the module name.
1154       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1155     OS.flush();
1156   }
1157   return Result;
1158 }
1159 #endif
1160 
1161 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1162                                          const Instruction *Orig) {
1163   // If the loop was versioned with memchecks, add the corresponding no-alias
1164   // metadata.
1165   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1166     LVer->annotateInstWithNoAlias(To, Orig);
1167 }
1168 
1169 void InnerLoopVectorizer::addMetadata(Instruction *To,
1170                                       Instruction *From) {
1171   propagateMetadata(To, From);
1172   addNewMetadata(To, From);
1173 }
1174 
1175 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1176                                       Instruction *From) {
1177   for (Value *V : To) {
1178     if (Instruction *I = dyn_cast<Instruction>(V))
1179       addMetadata(I, From);
1180   }
1181 }
1182 
1183 namespace llvm {
1184 
1185 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1186 // lowered.
1187 enum ScalarEpilogueLowering {
1188 
1189   // The default: allowing scalar epilogues.
1190   CM_ScalarEpilogueAllowed,
1191 
1192   // Vectorization with OptForSize: don't allow epilogues.
1193   CM_ScalarEpilogueNotAllowedOptSize,
1194 
1195   // A special case of vectorisation with OptForSize: loops with a very small
1196   // trip count are considered for vectorization under OptForSize, thereby
1197   // making sure the cost of their loop body is dominant, free of runtime
1198   // guards and scalar iteration overheads.
1199   CM_ScalarEpilogueNotAllowedLowTripLoop,
1200 
1201   // Loop hint predicate indicating an epilogue is undesired.
1202   CM_ScalarEpilogueNotNeededUsePredicate,
1203 
1204   // Directive indicating we must either tail fold or not vectorize
1205   CM_ScalarEpilogueNotAllowedUsePredicate
1206 };
1207 
1208 /// ElementCountComparator creates a total ordering for ElementCount
1209 /// for the purposes of using it in a set structure.
1210 struct ElementCountComparator {
1211   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1212     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1213            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1214   }
1215 };
1216 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1217 
1218 /// LoopVectorizationCostModel - estimates the expected speedups due to
1219 /// vectorization.
1220 /// In many cases vectorization is not profitable. This can happen because of
1221 /// a number of reasons. In this class we mainly attempt to predict the
1222 /// expected speedup/slowdowns due to the supported instruction set. We use the
1223 /// TargetTransformInfo to query the different backends for the cost of
1224 /// different operations.
1225 class LoopVectorizationCostModel {
1226 public:
1227   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1228                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1229                              LoopVectorizationLegality *Legal,
1230                              const TargetTransformInfo &TTI,
1231                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1232                              AssumptionCache *AC,
1233                              OptimizationRemarkEmitter *ORE, const Function *F,
1234                              const LoopVectorizeHints *Hints,
1235                              InterleavedAccessInfo &IAI)
1236       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1237         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1238         Hints(Hints), InterleaveInfo(IAI) {}
1239 
1240   /// \return An upper bound for the vectorization factors (both fixed and
1241   /// scalable). If the factors are 0, vectorization and interleaving should be
1242   /// avoided up front.
1243   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1244 
1245   /// \return True if runtime checks are required for vectorization, and false
1246   /// otherwise.
1247   bool runtimeChecksRequired();
1248 
1249   /// \return The most profitable vectorization factor and the cost of that VF.
1250   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1251   /// then this vectorization factor will be selected if vectorization is
1252   /// possible.
1253   VectorizationFactor
1254   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1255 
1256   VectorizationFactor
1257   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1258                                     const LoopVectorizationPlanner &LVP);
1259 
1260   /// Setup cost-based decisions for user vectorization factor.
1261   void selectUserVectorizationFactor(ElementCount UserVF) {
1262     collectUniformsAndScalars(UserVF);
1263     collectInstsToScalarize(UserVF);
1264   }
1265 
1266   /// \return The size (in bits) of the smallest and widest types in the code
1267   /// that needs to be vectorized. We ignore values that remain scalar such as
1268   /// 64 bit loop indices.
1269   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1270 
1271   /// \return The desired interleave count.
1272   /// If interleave count has been specified by metadata it will be returned.
1273   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1274   /// are the selected vectorization factor and the cost of the selected VF.
1275   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1276 
1277   /// Memory access instruction may be vectorized in more than one way.
1278   /// Form of instruction after vectorization depends on cost.
1279   /// This function takes cost-based decisions for Load/Store instructions
1280   /// and collects them in a map. This decisions map is used for building
1281   /// the lists of loop-uniform and loop-scalar instructions.
1282   /// The calculated cost is saved with widening decision in order to
1283   /// avoid redundant calculations.
1284   void setCostBasedWideningDecision(ElementCount VF);
1285 
1286   /// A struct that represents some properties of the register usage
1287   /// of a loop.
1288   struct RegisterUsage {
1289     /// Holds the number of loop invariant values that are used in the loop.
1290     /// The key is ClassID of target-provided register class.
1291     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1292     /// Holds the maximum number of concurrent live intervals in the loop.
1293     /// The key is ClassID of target-provided register class.
1294     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1295   };
1296 
1297   /// \return Returns information about the register usages of the loop for the
1298   /// given vectorization factors.
1299   SmallVector<RegisterUsage, 8>
1300   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1301 
1302   /// Collect values we want to ignore in the cost model.
1303   void collectValuesToIgnore();
1304 
1305   /// Split reductions into those that happen in the loop, and those that happen
1306   /// outside. In loop reductions are collected into InLoopReductionChains.
1307   void collectInLoopReductions();
1308 
1309   /// Returns true if we should use strict in-order reductions for the given
1310   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1311   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1312   /// of FP operations.
1313   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) {
1314     return EnableStrictReductions && !Hints->allowReordering() &&
1315            RdxDesc.isOrdered();
1316   }
1317 
1318   /// \returns The smallest bitwidth each instruction can be represented with.
1319   /// The vector equivalents of these instructions should be truncated to this
1320   /// type.
1321   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1322     return MinBWs;
1323   }
1324 
1325   /// \returns True if it is more profitable to scalarize instruction \p I for
1326   /// vectorization factor \p VF.
1327   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1328     assert(VF.isVector() &&
1329            "Profitable to scalarize relevant only for VF > 1.");
1330 
1331     // Cost model is not run in the VPlan-native path - return conservative
1332     // result until this changes.
1333     if (EnableVPlanNativePath)
1334       return false;
1335 
1336     auto Scalars = InstsToScalarize.find(VF);
1337     assert(Scalars != InstsToScalarize.end() &&
1338            "VF not yet analyzed for scalarization profitability");
1339     return Scalars->second.find(I) != Scalars->second.end();
1340   }
1341 
1342   /// Returns true if \p I is known to be uniform after vectorization.
1343   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1344     if (VF.isScalar())
1345       return true;
1346 
1347     // Cost model is not run in the VPlan-native path - return conservative
1348     // result until this changes.
1349     if (EnableVPlanNativePath)
1350       return false;
1351 
1352     auto UniformsPerVF = Uniforms.find(VF);
1353     assert(UniformsPerVF != Uniforms.end() &&
1354            "VF not yet analyzed for uniformity");
1355     return UniformsPerVF->second.count(I);
1356   }
1357 
1358   /// Returns true if \p I is known to be scalar after vectorization.
1359   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1360     if (VF.isScalar())
1361       return true;
1362 
1363     // Cost model is not run in the VPlan-native path - return conservative
1364     // result until this changes.
1365     if (EnableVPlanNativePath)
1366       return false;
1367 
1368     auto ScalarsPerVF = Scalars.find(VF);
1369     assert(ScalarsPerVF != Scalars.end() &&
1370            "Scalar values are not calculated for VF");
1371     return ScalarsPerVF->second.count(I);
1372   }
1373 
1374   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1375   /// for vectorization factor \p VF.
1376   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1377     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1378            !isProfitableToScalarize(I, VF) &&
1379            !isScalarAfterVectorization(I, VF);
1380   }
1381 
1382   /// Decision that was taken during cost calculation for memory instruction.
1383   enum InstWidening {
1384     CM_Unknown,
1385     CM_Widen,         // For consecutive accesses with stride +1.
1386     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1387     CM_Interleave,
1388     CM_GatherScatter,
1389     CM_Scalarize
1390   };
1391 
1392   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1393   /// instruction \p I and vector width \p VF.
1394   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1395                            InstructionCost Cost) {
1396     assert(VF.isVector() && "Expected VF >=2");
1397     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1398   }
1399 
1400   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1401   /// interleaving group \p Grp and vector width \p VF.
1402   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1403                            ElementCount VF, InstWidening W,
1404                            InstructionCost Cost) {
1405     assert(VF.isVector() && "Expected VF >=2");
1406     /// Broadcast this decicion to all instructions inside the group.
1407     /// But the cost will be assigned to one instruction only.
1408     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1409       if (auto *I = Grp->getMember(i)) {
1410         if (Grp->getInsertPos() == I)
1411           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1412         else
1413           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1414       }
1415     }
1416   }
1417 
1418   /// Return the cost model decision for the given instruction \p I and vector
1419   /// width \p VF. Return CM_Unknown if this instruction did not pass
1420   /// through the cost modeling.
1421   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1422     assert(VF.isVector() && "Expected VF to be a vector VF");
1423     // Cost model is not run in the VPlan-native path - return conservative
1424     // result until this changes.
1425     if (EnableVPlanNativePath)
1426       return CM_GatherScatter;
1427 
1428     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1429     auto Itr = WideningDecisions.find(InstOnVF);
1430     if (Itr == WideningDecisions.end())
1431       return CM_Unknown;
1432     return Itr->second.first;
1433   }
1434 
1435   /// Return the vectorization cost for the given instruction \p I and vector
1436   /// width \p VF.
1437   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1438     assert(VF.isVector() && "Expected VF >=2");
1439     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1440     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1441            "The cost is not calculated");
1442     return WideningDecisions[InstOnVF].second;
1443   }
1444 
1445   /// Return True if instruction \p I is an optimizable truncate whose operand
1446   /// is an induction variable. Such a truncate will be removed by adding a new
1447   /// induction variable with the destination type.
1448   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1449     // If the instruction is not a truncate, return false.
1450     auto *Trunc = dyn_cast<TruncInst>(I);
1451     if (!Trunc)
1452       return false;
1453 
1454     // Get the source and destination types of the truncate.
1455     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1456     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1457 
1458     // If the truncate is free for the given types, return false. Replacing a
1459     // free truncate with an induction variable would add an induction variable
1460     // update instruction to each iteration of the loop. We exclude from this
1461     // check the primary induction variable since it will need an update
1462     // instruction regardless.
1463     Value *Op = Trunc->getOperand(0);
1464     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1465       return false;
1466 
1467     // If the truncated value is not an induction variable, return false.
1468     return Legal->isInductionPhi(Op);
1469   }
1470 
1471   /// Collects the instructions to scalarize for each predicated instruction in
1472   /// the loop.
1473   void collectInstsToScalarize(ElementCount VF);
1474 
1475   /// Collect Uniform and Scalar values for the given \p VF.
1476   /// The sets depend on CM decision for Load/Store instructions
1477   /// that may be vectorized as interleave, gather-scatter or scalarized.
1478   void collectUniformsAndScalars(ElementCount VF) {
1479     // Do the analysis once.
1480     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1481       return;
1482     setCostBasedWideningDecision(VF);
1483     collectLoopUniforms(VF);
1484     collectLoopScalars(VF);
1485   }
1486 
1487   /// Returns true if the target machine supports masked store operation
1488   /// for the given \p DataType and kind of access to \p Ptr.
1489   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1490     return Legal->isConsecutivePtr(Ptr) &&
1491            TTI.isLegalMaskedStore(DataType, Alignment);
1492   }
1493 
1494   /// Returns true if the target machine supports masked load operation
1495   /// for the given \p DataType and kind of access to \p Ptr.
1496   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1497     return Legal->isConsecutivePtr(Ptr) &&
1498            TTI.isLegalMaskedLoad(DataType, Alignment);
1499   }
1500 
1501   /// Returns true if the target machine can represent \p V as a masked gather
1502   /// or scatter operation.
1503   bool isLegalGatherOrScatter(Value *V) {
1504     bool LI = isa<LoadInst>(V);
1505     bool SI = isa<StoreInst>(V);
1506     if (!LI && !SI)
1507       return false;
1508     auto *Ty = getLoadStoreType(V);
1509     Align Align = getLoadStoreAlignment(V);
1510     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1511            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1512   }
1513 
1514   /// Returns true if the target machine supports all of the reduction
1515   /// variables found for the given VF.
1516   bool canVectorizeReductions(ElementCount VF) {
1517     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1518       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1519       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1520     }));
1521   }
1522 
1523   /// Returns true if \p I is an instruction that will be scalarized with
1524   /// predication. Such instructions include conditional stores and
1525   /// instructions that may divide by zero.
1526   /// If a non-zero VF has been calculated, we check if I will be scalarized
1527   /// predication for that VF.
1528   bool isScalarWithPredication(Instruction *I) const;
1529 
1530   // Returns true if \p I is an instruction that will be predicated either
1531   // through scalar predication or masked load/store or masked gather/scatter.
1532   // Superset of instructions that return true for isScalarWithPredication.
1533   bool isPredicatedInst(Instruction *I) {
1534     if (!blockNeedsPredication(I->getParent()))
1535       return false;
1536     // Loads and stores that need some form of masked operation are predicated
1537     // instructions.
1538     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1539       return Legal->isMaskRequired(I);
1540     return isScalarWithPredication(I);
1541   }
1542 
1543   /// Returns true if \p I is a memory instruction with consecutive memory
1544   /// access that can be widened.
1545   bool
1546   memoryInstructionCanBeWidened(Instruction *I,
1547                                 ElementCount VF = ElementCount::getFixed(1));
1548 
1549   /// Returns true if \p I is a memory instruction in an interleaved-group
1550   /// of memory accesses that can be vectorized with wide vector loads/stores
1551   /// and shuffles.
1552   bool
1553   interleavedAccessCanBeWidened(Instruction *I,
1554                                 ElementCount VF = ElementCount::getFixed(1));
1555 
1556   /// Check if \p Instr belongs to any interleaved access group.
1557   bool isAccessInterleaved(Instruction *Instr) {
1558     return InterleaveInfo.isInterleaved(Instr);
1559   }
1560 
1561   /// Get the interleaved access group that \p Instr belongs to.
1562   const InterleaveGroup<Instruction> *
1563   getInterleavedAccessGroup(Instruction *Instr) {
1564     return InterleaveInfo.getInterleaveGroup(Instr);
1565   }
1566 
1567   /// Returns true if we're required to use a scalar epilogue for at least
1568   /// the final iteration of the original loop.
1569   bool requiresScalarEpilogue(ElementCount VF) const {
1570     if (!isScalarEpilogueAllowed())
1571       return false;
1572     // If we might exit from anywhere but the latch, must run the exiting
1573     // iteration in scalar form.
1574     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1575       return true;
1576     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1577   }
1578 
1579   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1580   /// loop hint annotation.
1581   bool isScalarEpilogueAllowed() const {
1582     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1583   }
1584 
1585   /// Returns true if all loop blocks should be masked to fold tail loop.
1586   bool foldTailByMasking() const { return FoldTailByMasking; }
1587 
1588   bool blockNeedsPredication(BasicBlock *BB) const {
1589     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1590   }
1591 
1592   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1593   /// nodes to the chain of instructions representing the reductions. Uses a
1594   /// MapVector to ensure deterministic iteration order.
1595   using ReductionChainMap =
1596       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1597 
1598   /// Return the chain of instructions representing an inloop reduction.
1599   const ReductionChainMap &getInLoopReductionChains() const {
1600     return InLoopReductionChains;
1601   }
1602 
1603   /// Returns true if the Phi is part of an inloop reduction.
1604   bool isInLoopReduction(PHINode *Phi) const {
1605     return InLoopReductionChains.count(Phi);
1606   }
1607 
1608   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1609   /// with factor VF.  Return the cost of the instruction, including
1610   /// scalarization overhead if it's needed.
1611   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1612 
1613   /// Estimate cost of a call instruction CI if it were vectorized with factor
1614   /// VF. Return the cost of the instruction, including scalarization overhead
1615   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1616   /// scalarized -
1617   /// i.e. either vector version isn't available, or is too expensive.
1618   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1619                                     bool &NeedToScalarize) const;
1620 
1621   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1622   /// that of B.
1623   bool isMoreProfitable(const VectorizationFactor &A,
1624                         const VectorizationFactor &B) const;
1625 
1626   /// Invalidates decisions already taken by the cost model.
1627   void invalidateCostModelingDecisions() {
1628     WideningDecisions.clear();
1629     Uniforms.clear();
1630     Scalars.clear();
1631   }
1632 
1633 private:
1634   unsigned NumPredStores = 0;
1635 
1636   /// \return An upper bound for the vectorization factors for both
1637   /// fixed and scalable vectorization, where the minimum-known number of
1638   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1639   /// disabled or unsupported, then the scalable part will be equal to
1640   /// ElementCount::getScalable(0).
1641   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1642                                            ElementCount UserVF);
1643 
1644   /// \return the maximized element count based on the targets vector
1645   /// registers and the loop trip-count, but limited to a maximum safe VF.
1646   /// This is a helper function of computeFeasibleMaxVF.
1647   /// FIXME: MaxSafeVF is currently passed by reference to avoid some obscure
1648   /// issue that occurred on one of the buildbots which cannot be reproduced
1649   /// without having access to the properietary compiler (see comments on
1650   /// D98509). The issue is currently under investigation and this workaround
1651   /// will be removed as soon as possible.
1652   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1653                                        unsigned SmallestType,
1654                                        unsigned WidestType,
1655                                        const ElementCount &MaxSafeVF);
1656 
1657   /// \return the maximum legal scalable VF, based on the safe max number
1658   /// of elements.
1659   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1660 
1661   /// The vectorization cost is a combination of the cost itself and a boolean
1662   /// indicating whether any of the contributing operations will actually
1663   /// operate on vector values after type legalization in the backend. If this
1664   /// latter value is false, then all operations will be scalarized (i.e. no
1665   /// vectorization has actually taken place).
1666   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1667 
1668   /// Returns the expected execution cost. The unit of the cost does
1669   /// not matter because we use the 'cost' units to compare different
1670   /// vector widths. The cost that is returned is *not* normalized by
1671   /// the factor width.
1672   VectorizationCostTy expectedCost(ElementCount VF);
1673 
1674   /// Returns the execution time cost of an instruction for a given vector
1675   /// width. Vector width of one means scalar.
1676   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1677 
1678   /// The cost-computation logic from getInstructionCost which provides
1679   /// the vector type as an output parameter.
1680   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1681                                      Type *&VectorTy);
1682 
1683   /// Return the cost of instructions in an inloop reduction pattern, if I is
1684   /// part of that pattern.
1685   InstructionCost getReductionPatternCost(Instruction *I, ElementCount VF,
1686                                           Type *VectorTy,
1687                                           TTI::TargetCostKind CostKind);
1688 
1689   /// Calculate vectorization cost of memory instruction \p I.
1690   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1691 
1692   /// The cost computation for scalarized memory instruction.
1693   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1694 
1695   /// The cost computation for interleaving group of memory instructions.
1696   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1697 
1698   /// The cost computation for Gather/Scatter instruction.
1699   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1700 
1701   /// The cost computation for widening instruction \p I with consecutive
1702   /// memory access.
1703   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1704 
1705   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1706   /// Load: scalar load + broadcast.
1707   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1708   /// element)
1709   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1710 
1711   /// Estimate the overhead of scalarizing an instruction. This is a
1712   /// convenience wrapper for the type-based getScalarizationOverhead API.
1713   InstructionCost getScalarizationOverhead(Instruction *I,
1714                                            ElementCount VF) const;
1715 
1716   /// Returns whether the instruction is a load or store and will be a emitted
1717   /// as a vector operation.
1718   bool isConsecutiveLoadOrStore(Instruction *I);
1719 
1720   /// Returns true if an artificially high cost for emulated masked memrefs
1721   /// should be used.
1722   bool useEmulatedMaskMemRefHack(Instruction *I);
1723 
1724   /// Map of scalar integer values to the smallest bitwidth they can be legally
1725   /// represented as. The vector equivalents of these values should be truncated
1726   /// to this type.
1727   MapVector<Instruction *, uint64_t> MinBWs;
1728 
1729   /// A type representing the costs for instructions if they were to be
1730   /// scalarized rather than vectorized. The entries are Instruction-Cost
1731   /// pairs.
1732   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1733 
1734   /// A set containing all BasicBlocks that are known to present after
1735   /// vectorization as a predicated block.
1736   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1737 
1738   /// Records whether it is allowed to have the original scalar loop execute at
1739   /// least once. This may be needed as a fallback loop in case runtime
1740   /// aliasing/dependence checks fail, or to handle the tail/remainder
1741   /// iterations when the trip count is unknown or doesn't divide by the VF,
1742   /// or as a peel-loop to handle gaps in interleave-groups.
1743   /// Under optsize and when the trip count is very small we don't allow any
1744   /// iterations to execute in the scalar loop.
1745   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1746 
1747   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1748   bool FoldTailByMasking = false;
1749 
1750   /// A map holding scalar costs for different vectorization factors. The
1751   /// presence of a cost for an instruction in the mapping indicates that the
1752   /// instruction will be scalarized when vectorizing with the associated
1753   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1754   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1755 
1756   /// Holds the instructions known to be uniform after vectorization.
1757   /// The data is collected per VF.
1758   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1759 
1760   /// Holds the instructions known to be scalar after vectorization.
1761   /// The data is collected per VF.
1762   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1763 
1764   /// Holds the instructions (address computations) that are forced to be
1765   /// scalarized.
1766   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1767 
1768   /// PHINodes of the reductions that should be expanded in-loop along with
1769   /// their associated chains of reduction operations, in program order from top
1770   /// (PHI) to bottom
1771   ReductionChainMap InLoopReductionChains;
1772 
1773   /// A Map of inloop reduction operations and their immediate chain operand.
1774   /// FIXME: This can be removed once reductions can be costed correctly in
1775   /// vplan. This was added to allow quick lookup to the inloop operations,
1776   /// without having to loop through InLoopReductionChains.
1777   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1778 
1779   /// Returns the expected difference in cost from scalarizing the expression
1780   /// feeding a predicated instruction \p PredInst. The instructions to
1781   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1782   /// non-negative return value implies the expression will be scalarized.
1783   /// Currently, only single-use chains are considered for scalarization.
1784   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1785                               ElementCount VF);
1786 
1787   /// Collect the instructions that are uniform after vectorization. An
1788   /// instruction is uniform if we represent it with a single scalar value in
1789   /// the vectorized loop corresponding to each vector iteration. Examples of
1790   /// uniform instructions include pointer operands of consecutive or
1791   /// interleaved memory accesses. Note that although uniformity implies an
1792   /// instruction will be scalar, the reverse is not true. In general, a
1793   /// scalarized instruction will be represented by VF scalar values in the
1794   /// vectorized loop, each corresponding to an iteration of the original
1795   /// scalar loop.
1796   void collectLoopUniforms(ElementCount VF);
1797 
1798   /// Collect the instructions that are scalar after vectorization. An
1799   /// instruction is scalar if it is known to be uniform or will be scalarized
1800   /// during vectorization. Non-uniform scalarized instructions will be
1801   /// represented by VF values in the vectorized loop, each corresponding to an
1802   /// iteration of the original scalar loop.
1803   void collectLoopScalars(ElementCount VF);
1804 
1805   /// Keeps cost model vectorization decision and cost for instructions.
1806   /// Right now it is used for memory instructions only.
1807   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1808                                 std::pair<InstWidening, InstructionCost>>;
1809 
1810   DecisionList WideningDecisions;
1811 
1812   /// Returns true if \p V is expected to be vectorized and it needs to be
1813   /// extracted.
1814   bool needsExtract(Value *V, ElementCount VF) const {
1815     Instruction *I = dyn_cast<Instruction>(V);
1816     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1817         TheLoop->isLoopInvariant(I))
1818       return false;
1819 
1820     // Assume we can vectorize V (and hence we need extraction) if the
1821     // scalars are not computed yet. This can happen, because it is called
1822     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1823     // the scalars are collected. That should be a safe assumption in most
1824     // cases, because we check if the operands have vectorizable types
1825     // beforehand in LoopVectorizationLegality.
1826     return Scalars.find(VF) == Scalars.end() ||
1827            !isScalarAfterVectorization(I, VF);
1828   };
1829 
1830   /// Returns a range containing only operands needing to be extracted.
1831   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1832                                                    ElementCount VF) const {
1833     return SmallVector<Value *, 4>(make_filter_range(
1834         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1835   }
1836 
1837   /// Determines if we have the infrastructure to vectorize loop \p L and its
1838   /// epilogue, assuming the main loop is vectorized by \p VF.
1839   bool isCandidateForEpilogueVectorization(const Loop &L,
1840                                            const ElementCount VF) const;
1841 
1842   /// Returns true if epilogue vectorization is considered profitable, and
1843   /// false otherwise.
1844   /// \p VF is the vectorization factor chosen for the original loop.
1845   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1846 
1847 public:
1848   /// The loop that we evaluate.
1849   Loop *TheLoop;
1850 
1851   /// Predicated scalar evolution analysis.
1852   PredicatedScalarEvolution &PSE;
1853 
1854   /// Loop Info analysis.
1855   LoopInfo *LI;
1856 
1857   /// Vectorization legality.
1858   LoopVectorizationLegality *Legal;
1859 
1860   /// Vector target information.
1861   const TargetTransformInfo &TTI;
1862 
1863   /// Target Library Info.
1864   const TargetLibraryInfo *TLI;
1865 
1866   /// Demanded bits analysis.
1867   DemandedBits *DB;
1868 
1869   /// Assumption cache.
1870   AssumptionCache *AC;
1871 
1872   /// Interface to emit optimization remarks.
1873   OptimizationRemarkEmitter *ORE;
1874 
1875   const Function *TheFunction;
1876 
1877   /// Loop Vectorize Hint.
1878   const LoopVectorizeHints *Hints;
1879 
1880   /// The interleave access information contains groups of interleaved accesses
1881   /// with the same stride and close to each other.
1882   InterleavedAccessInfo &InterleaveInfo;
1883 
1884   /// Values to ignore in the cost model.
1885   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1886 
1887   /// Values to ignore in the cost model when VF > 1.
1888   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1889 
1890   /// Profitable vector factors.
1891   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1892 };
1893 } // end namespace llvm
1894 
1895 /// Helper struct to manage generating runtime checks for vectorization.
1896 ///
1897 /// The runtime checks are created up-front in temporary blocks to allow better
1898 /// estimating the cost and un-linked from the existing IR. After deciding to
1899 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1900 /// temporary blocks are completely removed.
1901 class GeneratedRTChecks {
1902   /// Basic block which contains the generated SCEV checks, if any.
1903   BasicBlock *SCEVCheckBlock = nullptr;
1904 
1905   /// The value representing the result of the generated SCEV checks. If it is
1906   /// nullptr, either no SCEV checks have been generated or they have been used.
1907   Value *SCEVCheckCond = nullptr;
1908 
1909   /// Basic block which contains the generated memory runtime checks, if any.
1910   BasicBlock *MemCheckBlock = nullptr;
1911 
1912   /// The value representing the result of the generated memory runtime checks.
1913   /// If it is nullptr, either no memory runtime checks have been generated or
1914   /// they have been used.
1915   Instruction *MemRuntimeCheckCond = nullptr;
1916 
1917   DominatorTree *DT;
1918   LoopInfo *LI;
1919 
1920   SCEVExpander SCEVExp;
1921   SCEVExpander MemCheckExp;
1922 
1923 public:
1924   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1925                     const DataLayout &DL)
1926       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1927         MemCheckExp(SE, DL, "scev.check") {}
1928 
1929   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1930   /// accurately estimate the cost of the runtime checks. The blocks are
1931   /// un-linked from the IR and is added back during vector code generation. If
1932   /// there is no vector code generation, the check blocks are removed
1933   /// completely.
1934   void Create(Loop *L, const LoopAccessInfo &LAI,
1935               const SCEVUnionPredicate &UnionPred) {
1936 
1937     BasicBlock *LoopHeader = L->getHeader();
1938     BasicBlock *Preheader = L->getLoopPreheader();
1939 
1940     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1941     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1942     // may be used by SCEVExpander. The blocks will be un-linked from their
1943     // predecessors and removed from LI & DT at the end of the function.
1944     if (!UnionPred.isAlwaysTrue()) {
1945       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1946                                   nullptr, "vector.scevcheck");
1947 
1948       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1949           &UnionPred, SCEVCheckBlock->getTerminator());
1950     }
1951 
1952     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1953     if (RtPtrChecking.Need) {
1954       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1955       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1956                                  "vector.memcheck");
1957 
1958       std::tie(std::ignore, MemRuntimeCheckCond) =
1959           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1960                            RtPtrChecking.getChecks(), MemCheckExp);
1961       assert(MemRuntimeCheckCond &&
1962              "no RT checks generated although RtPtrChecking "
1963              "claimed checks are required");
1964     }
1965 
1966     if (!MemCheckBlock && !SCEVCheckBlock)
1967       return;
1968 
1969     // Unhook the temporary block with the checks, update various places
1970     // accordingly.
1971     if (SCEVCheckBlock)
1972       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1973     if (MemCheckBlock)
1974       MemCheckBlock->replaceAllUsesWith(Preheader);
1975 
1976     if (SCEVCheckBlock) {
1977       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1978       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1979       Preheader->getTerminator()->eraseFromParent();
1980     }
1981     if (MemCheckBlock) {
1982       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1983       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1984       Preheader->getTerminator()->eraseFromParent();
1985     }
1986 
1987     DT->changeImmediateDominator(LoopHeader, Preheader);
1988     if (MemCheckBlock) {
1989       DT->eraseNode(MemCheckBlock);
1990       LI->removeBlock(MemCheckBlock);
1991     }
1992     if (SCEVCheckBlock) {
1993       DT->eraseNode(SCEVCheckBlock);
1994       LI->removeBlock(SCEVCheckBlock);
1995     }
1996   }
1997 
1998   /// Remove the created SCEV & memory runtime check blocks & instructions, if
1999   /// unused.
2000   ~GeneratedRTChecks() {
2001     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
2002     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
2003     if (!SCEVCheckCond)
2004       SCEVCleaner.markResultUsed();
2005 
2006     if (!MemRuntimeCheckCond)
2007       MemCheckCleaner.markResultUsed();
2008 
2009     if (MemRuntimeCheckCond) {
2010       auto &SE = *MemCheckExp.getSE();
2011       // Memory runtime check generation creates compares that use expanded
2012       // values. Remove them before running the SCEVExpanderCleaners.
2013       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2014         if (MemCheckExp.isInsertedInstruction(&I))
2015           continue;
2016         SE.forgetValue(&I);
2017         SE.eraseValueFromMap(&I);
2018         I.eraseFromParent();
2019       }
2020     }
2021     MemCheckCleaner.cleanup();
2022     SCEVCleaner.cleanup();
2023 
2024     if (SCEVCheckCond)
2025       SCEVCheckBlock->eraseFromParent();
2026     if (MemRuntimeCheckCond)
2027       MemCheckBlock->eraseFromParent();
2028   }
2029 
2030   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2031   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2032   /// depending on the generated condition.
2033   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2034                              BasicBlock *LoopVectorPreHeader,
2035                              BasicBlock *LoopExitBlock) {
2036     if (!SCEVCheckCond)
2037       return nullptr;
2038     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2039       if (C->isZero())
2040         return nullptr;
2041 
2042     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2043 
2044     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2045     // Create new preheader for vector loop.
2046     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2047       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2048 
2049     SCEVCheckBlock->getTerminator()->eraseFromParent();
2050     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2051     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2052                                                 SCEVCheckBlock);
2053 
2054     DT->addNewBlock(SCEVCheckBlock, Pred);
2055     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2056 
2057     ReplaceInstWithInst(
2058         SCEVCheckBlock->getTerminator(),
2059         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2060     // Mark the check as used, to prevent it from being removed during cleanup.
2061     SCEVCheckCond = nullptr;
2062     return SCEVCheckBlock;
2063   }
2064 
2065   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2066   /// the branches to branch to the vector preheader or \p Bypass, depending on
2067   /// the generated condition.
2068   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2069                                    BasicBlock *LoopVectorPreHeader) {
2070     // Check if we generated code that checks in runtime if arrays overlap.
2071     if (!MemRuntimeCheckCond)
2072       return nullptr;
2073 
2074     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2075     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2076                                                 MemCheckBlock);
2077 
2078     DT->addNewBlock(MemCheckBlock, Pred);
2079     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2080     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2081 
2082     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2083       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2084 
2085     ReplaceInstWithInst(
2086         MemCheckBlock->getTerminator(),
2087         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2088     MemCheckBlock->getTerminator()->setDebugLoc(
2089         Pred->getTerminator()->getDebugLoc());
2090 
2091     // Mark the check as used, to prevent it from being removed during cleanup.
2092     MemRuntimeCheckCond = nullptr;
2093     return MemCheckBlock;
2094   }
2095 };
2096 
2097 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2098 // vectorization. The loop needs to be annotated with #pragma omp simd
2099 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2100 // vector length information is not provided, vectorization is not considered
2101 // explicit. Interleave hints are not allowed either. These limitations will be
2102 // relaxed in the future.
2103 // Please, note that we are currently forced to abuse the pragma 'clang
2104 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2105 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2106 // provides *explicit vectorization hints* (LV can bypass legal checks and
2107 // assume that vectorization is legal). However, both hints are implemented
2108 // using the same metadata (llvm.loop.vectorize, processed by
2109 // LoopVectorizeHints). This will be fixed in the future when the native IR
2110 // representation for pragma 'omp simd' is introduced.
2111 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2112                                    OptimizationRemarkEmitter *ORE) {
2113   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2114   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2115 
2116   // Only outer loops with an explicit vectorization hint are supported.
2117   // Unannotated outer loops are ignored.
2118   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2119     return false;
2120 
2121   Function *Fn = OuterLp->getHeader()->getParent();
2122   if (!Hints.allowVectorization(Fn, OuterLp,
2123                                 true /*VectorizeOnlyWhenForced*/)) {
2124     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2125     return false;
2126   }
2127 
2128   if (Hints.getInterleave() > 1) {
2129     // TODO: Interleave support is future work.
2130     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2131                          "outer loops.\n");
2132     Hints.emitRemarkWithHints();
2133     return false;
2134   }
2135 
2136   return true;
2137 }
2138 
2139 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2140                                   OptimizationRemarkEmitter *ORE,
2141                                   SmallVectorImpl<Loop *> &V) {
2142   // Collect inner loops and outer loops without irreducible control flow. For
2143   // now, only collect outer loops that have explicit vectorization hints. If we
2144   // are stress testing the VPlan H-CFG construction, we collect the outermost
2145   // loop of every loop nest.
2146   if (L.isInnermost() || VPlanBuildStressTest ||
2147       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2148     LoopBlocksRPO RPOT(&L);
2149     RPOT.perform(LI);
2150     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2151       V.push_back(&L);
2152       // TODO: Collect inner loops inside marked outer loops in case
2153       // vectorization fails for the outer loop. Do not invoke
2154       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2155       // already known to be reducible. We can use an inherited attribute for
2156       // that.
2157       return;
2158     }
2159   }
2160   for (Loop *InnerL : L)
2161     collectSupportedLoops(*InnerL, LI, ORE, V);
2162 }
2163 
2164 namespace {
2165 
2166 /// The LoopVectorize Pass.
2167 struct LoopVectorize : public FunctionPass {
2168   /// Pass identification, replacement for typeid
2169   static char ID;
2170 
2171   LoopVectorizePass Impl;
2172 
2173   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2174                          bool VectorizeOnlyWhenForced = false)
2175       : FunctionPass(ID),
2176         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2177     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2178   }
2179 
2180   bool runOnFunction(Function &F) override {
2181     if (skipFunction(F))
2182       return false;
2183 
2184     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2185     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2186     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2187     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2188     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2189     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2190     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2191     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2192     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2193     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2194     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2195     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2196     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2197 
2198     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2199         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2200 
2201     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2202                         GetLAA, *ORE, PSI).MadeAnyChange;
2203   }
2204 
2205   void getAnalysisUsage(AnalysisUsage &AU) const override {
2206     AU.addRequired<AssumptionCacheTracker>();
2207     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2208     AU.addRequired<DominatorTreeWrapperPass>();
2209     AU.addRequired<LoopInfoWrapperPass>();
2210     AU.addRequired<ScalarEvolutionWrapperPass>();
2211     AU.addRequired<TargetTransformInfoWrapperPass>();
2212     AU.addRequired<AAResultsWrapperPass>();
2213     AU.addRequired<LoopAccessLegacyAnalysis>();
2214     AU.addRequired<DemandedBitsWrapperPass>();
2215     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2216     AU.addRequired<InjectTLIMappingsLegacy>();
2217 
2218     // We currently do not preserve loopinfo/dominator analyses with outer loop
2219     // vectorization. Until this is addressed, mark these analyses as preserved
2220     // only for non-VPlan-native path.
2221     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2222     if (!EnableVPlanNativePath) {
2223       AU.addPreserved<LoopInfoWrapperPass>();
2224       AU.addPreserved<DominatorTreeWrapperPass>();
2225     }
2226 
2227     AU.addPreserved<BasicAAWrapperPass>();
2228     AU.addPreserved<GlobalsAAWrapperPass>();
2229     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2230   }
2231 };
2232 
2233 } // end anonymous namespace
2234 
2235 //===----------------------------------------------------------------------===//
2236 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2237 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2238 //===----------------------------------------------------------------------===//
2239 
2240 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2241   // We need to place the broadcast of invariant variables outside the loop,
2242   // but only if it's proven safe to do so. Else, broadcast will be inside
2243   // vector loop body.
2244   Instruction *Instr = dyn_cast<Instruction>(V);
2245   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2246                      (!Instr ||
2247                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2248   // Place the code for broadcasting invariant variables in the new preheader.
2249   IRBuilder<>::InsertPointGuard Guard(Builder);
2250   if (SafeToHoist)
2251     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2252 
2253   // Broadcast the scalar into all locations in the vector.
2254   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2255 
2256   return Shuf;
2257 }
2258 
2259 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2260     const InductionDescriptor &II, Value *Step, Value *Start,
2261     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2262     VPTransformState &State) {
2263   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2264          "Expected either an induction phi-node or a truncate of it!");
2265 
2266   // Construct the initial value of the vector IV in the vector loop preheader
2267   auto CurrIP = Builder.saveIP();
2268   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2269   if (isa<TruncInst>(EntryVal)) {
2270     assert(Start->getType()->isIntegerTy() &&
2271            "Truncation requires an integer type");
2272     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2273     Step = Builder.CreateTrunc(Step, TruncType);
2274     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2275   }
2276   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2277   Value *SteppedStart =
2278       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2279 
2280   // We create vector phi nodes for both integer and floating-point induction
2281   // variables. Here, we determine the kind of arithmetic we will perform.
2282   Instruction::BinaryOps AddOp;
2283   Instruction::BinaryOps MulOp;
2284   if (Step->getType()->isIntegerTy()) {
2285     AddOp = Instruction::Add;
2286     MulOp = Instruction::Mul;
2287   } else {
2288     AddOp = II.getInductionOpcode();
2289     MulOp = Instruction::FMul;
2290   }
2291 
2292   // Multiply the vectorization factor by the step using integer or
2293   // floating-point arithmetic as appropriate.
2294   Type *StepType = Step->getType();
2295   if (Step->getType()->isFloatingPointTy())
2296     StepType = IntegerType::get(StepType->getContext(),
2297                                 StepType->getScalarSizeInBits());
2298   Value *RuntimeVF = getRuntimeVF(Builder, StepType, VF);
2299   if (Step->getType()->isFloatingPointTy())
2300     RuntimeVF = Builder.CreateSIToFP(RuntimeVF, Step->getType());
2301   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2302 
2303   // Create a vector splat to use in the induction update.
2304   //
2305   // FIXME: If the step is non-constant, we create the vector splat with
2306   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2307   //        handle a constant vector splat.
2308   Value *SplatVF = isa<Constant>(Mul)
2309                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2310                        : Builder.CreateVectorSplat(VF, Mul);
2311   Builder.restoreIP(CurrIP);
2312 
2313   // We may need to add the step a number of times, depending on the unroll
2314   // factor. The last of those goes into the PHI.
2315   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2316                                     &*LoopVectorBody->getFirstInsertionPt());
2317   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2318   Instruction *LastInduction = VecInd;
2319   for (unsigned Part = 0; Part < UF; ++Part) {
2320     State.set(Def, LastInduction, Part);
2321 
2322     if (isa<TruncInst>(EntryVal))
2323       addMetadata(LastInduction, EntryVal);
2324     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2325                                           State, Part);
2326 
2327     LastInduction = cast<Instruction>(
2328         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2329     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2330   }
2331 
2332   // Move the last step to the end of the latch block. This ensures consistent
2333   // placement of all induction updates.
2334   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2335   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2336   auto *ICmp = cast<Instruction>(Br->getCondition());
2337   LastInduction->moveBefore(ICmp);
2338   LastInduction->setName("vec.ind.next");
2339 
2340   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2341   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2342 }
2343 
2344 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2345   return Cost->isScalarAfterVectorization(I, VF) ||
2346          Cost->isProfitableToScalarize(I, VF);
2347 }
2348 
2349 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2350   if (shouldScalarizeInstruction(IV))
2351     return true;
2352   auto isScalarInst = [&](User *U) -> bool {
2353     auto *I = cast<Instruction>(U);
2354     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2355   };
2356   return llvm::any_of(IV->users(), isScalarInst);
2357 }
2358 
2359 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2360     const InductionDescriptor &ID, const Instruction *EntryVal,
2361     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2362     unsigned Part, unsigned Lane) {
2363   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2364          "Expected either an induction phi-node or a truncate of it!");
2365 
2366   // This induction variable is not the phi from the original loop but the
2367   // newly-created IV based on the proof that casted Phi is equal to the
2368   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2369   // re-uses the same InductionDescriptor that original IV uses but we don't
2370   // have to do any recording in this case - that is done when original IV is
2371   // processed.
2372   if (isa<TruncInst>(EntryVal))
2373     return;
2374 
2375   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2376   if (Casts.empty())
2377     return;
2378   // Only the first Cast instruction in the Casts vector is of interest.
2379   // The rest of the Casts (if exist) have no uses outside the
2380   // induction update chain itself.
2381   if (Lane < UINT_MAX)
2382     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2383   else
2384     State.set(CastDef, VectorLoopVal, Part);
2385 }
2386 
2387 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2388                                                 TruncInst *Trunc, VPValue *Def,
2389                                                 VPValue *CastDef,
2390                                                 VPTransformState &State) {
2391   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2392          "Primary induction variable must have an integer type");
2393 
2394   auto II = Legal->getInductionVars().find(IV);
2395   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2396 
2397   auto ID = II->second;
2398   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2399 
2400   // The value from the original loop to which we are mapping the new induction
2401   // variable.
2402   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2403 
2404   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2405 
2406   // Generate code for the induction step. Note that induction steps are
2407   // required to be loop-invariant
2408   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2409     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2410            "Induction step should be loop invariant");
2411     if (PSE.getSE()->isSCEVable(IV->getType())) {
2412       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2413       return Exp.expandCodeFor(Step, Step->getType(),
2414                                LoopVectorPreHeader->getTerminator());
2415     }
2416     return cast<SCEVUnknown>(Step)->getValue();
2417   };
2418 
2419   // The scalar value to broadcast. This is derived from the canonical
2420   // induction variable. If a truncation type is given, truncate the canonical
2421   // induction variable and step. Otherwise, derive these values from the
2422   // induction descriptor.
2423   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2424     Value *ScalarIV = Induction;
2425     if (IV != OldInduction) {
2426       ScalarIV = IV->getType()->isIntegerTy()
2427                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2428                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2429                                           IV->getType());
2430       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2431       ScalarIV->setName("offset.idx");
2432     }
2433     if (Trunc) {
2434       auto *TruncType = cast<IntegerType>(Trunc->getType());
2435       assert(Step->getType()->isIntegerTy() &&
2436              "Truncation requires an integer step");
2437       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2438       Step = Builder.CreateTrunc(Step, TruncType);
2439     }
2440     return ScalarIV;
2441   };
2442 
2443   // Create the vector values from the scalar IV, in the absence of creating a
2444   // vector IV.
2445   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2446     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2447     for (unsigned Part = 0; Part < UF; ++Part) {
2448       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2449       Value *EntryPart =
2450           getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
2451                         ID.getInductionOpcode());
2452       State.set(Def, EntryPart, Part);
2453       if (Trunc)
2454         addMetadata(EntryPart, Trunc);
2455       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2456                                             State, Part);
2457     }
2458   };
2459 
2460   // Fast-math-flags propagate from the original induction instruction.
2461   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2462   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2463     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2464 
2465   // Now do the actual transformations, and start with creating the step value.
2466   Value *Step = CreateStepValue(ID.getStep());
2467   if (VF.isZero() || VF.isScalar()) {
2468     Value *ScalarIV = CreateScalarIV(Step);
2469     CreateSplatIV(ScalarIV, Step);
2470     return;
2471   }
2472 
2473   // Determine if we want a scalar version of the induction variable. This is
2474   // true if the induction variable itself is not widened, or if it has at
2475   // least one user in the loop that is not widened.
2476   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2477   if (!NeedsScalarIV) {
2478     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2479                                     State);
2480     return;
2481   }
2482 
2483   // Try to create a new independent vector induction variable. If we can't
2484   // create the phi node, we will splat the scalar induction variable in each
2485   // loop iteration.
2486   if (!shouldScalarizeInstruction(EntryVal)) {
2487     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2488                                     State);
2489     Value *ScalarIV = CreateScalarIV(Step);
2490     // Create scalar steps that can be used by instructions we will later
2491     // scalarize. Note that the addition of the scalar steps will not increase
2492     // the number of instructions in the loop in the common case prior to
2493     // InstCombine. We will be trading one vector extract for each scalar step.
2494     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2495     return;
2496   }
2497 
2498   // All IV users are scalar instructions, so only emit a scalar IV, not a
2499   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2500   // predicate used by the masked loads/stores.
2501   Value *ScalarIV = CreateScalarIV(Step);
2502   if (!Cost->isScalarEpilogueAllowed())
2503     CreateSplatIV(ScalarIV, Step);
2504   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2505 }
2506 
2507 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2508                                           Instruction::BinaryOps BinOp) {
2509   // Create and check the types.
2510   auto *ValVTy = cast<VectorType>(Val->getType());
2511   ElementCount VLen = ValVTy->getElementCount();
2512 
2513   Type *STy = Val->getType()->getScalarType();
2514   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2515          "Induction Step must be an integer or FP");
2516   assert(Step->getType() == STy && "Step has wrong type");
2517 
2518   SmallVector<Constant *, 8> Indices;
2519 
2520   // Create a vector of consecutive numbers from zero to VF.
2521   VectorType *InitVecValVTy = ValVTy;
2522   Type *InitVecValSTy = STy;
2523   if (STy->isFloatingPointTy()) {
2524     InitVecValSTy =
2525         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2526     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2527   }
2528   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2529 
2530   // Add on StartIdx
2531   Value *StartIdxSplat = Builder.CreateVectorSplat(
2532       VLen, ConstantInt::get(InitVecValSTy, StartIdx));
2533   InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2534 
2535   if (STy->isIntegerTy()) {
2536     Step = Builder.CreateVectorSplat(VLen, Step);
2537     assert(Step->getType() == Val->getType() && "Invalid step vec");
2538     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2539     // which can be found from the original scalar operations.
2540     Step = Builder.CreateMul(InitVec, Step);
2541     return Builder.CreateAdd(Val, Step, "induction");
2542   }
2543 
2544   // Floating point induction.
2545   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2546          "Binary Opcode should be specified for FP induction");
2547   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2548   Step = Builder.CreateVectorSplat(VLen, Step);
2549   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2550   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2551 }
2552 
2553 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2554                                            Instruction *EntryVal,
2555                                            const InductionDescriptor &ID,
2556                                            VPValue *Def, VPValue *CastDef,
2557                                            VPTransformState &State) {
2558   // We shouldn't have to build scalar steps if we aren't vectorizing.
2559   assert(VF.isVector() && "VF should be greater than one");
2560   // Get the value type and ensure it and the step have the same integer type.
2561   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2562   assert(ScalarIVTy == Step->getType() &&
2563          "Val and Step should have the same type");
2564 
2565   // We build scalar steps for both integer and floating-point induction
2566   // variables. Here, we determine the kind of arithmetic we will perform.
2567   Instruction::BinaryOps AddOp;
2568   Instruction::BinaryOps MulOp;
2569   if (ScalarIVTy->isIntegerTy()) {
2570     AddOp = Instruction::Add;
2571     MulOp = Instruction::Mul;
2572   } else {
2573     AddOp = ID.getInductionOpcode();
2574     MulOp = Instruction::FMul;
2575   }
2576 
2577   // Determine the number of scalars we need to generate for each unroll
2578   // iteration. If EntryVal is uniform, we only need to generate the first
2579   // lane. Otherwise, we generate all VF values.
2580   bool IsUniform =
2581       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF);
2582   unsigned Lanes = IsUniform ? 1 : VF.getKnownMinValue();
2583   // Compute the scalar steps and save the results in State.
2584   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2585                                      ScalarIVTy->getScalarSizeInBits());
2586   Type *VecIVTy = nullptr;
2587   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2588   if (!IsUniform && VF.isScalable()) {
2589     VecIVTy = VectorType::get(ScalarIVTy, VF);
2590     UnitStepVec = Builder.CreateStepVector(VectorType::get(IntStepTy, VF));
2591     SplatStep = Builder.CreateVectorSplat(VF, Step);
2592     SplatIV = Builder.CreateVectorSplat(VF, ScalarIV);
2593   }
2594 
2595   for (unsigned Part = 0; Part < UF; ++Part) {
2596     Value *StartIdx0 =
2597         createStepForVF(Builder, ConstantInt::get(IntStepTy, Part), VF);
2598 
2599     if (!IsUniform && VF.isScalable()) {
2600       auto *SplatStartIdx = Builder.CreateVectorSplat(VF, StartIdx0);
2601       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2602       if (ScalarIVTy->isFloatingPointTy())
2603         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2604       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2605       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2606       State.set(Def, Add, Part);
2607       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2608                                             Part);
2609       // It's useful to record the lane values too for the known minimum number
2610       // of elements so we do those below. This improves the code quality when
2611       // trying to extract the first element, for example.
2612     }
2613 
2614     if (ScalarIVTy->isFloatingPointTy())
2615       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2616 
2617     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2618       Value *StartIdx = Builder.CreateBinOp(
2619           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2620       // The step returned by `createStepForVF` is a runtime-evaluated value
2621       // when VF is scalable. Otherwise, it should be folded into a Constant.
2622       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2623              "Expected StartIdx to be folded to a constant when VF is not "
2624              "scalable");
2625       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2626       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2627       State.set(Def, Add, VPIteration(Part, Lane));
2628       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2629                                             Part, Lane);
2630     }
2631   }
2632 }
2633 
2634 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2635                                                     const VPIteration &Instance,
2636                                                     VPTransformState &State) {
2637   Value *ScalarInst = State.get(Def, Instance);
2638   Value *VectorValue = State.get(Def, Instance.Part);
2639   VectorValue = Builder.CreateInsertElement(
2640       VectorValue, ScalarInst,
2641       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2642   State.set(Def, VectorValue, Instance.Part);
2643 }
2644 
2645 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2646   assert(Vec->getType()->isVectorTy() && "Invalid type");
2647   return Builder.CreateVectorReverse(Vec, "reverse");
2648 }
2649 
2650 // Return whether we allow using masked interleave-groups (for dealing with
2651 // strided loads/stores that reside in predicated blocks, or for dealing
2652 // with gaps).
2653 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2654   // If an override option has been passed in for interleaved accesses, use it.
2655   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2656     return EnableMaskedInterleavedMemAccesses;
2657 
2658   return TTI.enableMaskedInterleavedAccessVectorization();
2659 }
2660 
2661 // Try to vectorize the interleave group that \p Instr belongs to.
2662 //
2663 // E.g. Translate following interleaved load group (factor = 3):
2664 //   for (i = 0; i < N; i+=3) {
2665 //     R = Pic[i];             // Member of index 0
2666 //     G = Pic[i+1];           // Member of index 1
2667 //     B = Pic[i+2];           // Member of index 2
2668 //     ... // do something to R, G, B
2669 //   }
2670 // To:
2671 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2672 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2673 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2674 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2675 //
2676 // Or translate following interleaved store group (factor = 3):
2677 //   for (i = 0; i < N; i+=3) {
2678 //     ... do something to R, G, B
2679 //     Pic[i]   = R;           // Member of index 0
2680 //     Pic[i+1] = G;           // Member of index 1
2681 //     Pic[i+2] = B;           // Member of index 2
2682 //   }
2683 // To:
2684 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2685 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2686 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2687 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2688 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2689 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2690     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2691     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2692     VPValue *BlockInMask) {
2693   Instruction *Instr = Group->getInsertPos();
2694   const DataLayout &DL = Instr->getModule()->getDataLayout();
2695 
2696   // Prepare for the vector type of the interleaved load/store.
2697   Type *ScalarTy = getLoadStoreType(Instr);
2698   unsigned InterleaveFactor = Group->getFactor();
2699   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2700   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2701 
2702   // Prepare for the new pointers.
2703   SmallVector<Value *, 2> AddrParts;
2704   unsigned Index = Group->getIndex(Instr);
2705 
2706   // TODO: extend the masked interleaved-group support to reversed access.
2707   assert((!BlockInMask || !Group->isReverse()) &&
2708          "Reversed masked interleave-group not supported.");
2709 
2710   // If the group is reverse, adjust the index to refer to the last vector lane
2711   // instead of the first. We adjust the index from the first vector lane,
2712   // rather than directly getting the pointer for lane VF - 1, because the
2713   // pointer operand of the interleaved access is supposed to be uniform. For
2714   // uniform instructions, we're only required to generate a value for the
2715   // first vector lane in each unroll iteration.
2716   if (Group->isReverse())
2717     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2718 
2719   for (unsigned Part = 0; Part < UF; Part++) {
2720     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2721     setDebugLocFromInst(Builder, AddrPart);
2722 
2723     // Notice current instruction could be any index. Need to adjust the address
2724     // to the member of index 0.
2725     //
2726     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2727     //       b = A[i];       // Member of index 0
2728     // Current pointer is pointed to A[i+1], adjust it to A[i].
2729     //
2730     // E.g.  A[i+1] = a;     // Member of index 1
2731     //       A[i]   = b;     // Member of index 0
2732     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2733     // Current pointer is pointed to A[i+2], adjust it to A[i].
2734 
2735     bool InBounds = false;
2736     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2737       InBounds = gep->isInBounds();
2738     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2739     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2740 
2741     // Cast to the vector pointer type.
2742     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2743     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2744     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2745   }
2746 
2747   setDebugLocFromInst(Builder, Instr);
2748   Value *PoisonVec = PoisonValue::get(VecTy);
2749 
2750   Value *MaskForGaps = nullptr;
2751   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2752     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2753     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2754   }
2755 
2756   // Vectorize the interleaved load group.
2757   if (isa<LoadInst>(Instr)) {
2758     // For each unroll part, create a wide load for the group.
2759     SmallVector<Value *, 2> NewLoads;
2760     for (unsigned Part = 0; Part < UF; Part++) {
2761       Instruction *NewLoad;
2762       if (BlockInMask || MaskForGaps) {
2763         assert(useMaskedInterleavedAccesses(*TTI) &&
2764                "masked interleaved groups are not allowed.");
2765         Value *GroupMask = MaskForGaps;
2766         if (BlockInMask) {
2767           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2768           Value *ShuffledMask = Builder.CreateShuffleVector(
2769               BlockInMaskPart,
2770               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2771               "interleaved.mask");
2772           GroupMask = MaskForGaps
2773                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2774                                                 MaskForGaps)
2775                           : ShuffledMask;
2776         }
2777         NewLoad =
2778             Builder.CreateMaskedLoad(AddrParts[Part], Group->getAlign(),
2779                                      GroupMask, PoisonVec, "wide.masked.vec");
2780       }
2781       else
2782         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2783                                             Group->getAlign(), "wide.vec");
2784       Group->addMetadata(NewLoad);
2785       NewLoads.push_back(NewLoad);
2786     }
2787 
2788     // For each member in the group, shuffle out the appropriate data from the
2789     // wide loads.
2790     unsigned J = 0;
2791     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2792       Instruction *Member = Group->getMember(I);
2793 
2794       // Skip the gaps in the group.
2795       if (!Member)
2796         continue;
2797 
2798       auto StrideMask =
2799           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2800       for (unsigned Part = 0; Part < UF; Part++) {
2801         Value *StridedVec = Builder.CreateShuffleVector(
2802             NewLoads[Part], StrideMask, "strided.vec");
2803 
2804         // If this member has different type, cast the result type.
2805         if (Member->getType() != ScalarTy) {
2806           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2807           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2808           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2809         }
2810 
2811         if (Group->isReverse())
2812           StridedVec = reverseVector(StridedVec);
2813 
2814         State.set(VPDefs[J], StridedVec, Part);
2815       }
2816       ++J;
2817     }
2818     return;
2819   }
2820 
2821   // The sub vector type for current instruction.
2822   auto *SubVT = VectorType::get(ScalarTy, VF);
2823 
2824   // Vectorize the interleaved store group.
2825   for (unsigned Part = 0; Part < UF; Part++) {
2826     // Collect the stored vector from each member.
2827     SmallVector<Value *, 4> StoredVecs;
2828     for (unsigned i = 0; i < InterleaveFactor; i++) {
2829       // Interleaved store group doesn't allow a gap, so each index has a member
2830       assert(Group->getMember(i) && "Fail to get a member from an interleaved store group");
2831 
2832       Value *StoredVec = State.get(StoredValues[i], Part);
2833 
2834       if (Group->isReverse())
2835         StoredVec = reverseVector(StoredVec);
2836 
2837       // If this member has different type, cast it to a unified type.
2838 
2839       if (StoredVec->getType() != SubVT)
2840         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2841 
2842       StoredVecs.push_back(StoredVec);
2843     }
2844 
2845     // Concatenate all vectors into a wide vector.
2846     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2847 
2848     // Interleave the elements in the wide vector.
2849     Value *IVec = Builder.CreateShuffleVector(
2850         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2851         "interleaved.vec");
2852 
2853     Instruction *NewStoreInstr;
2854     if (BlockInMask) {
2855       Value *BlockInMaskPart = State.get(BlockInMask, Part);
2856       Value *ShuffledMask = Builder.CreateShuffleVector(
2857           BlockInMaskPart,
2858           createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2859           "interleaved.mask");
2860       NewStoreInstr = Builder.CreateMaskedStore(
2861           IVec, AddrParts[Part], Group->getAlign(), ShuffledMask);
2862     }
2863     else
2864       NewStoreInstr =
2865           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2866 
2867     Group->addMetadata(NewStoreInstr);
2868   }
2869 }
2870 
2871 void InnerLoopVectorizer::vectorizeMemoryInstruction(
2872     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
2873     VPValue *StoredValue, VPValue *BlockInMask) {
2874   // Attempt to issue a wide load.
2875   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2876   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2877 
2878   assert((LI || SI) && "Invalid Load/Store instruction");
2879   assert((!SI || StoredValue) && "No stored value provided for widened store");
2880   assert((!LI || !StoredValue) && "Stored value provided for widened load");
2881 
2882   LoopVectorizationCostModel::InstWidening Decision =
2883       Cost->getWideningDecision(Instr, VF);
2884   assert((Decision == LoopVectorizationCostModel::CM_Widen ||
2885           Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
2886           Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
2887          "CM decision is not to widen the memory instruction");
2888 
2889   Type *ScalarDataTy = getLoadStoreType(Instr);
2890 
2891   auto *DataTy = VectorType::get(ScalarDataTy, VF);
2892   const Align Alignment = getLoadStoreAlignment(Instr);
2893 
2894   // Determine if the pointer operand of the access is either consecutive or
2895   // reverse consecutive.
2896   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2897   bool ConsecutiveStride =
2898       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2899   bool CreateGatherScatter =
2900       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2901 
2902   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2903   // gather/scatter. Otherwise Decision should have been to Scalarize.
2904   assert((ConsecutiveStride || CreateGatherScatter) &&
2905          "The instruction should be scalarized");
2906   (void)ConsecutiveStride;
2907 
2908   VectorParts BlockInMaskParts(UF);
2909   bool isMaskRequired = BlockInMask;
2910   if (isMaskRequired)
2911     for (unsigned Part = 0; Part < UF; ++Part)
2912       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
2913 
2914   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2915     // Calculate the pointer for the specific unroll-part.
2916     GetElementPtrInst *PartPtr = nullptr;
2917 
2918     bool InBounds = false;
2919     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2920       InBounds = gep->isInBounds();
2921     if (Reverse) {
2922       // If the address is consecutive but reversed, then the
2923       // wide store needs to start at the last vector element.
2924       // RunTimeVF =  VScale * VF.getKnownMinValue()
2925       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
2926       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), VF);
2927       // NumElt = -Part * RunTimeVF
2928       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
2929       // LastLane = 1 - RunTimeVF
2930       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
2931       PartPtr =
2932           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
2933       PartPtr->setIsInBounds(InBounds);
2934       PartPtr = cast<GetElementPtrInst>(
2935           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
2936       PartPtr->setIsInBounds(InBounds);
2937       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2938         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
2939     } else {
2940       Value *Increment = createStepForVF(Builder, Builder.getInt32(Part), VF);
2941       PartPtr = cast<GetElementPtrInst>(
2942           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
2943       PartPtr->setIsInBounds(InBounds);
2944     }
2945 
2946     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2947     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2948   };
2949 
2950   // Handle Stores:
2951   if (SI) {
2952     setDebugLocFromInst(Builder, SI);
2953 
2954     for (unsigned Part = 0; Part < UF; ++Part) {
2955       Instruction *NewSI = nullptr;
2956       Value *StoredVal = State.get(StoredValue, Part);
2957       if (CreateGatherScatter) {
2958         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2959         Value *VectorGep = State.get(Addr, Part);
2960         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2961                                             MaskPart);
2962       } else {
2963         if (Reverse) {
2964           // If we store to reverse consecutive memory locations, then we need
2965           // to reverse the order of elements in the stored value.
2966           StoredVal = reverseVector(StoredVal);
2967           // We don't want to update the value in the map as it might be used in
2968           // another expression. So don't call resetVectorValue(StoredVal).
2969         }
2970         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2971         if (isMaskRequired)
2972           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2973                                             BlockInMaskParts[Part]);
2974         else
2975           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2976       }
2977       addMetadata(NewSI, SI);
2978     }
2979     return;
2980   }
2981 
2982   // Handle loads.
2983   assert(LI && "Must have a load instruction");
2984   setDebugLocFromInst(Builder, LI);
2985   for (unsigned Part = 0; Part < UF; ++Part) {
2986     Value *NewLI;
2987     if (CreateGatherScatter) {
2988       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2989       Value *VectorGep = State.get(Addr, Part);
2990       NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
2991                                          nullptr, "wide.masked.gather");
2992       addMetadata(NewLI, LI);
2993     } else {
2994       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2995       if (isMaskRequired)
2996         NewLI = Builder.CreateMaskedLoad(
2997             VecPtr, Alignment, BlockInMaskParts[Part], PoisonValue::get(DataTy),
2998             "wide.masked.load");
2999       else
3000         NewLI =
3001             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
3002 
3003       // Add metadata to the load, but setVectorValue to the reverse shuffle.
3004       addMetadata(NewLI, LI);
3005       if (Reverse)
3006         NewLI = reverseVector(NewLI);
3007     }
3008 
3009     State.set(Def, NewLI, Part);
3010   }
3011 }
3012 
3013 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPValue *Def,
3014                                                VPUser &User,
3015                                                const VPIteration &Instance,
3016                                                bool IfPredicateInstr,
3017                                                VPTransformState &State) {
3018   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
3019 
3020   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
3021   // the first lane and part.
3022   if (isa<NoAliasScopeDeclInst>(Instr))
3023     if (!Instance.isFirstIteration())
3024       return;
3025 
3026   setDebugLocFromInst(Builder, Instr);
3027 
3028   // Does this instruction return a value ?
3029   bool IsVoidRetTy = Instr->getType()->isVoidTy();
3030 
3031   Instruction *Cloned = Instr->clone();
3032   if (!IsVoidRetTy)
3033     Cloned->setName(Instr->getName() + ".cloned");
3034 
3035   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
3036                                Builder.GetInsertPoint());
3037   // Replace the operands of the cloned instructions with their scalar
3038   // equivalents in the new loop.
3039   for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
3040     auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
3041     auto InputInstance = Instance;
3042     if (!Operand || !OrigLoop->contains(Operand) ||
3043         (Cost->isUniformAfterVectorization(Operand, State.VF)))
3044       InputInstance.Lane = VPLane::getFirstLane();
3045     auto *NewOp = State.get(User.getOperand(op), InputInstance);
3046     Cloned->setOperand(op, NewOp);
3047   }
3048   addNewMetadata(Cloned, Instr);
3049 
3050   // Place the cloned scalar in the new loop.
3051   Builder.Insert(Cloned);
3052 
3053   State.set(Def, Cloned, Instance);
3054 
3055   // If we just cloned a new assumption, add it the assumption cache.
3056   if (auto *II = dyn_cast<AssumeInst>(Cloned))
3057     AC->registerAssumption(II);
3058 
3059   // End if-block.
3060   if (IfPredicateInstr)
3061     PredicatedInstructions.push_back(Cloned);
3062 }
3063 
3064 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3065                                                       Value *End, Value *Step,
3066                                                       Instruction *DL) {
3067   BasicBlock *Header = L->getHeader();
3068   BasicBlock *Latch = L->getLoopLatch();
3069   // As we're just creating this loop, it's possible no latch exists
3070   // yet. If so, use the header as this will be a single block loop.
3071   if (!Latch)
3072     Latch = Header;
3073 
3074   IRBuilder<> B(&*Header->getFirstInsertionPt());
3075   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3076   setDebugLocFromInst(B, OldInst);
3077   auto *Induction = B.CreatePHI(Start->getType(), 2, "index");
3078 
3079   B.SetInsertPoint(Latch->getTerminator());
3080   setDebugLocFromInst(B, OldInst);
3081 
3082   // Create i+1 and fill the PHINode.
3083   //
3084   // If the tail is not folded, we know that End - Start >= Step (either
3085   // statically or through the minimum iteration checks). We also know that both
3086   // Start % Step == 0 and End % Step == 0. We exit the vector loop if %IV +
3087   // %Step == %End. Hence we must exit the loop before %IV + %Step unsigned
3088   // overflows and we can mark the induction increment as NUW.
3089   Value *Next = B.CreateAdd(Induction, Step, "index.next",
3090                             /*NUW=*/!Cost->foldTailByMasking(), /*NSW=*/false);
3091   Induction->addIncoming(Start, L->getLoopPreheader());
3092   Induction->addIncoming(Next, Latch);
3093   // Create the compare.
3094   Value *ICmp = B.CreateICmpEQ(Next, End);
3095   B.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3096 
3097   // Now we have two terminators. Remove the old one from the block.
3098   Latch->getTerminator()->eraseFromParent();
3099 
3100   return Induction;
3101 }
3102 
3103 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3104   if (TripCount)
3105     return TripCount;
3106 
3107   assert(L && "Create Trip Count for null loop.");
3108   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3109   // Find the loop boundaries.
3110   ScalarEvolution *SE = PSE.getSE();
3111   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3112   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3113          "Invalid loop count");
3114 
3115   Type *IdxTy = Legal->getWidestInductionType();
3116   assert(IdxTy && "No type for induction");
3117 
3118   // The exit count might have the type of i64 while the phi is i32. This can
3119   // happen if we have an induction variable that is sign extended before the
3120   // compare. The only way that we get a backedge taken count is that the
3121   // induction variable was signed and as such will not overflow. In such a case
3122   // truncation is legal.
3123   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3124       IdxTy->getPrimitiveSizeInBits())
3125     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3126   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3127 
3128   // Get the total trip count from the count by adding 1.
3129   const SCEV *ExitCount = SE->getAddExpr(
3130       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3131 
3132   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3133 
3134   // Expand the trip count and place the new instructions in the preheader.
3135   // Notice that the pre-header does not change, only the loop body.
3136   SCEVExpander Exp(*SE, DL, "induction");
3137 
3138   // Count holds the overall loop count (N).
3139   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3140                                 L->getLoopPreheader()->getTerminator());
3141 
3142   if (TripCount->getType()->isPointerTy())
3143     TripCount =
3144         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3145                                     L->getLoopPreheader()->getTerminator());
3146 
3147   return TripCount;
3148 }
3149 
3150 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3151   if (VectorTripCount)
3152     return VectorTripCount;
3153 
3154   Value *TC = getOrCreateTripCount(L);
3155   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3156 
3157   Type *Ty = TC->getType();
3158   // This is where we can make the step a runtime constant.
3159   Value *Step = createStepForVF(Builder, ConstantInt::get(Ty, UF), VF);
3160 
3161   // If the tail is to be folded by masking, round the number of iterations N
3162   // up to a multiple of Step instead of rounding down. This is done by first
3163   // adding Step-1 and then rounding down. Note that it's ok if this addition
3164   // overflows: the vector induction variable will eventually wrap to zero given
3165   // that it starts at zero and its Step is a power of two; the loop will then
3166   // exit, with the last early-exit vector comparison also producing all-true.
3167   if (Cost->foldTailByMasking()) {
3168     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3169            "VF*UF must be a power of 2 when folding tail by masking");
3170     assert(!VF.isScalable() &&
3171            "Tail folding not yet supported for scalable vectors");
3172     TC = Builder.CreateAdd(
3173         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3174   }
3175 
3176   // Now we need to generate the expression for the part of the loop that the
3177   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3178   // iterations are not required for correctness, or N - Step, otherwise. Step
3179   // is equal to the vectorization factor (number of SIMD elements) times the
3180   // unroll factor (number of SIMD instructions).
3181   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3182 
3183   // There are cases where we *must* run at least one iteration in the remainder
3184   // loop.  See the cost model for when this can happen.  If the step evenly
3185   // divides the trip count, we set the remainder to be equal to the step. If
3186   // the step does not evenly divide the trip count, no adjustment is necessary
3187   // since there will already be scalar iterations. Note that the minimum
3188   // iterations check ensures that N >= Step.
3189   if (Cost->requiresScalarEpilogue(VF)) {
3190     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3191     R = Builder.CreateSelect(IsZero, Step, R);
3192   }
3193 
3194   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3195 
3196   return VectorTripCount;
3197 }
3198 
3199 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3200                                                    const DataLayout &DL) {
3201   // Verify that V is a vector type with same number of elements as DstVTy.
3202   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3203   unsigned VF = DstFVTy->getNumElements();
3204   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3205   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3206   Type *SrcElemTy = SrcVecTy->getElementType();
3207   Type *DstElemTy = DstFVTy->getElementType();
3208   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3209          "Vector elements must have same size");
3210 
3211   // Do a direct cast if element types are castable.
3212   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3213     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3214   }
3215   // V cannot be directly casted to desired vector type.
3216   // May happen when V is a floating point vector but DstVTy is a vector of
3217   // pointers or vice-versa. Handle this using a two-step bitcast using an
3218   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3219   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3220          "Only one type should be a pointer type");
3221   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3222          "Only one type should be a floating point type");
3223   Type *IntTy =
3224       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3225   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3226   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3227   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3228 }
3229 
3230 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3231                                                          BasicBlock *Bypass) {
3232   Value *Count = getOrCreateTripCount(L);
3233   // Reuse existing vector loop preheader for TC checks.
3234   // Note that new preheader block is generated for vector loop.
3235   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3236   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3237 
3238   // Generate code to check if the loop's trip count is less than VF * UF, or
3239   // equal to it in case a scalar epilogue is required; this implies that the
3240   // vector trip count is zero. This check also covers the case where adding one
3241   // to the backedge-taken count overflowed leading to an incorrect trip count
3242   // of zero. In this case we will also jump to the scalar loop.
3243   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
3244                                             : ICmpInst::ICMP_ULT;
3245 
3246   // If tail is to be folded, vector loop takes care of all iterations.
3247   Value *CheckMinIters = Builder.getFalse();
3248   if (!Cost->foldTailByMasking()) {
3249     Value *Step =
3250         createStepForVF(Builder, ConstantInt::get(Count->getType(), UF), VF);
3251     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3252   }
3253   // Create new preheader for vector loop.
3254   LoopVectorPreHeader =
3255       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3256                  "vector.ph");
3257 
3258   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3259                                DT->getNode(Bypass)->getIDom()) &&
3260          "TC check is expected to dominate Bypass");
3261 
3262   // Update dominator for Bypass & LoopExit.
3263   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3264   DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3265 
3266   ReplaceInstWithInst(
3267       TCCheckBlock->getTerminator(),
3268       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3269   LoopBypassBlocks.push_back(TCCheckBlock);
3270 }
3271 
3272 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3273 
3274   BasicBlock *const SCEVCheckBlock =
3275       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3276   if (!SCEVCheckBlock)
3277     return nullptr;
3278 
3279   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3280            (OptForSizeBasedOnProfile &&
3281             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3282          "Cannot SCEV check stride or overflow when optimizing for size");
3283 
3284 
3285   // Update dominator only if this is first RT check.
3286   if (LoopBypassBlocks.empty()) {
3287     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3288     DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3289   }
3290 
3291   LoopBypassBlocks.push_back(SCEVCheckBlock);
3292   AddedSafetyChecks = true;
3293   return SCEVCheckBlock;
3294 }
3295 
3296 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3297                                                       BasicBlock *Bypass) {
3298   // VPlan-native path does not do any analysis for runtime checks currently.
3299   if (EnableVPlanNativePath)
3300     return nullptr;
3301 
3302   BasicBlock *const MemCheckBlock =
3303       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3304 
3305   // Check if we generated code that checks in runtime if arrays overlap. We put
3306   // the checks into a separate block to make the more common case of few
3307   // elements faster.
3308   if (!MemCheckBlock)
3309     return nullptr;
3310 
3311   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3312     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3313            "Cannot emit memory checks when optimizing for size, unless forced "
3314            "to vectorize.");
3315     ORE->emit([&]() {
3316       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3317                                         L->getStartLoc(), L->getHeader())
3318              << "Code-size may be reduced by not forcing "
3319                 "vectorization, or by source-code modifications "
3320                 "eliminating the need for runtime checks "
3321                 "(e.g., adding 'restrict').";
3322     });
3323   }
3324 
3325   LoopBypassBlocks.push_back(MemCheckBlock);
3326 
3327   AddedSafetyChecks = true;
3328 
3329   // We currently don't use LoopVersioning for the actual loop cloning but we
3330   // still use it to add the noalias metadata.
3331   LVer = std::make_unique<LoopVersioning>(
3332       *Legal->getLAI(),
3333       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3334       DT, PSE.getSE());
3335   LVer->prepareNoAliasMetadata();
3336   return MemCheckBlock;
3337 }
3338 
3339 Value *InnerLoopVectorizer::emitTransformedIndex(
3340     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3341     const InductionDescriptor &ID) const {
3342 
3343   SCEVExpander Exp(*SE, DL, "induction");
3344   auto Step = ID.getStep();
3345   auto StartValue = ID.getStartValue();
3346   assert(Index->getType()->getScalarType() == Step->getType() &&
3347          "Index scalar type does not match StepValue type");
3348 
3349   // Note: the IR at this point is broken. We cannot use SE to create any new
3350   // SCEV and then expand it, hoping that SCEV's simplification will give us
3351   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3352   // lead to various SCEV crashes. So all we can do is to use builder and rely
3353   // on InstCombine for future simplifications. Here we handle some trivial
3354   // cases only.
3355   auto CreateAdd = [&B](Value *X, Value *Y) {
3356     assert(X->getType() == Y->getType() && "Types don't match!");
3357     if (auto *CX = dyn_cast<ConstantInt>(X))
3358       if (CX->isZero())
3359         return Y;
3360     if (auto *CY = dyn_cast<ConstantInt>(Y))
3361       if (CY->isZero())
3362         return X;
3363     return B.CreateAdd(X, Y);
3364   };
3365 
3366   // We allow X to be a vector type, in which case Y will potentially be
3367   // splatted into a vector with the same element count.
3368   auto CreateMul = [&B](Value *X, Value *Y) {
3369     assert(X->getType()->getScalarType() == Y->getType() &&
3370            "Types don't match!");
3371     if (auto *CX = dyn_cast<ConstantInt>(X))
3372       if (CX->isOne())
3373         return Y;
3374     if (auto *CY = dyn_cast<ConstantInt>(Y))
3375       if (CY->isOne())
3376         return X;
3377     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
3378     if (XVTy && !isa<VectorType>(Y->getType()))
3379       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
3380     return B.CreateMul(X, Y);
3381   };
3382 
3383   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3384   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3385   // the DomTree is not kept up-to-date for additional blocks generated in the
3386   // vector loop. By using the header as insertion point, we guarantee that the
3387   // expanded instructions dominate all their uses.
3388   auto GetInsertPoint = [this, &B]() {
3389     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3390     if (InsertBB != LoopVectorBody &&
3391         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3392       return LoopVectorBody->getTerminator();
3393     return &*B.GetInsertPoint();
3394   };
3395 
3396   switch (ID.getKind()) {
3397   case InductionDescriptor::IK_IntInduction: {
3398     assert(!isa<VectorType>(Index->getType()) &&
3399            "Vector indices not supported for integer inductions yet");
3400     assert(Index->getType() == StartValue->getType() &&
3401            "Index type does not match StartValue type");
3402     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3403       return B.CreateSub(StartValue, Index);
3404     auto *Offset = CreateMul(
3405         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3406     return CreateAdd(StartValue, Offset);
3407   }
3408   case InductionDescriptor::IK_PtrInduction: {
3409     assert(isa<SCEVConstant>(Step) &&
3410            "Expected constant step for pointer induction");
3411     return B.CreateGEP(
3412         StartValue->getType()->getPointerElementType(), StartValue,
3413         CreateMul(Index,
3414                   Exp.expandCodeFor(Step, Index->getType()->getScalarType(),
3415                                     GetInsertPoint())));
3416   }
3417   case InductionDescriptor::IK_FpInduction: {
3418     assert(!isa<VectorType>(Index->getType()) &&
3419            "Vector indices not supported for FP inductions yet");
3420     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3421     auto InductionBinOp = ID.getInductionBinOp();
3422     assert(InductionBinOp &&
3423            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3424             InductionBinOp->getOpcode() == Instruction::FSub) &&
3425            "Original bin op should be defined for FP induction");
3426 
3427     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3428     Value *MulExp = B.CreateFMul(StepValue, Index);
3429     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3430                          "induction");
3431   }
3432   case InductionDescriptor::IK_NoInduction:
3433     return nullptr;
3434   }
3435   llvm_unreachable("invalid enum");
3436 }
3437 
3438 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3439   LoopScalarBody = OrigLoop->getHeader();
3440   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3441   LoopExitBlock = OrigLoop->getUniqueExitBlock();
3442   assert(LoopExitBlock && "Must have an exit block");
3443   assert(LoopVectorPreHeader && "Invalid loop structure");
3444 
3445   LoopMiddleBlock =
3446       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3447                  LI, nullptr, Twine(Prefix) + "middle.block");
3448   LoopScalarPreHeader =
3449       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3450                  nullptr, Twine(Prefix) + "scalar.ph");
3451 
3452   // Set up branch from middle block to the exit and scalar preheader blocks.
3453   // completeLoopSkeleton will update the condition to use an iteration check,
3454   // if required to decide whether to execute the remainder.
3455   BranchInst *BrInst =
3456       BranchInst::Create(LoopExitBlock, LoopScalarPreHeader, Builder.getTrue());
3457   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3458   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3459   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3460 
3461   // We intentionally don't let SplitBlock to update LoopInfo since
3462   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3463   // LoopVectorBody is explicitly added to the correct place few lines later.
3464   LoopVectorBody =
3465       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3466                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3467 
3468   // Update dominator for loop exit.
3469   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3470 
3471   // Create and register the new vector loop.
3472   Loop *Lp = LI->AllocateLoop();
3473   Loop *ParentLoop = OrigLoop->getParentLoop();
3474 
3475   // Insert the new loop into the loop nest and register the new basic blocks
3476   // before calling any utilities such as SCEV that require valid LoopInfo.
3477   if (ParentLoop) {
3478     ParentLoop->addChildLoop(Lp);
3479   } else {
3480     LI->addTopLevelLoop(Lp);
3481   }
3482   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3483   return Lp;
3484 }
3485 
3486 void InnerLoopVectorizer::createInductionResumeValues(
3487     Loop *L, Value *VectorTripCount,
3488     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3489   assert(VectorTripCount && L && "Expected valid arguments");
3490   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3491           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3492          "Inconsistent information about additional bypass.");
3493   // We are going to resume the execution of the scalar loop.
3494   // Go over all of the induction variables that we found and fix the
3495   // PHIs that are left in the scalar version of the loop.
3496   // The starting values of PHI nodes depend on the counter of the last
3497   // iteration in the vectorized loop.
3498   // If we come from a bypass edge then we need to start from the original
3499   // start value.
3500   for (auto &InductionEntry : Legal->getInductionVars()) {
3501     PHINode *OrigPhi = InductionEntry.first;
3502     InductionDescriptor II = InductionEntry.second;
3503 
3504     // Create phi nodes to merge from the  backedge-taken check block.
3505     PHINode *BCResumeVal =
3506         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3507                         LoopScalarPreHeader->getTerminator());
3508     // Copy original phi DL over to the new one.
3509     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3510     Value *&EndValue = IVEndValues[OrigPhi];
3511     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3512     if (OrigPhi == OldInduction) {
3513       // We know what the end value is.
3514       EndValue = VectorTripCount;
3515     } else {
3516       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3517 
3518       // Fast-math-flags propagate from the original induction instruction.
3519       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3520         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3521 
3522       Type *StepType = II.getStep()->getType();
3523       Instruction::CastOps CastOp =
3524           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3525       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3526       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3527       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3528       EndValue->setName("ind.end");
3529 
3530       // Compute the end value for the additional bypass (if applicable).
3531       if (AdditionalBypass.first) {
3532         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3533         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3534                                          StepType, true);
3535         CRD =
3536             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3537         EndValueFromAdditionalBypass =
3538             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3539         EndValueFromAdditionalBypass->setName("ind.end");
3540       }
3541     }
3542     // The new PHI merges the original incoming value, in case of a bypass,
3543     // or the value at the end of the vectorized loop.
3544     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3545 
3546     // Fix the scalar body counter (PHI node).
3547     // The old induction's phi node in the scalar body needs the truncated
3548     // value.
3549     for (BasicBlock *BB : LoopBypassBlocks)
3550       BCResumeVal->addIncoming(II.getStartValue(), BB);
3551 
3552     if (AdditionalBypass.first)
3553       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3554                                             EndValueFromAdditionalBypass);
3555 
3556     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3557   }
3558 }
3559 
3560 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3561                                                       MDNode *OrigLoopID) {
3562   assert(L && "Expected valid loop.");
3563 
3564   // The trip counts should be cached by now.
3565   Value *Count = getOrCreateTripCount(L);
3566   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3567 
3568   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3569 
3570   // Add a check in the middle block to see if we have completed
3571   // all of the iterations in the first vector loop.
3572   // If (N - N%VF) == N, then we *don't* need to run the remainder.
3573   // If tail is to be folded, we know we don't need to run the remainder.
3574   if (!Cost->foldTailByMasking()) {
3575     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3576                                         Count, VectorTripCount, "cmp.n",
3577                                         LoopMiddleBlock->getTerminator());
3578 
3579     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3580     // of the corresponding compare because they may have ended up with
3581     // different line numbers and we want to avoid awkward line stepping while
3582     // debugging. Eg. if the compare has got a line number inside the loop.
3583     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3584     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3585   }
3586 
3587   // Get ready to start creating new instructions into the vectorized body.
3588   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3589          "Inconsistent vector loop preheader");
3590   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3591 
3592   Optional<MDNode *> VectorizedLoopID =
3593       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3594                                       LLVMLoopVectorizeFollowupVectorized});
3595   if (VectorizedLoopID.hasValue()) {
3596     L->setLoopID(VectorizedLoopID.getValue());
3597 
3598     // Do not setAlreadyVectorized if loop attributes have been defined
3599     // explicitly.
3600     return LoopVectorPreHeader;
3601   }
3602 
3603   // Keep all loop hints from the original loop on the vector loop (we'll
3604   // replace the vectorizer-specific hints below).
3605   if (MDNode *LID = OrigLoop->getLoopID())
3606     L->setLoopID(LID);
3607 
3608   LoopVectorizeHints Hints(L, true, *ORE);
3609   Hints.setAlreadyVectorized();
3610 
3611 #ifdef EXPENSIVE_CHECKS
3612   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3613   LI->verify(*DT);
3614 #endif
3615 
3616   return LoopVectorPreHeader;
3617 }
3618 
3619 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3620   /*
3621    In this function we generate a new loop. The new loop will contain
3622    the vectorized instructions while the old loop will continue to run the
3623    scalar remainder.
3624 
3625        [ ] <-- loop iteration number check.
3626     /   |
3627    /    v
3628   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3629   |  /  |
3630   | /   v
3631   ||   [ ]     <-- vector pre header.
3632   |/    |
3633   |     v
3634   |    [  ] \
3635   |    [  ]_|   <-- vector loop.
3636   |     |
3637   |     v
3638   |   -[ ]   <--- middle-block.
3639   |  /  |
3640   | /   v
3641   -|- >[ ]     <--- new preheader.
3642    |    |
3643    |    v
3644    |   [ ] \
3645    |   [ ]_|   <-- old scalar loop to handle remainder.
3646     \   |
3647      \  v
3648       >[ ]     <-- exit block.
3649    ...
3650    */
3651 
3652   // Get the metadata of the original loop before it gets modified.
3653   MDNode *OrigLoopID = OrigLoop->getLoopID();
3654 
3655   // Workaround!  Compute the trip count of the original loop and cache it
3656   // before we start modifying the CFG.  This code has a systemic problem
3657   // wherein it tries to run analysis over partially constructed IR; this is
3658   // wrong, and not simply for SCEV.  The trip count of the original loop
3659   // simply happens to be prone to hitting this in practice.  In theory, we
3660   // can hit the same issue for any SCEV, or ValueTracking query done during
3661   // mutation.  See PR49900.
3662   getOrCreateTripCount(OrigLoop);
3663 
3664   // Create an empty vector loop, and prepare basic blocks for the runtime
3665   // checks.
3666   Loop *Lp = createVectorLoopSkeleton("");
3667 
3668   // Now, compare the new count to zero. If it is zero skip the vector loop and
3669   // jump to the scalar loop. This check also covers the case where the
3670   // backedge-taken count is uint##_max: adding one to it will overflow leading
3671   // to an incorrect trip count of zero. In this (rare) case we will also jump
3672   // to the scalar loop.
3673   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3674 
3675   // Generate the code to check any assumptions that we've made for SCEV
3676   // expressions.
3677   emitSCEVChecks(Lp, LoopScalarPreHeader);
3678 
3679   // Generate the code that checks in runtime if arrays overlap. We put the
3680   // checks into a separate block to make the more common case of few elements
3681   // faster.
3682   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3683 
3684   // Some loops have a single integer induction variable, while other loops
3685   // don't. One example is c++ iterators that often have multiple pointer
3686   // induction variables. In the code below we also support a case where we
3687   // don't have a single induction variable.
3688   //
3689   // We try to obtain an induction variable from the original loop as hard
3690   // as possible. However if we don't find one that:
3691   //   - is an integer
3692   //   - counts from zero, stepping by one
3693   //   - is the size of the widest induction variable type
3694   // then we create a new one.
3695   OldInduction = Legal->getPrimaryInduction();
3696   Type *IdxTy = Legal->getWidestInductionType();
3697   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3698   // The loop step is equal to the vectorization factor (num of SIMD elements)
3699   // times the unroll factor (num of SIMD instructions).
3700   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3701   Value *Step = createStepForVF(Builder, ConstantInt::get(IdxTy, UF), VF);
3702   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3703   Induction =
3704       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3705                               getDebugLocFromInstOrOperands(OldInduction));
3706 
3707   // Emit phis for the new starting index of the scalar loop.
3708   createInductionResumeValues(Lp, CountRoundDown);
3709 
3710   return completeLoopSkeleton(Lp, OrigLoopID);
3711 }
3712 
3713 // Fix up external users of the induction variable. At this point, we are
3714 // in LCSSA form, with all external PHIs that use the IV having one input value,
3715 // coming from the remainder loop. We need those PHIs to also have a correct
3716 // value for the IV when arriving directly from the middle block.
3717 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3718                                        const InductionDescriptor &II,
3719                                        Value *CountRoundDown, Value *EndValue,
3720                                        BasicBlock *MiddleBlock) {
3721   // There are two kinds of external IV usages - those that use the value
3722   // computed in the last iteration (the PHI) and those that use the penultimate
3723   // value (the value that feeds into the phi from the loop latch).
3724   // We allow both, but they, obviously, have different values.
3725 
3726   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3727 
3728   DenseMap<Value *, Value *> MissingVals;
3729 
3730   // An external user of the last iteration's value should see the value that
3731   // the remainder loop uses to initialize its own IV.
3732   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3733   for (User *U : PostInc->users()) {
3734     Instruction *UI = cast<Instruction>(U);
3735     if (!OrigLoop->contains(UI)) {
3736       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3737       MissingVals[UI] = EndValue;
3738     }
3739   }
3740 
3741   // An external user of the penultimate value need to see EndValue - Step.
3742   // The simplest way to get this is to recompute it from the constituent SCEVs,
3743   // that is Start + (Step * (CRD - 1)).
3744   for (User *U : OrigPhi->users()) {
3745     auto *UI = cast<Instruction>(U);
3746     if (!OrigLoop->contains(UI)) {
3747       const DataLayout &DL =
3748           OrigLoop->getHeader()->getModule()->getDataLayout();
3749       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3750 
3751       IRBuilder<> B(MiddleBlock->getTerminator());
3752 
3753       // Fast-math-flags propagate from the original induction instruction.
3754       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3755         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3756 
3757       Value *CountMinusOne = B.CreateSub(
3758           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3759       Value *CMO =
3760           !II.getStep()->getType()->isIntegerTy()
3761               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3762                              II.getStep()->getType())
3763               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3764       CMO->setName("cast.cmo");
3765       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3766       Escape->setName("ind.escape");
3767       MissingVals[UI] = Escape;
3768     }
3769   }
3770 
3771   for (auto &I : MissingVals) {
3772     PHINode *PHI = cast<PHINode>(I.first);
3773     // One corner case we have to handle is two IVs "chasing" each-other,
3774     // that is %IV2 = phi [...], [ %IV1, %latch ]
3775     // In this case, if IV1 has an external use, we need to avoid adding both
3776     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3777     // don't already have an incoming value for the middle block.
3778     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3779       PHI->addIncoming(I.second, MiddleBlock);
3780   }
3781 }
3782 
3783 namespace {
3784 
3785 struct CSEDenseMapInfo {
3786   static bool canHandle(const Instruction *I) {
3787     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3788            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3789   }
3790 
3791   static inline Instruction *getEmptyKey() {
3792     return DenseMapInfo<Instruction *>::getEmptyKey();
3793   }
3794 
3795   static inline Instruction *getTombstoneKey() {
3796     return DenseMapInfo<Instruction *>::getTombstoneKey();
3797   }
3798 
3799   static unsigned getHashValue(const Instruction *I) {
3800     assert(canHandle(I) && "Unknown instruction!");
3801     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3802                                                            I->value_op_end()));
3803   }
3804 
3805   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3806     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3807         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3808       return LHS == RHS;
3809     return LHS->isIdenticalTo(RHS);
3810   }
3811 };
3812 
3813 } // end anonymous namespace
3814 
3815 ///Perform cse of induction variable instructions.
3816 static void cse(BasicBlock *BB) {
3817   // Perform simple cse.
3818   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3819   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3820     Instruction *In = &*I++;
3821 
3822     if (!CSEDenseMapInfo::canHandle(In))
3823       continue;
3824 
3825     // Check if we can replace this instruction with any of the
3826     // visited instructions.
3827     if (Instruction *V = CSEMap.lookup(In)) {
3828       In->replaceAllUsesWith(V);
3829       In->eraseFromParent();
3830       continue;
3831     }
3832 
3833     CSEMap[In] = In;
3834   }
3835 }
3836 
3837 InstructionCost
3838 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3839                                               bool &NeedToScalarize) const {
3840   Function *F = CI->getCalledFunction();
3841   Type *ScalarRetTy = CI->getType();
3842   SmallVector<Type *, 4> Tys, ScalarTys;
3843   for (auto &ArgOp : CI->arg_operands())
3844     ScalarTys.push_back(ArgOp->getType());
3845 
3846   // Estimate cost of scalarized vector call. The source operands are assumed
3847   // to be vectors, so we need to extract individual elements from there,
3848   // execute VF scalar calls, and then gather the result into the vector return
3849   // value.
3850   InstructionCost ScalarCallCost =
3851       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3852   if (VF.isScalar())
3853     return ScalarCallCost;
3854 
3855   // Compute corresponding vector type for return value and arguments.
3856   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3857   for (Type *ScalarTy : ScalarTys)
3858     Tys.push_back(ToVectorTy(ScalarTy, VF));
3859 
3860   // Compute costs of unpacking argument values for the scalar calls and
3861   // packing the return values to a vector.
3862   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3863 
3864   InstructionCost Cost =
3865       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3866 
3867   // If we can't emit a vector call for this function, then the currently found
3868   // cost is the cost we need to return.
3869   NeedToScalarize = true;
3870   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3871   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3872 
3873   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3874     return Cost;
3875 
3876   // If the corresponding vector cost is cheaper, return its cost.
3877   InstructionCost VectorCallCost =
3878       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3879   if (VectorCallCost < Cost) {
3880     NeedToScalarize = false;
3881     Cost = VectorCallCost;
3882   }
3883   return Cost;
3884 }
3885 
3886 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3887   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3888     return Elt;
3889   return VectorType::get(Elt, VF);
3890 }
3891 
3892 InstructionCost
3893 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3894                                                    ElementCount VF) const {
3895   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3896   assert(ID && "Expected intrinsic call!");
3897   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3898   FastMathFlags FMF;
3899   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3900     FMF = FPMO->getFastMathFlags();
3901 
3902   SmallVector<const Value *> Arguments(CI->arg_begin(), CI->arg_end());
3903   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3904   SmallVector<Type *> ParamTys;
3905   std::transform(FTy->param_begin(), FTy->param_end(),
3906                  std::back_inserter(ParamTys),
3907                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3908 
3909   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3910                                     dyn_cast<IntrinsicInst>(CI));
3911   return TTI.getIntrinsicInstrCost(CostAttrs,
3912                                    TargetTransformInfo::TCK_RecipThroughput);
3913 }
3914 
3915 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3916   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3917   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3918   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3919 }
3920 
3921 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3922   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3923   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3924   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3925 }
3926 
3927 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3928   // For every instruction `I` in MinBWs, truncate the operands, create a
3929   // truncated version of `I` and reextend its result. InstCombine runs
3930   // later and will remove any ext/trunc pairs.
3931   SmallPtrSet<Value *, 4> Erased;
3932   for (const auto &KV : Cost->getMinimalBitwidths()) {
3933     // If the value wasn't vectorized, we must maintain the original scalar
3934     // type. The absence of the value from State indicates that it
3935     // wasn't vectorized.
3936     VPValue *Def = State.Plan->getVPValue(KV.first);
3937     if (!State.hasAnyVectorValue(Def))
3938       continue;
3939     for (unsigned Part = 0; Part < UF; ++Part) {
3940       Value *I = State.get(Def, Part);
3941       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3942         continue;
3943       Type *OriginalTy = I->getType();
3944       Type *ScalarTruncatedTy =
3945           IntegerType::get(OriginalTy->getContext(), KV.second);
3946       auto *TruncatedTy = FixedVectorType::get(
3947           ScalarTruncatedTy,
3948           cast<FixedVectorType>(OriginalTy)->getNumElements());
3949       if (TruncatedTy == OriginalTy)
3950         continue;
3951 
3952       IRBuilder<> B(cast<Instruction>(I));
3953       auto ShrinkOperand = [&](Value *V) -> Value * {
3954         if (auto *ZI = dyn_cast<ZExtInst>(V))
3955           if (ZI->getSrcTy() == TruncatedTy)
3956             return ZI->getOperand(0);
3957         return B.CreateZExtOrTrunc(V, TruncatedTy);
3958       };
3959 
3960       // The actual instruction modification depends on the instruction type,
3961       // unfortunately.
3962       Value *NewI = nullptr;
3963       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3964         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3965                              ShrinkOperand(BO->getOperand(1)));
3966 
3967         // Any wrapping introduced by shrinking this operation shouldn't be
3968         // considered undefined behavior. So, we can't unconditionally copy
3969         // arithmetic wrapping flags to NewI.
3970         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3971       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3972         NewI =
3973             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3974                          ShrinkOperand(CI->getOperand(1)));
3975       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3976         NewI = B.CreateSelect(SI->getCondition(),
3977                               ShrinkOperand(SI->getTrueValue()),
3978                               ShrinkOperand(SI->getFalseValue()));
3979       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3980         switch (CI->getOpcode()) {
3981         default:
3982           llvm_unreachable("Unhandled cast!");
3983         case Instruction::Trunc:
3984           NewI = ShrinkOperand(CI->getOperand(0));
3985           break;
3986         case Instruction::SExt:
3987           NewI = B.CreateSExtOrTrunc(
3988               CI->getOperand(0),
3989               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3990           break;
3991         case Instruction::ZExt:
3992           NewI = B.CreateZExtOrTrunc(
3993               CI->getOperand(0),
3994               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3995           break;
3996         }
3997       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3998         auto Elements0 = cast<FixedVectorType>(SI->getOperand(0)->getType())
3999                              ->getNumElements();
4000         auto *O0 = B.CreateZExtOrTrunc(
4001             SI->getOperand(0),
4002             FixedVectorType::get(ScalarTruncatedTy, Elements0));
4003         auto Elements1 = cast<FixedVectorType>(SI->getOperand(1)->getType())
4004                              ->getNumElements();
4005         auto *O1 = B.CreateZExtOrTrunc(
4006             SI->getOperand(1),
4007             FixedVectorType::get(ScalarTruncatedTy, Elements1));
4008 
4009         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
4010       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
4011         // Don't do anything with the operands, just extend the result.
4012         continue;
4013       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
4014         auto Elements = cast<FixedVectorType>(IE->getOperand(0)->getType())
4015                             ->getNumElements();
4016         auto *O0 = B.CreateZExtOrTrunc(
4017             IE->getOperand(0),
4018             FixedVectorType::get(ScalarTruncatedTy, Elements));
4019         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
4020         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
4021       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
4022         auto Elements = cast<FixedVectorType>(EE->getOperand(0)->getType())
4023                             ->getNumElements();
4024         auto *O0 = B.CreateZExtOrTrunc(
4025             EE->getOperand(0),
4026             FixedVectorType::get(ScalarTruncatedTy, Elements));
4027         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
4028       } else {
4029         // If we don't know what to do, be conservative and don't do anything.
4030         continue;
4031       }
4032 
4033       // Lastly, extend the result.
4034       NewI->takeName(cast<Instruction>(I));
4035       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
4036       I->replaceAllUsesWith(Res);
4037       cast<Instruction>(I)->eraseFromParent();
4038       Erased.insert(I);
4039       State.reset(Def, Res, Part);
4040     }
4041   }
4042 
4043   // We'll have created a bunch of ZExts that are now parentless. Clean up.
4044   for (const auto &KV : Cost->getMinimalBitwidths()) {
4045     // If the value wasn't vectorized, we must maintain the original scalar
4046     // type. The absence of the value from State indicates that it
4047     // wasn't vectorized.
4048     VPValue *Def = State.Plan->getVPValue(KV.first);
4049     if (!State.hasAnyVectorValue(Def))
4050       continue;
4051     for (unsigned Part = 0; Part < UF; ++Part) {
4052       Value *I = State.get(Def, Part);
4053       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
4054       if (Inst && Inst->use_empty()) {
4055         Value *NewI = Inst->getOperand(0);
4056         Inst->eraseFromParent();
4057         State.reset(Def, NewI, Part);
4058       }
4059     }
4060   }
4061 }
4062 
4063 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
4064   // Insert truncates and extends for any truncated instructions as hints to
4065   // InstCombine.
4066   if (VF.isVector())
4067     truncateToMinimalBitwidths(State);
4068 
4069   // Fix widened non-induction PHIs by setting up the PHI operands.
4070   if (OrigPHIsToFix.size()) {
4071     assert(EnableVPlanNativePath &&
4072            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4073     fixNonInductionPHIs(State);
4074   }
4075 
4076   // At this point every instruction in the original loop is widened to a
4077   // vector form. Now we need to fix the recurrences in the loop. These PHI
4078   // nodes are currently empty because we did not want to introduce cycles.
4079   // This is the second stage of vectorizing recurrences.
4080   fixCrossIterationPHIs(State);
4081 
4082   // Forget the original basic block.
4083   PSE.getSE()->forgetLoop(OrigLoop);
4084 
4085   // Fix-up external users of the induction variables.
4086   for (auto &Entry : Legal->getInductionVars())
4087     fixupIVUsers(Entry.first, Entry.second,
4088                  getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4089                  IVEndValues[Entry.first], LoopMiddleBlock);
4090 
4091   fixLCSSAPHIs(State);
4092   for (Instruction *PI : PredicatedInstructions)
4093     sinkScalarOperands(&*PI);
4094 
4095   // Remove redundant induction instructions.
4096   cse(LoopVectorBody);
4097 
4098   // Set/update profile weights for the vector and remainder loops as original
4099   // loop iterations are now distributed among them. Note that original loop
4100   // represented by LoopScalarBody becomes remainder loop after vectorization.
4101   //
4102   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4103   // end up getting slightly roughened result but that should be OK since
4104   // profile is not inherently precise anyway. Note also possible bypass of
4105   // vector code caused by legality checks is ignored, assigning all the weight
4106   // to the vector loop, optimistically.
4107   //
4108   // For scalable vectorization we can't know at compile time how many iterations
4109   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4110   // vscale of '1'.
4111   setProfileInfoAfterUnrolling(
4112       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4113       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4114 }
4115 
4116 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4117   // In order to support recurrences we need to be able to vectorize Phi nodes.
4118   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4119   // stage #2: We now need to fix the recurrences by adding incoming edges to
4120   // the currently empty PHI nodes. At this point every instruction in the
4121   // original loop is widened to a vector form so we can use them to construct
4122   // the incoming edges.
4123   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4124   for (VPRecipeBase &R : Header->phis()) {
4125     auto *PhiR = dyn_cast<VPWidenPHIRecipe>(&R);
4126     if (!PhiR)
4127       continue;
4128     auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4129     if (PhiR->getRecurrenceDescriptor()) {
4130       fixReduction(PhiR, State);
4131     } else if (Legal->isFirstOrderRecurrence(OrigPhi))
4132       fixFirstOrderRecurrence(PhiR, State);
4133   }
4134 }
4135 
4136 void InnerLoopVectorizer::fixFirstOrderRecurrence(VPWidenPHIRecipe *PhiR,
4137                                                   VPTransformState &State) {
4138   // This is the second phase of vectorizing first-order recurrences. An
4139   // overview of the transformation is described below. Suppose we have the
4140   // following loop.
4141   //
4142   //   for (int i = 0; i < n; ++i)
4143   //     b[i] = a[i] - a[i - 1];
4144   //
4145   // There is a first-order recurrence on "a". For this loop, the shorthand
4146   // scalar IR looks like:
4147   //
4148   //   scalar.ph:
4149   //     s_init = a[-1]
4150   //     br scalar.body
4151   //
4152   //   scalar.body:
4153   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4154   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4155   //     s2 = a[i]
4156   //     b[i] = s2 - s1
4157   //     br cond, scalar.body, ...
4158   //
4159   // In this example, s1 is a recurrence because it's value depends on the
4160   // previous iteration. In the first phase of vectorization, we created a
4161   // temporary value for s1. We now complete the vectorization and produce the
4162   // shorthand vector IR shown below (for VF = 4, UF = 1).
4163   //
4164   //   vector.ph:
4165   //     v_init = vector(..., ..., ..., a[-1])
4166   //     br vector.body
4167   //
4168   //   vector.body
4169   //     i = phi [0, vector.ph], [i+4, vector.body]
4170   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4171   //     v2 = a[i, i+1, i+2, i+3];
4172   //     v3 = vector(v1(3), v2(0, 1, 2))
4173   //     b[i, i+1, i+2, i+3] = v2 - v3
4174   //     br cond, vector.body, middle.block
4175   //
4176   //   middle.block:
4177   //     x = v2(3)
4178   //     br scalar.ph
4179   //
4180   //   scalar.ph:
4181   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4182   //     br scalar.body
4183   //
4184   // After execution completes the vector loop, we extract the next value of
4185   // the recurrence (x) to use as the initial value in the scalar loop.
4186 
4187   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
4188 
4189   auto *IdxTy = Builder.getInt32Ty();
4190   auto *One = ConstantInt::get(IdxTy, 1);
4191 
4192   // Create a vector from the initial value.
4193   auto *VectorInit = ScalarInit;
4194   if (VF.isVector()) {
4195     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4196     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4197     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4198     VectorInit = Builder.CreateInsertElement(
4199         PoisonValue::get(VectorType::get(VectorInit->getType(), VF)),
4200         VectorInit, LastIdx, "vector.recur.init");
4201   }
4202 
4203   VPValue *PreviousDef = PhiR->getBackedgeValue();
4204   // We constructed a temporary phi node in the first phase of vectorization.
4205   // This phi node will eventually be deleted.
4206   Builder.SetInsertPoint(cast<Instruction>(State.get(PhiR, 0)));
4207 
4208   // Create a phi node for the new recurrence. The current value will either be
4209   // the initial value inserted into a vector or loop-varying vector value.
4210   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4211   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4212 
4213   // Get the vectorized previous value of the last part UF - 1. It appears last
4214   // among all unrolled iterations, due to the order of their construction.
4215   Value *PreviousLastPart = State.get(PreviousDef, UF - 1);
4216 
4217   // Find and set the insertion point after the previous value if it is an
4218   // instruction.
4219   BasicBlock::iterator InsertPt;
4220   // Note that the previous value may have been constant-folded so it is not
4221   // guaranteed to be an instruction in the vector loop.
4222   // FIXME: Loop invariant values do not form recurrences. We should deal with
4223   //        them earlier.
4224   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart))
4225     InsertPt = LoopVectorBody->getFirstInsertionPt();
4226   else {
4227     Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
4228     if (isa<PHINode>(PreviousLastPart))
4229       // If the previous value is a phi node, we should insert after all the phi
4230       // nodes in the block containing the PHI to avoid breaking basic block
4231       // verification. Note that the basic block may be different to
4232       // LoopVectorBody, in case we predicate the loop.
4233       InsertPt = PreviousInst->getParent()->getFirstInsertionPt();
4234     else
4235       InsertPt = ++PreviousInst->getIterator();
4236   }
4237   Builder.SetInsertPoint(&*InsertPt);
4238 
4239   // The vector from which to take the initial value for the current iteration
4240   // (actual or unrolled). Initially, this is the vector phi node.
4241   Value *Incoming = VecPhi;
4242 
4243   // Shuffle the current and previous vector and update the vector parts.
4244   for (unsigned Part = 0; Part < UF; ++Part) {
4245     Value *PreviousPart = State.get(PreviousDef, Part);
4246     Value *PhiPart = State.get(PhiR, Part);
4247     auto *Shuffle = VF.isVector()
4248                         ? Builder.CreateVectorSplice(Incoming, PreviousPart, -1)
4249                         : Incoming;
4250     PhiPart->replaceAllUsesWith(Shuffle);
4251     cast<Instruction>(PhiPart)->eraseFromParent();
4252     State.reset(PhiR, Shuffle, Part);
4253     Incoming = PreviousPart;
4254   }
4255 
4256   // Fix the latch value of the new recurrence in the vector loop.
4257   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4258 
4259   // Extract the last vector element in the middle block. This will be the
4260   // initial value for the recurrence when jumping to the scalar loop.
4261   auto *ExtractForScalar = Incoming;
4262   if (VF.isVector()) {
4263     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4264     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4265     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
4266     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
4267                                                     "vector.recur.extract");
4268   }
4269   // Extract the second last element in the middle block if the
4270   // Phi is used outside the loop. We need to extract the phi itself
4271   // and not the last element (the phi update in the current iteration). This
4272   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4273   // when the scalar loop is not run at all.
4274   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4275   if (VF.isVector()) {
4276     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
4277     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
4278     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4279         Incoming, Idx, "vector.recur.extract.for.phi");
4280   } else if (UF > 1)
4281     // When loop is unrolled without vectorizing, initialize
4282     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
4283     // of `Incoming`. This is analogous to the vectorized case above: extracting
4284     // the second last element when VF > 1.
4285     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4286 
4287   // Fix the initial value of the original recurrence in the scalar loop.
4288   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4289   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
4290   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4291   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4292     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4293     Start->addIncoming(Incoming, BB);
4294   }
4295 
4296   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4297   Phi->setName("scalar.recur");
4298 
4299   // Finally, fix users of the recurrence outside the loop. The users will need
4300   // either the last value of the scalar recurrence or the last value of the
4301   // vector recurrence we extracted in the middle block. Since the loop is in
4302   // LCSSA form, we just need to find all the phi nodes for the original scalar
4303   // recurrence in the exit block, and then add an edge for the middle block.
4304   // Note that LCSSA does not imply single entry when the original scalar loop
4305   // had multiple exiting edges (as we always run the last iteration in the
4306   // scalar epilogue); in that case, the exiting path through middle will be
4307   // dynamically dead and the value picked for the phi doesn't matter.
4308   for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4309     if (any_of(LCSSAPhi.incoming_values(),
4310                [Phi](Value *V) { return V == Phi; }))
4311       LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4312 }
4313 
4314 void InnerLoopVectorizer::fixReduction(VPWidenPHIRecipe *PhiR,
4315                                        VPTransformState &State) {
4316   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4317   // Get it's reduction variable descriptor.
4318   assert(Legal->isReductionVariable(OrigPhi) &&
4319          "Unable to find the reduction variable");
4320   const RecurrenceDescriptor &RdxDesc = *PhiR->getRecurrenceDescriptor();
4321 
4322   RecurKind RK = RdxDesc.getRecurrenceKind();
4323   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4324   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4325   setDebugLocFromInst(Builder, ReductionStartValue);
4326   bool IsInLoopReductionPhi = Cost->isInLoopReduction(OrigPhi);
4327 
4328   VPValue *LoopExitInstDef = State.Plan->getVPValue(LoopExitInst);
4329   // This is the vector-clone of the value that leaves the loop.
4330   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4331 
4332   // Wrap flags are in general invalid after vectorization, clear them.
4333   clearReductionWrapFlags(RdxDesc, State);
4334 
4335   // Fix the vector-loop phi.
4336 
4337   // Reductions do not have to start at zero. They can start with
4338   // any loop invariant values.
4339   BasicBlock *VectorLoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4340 
4341   bool IsOrdered = IsInLoopReductionPhi && Cost->useOrderedReductions(RdxDesc);
4342 
4343   for (unsigned Part = 0; Part < UF; ++Part) {
4344     if (IsOrdered && Part > 0)
4345       break;
4346     Value *VecRdxPhi = State.get(PhiR->getVPSingleValue(), Part);
4347     Value *Val = State.get(PhiR->getBackedgeValue(), Part);
4348     if (IsOrdered)
4349       Val = State.get(PhiR->getBackedgeValue(), UF - 1);
4350 
4351     cast<PHINode>(VecRdxPhi)->addIncoming(Val, VectorLoopLatch);
4352   }
4353 
4354   // Before each round, move the insertion point right between
4355   // the PHIs and the values we are going to write.
4356   // This allows us to write both PHINodes and the extractelement
4357   // instructions.
4358   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4359 
4360   setDebugLocFromInst(Builder, LoopExitInst);
4361 
4362   Type *PhiTy = OrigPhi->getType();
4363   // If tail is folded by masking, the vector value to leave the loop should be
4364   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4365   // instead of the former. For an inloop reduction the reduction will already
4366   // be predicated, and does not need to be handled here.
4367   if (Cost->foldTailByMasking() && !IsInLoopReductionPhi) {
4368     for (unsigned Part = 0; Part < UF; ++Part) {
4369       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4370       Value *Sel = nullptr;
4371       for (User *U : VecLoopExitInst->users()) {
4372         if (isa<SelectInst>(U)) {
4373           assert(!Sel && "Reduction exit feeding two selects");
4374           Sel = U;
4375         } else
4376           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4377       }
4378       assert(Sel && "Reduction exit feeds no select");
4379       State.reset(LoopExitInstDef, Sel, Part);
4380 
4381       // If the target can create a predicated operator for the reduction at no
4382       // extra cost in the loop (for example a predicated vadd), it can be
4383       // cheaper for the select to remain in the loop than be sunk out of it,
4384       // and so use the select value for the phi instead of the old
4385       // LoopExitValue.
4386       if (PreferPredicatedReductionSelect ||
4387           TTI->preferPredicatedReductionSelect(
4388               RdxDesc.getOpcode(), PhiTy,
4389               TargetTransformInfo::ReductionFlags())) {
4390         auto *VecRdxPhi =
4391             cast<PHINode>(State.get(PhiR->getVPSingleValue(), Part));
4392         VecRdxPhi->setIncomingValueForBlock(
4393             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4394       }
4395     }
4396   }
4397 
4398   // If the vector reduction can be performed in a smaller type, we truncate
4399   // then extend the loop exit value to enable InstCombine to evaluate the
4400   // entire expression in the smaller type.
4401   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4402     assert(!IsInLoopReductionPhi && "Unexpected truncated inloop reduction!");
4403     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4404     Builder.SetInsertPoint(
4405         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4406     VectorParts RdxParts(UF);
4407     for (unsigned Part = 0; Part < UF; ++Part) {
4408       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4409       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4410       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4411                                         : Builder.CreateZExt(Trunc, VecTy);
4412       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4413            UI != RdxParts[Part]->user_end();)
4414         if (*UI != Trunc) {
4415           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4416           RdxParts[Part] = Extnd;
4417         } else {
4418           ++UI;
4419         }
4420     }
4421     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4422     for (unsigned Part = 0; Part < UF; ++Part) {
4423       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4424       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4425     }
4426   }
4427 
4428   // Reduce all of the unrolled parts into a single vector.
4429   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4430   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4431 
4432   // The middle block terminator has already been assigned a DebugLoc here (the
4433   // OrigLoop's single latch terminator). We want the whole middle block to
4434   // appear to execute on this line because: (a) it is all compiler generated,
4435   // (b) these instructions are always executed after evaluating the latch
4436   // conditional branch, and (c) other passes may add new predecessors which
4437   // terminate on this line. This is the easiest way to ensure we don't
4438   // accidentally cause an extra step back into the loop while debugging.
4439   setDebugLocFromInst(Builder, LoopMiddleBlock->getTerminator());
4440   if (IsOrdered)
4441     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4442   else {
4443     // Floating-point operations should have some FMF to enable the reduction.
4444     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4445     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4446     for (unsigned Part = 1; Part < UF; ++Part) {
4447       Value *RdxPart = State.get(LoopExitInstDef, Part);
4448       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4449         ReducedPartRdx = Builder.CreateBinOp(
4450             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4451       } else {
4452         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4453       }
4454     }
4455   }
4456 
4457   // Create the reduction after the loop. Note that inloop reductions create the
4458   // target reduction in the loop using a Reduction recipe.
4459   if (VF.isVector() && !IsInLoopReductionPhi) {
4460     ReducedPartRdx =
4461         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx);
4462     // If the reduction can be performed in a smaller type, we need to extend
4463     // the reduction to the wider type before we branch to the original loop.
4464     if (PhiTy != RdxDesc.getRecurrenceType())
4465       ReducedPartRdx = RdxDesc.isSigned()
4466                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4467                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4468   }
4469 
4470   // Create a phi node that merges control-flow from the backedge-taken check
4471   // block and the middle block.
4472   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4473                                         LoopScalarPreHeader->getTerminator());
4474   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4475     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4476   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4477 
4478   // Now, we need to fix the users of the reduction variable
4479   // inside and outside of the scalar remainder loop.
4480 
4481   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4482   // in the exit blocks.  See comment on analogous loop in
4483   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4484   for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4485     if (any_of(LCSSAPhi.incoming_values(),
4486                [LoopExitInst](Value *V) { return V == LoopExitInst; }))
4487       LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4488 
4489   // Fix the scalar loop reduction variable with the incoming reduction sum
4490   // from the vector body and from the backedge value.
4491   int IncomingEdgeBlockIdx =
4492       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4493   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4494   // Pick the other block.
4495   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4496   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4497   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4498 }
4499 
4500 void InnerLoopVectorizer::clearReductionWrapFlags(const RecurrenceDescriptor &RdxDesc,
4501                                                   VPTransformState &State) {
4502   RecurKind RK = RdxDesc.getRecurrenceKind();
4503   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4504     return;
4505 
4506   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4507   assert(LoopExitInstr && "null loop exit instruction");
4508   SmallVector<Instruction *, 8> Worklist;
4509   SmallPtrSet<Instruction *, 8> Visited;
4510   Worklist.push_back(LoopExitInstr);
4511   Visited.insert(LoopExitInstr);
4512 
4513   while (!Worklist.empty()) {
4514     Instruction *Cur = Worklist.pop_back_val();
4515     if (isa<OverflowingBinaryOperator>(Cur))
4516       for (unsigned Part = 0; Part < UF; ++Part) {
4517         Value *V = State.get(State.Plan->getVPValue(Cur), Part);
4518         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4519       }
4520 
4521     for (User *U : Cur->users()) {
4522       Instruction *UI = cast<Instruction>(U);
4523       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4524           Visited.insert(UI).second)
4525         Worklist.push_back(UI);
4526     }
4527   }
4528 }
4529 
4530 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4531   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4532     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4533       // Some phis were already hand updated by the reduction and recurrence
4534       // code above, leave them alone.
4535       continue;
4536 
4537     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4538     // Non-instruction incoming values will have only one value.
4539 
4540     VPLane Lane = VPLane::getFirstLane();
4541     if (isa<Instruction>(IncomingValue) &&
4542         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4543                                            VF))
4544       Lane = VPLane::getLastLaneForVF(VF);
4545 
4546     // Can be a loop invariant incoming value or the last scalar value to be
4547     // extracted from the vectorized loop.
4548     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4549     Value *lastIncomingValue =
4550         OrigLoop->isLoopInvariant(IncomingValue)
4551             ? IncomingValue
4552             : State.get(State.Plan->getVPValue(IncomingValue),
4553                         VPIteration(UF - 1, Lane));
4554     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4555   }
4556 }
4557 
4558 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4559   // The basic block and loop containing the predicated instruction.
4560   auto *PredBB = PredInst->getParent();
4561   auto *VectorLoop = LI->getLoopFor(PredBB);
4562 
4563   // Initialize a worklist with the operands of the predicated instruction.
4564   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4565 
4566   // Holds instructions that we need to analyze again. An instruction may be
4567   // reanalyzed if we don't yet know if we can sink it or not.
4568   SmallVector<Instruction *, 8> InstsToReanalyze;
4569 
4570   // Returns true if a given use occurs in the predicated block. Phi nodes use
4571   // their operands in their corresponding predecessor blocks.
4572   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4573     auto *I = cast<Instruction>(U.getUser());
4574     BasicBlock *BB = I->getParent();
4575     if (auto *Phi = dyn_cast<PHINode>(I))
4576       BB = Phi->getIncomingBlock(
4577           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4578     return BB == PredBB;
4579   };
4580 
4581   // Iteratively sink the scalarized operands of the predicated instruction
4582   // into the block we created for it. When an instruction is sunk, it's
4583   // operands are then added to the worklist. The algorithm ends after one pass
4584   // through the worklist doesn't sink a single instruction.
4585   bool Changed;
4586   do {
4587     // Add the instructions that need to be reanalyzed to the worklist, and
4588     // reset the changed indicator.
4589     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4590     InstsToReanalyze.clear();
4591     Changed = false;
4592 
4593     while (!Worklist.empty()) {
4594       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4595 
4596       // We can't sink an instruction if it is a phi node, is not in the loop,
4597       // or may have side effects.
4598       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4599           I->mayHaveSideEffects())
4600         continue;
4601 
4602       // If the instruction is already in PredBB, check if we can sink its
4603       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4604       // sinking the scalar instruction I, hence it appears in PredBB; but it
4605       // may have failed to sink I's operands (recursively), which we try
4606       // (again) here.
4607       if (I->getParent() == PredBB) {
4608         Worklist.insert(I->op_begin(), I->op_end());
4609         continue;
4610       }
4611 
4612       // It's legal to sink the instruction if all its uses occur in the
4613       // predicated block. Otherwise, there's nothing to do yet, and we may
4614       // need to reanalyze the instruction.
4615       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4616         InstsToReanalyze.push_back(I);
4617         continue;
4618       }
4619 
4620       // Move the instruction to the beginning of the predicated block, and add
4621       // it's operands to the worklist.
4622       I->moveBefore(&*PredBB->getFirstInsertionPt());
4623       Worklist.insert(I->op_begin(), I->op_end());
4624 
4625       // The sinking may have enabled other instructions to be sunk, so we will
4626       // need to iterate.
4627       Changed = true;
4628     }
4629   } while (Changed);
4630 }
4631 
4632 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4633   for (PHINode *OrigPhi : OrigPHIsToFix) {
4634     VPWidenPHIRecipe *VPPhi =
4635         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4636     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4637     // Make sure the builder has a valid insert point.
4638     Builder.SetInsertPoint(NewPhi);
4639     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4640       VPValue *Inc = VPPhi->getIncomingValue(i);
4641       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4642       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4643     }
4644   }
4645 }
4646 
4647 bool InnerLoopVectorizer::useOrderedReductions(RecurrenceDescriptor &RdxDesc) {
4648   return Cost->useOrderedReductions(RdxDesc);
4649 }
4650 
4651 void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPValue *VPDef,
4652                                    VPUser &Operands, unsigned UF,
4653                                    ElementCount VF, bool IsPtrLoopInvariant,
4654                                    SmallBitVector &IsIndexLoopInvariant,
4655                                    VPTransformState &State) {
4656   // Construct a vector GEP by widening the operands of the scalar GEP as
4657   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4658   // results in a vector of pointers when at least one operand of the GEP
4659   // is vector-typed. Thus, to keep the representation compact, we only use
4660   // vector-typed operands for loop-varying values.
4661 
4662   if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
4663     // If we are vectorizing, but the GEP has only loop-invariant operands,
4664     // the GEP we build (by only using vector-typed operands for
4665     // loop-varying values) would be a scalar pointer. Thus, to ensure we
4666     // produce a vector of pointers, we need to either arbitrarily pick an
4667     // operand to broadcast, or broadcast a clone of the original GEP.
4668     // Here, we broadcast a clone of the original.
4669     //
4670     // TODO: If at some point we decide to scalarize instructions having
4671     //       loop-invariant operands, this special case will no longer be
4672     //       required. We would add the scalarization decision to
4673     //       collectLoopScalars() and teach getVectorValue() to broadcast
4674     //       the lane-zero scalar value.
4675     auto *Clone = Builder.Insert(GEP->clone());
4676     for (unsigned Part = 0; Part < UF; ++Part) {
4677       Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4678       State.set(VPDef, EntryPart, Part);
4679       addMetadata(EntryPart, GEP);
4680     }
4681   } else {
4682     // If the GEP has at least one loop-varying operand, we are sure to
4683     // produce a vector of pointers. But if we are only unrolling, we want
4684     // to produce a scalar GEP for each unroll part. Thus, the GEP we
4685     // produce with the code below will be scalar (if VF == 1) or vector
4686     // (otherwise). Note that for the unroll-only case, we still maintain
4687     // values in the vector mapping with initVector, as we do for other
4688     // instructions.
4689     for (unsigned Part = 0; Part < UF; ++Part) {
4690       // The pointer operand of the new GEP. If it's loop-invariant, we
4691       // won't broadcast it.
4692       auto *Ptr = IsPtrLoopInvariant
4693                       ? State.get(Operands.getOperand(0), VPIteration(0, 0))
4694                       : State.get(Operands.getOperand(0), Part);
4695 
4696       // Collect all the indices for the new GEP. If any index is
4697       // loop-invariant, we won't broadcast it.
4698       SmallVector<Value *, 4> Indices;
4699       for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
4700         VPValue *Operand = Operands.getOperand(I);
4701         if (IsIndexLoopInvariant[I - 1])
4702           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
4703         else
4704           Indices.push_back(State.get(Operand, Part));
4705       }
4706 
4707       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4708       // but it should be a vector, otherwise.
4709       auto *NewGEP =
4710           GEP->isInBounds()
4711               ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
4712                                           Indices)
4713               : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
4714       assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
4715              "NewGEP is not a pointer vector");
4716       State.set(VPDef, NewGEP, Part);
4717       addMetadata(NewGEP, GEP);
4718     }
4719   }
4720 }
4721 
4722 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4723                                               RecurrenceDescriptor *RdxDesc,
4724                                               VPWidenPHIRecipe *PhiR,
4725                                               VPTransformState &State) {
4726   PHINode *P = cast<PHINode>(PN);
4727   if (EnableVPlanNativePath) {
4728     // Currently we enter here in the VPlan-native path for non-induction
4729     // PHIs where all control flow is uniform. We simply widen these PHIs.
4730     // Create a vector phi with no operands - the vector phi operands will be
4731     // set at the end of vector code generation.
4732     Type *VecTy = (State.VF.isScalar())
4733                       ? PN->getType()
4734                       : VectorType::get(PN->getType(), State.VF);
4735     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4736     State.set(PhiR, VecPhi, 0);
4737     OrigPHIsToFix.push_back(P);
4738 
4739     return;
4740   }
4741 
4742   assert(PN->getParent() == OrigLoop->getHeader() &&
4743          "Non-header phis should have been handled elsewhere");
4744 
4745   // In order to support recurrences we need to be able to vectorize Phi nodes.
4746   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4747   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4748   // this value when we vectorize all of the instructions that use the PHI.
4749   if (RdxDesc || Legal->isFirstOrderRecurrence(P)) {
4750     bool ScalarPHI =
4751         (State.VF.isScalar()) || Cost->isInLoopReduction(cast<PHINode>(PN));
4752     Type *VecTy =
4753         ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF);
4754 
4755     bool IsOrdered = Cost->isInLoopReduction(cast<PHINode>(PN)) &&
4756                      Cost->useOrderedReductions(*RdxDesc);
4757     unsigned LastPartForNewPhi = IsOrdered ? 1 : State.UF;
4758     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
4759       Value *EntryPart = PHINode::Create(
4760           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4761       State.set(PhiR, EntryPart, Part);
4762     }
4763     if (Legal->isFirstOrderRecurrence(P))
4764       return;
4765     VPValue *StartVPV = PhiR->getStartValue();
4766     Value *StartV = StartVPV->getLiveInIRValue();
4767 
4768     Value *Iden = nullptr;
4769 
4770     assert(Legal->isReductionVariable(P) && StartV &&
4771            "RdxDesc should only be set for reduction variables; in that case "
4772            "a StartV is also required");
4773     RecurKind RK = RdxDesc->getRecurrenceKind();
4774     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK)) {
4775       // MinMax reduction have the start value as their identify.
4776       if (ScalarPHI) {
4777         Iden = StartV;
4778       } else {
4779         IRBuilderBase::InsertPointGuard IPBuilder(Builder);
4780         Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4781         StartV = Iden =
4782             Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident");
4783       }
4784     } else {
4785       Constant *IdenC = RecurrenceDescriptor::getRecurrenceIdentity(
4786           RK, VecTy->getScalarType(), RdxDesc->getFastMathFlags());
4787       Iden = IdenC;
4788 
4789       if (!ScalarPHI) {
4790         Iden = ConstantVector::getSplat(State.VF, IdenC);
4791         IRBuilderBase::InsertPointGuard IPBuilder(Builder);
4792         Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4793         Constant *Zero = Builder.getInt32(0);
4794         StartV = Builder.CreateInsertElement(Iden, StartV, Zero);
4795       }
4796     }
4797 
4798     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
4799       Value *EntryPart = State.get(PhiR, Part);
4800       // Make sure to add the reduction start value only to the
4801       // first unroll part.
4802       Value *StartVal = (Part == 0) ? StartV : Iden;
4803       cast<PHINode>(EntryPart)->addIncoming(StartVal, LoopVectorPreHeader);
4804     }
4805 
4806     return;
4807   }
4808 
4809   assert(!Legal->isReductionVariable(P) &&
4810          "reductions should be handled above");
4811 
4812   setDebugLocFromInst(Builder, P);
4813 
4814   // This PHINode must be an induction variable.
4815   // Make sure that we know about it.
4816   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4817 
4818   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4819   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4820 
4821   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4822   // which can be found from the original scalar operations.
4823   switch (II.getKind()) {
4824   case InductionDescriptor::IK_NoInduction:
4825     llvm_unreachable("Unknown induction");
4826   case InductionDescriptor::IK_IntInduction:
4827   case InductionDescriptor::IK_FpInduction:
4828     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4829   case InductionDescriptor::IK_PtrInduction: {
4830     // Handle the pointer induction variable case.
4831     assert(P->getType()->isPointerTy() && "Unexpected type.");
4832 
4833     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4834       // This is the normalized GEP that starts counting at zero.
4835       Value *PtrInd =
4836           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4837       // Determine the number of scalars we need to generate for each unroll
4838       // iteration. If the instruction is uniform, we only need to generate the
4839       // first lane. Otherwise, we generate all VF values.
4840       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4841       unsigned Lanes = IsUniform ? 1 : State.VF.getKnownMinValue();
4842 
4843       bool NeedsVectorIndex = !IsUniform && VF.isScalable();
4844       Value *UnitStepVec = nullptr, *PtrIndSplat = nullptr;
4845       if (NeedsVectorIndex) {
4846         Type *VecIVTy = VectorType::get(PtrInd->getType(), VF);
4847         UnitStepVec = Builder.CreateStepVector(VecIVTy);
4848         PtrIndSplat = Builder.CreateVectorSplat(VF, PtrInd);
4849       }
4850 
4851       for (unsigned Part = 0; Part < UF; ++Part) {
4852         Value *PartStart = createStepForVF(
4853             Builder, ConstantInt::get(PtrInd->getType(), Part), VF);
4854 
4855         if (NeedsVectorIndex) {
4856           Value *PartStartSplat = Builder.CreateVectorSplat(VF, PartStart);
4857           Value *Indices = Builder.CreateAdd(PartStartSplat, UnitStepVec);
4858           Value *GlobalIndices = Builder.CreateAdd(PtrIndSplat, Indices);
4859           Value *SclrGep =
4860               emitTransformedIndex(Builder, GlobalIndices, PSE.getSE(), DL, II);
4861           SclrGep->setName("next.gep");
4862           State.set(PhiR, SclrGep, Part);
4863           // We've cached the whole vector, which means we can support the
4864           // extraction of any lane.
4865           continue;
4866         }
4867 
4868         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4869           Value *Idx = Builder.CreateAdd(
4870               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4871           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4872           Value *SclrGep =
4873               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4874           SclrGep->setName("next.gep");
4875           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4876         }
4877       }
4878       return;
4879     }
4880     assert(isa<SCEVConstant>(II.getStep()) &&
4881            "Induction step not a SCEV constant!");
4882     Type *PhiType = II.getStep()->getType();
4883 
4884     // Build a pointer phi
4885     Value *ScalarStartValue = II.getStartValue();
4886     Type *ScStValueType = ScalarStartValue->getType();
4887     PHINode *NewPointerPhi =
4888         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4889     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4890 
4891     // A pointer induction, performed by using a gep
4892     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4893     Instruction *InductionLoc = LoopLatch->getTerminator();
4894     const SCEV *ScalarStep = II.getStep();
4895     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4896     Value *ScalarStepValue =
4897         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4898     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4899     Value *NumUnrolledElems =
4900         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4901     Value *InductionGEP = GetElementPtrInst::Create(
4902         ScStValueType->getPointerElementType(), NewPointerPhi,
4903         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4904         InductionLoc);
4905     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4906 
4907     // Create UF many actual address geps that use the pointer
4908     // phi as base and a vectorized version of the step value
4909     // (<step*0, ..., step*N>) as offset.
4910     for (unsigned Part = 0; Part < State.UF; ++Part) {
4911       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4912       Value *StartOffsetScalar =
4913           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4914       Value *StartOffset =
4915           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4916       // Create a vector of consecutive numbers from zero to VF.
4917       StartOffset =
4918           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4919 
4920       Value *GEP = Builder.CreateGEP(
4921           ScStValueType->getPointerElementType(), NewPointerPhi,
4922           Builder.CreateMul(
4923               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4924               "vector.gep"));
4925       State.set(PhiR, GEP, Part);
4926     }
4927   }
4928   }
4929 }
4930 
4931 /// A helper function for checking whether an integer division-related
4932 /// instruction may divide by zero (in which case it must be predicated if
4933 /// executed conditionally in the scalar code).
4934 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4935 /// Non-zero divisors that are non compile-time constants will not be
4936 /// converted into multiplication, so we will still end up scalarizing
4937 /// the division, but can do so w/o predication.
4938 static bool mayDivideByZero(Instruction &I) {
4939   assert((I.getOpcode() == Instruction::UDiv ||
4940           I.getOpcode() == Instruction::SDiv ||
4941           I.getOpcode() == Instruction::URem ||
4942           I.getOpcode() == Instruction::SRem) &&
4943          "Unexpected instruction");
4944   Value *Divisor = I.getOperand(1);
4945   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4946   return !CInt || CInt->isZero();
4947 }
4948 
4949 void InnerLoopVectorizer::widenInstruction(Instruction &I, VPValue *Def,
4950                                            VPUser &User,
4951                                            VPTransformState &State) {
4952   switch (I.getOpcode()) {
4953   case Instruction::Call:
4954   case Instruction::Br:
4955   case Instruction::PHI:
4956   case Instruction::GetElementPtr:
4957   case Instruction::Select:
4958     llvm_unreachable("This instruction is handled by a different recipe.");
4959   case Instruction::UDiv:
4960   case Instruction::SDiv:
4961   case Instruction::SRem:
4962   case Instruction::URem:
4963   case Instruction::Add:
4964   case Instruction::FAdd:
4965   case Instruction::Sub:
4966   case Instruction::FSub:
4967   case Instruction::FNeg:
4968   case Instruction::Mul:
4969   case Instruction::FMul:
4970   case Instruction::FDiv:
4971   case Instruction::FRem:
4972   case Instruction::Shl:
4973   case Instruction::LShr:
4974   case Instruction::AShr:
4975   case Instruction::And:
4976   case Instruction::Or:
4977   case Instruction::Xor: {
4978     // Just widen unops and binops.
4979     setDebugLocFromInst(Builder, &I);
4980 
4981     for (unsigned Part = 0; Part < UF; ++Part) {
4982       SmallVector<Value *, 2> Ops;
4983       for (VPValue *VPOp : User.operands())
4984         Ops.push_back(State.get(VPOp, Part));
4985 
4986       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
4987 
4988       if (auto *VecOp = dyn_cast<Instruction>(V))
4989         VecOp->copyIRFlags(&I);
4990 
4991       // Use this vector value for all users of the original instruction.
4992       State.set(Def, V, Part);
4993       addMetadata(V, &I);
4994     }
4995 
4996     break;
4997   }
4998   case Instruction::ICmp:
4999   case Instruction::FCmp: {
5000     // Widen compares. Generate vector compares.
5001     bool FCmp = (I.getOpcode() == Instruction::FCmp);
5002     auto *Cmp = cast<CmpInst>(&I);
5003     setDebugLocFromInst(Builder, Cmp);
5004     for (unsigned Part = 0; Part < UF; ++Part) {
5005       Value *A = State.get(User.getOperand(0), Part);
5006       Value *B = State.get(User.getOperand(1), Part);
5007       Value *C = nullptr;
5008       if (FCmp) {
5009         // Propagate fast math flags.
5010         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
5011         Builder.setFastMathFlags(Cmp->getFastMathFlags());
5012         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
5013       } else {
5014         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
5015       }
5016       State.set(Def, C, Part);
5017       addMetadata(C, &I);
5018     }
5019 
5020     break;
5021   }
5022 
5023   case Instruction::ZExt:
5024   case Instruction::SExt:
5025   case Instruction::FPToUI:
5026   case Instruction::FPToSI:
5027   case Instruction::FPExt:
5028   case Instruction::PtrToInt:
5029   case Instruction::IntToPtr:
5030   case Instruction::SIToFP:
5031   case Instruction::UIToFP:
5032   case Instruction::Trunc:
5033   case Instruction::FPTrunc:
5034   case Instruction::BitCast: {
5035     auto *CI = cast<CastInst>(&I);
5036     setDebugLocFromInst(Builder, CI);
5037 
5038     /// Vectorize casts.
5039     Type *DestTy =
5040         (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
5041 
5042     for (unsigned Part = 0; Part < UF; ++Part) {
5043       Value *A = State.get(User.getOperand(0), Part);
5044       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
5045       State.set(Def, Cast, Part);
5046       addMetadata(Cast, &I);
5047     }
5048     break;
5049   }
5050   default:
5051     // This instruction is not vectorized by simple widening.
5052     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
5053     llvm_unreachable("Unhandled instruction!");
5054   } // end of switch.
5055 }
5056 
5057 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
5058                                                VPUser &ArgOperands,
5059                                                VPTransformState &State) {
5060   assert(!isa<DbgInfoIntrinsic>(I) &&
5061          "DbgInfoIntrinsic should have been dropped during VPlan construction");
5062   setDebugLocFromInst(Builder, &I);
5063 
5064   Module *M = I.getParent()->getParent()->getParent();
5065   auto *CI = cast<CallInst>(&I);
5066 
5067   SmallVector<Type *, 4> Tys;
5068   for (Value *ArgOperand : CI->arg_operands())
5069     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
5070 
5071   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5072 
5073   // The flag shows whether we use Intrinsic or a usual Call for vectorized
5074   // version of the instruction.
5075   // Is it beneficial to perform intrinsic call compared to lib call?
5076   bool NeedToScalarize = false;
5077   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
5078   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
5079   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
5080   assert((UseVectorIntrinsic || !NeedToScalarize) &&
5081          "Instruction should be scalarized elsewhere.");
5082   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
5083          "Either the intrinsic cost or vector call cost must be valid");
5084 
5085   for (unsigned Part = 0; Part < UF; ++Part) {
5086     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
5087     SmallVector<Value *, 4> Args;
5088     for (auto &I : enumerate(ArgOperands.operands())) {
5089       // Some intrinsics have a scalar argument - don't replace it with a
5090       // vector.
5091       Value *Arg;
5092       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
5093         Arg = State.get(I.value(), Part);
5094       else {
5095         Arg = State.get(I.value(), VPIteration(0, 0));
5096         if (hasVectorInstrinsicOverloadedScalarOpd(ID, I.index()))
5097           TysForDecl.push_back(Arg->getType());
5098       }
5099       Args.push_back(Arg);
5100     }
5101 
5102     Function *VectorF;
5103     if (UseVectorIntrinsic) {
5104       // Use vector version of the intrinsic.
5105       if (VF.isVector())
5106         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
5107       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
5108       assert(VectorF && "Can't retrieve vector intrinsic.");
5109     } else {
5110       // Use vector version of the function call.
5111       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
5112 #ifndef NDEBUG
5113       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
5114              "Can't create vector function.");
5115 #endif
5116         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
5117     }
5118       SmallVector<OperandBundleDef, 1> OpBundles;
5119       CI->getOperandBundlesAsDefs(OpBundles);
5120       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
5121 
5122       if (isa<FPMathOperator>(V))
5123         V->copyFastMathFlags(CI);
5124 
5125       State.set(Def, V, Part);
5126       addMetadata(V, &I);
5127   }
5128 }
5129 
5130 void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I, VPValue *VPDef,
5131                                                  VPUser &Operands,
5132                                                  bool InvariantCond,
5133                                                  VPTransformState &State) {
5134   setDebugLocFromInst(Builder, &I);
5135 
5136   // The condition can be loop invariant  but still defined inside the
5137   // loop. This means that we can't just use the original 'cond' value.
5138   // We have to take the 'vectorized' value and pick the first lane.
5139   // Instcombine will make this a no-op.
5140   auto *InvarCond = InvariantCond
5141                         ? State.get(Operands.getOperand(0), VPIteration(0, 0))
5142                         : nullptr;
5143 
5144   for (unsigned Part = 0; Part < UF; ++Part) {
5145     Value *Cond =
5146         InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
5147     Value *Op0 = State.get(Operands.getOperand(1), Part);
5148     Value *Op1 = State.get(Operands.getOperand(2), Part);
5149     Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
5150     State.set(VPDef, Sel, Part);
5151     addMetadata(Sel, &I);
5152   }
5153 }
5154 
5155 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
5156   // We should not collect Scalars more than once per VF. Right now, this
5157   // function is called from collectUniformsAndScalars(), which already does
5158   // this check. Collecting Scalars for VF=1 does not make any sense.
5159   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
5160          "This function should not be visited twice for the same VF");
5161 
5162   SmallSetVector<Instruction *, 8> Worklist;
5163 
5164   // These sets are used to seed the analysis with pointers used by memory
5165   // accesses that will remain scalar.
5166   SmallSetVector<Instruction *, 8> ScalarPtrs;
5167   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5168   auto *Latch = TheLoop->getLoopLatch();
5169 
5170   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5171   // The pointer operands of loads and stores will be scalar as long as the
5172   // memory access is not a gather or scatter operation. The value operand of a
5173   // store will remain scalar if the store is scalarized.
5174   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5175     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5176     assert(WideningDecision != CM_Unknown &&
5177            "Widening decision should be ready at this moment");
5178     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5179       if (Ptr == Store->getValueOperand())
5180         return WideningDecision == CM_Scalarize;
5181     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
5182            "Ptr is neither a value or pointer operand");
5183     return WideningDecision != CM_GatherScatter;
5184   };
5185 
5186   // A helper that returns true if the given value is a bitcast or
5187   // getelementptr instruction contained in the loop.
5188   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5189     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5190             isa<GetElementPtrInst>(V)) &&
5191            !TheLoop->isLoopInvariant(V);
5192   };
5193 
5194   auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
5195     if (!isa<PHINode>(Ptr) ||
5196         !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
5197       return false;
5198     auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
5199     if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
5200       return false;
5201     return isScalarUse(MemAccess, Ptr);
5202   };
5203 
5204   // A helper that evaluates a memory access's use of a pointer. If the
5205   // pointer is actually the pointer induction of a loop, it is being
5206   // inserted into Worklist. If the use will be a scalar use, and the
5207   // pointer is only used by memory accesses, we place the pointer in
5208   // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
5209   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5210     if (isScalarPtrInduction(MemAccess, Ptr)) {
5211       Worklist.insert(cast<Instruction>(Ptr));
5212       Instruction *Update = cast<Instruction>(
5213           cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
5214       Worklist.insert(Update);
5215       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
5216                         << "\n");
5217       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Update
5218                         << "\n");
5219       return;
5220     }
5221     // We only care about bitcast and getelementptr instructions contained in
5222     // the loop.
5223     if (!isLoopVaryingBitCastOrGEP(Ptr))
5224       return;
5225 
5226     // If the pointer has already been identified as scalar (e.g., if it was
5227     // also identified as uniform), there's nothing to do.
5228     auto *I = cast<Instruction>(Ptr);
5229     if (Worklist.count(I))
5230       return;
5231 
5232     // If the use of the pointer will be a scalar use, and all users of the
5233     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5234     // place the pointer in PossibleNonScalarPtrs.
5235     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5236           return isa<LoadInst>(U) || isa<StoreInst>(U);
5237         }))
5238       ScalarPtrs.insert(I);
5239     else
5240       PossibleNonScalarPtrs.insert(I);
5241   };
5242 
5243   // We seed the scalars analysis with three classes of instructions: (1)
5244   // instructions marked uniform-after-vectorization and (2) bitcast,
5245   // getelementptr and (pointer) phi instructions used by memory accesses
5246   // requiring a scalar use.
5247   //
5248   // (1) Add to the worklist all instructions that have been identified as
5249   // uniform-after-vectorization.
5250   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5251 
5252   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5253   // memory accesses requiring a scalar use. The pointer operands of loads and
5254   // stores will be scalar as long as the memory accesses is not a gather or
5255   // scatter operation. The value operand of a store will remain scalar if the
5256   // store is scalarized.
5257   for (auto *BB : TheLoop->blocks())
5258     for (auto &I : *BB) {
5259       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5260         evaluatePtrUse(Load, Load->getPointerOperand());
5261       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5262         evaluatePtrUse(Store, Store->getPointerOperand());
5263         evaluatePtrUse(Store, Store->getValueOperand());
5264       }
5265     }
5266   for (auto *I : ScalarPtrs)
5267     if (!PossibleNonScalarPtrs.count(I)) {
5268       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5269       Worklist.insert(I);
5270     }
5271 
5272   // Insert the forced scalars.
5273   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5274   // induction variable when the PHI user is scalarized.
5275   auto ForcedScalar = ForcedScalars.find(VF);
5276   if (ForcedScalar != ForcedScalars.end())
5277     for (auto *I : ForcedScalar->second)
5278       Worklist.insert(I);
5279 
5280   // Expand the worklist by looking through any bitcasts and getelementptr
5281   // instructions we've already identified as scalar. This is similar to the
5282   // expansion step in collectLoopUniforms(); however, here we're only
5283   // expanding to include additional bitcasts and getelementptr instructions.
5284   unsigned Idx = 0;
5285   while (Idx != Worklist.size()) {
5286     Instruction *Dst = Worklist[Idx++];
5287     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5288       continue;
5289     auto *Src = cast<Instruction>(Dst->getOperand(0));
5290     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5291           auto *J = cast<Instruction>(U);
5292           return !TheLoop->contains(J) || Worklist.count(J) ||
5293                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5294                   isScalarUse(J, Src));
5295         })) {
5296       Worklist.insert(Src);
5297       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5298     }
5299   }
5300 
5301   // An induction variable will remain scalar if all users of the induction
5302   // variable and induction variable update remain scalar.
5303   for (auto &Induction : Legal->getInductionVars()) {
5304     auto *Ind = Induction.first;
5305     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5306 
5307     // If tail-folding is applied, the primary induction variable will be used
5308     // to feed a vector compare.
5309     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
5310       continue;
5311 
5312     // Determine if all users of the induction variable are scalar after
5313     // vectorization.
5314     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5315       auto *I = cast<Instruction>(U);
5316       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5317     });
5318     if (!ScalarInd)
5319       continue;
5320 
5321     // Determine if all users of the induction variable update instruction are
5322     // scalar after vectorization.
5323     auto ScalarIndUpdate =
5324         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5325           auto *I = cast<Instruction>(U);
5326           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5327         });
5328     if (!ScalarIndUpdate)
5329       continue;
5330 
5331     // The induction variable and its update instruction will remain scalar.
5332     Worklist.insert(Ind);
5333     Worklist.insert(IndUpdate);
5334     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5335     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
5336                       << "\n");
5337   }
5338 
5339   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5340 }
5341 
5342 bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) const {
5343   if (!blockNeedsPredication(I->getParent()))
5344     return false;
5345   switch(I->getOpcode()) {
5346   default:
5347     break;
5348   case Instruction::Load:
5349   case Instruction::Store: {
5350     if (!Legal->isMaskRequired(I))
5351       return false;
5352     auto *Ptr = getLoadStorePointerOperand(I);
5353     auto *Ty = getLoadStoreType(I);
5354     const Align Alignment = getLoadStoreAlignment(I);
5355     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
5356                                 TTI.isLegalMaskedGather(Ty, Alignment))
5357                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
5358                                 TTI.isLegalMaskedScatter(Ty, Alignment));
5359   }
5360   case Instruction::UDiv:
5361   case Instruction::SDiv:
5362   case Instruction::SRem:
5363   case Instruction::URem:
5364     return mayDivideByZero(*I);
5365   }
5366   return false;
5367 }
5368 
5369 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5370     Instruction *I, ElementCount VF) {
5371   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5372   assert(getWideningDecision(I, VF) == CM_Unknown &&
5373          "Decision should not be set yet.");
5374   auto *Group = getInterleavedAccessGroup(I);
5375   assert(Group && "Must have a group.");
5376 
5377   // If the instruction's allocated size doesn't equal it's type size, it
5378   // requires padding and will be scalarized.
5379   auto &DL = I->getModule()->getDataLayout();
5380   auto *ScalarTy = getLoadStoreType(I);
5381   if (hasIrregularType(ScalarTy, DL))
5382     return false;
5383 
5384   // Check if masking is required.
5385   // A Group may need masking for one of two reasons: it resides in a block that
5386   // needs predication, or it was decided to use masking to deal with gaps.
5387   bool PredicatedAccessRequiresMasking =
5388       Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
5389   bool AccessWithGapsRequiresMasking =
5390       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
5391   if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
5392     return true;
5393 
5394   // If masked interleaving is required, we expect that the user/target had
5395   // enabled it, because otherwise it either wouldn't have been created or
5396   // it should have been invalidated by the CostModel.
5397   assert(useMaskedInterleavedAccesses(TTI) &&
5398          "Masked interleave-groups for predicated accesses are not enabled.");
5399 
5400   auto *Ty = getLoadStoreType(I);
5401   const Align Alignment = getLoadStoreAlignment(I);
5402   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5403                           : TTI.isLegalMaskedStore(Ty, Alignment);
5404 }
5405 
5406 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5407     Instruction *I, ElementCount VF) {
5408   // Get and ensure we have a valid memory instruction.
5409   LoadInst *LI = dyn_cast<LoadInst>(I);
5410   StoreInst *SI = dyn_cast<StoreInst>(I);
5411   assert((LI || SI) && "Invalid memory instruction");
5412 
5413   auto *Ptr = getLoadStorePointerOperand(I);
5414 
5415   // In order to be widened, the pointer should be consecutive, first of all.
5416   if (!Legal->isConsecutivePtr(Ptr))
5417     return false;
5418 
5419   // If the instruction is a store located in a predicated block, it will be
5420   // scalarized.
5421   if (isScalarWithPredication(I))
5422     return false;
5423 
5424   // If the instruction's allocated size doesn't equal it's type size, it
5425   // requires padding and will be scalarized.
5426   auto &DL = I->getModule()->getDataLayout();
5427   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5428   if (hasIrregularType(ScalarTy, DL))
5429     return false;
5430 
5431   return true;
5432 }
5433 
5434 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5435   // We should not collect Uniforms more than once per VF. Right now,
5436   // this function is called from collectUniformsAndScalars(), which
5437   // already does this check. Collecting Uniforms for VF=1 does not make any
5438   // sense.
5439 
5440   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5441          "This function should not be visited twice for the same VF");
5442 
5443   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5444   // not analyze again.  Uniforms.count(VF) will return 1.
5445   Uniforms[VF].clear();
5446 
5447   // We now know that the loop is vectorizable!
5448   // Collect instructions inside the loop that will remain uniform after
5449   // vectorization.
5450 
5451   // Global values, params and instructions outside of current loop are out of
5452   // scope.
5453   auto isOutOfScope = [&](Value *V) -> bool {
5454     Instruction *I = dyn_cast<Instruction>(V);
5455     return (!I || !TheLoop->contains(I));
5456   };
5457 
5458   SetVector<Instruction *> Worklist;
5459   BasicBlock *Latch = TheLoop->getLoopLatch();
5460 
5461   // Instructions that are scalar with predication must not be considered
5462   // uniform after vectorization, because that would create an erroneous
5463   // replicating region where only a single instance out of VF should be formed.
5464   // TODO: optimize such seldom cases if found important, see PR40816.
5465   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5466     if (isOutOfScope(I)) {
5467       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5468                         << *I << "\n");
5469       return;
5470     }
5471     if (isScalarWithPredication(I)) {
5472       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5473                         << *I << "\n");
5474       return;
5475     }
5476     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5477     Worklist.insert(I);
5478   };
5479 
5480   // Start with the conditional branch. If the branch condition is an
5481   // instruction contained in the loop that is only used by the branch, it is
5482   // uniform.
5483   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5484   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5485     addToWorklistIfAllowed(Cmp);
5486 
5487   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5488     InstWidening WideningDecision = getWideningDecision(I, VF);
5489     assert(WideningDecision != CM_Unknown &&
5490            "Widening decision should be ready at this moment");
5491 
5492     // A uniform memory op is itself uniform.  We exclude uniform stores
5493     // here as they demand the last lane, not the first one.
5494     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5495       assert(WideningDecision == CM_Scalarize);
5496       return true;
5497     }
5498 
5499     return (WideningDecision == CM_Widen ||
5500             WideningDecision == CM_Widen_Reverse ||
5501             WideningDecision == CM_Interleave);
5502   };
5503 
5504 
5505   // Returns true if Ptr is the pointer operand of a memory access instruction
5506   // I, and I is known to not require scalarization.
5507   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5508     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5509   };
5510 
5511   // Holds a list of values which are known to have at least one uniform use.
5512   // Note that there may be other uses which aren't uniform.  A "uniform use"
5513   // here is something which only demands lane 0 of the unrolled iterations;
5514   // it does not imply that all lanes produce the same value (e.g. this is not
5515   // the usual meaning of uniform)
5516   SetVector<Value *> HasUniformUse;
5517 
5518   // Scan the loop for instructions which are either a) known to have only
5519   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5520   for (auto *BB : TheLoop->blocks())
5521     for (auto &I : *BB) {
5522       // If there's no pointer operand, there's nothing to do.
5523       auto *Ptr = getLoadStorePointerOperand(&I);
5524       if (!Ptr)
5525         continue;
5526 
5527       // A uniform memory op is itself uniform.  We exclude uniform stores
5528       // here as they demand the last lane, not the first one.
5529       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5530         addToWorklistIfAllowed(&I);
5531 
5532       if (isUniformDecision(&I, VF)) {
5533         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5534         HasUniformUse.insert(Ptr);
5535       }
5536     }
5537 
5538   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5539   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5540   // disallows uses outside the loop as well.
5541   for (auto *V : HasUniformUse) {
5542     if (isOutOfScope(V))
5543       continue;
5544     auto *I = cast<Instruction>(V);
5545     auto UsersAreMemAccesses =
5546       llvm::all_of(I->users(), [&](User *U) -> bool {
5547         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5548       });
5549     if (UsersAreMemAccesses)
5550       addToWorklistIfAllowed(I);
5551   }
5552 
5553   // Expand Worklist in topological order: whenever a new instruction
5554   // is added , its users should be already inside Worklist.  It ensures
5555   // a uniform instruction will only be used by uniform instructions.
5556   unsigned idx = 0;
5557   while (idx != Worklist.size()) {
5558     Instruction *I = Worklist[idx++];
5559 
5560     for (auto OV : I->operand_values()) {
5561       // isOutOfScope operands cannot be uniform instructions.
5562       if (isOutOfScope(OV))
5563         continue;
5564       // First order recurrence Phi's should typically be considered
5565       // non-uniform.
5566       auto *OP = dyn_cast<PHINode>(OV);
5567       if (OP && Legal->isFirstOrderRecurrence(OP))
5568         continue;
5569       // If all the users of the operand are uniform, then add the
5570       // operand into the uniform worklist.
5571       auto *OI = cast<Instruction>(OV);
5572       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5573             auto *J = cast<Instruction>(U);
5574             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5575           }))
5576         addToWorklistIfAllowed(OI);
5577     }
5578   }
5579 
5580   // For an instruction to be added into Worklist above, all its users inside
5581   // the loop should also be in Worklist. However, this condition cannot be
5582   // true for phi nodes that form a cyclic dependence. We must process phi
5583   // nodes separately. An induction variable will remain uniform if all users
5584   // of the induction variable and induction variable update remain uniform.
5585   // The code below handles both pointer and non-pointer induction variables.
5586   for (auto &Induction : Legal->getInductionVars()) {
5587     auto *Ind = Induction.first;
5588     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5589 
5590     // Determine if all users of the induction variable are uniform after
5591     // vectorization.
5592     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5593       auto *I = cast<Instruction>(U);
5594       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5595              isVectorizedMemAccessUse(I, Ind);
5596     });
5597     if (!UniformInd)
5598       continue;
5599 
5600     // Determine if all users of the induction variable update instruction are
5601     // uniform after vectorization.
5602     auto UniformIndUpdate =
5603         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5604           auto *I = cast<Instruction>(U);
5605           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5606                  isVectorizedMemAccessUse(I, IndUpdate);
5607         });
5608     if (!UniformIndUpdate)
5609       continue;
5610 
5611     // The induction variable and its update instruction will remain uniform.
5612     addToWorklistIfAllowed(Ind);
5613     addToWorklistIfAllowed(IndUpdate);
5614   }
5615 
5616   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5617 }
5618 
5619 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5620   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5621 
5622   if (Legal->getRuntimePointerChecking()->Need) {
5623     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5624         "runtime pointer checks needed. Enable vectorization of this "
5625         "loop with '#pragma clang loop vectorize(enable)' when "
5626         "compiling with -Os/-Oz",
5627         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5628     return true;
5629   }
5630 
5631   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5632     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5633         "runtime SCEV checks needed. Enable vectorization of this "
5634         "loop with '#pragma clang loop vectorize(enable)' when "
5635         "compiling with -Os/-Oz",
5636         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5637     return true;
5638   }
5639 
5640   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5641   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5642     reportVectorizationFailure("Runtime stride check for small trip count",
5643         "runtime stride == 1 checks needed. Enable vectorization of "
5644         "this loop without such check by compiling with -Os/-Oz",
5645         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5646     return true;
5647   }
5648 
5649   return false;
5650 }
5651 
5652 ElementCount
5653 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
5654   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
5655     reportVectorizationInfo(
5656         "Disabling scalable vectorization, because target does not "
5657         "support scalable vectors.",
5658         "ScalableVectorsUnsupported", ORE, TheLoop);
5659     return ElementCount::getScalable(0);
5660   }
5661 
5662   if (Hints->isScalableVectorizationDisabled()) {
5663     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
5664                             "ScalableVectorizationDisabled", ORE, TheLoop);
5665     return ElementCount::getScalable(0);
5666   }
5667 
5668   auto MaxScalableVF = ElementCount::getScalable(
5669       std::numeric_limits<ElementCount::ScalarTy>::max());
5670 
5671   // Disable scalable vectorization if the loop contains unsupported reductions.
5672   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
5673   // FIXME: While for scalable vectors this is currently sufficient, this should
5674   // be replaced by a more detailed mechanism that filters out specific VFs,
5675   // instead of invalidating vectorization for a whole set of VFs based on the
5676   // MaxVF.
5677   if (!canVectorizeReductions(MaxScalableVF)) {
5678     reportVectorizationInfo(
5679         "Scalable vectorization not supported for the reduction "
5680         "operations found in this loop.",
5681         "ScalableVFUnfeasible", ORE, TheLoop);
5682     return ElementCount::getScalable(0);
5683   }
5684 
5685   if (Legal->isSafeForAnyVectorWidth())
5686     return MaxScalableVF;
5687 
5688   // Limit MaxScalableVF by the maximum safe dependence distance.
5689   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5690   MaxScalableVF = ElementCount::getScalable(
5691       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5692   if (!MaxScalableVF)
5693     reportVectorizationInfo(
5694         "Max legal vector width too small, scalable vectorization "
5695         "unfeasible.",
5696         "ScalableVFUnfeasible", ORE, TheLoop);
5697 
5698   return MaxScalableVF;
5699 }
5700 
5701 FixedScalableVFPair
5702 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5703                                                  ElementCount UserVF) {
5704   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5705   unsigned SmallestType, WidestType;
5706   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5707 
5708   // Get the maximum safe dependence distance in bits computed by LAA.
5709   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5710   // the memory accesses that is most restrictive (involved in the smallest
5711   // dependence distance).
5712   unsigned MaxSafeElements =
5713       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
5714 
5715   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
5716   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
5717 
5718   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
5719                     << ".\n");
5720   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
5721                     << ".\n");
5722 
5723   // First analyze the UserVF, fall back if the UserVF should be ignored.
5724   if (UserVF) {
5725     auto MaxSafeUserVF =
5726         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
5727 
5728     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF))
5729       return UserVF;
5730 
5731     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
5732 
5733     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
5734     // is better to ignore the hint and let the compiler choose a suitable VF.
5735     if (!UserVF.isScalable()) {
5736       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5737                         << " is unsafe, clamping to max safe VF="
5738                         << MaxSafeFixedVF << ".\n");
5739       ORE->emit([&]() {
5740         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5741                                           TheLoop->getStartLoc(),
5742                                           TheLoop->getHeader())
5743                << "User-specified vectorization factor "
5744                << ore::NV("UserVectorizationFactor", UserVF)
5745                << " is unsafe, clamping to maximum safe vectorization factor "
5746                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
5747       });
5748       return MaxSafeFixedVF;
5749     }
5750 
5751     LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5752                       << " is unsafe. Ignoring scalable UserVF.\n");
5753     ORE->emit([&]() {
5754       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5755                                         TheLoop->getStartLoc(),
5756                                         TheLoop->getHeader())
5757              << "User-specified vectorization factor "
5758              << ore::NV("UserVectorizationFactor", UserVF)
5759              << " is unsafe. Ignoring the hint to let the compiler pick a "
5760                 "suitable VF.";
5761     });
5762   }
5763 
5764   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5765                     << " / " << WidestType << " bits.\n");
5766 
5767   FixedScalableVFPair Result(ElementCount::getFixed(1),
5768                              ElementCount::getScalable(0));
5769   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5770                                            WidestType, MaxSafeFixedVF))
5771     Result.FixedVF = MaxVF;
5772 
5773   if (auto MaxVF = getMaximizedVFForTarget(ConstTripCount, SmallestType,
5774                                            WidestType, MaxSafeScalableVF))
5775     if (MaxVF.isScalable()) {
5776       Result.ScalableVF = MaxVF;
5777       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
5778                         << "\n");
5779     }
5780 
5781   return Result;
5782 }
5783 
5784 FixedScalableVFPair
5785 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5786   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5787     // TODO: It may by useful to do since it's still likely to be dynamically
5788     // uniform if the target can skip.
5789     reportVectorizationFailure(
5790         "Not inserting runtime ptr check for divergent target",
5791         "runtime pointer checks needed. Not enabled for divergent target",
5792         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5793     return FixedScalableVFPair::getNone();
5794   }
5795 
5796   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5797   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5798   if (TC == 1) {
5799     reportVectorizationFailure("Single iteration (non) loop",
5800         "loop trip count is one, irrelevant for vectorization",
5801         "SingleIterationLoop", ORE, TheLoop);
5802     return FixedScalableVFPair::getNone();
5803   }
5804 
5805   switch (ScalarEpilogueStatus) {
5806   case CM_ScalarEpilogueAllowed:
5807     return computeFeasibleMaxVF(TC, UserVF);
5808   case CM_ScalarEpilogueNotAllowedUsePredicate:
5809     LLVM_FALLTHROUGH;
5810   case CM_ScalarEpilogueNotNeededUsePredicate:
5811     LLVM_DEBUG(
5812         dbgs() << "LV: vector predicate hint/switch found.\n"
5813                << "LV: Not allowing scalar epilogue, creating predicated "
5814                << "vector loop.\n");
5815     break;
5816   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5817     // fallthrough as a special case of OptForSize
5818   case CM_ScalarEpilogueNotAllowedOptSize:
5819     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5820       LLVM_DEBUG(
5821           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5822     else
5823       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5824                         << "count.\n");
5825 
5826     // Bail if runtime checks are required, which are not good when optimising
5827     // for size.
5828     if (runtimeChecksRequired())
5829       return FixedScalableVFPair::getNone();
5830 
5831     break;
5832   }
5833 
5834   // The only loops we can vectorize without a scalar epilogue, are loops with
5835   // a bottom-test and a single exiting block. We'd have to handle the fact
5836   // that not every instruction executes on the last iteration.  This will
5837   // require a lane mask which varies through the vector loop body.  (TODO)
5838   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5839     // If there was a tail-folding hint/switch, but we can't fold the tail by
5840     // masking, fallback to a vectorization with a scalar epilogue.
5841     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5842       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5843                            "scalar epilogue instead.\n");
5844       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5845       return computeFeasibleMaxVF(TC, UserVF);
5846     }
5847     return FixedScalableVFPair::getNone();
5848   }
5849 
5850   // Now try the tail folding
5851 
5852   // Invalidate interleave groups that require an epilogue if we can't mask
5853   // the interleave-group.
5854   if (!useMaskedInterleavedAccesses(TTI)) {
5855     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5856            "No decisions should have been taken at this point");
5857     // Note: There is no need to invalidate any cost modeling decisions here, as
5858     // non where taken so far.
5859     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5860   }
5861 
5862   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF);
5863   // Avoid tail folding if the trip count is known to be a multiple of any VF
5864   // we chose.
5865   // FIXME: The condition below pessimises the case for fixed-width vectors,
5866   // when scalable VFs are also candidates for vectorization.
5867   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5868     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5869     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5870            "MaxFixedVF must be a power of 2");
5871     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5872                                    : MaxFixedVF.getFixedValue();
5873     ScalarEvolution *SE = PSE.getSE();
5874     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5875     const SCEV *ExitCount = SE->getAddExpr(
5876         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5877     const SCEV *Rem = SE->getURemExpr(
5878         SE->applyLoopGuards(ExitCount, TheLoop),
5879         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5880     if (Rem->isZero()) {
5881       // Accept MaxFixedVF if we do not have a tail.
5882       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5883       return MaxFactors;
5884     }
5885   }
5886 
5887   // If we don't know the precise trip count, or if the trip count that we
5888   // found modulo the vectorization factor is not zero, try to fold the tail
5889   // by masking.
5890   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5891   if (Legal->prepareToFoldTailByMasking()) {
5892     FoldTailByMasking = true;
5893     return MaxFactors;
5894   }
5895 
5896   // If there was a tail-folding hint/switch, but we can't fold the tail by
5897   // masking, fallback to a vectorization with a scalar epilogue.
5898   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5899     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5900                          "scalar epilogue instead.\n");
5901     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5902     return MaxFactors;
5903   }
5904 
5905   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5906     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5907     return FixedScalableVFPair::getNone();
5908   }
5909 
5910   if (TC == 0) {
5911     reportVectorizationFailure(
5912         "Unable to calculate the loop count due to complex control flow",
5913         "unable to calculate the loop count due to complex control flow",
5914         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5915     return FixedScalableVFPair::getNone();
5916   }
5917 
5918   reportVectorizationFailure(
5919       "Cannot optimize for size and vectorize at the same time.",
5920       "cannot optimize for size and vectorize at the same time. "
5921       "Enable vectorization of this loop with '#pragma clang loop "
5922       "vectorize(enable)' when compiling with -Os/-Oz",
5923       "NoTailLoopWithOptForSize", ORE, TheLoop);
5924   return FixedScalableVFPair::getNone();
5925 }
5926 
5927 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5928     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5929     const ElementCount &MaxSafeVF) {
5930   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5931   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5932       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5933                            : TargetTransformInfo::RGK_FixedWidthVector);
5934 
5935   // Convenience function to return the minimum of two ElementCounts.
5936   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5937     assert((LHS.isScalable() == RHS.isScalable()) &&
5938            "Scalable flags must match");
5939     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5940   };
5941 
5942   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5943   // Note that both WidestRegister and WidestType may not be a powers of 2.
5944   auto MaxVectorElementCount = ElementCount::get(
5945       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5946       ComputeScalableMaxVF);
5947   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5948   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5949                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5950 
5951   if (!MaxVectorElementCount) {
5952     LLVM_DEBUG(dbgs() << "LV: The target has no "
5953                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5954                       << " vector registers.\n");
5955     return ElementCount::getFixed(1);
5956   }
5957 
5958   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5959   if (ConstTripCount &&
5960       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5961       isPowerOf2_32(ConstTripCount)) {
5962     // We need to clamp the VF to be the ConstTripCount. There is no point in
5963     // choosing a higher viable VF as done in the loop below. If
5964     // MaxVectorElementCount is scalable, we only fall back on a fixed VF when
5965     // the TC is less than or equal to the known number of lanes.
5966     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5967                       << ConstTripCount << "\n");
5968     return TripCountEC;
5969   }
5970 
5971   ElementCount MaxVF = MaxVectorElementCount;
5972   if (TTI.shouldMaximizeVectorBandwidth() ||
5973       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5974     auto MaxVectorElementCountMaxBW = ElementCount::get(
5975         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5976         ComputeScalableMaxVF);
5977     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5978 
5979     // Collect all viable vectorization factors larger than the default MaxVF
5980     // (i.e. MaxVectorElementCount).
5981     SmallVector<ElementCount, 8> VFs;
5982     for (ElementCount VS = MaxVectorElementCount * 2;
5983          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5984       VFs.push_back(VS);
5985 
5986     // For each VF calculate its register usage.
5987     auto RUs = calculateRegisterUsage(VFs);
5988 
5989     // Select the largest VF which doesn't require more registers than existing
5990     // ones.
5991     for (int i = RUs.size() - 1; i >= 0; --i) {
5992       bool Selected = true;
5993       for (auto &pair : RUs[i].MaxLocalUsers) {
5994         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5995         if (pair.second > TargetNumRegisters)
5996           Selected = false;
5997       }
5998       if (Selected) {
5999         MaxVF = VFs[i];
6000         break;
6001       }
6002     }
6003     if (ElementCount MinVF =
6004             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
6005       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
6006         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
6007                           << ") with target's minimum: " << MinVF << '\n');
6008         MaxVF = MinVF;
6009       }
6010     }
6011   }
6012   return MaxVF;
6013 }
6014 
6015 bool LoopVectorizationCostModel::isMoreProfitable(
6016     const VectorizationFactor &A, const VectorizationFactor &B) const {
6017   InstructionCost::CostType CostA = *A.Cost.getValue();
6018   InstructionCost::CostType CostB = *B.Cost.getValue();
6019 
6020   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
6021 
6022   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
6023       MaxTripCount) {
6024     // If we are folding the tail and the trip count is a known (possibly small)
6025     // constant, the trip count will be rounded up to an integer number of
6026     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
6027     // which we compare directly. When not folding the tail, the total cost will
6028     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
6029     // approximated with the per-lane cost below instead of using the tripcount
6030     // as here.
6031     int64_t RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
6032     int64_t RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
6033     return RTCostA < RTCostB;
6034   }
6035 
6036   // When set to preferred, for now assume vscale may be larger than 1, so
6037   // that scalable vectorization is slightly favorable over fixed-width
6038   // vectorization.
6039   if (Hints->isScalableVectorizationPreferred())
6040     if (A.Width.isScalable() && !B.Width.isScalable())
6041       return (CostA * B.Width.getKnownMinValue()) <=
6042              (CostB * A.Width.getKnownMinValue());
6043 
6044   // To avoid the need for FP division:
6045   //      (CostA / A.Width) < (CostB / B.Width)
6046   // <=>  (CostA * B.Width) < (CostB * A.Width)
6047   return (CostA * B.Width.getKnownMinValue()) <
6048          (CostB * A.Width.getKnownMinValue());
6049 }
6050 
6051 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
6052     const ElementCountSet &VFCandidates) {
6053   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
6054   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
6055   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
6056   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
6057          "Expected Scalar VF to be a candidate");
6058 
6059   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
6060   VectorizationFactor ChosenFactor = ScalarCost;
6061 
6062   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
6063   if (ForceVectorization && VFCandidates.size() > 1) {
6064     // Ignore scalar width, because the user explicitly wants vectorization.
6065     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
6066     // evaluation.
6067     ChosenFactor.Cost = std::numeric_limits<InstructionCost::CostType>::max();
6068   }
6069 
6070   for (const auto &i : VFCandidates) {
6071     // The cost for scalar VF=1 is already calculated, so ignore it.
6072     if (i.isScalar())
6073       continue;
6074 
6075     // Notice that the vector loop needs to be executed less times, so
6076     // we need to divide the cost of the vector loops by the width of
6077     // the vector elements.
6078     VectorizationCostTy C = expectedCost(i);
6079 
6080     assert(C.first.isValid() && "Unexpected invalid cost for vector loop");
6081     VectorizationFactor Candidate(i, C.first);
6082     LLVM_DEBUG(
6083         dbgs() << "LV: Vector loop of width " << i << " costs: "
6084                << (*Candidate.Cost.getValue() /
6085                    Candidate.Width.getKnownMinValue())
6086                << (i.isScalable() ? " (assuming a minimum vscale of 1)" : "")
6087                << ".\n");
6088 
6089     if (!C.second && !ForceVectorization) {
6090       LLVM_DEBUG(
6091           dbgs() << "LV: Not considering vector loop of width " << i
6092                  << " because it will not generate any vector instructions.\n");
6093       continue;
6094     }
6095 
6096     // If profitable add it to ProfitableVF list.
6097     if (isMoreProfitable(Candidate, ScalarCost))
6098       ProfitableVFs.push_back(Candidate);
6099 
6100     if (isMoreProfitable(Candidate, ChosenFactor))
6101       ChosenFactor = Candidate;
6102   }
6103 
6104   if (!EnableCondStoresVectorization && NumPredStores) {
6105     reportVectorizationFailure("There are conditional stores.",
6106         "store that is conditionally executed prevents vectorization",
6107         "ConditionalStore", ORE, TheLoop);
6108     ChosenFactor = ScalarCost;
6109   }
6110 
6111   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
6112                  *ChosenFactor.Cost.getValue() >= *ScalarCost.Cost.getValue())
6113                  dbgs()
6114              << "LV: Vectorization seems to be not beneficial, "
6115              << "but was forced by a user.\n");
6116   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
6117   return ChosenFactor;
6118 }
6119 
6120 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
6121     const Loop &L, ElementCount VF) const {
6122   // Cross iteration phis such as reductions need special handling and are
6123   // currently unsupported.
6124   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
6125         return Legal->isFirstOrderRecurrence(&Phi) ||
6126                Legal->isReductionVariable(&Phi);
6127       }))
6128     return false;
6129 
6130   // Phis with uses outside of the loop require special handling and are
6131   // currently unsupported.
6132   for (auto &Entry : Legal->getInductionVars()) {
6133     // Look for uses of the value of the induction at the last iteration.
6134     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
6135     for (User *U : PostInc->users())
6136       if (!L.contains(cast<Instruction>(U)))
6137         return false;
6138     // Look for uses of penultimate value of the induction.
6139     for (User *U : Entry.first->users())
6140       if (!L.contains(cast<Instruction>(U)))
6141         return false;
6142   }
6143 
6144   // Induction variables that are widened require special handling that is
6145   // currently not supported.
6146   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
6147         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
6148                  this->isProfitableToScalarize(Entry.first, VF));
6149       }))
6150     return false;
6151 
6152   return true;
6153 }
6154 
6155 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
6156     const ElementCount VF) const {
6157   // FIXME: We need a much better cost-model to take different parameters such
6158   // as register pressure, code size increase and cost of extra branches into
6159   // account. For now we apply a very crude heuristic and only consider loops
6160   // with vectorization factors larger than a certain value.
6161   // We also consider epilogue vectorization unprofitable for targets that don't
6162   // consider interleaving beneficial (eg. MVE).
6163   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
6164     return false;
6165   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
6166     return true;
6167   return false;
6168 }
6169 
6170 VectorizationFactor
6171 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
6172     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
6173   VectorizationFactor Result = VectorizationFactor::Disabled();
6174   if (!EnableEpilogueVectorization) {
6175     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
6176     return Result;
6177   }
6178 
6179   if (!isScalarEpilogueAllowed()) {
6180     LLVM_DEBUG(
6181         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
6182                   "allowed.\n";);
6183     return Result;
6184   }
6185 
6186   // FIXME: This can be fixed for scalable vectors later, because at this stage
6187   // the LoopVectorizer will only consider vectorizing a loop with scalable
6188   // vectors when the loop has a hint to enable vectorization for a given VF.
6189   if (MainLoopVF.isScalable()) {
6190     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization for scalable vectors not "
6191                          "yet supported.\n");
6192     return Result;
6193   }
6194 
6195   // Not really a cost consideration, but check for unsupported cases here to
6196   // simplify the logic.
6197   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
6198     LLVM_DEBUG(
6199         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
6200                   "not a supported candidate.\n";);
6201     return Result;
6202   }
6203 
6204   if (EpilogueVectorizationForceVF > 1) {
6205     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
6206     if (LVP.hasPlanWithVFs(
6207             {MainLoopVF, ElementCount::getFixed(EpilogueVectorizationForceVF)}))
6208       return {ElementCount::getFixed(EpilogueVectorizationForceVF), 0};
6209     else {
6210       LLVM_DEBUG(
6211           dbgs()
6212               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
6213       return Result;
6214     }
6215   }
6216 
6217   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
6218       TheLoop->getHeader()->getParent()->hasMinSize()) {
6219     LLVM_DEBUG(
6220         dbgs()
6221             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
6222     return Result;
6223   }
6224 
6225   if (!isEpilogueVectorizationProfitable(MainLoopVF))
6226     return Result;
6227 
6228   for (auto &NextVF : ProfitableVFs)
6229     if (ElementCount::isKnownLT(NextVF.Width, MainLoopVF) &&
6230         (Result.Width.getFixedValue() == 1 ||
6231          isMoreProfitable(NextVF, Result)) &&
6232         LVP.hasPlanWithVFs({MainLoopVF, NextVF.Width}))
6233       Result = NextVF;
6234 
6235   if (Result != VectorizationFactor::Disabled())
6236     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6237                       << Result.Width.getFixedValue() << "\n";);
6238   return Result;
6239 }
6240 
6241 std::pair<unsigned, unsigned>
6242 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6243   unsigned MinWidth = -1U;
6244   unsigned MaxWidth = 8;
6245   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6246 
6247   // For each block.
6248   for (BasicBlock *BB : TheLoop->blocks()) {
6249     // For each instruction in the loop.
6250     for (Instruction &I : BB->instructionsWithoutDebug()) {
6251       Type *T = I.getType();
6252 
6253       // Skip ignored values.
6254       if (ValuesToIgnore.count(&I))
6255         continue;
6256 
6257       // Only examine Loads, Stores and PHINodes.
6258       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6259         continue;
6260 
6261       // Examine PHI nodes that are reduction variables. Update the type to
6262       // account for the recurrence type.
6263       if (auto *PN = dyn_cast<PHINode>(&I)) {
6264         if (!Legal->isReductionVariable(PN))
6265           continue;
6266         const RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[PN];
6267         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6268             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6269                                       RdxDesc.getRecurrenceType(),
6270                                       TargetTransformInfo::ReductionFlags()))
6271           continue;
6272         T = RdxDesc.getRecurrenceType();
6273       }
6274 
6275       // Examine the stored values.
6276       if (auto *ST = dyn_cast<StoreInst>(&I))
6277         T = ST->getValueOperand()->getType();
6278 
6279       // Ignore loaded pointer types and stored pointer types that are not
6280       // vectorizable.
6281       //
6282       // FIXME: The check here attempts to predict whether a load or store will
6283       //        be vectorized. We only know this for certain after a VF has
6284       //        been selected. Here, we assume that if an access can be
6285       //        vectorized, it will be. We should also look at extending this
6286       //        optimization to non-pointer types.
6287       //
6288       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6289           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6290         continue;
6291 
6292       MinWidth = std::min(MinWidth,
6293                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6294       MaxWidth = std::max(MaxWidth,
6295                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6296     }
6297   }
6298 
6299   return {MinWidth, MaxWidth};
6300 }
6301 
6302 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6303                                                            unsigned LoopCost) {
6304   // -- The interleave heuristics --
6305   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6306   // There are many micro-architectural considerations that we can't predict
6307   // at this level. For example, frontend pressure (on decode or fetch) due to
6308   // code size, or the number and capabilities of the execution ports.
6309   //
6310   // We use the following heuristics to select the interleave count:
6311   // 1. If the code has reductions, then we interleave to break the cross
6312   // iteration dependency.
6313   // 2. If the loop is really small, then we interleave to reduce the loop
6314   // overhead.
6315   // 3. We don't interleave if we think that we will spill registers to memory
6316   // due to the increased register pressure.
6317 
6318   if (!isScalarEpilogueAllowed())
6319     return 1;
6320 
6321   // We used the distance for the interleave count.
6322   if (Legal->getMaxSafeDepDistBytes() != -1U)
6323     return 1;
6324 
6325   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6326   const bool HasReductions = !Legal->getReductionVars().empty();
6327   // Do not interleave loops with a relatively small known or estimated trip
6328   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6329   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6330   // because with the above conditions interleaving can expose ILP and break
6331   // cross iteration dependences for reductions.
6332   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6333       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6334     return 1;
6335 
6336   RegisterUsage R = calculateRegisterUsage({VF})[0];
6337   // We divide by these constants so assume that we have at least one
6338   // instruction that uses at least one register.
6339   for (auto& pair : R.MaxLocalUsers) {
6340     pair.second = std::max(pair.second, 1U);
6341   }
6342 
6343   // We calculate the interleave count using the following formula.
6344   // Subtract the number of loop invariants from the number of available
6345   // registers. These registers are used by all of the interleaved instances.
6346   // Next, divide the remaining registers by the number of registers that is
6347   // required by the loop, in order to estimate how many parallel instances
6348   // fit without causing spills. All of this is rounded down if necessary to be
6349   // a power of two. We want power of two interleave count to simplify any
6350   // addressing operations or alignment considerations.
6351   // We also want power of two interleave counts to ensure that the induction
6352   // variable of the vector loop wraps to zero, when tail is folded by masking;
6353   // this currently happens when OptForSize, in which case IC is set to 1 above.
6354   unsigned IC = UINT_MAX;
6355 
6356   for (auto& pair : R.MaxLocalUsers) {
6357     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6358     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6359                       << " registers of "
6360                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6361     if (VF.isScalar()) {
6362       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6363         TargetNumRegisters = ForceTargetNumScalarRegs;
6364     } else {
6365       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6366         TargetNumRegisters = ForceTargetNumVectorRegs;
6367     }
6368     unsigned MaxLocalUsers = pair.second;
6369     unsigned LoopInvariantRegs = 0;
6370     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6371       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6372 
6373     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6374     // Don't count the induction variable as interleaved.
6375     if (EnableIndVarRegisterHeur) {
6376       TmpIC =
6377           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6378                         std::max(1U, (MaxLocalUsers - 1)));
6379     }
6380 
6381     IC = std::min(IC, TmpIC);
6382   }
6383 
6384   // Clamp the interleave ranges to reasonable counts.
6385   unsigned MaxInterleaveCount =
6386       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6387 
6388   // Check if the user has overridden the max.
6389   if (VF.isScalar()) {
6390     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6391       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6392   } else {
6393     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6394       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6395   }
6396 
6397   // If trip count is known or estimated compile time constant, limit the
6398   // interleave count to be less than the trip count divided by VF, provided it
6399   // is at least 1.
6400   //
6401   // For scalable vectors we can't know if interleaving is beneficial. It may
6402   // not be beneficial for small loops if none of the lanes in the second vector
6403   // iterations is enabled. However, for larger loops, there is likely to be a
6404   // similar benefit as for fixed-width vectors. For now, we choose to leave
6405   // the InterleaveCount as if vscale is '1', although if some information about
6406   // the vector is known (e.g. min vector size), we can make a better decision.
6407   if (BestKnownTC) {
6408     MaxInterleaveCount =
6409         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6410     // Make sure MaxInterleaveCount is greater than 0.
6411     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6412   }
6413 
6414   assert(MaxInterleaveCount > 0 &&
6415          "Maximum interleave count must be greater than 0");
6416 
6417   // Clamp the calculated IC to be between the 1 and the max interleave count
6418   // that the target and trip count allows.
6419   if (IC > MaxInterleaveCount)
6420     IC = MaxInterleaveCount;
6421   else
6422     // Make sure IC is greater than 0.
6423     IC = std::max(1u, IC);
6424 
6425   assert(IC > 0 && "Interleave count must be greater than 0.");
6426 
6427   // If we did not calculate the cost for VF (because the user selected the VF)
6428   // then we calculate the cost of VF here.
6429   if (LoopCost == 0) {
6430     assert(expectedCost(VF).first.isValid() && "Expected a valid cost");
6431     LoopCost = *expectedCost(VF).first.getValue();
6432   }
6433 
6434   assert(LoopCost && "Non-zero loop cost expected");
6435 
6436   // Interleave if we vectorized this loop and there is a reduction that could
6437   // benefit from interleaving.
6438   if (VF.isVector() && HasReductions) {
6439     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6440     return IC;
6441   }
6442 
6443   // Note that if we've already vectorized the loop we will have done the
6444   // runtime check and so interleaving won't require further checks.
6445   bool InterleavingRequiresRuntimePointerCheck =
6446       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6447 
6448   // We want to interleave small loops in order to reduce the loop overhead and
6449   // potentially expose ILP opportunities.
6450   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6451                     << "LV: IC is " << IC << '\n'
6452                     << "LV: VF is " << VF << '\n');
6453   const bool AggressivelyInterleaveReductions =
6454       TTI.enableAggressiveInterleaving(HasReductions);
6455   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6456     // We assume that the cost overhead is 1 and we use the cost model
6457     // to estimate the cost of the loop and interleave until the cost of the
6458     // loop overhead is about 5% of the cost of the loop.
6459     unsigned SmallIC =
6460         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6461 
6462     // Interleave until store/load ports (estimated by max interleave count) are
6463     // saturated.
6464     unsigned NumStores = Legal->getNumStores();
6465     unsigned NumLoads = Legal->getNumLoads();
6466     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6467     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6468 
6469     // If we have a scalar reduction (vector reductions are already dealt with
6470     // by this point), we can increase the critical path length if the loop
6471     // we're interleaving is inside another loop. Limit, by default to 2, so the
6472     // critical path only gets increased by one reduction operation.
6473     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6474       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6475       SmallIC = std::min(SmallIC, F);
6476       StoresIC = std::min(StoresIC, F);
6477       LoadsIC = std::min(LoadsIC, F);
6478     }
6479 
6480     if (EnableLoadStoreRuntimeInterleave &&
6481         std::max(StoresIC, LoadsIC) > SmallIC) {
6482       LLVM_DEBUG(
6483           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6484       return std::max(StoresIC, LoadsIC);
6485     }
6486 
6487     // If there are scalar reductions and TTI has enabled aggressive
6488     // interleaving for reductions, we will interleave to expose ILP.
6489     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6490         AggressivelyInterleaveReductions) {
6491       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6492       // Interleave no less than SmallIC but not as aggressive as the normal IC
6493       // to satisfy the rare situation when resources are too limited.
6494       return std::max(IC / 2, SmallIC);
6495     } else {
6496       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6497       return SmallIC;
6498     }
6499   }
6500 
6501   // Interleave if this is a large loop (small loops are already dealt with by
6502   // this point) that could benefit from interleaving.
6503   if (AggressivelyInterleaveReductions) {
6504     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6505     return IC;
6506   }
6507 
6508   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6509   return 1;
6510 }
6511 
6512 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6513 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6514   // This function calculates the register usage by measuring the highest number
6515   // of values that are alive at a single location. Obviously, this is a very
6516   // rough estimation. We scan the loop in a topological order in order and
6517   // assign a number to each instruction. We use RPO to ensure that defs are
6518   // met before their users. We assume that each instruction that has in-loop
6519   // users starts an interval. We record every time that an in-loop value is
6520   // used, so we have a list of the first and last occurrences of each
6521   // instruction. Next, we transpose this data structure into a multi map that
6522   // holds the list of intervals that *end* at a specific location. This multi
6523   // map allows us to perform a linear search. We scan the instructions linearly
6524   // and record each time that a new interval starts, by placing it in a set.
6525   // If we find this value in the multi-map then we remove it from the set.
6526   // The max register usage is the maximum size of the set.
6527   // We also search for instructions that are defined outside the loop, but are
6528   // used inside the loop. We need this number separately from the max-interval
6529   // usage number because when we unroll, loop-invariant values do not take
6530   // more register.
6531   LoopBlocksDFS DFS(TheLoop);
6532   DFS.perform(LI);
6533 
6534   RegisterUsage RU;
6535 
6536   // Each 'key' in the map opens a new interval. The values
6537   // of the map are the index of the 'last seen' usage of the
6538   // instruction that is the key.
6539   using IntervalMap = DenseMap<Instruction *, unsigned>;
6540 
6541   // Maps instruction to its index.
6542   SmallVector<Instruction *, 64> IdxToInstr;
6543   // Marks the end of each interval.
6544   IntervalMap EndPoint;
6545   // Saves the list of instruction indices that are used in the loop.
6546   SmallPtrSet<Instruction *, 8> Ends;
6547   // Saves the list of values that are used in the loop but are
6548   // defined outside the loop, such as arguments and constants.
6549   SmallPtrSet<Value *, 8> LoopInvariants;
6550 
6551   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6552     for (Instruction &I : BB->instructionsWithoutDebug()) {
6553       IdxToInstr.push_back(&I);
6554 
6555       // Save the end location of each USE.
6556       for (Value *U : I.operands()) {
6557         auto *Instr = dyn_cast<Instruction>(U);
6558 
6559         // Ignore non-instruction values such as arguments, constants, etc.
6560         if (!Instr)
6561           continue;
6562 
6563         // If this instruction is outside the loop then record it and continue.
6564         if (!TheLoop->contains(Instr)) {
6565           LoopInvariants.insert(Instr);
6566           continue;
6567         }
6568 
6569         // Overwrite previous end points.
6570         EndPoint[Instr] = IdxToInstr.size();
6571         Ends.insert(Instr);
6572       }
6573     }
6574   }
6575 
6576   // Saves the list of intervals that end with the index in 'key'.
6577   using InstrList = SmallVector<Instruction *, 2>;
6578   DenseMap<unsigned, InstrList> TransposeEnds;
6579 
6580   // Transpose the EndPoints to a list of values that end at each index.
6581   for (auto &Interval : EndPoint)
6582     TransposeEnds[Interval.second].push_back(Interval.first);
6583 
6584   SmallPtrSet<Instruction *, 8> OpenIntervals;
6585   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6586   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6587 
6588   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6589 
6590   // A lambda that gets the register usage for the given type and VF.
6591   const auto &TTICapture = TTI;
6592   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) {
6593     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6594       return 0;
6595     return *TTICapture.getRegUsageForType(VectorType::get(Ty, VF)).getValue();
6596   };
6597 
6598   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6599     Instruction *I = IdxToInstr[i];
6600 
6601     // Remove all of the instructions that end at this location.
6602     InstrList &List = TransposeEnds[i];
6603     for (Instruction *ToRemove : List)
6604       OpenIntervals.erase(ToRemove);
6605 
6606     // Ignore instructions that are never used within the loop.
6607     if (!Ends.count(I))
6608       continue;
6609 
6610     // Skip ignored values.
6611     if (ValuesToIgnore.count(I))
6612       continue;
6613 
6614     // For each VF find the maximum usage of registers.
6615     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6616       // Count the number of live intervals.
6617       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6618 
6619       if (VFs[j].isScalar()) {
6620         for (auto Inst : OpenIntervals) {
6621           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6622           if (RegUsage.find(ClassID) == RegUsage.end())
6623             RegUsage[ClassID] = 1;
6624           else
6625             RegUsage[ClassID] += 1;
6626         }
6627       } else {
6628         collectUniformsAndScalars(VFs[j]);
6629         for (auto Inst : OpenIntervals) {
6630           // Skip ignored values for VF > 1.
6631           if (VecValuesToIgnore.count(Inst))
6632             continue;
6633           if (isScalarAfterVectorization(Inst, VFs[j])) {
6634             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6635             if (RegUsage.find(ClassID) == RegUsage.end())
6636               RegUsage[ClassID] = 1;
6637             else
6638               RegUsage[ClassID] += 1;
6639           } else {
6640             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6641             if (RegUsage.find(ClassID) == RegUsage.end())
6642               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6643             else
6644               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6645           }
6646         }
6647       }
6648 
6649       for (auto& pair : RegUsage) {
6650         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6651           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6652         else
6653           MaxUsages[j][pair.first] = pair.second;
6654       }
6655     }
6656 
6657     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6658                       << OpenIntervals.size() << '\n');
6659 
6660     // Add the current instruction to the list of open intervals.
6661     OpenIntervals.insert(I);
6662   }
6663 
6664   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6665     SmallMapVector<unsigned, unsigned, 4> Invariant;
6666 
6667     for (auto Inst : LoopInvariants) {
6668       unsigned Usage =
6669           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6670       unsigned ClassID =
6671           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6672       if (Invariant.find(ClassID) == Invariant.end())
6673         Invariant[ClassID] = Usage;
6674       else
6675         Invariant[ClassID] += Usage;
6676     }
6677 
6678     LLVM_DEBUG({
6679       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6680       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6681              << " item\n";
6682       for (const auto &pair : MaxUsages[i]) {
6683         dbgs() << "LV(REG): RegisterClass: "
6684                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6685                << " registers\n";
6686       }
6687       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6688              << " item\n";
6689       for (const auto &pair : Invariant) {
6690         dbgs() << "LV(REG): RegisterClass: "
6691                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6692                << " registers\n";
6693       }
6694     });
6695 
6696     RU.LoopInvariantRegs = Invariant;
6697     RU.MaxLocalUsers = MaxUsages[i];
6698     RUs[i] = RU;
6699   }
6700 
6701   return RUs;
6702 }
6703 
6704 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6705   // TODO: Cost model for emulated masked load/store is completely
6706   // broken. This hack guides the cost model to use an artificially
6707   // high enough value to practically disable vectorization with such
6708   // operations, except where previously deployed legality hack allowed
6709   // using very low cost values. This is to avoid regressions coming simply
6710   // from moving "masked load/store" check from legality to cost model.
6711   // Masked Load/Gather emulation was previously never allowed.
6712   // Limited number of Masked Store/Scatter emulation was allowed.
6713   assert(isPredicatedInst(I) &&
6714          "Expecting a scalar emulated instruction");
6715   return isa<LoadInst>(I) ||
6716          (isa<StoreInst>(I) &&
6717           NumPredStores > NumberOfStoresToPredicate);
6718 }
6719 
6720 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6721   // If we aren't vectorizing the loop, or if we've already collected the
6722   // instructions to scalarize, there's nothing to do. Collection may already
6723   // have occurred if we have a user-selected VF and are now computing the
6724   // expected cost for interleaving.
6725   if (VF.isScalar() || VF.isZero() ||
6726       InstsToScalarize.find(VF) != InstsToScalarize.end())
6727     return;
6728 
6729   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6730   // not profitable to scalarize any instructions, the presence of VF in the
6731   // map will indicate that we've analyzed it already.
6732   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6733 
6734   // Find all the instructions that are scalar with predication in the loop and
6735   // determine if it would be better to not if-convert the blocks they are in.
6736   // If so, we also record the instructions to scalarize.
6737   for (BasicBlock *BB : TheLoop->blocks()) {
6738     if (!blockNeedsPredication(BB))
6739       continue;
6740     for (Instruction &I : *BB)
6741       if (isScalarWithPredication(&I)) {
6742         ScalarCostsTy ScalarCosts;
6743         // Do not apply discount logic if hacked cost is needed
6744         // for emulated masked memrefs.
6745         if (!useEmulatedMaskMemRefHack(&I) &&
6746             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6747           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6748         // Remember that BB will remain after vectorization.
6749         PredicatedBBsAfterVectorization.insert(BB);
6750       }
6751   }
6752 }
6753 
6754 int LoopVectorizationCostModel::computePredInstDiscount(
6755     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6756   assert(!isUniformAfterVectorization(PredInst, VF) &&
6757          "Instruction marked uniform-after-vectorization will be predicated");
6758 
6759   // Initialize the discount to zero, meaning that the scalar version and the
6760   // vector version cost the same.
6761   InstructionCost Discount = 0;
6762 
6763   // Holds instructions to analyze. The instructions we visit are mapped in
6764   // ScalarCosts. Those instructions are the ones that would be scalarized if
6765   // we find that the scalar version costs less.
6766   SmallVector<Instruction *, 8> Worklist;
6767 
6768   // Returns true if the given instruction can be scalarized.
6769   auto canBeScalarized = [&](Instruction *I) -> bool {
6770     // We only attempt to scalarize instructions forming a single-use chain
6771     // from the original predicated block that would otherwise be vectorized.
6772     // Although not strictly necessary, we give up on instructions we know will
6773     // already be scalar to avoid traversing chains that are unlikely to be
6774     // beneficial.
6775     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6776         isScalarAfterVectorization(I, VF))
6777       return false;
6778 
6779     // If the instruction is scalar with predication, it will be analyzed
6780     // separately. We ignore it within the context of PredInst.
6781     if (isScalarWithPredication(I))
6782       return false;
6783 
6784     // If any of the instruction's operands are uniform after vectorization,
6785     // the instruction cannot be scalarized. This prevents, for example, a
6786     // masked load from being scalarized.
6787     //
6788     // We assume we will only emit a value for lane zero of an instruction
6789     // marked uniform after vectorization, rather than VF identical values.
6790     // Thus, if we scalarize an instruction that uses a uniform, we would
6791     // create uses of values corresponding to the lanes we aren't emitting code
6792     // for. This behavior can be changed by allowing getScalarValue to clone
6793     // the lane zero values for uniforms rather than asserting.
6794     for (Use &U : I->operands())
6795       if (auto *J = dyn_cast<Instruction>(U.get()))
6796         if (isUniformAfterVectorization(J, VF))
6797           return false;
6798 
6799     // Otherwise, we can scalarize the instruction.
6800     return true;
6801   };
6802 
6803   // Compute the expected cost discount from scalarizing the entire expression
6804   // feeding the predicated instruction. We currently only consider expressions
6805   // that are single-use instruction chains.
6806   Worklist.push_back(PredInst);
6807   while (!Worklist.empty()) {
6808     Instruction *I = Worklist.pop_back_val();
6809 
6810     // If we've already analyzed the instruction, there's nothing to do.
6811     if (ScalarCosts.find(I) != ScalarCosts.end())
6812       continue;
6813 
6814     // Compute the cost of the vector instruction. Note that this cost already
6815     // includes the scalarization overhead of the predicated instruction.
6816     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6817 
6818     // Compute the cost of the scalarized instruction. This cost is the cost of
6819     // the instruction as if it wasn't if-converted and instead remained in the
6820     // predicated block. We will scale this cost by block probability after
6821     // computing the scalarization overhead.
6822     assert(!VF.isScalable() && "scalable vectors not yet supported.");
6823     InstructionCost ScalarCost =
6824         VF.getKnownMinValue() *
6825         getInstructionCost(I, ElementCount::getFixed(1)).first;
6826 
6827     // Compute the scalarization overhead of needed insertelement instructions
6828     // and phi nodes.
6829     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6830       ScalarCost += TTI.getScalarizationOverhead(
6831           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6832           APInt::getAllOnesValue(VF.getKnownMinValue()), true, false);
6833       assert(!VF.isScalable() && "scalable vectors not yet supported.");
6834       ScalarCost +=
6835           VF.getKnownMinValue() *
6836           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6837     }
6838 
6839     // Compute the scalarization overhead of needed extractelement
6840     // instructions. For each of the instruction's operands, if the operand can
6841     // be scalarized, add it to the worklist; otherwise, account for the
6842     // overhead.
6843     for (Use &U : I->operands())
6844       if (auto *J = dyn_cast<Instruction>(U.get())) {
6845         assert(VectorType::isValidElementType(J->getType()) &&
6846                "Instruction has non-scalar type");
6847         if (canBeScalarized(J))
6848           Worklist.push_back(J);
6849         else if (needsExtract(J, VF)) {
6850           assert(!VF.isScalable() && "scalable vectors not yet supported.");
6851           ScalarCost += TTI.getScalarizationOverhead(
6852               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6853               APInt::getAllOnesValue(VF.getKnownMinValue()), false, true);
6854         }
6855       }
6856 
6857     // Scale the total scalar cost by block probability.
6858     ScalarCost /= getReciprocalPredBlockProb();
6859 
6860     // Compute the discount. A non-negative discount means the vector version
6861     // of the instruction costs more, and scalarizing would be beneficial.
6862     Discount += VectorCost - ScalarCost;
6863     ScalarCosts[I] = ScalarCost;
6864   }
6865 
6866   return *Discount.getValue();
6867 }
6868 
6869 LoopVectorizationCostModel::VectorizationCostTy
6870 LoopVectorizationCostModel::expectedCost(ElementCount VF) {
6871   VectorizationCostTy Cost;
6872 
6873   // For each block.
6874   for (BasicBlock *BB : TheLoop->blocks()) {
6875     VectorizationCostTy BlockCost;
6876 
6877     // For each instruction in the old loop.
6878     for (Instruction &I : BB->instructionsWithoutDebug()) {
6879       // Skip ignored values.
6880       if (ValuesToIgnore.count(&I) ||
6881           (VF.isVector() && VecValuesToIgnore.count(&I)))
6882         continue;
6883 
6884       VectorizationCostTy C = getInstructionCost(&I, VF);
6885 
6886       // Check if we should override the cost.
6887       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6888         C.first = InstructionCost(ForceTargetInstructionCost);
6889 
6890       BlockCost.first += C.first;
6891       BlockCost.second |= C.second;
6892       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6893                         << " for VF " << VF << " For instruction: " << I
6894                         << '\n');
6895     }
6896 
6897     // If we are vectorizing a predicated block, it will have been
6898     // if-converted. This means that the block's instructions (aside from
6899     // stores and instructions that may divide by zero) will now be
6900     // unconditionally executed. For the scalar case, we may not always execute
6901     // the predicated block, if it is an if-else block. Thus, scale the block's
6902     // cost by the probability of executing it. blockNeedsPredication from
6903     // Legal is used so as to not include all blocks in tail folded loops.
6904     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6905       BlockCost.first /= getReciprocalPredBlockProb();
6906 
6907     Cost.first += BlockCost.first;
6908     Cost.second |= BlockCost.second;
6909   }
6910 
6911   return Cost;
6912 }
6913 
6914 /// Gets Address Access SCEV after verifying that the access pattern
6915 /// is loop invariant except the induction variable dependence.
6916 ///
6917 /// This SCEV can be sent to the Target in order to estimate the address
6918 /// calculation cost.
6919 static const SCEV *getAddressAccessSCEV(
6920               Value *Ptr,
6921               LoopVectorizationLegality *Legal,
6922               PredicatedScalarEvolution &PSE,
6923               const Loop *TheLoop) {
6924 
6925   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6926   if (!Gep)
6927     return nullptr;
6928 
6929   // We are looking for a gep with all loop invariant indices except for one
6930   // which should be an induction variable.
6931   auto SE = PSE.getSE();
6932   unsigned NumOperands = Gep->getNumOperands();
6933   for (unsigned i = 1; i < NumOperands; ++i) {
6934     Value *Opd = Gep->getOperand(i);
6935     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6936         !Legal->isInductionVariable(Opd))
6937       return nullptr;
6938   }
6939 
6940   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6941   return PSE.getSCEV(Ptr);
6942 }
6943 
6944 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6945   return Legal->hasStride(I->getOperand(0)) ||
6946          Legal->hasStride(I->getOperand(1));
6947 }
6948 
6949 InstructionCost
6950 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6951                                                         ElementCount VF) {
6952   assert(VF.isVector() &&
6953          "Scalarization cost of instruction implies vectorization.");
6954   if (VF.isScalable())
6955     return InstructionCost::getInvalid();
6956 
6957   Type *ValTy = getLoadStoreType(I);
6958   auto SE = PSE.getSE();
6959 
6960   unsigned AS = getLoadStoreAddressSpace(I);
6961   Value *Ptr = getLoadStorePointerOperand(I);
6962   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6963 
6964   // Figure out whether the access is strided and get the stride value
6965   // if it's known in compile time
6966   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6967 
6968   // Get the cost of the scalar memory instruction and address computation.
6969   InstructionCost Cost =
6970       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6971 
6972   // Don't pass *I here, since it is scalar but will actually be part of a
6973   // vectorized loop where the user of it is a vectorized instruction.
6974   const Align Alignment = getLoadStoreAlignment(I);
6975   Cost += VF.getKnownMinValue() *
6976           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6977                               AS, TTI::TCK_RecipThroughput);
6978 
6979   // Get the overhead of the extractelement and insertelement instructions
6980   // we might create due to scalarization.
6981   Cost += getScalarizationOverhead(I, VF);
6982 
6983   // If we have a predicated load/store, it will need extra i1 extracts and
6984   // conditional branches, but may not be executed for each vector lane. Scale
6985   // the cost by the probability of executing the predicated block.
6986   if (isPredicatedInst(I)) {
6987     Cost /= getReciprocalPredBlockProb();
6988 
6989     // Add the cost of an i1 extract and a branch
6990     auto *Vec_i1Ty =
6991         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6992     Cost += TTI.getScalarizationOverhead(
6993         Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
6994         /*Insert=*/false, /*Extract=*/true);
6995     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6996 
6997     if (useEmulatedMaskMemRefHack(I))
6998       // Artificially setting to a high enough value to practically disable
6999       // vectorization with such operations.
7000       Cost = 3000000;
7001   }
7002 
7003   return Cost;
7004 }
7005 
7006 InstructionCost
7007 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
7008                                                     ElementCount VF) {
7009   Type *ValTy = getLoadStoreType(I);
7010   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7011   Value *Ptr = getLoadStorePointerOperand(I);
7012   unsigned AS = getLoadStoreAddressSpace(I);
7013   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
7014   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7015 
7016   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7017          "Stride should be 1 or -1 for consecutive memory access");
7018   const Align Alignment = getLoadStoreAlignment(I);
7019   InstructionCost Cost = 0;
7020   if (Legal->isMaskRequired(I))
7021     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7022                                       CostKind);
7023   else
7024     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
7025                                 CostKind, I);
7026 
7027   bool Reverse = ConsecutiveStride < 0;
7028   if (Reverse)
7029     Cost +=
7030         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7031   return Cost;
7032 }
7033 
7034 InstructionCost
7035 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
7036                                                 ElementCount VF) {
7037   assert(Legal->isUniformMemOp(*I));
7038 
7039   Type *ValTy = getLoadStoreType(I);
7040   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7041   const Align Alignment = getLoadStoreAlignment(I);
7042   unsigned AS = getLoadStoreAddressSpace(I);
7043   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7044   if (isa<LoadInst>(I)) {
7045     return TTI.getAddressComputationCost(ValTy) +
7046            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
7047                                CostKind) +
7048            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
7049   }
7050   StoreInst *SI = cast<StoreInst>(I);
7051 
7052   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
7053   return TTI.getAddressComputationCost(ValTy) +
7054          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
7055                              CostKind) +
7056          (isLoopInvariantStoreValue
7057               ? 0
7058               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
7059                                        VF.getKnownMinValue() - 1));
7060 }
7061 
7062 InstructionCost
7063 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
7064                                                  ElementCount VF) {
7065   Type *ValTy = getLoadStoreType(I);
7066   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7067   const Align Alignment = getLoadStoreAlignment(I);
7068   const Value *Ptr = getLoadStorePointerOperand(I);
7069 
7070   return TTI.getAddressComputationCost(VectorTy) +
7071          TTI.getGatherScatterOpCost(
7072              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
7073              TargetTransformInfo::TCK_RecipThroughput, I);
7074 }
7075 
7076 InstructionCost
7077 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
7078                                                    ElementCount VF) {
7079   // TODO: Once we have support for interleaving with scalable vectors
7080   // we can calculate the cost properly here.
7081   if (VF.isScalable())
7082     return InstructionCost::getInvalid();
7083 
7084   Type *ValTy = getLoadStoreType(I);
7085   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
7086   unsigned AS = getLoadStoreAddressSpace(I);
7087 
7088   auto Group = getInterleavedAccessGroup(I);
7089   assert(Group && "Fail to get an interleaved access group.");
7090 
7091   unsigned InterleaveFactor = Group->getFactor();
7092   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
7093 
7094   // Holds the indices of existing members in an interleaved load group.
7095   // An interleaved store group doesn't need this as it doesn't allow gaps.
7096   SmallVector<unsigned, 4> Indices;
7097   if (isa<LoadInst>(I)) {
7098     for (unsigned i = 0; i < InterleaveFactor; i++)
7099       if (Group->getMember(i))
7100         Indices.push_back(i);
7101   }
7102 
7103   // Calculate the cost of the whole interleaved group.
7104   bool UseMaskForGaps =
7105       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
7106   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
7107       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
7108       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
7109 
7110   if (Group->isReverse()) {
7111     // TODO: Add support for reversed masked interleaved access.
7112     assert(!Legal->isMaskRequired(I) &&
7113            "Reverse masked interleaved access not supported.");
7114     Cost +=
7115         Group->getNumMembers() *
7116         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
7117   }
7118   return Cost;
7119 }
7120 
7121 InstructionCost LoopVectorizationCostModel::getReductionPatternCost(
7122     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
7123   // Early exit for no inloop reductions
7124   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
7125     return InstructionCost::getInvalid();
7126   auto *VectorTy = cast<VectorType>(Ty);
7127 
7128   // We are looking for a pattern of, and finding the minimal acceptable cost:
7129   //  reduce(mul(ext(A), ext(B))) or
7130   //  reduce(mul(A, B)) or
7131   //  reduce(ext(A)) or
7132   //  reduce(A).
7133   // The basic idea is that we walk down the tree to do that, finding the root
7134   // reduction instruction in InLoopReductionImmediateChains. From there we find
7135   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
7136   // of the components. If the reduction cost is lower then we return it for the
7137   // reduction instruction and 0 for the other instructions in the pattern. If
7138   // it is not we return an invalid cost specifying the orignal cost method
7139   // should be used.
7140   Instruction *RetI = I;
7141   if ((RetI->getOpcode() == Instruction::SExt ||
7142        RetI->getOpcode() == Instruction::ZExt)) {
7143     if (!RetI->hasOneUser())
7144       return InstructionCost::getInvalid();
7145     RetI = RetI->user_back();
7146   }
7147   if (RetI->getOpcode() == Instruction::Mul &&
7148       RetI->user_back()->getOpcode() == Instruction::Add) {
7149     if (!RetI->hasOneUser())
7150       return InstructionCost::getInvalid();
7151     RetI = RetI->user_back();
7152   }
7153 
7154   // Test if the found instruction is a reduction, and if not return an invalid
7155   // cost specifying the parent to use the original cost modelling.
7156   if (!InLoopReductionImmediateChains.count(RetI))
7157     return InstructionCost::getInvalid();
7158 
7159   // Find the reduction this chain is a part of and calculate the basic cost of
7160   // the reduction on its own.
7161   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
7162   Instruction *ReductionPhi = LastChain;
7163   while (!isa<PHINode>(ReductionPhi))
7164     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
7165 
7166   const RecurrenceDescriptor &RdxDesc =
7167       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
7168   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
7169       RdxDesc.getOpcode(), VectorTy, false, CostKind);
7170 
7171   // Get the operand that was not the reduction chain and match it to one of the
7172   // patterns, returning the better cost if it is found.
7173   Instruction *RedOp = RetI->getOperand(1) == LastChain
7174                            ? dyn_cast<Instruction>(RetI->getOperand(0))
7175                            : dyn_cast<Instruction>(RetI->getOperand(1));
7176 
7177   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
7178 
7179   if (RedOp && (isa<SExtInst>(RedOp) || isa<ZExtInst>(RedOp)) &&
7180       !TheLoop->isLoopInvariant(RedOp)) {
7181     bool IsUnsigned = isa<ZExtInst>(RedOp);
7182     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7183     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7184         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7185         CostKind);
7186 
7187     InstructionCost ExtCost =
7188         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7189                              TTI::CastContextHint::None, CostKind, RedOp);
7190     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7191       return I == RetI ? *RedCost.getValue() : 0;
7192   } else if (RedOp && RedOp->getOpcode() == Instruction::Mul) {
7193     Instruction *Mul = RedOp;
7194     Instruction *Op0 = dyn_cast<Instruction>(Mul->getOperand(0));
7195     Instruction *Op1 = dyn_cast<Instruction>(Mul->getOperand(1));
7196     if (Op0 && Op1 && (isa<SExtInst>(Op0) || isa<ZExtInst>(Op0)) &&
7197         Op0->getOpcode() == Op1->getOpcode() &&
7198         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7199         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7200       bool IsUnsigned = isa<ZExtInst>(Op0);
7201       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7202       // reduce(mul(ext, ext))
7203       InstructionCost ExtCost =
7204           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
7205                                TTI::CastContextHint::None, CostKind, Op0);
7206       InstructionCost MulCost =
7207           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7208 
7209       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7210           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7211           CostKind);
7212 
7213       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
7214         return I == RetI ? *RedCost.getValue() : 0;
7215     } else {
7216       InstructionCost MulCost =
7217           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7218 
7219       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7220           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7221           CostKind);
7222 
7223       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7224         return I == RetI ? *RedCost.getValue() : 0;
7225     }
7226   }
7227 
7228   return I == RetI ? BaseCost : InstructionCost::getInvalid();
7229 }
7230 
7231 InstructionCost
7232 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7233                                                      ElementCount VF) {
7234   // Calculate scalar cost only. Vectorization cost should be ready at this
7235   // moment.
7236   if (VF.isScalar()) {
7237     Type *ValTy = getLoadStoreType(I);
7238     const Align Alignment = getLoadStoreAlignment(I);
7239     unsigned AS = getLoadStoreAddressSpace(I);
7240 
7241     return TTI.getAddressComputationCost(ValTy) +
7242            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7243                                TTI::TCK_RecipThroughput, I);
7244   }
7245   return getWideningCost(I, VF);
7246 }
7247 
7248 LoopVectorizationCostModel::VectorizationCostTy
7249 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7250                                                ElementCount VF) {
7251   // If we know that this instruction will remain uniform, check the cost of
7252   // the scalar version.
7253   if (isUniformAfterVectorization(I, VF))
7254     VF = ElementCount::getFixed(1);
7255 
7256   if (VF.isVector() && isProfitableToScalarize(I, VF))
7257     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7258 
7259   // Forced scalars do not have any scalarization overhead.
7260   auto ForcedScalar = ForcedScalars.find(VF);
7261   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7262     auto InstSet = ForcedScalar->second;
7263     if (InstSet.count(I))
7264       return VectorizationCostTy(
7265           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7266            VF.getKnownMinValue()),
7267           false);
7268   }
7269 
7270   Type *VectorTy;
7271   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7272 
7273   bool TypeNotScalarized =
7274       VF.isVector() && VectorTy->isVectorTy() &&
7275       TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
7276   return VectorizationCostTy(C, TypeNotScalarized);
7277 }
7278 
7279 InstructionCost
7280 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7281                                                      ElementCount VF) const {
7282 
7283   if (VF.isScalable())
7284     return InstructionCost::getInvalid();
7285 
7286   if (VF.isScalar())
7287     return 0;
7288 
7289   InstructionCost Cost = 0;
7290   Type *RetTy = ToVectorTy(I->getType(), VF);
7291   if (!RetTy->isVoidTy() &&
7292       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7293     Cost += TTI.getScalarizationOverhead(
7294         cast<VectorType>(RetTy), APInt::getAllOnesValue(VF.getKnownMinValue()),
7295         true, false);
7296 
7297   // Some targets keep addresses scalar.
7298   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7299     return Cost;
7300 
7301   // Some targets support efficient element stores.
7302   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7303     return Cost;
7304 
7305   // Collect operands to consider.
7306   CallInst *CI = dyn_cast<CallInst>(I);
7307   Instruction::op_range Ops = CI ? CI->arg_operands() : I->operands();
7308 
7309   // Skip operands that do not require extraction/scalarization and do not incur
7310   // any overhead.
7311   SmallVector<Type *> Tys;
7312   for (auto *V : filterExtractingOperands(Ops, VF))
7313     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7314   return Cost + TTI.getOperandsScalarizationOverhead(
7315                     filterExtractingOperands(Ops, VF), Tys);
7316 }
7317 
7318 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7319   if (VF.isScalar())
7320     return;
7321   NumPredStores = 0;
7322   for (BasicBlock *BB : TheLoop->blocks()) {
7323     // For each instruction in the old loop.
7324     for (Instruction &I : *BB) {
7325       Value *Ptr =  getLoadStorePointerOperand(&I);
7326       if (!Ptr)
7327         continue;
7328 
7329       // TODO: We should generate better code and update the cost model for
7330       // predicated uniform stores. Today they are treated as any other
7331       // predicated store (see added test cases in
7332       // invariant-store-vectorization.ll).
7333       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7334         NumPredStores++;
7335 
7336       if (Legal->isUniformMemOp(I)) {
7337         // TODO: Avoid replicating loads and stores instead of
7338         // relying on instcombine to remove them.
7339         // Load: Scalar load + broadcast
7340         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7341         InstructionCost Cost;
7342         if (isa<StoreInst>(&I) && VF.isScalable() &&
7343             isLegalGatherOrScatter(&I)) {
7344           Cost = getGatherScatterCost(&I, VF);
7345           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
7346         } else {
7347           assert((isa<LoadInst>(&I) || !VF.isScalable()) &&
7348                  "Cannot yet scalarize uniform stores");
7349           Cost = getUniformMemOpCost(&I, VF);
7350           setWideningDecision(&I, VF, CM_Scalarize, Cost);
7351         }
7352         continue;
7353       }
7354 
7355       // We assume that widening is the best solution when possible.
7356       if (memoryInstructionCanBeWidened(&I, VF)) {
7357         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7358         int ConsecutiveStride =
7359                Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
7360         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7361                "Expected consecutive stride.");
7362         InstWidening Decision =
7363             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7364         setWideningDecision(&I, VF, Decision, Cost);
7365         continue;
7366       }
7367 
7368       // Choose between Interleaving, Gather/Scatter or Scalarization.
7369       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7370       unsigned NumAccesses = 1;
7371       if (isAccessInterleaved(&I)) {
7372         auto Group = getInterleavedAccessGroup(&I);
7373         assert(Group && "Fail to get an interleaved access group.");
7374 
7375         // Make one decision for the whole group.
7376         if (getWideningDecision(&I, VF) != CM_Unknown)
7377           continue;
7378 
7379         NumAccesses = Group->getNumMembers();
7380         if (interleavedAccessCanBeWidened(&I, VF))
7381           InterleaveCost = getInterleaveGroupCost(&I, VF);
7382       }
7383 
7384       InstructionCost GatherScatterCost =
7385           isLegalGatherOrScatter(&I)
7386               ? getGatherScatterCost(&I, VF) * NumAccesses
7387               : InstructionCost::getInvalid();
7388 
7389       InstructionCost ScalarizationCost =
7390           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7391 
7392       // Choose better solution for the current VF,
7393       // write down this decision and use it during vectorization.
7394       InstructionCost Cost;
7395       InstWidening Decision;
7396       if (InterleaveCost <= GatherScatterCost &&
7397           InterleaveCost < ScalarizationCost) {
7398         Decision = CM_Interleave;
7399         Cost = InterleaveCost;
7400       } else if (GatherScatterCost < ScalarizationCost) {
7401         Decision = CM_GatherScatter;
7402         Cost = GatherScatterCost;
7403       } else {
7404         assert(!VF.isScalable() &&
7405                "We cannot yet scalarise for scalable vectors");
7406         Decision = CM_Scalarize;
7407         Cost = ScalarizationCost;
7408       }
7409       // If the instructions belongs to an interleave group, the whole group
7410       // receives the same decision. The whole group receives the cost, but
7411       // the cost will actually be assigned to one instruction.
7412       if (auto Group = getInterleavedAccessGroup(&I))
7413         setWideningDecision(Group, VF, Decision, Cost);
7414       else
7415         setWideningDecision(&I, VF, Decision, Cost);
7416     }
7417   }
7418 
7419   // Make sure that any load of address and any other address computation
7420   // remains scalar unless there is gather/scatter support. This avoids
7421   // inevitable extracts into address registers, and also has the benefit of
7422   // activating LSR more, since that pass can't optimize vectorized
7423   // addresses.
7424   if (TTI.prefersVectorizedAddressing())
7425     return;
7426 
7427   // Start with all scalar pointer uses.
7428   SmallPtrSet<Instruction *, 8> AddrDefs;
7429   for (BasicBlock *BB : TheLoop->blocks())
7430     for (Instruction &I : *BB) {
7431       Instruction *PtrDef =
7432         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7433       if (PtrDef && TheLoop->contains(PtrDef) &&
7434           getWideningDecision(&I, VF) != CM_GatherScatter)
7435         AddrDefs.insert(PtrDef);
7436     }
7437 
7438   // Add all instructions used to generate the addresses.
7439   SmallVector<Instruction *, 4> Worklist;
7440   append_range(Worklist, AddrDefs);
7441   while (!Worklist.empty()) {
7442     Instruction *I = Worklist.pop_back_val();
7443     for (auto &Op : I->operands())
7444       if (auto *InstOp = dyn_cast<Instruction>(Op))
7445         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7446             AddrDefs.insert(InstOp).second)
7447           Worklist.push_back(InstOp);
7448   }
7449 
7450   for (auto *I : AddrDefs) {
7451     if (isa<LoadInst>(I)) {
7452       // Setting the desired widening decision should ideally be handled in
7453       // by cost functions, but since this involves the task of finding out
7454       // if the loaded register is involved in an address computation, it is
7455       // instead changed here when we know this is the case.
7456       InstWidening Decision = getWideningDecision(I, VF);
7457       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7458         // Scalarize a widened load of address.
7459         setWideningDecision(
7460             I, VF, CM_Scalarize,
7461             (VF.getKnownMinValue() *
7462              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7463       else if (auto Group = getInterleavedAccessGroup(I)) {
7464         // Scalarize an interleave group of address loads.
7465         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7466           if (Instruction *Member = Group->getMember(I))
7467             setWideningDecision(
7468                 Member, VF, CM_Scalarize,
7469                 (VF.getKnownMinValue() *
7470                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7471         }
7472       }
7473     } else
7474       // Make sure I gets scalarized and a cost estimate without
7475       // scalarization overhead.
7476       ForcedScalars[VF].insert(I);
7477   }
7478 }
7479 
7480 InstructionCost
7481 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7482                                                Type *&VectorTy) {
7483   Type *RetTy = I->getType();
7484   if (canTruncateToMinimalBitwidth(I, VF))
7485     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7486   auto SE = PSE.getSE();
7487   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7488 
7489   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7490                                                 ElementCount VF) -> bool {
7491     if (VF.isScalar())
7492       return true;
7493 
7494     auto Scalarized = InstsToScalarize.find(VF);
7495     assert(Scalarized != InstsToScalarize.end() &&
7496            "VF not yet analyzed for scalarization profitability");
7497     return !Scalarized->second.count(I) &&
7498            llvm::all_of(I->users(), [&](User *U) {
7499              auto *UI = cast<Instruction>(U);
7500              return !Scalarized->second.count(UI);
7501            });
7502   };
7503   (void) hasSingleCopyAfterVectorization;
7504 
7505   if (isScalarAfterVectorization(I, VF)) {
7506     // With the exception of GEPs and PHIs, after scalarization there should
7507     // only be one copy of the instruction generated in the loop. This is
7508     // because the VF is either 1, or any instructions that need scalarizing
7509     // have already been dealt with by the the time we get here. As a result,
7510     // it means we don't have to multiply the instruction cost by VF.
7511     assert(I->getOpcode() == Instruction::GetElementPtr ||
7512            I->getOpcode() == Instruction::PHI ||
7513            (I->getOpcode() == Instruction::BitCast &&
7514             I->getType()->isPointerTy()) ||
7515            hasSingleCopyAfterVectorization(I, VF));
7516     VectorTy = RetTy;
7517   } else
7518     VectorTy = ToVectorTy(RetTy, VF);
7519 
7520   // TODO: We need to estimate the cost of intrinsic calls.
7521   switch (I->getOpcode()) {
7522   case Instruction::GetElementPtr:
7523     // We mark this instruction as zero-cost because the cost of GEPs in
7524     // vectorized code depends on whether the corresponding memory instruction
7525     // is scalarized or not. Therefore, we handle GEPs with the memory
7526     // instruction cost.
7527     return 0;
7528   case Instruction::Br: {
7529     // In cases of scalarized and predicated instructions, there will be VF
7530     // predicated blocks in the vectorized loop. Each branch around these
7531     // blocks requires also an extract of its vector compare i1 element.
7532     bool ScalarPredicatedBB = false;
7533     BranchInst *BI = cast<BranchInst>(I);
7534     if (VF.isVector() && BI->isConditional() &&
7535         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7536          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7537       ScalarPredicatedBB = true;
7538 
7539     if (ScalarPredicatedBB) {
7540       // Return cost for branches around scalarized and predicated blocks.
7541       assert(!VF.isScalable() && "scalable vectors not yet supported.");
7542       auto *Vec_i1Ty =
7543           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7544       return (TTI.getScalarizationOverhead(
7545                   Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7546                   false, true) +
7547               (TTI.getCFInstrCost(Instruction::Br, CostKind) *
7548                VF.getKnownMinValue()));
7549     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7550       // The back-edge branch will remain, as will all scalar branches.
7551       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7552     else
7553       // This branch will be eliminated by if-conversion.
7554       return 0;
7555     // Note: We currently assume zero cost for an unconditional branch inside
7556     // a predicated block since it will become a fall-through, although we
7557     // may decide in the future to call TTI for all branches.
7558   }
7559   case Instruction::PHI: {
7560     auto *Phi = cast<PHINode>(I);
7561 
7562     // First-order recurrences are replaced by vector shuffles inside the loop.
7563     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7564     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7565       return TTI.getShuffleCost(
7566           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7567           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7568 
7569     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7570     // converted into select instructions. We require N - 1 selects per phi
7571     // node, where N is the number of incoming values.
7572     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7573       return (Phi->getNumIncomingValues() - 1) *
7574              TTI.getCmpSelInstrCost(
7575                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7576                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7577                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7578 
7579     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7580   }
7581   case Instruction::UDiv:
7582   case Instruction::SDiv:
7583   case Instruction::URem:
7584   case Instruction::SRem:
7585     // If we have a predicated instruction, it may not be executed for each
7586     // vector lane. Get the scalarization cost and scale this amount by the
7587     // probability of executing the predicated block. If the instruction is not
7588     // predicated, we fall through to the next case.
7589     if (VF.isVector() && isScalarWithPredication(I)) {
7590       InstructionCost Cost = 0;
7591 
7592       // These instructions have a non-void type, so account for the phi nodes
7593       // that we will create. This cost is likely to be zero. The phi node
7594       // cost, if any, should be scaled by the block probability because it
7595       // models a copy at the end of each predicated block.
7596       Cost += VF.getKnownMinValue() *
7597               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7598 
7599       // The cost of the non-predicated instruction.
7600       Cost += VF.getKnownMinValue() *
7601               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7602 
7603       // The cost of insertelement and extractelement instructions needed for
7604       // scalarization.
7605       Cost += getScalarizationOverhead(I, VF);
7606 
7607       // Scale the cost by the probability of executing the predicated blocks.
7608       // This assumes the predicated block for each vector lane is equally
7609       // likely.
7610       return Cost / getReciprocalPredBlockProb();
7611     }
7612     LLVM_FALLTHROUGH;
7613   case Instruction::Add:
7614   case Instruction::FAdd:
7615   case Instruction::Sub:
7616   case Instruction::FSub:
7617   case Instruction::Mul:
7618   case Instruction::FMul:
7619   case Instruction::FDiv:
7620   case Instruction::FRem:
7621   case Instruction::Shl:
7622   case Instruction::LShr:
7623   case Instruction::AShr:
7624   case Instruction::And:
7625   case Instruction::Or:
7626   case Instruction::Xor: {
7627     // Since we will replace the stride by 1 the multiplication should go away.
7628     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7629       return 0;
7630 
7631     // Detect reduction patterns
7632     InstructionCost RedCost;
7633     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7634             .isValid())
7635       return RedCost;
7636 
7637     // Certain instructions can be cheaper to vectorize if they have a constant
7638     // second vector operand. One example of this are shifts on x86.
7639     Value *Op2 = I->getOperand(1);
7640     TargetTransformInfo::OperandValueProperties Op2VP;
7641     TargetTransformInfo::OperandValueKind Op2VK =
7642         TTI.getOperandInfo(Op2, Op2VP);
7643     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7644       Op2VK = TargetTransformInfo::OK_UniformValue;
7645 
7646     SmallVector<const Value *, 4> Operands(I->operand_values());
7647     return TTI.getArithmeticInstrCost(
7648         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7649         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7650   }
7651   case Instruction::FNeg: {
7652     return TTI.getArithmeticInstrCost(
7653         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7654         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7655         TargetTransformInfo::OP_None, I->getOperand(0), I);
7656   }
7657   case Instruction::Select: {
7658     SelectInst *SI = cast<SelectInst>(I);
7659     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7660     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7661 
7662     const Value *Op0, *Op1;
7663     using namespace llvm::PatternMatch;
7664     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7665                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7666       // select x, y, false --> x & y
7667       // select x, true, y --> x | y
7668       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7669       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7670       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7671       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7672       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7673               Op1->getType()->getScalarSizeInBits() == 1);
7674 
7675       SmallVector<const Value *, 2> Operands{Op0, Op1};
7676       return TTI.getArithmeticInstrCost(
7677           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7678           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7679     }
7680 
7681     Type *CondTy = SI->getCondition()->getType();
7682     if (!ScalarCond)
7683       CondTy = VectorType::get(CondTy, VF);
7684     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
7685                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7686   }
7687   case Instruction::ICmp:
7688   case Instruction::FCmp: {
7689     Type *ValTy = I->getOperand(0)->getType();
7690     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7691     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7692       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7693     VectorTy = ToVectorTy(ValTy, VF);
7694     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7695                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7696   }
7697   case Instruction::Store:
7698   case Instruction::Load: {
7699     ElementCount Width = VF;
7700     if (Width.isVector()) {
7701       InstWidening Decision = getWideningDecision(I, Width);
7702       assert(Decision != CM_Unknown &&
7703              "CM decision should be taken at this point");
7704       if (Decision == CM_Scalarize)
7705         Width = ElementCount::getFixed(1);
7706     }
7707     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7708     return getMemoryInstructionCost(I, VF);
7709   }
7710   case Instruction::BitCast:
7711     if (I->getType()->isPointerTy())
7712       return 0;
7713     LLVM_FALLTHROUGH;
7714   case Instruction::ZExt:
7715   case Instruction::SExt:
7716   case Instruction::FPToUI:
7717   case Instruction::FPToSI:
7718   case Instruction::FPExt:
7719   case Instruction::PtrToInt:
7720   case Instruction::IntToPtr:
7721   case Instruction::SIToFP:
7722   case Instruction::UIToFP:
7723   case Instruction::Trunc:
7724   case Instruction::FPTrunc: {
7725     // Computes the CastContextHint from a Load/Store instruction.
7726     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7727       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7728              "Expected a load or a store!");
7729 
7730       if (VF.isScalar() || !TheLoop->contains(I))
7731         return TTI::CastContextHint::Normal;
7732 
7733       switch (getWideningDecision(I, VF)) {
7734       case LoopVectorizationCostModel::CM_GatherScatter:
7735         return TTI::CastContextHint::GatherScatter;
7736       case LoopVectorizationCostModel::CM_Interleave:
7737         return TTI::CastContextHint::Interleave;
7738       case LoopVectorizationCostModel::CM_Scalarize:
7739       case LoopVectorizationCostModel::CM_Widen:
7740         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7741                                         : TTI::CastContextHint::Normal;
7742       case LoopVectorizationCostModel::CM_Widen_Reverse:
7743         return TTI::CastContextHint::Reversed;
7744       case LoopVectorizationCostModel::CM_Unknown:
7745         llvm_unreachable("Instr did not go through cost modelling?");
7746       }
7747 
7748       llvm_unreachable("Unhandled case!");
7749     };
7750 
7751     unsigned Opcode = I->getOpcode();
7752     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7753     // For Trunc, the context is the only user, which must be a StoreInst.
7754     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7755       if (I->hasOneUse())
7756         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7757           CCH = ComputeCCH(Store);
7758     }
7759     // For Z/Sext, the context is the operand, which must be a LoadInst.
7760     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7761              Opcode == Instruction::FPExt) {
7762       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7763         CCH = ComputeCCH(Load);
7764     }
7765 
7766     // We optimize the truncation of induction variables having constant
7767     // integer steps. The cost of these truncations is the same as the scalar
7768     // operation.
7769     if (isOptimizableIVTruncate(I, VF)) {
7770       auto *Trunc = cast<TruncInst>(I);
7771       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7772                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7773     }
7774 
7775     // Detect reduction patterns
7776     InstructionCost RedCost;
7777     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7778             .isValid())
7779       return RedCost;
7780 
7781     Type *SrcScalarTy = I->getOperand(0)->getType();
7782     Type *SrcVecTy =
7783         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7784     if (canTruncateToMinimalBitwidth(I, VF)) {
7785       // This cast is going to be shrunk. This may remove the cast or it might
7786       // turn it into slightly different cast. For example, if MinBW == 16,
7787       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7788       //
7789       // Calculate the modified src and dest types.
7790       Type *MinVecTy = VectorTy;
7791       if (Opcode == Instruction::Trunc) {
7792         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7793         VectorTy =
7794             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7795       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7796         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7797         VectorTy =
7798             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7799       }
7800     }
7801 
7802     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7803   }
7804   case Instruction::Call: {
7805     bool NeedToScalarize;
7806     CallInst *CI = cast<CallInst>(I);
7807     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7808     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7809       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7810       return std::min(CallCost, IntrinsicCost);
7811     }
7812     return CallCost;
7813   }
7814   case Instruction::ExtractValue:
7815     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7816   default:
7817     // This opcode is unknown. Assume that it is the same as 'mul'.
7818     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7819   } // end of switch.
7820 }
7821 
7822 char LoopVectorize::ID = 0;
7823 
7824 static const char lv_name[] = "Loop Vectorization";
7825 
7826 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7827 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7828 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7829 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7830 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7831 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7832 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7833 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7834 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7835 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7836 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7837 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7838 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7839 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7840 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7841 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7842 
7843 namespace llvm {
7844 
7845 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7846 
7847 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7848                               bool VectorizeOnlyWhenForced) {
7849   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7850 }
7851 
7852 } // end namespace llvm
7853 
7854 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7855   // Check if the pointer operand of a load or store instruction is
7856   // consecutive.
7857   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7858     return Legal->isConsecutivePtr(Ptr);
7859   return false;
7860 }
7861 
7862 void LoopVectorizationCostModel::collectValuesToIgnore() {
7863   // Ignore ephemeral values.
7864   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7865 
7866   // Ignore type-promoting instructions we identified during reduction
7867   // detection.
7868   for (auto &Reduction : Legal->getReductionVars()) {
7869     RecurrenceDescriptor &RedDes = Reduction.second;
7870     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7871     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7872   }
7873   // Ignore type-casting instructions we identified during induction
7874   // detection.
7875   for (auto &Induction : Legal->getInductionVars()) {
7876     InductionDescriptor &IndDes = Induction.second;
7877     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7878     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7879   }
7880 }
7881 
7882 void LoopVectorizationCostModel::collectInLoopReductions() {
7883   for (auto &Reduction : Legal->getReductionVars()) {
7884     PHINode *Phi = Reduction.first;
7885     RecurrenceDescriptor &RdxDesc = Reduction.second;
7886 
7887     // We don't collect reductions that are type promoted (yet).
7888     if (RdxDesc.getRecurrenceType() != Phi->getType())
7889       continue;
7890 
7891     // If the target would prefer this reduction to happen "in-loop", then we
7892     // want to record it as such.
7893     unsigned Opcode = RdxDesc.getOpcode();
7894     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7895         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7896                                    TargetTransformInfo::ReductionFlags()))
7897       continue;
7898 
7899     // Check that we can correctly put the reductions into the loop, by
7900     // finding the chain of operations that leads from the phi to the loop
7901     // exit value.
7902     SmallVector<Instruction *, 4> ReductionOperations =
7903         RdxDesc.getReductionOpChain(Phi, TheLoop);
7904     bool InLoop = !ReductionOperations.empty();
7905     if (InLoop) {
7906       InLoopReductionChains[Phi] = ReductionOperations;
7907       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7908       Instruction *LastChain = Phi;
7909       for (auto *I : ReductionOperations) {
7910         InLoopReductionImmediateChains[I] = LastChain;
7911         LastChain = I;
7912       }
7913     }
7914     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7915                       << " reduction for phi: " << *Phi << "\n");
7916   }
7917 }
7918 
7919 // TODO: we could return a pair of values that specify the max VF and
7920 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7921 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7922 // doesn't have a cost model that can choose which plan to execute if
7923 // more than one is generated.
7924 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7925                                  LoopVectorizationCostModel &CM) {
7926   unsigned WidestType;
7927   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7928   return WidestVectorRegBits / WidestType;
7929 }
7930 
7931 VectorizationFactor
7932 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7933   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7934   ElementCount VF = UserVF;
7935   // Outer loop handling: They may require CFG and instruction level
7936   // transformations before even evaluating whether vectorization is profitable.
7937   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7938   // the vectorization pipeline.
7939   if (!OrigLoop->isInnermost()) {
7940     // If the user doesn't provide a vectorization factor, determine a
7941     // reasonable one.
7942     if (UserVF.isZero()) {
7943       VF = ElementCount::getFixed(determineVPlanVF(
7944           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7945               .getFixedSize(),
7946           CM));
7947       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7948 
7949       // Make sure we have a VF > 1 for stress testing.
7950       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7951         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7952                           << "overriding computed VF.\n");
7953         VF = ElementCount::getFixed(4);
7954       }
7955     }
7956     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7957     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7958            "VF needs to be a power of two");
7959     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7960                       << "VF " << VF << " to build VPlans.\n");
7961     buildVPlans(VF, VF);
7962 
7963     // For VPlan build stress testing, we bail out after VPlan construction.
7964     if (VPlanBuildStressTest)
7965       return VectorizationFactor::Disabled();
7966 
7967     return {VF, 0 /*Cost*/};
7968   }
7969 
7970   LLVM_DEBUG(
7971       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7972                 "VPlan-native path.\n");
7973   return VectorizationFactor::Disabled();
7974 }
7975 
7976 Optional<VectorizationFactor>
7977 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7978   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7979   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7980   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7981     return None;
7982 
7983   // Invalidate interleave groups if all blocks of loop will be predicated.
7984   if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
7985       !useMaskedInterleavedAccesses(*TTI)) {
7986     LLVM_DEBUG(
7987         dbgs()
7988         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7989            "which requires masked-interleaved support.\n");
7990     if (CM.InterleaveInfo.invalidateGroups())
7991       // Invalidating interleave groups also requires invalidating all decisions
7992       // based on them, which includes widening decisions and uniform and scalar
7993       // values.
7994       CM.invalidateCostModelingDecisions();
7995   }
7996 
7997   ElementCount MaxUserVF =
7998       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7999   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
8000   if (!UserVF.isZero() && UserVFIsLegal) {
8001     LLVM_DEBUG(dbgs() << "LV: Using " << (UserVFIsLegal ? "user" : "max")
8002                       << " VF " << UserVF << ".\n");
8003     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
8004            "VF needs to be a power of two");
8005     // Collect the instructions (and their associated costs) that will be more
8006     // profitable to scalarize.
8007     CM.selectUserVectorizationFactor(UserVF);
8008     CM.collectInLoopReductions();
8009     buildVPlansWithVPRecipes(UserVF, UserVF);
8010     LLVM_DEBUG(printPlans(dbgs()));
8011     return {{UserVF, 0}};
8012   }
8013 
8014   // Populate the set of Vectorization Factor Candidates.
8015   ElementCountSet VFCandidates;
8016   for (auto VF = ElementCount::getFixed(1);
8017        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
8018     VFCandidates.insert(VF);
8019   for (auto VF = ElementCount::getScalable(1);
8020        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
8021     VFCandidates.insert(VF);
8022 
8023   for (const auto &VF : VFCandidates) {
8024     // Collect Uniform and Scalar instructions after vectorization with VF.
8025     CM.collectUniformsAndScalars(VF);
8026 
8027     // Collect the instructions (and their associated costs) that will be more
8028     // profitable to scalarize.
8029     if (VF.isVector())
8030       CM.collectInstsToScalarize(VF);
8031   }
8032 
8033   CM.collectInLoopReductions();
8034   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
8035   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
8036 
8037   LLVM_DEBUG(printPlans(dbgs()));
8038   if (!MaxFactors.hasVector())
8039     return VectorizationFactor::Disabled();
8040 
8041   // Select the optimal vectorization factor.
8042   auto SelectedVF = CM.selectVectorizationFactor(VFCandidates);
8043 
8044   // Check if it is profitable to vectorize with runtime checks.
8045   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
8046   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
8047     bool PragmaThresholdReached =
8048         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
8049     bool ThresholdReached =
8050         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
8051     if ((ThresholdReached && !Hints.allowReordering()) ||
8052         PragmaThresholdReached) {
8053       ORE->emit([&]() {
8054         return OptimizationRemarkAnalysisAliasing(
8055                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
8056                    OrigLoop->getHeader())
8057                << "loop not vectorized: cannot prove it is safe to reorder "
8058                   "memory operations";
8059       });
8060       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
8061       Hints.emitRemarkWithHints();
8062       return VectorizationFactor::Disabled();
8063     }
8064   }
8065   return SelectedVF;
8066 }
8067 
8068 void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
8069   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
8070                     << '\n');
8071   BestVF = VF;
8072   BestUF = UF;
8073 
8074   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
8075     return !Plan->hasVF(VF);
8076   });
8077   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
8078 }
8079 
8080 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
8081                                            DominatorTree *DT) {
8082   // Perform the actual loop transformation.
8083 
8084   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
8085   assert(BestVF.hasValue() && "Vectorization Factor is missing");
8086   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
8087 
8088   VPTransformState State{
8089       *BestVF, BestUF, LI, DT, ILV.Builder, &ILV, VPlans.front().get()};
8090   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
8091   State.TripCount = ILV.getOrCreateTripCount(nullptr);
8092   State.CanonicalIV = ILV.Induction;
8093 
8094   ILV.printDebugTracesAtStart();
8095 
8096   //===------------------------------------------------===//
8097   //
8098   // Notice: any optimization or new instruction that go
8099   // into the code below should also be implemented in
8100   // the cost-model.
8101   //
8102   //===------------------------------------------------===//
8103 
8104   // 2. Copy and widen instructions from the old loop into the new loop.
8105   VPlans.front()->execute(&State);
8106 
8107   // 3. Fix the vectorized code: take care of header phi's, live-outs,
8108   //    predication, updating analyses.
8109   ILV.fixVectorizedLoop(State);
8110 
8111   ILV.printDebugTracesAtEnd();
8112 }
8113 
8114 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
8115 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
8116   for (const auto &Plan : VPlans)
8117     if (PrintVPlansInDotFormat)
8118       Plan->printDOT(O);
8119     else
8120       Plan->print(O);
8121 }
8122 #endif
8123 
8124 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
8125     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
8126 
8127   // We create new control-flow for the vectorized loop, so the original exit
8128   // conditions will be dead after vectorization if it's only used by the
8129   // terminator
8130   SmallVector<BasicBlock*> ExitingBlocks;
8131   OrigLoop->getExitingBlocks(ExitingBlocks);
8132   for (auto *BB : ExitingBlocks) {
8133     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
8134     if (!Cmp || !Cmp->hasOneUse())
8135       continue;
8136 
8137     // TODO: we should introduce a getUniqueExitingBlocks on Loop
8138     if (!DeadInstructions.insert(Cmp).second)
8139       continue;
8140 
8141     // The operands of the icmp is often a dead trunc, used by IndUpdate.
8142     // TODO: can recurse through operands in general
8143     for (Value *Op : Cmp->operands()) {
8144       if (isa<TruncInst>(Op) && Op->hasOneUse())
8145           DeadInstructions.insert(cast<Instruction>(Op));
8146     }
8147   }
8148 
8149   // We create new "steps" for induction variable updates to which the original
8150   // induction variables map. An original update instruction will be dead if
8151   // all its users except the induction variable are dead.
8152   auto *Latch = OrigLoop->getLoopLatch();
8153   for (auto &Induction : Legal->getInductionVars()) {
8154     PHINode *Ind = Induction.first;
8155     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8156 
8157     // If the tail is to be folded by masking, the primary induction variable,
8158     // if exists, isn't dead: it will be used for masking. Don't kill it.
8159     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8160       continue;
8161 
8162     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8163           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8164         }))
8165       DeadInstructions.insert(IndUpdate);
8166 
8167     // We record as "Dead" also the type-casting instructions we had identified
8168     // during induction analysis. We don't need any handling for them in the
8169     // vectorized loop because we have proven that, under a proper runtime
8170     // test guarding the vectorized loop, the value of the phi, and the casted
8171     // value of the phi, are the same. The last instruction in this casting chain
8172     // will get its scalar/vector/widened def from the scalar/vector/widened def
8173     // of the respective phi node. Any other casts in the induction def-use chain
8174     // have no other uses outside the phi update chain, and will be ignored.
8175     InductionDescriptor &IndDes = Induction.second;
8176     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8177     DeadInstructions.insert(Casts.begin(), Casts.end());
8178   }
8179 }
8180 
8181 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
8182 
8183 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8184 
8185 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
8186                                         Instruction::BinaryOps BinOp) {
8187   // When unrolling and the VF is 1, we only need to add a simple scalar.
8188   Type *Ty = Val->getType();
8189   assert(!Ty->isVectorTy() && "Val must be a scalar");
8190 
8191   if (Ty->isFloatingPointTy()) {
8192     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
8193 
8194     // Floating-point operations inherit FMF via the builder's flags.
8195     Value *MulOp = Builder.CreateFMul(C, Step);
8196     return Builder.CreateBinOp(BinOp, Val, MulOp);
8197   }
8198   Constant *C = ConstantInt::get(Ty, StartIdx);
8199   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
8200 }
8201 
8202 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8203   SmallVector<Metadata *, 4> MDs;
8204   // Reserve first location for self reference to the LoopID metadata node.
8205   MDs.push_back(nullptr);
8206   bool IsUnrollMetadata = false;
8207   MDNode *LoopID = L->getLoopID();
8208   if (LoopID) {
8209     // First find existing loop unrolling disable metadata.
8210     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8211       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8212       if (MD) {
8213         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8214         IsUnrollMetadata =
8215             S && S->getString().startswith("llvm.loop.unroll.disable");
8216       }
8217       MDs.push_back(LoopID->getOperand(i));
8218     }
8219   }
8220 
8221   if (!IsUnrollMetadata) {
8222     // Add runtime unroll disable metadata.
8223     LLVMContext &Context = L->getHeader()->getContext();
8224     SmallVector<Metadata *, 1> DisableOperands;
8225     DisableOperands.push_back(
8226         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8227     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8228     MDs.push_back(DisableNode);
8229     MDNode *NewLoopID = MDNode::get(Context, MDs);
8230     // Set operand 0 to refer to the loop id itself.
8231     NewLoopID->replaceOperandWith(0, NewLoopID);
8232     L->setLoopID(NewLoopID);
8233   }
8234 }
8235 
8236 //===--------------------------------------------------------------------===//
8237 // EpilogueVectorizerMainLoop
8238 //===--------------------------------------------------------------------===//
8239 
8240 /// This function is partially responsible for generating the control flow
8241 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8242 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8243   MDNode *OrigLoopID = OrigLoop->getLoopID();
8244   Loop *Lp = createVectorLoopSkeleton("");
8245 
8246   // Generate the code to check the minimum iteration count of the vector
8247   // epilogue (see below).
8248   EPI.EpilogueIterationCountCheck =
8249       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8250   EPI.EpilogueIterationCountCheck->setName("iter.check");
8251 
8252   // Generate the code to check any assumptions that we've made for SCEV
8253   // expressions.
8254   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8255 
8256   // Generate the code that checks at runtime if arrays overlap. We put the
8257   // checks into a separate block to make the more common case of few elements
8258   // faster.
8259   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8260 
8261   // Generate the iteration count check for the main loop, *after* the check
8262   // for the epilogue loop, so that the path-length is shorter for the case
8263   // that goes directly through the vector epilogue. The longer-path length for
8264   // the main loop is compensated for, by the gain from vectorizing the larger
8265   // trip count. Note: the branch will get updated later on when we vectorize
8266   // the epilogue.
8267   EPI.MainLoopIterationCountCheck =
8268       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8269 
8270   // Generate the induction variable.
8271   OldInduction = Legal->getPrimaryInduction();
8272   Type *IdxTy = Legal->getWidestInductionType();
8273   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8274   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8275   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8276   EPI.VectorTripCount = CountRoundDown;
8277   Induction =
8278       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8279                               getDebugLocFromInstOrOperands(OldInduction));
8280 
8281   // Skip induction resume value creation here because they will be created in
8282   // the second pass. If we created them here, they wouldn't be used anyway,
8283   // because the vplan in the second pass still contains the inductions from the
8284   // original loop.
8285 
8286   return completeLoopSkeleton(Lp, OrigLoopID);
8287 }
8288 
8289 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8290   LLVM_DEBUG({
8291     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8292            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
8293            << ", Main Loop UF:" << EPI.MainLoopUF
8294            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8295            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8296   });
8297 }
8298 
8299 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8300   DEBUG_WITH_TYPE(VerboseDebug, {
8301     dbgs() << "intermediate fn:\n" << *Induction->getFunction() << "\n";
8302   });
8303 }
8304 
8305 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8306     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8307   assert(L && "Expected valid Loop.");
8308   assert(Bypass && "Expected valid bypass basic block.");
8309   unsigned VFactor =
8310       ForEpilogue ? EPI.EpilogueVF.getKnownMinValue() : VF.getKnownMinValue();
8311   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8312   Value *Count = getOrCreateTripCount(L);
8313   // Reuse existing vector loop preheader for TC checks.
8314   // Note that new preheader block is generated for vector loop.
8315   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8316   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8317 
8318   // Generate code to check if the loop's trip count is less than VF * UF of the
8319   // main vector loop.
8320   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
8321       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8322 
8323   Value *CheckMinIters = Builder.CreateICmp(
8324       P, Count, ConstantInt::get(Count->getType(), VFactor * UFactor),
8325       "min.iters.check");
8326 
8327   if (!ForEpilogue)
8328     TCCheckBlock->setName("vector.main.loop.iter.check");
8329 
8330   // Create new preheader for vector loop.
8331   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8332                                    DT, LI, nullptr, "vector.ph");
8333 
8334   if (ForEpilogue) {
8335     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8336                                  DT->getNode(Bypass)->getIDom()) &&
8337            "TC check is expected to dominate Bypass");
8338 
8339     // Update dominator for Bypass & LoopExit.
8340     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8341     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8342 
8343     LoopBypassBlocks.push_back(TCCheckBlock);
8344 
8345     // Save the trip count so we don't have to regenerate it in the
8346     // vec.epilog.iter.check. This is safe to do because the trip count
8347     // generated here dominates the vector epilog iter check.
8348     EPI.TripCount = Count;
8349   }
8350 
8351   ReplaceInstWithInst(
8352       TCCheckBlock->getTerminator(),
8353       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8354 
8355   return TCCheckBlock;
8356 }
8357 
8358 //===--------------------------------------------------------------------===//
8359 // EpilogueVectorizerEpilogueLoop
8360 //===--------------------------------------------------------------------===//
8361 
8362 /// This function is partially responsible for generating the control flow
8363 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8364 BasicBlock *
8365 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8366   MDNode *OrigLoopID = OrigLoop->getLoopID();
8367   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8368 
8369   // Now, compare the remaining count and if there aren't enough iterations to
8370   // execute the vectorized epilogue skip to the scalar part.
8371   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8372   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8373   LoopVectorPreHeader =
8374       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8375                  LI, nullptr, "vec.epilog.ph");
8376   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8377                                           VecEpilogueIterationCountCheck);
8378 
8379   // Adjust the control flow taking the state info from the main loop
8380   // vectorization into account.
8381   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8382          "expected this to be saved from the previous pass.");
8383   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8384       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8385 
8386   DT->changeImmediateDominator(LoopVectorPreHeader,
8387                                EPI.MainLoopIterationCountCheck);
8388 
8389   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8390       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8391 
8392   if (EPI.SCEVSafetyCheck)
8393     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8394         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8395   if (EPI.MemSafetyCheck)
8396     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8397         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8398 
8399   DT->changeImmediateDominator(
8400       VecEpilogueIterationCountCheck,
8401       VecEpilogueIterationCountCheck->getSinglePredecessor());
8402 
8403   DT->changeImmediateDominator(LoopScalarPreHeader,
8404                                EPI.EpilogueIterationCountCheck);
8405   DT->changeImmediateDominator(LoopExitBlock, EPI.EpilogueIterationCountCheck);
8406 
8407   // Keep track of bypass blocks, as they feed start values to the induction
8408   // phis in the scalar loop preheader.
8409   if (EPI.SCEVSafetyCheck)
8410     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8411   if (EPI.MemSafetyCheck)
8412     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8413   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8414 
8415   // Generate a resume induction for the vector epilogue and put it in the
8416   // vector epilogue preheader
8417   Type *IdxTy = Legal->getWidestInductionType();
8418   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8419                                          LoopVectorPreHeader->getFirstNonPHI());
8420   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8421   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8422                            EPI.MainLoopIterationCountCheck);
8423 
8424   // Generate the induction variable.
8425   OldInduction = Legal->getPrimaryInduction();
8426   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8427   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8428   Value *StartIdx = EPResumeVal;
8429   Induction =
8430       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8431                               getDebugLocFromInstOrOperands(OldInduction));
8432 
8433   // Generate induction resume values. These variables save the new starting
8434   // indexes for the scalar loop. They are used to test if there are any tail
8435   // iterations left once the vector loop has completed.
8436   // Note that when the vectorized epilogue is skipped due to iteration count
8437   // check, then the resume value for the induction variable comes from
8438   // the trip count of the main vector loop, hence passing the AdditionalBypass
8439   // argument.
8440   createInductionResumeValues(Lp, CountRoundDown,
8441                               {VecEpilogueIterationCountCheck,
8442                                EPI.VectorTripCount} /* AdditionalBypass */);
8443 
8444   AddRuntimeUnrollDisableMetaData(Lp);
8445   return completeLoopSkeleton(Lp, OrigLoopID);
8446 }
8447 
8448 BasicBlock *
8449 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8450     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8451 
8452   assert(EPI.TripCount &&
8453          "Expected trip count to have been safed in the first pass.");
8454   assert(
8455       (!isa<Instruction>(EPI.TripCount) ||
8456        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8457       "saved trip count does not dominate insertion point.");
8458   Value *TC = EPI.TripCount;
8459   IRBuilder<> Builder(Insert->getTerminator());
8460   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8461 
8462   // Generate code to check if the loop's trip count is less than VF * UF of the
8463   // vector epilogue loop.
8464   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
8465       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8466 
8467   Value *CheckMinIters = Builder.CreateICmp(
8468       P, Count,
8469       ConstantInt::get(Count->getType(),
8470                        EPI.EpilogueVF.getKnownMinValue() * EPI.EpilogueUF),
8471       "min.epilog.iters.check");
8472 
8473   ReplaceInstWithInst(
8474       Insert->getTerminator(),
8475       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8476 
8477   LoopBypassBlocks.push_back(Insert);
8478   return Insert;
8479 }
8480 
8481 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8482   LLVM_DEBUG({
8483     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8484            << "Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8485            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8486   });
8487 }
8488 
8489 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8490   DEBUG_WITH_TYPE(VerboseDebug, {
8491     dbgs() << "final fn:\n" << *Induction->getFunction() << "\n";
8492   });
8493 }
8494 
8495 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8496     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8497   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8498   bool PredicateAtRangeStart = Predicate(Range.Start);
8499 
8500   for (ElementCount TmpVF = Range.Start * 2;
8501        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8502     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8503       Range.End = TmpVF;
8504       break;
8505     }
8506 
8507   return PredicateAtRangeStart;
8508 }
8509 
8510 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8511 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8512 /// of VF's starting at a given VF and extending it as much as possible. Each
8513 /// vectorization decision can potentially shorten this sub-range during
8514 /// buildVPlan().
8515 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8516                                            ElementCount MaxVF) {
8517   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8518   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8519     VFRange SubRange = {VF, MaxVFPlusOne};
8520     VPlans.push_back(buildVPlan(SubRange));
8521     VF = SubRange.End;
8522   }
8523 }
8524 
8525 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8526                                          VPlanPtr &Plan) {
8527   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8528 
8529   // Look for cached value.
8530   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8531   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8532   if (ECEntryIt != EdgeMaskCache.end())
8533     return ECEntryIt->second;
8534 
8535   VPValue *SrcMask = createBlockInMask(Src, Plan);
8536 
8537   // The terminator has to be a branch inst!
8538   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8539   assert(BI && "Unexpected terminator found");
8540 
8541   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8542     return EdgeMaskCache[Edge] = SrcMask;
8543 
8544   // If source is an exiting block, we know the exit edge is dynamically dead
8545   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8546   // adding uses of an otherwise potentially dead instruction.
8547   if (OrigLoop->isLoopExiting(Src))
8548     return EdgeMaskCache[Edge] = SrcMask;
8549 
8550   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8551   assert(EdgeMask && "No Edge Mask found for condition");
8552 
8553   if (BI->getSuccessor(0) != Dst)
8554     EdgeMask = Builder.createNot(EdgeMask);
8555 
8556   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8557     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8558     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8559     // The select version does not introduce new UB if SrcMask is false and
8560     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8561     VPValue *False = Plan->getOrAddVPValue(
8562         ConstantInt::getFalse(BI->getCondition()->getType()));
8563     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8564   }
8565 
8566   return EdgeMaskCache[Edge] = EdgeMask;
8567 }
8568 
8569 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8570   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8571 
8572   // Look for cached value.
8573   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8574   if (BCEntryIt != BlockMaskCache.end())
8575     return BCEntryIt->second;
8576 
8577   // All-one mask is modelled as no-mask following the convention for masked
8578   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8579   VPValue *BlockMask = nullptr;
8580 
8581   if (OrigLoop->getHeader() == BB) {
8582     if (!CM.blockNeedsPredication(BB))
8583       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8584 
8585     // Create the block in mask as the first non-phi instruction in the block.
8586     VPBuilder::InsertPointGuard Guard(Builder);
8587     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8588     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8589 
8590     // Introduce the early-exit compare IV <= BTC to form header block mask.
8591     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8592     // Start by constructing the desired canonical IV.
8593     VPValue *IV = nullptr;
8594     if (Legal->getPrimaryInduction())
8595       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8596     else {
8597       auto IVRecipe = new VPWidenCanonicalIVRecipe();
8598       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8599       IV = IVRecipe->getVPSingleValue();
8600     }
8601     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8602     bool TailFolded = !CM.isScalarEpilogueAllowed();
8603 
8604     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8605       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8606       // as a second argument, we only pass the IV here and extract the
8607       // tripcount from the transform state where codegen of the VP instructions
8608       // happen.
8609       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8610     } else {
8611       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8612     }
8613     return BlockMaskCache[BB] = BlockMask;
8614   }
8615 
8616   // This is the block mask. We OR all incoming edges.
8617   for (auto *Predecessor : predecessors(BB)) {
8618     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8619     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8620       return BlockMaskCache[BB] = EdgeMask;
8621 
8622     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8623       BlockMask = EdgeMask;
8624       continue;
8625     }
8626 
8627     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8628   }
8629 
8630   return BlockMaskCache[BB] = BlockMask;
8631 }
8632 
8633 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8634                                                 ArrayRef<VPValue *> Operands,
8635                                                 VFRange &Range,
8636                                                 VPlanPtr &Plan) {
8637   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8638          "Must be called with either a load or store");
8639 
8640   auto willWiden = [&](ElementCount VF) -> bool {
8641     if (VF.isScalar())
8642       return false;
8643     LoopVectorizationCostModel::InstWidening Decision =
8644         CM.getWideningDecision(I, VF);
8645     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8646            "CM decision should be taken at this point.");
8647     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8648       return true;
8649     if (CM.isScalarAfterVectorization(I, VF) ||
8650         CM.isProfitableToScalarize(I, VF))
8651       return false;
8652     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8653   };
8654 
8655   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8656     return nullptr;
8657 
8658   VPValue *Mask = nullptr;
8659   if (Legal->isMaskRequired(I))
8660     Mask = createBlockInMask(I->getParent(), Plan);
8661 
8662   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8663     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask);
8664 
8665   StoreInst *Store = cast<StoreInst>(I);
8666   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8667                                             Mask);
8668 }
8669 
8670 VPWidenIntOrFpInductionRecipe *
8671 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8672                                            ArrayRef<VPValue *> Operands) const {
8673   // Check if this is an integer or fp induction. If so, build the recipe that
8674   // produces its scalar and vector values.
8675   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8676   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8677       II.getKind() == InductionDescriptor::IK_FpInduction) {
8678     assert(II.getStartValue() ==
8679            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8680     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8681     return new VPWidenIntOrFpInductionRecipe(
8682         Phi, Operands[0], Casts.empty() ? nullptr : Casts.front());
8683   }
8684 
8685   return nullptr;
8686 }
8687 
8688 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8689     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8690     VPlan &Plan) const {
8691   // Optimize the special case where the source is a constant integer
8692   // induction variable. Notice that we can only optimize the 'trunc' case
8693   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8694   // (c) other casts depend on pointer size.
8695 
8696   // Determine whether \p K is a truncation based on an induction variable that
8697   // can be optimized.
8698   auto isOptimizableIVTruncate =
8699       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8700     return [=](ElementCount VF) -> bool {
8701       return CM.isOptimizableIVTruncate(K, VF);
8702     };
8703   };
8704 
8705   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8706           isOptimizableIVTruncate(I), Range)) {
8707 
8708     InductionDescriptor II =
8709         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8710     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8711     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8712                                              Start, nullptr, I);
8713   }
8714   return nullptr;
8715 }
8716 
8717 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8718                                                 ArrayRef<VPValue *> Operands,
8719                                                 VPlanPtr &Plan) {
8720   // If all incoming values are equal, the incoming VPValue can be used directly
8721   // instead of creating a new VPBlendRecipe.
8722   VPValue *FirstIncoming = Operands[0];
8723   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8724         return FirstIncoming == Inc;
8725       })) {
8726     return Operands[0];
8727   }
8728 
8729   // We know that all PHIs in non-header blocks are converted into selects, so
8730   // we don't have to worry about the insertion order and we can just use the
8731   // builder. At this point we generate the predication tree. There may be
8732   // duplications since this is a simple recursive scan, but future
8733   // optimizations will clean it up.
8734   SmallVector<VPValue *, 2> OperandsWithMask;
8735   unsigned NumIncoming = Phi->getNumIncomingValues();
8736 
8737   for (unsigned In = 0; In < NumIncoming; In++) {
8738     VPValue *EdgeMask =
8739       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8740     assert((EdgeMask || NumIncoming == 1) &&
8741            "Multiple predecessors with one having a full mask");
8742     OperandsWithMask.push_back(Operands[In]);
8743     if (EdgeMask)
8744       OperandsWithMask.push_back(EdgeMask);
8745   }
8746   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8747 }
8748 
8749 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8750                                                    ArrayRef<VPValue *> Operands,
8751                                                    VFRange &Range) const {
8752 
8753   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8754       [this, CI](ElementCount VF) { return CM.isScalarWithPredication(CI); },
8755       Range);
8756 
8757   if (IsPredicated)
8758     return nullptr;
8759 
8760   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8761   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8762              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8763              ID == Intrinsic::pseudoprobe ||
8764              ID == Intrinsic::experimental_noalias_scope_decl))
8765     return nullptr;
8766 
8767   auto willWiden = [&](ElementCount VF) -> bool {
8768     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8769     // The following case may be scalarized depending on the VF.
8770     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8771     // version of the instruction.
8772     // Is it beneficial to perform intrinsic call compared to lib call?
8773     bool NeedToScalarize = false;
8774     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8775     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8776     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8777     assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
8778            "Either the intrinsic cost or vector call cost must be valid");
8779     return UseVectorIntrinsic || !NeedToScalarize;
8780   };
8781 
8782   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8783     return nullptr;
8784 
8785   ArrayRef<VPValue *> Ops = Operands.take_front(CI->getNumArgOperands());
8786   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8787 }
8788 
8789 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8790   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8791          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8792   // Instruction should be widened, unless it is scalar after vectorization,
8793   // scalarization is profitable or it is predicated.
8794   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8795     return CM.isScalarAfterVectorization(I, VF) ||
8796            CM.isProfitableToScalarize(I, VF) || CM.isScalarWithPredication(I);
8797   };
8798   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8799                                                              Range);
8800 }
8801 
8802 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8803                                            ArrayRef<VPValue *> Operands) const {
8804   auto IsVectorizableOpcode = [](unsigned Opcode) {
8805     switch (Opcode) {
8806     case Instruction::Add:
8807     case Instruction::And:
8808     case Instruction::AShr:
8809     case Instruction::BitCast:
8810     case Instruction::FAdd:
8811     case Instruction::FCmp:
8812     case Instruction::FDiv:
8813     case Instruction::FMul:
8814     case Instruction::FNeg:
8815     case Instruction::FPExt:
8816     case Instruction::FPToSI:
8817     case Instruction::FPToUI:
8818     case Instruction::FPTrunc:
8819     case Instruction::FRem:
8820     case Instruction::FSub:
8821     case Instruction::ICmp:
8822     case Instruction::IntToPtr:
8823     case Instruction::LShr:
8824     case Instruction::Mul:
8825     case Instruction::Or:
8826     case Instruction::PtrToInt:
8827     case Instruction::SDiv:
8828     case Instruction::Select:
8829     case Instruction::SExt:
8830     case Instruction::Shl:
8831     case Instruction::SIToFP:
8832     case Instruction::SRem:
8833     case Instruction::Sub:
8834     case Instruction::Trunc:
8835     case Instruction::UDiv:
8836     case Instruction::UIToFP:
8837     case Instruction::URem:
8838     case Instruction::Xor:
8839     case Instruction::ZExt:
8840       return true;
8841     }
8842     return false;
8843   };
8844 
8845   if (!IsVectorizableOpcode(I->getOpcode()))
8846     return nullptr;
8847 
8848   // Success: widen this instruction.
8849   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8850 }
8851 
8852 void VPRecipeBuilder::fixHeaderPhis() {
8853   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8854   for (VPWidenPHIRecipe *R : PhisToFix) {
8855     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8856     VPRecipeBase *IncR =
8857         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8858     R->addOperand(IncR->getVPSingleValue());
8859   }
8860 }
8861 
8862 VPBasicBlock *VPRecipeBuilder::handleReplication(
8863     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8864     VPlanPtr &Plan) {
8865   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8866       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8867       Range);
8868 
8869   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8870       [&](ElementCount VF) { return CM.isPredicatedInst(I); }, Range);
8871 
8872   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8873                                        IsUniform, IsPredicated);
8874   setRecipe(I, Recipe);
8875   Plan->addVPValue(I, Recipe);
8876 
8877   // Find if I uses a predicated instruction. If so, it will use its scalar
8878   // value. Avoid hoisting the insert-element which packs the scalar value into
8879   // a vector value, as that happens iff all users use the vector value.
8880   for (VPValue *Op : Recipe->operands()) {
8881     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8882     if (!PredR)
8883       continue;
8884     auto *RepR =
8885         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8886     assert(RepR->isPredicated() &&
8887            "expected Replicate recipe to be predicated");
8888     RepR->setAlsoPack(false);
8889   }
8890 
8891   // Finalize the recipe for Instr, first if it is not predicated.
8892   if (!IsPredicated) {
8893     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8894     VPBB->appendRecipe(Recipe);
8895     return VPBB;
8896   }
8897   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8898   assert(VPBB->getSuccessors().empty() &&
8899          "VPBB has successors when handling predicated replication.");
8900   // Record predicated instructions for above packing optimizations.
8901   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8902   VPBlockUtils::insertBlockAfter(Region, VPBB);
8903   auto *RegSucc = new VPBasicBlock();
8904   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8905   return RegSucc;
8906 }
8907 
8908 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8909                                                       VPRecipeBase *PredRecipe,
8910                                                       VPlanPtr &Plan) {
8911   // Instructions marked for predication are replicated and placed under an
8912   // if-then construct to prevent side-effects.
8913 
8914   // Generate recipes to compute the block mask for this region.
8915   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8916 
8917   // Build the triangular if-then region.
8918   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8919   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8920   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8921   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8922   auto *PHIRecipe = Instr->getType()->isVoidTy()
8923                         ? nullptr
8924                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8925   if (PHIRecipe) {
8926     Plan->removeVPValueFor(Instr);
8927     Plan->addVPValue(Instr, PHIRecipe);
8928   }
8929   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8930   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8931   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8932 
8933   // Note: first set Entry as region entry and then connect successors starting
8934   // from it in order, to propagate the "parent" of each VPBasicBlock.
8935   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8936   VPBlockUtils::connectBlocks(Pred, Exit);
8937 
8938   return Region;
8939 }
8940 
8941 VPRecipeOrVPValueTy
8942 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8943                                         ArrayRef<VPValue *> Operands,
8944                                         VFRange &Range, VPlanPtr &Plan) {
8945   // First, check for specific widening recipes that deal with calls, memory
8946   // operations, inductions and Phi nodes.
8947   if (auto *CI = dyn_cast<CallInst>(Instr))
8948     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8949 
8950   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8951     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8952 
8953   VPRecipeBase *Recipe;
8954   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8955     if (Phi->getParent() != OrigLoop->getHeader())
8956       return tryToBlend(Phi, Operands, Plan);
8957     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
8958       return toVPRecipeResult(Recipe);
8959 
8960     VPWidenPHIRecipe *PhiRecipe = nullptr;
8961     if (Legal->isReductionVariable(Phi) || Legal->isFirstOrderRecurrence(Phi)) {
8962       VPValue *StartV = Operands[0];
8963       if (Legal->isReductionVariable(Phi)) {
8964         RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
8965         assert(RdxDesc.getRecurrenceStartValue() ==
8966                Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8967         PhiRecipe = new VPWidenPHIRecipe(Phi, RdxDesc, *StartV);
8968       } else {
8969         PhiRecipe = new VPWidenPHIRecipe(Phi, *StartV);
8970       }
8971 
8972       // Record the incoming value from the backedge, so we can add the incoming
8973       // value from the backedge after all recipes have been created.
8974       recordRecipeOf(cast<Instruction>(
8975           Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8976       PhisToFix.push_back(PhiRecipe);
8977     } else {
8978       // TODO: record start and backedge value for remaining pointer induction
8979       // phis.
8980       assert(Phi->getType()->isPointerTy() &&
8981              "only pointer phis should be handled here");
8982       PhiRecipe = new VPWidenPHIRecipe(Phi);
8983     }
8984 
8985     return toVPRecipeResult(PhiRecipe);
8986   }
8987 
8988   if (isa<TruncInst>(Instr) &&
8989       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8990                                                Range, *Plan)))
8991     return toVPRecipeResult(Recipe);
8992 
8993   if (!shouldWiden(Instr, Range))
8994     return nullptr;
8995 
8996   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8997     return toVPRecipeResult(new VPWidenGEPRecipe(
8998         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8999 
9000   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
9001     bool InvariantCond =
9002         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
9003     return toVPRecipeResult(new VPWidenSelectRecipe(
9004         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
9005   }
9006 
9007   return toVPRecipeResult(tryToWiden(Instr, Operands));
9008 }
9009 
9010 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
9011                                                         ElementCount MaxVF) {
9012   assert(OrigLoop->isInnermost() && "Inner loop expected.");
9013 
9014   // Collect instructions from the original loop that will become trivially dead
9015   // in the vectorized loop. We don't need to vectorize these instructions. For
9016   // example, original induction update instructions can become dead because we
9017   // separately emit induction "steps" when generating code for the new loop.
9018   // Similarly, we create a new latch condition when setting up the structure
9019   // of the new loop, so the old one can become dead.
9020   SmallPtrSet<Instruction *, 4> DeadInstructions;
9021   collectTriviallyDeadInstructions(DeadInstructions);
9022 
9023   // Add assume instructions we need to drop to DeadInstructions, to prevent
9024   // them from being added to the VPlan.
9025   // TODO: We only need to drop assumes in blocks that get flattend. If the
9026   // control flow is preserved, we should keep them.
9027   auto &ConditionalAssumes = Legal->getConditionalAssumes();
9028   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
9029 
9030   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
9031   // Dead instructions do not need sinking. Remove them from SinkAfter.
9032   for (Instruction *I : DeadInstructions)
9033     SinkAfter.erase(I);
9034 
9035   // Cannot sink instructions after dead instructions (there won't be any
9036   // recipes for them). Instead, find the first non-dead previous instruction.
9037   for (auto &P : Legal->getSinkAfter()) {
9038     Instruction *SinkTarget = P.second;
9039     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
9040     (void)FirstInst;
9041     while (DeadInstructions.contains(SinkTarget)) {
9042       assert(
9043           SinkTarget != FirstInst &&
9044           "Must find a live instruction (at least the one feeding the "
9045           "first-order recurrence PHI) before reaching beginning of the block");
9046       SinkTarget = SinkTarget->getPrevNode();
9047       assert(SinkTarget != P.first &&
9048              "sink source equals target, no sinking required");
9049     }
9050     P.second = SinkTarget;
9051   }
9052 
9053   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
9054   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
9055     VFRange SubRange = {VF, MaxVFPlusOne};
9056     VPlans.push_back(
9057         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
9058     VF = SubRange.End;
9059   }
9060 }
9061 
9062 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
9063     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
9064     const MapVector<Instruction *, Instruction *> &SinkAfter) {
9065 
9066   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
9067 
9068   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
9069 
9070   // ---------------------------------------------------------------------------
9071   // Pre-construction: record ingredients whose recipes we'll need to further
9072   // process after constructing the initial VPlan.
9073   // ---------------------------------------------------------------------------
9074 
9075   // Mark instructions we'll need to sink later and their targets as
9076   // ingredients whose recipe we'll need to record.
9077   for (auto &Entry : SinkAfter) {
9078     RecipeBuilder.recordRecipeOf(Entry.first);
9079     RecipeBuilder.recordRecipeOf(Entry.second);
9080   }
9081   for (auto &Reduction : CM.getInLoopReductionChains()) {
9082     PHINode *Phi = Reduction.first;
9083     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
9084     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9085 
9086     RecipeBuilder.recordRecipeOf(Phi);
9087     for (auto &R : ReductionOperations) {
9088       RecipeBuilder.recordRecipeOf(R);
9089       // For min/max reducitons, where we have a pair of icmp/select, we also
9090       // need to record the ICmp recipe, so it can be removed later.
9091       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
9092         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
9093     }
9094   }
9095 
9096   // For each interleave group which is relevant for this (possibly trimmed)
9097   // Range, add it to the set of groups to be later applied to the VPlan and add
9098   // placeholders for its members' Recipes which we'll be replacing with a
9099   // single VPInterleaveRecipe.
9100   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
9101     auto applyIG = [IG, this](ElementCount VF) -> bool {
9102       return (VF.isVector() && // Query is illegal for VF == 1
9103               CM.getWideningDecision(IG->getInsertPos(), VF) ==
9104                   LoopVectorizationCostModel::CM_Interleave);
9105     };
9106     if (!getDecisionAndClampRange(applyIG, Range))
9107       continue;
9108     InterleaveGroups.insert(IG);
9109     for (unsigned i = 0; i < IG->getFactor(); i++)
9110       if (Instruction *Member = IG->getMember(i))
9111         RecipeBuilder.recordRecipeOf(Member);
9112   };
9113 
9114   // ---------------------------------------------------------------------------
9115   // Build initial VPlan: Scan the body of the loop in a topological order to
9116   // visit each basic block after having visited its predecessor basic blocks.
9117   // ---------------------------------------------------------------------------
9118 
9119   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
9120   auto Plan = std::make_unique<VPlan>();
9121   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
9122   Plan->setEntry(VPBB);
9123 
9124   // Scan the body of the loop in a topological order to visit each basic block
9125   // after having visited its predecessor basic blocks.
9126   LoopBlocksDFS DFS(OrigLoop);
9127   DFS.perform(LI);
9128 
9129   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
9130     // Relevant instructions from basic block BB will be grouped into VPRecipe
9131     // ingredients and fill a new VPBasicBlock.
9132     unsigned VPBBsForBB = 0;
9133     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
9134     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
9135     VPBB = FirstVPBBForBB;
9136     Builder.setInsertPoint(VPBB);
9137 
9138     // Introduce each ingredient into VPlan.
9139     // TODO: Model and preserve debug instrinsics in VPlan.
9140     for (Instruction &I : BB->instructionsWithoutDebug()) {
9141       Instruction *Instr = &I;
9142 
9143       // First filter out irrelevant instructions, to ensure no recipes are
9144       // built for them.
9145       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
9146         continue;
9147 
9148       SmallVector<VPValue *, 4> Operands;
9149       auto *Phi = dyn_cast<PHINode>(Instr);
9150       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
9151         Operands.push_back(Plan->getOrAddVPValue(
9152             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
9153       } else {
9154         auto OpRange = Plan->mapToVPValues(Instr->operands());
9155         Operands = {OpRange.begin(), OpRange.end()};
9156       }
9157       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
9158               Instr, Operands, Range, Plan)) {
9159         // If Instr can be simplified to an existing VPValue, use it.
9160         if (RecipeOrValue.is<VPValue *>()) {
9161           auto *VPV = RecipeOrValue.get<VPValue *>();
9162           Plan->addVPValue(Instr, VPV);
9163           // If the re-used value is a recipe, register the recipe for the
9164           // instruction, in case the recipe for Instr needs to be recorded.
9165           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
9166             RecipeBuilder.setRecipe(Instr, R);
9167           continue;
9168         }
9169         // Otherwise, add the new recipe.
9170         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
9171         for (auto *Def : Recipe->definedValues()) {
9172           auto *UV = Def->getUnderlyingValue();
9173           Plan->addVPValue(UV, Def);
9174         }
9175 
9176         RecipeBuilder.setRecipe(Instr, Recipe);
9177         VPBB->appendRecipe(Recipe);
9178         continue;
9179       }
9180 
9181       // Otherwise, if all widening options failed, Instruction is to be
9182       // replicated. This may create a successor for VPBB.
9183       VPBasicBlock *NextVPBB =
9184           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
9185       if (NextVPBB != VPBB) {
9186         VPBB = NextVPBB;
9187         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
9188                                     : "");
9189       }
9190     }
9191   }
9192 
9193   RecipeBuilder.fixHeaderPhis();
9194 
9195   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
9196   // may also be empty, such as the last one VPBB, reflecting original
9197   // basic-blocks with no recipes.
9198   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
9199   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
9200   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
9201   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
9202   delete PreEntry;
9203 
9204   // ---------------------------------------------------------------------------
9205   // Transform initial VPlan: Apply previously taken decisions, in order, to
9206   // bring the VPlan to its final state.
9207   // ---------------------------------------------------------------------------
9208 
9209   // Apply Sink-After legal constraints.
9210   for (auto &Entry : SinkAfter) {
9211     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9212     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9213 
9214     auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
9215       auto *Region =
9216           dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
9217       if (Region && Region->isReplicator()) {
9218         assert(Region->getNumSuccessors() == 1 &&
9219                Region->getNumPredecessors() == 1 && "Expected SESE region!");
9220         assert(R->getParent()->size() == 1 &&
9221                "A recipe in an original replicator region must be the only "
9222                "recipe in its block");
9223         return Region;
9224       }
9225       return nullptr;
9226     };
9227     auto *TargetRegion = GetReplicateRegion(Target);
9228     auto *SinkRegion = GetReplicateRegion(Sink);
9229     if (!SinkRegion) {
9230       // If the sink source is not a replicate region, sink the recipe directly.
9231       if (TargetRegion) {
9232         // The target is in a replication region, make sure to move Sink to
9233         // the block after it, not into the replication region itself.
9234         VPBasicBlock *NextBlock =
9235             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
9236         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9237       } else
9238         Sink->moveAfter(Target);
9239       continue;
9240     }
9241 
9242     // The sink source is in a replicate region. Unhook the region from the CFG.
9243     auto *SinkPred = SinkRegion->getSinglePredecessor();
9244     auto *SinkSucc = SinkRegion->getSingleSuccessor();
9245     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
9246     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
9247     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
9248 
9249     if (TargetRegion) {
9250       // The target recipe is also in a replicate region, move the sink region
9251       // after the target region.
9252       auto *TargetSucc = TargetRegion->getSingleSuccessor();
9253       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
9254       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
9255       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
9256     } else {
9257       // The sink source is in a replicate region, we need to move the whole
9258       // replicate region, which should only contain a single recipe in the main
9259       // block.
9260       auto *SplitBlock =
9261           Target->getParent()->splitAt(std::next(Target->getIterator()));
9262 
9263       auto *SplitPred = SplitBlock->getSinglePredecessor();
9264 
9265       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
9266       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
9267       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
9268       if (VPBB == SplitPred)
9269         VPBB = SplitBlock;
9270     }
9271   }
9272 
9273   // Interleave memory: for each Interleave Group we marked earlier as relevant
9274   // for this VPlan, replace the Recipes widening its memory instructions with a
9275   // single VPInterleaveRecipe at its insertion point.
9276   for (auto IG : InterleaveGroups) {
9277     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9278         RecipeBuilder.getRecipe(IG->getInsertPos()));
9279     SmallVector<VPValue *, 4> StoredValues;
9280     for (unsigned i = 0; i < IG->getFactor(); ++i)
9281       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i)))
9282         StoredValues.push_back(Plan->getOrAddVPValue(SI->getOperand(0)));
9283 
9284     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9285                                         Recipe->getMask());
9286     VPIG->insertBefore(Recipe);
9287     unsigned J = 0;
9288     for (unsigned i = 0; i < IG->getFactor(); ++i)
9289       if (Instruction *Member = IG->getMember(i)) {
9290         if (!Member->getType()->isVoidTy()) {
9291           VPValue *OriginalV = Plan->getVPValue(Member);
9292           Plan->removeVPValueFor(Member);
9293           Plan->addVPValue(Member, VPIG->getVPValue(J));
9294           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9295           J++;
9296         }
9297         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9298       }
9299   }
9300 
9301   // Adjust the recipes for any inloop reductions.
9302   adjustRecipesForInLoopReductions(Plan, RecipeBuilder, Range.Start);
9303 
9304   // Finally, if tail is folded by masking, introduce selects between the phi
9305   // and the live-out instruction of each reduction, at the end of the latch.
9306   if (CM.foldTailByMasking() && !Legal->getReductionVars().empty()) {
9307     Builder.setInsertPoint(VPBB);
9308     auto *Cond = RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9309     for (auto &Reduction : Legal->getReductionVars()) {
9310       if (CM.isInLoopReduction(Reduction.first))
9311         continue;
9312       VPValue *Phi = Plan->getOrAddVPValue(Reduction.first);
9313       VPValue *Red = Plan->getOrAddVPValue(Reduction.second.getLoopExitInstr());
9314       Builder.createNaryOp(Instruction::Select, {Cond, Red, Phi});
9315     }
9316   }
9317 
9318   VPlanTransforms::sinkScalarOperands(*Plan);
9319   VPlanTransforms::mergeReplicateRegions(*Plan);
9320 
9321   std::string PlanName;
9322   raw_string_ostream RSO(PlanName);
9323   ElementCount VF = Range.Start;
9324   Plan->addVF(VF);
9325   RSO << "Initial VPlan for VF={" << VF;
9326   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9327     Plan->addVF(VF);
9328     RSO << "," << VF;
9329   }
9330   RSO << "},UF>=1";
9331   RSO.flush();
9332   Plan->setName(PlanName);
9333 
9334   return Plan;
9335 }
9336 
9337 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9338   // Outer loop handling: They may require CFG and instruction level
9339   // transformations before even evaluating whether vectorization is profitable.
9340   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9341   // the vectorization pipeline.
9342   assert(!OrigLoop->isInnermost());
9343   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9344 
9345   // Create new empty VPlan
9346   auto Plan = std::make_unique<VPlan>();
9347 
9348   // Build hierarchical CFG
9349   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9350   HCFGBuilder.buildHierarchicalCFG();
9351 
9352   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9353        VF *= 2)
9354     Plan->addVF(VF);
9355 
9356   if (EnableVPlanPredication) {
9357     VPlanPredicator VPP(*Plan);
9358     VPP.predicate();
9359 
9360     // Avoid running transformation to recipes until masked code generation in
9361     // VPlan-native path is in place.
9362     return Plan;
9363   }
9364 
9365   SmallPtrSet<Instruction *, 1> DeadInstructions;
9366   VPlanTransforms::VPInstructionsToVPRecipes(OrigLoop, Plan,
9367                                              Legal->getInductionVars(),
9368                                              DeadInstructions, *PSE.getSE());
9369   return Plan;
9370 }
9371 
9372 // Adjust the recipes for any inloop reductions. The chain of instructions
9373 // leading from the loop exit instr to the phi need to be converted to
9374 // reductions, with one operand being vector and the other being the scalar
9375 // reduction chain.
9376 void LoopVectorizationPlanner::adjustRecipesForInLoopReductions(
9377     VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder, ElementCount MinVF) {
9378   for (auto &Reduction : CM.getInLoopReductionChains()) {
9379     PHINode *Phi = Reduction.first;
9380     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9381     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9382 
9383     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9384       continue;
9385 
9386     // ReductionOperations are orders top-down from the phi's use to the
9387     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9388     // which of the two operands will remain scalar and which will be reduced.
9389     // For minmax the chain will be the select instructions.
9390     Instruction *Chain = Phi;
9391     for (Instruction *R : ReductionOperations) {
9392       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9393       RecurKind Kind = RdxDesc.getRecurrenceKind();
9394 
9395       VPValue *ChainOp = Plan->getVPValue(Chain);
9396       unsigned FirstOpId;
9397       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9398         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9399                "Expected to replace a VPWidenSelectSC");
9400         FirstOpId = 1;
9401       } else {
9402         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe)) &&
9403                "Expected to replace a VPWidenSC");
9404         FirstOpId = 0;
9405       }
9406       unsigned VecOpId =
9407           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9408       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9409 
9410       auto *CondOp = CM.foldTailByMasking()
9411                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9412                          : nullptr;
9413       VPReductionRecipe *RedRecipe = new VPReductionRecipe(
9414           &RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9415       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9416       Plan->removeVPValueFor(R);
9417       Plan->addVPValue(R, RedRecipe);
9418       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9419       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9420       WidenRecipe->eraseFromParent();
9421 
9422       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9423         VPRecipeBase *CompareRecipe =
9424             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9425         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9426                "Expected to replace a VPWidenSC");
9427         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9428                "Expected no remaining users");
9429         CompareRecipe->eraseFromParent();
9430       }
9431       Chain = R;
9432     }
9433   }
9434 }
9435 
9436 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9437 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9438                                VPSlotTracker &SlotTracker) const {
9439   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9440   IG->getInsertPos()->printAsOperand(O, false);
9441   O << ", ";
9442   getAddr()->printAsOperand(O, SlotTracker);
9443   VPValue *Mask = getMask();
9444   if (Mask) {
9445     O << ", ";
9446     Mask->printAsOperand(O, SlotTracker);
9447   }
9448   for (unsigned i = 0; i < IG->getFactor(); ++i)
9449     if (Instruction *I = IG->getMember(i))
9450       O << "\n" << Indent << "  " << VPlanIngredient(I) << " " << i;
9451 }
9452 #endif
9453 
9454 void VPWidenCallRecipe::execute(VPTransformState &State) {
9455   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9456                                   *this, State);
9457 }
9458 
9459 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9460   State.ILV->widenSelectInstruction(*cast<SelectInst>(getUnderlyingInstr()),
9461                                     this, *this, InvariantCond, State);
9462 }
9463 
9464 void VPWidenRecipe::execute(VPTransformState &State) {
9465   State.ILV->widenInstruction(*getUnderlyingInstr(), this, *this, State);
9466 }
9467 
9468 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9469   State.ILV->widenGEP(cast<GetElementPtrInst>(getUnderlyingInstr()), this,
9470                       *this, State.UF, State.VF, IsPtrLoopInvariant,
9471                       IsIndexLoopInvariant, State);
9472 }
9473 
9474 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9475   assert(!State.Instance && "Int or FP induction being replicated.");
9476   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9477                                    getTruncInst(), getVPValue(0),
9478                                    getCastValue(), State);
9479 }
9480 
9481 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9482   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), RdxDesc,
9483                                  this, State);
9484 }
9485 
9486 void VPBlendRecipe::execute(VPTransformState &State) {
9487   State.ILV->setDebugLocFromInst(State.Builder, Phi);
9488   // We know that all PHIs in non-header blocks are converted into
9489   // selects, so we don't have to worry about the insertion order and we
9490   // can just use the builder.
9491   // At this point we generate the predication tree. There may be
9492   // duplications since this is a simple recursive scan, but future
9493   // optimizations will clean it up.
9494 
9495   unsigned NumIncoming = getNumIncomingValues();
9496 
9497   // Generate a sequence of selects of the form:
9498   // SELECT(Mask3, In3,
9499   //        SELECT(Mask2, In2,
9500   //               SELECT(Mask1, In1,
9501   //                      In0)))
9502   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9503   // are essentially undef are taken from In0.
9504   InnerLoopVectorizer::VectorParts Entry(State.UF);
9505   for (unsigned In = 0; In < NumIncoming; ++In) {
9506     for (unsigned Part = 0; Part < State.UF; ++Part) {
9507       // We might have single edge PHIs (blocks) - use an identity
9508       // 'select' for the first PHI operand.
9509       Value *In0 = State.get(getIncomingValue(In), Part);
9510       if (In == 0)
9511         Entry[Part] = In0; // Initialize with the first incoming value.
9512       else {
9513         // Select between the current value and the previous incoming edge
9514         // based on the incoming mask.
9515         Value *Cond = State.get(getMask(In), Part);
9516         Entry[Part] =
9517             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9518       }
9519     }
9520   }
9521   for (unsigned Part = 0; Part < State.UF; ++Part)
9522     State.set(this, Entry[Part], Part);
9523 }
9524 
9525 void VPInterleaveRecipe::execute(VPTransformState &State) {
9526   assert(!State.Instance && "Interleave group being replicated.");
9527   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9528                                       getStoredValues(), getMask());
9529 }
9530 
9531 void VPReductionRecipe::execute(VPTransformState &State) {
9532   assert(!State.Instance && "Reduction being replicated.");
9533   Value *PrevInChain = State.get(getChainOp(), 0);
9534   for (unsigned Part = 0; Part < State.UF; ++Part) {
9535     RecurKind Kind = RdxDesc->getRecurrenceKind();
9536     bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9537     Value *NewVecOp = State.get(getVecOp(), Part);
9538     if (VPValue *Cond = getCondOp()) {
9539       Value *NewCond = State.get(Cond, Part);
9540       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9541       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
9542           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9543       Constant *IdenVec =
9544           ConstantVector::getSplat(VecTy->getElementCount(), Iden);
9545       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9546       NewVecOp = Select;
9547     }
9548     Value *NewRed;
9549     Value *NextInChain;
9550     if (IsOrdered) {
9551       if (State.VF.isVector())
9552         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9553                                         PrevInChain);
9554       else
9555         NewRed = State.Builder.CreateBinOp(
9556             (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(),
9557             PrevInChain, NewVecOp);
9558       PrevInChain = NewRed;
9559     } else {
9560       PrevInChain = State.get(getChainOp(), Part);
9561       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9562     }
9563     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9564       NextInChain =
9565           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9566                          NewRed, PrevInChain);
9567     } else if (IsOrdered)
9568       NextInChain = NewRed;
9569     else {
9570       NextInChain = State.Builder.CreateBinOp(
9571           (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(), NewRed,
9572           PrevInChain);
9573     }
9574     State.set(this, NextInChain, Part);
9575   }
9576 }
9577 
9578 void VPReplicateRecipe::execute(VPTransformState &State) {
9579   if (State.Instance) { // Generate a single instance.
9580     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9581     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9582                                     *State.Instance, IsPredicated, State);
9583     // Insert scalar instance packing it into a vector.
9584     if (AlsoPack && State.VF.isVector()) {
9585       // If we're constructing lane 0, initialize to start from poison.
9586       if (State.Instance->Lane.isFirstLane()) {
9587         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9588         Value *Poison = PoisonValue::get(
9589             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9590         State.set(this, Poison, State.Instance->Part);
9591       }
9592       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9593     }
9594     return;
9595   }
9596 
9597   // Generate scalar instances for all VF lanes of all UF parts, unless the
9598   // instruction is uniform inwhich case generate only the first lane for each
9599   // of the UF parts.
9600   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9601   assert((!State.VF.isScalable() || IsUniform) &&
9602          "Can't scalarize a scalable vector");
9603   for (unsigned Part = 0; Part < State.UF; ++Part)
9604     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9605       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9606                                       VPIteration(Part, Lane), IsPredicated,
9607                                       State);
9608 }
9609 
9610 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9611   assert(State.Instance && "Branch on Mask works only on single instance.");
9612 
9613   unsigned Part = State.Instance->Part;
9614   unsigned Lane = State.Instance->Lane.getKnownLane();
9615 
9616   Value *ConditionBit = nullptr;
9617   VPValue *BlockInMask = getMask();
9618   if (BlockInMask) {
9619     ConditionBit = State.get(BlockInMask, Part);
9620     if (ConditionBit->getType()->isVectorTy())
9621       ConditionBit = State.Builder.CreateExtractElement(
9622           ConditionBit, State.Builder.getInt32(Lane));
9623   } else // Block in mask is all-one.
9624     ConditionBit = State.Builder.getTrue();
9625 
9626   // Replace the temporary unreachable terminator with a new conditional branch,
9627   // whose two destinations will be set later when they are created.
9628   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9629   assert(isa<UnreachableInst>(CurrentTerminator) &&
9630          "Expected to replace unreachable terminator with conditional branch.");
9631   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9632   CondBr->setSuccessor(0, nullptr);
9633   ReplaceInstWithInst(CurrentTerminator, CondBr);
9634 }
9635 
9636 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9637   assert(State.Instance && "Predicated instruction PHI works per instance.");
9638   Instruction *ScalarPredInst =
9639       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9640   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9641   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9642   assert(PredicatingBB && "Predicated block has no single predecessor.");
9643   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9644          "operand must be VPReplicateRecipe");
9645 
9646   // By current pack/unpack logic we need to generate only a single phi node: if
9647   // a vector value for the predicated instruction exists at this point it means
9648   // the instruction has vector users only, and a phi for the vector value is
9649   // needed. In this case the recipe of the predicated instruction is marked to
9650   // also do that packing, thereby "hoisting" the insert-element sequence.
9651   // Otherwise, a phi node for the scalar value is needed.
9652   unsigned Part = State.Instance->Part;
9653   if (State.hasVectorValue(getOperand(0), Part)) {
9654     Value *VectorValue = State.get(getOperand(0), Part);
9655     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9656     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9657     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9658     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9659     if (State.hasVectorValue(this, Part))
9660       State.reset(this, VPhi, Part);
9661     else
9662       State.set(this, VPhi, Part);
9663     // NOTE: Currently we need to update the value of the operand, so the next
9664     // predicated iteration inserts its generated value in the correct vector.
9665     State.reset(getOperand(0), VPhi, Part);
9666   } else {
9667     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9668     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9669     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9670                      PredicatingBB);
9671     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9672     if (State.hasScalarValue(this, *State.Instance))
9673       State.reset(this, Phi, *State.Instance);
9674     else
9675       State.set(this, Phi, *State.Instance);
9676     // NOTE: Currently we need to update the value of the operand, so the next
9677     // predicated iteration inserts its generated value in the correct vector.
9678     State.reset(getOperand(0), Phi, *State.Instance);
9679   }
9680 }
9681 
9682 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9683   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9684   State.ILV->vectorizeMemoryInstruction(
9685       &Ingredient, State, StoredValue ? nullptr : getVPSingleValue(), getAddr(),
9686       StoredValue, getMask());
9687 }
9688 
9689 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9690 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9691 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9692 // for predication.
9693 static ScalarEpilogueLowering getScalarEpilogueLowering(
9694     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9695     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9696     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9697     LoopVectorizationLegality &LVL) {
9698   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9699   // don't look at hints or options, and don't request a scalar epilogue.
9700   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9701   // LoopAccessInfo (due to code dependency and not being able to reliably get
9702   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9703   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9704   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9705   // back to the old way and vectorize with versioning when forced. See D81345.)
9706   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9707                                                       PGSOQueryType::IRPass) &&
9708                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9709     return CM_ScalarEpilogueNotAllowedOptSize;
9710 
9711   // 2) If set, obey the directives
9712   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9713     switch (PreferPredicateOverEpilogue) {
9714     case PreferPredicateTy::ScalarEpilogue:
9715       return CM_ScalarEpilogueAllowed;
9716     case PreferPredicateTy::PredicateElseScalarEpilogue:
9717       return CM_ScalarEpilogueNotNeededUsePredicate;
9718     case PreferPredicateTy::PredicateOrDontVectorize:
9719       return CM_ScalarEpilogueNotAllowedUsePredicate;
9720     };
9721   }
9722 
9723   // 3) If set, obey the hints
9724   switch (Hints.getPredicate()) {
9725   case LoopVectorizeHints::FK_Enabled:
9726     return CM_ScalarEpilogueNotNeededUsePredicate;
9727   case LoopVectorizeHints::FK_Disabled:
9728     return CM_ScalarEpilogueAllowed;
9729   };
9730 
9731   // 4) if the TTI hook indicates this is profitable, request predication.
9732   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
9733                                        LVL.getLAI()))
9734     return CM_ScalarEpilogueNotNeededUsePredicate;
9735 
9736   return CM_ScalarEpilogueAllowed;
9737 }
9738 
9739 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9740   // If Values have been set for this Def return the one relevant for \p Part.
9741   if (hasVectorValue(Def, Part))
9742     return Data.PerPartOutput[Def][Part];
9743 
9744   if (!hasScalarValue(Def, {Part, 0})) {
9745     Value *IRV = Def->getLiveInIRValue();
9746     Value *B = ILV->getBroadcastInstrs(IRV);
9747     set(Def, B, Part);
9748     return B;
9749   }
9750 
9751   Value *ScalarValue = get(Def, {Part, 0});
9752   // If we aren't vectorizing, we can just copy the scalar map values over
9753   // to the vector map.
9754   if (VF.isScalar()) {
9755     set(Def, ScalarValue, Part);
9756     return ScalarValue;
9757   }
9758 
9759   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9760   bool IsUniform = RepR && RepR->isUniform();
9761 
9762   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9763   // Check if there is a scalar value for the selected lane.
9764   if (!hasScalarValue(Def, {Part, LastLane})) {
9765     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
9766     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
9767            "unexpected recipe found to be invariant");
9768     IsUniform = true;
9769     LastLane = 0;
9770   }
9771 
9772   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
9773   // Set the insert point after the last scalarized instruction or after the
9774   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
9775   // will directly follow the scalar definitions.
9776   auto OldIP = Builder.saveIP();
9777   auto NewIP =
9778       isa<PHINode>(LastInst)
9779           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
9780           : std::next(BasicBlock::iterator(LastInst));
9781   Builder.SetInsertPoint(&*NewIP);
9782 
9783   // However, if we are vectorizing, we need to construct the vector values.
9784   // If the value is known to be uniform after vectorization, we can just
9785   // broadcast the scalar value corresponding to lane zero for each unroll
9786   // iteration. Otherwise, we construct the vector values using
9787   // insertelement instructions. Since the resulting vectors are stored in
9788   // State, we will only generate the insertelements once.
9789   Value *VectorValue = nullptr;
9790   if (IsUniform) {
9791     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
9792     set(Def, VectorValue, Part);
9793   } else {
9794     // Initialize packing with insertelements to start from undef.
9795     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
9796     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
9797     set(Def, Undef, Part);
9798     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
9799       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
9800     VectorValue = get(Def, Part);
9801   }
9802   Builder.restoreIP(OldIP);
9803   return VectorValue;
9804 }
9805 
9806 // Process the loop in the VPlan-native vectorization path. This path builds
9807 // VPlan upfront in the vectorization pipeline, which allows to apply
9808 // VPlan-to-VPlan transformations from the very beginning without modifying the
9809 // input LLVM IR.
9810 static bool processLoopInVPlanNativePath(
9811     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
9812     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
9813     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
9814     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
9815     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
9816     LoopVectorizationRequirements &Requirements) {
9817 
9818   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9819     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9820     return false;
9821   }
9822   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9823   Function *F = L->getHeader()->getParent();
9824   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9825 
9826   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9827       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
9828 
9829   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9830                                 &Hints, IAI);
9831   // Use the planner for outer loop vectorization.
9832   // TODO: CM is not used at this point inside the planner. Turn CM into an
9833   // optional argument if we don't need it in the future.
9834   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
9835                                Requirements, ORE);
9836 
9837   // Get user vectorization factor.
9838   ElementCount UserVF = Hints.getWidth();
9839 
9840   // Plan how to best vectorize, return the best VF and its cost.
9841   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9842 
9843   // If we are stress testing VPlan builds, do not attempt to generate vector
9844   // code. Masked vector code generation support will follow soon.
9845   // Also, do not attempt to vectorize if no vector code will be produced.
9846   if (VPlanBuildStressTest || EnableVPlanPredication ||
9847       VectorizationFactor::Disabled() == VF)
9848     return false;
9849 
9850   LVP.setBestPlan(VF.Width, 1);
9851 
9852   {
9853     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
9854                              F->getParent()->getDataLayout());
9855     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
9856                            &CM, BFI, PSI, Checks);
9857     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9858                       << L->getHeader()->getParent()->getName() << "\"\n");
9859     LVP.executePlan(LB, DT);
9860   }
9861 
9862   // Mark the loop as already vectorized to avoid vectorizing again.
9863   Hints.setAlreadyVectorized();
9864   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9865   return true;
9866 }
9867 
9868 // Emit a remark if there are stores to floats that required a floating point
9869 // extension. If the vectorized loop was generated with floating point there
9870 // will be a performance penalty from the conversion overhead and the change in
9871 // the vector width.
9872 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
9873   SmallVector<Instruction *, 4> Worklist;
9874   for (BasicBlock *BB : L->getBlocks()) {
9875     for (Instruction &Inst : *BB) {
9876       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9877         if (S->getValueOperand()->getType()->isFloatTy())
9878           Worklist.push_back(S);
9879       }
9880     }
9881   }
9882 
9883   // Traverse the floating point stores upwards searching, for floating point
9884   // conversions.
9885   SmallPtrSet<const Instruction *, 4> Visited;
9886   SmallPtrSet<const Instruction *, 4> EmittedRemark;
9887   while (!Worklist.empty()) {
9888     auto *I = Worklist.pop_back_val();
9889     if (!L->contains(I))
9890       continue;
9891     if (!Visited.insert(I).second)
9892       continue;
9893 
9894     // Emit a remark if the floating point store required a floating
9895     // point conversion.
9896     // TODO: More work could be done to identify the root cause such as a
9897     // constant or a function return type and point the user to it.
9898     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9899       ORE->emit([&]() {
9900         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9901                                           I->getDebugLoc(), L->getHeader())
9902                << "floating point conversion changes vector width. "
9903                << "Mixed floating point precision requires an up/down "
9904                << "cast that will negatively impact performance.";
9905       });
9906 
9907     for (Use &Op : I->operands())
9908       if (auto *OpI = dyn_cast<Instruction>(Op))
9909         Worklist.push_back(OpI);
9910   }
9911 }
9912 
9913 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
9914     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9915                                !EnableLoopInterleaving),
9916       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9917                               !EnableLoopVectorization) {}
9918 
9919 bool LoopVectorizePass::processLoop(Loop *L) {
9920   assert((EnableVPlanNativePath || L->isInnermost()) &&
9921          "VPlan-native path is not enabled. Only process inner loops.");
9922 
9923 #ifndef NDEBUG
9924   const std::string DebugLocStr = getDebugLocString(L);
9925 #endif /* NDEBUG */
9926 
9927   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
9928                     << L->getHeader()->getParent()->getName() << "\" from "
9929                     << DebugLocStr << "\n");
9930 
9931   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
9932 
9933   LLVM_DEBUG(
9934       dbgs() << "LV: Loop hints:"
9935              << " force="
9936              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
9937                      ? "disabled"
9938                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
9939                             ? "enabled"
9940                             : "?"))
9941              << " width=" << Hints.getWidth()
9942              << " interleave=" << Hints.getInterleave() << "\n");
9943 
9944   // Function containing loop
9945   Function *F = L->getHeader()->getParent();
9946 
9947   // Looking at the diagnostic output is the only way to determine if a loop
9948   // was vectorized (other than looking at the IR or machine code), so it
9949   // is important to generate an optimization remark for each loop. Most of
9950   // these messages are generated as OptimizationRemarkAnalysis. Remarks
9951   // generated as OptimizationRemark and OptimizationRemarkMissed are
9952   // less verbose reporting vectorized loops and unvectorized loops that may
9953   // benefit from vectorization, respectively.
9954 
9955   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9956     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9957     return false;
9958   }
9959 
9960   PredicatedScalarEvolution PSE(*SE, *L);
9961 
9962   // Check if it is legal to vectorize the loop.
9963   LoopVectorizationRequirements Requirements;
9964   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
9965                                 &Requirements, &Hints, DB, AC, BFI, PSI);
9966   if (!LVL.canVectorize(EnableVPlanNativePath)) {
9967     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
9968     Hints.emitRemarkWithHints();
9969     return false;
9970   }
9971 
9972   // Check the function attributes and profiles to find out if this function
9973   // should be optimized for size.
9974   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9975       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
9976 
9977   // Entrance to the VPlan-native vectorization path. Outer loops are processed
9978   // here. They may require CFG and instruction level transformations before
9979   // even evaluating whether vectorization is profitable. Since we cannot modify
9980   // the incoming IR, we need to build VPlan upfront in the vectorization
9981   // pipeline.
9982   if (!L->isInnermost())
9983     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
9984                                         ORE, BFI, PSI, Hints, Requirements);
9985 
9986   assert(L->isInnermost() && "Inner loop expected.");
9987 
9988   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
9989   // count by optimizing for size, to minimize overheads.
9990   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
9991   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
9992     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
9993                       << "This loop is worth vectorizing only if no scalar "
9994                       << "iteration overheads are incurred.");
9995     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
9996       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
9997     else {
9998       LLVM_DEBUG(dbgs() << "\n");
9999       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10000     }
10001   }
10002 
10003   // Check the function attributes to see if implicit floats are allowed.
10004   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10005   // an integer loop and the vector instructions selected are purely integer
10006   // vector instructions?
10007   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10008     reportVectorizationFailure(
10009         "Can't vectorize when the NoImplicitFloat attribute is used",
10010         "loop not vectorized due to NoImplicitFloat attribute",
10011         "NoImplicitFloat", ORE, L);
10012     Hints.emitRemarkWithHints();
10013     return false;
10014   }
10015 
10016   // Check if the target supports potentially unsafe FP vectorization.
10017   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10018   // for the target we're vectorizing for, to make sure none of the
10019   // additional fp-math flags can help.
10020   if (Hints.isPotentiallyUnsafe() &&
10021       TTI->isFPVectorizationPotentiallyUnsafe()) {
10022     reportVectorizationFailure(
10023         "Potentially unsafe FP op prevents vectorization",
10024         "loop not vectorized due to unsafe FP support.",
10025         "UnsafeFP", ORE, L);
10026     Hints.emitRemarkWithHints();
10027     return false;
10028   }
10029 
10030   if (!LVL.canVectorizeFPMath(EnableStrictReductions)) {
10031     ORE->emit([&]() {
10032       auto *ExactFPMathInst = Requirements.getExactFPInst();
10033       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10034                                                  ExactFPMathInst->getDebugLoc(),
10035                                                  ExactFPMathInst->getParent())
10036              << "loop not vectorized: cannot prove it is safe to reorder "
10037                 "floating-point operations";
10038     });
10039     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10040                          "reorder floating-point operations\n");
10041     Hints.emitRemarkWithHints();
10042     return false;
10043   }
10044 
10045   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10046   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10047 
10048   // If an override option has been passed in for interleaved accesses, use it.
10049   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10050     UseInterleaved = EnableInterleavedMemAccesses;
10051 
10052   // Analyze interleaved memory accesses.
10053   if (UseInterleaved) {
10054     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10055   }
10056 
10057   // Use the cost model.
10058   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10059                                 F, &Hints, IAI);
10060   CM.collectValuesToIgnore();
10061 
10062   // Use the planner for vectorization.
10063   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10064                                Requirements, ORE);
10065 
10066   // Get user vectorization factor and interleave count.
10067   ElementCount UserVF = Hints.getWidth();
10068   unsigned UserIC = Hints.getInterleave();
10069 
10070   // Plan how to best vectorize, return the best VF and its cost.
10071   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10072 
10073   VectorizationFactor VF = VectorizationFactor::Disabled();
10074   unsigned IC = 1;
10075 
10076   if (MaybeVF) {
10077     VF = *MaybeVF;
10078     // Select the interleave count.
10079     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10080   }
10081 
10082   // Identify the diagnostic messages that should be produced.
10083   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10084   bool VectorizeLoop = true, InterleaveLoop = true;
10085   if (VF.Width.isScalar()) {
10086     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10087     VecDiagMsg = std::make_pair(
10088         "VectorizationNotBeneficial",
10089         "the cost-model indicates that vectorization is not beneficial");
10090     VectorizeLoop = false;
10091   }
10092 
10093   if (!MaybeVF && UserIC > 1) {
10094     // Tell the user interleaving was avoided up-front, despite being explicitly
10095     // requested.
10096     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10097                          "interleaving should be avoided up front\n");
10098     IntDiagMsg = std::make_pair(
10099         "InterleavingAvoided",
10100         "Ignoring UserIC, because interleaving was avoided up front");
10101     InterleaveLoop = false;
10102   } else if (IC == 1 && UserIC <= 1) {
10103     // Tell the user interleaving is not beneficial.
10104     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10105     IntDiagMsg = std::make_pair(
10106         "InterleavingNotBeneficial",
10107         "the cost-model indicates that interleaving is not beneficial");
10108     InterleaveLoop = false;
10109     if (UserIC == 1) {
10110       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10111       IntDiagMsg.second +=
10112           " and is explicitly disabled or interleave count is set to 1";
10113     }
10114   } else if (IC > 1 && UserIC == 1) {
10115     // Tell the user interleaving is beneficial, but it explicitly disabled.
10116     LLVM_DEBUG(
10117         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10118     IntDiagMsg = std::make_pair(
10119         "InterleavingBeneficialButDisabled",
10120         "the cost-model indicates that interleaving is beneficial "
10121         "but is explicitly disabled or interleave count is set to 1");
10122     InterleaveLoop = false;
10123   }
10124 
10125   // Override IC if user provided an interleave count.
10126   IC = UserIC > 0 ? UserIC : IC;
10127 
10128   // Emit diagnostic messages, if any.
10129   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10130   if (!VectorizeLoop && !InterleaveLoop) {
10131     // Do not vectorize or interleaving the loop.
10132     ORE->emit([&]() {
10133       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10134                                       L->getStartLoc(), L->getHeader())
10135              << VecDiagMsg.second;
10136     });
10137     ORE->emit([&]() {
10138       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10139                                       L->getStartLoc(), L->getHeader())
10140              << IntDiagMsg.second;
10141     });
10142     return false;
10143   } else if (!VectorizeLoop && InterleaveLoop) {
10144     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10145     ORE->emit([&]() {
10146       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10147                                         L->getStartLoc(), L->getHeader())
10148              << VecDiagMsg.second;
10149     });
10150   } else if (VectorizeLoop && !InterleaveLoop) {
10151     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10152                       << ") in " << DebugLocStr << '\n');
10153     ORE->emit([&]() {
10154       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10155                                         L->getStartLoc(), L->getHeader())
10156              << IntDiagMsg.second;
10157     });
10158   } else if (VectorizeLoop && InterleaveLoop) {
10159     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10160                       << ") in " << DebugLocStr << '\n');
10161     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10162   }
10163 
10164   bool DisableRuntimeUnroll = false;
10165   MDNode *OrigLoopID = L->getLoopID();
10166   {
10167     // Optimistically generate runtime checks. Drop them if they turn out to not
10168     // be profitable. Limit the scope of Checks, so the cleanup happens
10169     // immediately after vector codegeneration is done.
10170     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10171                              F->getParent()->getDataLayout());
10172     if (!VF.Width.isScalar() || IC > 1)
10173       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
10174     LVP.setBestPlan(VF.Width, IC);
10175 
10176     using namespace ore;
10177     if (!VectorizeLoop) {
10178       assert(IC > 1 && "interleave count should not be 1 or 0");
10179       // If we decided that it is not legal to vectorize the loop, then
10180       // interleave it.
10181       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10182                                  &CM, BFI, PSI, Checks);
10183       LVP.executePlan(Unroller, DT);
10184 
10185       ORE->emit([&]() {
10186         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10187                                   L->getHeader())
10188                << "interleaved loop (interleaved count: "
10189                << NV("InterleaveCount", IC) << ")";
10190       });
10191     } else {
10192       // If we decided that it is *legal* to vectorize the loop, then do it.
10193 
10194       // Consider vectorizing the epilogue too if it's profitable.
10195       VectorizationFactor EpilogueVF =
10196           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10197       if (EpilogueVF.Width.isVector()) {
10198 
10199         // The first pass vectorizes the main loop and creates a scalar epilogue
10200         // to be vectorized by executing the plan (potentially with a different
10201         // factor) again shortly afterwards.
10202         EpilogueLoopVectorizationInfo EPI(VF.Width.getKnownMinValue(), IC,
10203                                           EpilogueVF.Width.getKnownMinValue(),
10204                                           1);
10205         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10206                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10207 
10208         LVP.setBestPlan(EPI.MainLoopVF, EPI.MainLoopUF);
10209         LVP.executePlan(MainILV, DT);
10210         ++LoopsVectorized;
10211 
10212         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10213         formLCSSARecursively(*L, *DT, LI, SE);
10214 
10215         // Second pass vectorizes the epilogue and adjusts the control flow
10216         // edges from the first pass.
10217         LVP.setBestPlan(EPI.EpilogueVF, EPI.EpilogueUF);
10218         EPI.MainLoopVF = EPI.EpilogueVF;
10219         EPI.MainLoopUF = EPI.EpilogueUF;
10220         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10221                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10222                                                  Checks);
10223         LVP.executePlan(EpilogILV, DT);
10224         ++LoopsEpilogueVectorized;
10225 
10226         if (!MainILV.areSafetyChecksAdded())
10227           DisableRuntimeUnroll = true;
10228       } else {
10229         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10230                                &LVL, &CM, BFI, PSI, Checks);
10231         LVP.executePlan(LB, DT);
10232         ++LoopsVectorized;
10233 
10234         // Add metadata to disable runtime unrolling a scalar loop when there
10235         // are no runtime checks about strides and memory. A scalar loop that is
10236         // rarely used is not worth unrolling.
10237         if (!LB.areSafetyChecksAdded())
10238           DisableRuntimeUnroll = true;
10239       }
10240       // Report the vectorization decision.
10241       ORE->emit([&]() {
10242         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10243                                   L->getHeader())
10244                << "vectorized loop (vectorization width: "
10245                << NV("VectorizationFactor", VF.Width)
10246                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10247       });
10248     }
10249 
10250     if (ORE->allowExtraAnalysis(LV_NAME))
10251       checkMixedPrecision(L, ORE);
10252   }
10253 
10254   Optional<MDNode *> RemainderLoopID =
10255       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10256                                       LLVMLoopVectorizeFollowupEpilogue});
10257   if (RemainderLoopID.hasValue()) {
10258     L->setLoopID(RemainderLoopID.getValue());
10259   } else {
10260     if (DisableRuntimeUnroll)
10261       AddRuntimeUnrollDisableMetaData(L);
10262 
10263     // Mark the loop as already vectorized to avoid vectorizing again.
10264     Hints.setAlreadyVectorized();
10265   }
10266 
10267   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10268   return true;
10269 }
10270 
10271 LoopVectorizeResult LoopVectorizePass::runImpl(
10272     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10273     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10274     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10275     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10276     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10277   SE = &SE_;
10278   LI = &LI_;
10279   TTI = &TTI_;
10280   DT = &DT_;
10281   BFI = &BFI_;
10282   TLI = TLI_;
10283   AA = &AA_;
10284   AC = &AC_;
10285   GetLAA = &GetLAA_;
10286   DB = &DB_;
10287   ORE = &ORE_;
10288   PSI = PSI_;
10289 
10290   // Don't attempt if
10291   // 1. the target claims to have no vector registers, and
10292   // 2. interleaving won't help ILP.
10293   //
10294   // The second condition is necessary because, even if the target has no
10295   // vector registers, loop vectorization may still enable scalar
10296   // interleaving.
10297   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10298       TTI->getMaxInterleaveFactor(1) < 2)
10299     return LoopVectorizeResult(false, false);
10300 
10301   bool Changed = false, CFGChanged = false;
10302 
10303   // The vectorizer requires loops to be in simplified form.
10304   // Since simplification may add new inner loops, it has to run before the
10305   // legality and profitability checks. This means running the loop vectorizer
10306   // will simplify all loops, regardless of whether anything end up being
10307   // vectorized.
10308   for (auto &L : *LI)
10309     Changed |= CFGChanged |=
10310         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10311 
10312   // Build up a worklist of inner-loops to vectorize. This is necessary as
10313   // the act of vectorizing or partially unrolling a loop creates new loops
10314   // and can invalidate iterators across the loops.
10315   SmallVector<Loop *, 8> Worklist;
10316 
10317   for (Loop *L : *LI)
10318     collectSupportedLoops(*L, LI, ORE, Worklist);
10319 
10320   LoopsAnalyzed += Worklist.size();
10321 
10322   // Now walk the identified inner loops.
10323   while (!Worklist.empty()) {
10324     Loop *L = Worklist.pop_back_val();
10325 
10326     // For the inner loops we actually process, form LCSSA to simplify the
10327     // transform.
10328     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10329 
10330     Changed |= CFGChanged |= processLoop(L);
10331   }
10332 
10333   // Process each loop nest in the function.
10334   return LoopVectorizeResult(Changed, CFGChanged);
10335 }
10336 
10337 PreservedAnalyses LoopVectorizePass::run(Function &F,
10338                                          FunctionAnalysisManager &AM) {
10339     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10340     auto &LI = AM.getResult<LoopAnalysis>(F);
10341     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10342     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10343     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10344     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10345     auto &AA = AM.getResult<AAManager>(F);
10346     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10347     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10348     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10349     MemorySSA *MSSA = EnableMSSALoopDependency
10350                           ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
10351                           : nullptr;
10352 
10353     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10354     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10355         [&](Loop &L) -> const LoopAccessInfo & {
10356       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,  SE,
10357                                         TLI, TTI, nullptr, MSSA};
10358       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10359     };
10360     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10361     ProfileSummaryInfo *PSI =
10362         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10363     LoopVectorizeResult Result =
10364         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10365     if (!Result.MadeAnyChange)
10366       return PreservedAnalyses::all();
10367     PreservedAnalyses PA;
10368 
10369     // We currently do not preserve loopinfo/dominator analyses with outer loop
10370     // vectorization. Until this is addressed, mark these analyses as preserved
10371     // only for non-VPlan-native path.
10372     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10373     if (!EnableVPlanNativePath) {
10374       PA.preserve<LoopAnalysis>();
10375       PA.preserve<DominatorTreeAnalysis>();
10376     }
10377     if (!Result.MadeCFGChange)
10378       PA.preserveSet<CFGAnalyses>();
10379     return PA;
10380 }
10381