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/SmallVector.h"
74 #include "llvm/ADT/Statistic.h"
75 #include "llvm/ADT/StringRef.h"
76 #include "llvm/ADT/Twine.h"
77 #include "llvm/ADT/iterator_range.h"
78 #include "llvm/Analysis/AssumptionCache.h"
79 #include "llvm/Analysis/BasicAliasAnalysis.h"
80 #include "llvm/Analysis/BlockFrequencyInfo.h"
81 #include "llvm/Analysis/CFG.h"
82 #include "llvm/Analysis/CodeMetrics.h"
83 #include "llvm/Analysis/DemandedBits.h"
84 #include "llvm/Analysis/GlobalsModRef.h"
85 #include "llvm/Analysis/LoopAccessAnalysis.h"
86 #include "llvm/Analysis/LoopAnalysisManager.h"
87 #include "llvm/Analysis/LoopInfo.h"
88 #include "llvm/Analysis/LoopIterator.h"
89 #include "llvm/Analysis/MemorySSA.h"
90 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
91 #include "llvm/Analysis/ProfileSummaryInfo.h"
92 #include "llvm/Analysis/ScalarEvolution.h"
93 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
94 #include "llvm/Analysis/TargetLibraryInfo.h"
95 #include "llvm/Analysis/TargetTransformInfo.h"
96 #include "llvm/Analysis/VectorUtils.h"
97 #include "llvm/IR/Attributes.h"
98 #include "llvm/IR/BasicBlock.h"
99 #include "llvm/IR/CFG.h"
100 #include "llvm/IR/Constant.h"
101 #include "llvm/IR/Constants.h"
102 #include "llvm/IR/DataLayout.h"
103 #include "llvm/IR/DebugInfoMetadata.h"
104 #include "llvm/IR/DebugLoc.h"
105 #include "llvm/IR/DerivedTypes.h"
106 #include "llvm/IR/DiagnosticInfo.h"
107 #include "llvm/IR/Dominators.h"
108 #include "llvm/IR/Function.h"
109 #include "llvm/IR/IRBuilder.h"
110 #include "llvm/IR/InstrTypes.h"
111 #include "llvm/IR/Instruction.h"
112 #include "llvm/IR/Instructions.h"
113 #include "llvm/IR/IntrinsicInst.h"
114 #include "llvm/IR/Intrinsics.h"
115 #include "llvm/IR/LLVMContext.h"
116 #include "llvm/IR/Metadata.h"
117 #include "llvm/IR/Module.h"
118 #include "llvm/IR/Operator.h"
119 #include "llvm/IR/PatternMatch.h"
120 #include "llvm/IR/Type.h"
121 #include "llvm/IR/Use.h"
122 #include "llvm/IR/User.h"
123 #include "llvm/IR/Value.h"
124 #include "llvm/IR/ValueHandle.h"
125 #include "llvm/IR/Verifier.h"
126 #include "llvm/InitializePasses.h"
127 #include "llvm/Pass.h"
128 #include "llvm/Support/Casting.h"
129 #include "llvm/Support/CommandLine.h"
130 #include "llvm/Support/Compiler.h"
131 #include "llvm/Support/Debug.h"
132 #include "llvm/Support/ErrorHandling.h"
133 #include "llvm/Support/InstructionCost.h"
134 #include "llvm/Support/MathExtras.h"
135 #include "llvm/Support/raw_ostream.h"
136 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
137 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
138 #include "llvm/Transforms/Utils/LoopSimplify.h"
139 #include "llvm/Transforms/Utils/LoopUtils.h"
140 #include "llvm/Transforms/Utils/LoopVersioning.h"
141 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
142 #include "llvm/Transforms/Utils/SizeOpts.h"
143 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
144 #include <algorithm>
145 #include <cassert>
146 #include <cstdint>
147 #include <cstdlib>
148 #include <functional>
149 #include <iterator>
150 #include <limits>
151 #include <memory>
152 #include <string>
153 #include <tuple>
154 #include <utility>
155 
156 using namespace llvm;
157 
158 #define LV_NAME "loop-vectorize"
159 #define DEBUG_TYPE LV_NAME
160 
161 #ifndef NDEBUG
162 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
163 #endif
164 
165 /// @{
166 /// Metadata attribute names
167 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
168 const char LLVMLoopVectorizeFollowupVectorized[] =
169     "llvm.loop.vectorize.followup_vectorized";
170 const char LLVMLoopVectorizeFollowupEpilogue[] =
171     "llvm.loop.vectorize.followup_epilogue";
172 /// @}
173 
174 STATISTIC(LoopsVectorized, "Number of loops vectorized");
175 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
176 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
177 
178 static cl::opt<bool> EnableEpilogueVectorization(
179     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
180     cl::desc("Enable vectorization of epilogue loops."));
181 
182 static cl::opt<unsigned> EpilogueVectorizationForceVF(
183     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
184     cl::desc("When epilogue vectorization is enabled, and a value greater than "
185              "1 is specified, forces the given VF for all applicable epilogue "
186              "loops."));
187 
188 static cl::opt<unsigned> EpilogueVectorizationMinVF(
189     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
190     cl::desc("Only loops with vectorization factor equal to or larger than "
191              "the specified value are considered for epilogue vectorization."));
192 
193 /// Loops with a known constant trip count below this number are vectorized only
194 /// if no scalar iteration overheads are incurred.
195 static cl::opt<unsigned> TinyTripCountVectorThreshold(
196     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
197     cl::desc("Loops with a constant trip count that is smaller than this "
198              "value are vectorized only if no scalar iteration overheads "
199              "are incurred."));
200 
201 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
202     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
203     cl::desc("The maximum allowed number of runtime memory checks with a "
204              "vectorize(enable) pragma."));
205 
206 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
207 // that predication is preferred, and this lists all options. I.e., the
208 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
209 // and predicate the instructions accordingly. If tail-folding fails, there are
210 // different fallback strategies depending on these values:
211 namespace PreferPredicateTy {
212   enum Option {
213     ScalarEpilogue = 0,
214     PredicateElseScalarEpilogue,
215     PredicateOrDontVectorize
216   };
217 } // namespace PreferPredicateTy
218 
219 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
220     "prefer-predicate-over-epilogue",
221     cl::init(PreferPredicateTy::ScalarEpilogue),
222     cl::Hidden,
223     cl::desc("Tail-folding and predication preferences over creating a scalar "
224              "epilogue loop."),
225     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
226                          "scalar-epilogue",
227                          "Don't tail-predicate loops, create scalar epilogue"),
228               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
229                          "predicate-else-scalar-epilogue",
230                          "prefer tail-folding, create scalar epilogue if tail "
231                          "folding fails."),
232               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
233                          "predicate-dont-vectorize",
234                          "prefers tail-folding, don't attempt vectorization if "
235                          "tail-folding fails.")));
236 
237 static cl::opt<bool> MaximizeBandwidth(
238     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
239     cl::desc("Maximize bandwidth when selecting vectorization factor which "
240              "will be determined by the smallest type in loop."));
241 
242 static cl::opt<bool> EnableInterleavedMemAccesses(
243     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
244     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
245 
246 /// An interleave-group may need masking if it resides in a block that needs
247 /// predication, or in order to mask away gaps.
248 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
249     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
250     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
251 
252 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
253     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
254     cl::desc("We don't interleave loops with a estimated constant trip count "
255              "below this number"));
256 
257 static cl::opt<unsigned> ForceTargetNumScalarRegs(
258     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
259     cl::desc("A flag that overrides the target's number of scalar registers."));
260 
261 static cl::opt<unsigned> ForceTargetNumVectorRegs(
262     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
263     cl::desc("A flag that overrides the target's number of vector registers."));
264 
265 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
266     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
267     cl::desc("A flag that overrides the target's max interleave factor for "
268              "scalar loops."));
269 
270 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
271     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
272     cl::desc("A flag that overrides the target's max interleave factor for "
273              "vectorized loops."));
274 
275 static cl::opt<unsigned> ForceTargetInstructionCost(
276     "force-target-instruction-cost", cl::init(0), cl::Hidden,
277     cl::desc("A flag that overrides the target's expected cost for "
278              "an instruction to a single constant value. Mostly "
279              "useful for getting consistent testing."));
280 
281 static cl::opt<bool> ForceTargetSupportsScalableVectors(
282     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
283     cl::desc(
284         "Pretend that scalable vectors are supported, even if the target does "
285         "not support them. This flag should only be used for testing."));
286 
287 static cl::opt<unsigned> SmallLoopCost(
288     "small-loop-cost", cl::init(20), cl::Hidden,
289     cl::desc(
290         "The cost of a loop that is considered 'small' by the interleaver."));
291 
292 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
293     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
294     cl::desc("Enable the use of the block frequency analysis to access PGO "
295              "heuristics minimizing code growth in cold regions and being more "
296              "aggressive in hot regions."));
297 
298 // Runtime interleave loops for load/store throughput.
299 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
300     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
301     cl::desc(
302         "Enable runtime interleaving until load/store ports are saturated"));
303 
304 /// Interleave small loops with scalar reductions.
305 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
306     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
307     cl::desc("Enable interleaving for loops with small iteration counts that "
308              "contain scalar reductions to expose ILP."));
309 
310 /// The number of stores in a loop that are allowed to need predication.
311 static cl::opt<unsigned> NumberOfStoresToPredicate(
312     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
313     cl::desc("Max number of stores to be predicated behind an if."));
314 
315 static cl::opt<bool> EnableIndVarRegisterHeur(
316     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
317     cl::desc("Count the induction variable only once when interleaving"));
318 
319 static cl::opt<bool> EnableCondStoresVectorization(
320     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
321     cl::desc("Enable if predication of stores during vectorization."));
322 
323 static cl::opt<unsigned> MaxNestedScalarReductionIC(
324     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
325     cl::desc("The maximum interleave count to use when interleaving a scalar "
326              "reduction in a nested loop."));
327 
328 static cl::opt<bool>
329     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
330                            cl::Hidden,
331                            cl::desc("Prefer in-loop vector reductions, "
332                                     "overriding the targets preference."));
333 
334 cl::opt<bool> EnableStrictReductions(
335     "enable-strict-reductions", cl::init(false), cl::Hidden,
336     cl::desc("Enable the vectorisation of loops with in-order (strict) "
337              "FP reductions"));
338 
339 static cl::opt<bool> PreferPredicatedReductionSelect(
340     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
341     cl::desc(
342         "Prefer predicating a reduction operation over an after loop select."));
343 
344 cl::opt<bool> EnableVPlanNativePath(
345     "enable-vplan-native-path", cl::init(false), cl::Hidden,
346     cl::desc("Enable VPlan-native vectorization path with "
347              "support for outer loop vectorization."));
348 
349 // FIXME: Remove this switch once we have divergence analysis. Currently we
350 // assume divergent non-backedge branches when this switch is true.
351 cl::opt<bool> EnableVPlanPredication(
352     "enable-vplan-predication", cl::init(false), cl::Hidden,
353     cl::desc("Enable VPlan-native vectorization path predicator with "
354              "support for outer loop vectorization."));
355 
356 // This flag enables the stress testing of the VPlan H-CFG construction in the
357 // VPlan-native vectorization path. It must be used in conjuction with
358 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
359 // verification of the H-CFGs built.
360 static cl::opt<bool> VPlanBuildStressTest(
361     "vplan-build-stress-test", cl::init(false), cl::Hidden,
362     cl::desc(
363         "Build VPlan for every supported loop nest in the function and bail "
364         "out right after the build (stress test the VPlan H-CFG construction "
365         "in the VPlan-native vectorization path)."));
366 
367 cl::opt<bool> llvm::EnableLoopInterleaving(
368     "interleave-loops", cl::init(true), cl::Hidden,
369     cl::desc("Enable loop interleaving in Loop vectorization passes"));
370 cl::opt<bool> llvm::EnableLoopVectorization(
371     "vectorize-loops", cl::init(true), cl::Hidden,
372     cl::desc("Run the Loop vectorization passes"));
373 
374 cl::opt<bool> PrintVPlansInDotFormat(
375     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
376     cl::desc("Use dot format instead of plain text when dumping VPlans"));
377 
378 /// A helper function that returns the type of loaded or stored value.
379 static Type *getMemInstValueType(Value *I) {
380   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
381          "Expected Load or Store instruction");
382   if (auto *LI = dyn_cast<LoadInst>(I))
383     return LI->getType();
384   return cast<StoreInst>(I)->getValueOperand()->getType();
385 }
386 
387 /// A helper function that returns true if the given type is irregular. The
388 /// type is irregular if its allocated size doesn't equal the store size of an
389 /// element of the corresponding vector type.
390 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
391   // Determine if an array of N elements of type Ty is "bitcast compatible"
392   // with a <N x Ty> vector.
393   // This is only true if there is no padding between the array elements.
394   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
395 }
396 
397 /// A helper function that returns the reciprocal of the block probability of
398 /// predicated blocks. If we return X, we are assuming the predicated block
399 /// will execute once for every X iterations of the loop header.
400 ///
401 /// TODO: We should use actual block probability here, if available. Currently,
402 ///       we always assume predicated blocks have a 50% chance of executing.
403 static unsigned getReciprocalPredBlockProb() { return 2; }
404 
405 /// A helper function that returns an integer or floating-point constant with
406 /// value C.
407 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
408   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
409                            : ConstantFP::get(Ty, C);
410 }
411 
412 /// Returns "best known" trip count for the specified loop \p L as defined by
413 /// the following procedure:
414 ///   1) Returns exact trip count if it is known.
415 ///   2) Returns expected trip count according to profile data if any.
416 ///   3) Returns upper bound estimate if it is known.
417 ///   4) Returns None if all of the above failed.
418 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
419   // Check if exact trip count is known.
420   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
421     return ExpectedTC;
422 
423   // Check if there is an expected trip count available from profile data.
424   if (LoopVectorizeWithBlockFrequency)
425     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
426       return EstimatedTC;
427 
428   // Check if upper bound estimate is known.
429   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
430     return ExpectedTC;
431 
432   return None;
433 }
434 
435 // Forward declare GeneratedRTChecks.
436 class GeneratedRTChecks;
437 
438 namespace llvm {
439 
440 /// InnerLoopVectorizer vectorizes loops which contain only one basic
441 /// block to a specified vectorization factor (VF).
442 /// This class performs the widening of scalars into vectors, or multiple
443 /// scalars. This class also implements the following features:
444 /// * It inserts an epilogue loop for handling loops that don't have iteration
445 ///   counts that are known to be a multiple of the vectorization factor.
446 /// * It handles the code generation for reduction variables.
447 /// * Scalarization (implementation using scalars) of un-vectorizable
448 ///   instructions.
449 /// InnerLoopVectorizer does not perform any vectorization-legality
450 /// checks, and relies on the caller to check for the different legality
451 /// aspects. The InnerLoopVectorizer relies on the
452 /// LoopVectorizationLegality class to provide information about the induction
453 /// and reduction variables that were found to a given vectorization factor.
454 class InnerLoopVectorizer {
455 public:
456   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
457                       LoopInfo *LI, DominatorTree *DT,
458                       const TargetLibraryInfo *TLI,
459                       const TargetTransformInfo *TTI, AssumptionCache *AC,
460                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
461                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
462                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
463                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
464       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
465         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
466         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
467         PSI(PSI), RTChecks(RTChecks) {
468     // Query this against the original loop and save it here because the profile
469     // of the original loop header may change as the transformation happens.
470     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
471         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
472   }
473 
474   virtual ~InnerLoopVectorizer() = default;
475 
476   /// Create a new empty loop that will contain vectorized instructions later
477   /// on, while the old loop will be used as the scalar remainder. Control flow
478   /// is generated around the vectorized (and scalar epilogue) loops consisting
479   /// of various checks and bypasses. Return the pre-header block of the new
480   /// loop.
481   /// In the case of epilogue vectorization, this function is overriden to
482   /// handle the more complex control flow around the loops.
483   virtual BasicBlock *createVectorizedLoopSkeleton();
484 
485   /// Widen a single instruction within the innermost loop.
486   void widenInstruction(Instruction &I, VPValue *Def, VPUser &Operands,
487                         VPTransformState &State);
488 
489   /// Widen a single call instruction within the innermost loop.
490   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
491                             VPTransformState &State);
492 
493   /// Widen a single select instruction within the innermost loop.
494   void widenSelectInstruction(SelectInst &I, VPValue *VPDef, VPUser &Operands,
495                               bool InvariantCond, VPTransformState &State);
496 
497   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
498   void fixVectorizedLoop(VPTransformState &State);
499 
500   // Return true if any runtime check is added.
501   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
502 
503   /// A type for vectorized values in the new loop. Each value from the
504   /// original loop, when vectorized, is represented by UF vector values in the
505   /// new unrolled loop, where UF is the unroll factor.
506   using VectorParts = SmallVector<Value *, 2>;
507 
508   /// Vectorize a single GetElementPtrInst based on information gathered and
509   /// decisions taken during planning.
510   void widenGEP(GetElementPtrInst *GEP, VPValue *VPDef, VPUser &Indices,
511                 unsigned UF, ElementCount VF, bool IsPtrLoopInvariant,
512                 SmallBitVector &IsIndexLoopInvariant, VPTransformState &State);
513 
514   /// Vectorize a single PHINode in a block. This method handles the induction
515   /// variable canonicalization. It supports both VF = 1 for unrolled loops and
516   /// arbitrary length vectors.
517   void widenPHIInstruction(Instruction *PN, RecurrenceDescriptor *RdxDesc,
518                            VPWidenPHIRecipe *PhiR, VPTransformState &State);
519 
520   /// A helper function to scalarize a single Instruction in the innermost loop.
521   /// Generates a sequence of scalar instances for each lane between \p MinLane
522   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
523   /// inclusive. Uses the VPValue operands from \p Operands instead of \p
524   /// Instr's operands.
525   void scalarizeInstruction(Instruction *Instr, VPValue *Def, VPUser &Operands,
526                             const VPIteration &Instance, bool IfPredicateInstr,
527                             VPTransformState &State);
528 
529   /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
530   /// is provided, the integer induction variable will first be truncated to
531   /// the corresponding type.
532   void widenIntOrFpInduction(PHINode *IV, Value *Start, TruncInst *Trunc,
533                              VPValue *Def, VPValue *CastDef,
534                              VPTransformState &State);
535 
536   /// Construct the vector value of a scalarized value \p V one lane at a time.
537   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
538                                  VPTransformState &State);
539 
540   /// Try to vectorize interleaved access group \p Group with the base address
541   /// given in \p Addr, optionally masking the vector operations if \p
542   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
543   /// values in the vectorized loop.
544   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
545                                 ArrayRef<VPValue *> VPDefs,
546                                 VPTransformState &State, VPValue *Addr,
547                                 ArrayRef<VPValue *> StoredValues,
548                                 VPValue *BlockInMask = nullptr);
549 
550   /// Vectorize Load and Store instructions with the base address given in \p
551   /// Addr, optionally masking the vector operations if \p BlockInMask is
552   /// non-null. Use \p State to translate given VPValues to IR values in the
553   /// vectorized loop.
554   void vectorizeMemoryInstruction(Instruction *Instr, VPTransformState &State,
555                                   VPValue *Def, VPValue *Addr,
556                                   VPValue *StoredValue, VPValue *BlockInMask);
557 
558   /// Set the debug location in the builder using the debug location in
559   /// the instruction.
560   void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
561 
562   /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
563   void fixNonInductionPHIs(VPTransformState &State);
564 
565   /// Create a broadcast instruction. This method generates a broadcast
566   /// instruction (shuffle) for loop invariant values and for the induction
567   /// value. If this is the induction variable then we extend it to N, N+1, ...
568   /// this is needed because each iteration in the loop corresponds to a SIMD
569   /// element.
570   virtual Value *getBroadcastInstrs(Value *V);
571 
572 protected:
573   friend class LoopVectorizationPlanner;
574 
575   /// A small list of PHINodes.
576   using PhiVector = SmallVector<PHINode *, 4>;
577 
578   /// A type for scalarized values in the new loop. Each value from the
579   /// original loop, when scalarized, is represented by UF x VF scalar values
580   /// in the new unrolled loop, where UF is the unroll factor and VF is the
581   /// vectorization factor.
582   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
583 
584   /// Set up the values of the IVs correctly when exiting the vector loop.
585   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
586                     Value *CountRoundDown, Value *EndValue,
587                     BasicBlock *MiddleBlock);
588 
589   /// Create a new induction variable inside L.
590   PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
591                                    Value *Step, Instruction *DL);
592 
593   /// Handle all cross-iteration phis in the header.
594   void fixCrossIterationPHIs(VPTransformState &State);
595 
596   /// Fix a first-order recurrence. This is the second phase of vectorizing
597   /// this phi node.
598   void fixFirstOrderRecurrence(PHINode *Phi, VPTransformState &State);
599 
600   /// Fix a reduction cross-iteration phi. This is the second phase of
601   /// vectorizing this phi node.
602   void fixReduction(VPWidenPHIRecipe *Phi, VPTransformState &State);
603 
604   /// Clear NSW/NUW flags from reduction instructions if necessary.
605   void clearReductionWrapFlags(RecurrenceDescriptor &RdxDesc,
606                                VPTransformState &State);
607 
608   /// Fixup the LCSSA phi nodes in the unique exit block.  This simply
609   /// means we need to add the appropriate incoming value from the middle
610   /// block as exiting edges from the scalar epilogue loop (if present) are
611   /// already in place, and we exit the vector loop exclusively to the middle
612   /// block.
613   void fixLCSSAPHIs(VPTransformState &State);
614 
615   /// Iteratively sink the scalarized operands of a predicated instruction into
616   /// the block that was created for it.
617   void sinkScalarOperands(Instruction *PredInst);
618 
619   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
620   /// represented as.
621   void truncateToMinimalBitwidths(VPTransformState &State);
622 
623   /// This function adds
624   /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
625   /// to each vector element of Val. The sequence starts at StartIndex.
626   /// \p Opcode is relevant for FP induction variable.
627   virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
628                                Instruction::BinaryOps Opcode =
629                                Instruction::BinaryOpsEnd);
630 
631   /// Compute scalar induction steps. \p ScalarIV is the scalar induction
632   /// variable on which to base the steps, \p Step is the size of the step, and
633   /// \p EntryVal is the value from the original loop that maps to the steps.
634   /// Note that \p EntryVal doesn't have to be an induction variable - it
635   /// can also be a truncate instruction.
636   void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
637                         const InductionDescriptor &ID, VPValue *Def,
638                         VPValue *CastDef, VPTransformState &State);
639 
640   /// Create a vector induction phi node based on an existing scalar one. \p
641   /// EntryVal is the value from the original loop that maps to the vector phi
642   /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
643   /// truncate instruction, instead of widening the original IV, we widen a
644   /// version of the IV truncated to \p EntryVal's type.
645   void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
646                                        Value *Step, Value *Start,
647                                        Instruction *EntryVal, VPValue *Def,
648                                        VPValue *CastDef,
649                                        VPTransformState &State);
650 
651   /// Returns true if an instruction \p I should be scalarized instead of
652   /// vectorized for the chosen vectorization factor.
653   bool shouldScalarizeInstruction(Instruction *I) const;
654 
655   /// Returns true if we should generate a scalar version of \p IV.
656   bool needsScalarInduction(Instruction *IV) const;
657 
658   /// If there is a cast involved in the induction variable \p ID, which should
659   /// be ignored in the vectorized loop body, this function records the
660   /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
661   /// cast. We had already proved that the casted Phi is equal to the uncasted
662   /// Phi in the vectorized loop (under a runtime guard), and therefore
663   /// there is no need to vectorize the cast - the same value can be used in the
664   /// vector loop for both the Phi and the cast.
665   /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
666   /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
667   ///
668   /// \p EntryVal is the value from the original loop that maps to the vector
669   /// phi node and is used to distinguish what is the IV currently being
670   /// processed - original one (if \p EntryVal is a phi corresponding to the
671   /// original IV) or the "newly-created" one based on the proof mentioned above
672   /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
673   /// latter case \p EntryVal is a TruncInst and we must not record anything for
674   /// that IV, but it's error-prone to expect callers of this routine to care
675   /// about that, hence this explicit parameter.
676   void recordVectorLoopValueForInductionCast(
677       const InductionDescriptor &ID, const Instruction *EntryVal,
678       Value *VectorLoopValue, VPValue *CastDef, VPTransformState &State,
679       unsigned Part, unsigned Lane = UINT_MAX);
680 
681   /// Generate a shuffle sequence that will reverse the vector Vec.
682   virtual Value *reverseVector(Value *Vec);
683 
684   /// Returns (and creates if needed) the original loop trip count.
685   Value *getOrCreateTripCount(Loop *NewLoop);
686 
687   /// Returns (and creates if needed) the trip count of the widened loop.
688   Value *getOrCreateVectorTripCount(Loop *NewLoop);
689 
690   /// Returns a bitcasted value to the requested vector type.
691   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
692   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
693                                 const DataLayout &DL);
694 
695   /// Emit a bypass check to see if the vector trip count is zero, including if
696   /// it overflows.
697   void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
698 
699   /// Emit a bypass check to see if all of the SCEV assumptions we've
700   /// had to make are correct. Returns the block containing the checks or
701   /// nullptr if no checks have been added.
702   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass);
703 
704   /// Emit bypass checks to check any memory assumptions we may have made.
705   /// Returns the block containing the checks or nullptr if no checks have been
706   /// added.
707   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
708 
709   /// Compute the transformed value of Index at offset StartValue using step
710   /// StepValue.
711   /// For integer induction, returns StartValue + Index * StepValue.
712   /// For pointer induction, returns StartValue[Index * StepValue].
713   /// FIXME: The newly created binary instructions should contain nsw/nuw
714   /// flags, which can be found from the original scalar operations.
715   Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
716                               const DataLayout &DL,
717                               const InductionDescriptor &ID) const;
718 
719   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
720   /// vector loop preheader, middle block and scalar preheader. Also
721   /// allocate a loop object for the new vector loop and return it.
722   Loop *createVectorLoopSkeleton(StringRef Prefix);
723 
724   /// Create new phi nodes for the induction variables to resume iteration count
725   /// in the scalar epilogue, from where the vectorized loop left off (given by
726   /// \p VectorTripCount).
727   /// In cases where the loop skeleton is more complicated (eg. epilogue
728   /// vectorization) and the resume values can come from an additional bypass
729   /// block, the \p AdditionalBypass pair provides information about the bypass
730   /// block and the end value on the edge from bypass to this loop.
731   void createInductionResumeValues(
732       Loop *L, Value *VectorTripCount,
733       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
734 
735   /// Complete the loop skeleton by adding debug MDs, creating appropriate
736   /// conditional branches in the middle block, preparing the builder and
737   /// running the verifier. Take in the vector loop \p L as argument, and return
738   /// the preheader of the completed vector loop.
739   BasicBlock *completeLoopSkeleton(Loop *L, MDNode *OrigLoopID);
740 
741   /// Add additional metadata to \p To that was not present on \p Orig.
742   ///
743   /// Currently this is used to add the noalias annotations based on the
744   /// inserted memchecks.  Use this for instructions that are *cloned* into the
745   /// vector loop.
746   void addNewMetadata(Instruction *To, const Instruction *Orig);
747 
748   /// Add metadata from one instruction to another.
749   ///
750   /// This includes both the original MDs from \p From and additional ones (\see
751   /// addNewMetadata).  Use this for *newly created* instructions in the vector
752   /// loop.
753   void addMetadata(Instruction *To, Instruction *From);
754 
755   /// Similar to the previous function but it adds the metadata to a
756   /// vector of instructions.
757   void addMetadata(ArrayRef<Value *> To, Instruction *From);
758 
759   /// Allow subclasses to override and print debug traces before/after vplan
760   /// execution, when trace information is requested.
761   virtual void printDebugTracesAtStart(){};
762   virtual void printDebugTracesAtEnd(){};
763 
764   /// The original loop.
765   Loop *OrigLoop;
766 
767   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
768   /// dynamic knowledge to simplify SCEV expressions and converts them to a
769   /// more usable form.
770   PredicatedScalarEvolution &PSE;
771 
772   /// Loop Info.
773   LoopInfo *LI;
774 
775   /// Dominator Tree.
776   DominatorTree *DT;
777 
778   /// Alias Analysis.
779   AAResults *AA;
780 
781   /// Target Library Info.
782   const TargetLibraryInfo *TLI;
783 
784   /// Target Transform Info.
785   const TargetTransformInfo *TTI;
786 
787   /// Assumption Cache.
788   AssumptionCache *AC;
789 
790   /// Interface to emit optimization remarks.
791   OptimizationRemarkEmitter *ORE;
792 
793   /// LoopVersioning.  It's only set up (non-null) if memchecks were
794   /// used.
795   ///
796   /// This is currently only used to add no-alias metadata based on the
797   /// memchecks.  The actually versioning is performed manually.
798   std::unique_ptr<LoopVersioning> LVer;
799 
800   /// The vectorization SIMD factor to use. Each vector will have this many
801   /// vector elements.
802   ElementCount VF;
803 
804   /// The vectorization unroll factor to use. Each scalar is vectorized to this
805   /// many different vector instructions.
806   unsigned UF;
807 
808   /// The builder that we use
809   IRBuilder<> Builder;
810 
811   // --- Vectorization state ---
812 
813   /// The vector-loop preheader.
814   BasicBlock *LoopVectorPreHeader;
815 
816   /// The scalar-loop preheader.
817   BasicBlock *LoopScalarPreHeader;
818 
819   /// Middle Block between the vector and the scalar.
820   BasicBlock *LoopMiddleBlock;
821 
822   /// The (unique) ExitBlock of the scalar loop.  Note that
823   /// there can be multiple exiting edges reaching this block.
824   BasicBlock *LoopExitBlock;
825 
826   /// The vector loop body.
827   BasicBlock *LoopVectorBody;
828 
829   /// The scalar loop body.
830   BasicBlock *LoopScalarBody;
831 
832   /// A list of all bypass blocks. The first block is the entry of the loop.
833   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
834 
835   /// The new Induction variable which was added to the new block.
836   PHINode *Induction = nullptr;
837 
838   /// The induction variable of the old basic block.
839   PHINode *OldInduction = nullptr;
840 
841   /// Store instructions that were predicated.
842   SmallVector<Instruction *, 4> PredicatedInstructions;
843 
844   /// Trip count of the original loop.
845   Value *TripCount = nullptr;
846 
847   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
848   Value *VectorTripCount = nullptr;
849 
850   /// The legality analysis.
851   LoopVectorizationLegality *Legal;
852 
853   /// The profitablity analysis.
854   LoopVectorizationCostModel *Cost;
855 
856   // Record whether runtime checks are added.
857   bool AddedSafetyChecks = false;
858 
859   // Holds the end values for each induction variable. We save the end values
860   // so we can later fix-up the external users of the induction variables.
861   DenseMap<PHINode *, Value *> IVEndValues;
862 
863   // Vector of original scalar PHIs whose corresponding widened PHIs need to be
864   // fixed up at the end of vector code generation.
865   SmallVector<PHINode *, 8> OrigPHIsToFix;
866 
867   /// BFI and PSI are used to check for profile guided size optimizations.
868   BlockFrequencyInfo *BFI;
869   ProfileSummaryInfo *PSI;
870 
871   // Whether this loop should be optimized for size based on profile guided size
872   // optimizatios.
873   bool OptForSizeBasedOnProfile;
874 
875   /// Structure to hold information about generated runtime checks, responsible
876   /// for cleaning the checks, if vectorization turns out unprofitable.
877   GeneratedRTChecks &RTChecks;
878 };
879 
880 class InnerLoopUnroller : public InnerLoopVectorizer {
881 public:
882   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
883                     LoopInfo *LI, DominatorTree *DT,
884                     const TargetLibraryInfo *TLI,
885                     const TargetTransformInfo *TTI, AssumptionCache *AC,
886                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
887                     LoopVectorizationLegality *LVL,
888                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
889                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
890       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
891                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
892                             BFI, PSI, Check) {}
893 
894 private:
895   Value *getBroadcastInstrs(Value *V) override;
896   Value *getStepVector(Value *Val, int StartIdx, Value *Step,
897                        Instruction::BinaryOps Opcode =
898                        Instruction::BinaryOpsEnd) override;
899   Value *reverseVector(Value *Vec) override;
900 };
901 
902 /// Encapsulate information regarding vectorization of a loop and its epilogue.
903 /// This information is meant to be updated and used across two stages of
904 /// epilogue vectorization.
905 struct EpilogueLoopVectorizationInfo {
906   ElementCount MainLoopVF = ElementCount::getFixed(0);
907   unsigned MainLoopUF = 0;
908   ElementCount EpilogueVF = ElementCount::getFixed(0);
909   unsigned EpilogueUF = 0;
910   BasicBlock *MainLoopIterationCountCheck = nullptr;
911   BasicBlock *EpilogueIterationCountCheck = nullptr;
912   BasicBlock *SCEVSafetyCheck = nullptr;
913   BasicBlock *MemSafetyCheck = nullptr;
914   Value *TripCount = nullptr;
915   Value *VectorTripCount = nullptr;
916 
917   EpilogueLoopVectorizationInfo(unsigned MVF, unsigned MUF, unsigned EVF,
918                                 unsigned EUF)
919       : MainLoopVF(ElementCount::getFixed(MVF)), MainLoopUF(MUF),
920         EpilogueVF(ElementCount::getFixed(EVF)), EpilogueUF(EUF) {
921     assert(EUF == 1 &&
922            "A high UF for the epilogue loop is likely not beneficial.");
923   }
924 };
925 
926 /// An extension of the inner loop vectorizer that creates a skeleton for a
927 /// vectorized loop that has its epilogue (residual) also vectorized.
928 /// The idea is to run the vplan on a given loop twice, firstly to setup the
929 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
930 /// from the first step and vectorize the epilogue.  This is achieved by
931 /// deriving two concrete strategy classes from this base class and invoking
932 /// them in succession from the loop vectorizer planner.
933 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
934 public:
935   InnerLoopAndEpilogueVectorizer(
936       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
937       DominatorTree *DT, const TargetLibraryInfo *TLI,
938       const TargetTransformInfo *TTI, AssumptionCache *AC,
939       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
940       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
941       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
942       GeneratedRTChecks &Checks)
943       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
944                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
945                             Checks),
946         EPI(EPI) {}
947 
948   // Override this function to handle the more complex control flow around the
949   // three loops.
950   BasicBlock *createVectorizedLoopSkeleton() final override {
951     return createEpilogueVectorizedLoopSkeleton();
952   }
953 
954   /// The interface for creating a vectorized skeleton using one of two
955   /// different strategies, each corresponding to one execution of the vplan
956   /// as described above.
957   virtual BasicBlock *createEpilogueVectorizedLoopSkeleton() = 0;
958 
959   /// Holds and updates state information required to vectorize the main loop
960   /// and its epilogue in two separate passes. This setup helps us avoid
961   /// regenerating and recomputing runtime safety checks. It also helps us to
962   /// shorten the iteration-count-check path length for the cases where the
963   /// iteration count of the loop is so small that the main vector loop is
964   /// completely skipped.
965   EpilogueLoopVectorizationInfo &EPI;
966 };
967 
968 /// A specialized derived class of inner loop vectorizer that performs
969 /// vectorization of *main* loops in the process of vectorizing loops and their
970 /// epilogues.
971 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
972 public:
973   EpilogueVectorizerMainLoop(
974       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
975       DominatorTree *DT, const TargetLibraryInfo *TLI,
976       const TargetTransformInfo *TTI, AssumptionCache *AC,
977       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
978       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
979       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
980       GeneratedRTChecks &Check)
981       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
982                                        EPI, LVL, CM, BFI, PSI, Check) {}
983   /// Implements the interface for creating a vectorized skeleton using the
984   /// *main loop* strategy (ie the first pass of vplan execution).
985   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
986 
987 protected:
988   /// Emits an iteration count bypass check once for the main loop (when \p
989   /// ForEpilogue is false) and once for the epilogue loop (when \p
990   /// ForEpilogue is true).
991   BasicBlock *emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass,
992                                              bool ForEpilogue);
993   void printDebugTracesAtStart() override;
994   void printDebugTracesAtEnd() override;
995 };
996 
997 // A specialized derived class of inner loop vectorizer that performs
998 // vectorization of *epilogue* loops in the process of vectorizing loops and
999 // their epilogues.
1000 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
1001 public:
1002   EpilogueVectorizerEpilogueLoop(
1003       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
1004       DominatorTree *DT, const TargetLibraryInfo *TLI,
1005       const TargetTransformInfo *TTI, AssumptionCache *AC,
1006       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
1007       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
1008       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
1009       GeneratedRTChecks &Checks)
1010       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
1011                                        EPI, LVL, CM, BFI, PSI, Checks) {}
1012   /// Implements the interface for creating a vectorized skeleton using the
1013   /// *epilogue loop* strategy (ie the second pass of vplan execution).
1014   BasicBlock *createEpilogueVectorizedLoopSkeleton() final override;
1015 
1016 protected:
1017   /// Emits an iteration count bypass check after the main vector loop has
1018   /// finished to see if there are any iterations left to execute by either
1019   /// the vector epilogue or the scalar epilogue.
1020   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(Loop *L,
1021                                                       BasicBlock *Bypass,
1022                                                       BasicBlock *Insert);
1023   void printDebugTracesAtStart() override;
1024   void printDebugTracesAtEnd() override;
1025 };
1026 } // end namespace llvm
1027 
1028 /// Look for a meaningful debug location on the instruction or it's
1029 /// operands.
1030 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
1031   if (!I)
1032     return I;
1033 
1034   DebugLoc Empty;
1035   if (I->getDebugLoc() != Empty)
1036     return I;
1037 
1038   for (Use &Op : I->operands()) {
1039     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
1040       if (OpInst->getDebugLoc() != Empty)
1041         return OpInst;
1042   }
1043 
1044   return I;
1045 }
1046 
1047 void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
1048   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
1049     const DILocation *DIL = Inst->getDebugLoc();
1050     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
1051         !isa<DbgInfoIntrinsic>(Inst)) {
1052       assert(!VF.isScalable() && "scalable vectors not yet supported.");
1053       auto NewDIL =
1054           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
1055       if (NewDIL)
1056         B.SetCurrentDebugLocation(NewDIL.getValue());
1057       else
1058         LLVM_DEBUG(dbgs()
1059                    << "Failed to create new discriminator: "
1060                    << DIL->getFilename() << " Line: " << DIL->getLine());
1061     }
1062     else
1063       B.SetCurrentDebugLocation(DIL);
1064   } else
1065     B.SetCurrentDebugLocation(DebugLoc());
1066 }
1067 
1068 /// Write a record \p DebugMsg about vectorization failure to the debug
1069 /// output stream. If \p I is passed, it is an instruction that prevents
1070 /// vectorization.
1071 #ifndef NDEBUG
1072 static void debugVectorizationFailure(const StringRef DebugMsg,
1073     Instruction *I) {
1074   dbgs() << "LV: Not vectorizing: " << DebugMsg;
1075   if (I != nullptr)
1076     dbgs() << " " << *I;
1077   else
1078     dbgs() << '.';
1079   dbgs() << '\n';
1080 }
1081 #endif
1082 
1083 /// Create an analysis remark that explains why vectorization failed
1084 ///
1085 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
1086 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
1087 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
1088 /// the location of the remark.  \return the remark object that can be
1089 /// streamed to.
1090 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
1091     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
1092   Value *CodeRegion = TheLoop->getHeader();
1093   DebugLoc DL = TheLoop->getStartLoc();
1094 
1095   if (I) {
1096     CodeRegion = I->getParent();
1097     // If there is no debug location attached to the instruction, revert back to
1098     // using the loop's.
1099     if (I->getDebugLoc())
1100       DL = I->getDebugLoc();
1101   }
1102 
1103   OptimizationRemarkAnalysis R(PassName, RemarkName, DL, CodeRegion);
1104   R << "loop not vectorized: ";
1105   return R;
1106 }
1107 
1108 /// Return a value for Step multiplied by VF.
1109 static Value *createStepForVF(IRBuilder<> &B, Constant *Step, ElementCount VF) {
1110   assert(isa<ConstantInt>(Step) && "Expected an integer step");
1111   Constant *StepVal = ConstantInt::get(
1112       Step->getType(),
1113       cast<ConstantInt>(Step)->getSExtValue() * VF.getKnownMinValue());
1114   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
1115 }
1116 
1117 namespace llvm {
1118 
1119 /// Return the runtime value for VF.
1120 Value *getRuntimeVF(IRBuilder<> &B, Type *Ty, ElementCount VF) {
1121   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
1122   return VF.isScalable() ? B.CreateVScale(EC) : EC;
1123 }
1124 
1125 void reportVectorizationFailure(const StringRef DebugMsg,
1126     const StringRef OREMsg, const StringRef ORETag,
1127     OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I) {
1128   LLVM_DEBUG(debugVectorizationFailure(DebugMsg, I));
1129   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1130   ORE->emit(createLVAnalysis(Hints.vectorizeAnalysisPassName(),
1131                 ORETag, TheLoop, I) << OREMsg);
1132 }
1133 
1134 } // end namespace llvm
1135 
1136 #ifndef NDEBUG
1137 /// \return string containing a file name and a line # for the given loop.
1138 static std::string getDebugLocString(const Loop *L) {
1139   std::string Result;
1140   if (L) {
1141     raw_string_ostream OS(Result);
1142     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1143       LoopDbgLoc.print(OS);
1144     else
1145       // Just print the module name.
1146       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1147     OS.flush();
1148   }
1149   return Result;
1150 }
1151 #endif
1152 
1153 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1154                                          const Instruction *Orig) {
1155   // If the loop was versioned with memchecks, add the corresponding no-alias
1156   // metadata.
1157   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1158     LVer->annotateInstWithNoAlias(To, Orig);
1159 }
1160 
1161 void InnerLoopVectorizer::addMetadata(Instruction *To,
1162                                       Instruction *From) {
1163   propagateMetadata(To, From);
1164   addNewMetadata(To, From);
1165 }
1166 
1167 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1168                                       Instruction *From) {
1169   for (Value *V : To) {
1170     if (Instruction *I = dyn_cast<Instruction>(V))
1171       addMetadata(I, From);
1172   }
1173 }
1174 
1175 namespace llvm {
1176 
1177 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1178 // lowered.
1179 enum ScalarEpilogueLowering {
1180 
1181   // The default: allowing scalar epilogues.
1182   CM_ScalarEpilogueAllowed,
1183 
1184   // Vectorization with OptForSize: don't allow epilogues.
1185   CM_ScalarEpilogueNotAllowedOptSize,
1186 
1187   // A special case of vectorisation with OptForSize: loops with a very small
1188   // trip count are considered for vectorization under OptForSize, thereby
1189   // making sure the cost of their loop body is dominant, free of runtime
1190   // guards and scalar iteration overheads.
1191   CM_ScalarEpilogueNotAllowedLowTripLoop,
1192 
1193   // Loop hint predicate indicating an epilogue is undesired.
1194   CM_ScalarEpilogueNotNeededUsePredicate,
1195 
1196   // Directive indicating we must either tail fold or not vectorize
1197   CM_ScalarEpilogueNotAllowedUsePredicate
1198 };
1199 
1200 /// LoopVectorizationCostModel - estimates the expected speedups due to
1201 /// vectorization.
1202 /// In many cases vectorization is not profitable. This can happen because of
1203 /// a number of reasons. In this class we mainly attempt to predict the
1204 /// expected speedup/slowdowns due to the supported instruction set. We use the
1205 /// TargetTransformInfo to query the different backends for the cost of
1206 /// different operations.
1207 class LoopVectorizationCostModel {
1208 public:
1209   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1210                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1211                              LoopVectorizationLegality *Legal,
1212                              const TargetTransformInfo &TTI,
1213                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1214                              AssumptionCache *AC,
1215                              OptimizationRemarkEmitter *ORE, const Function *F,
1216                              const LoopVectorizeHints *Hints,
1217                              InterleavedAccessInfo &IAI)
1218       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1219         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1220         Hints(Hints), InterleaveInfo(IAI) {}
1221 
1222   /// \return An upper bound for the vectorization factor, or None if
1223   /// vectorization and interleaving should be avoided up front.
1224   Optional<ElementCount> computeMaxVF(ElementCount UserVF, unsigned UserIC);
1225 
1226   /// \return True if runtime checks are required for vectorization, and false
1227   /// otherwise.
1228   bool runtimeChecksRequired();
1229 
1230   /// \return The most profitable vectorization factor and the cost of that VF.
1231   /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
1232   /// then this vectorization factor will be selected if vectorization is
1233   /// possible.
1234   VectorizationFactor selectVectorizationFactor(ElementCount MaxVF);
1235   VectorizationFactor
1236   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1237                                     const LoopVectorizationPlanner &LVP);
1238 
1239   /// Setup cost-based decisions for user vectorization factor.
1240   void selectUserVectorizationFactor(ElementCount UserVF) {
1241     collectUniformsAndScalars(UserVF);
1242     collectInstsToScalarize(UserVF);
1243   }
1244 
1245   /// \return The size (in bits) of the smallest and widest types in the code
1246   /// that needs to be vectorized. We ignore values that remain scalar such as
1247   /// 64 bit loop indices.
1248   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1249 
1250   /// \return The desired interleave count.
1251   /// If interleave count has been specified by metadata it will be returned.
1252   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1253   /// are the selected vectorization factor and the cost of the selected VF.
1254   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1255 
1256   /// Memory access instruction may be vectorized in more than one way.
1257   /// Form of instruction after vectorization depends on cost.
1258   /// This function takes cost-based decisions for Load/Store instructions
1259   /// and collects them in a map. This decisions map is used for building
1260   /// the lists of loop-uniform and loop-scalar instructions.
1261   /// The calculated cost is saved with widening decision in order to
1262   /// avoid redundant calculations.
1263   void setCostBasedWideningDecision(ElementCount VF);
1264 
1265   /// A struct that represents some properties of the register usage
1266   /// of a loop.
1267   struct RegisterUsage {
1268     /// Holds the number of loop invariant values that are used in the loop.
1269     /// The key is ClassID of target-provided register class.
1270     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1271     /// Holds the maximum number of concurrent live intervals in the loop.
1272     /// The key is ClassID of target-provided register class.
1273     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1274   };
1275 
1276   /// \return Returns information about the register usages of the loop for the
1277   /// given vectorization factors.
1278   SmallVector<RegisterUsage, 8>
1279   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1280 
1281   /// Collect values we want to ignore in the cost model.
1282   void collectValuesToIgnore();
1283 
1284   /// Split reductions into those that happen in the loop, and those that happen
1285   /// outside. In loop reductions are collected into InLoopReductionChains.
1286   void collectInLoopReductions();
1287 
1288   /// \returns The smallest bitwidth each instruction can be represented with.
1289   /// The vector equivalents of these instructions should be truncated to this
1290   /// type.
1291   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1292     return MinBWs;
1293   }
1294 
1295   /// \returns True if it is more profitable to scalarize instruction \p I for
1296   /// vectorization factor \p VF.
1297   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1298     assert(VF.isVector() &&
1299            "Profitable to scalarize relevant only for VF > 1.");
1300 
1301     // Cost model is not run in the VPlan-native path - return conservative
1302     // result until this changes.
1303     if (EnableVPlanNativePath)
1304       return false;
1305 
1306     auto Scalars = InstsToScalarize.find(VF);
1307     assert(Scalars != InstsToScalarize.end() &&
1308            "VF not yet analyzed for scalarization profitability");
1309     return Scalars->second.find(I) != Scalars->second.end();
1310   }
1311 
1312   /// Returns true if \p I is known to be uniform after vectorization.
1313   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1314     if (VF.isScalar())
1315       return true;
1316 
1317     // Cost model is not run in the VPlan-native path - return conservative
1318     // result until this changes.
1319     if (EnableVPlanNativePath)
1320       return false;
1321 
1322     auto UniformsPerVF = Uniforms.find(VF);
1323     assert(UniformsPerVF != Uniforms.end() &&
1324            "VF not yet analyzed for uniformity");
1325     return UniformsPerVF->second.count(I);
1326   }
1327 
1328   /// Returns true if \p I is known to be scalar after vectorization.
1329   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1330     if (VF.isScalar())
1331       return true;
1332 
1333     // Cost model is not run in the VPlan-native path - return conservative
1334     // result until this changes.
1335     if (EnableVPlanNativePath)
1336       return false;
1337 
1338     auto ScalarsPerVF = Scalars.find(VF);
1339     assert(ScalarsPerVF != Scalars.end() &&
1340            "Scalar values are not calculated for VF");
1341     return ScalarsPerVF->second.count(I);
1342   }
1343 
1344   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1345   /// for vectorization factor \p VF.
1346   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1347     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1348            !isProfitableToScalarize(I, VF) &&
1349            !isScalarAfterVectorization(I, VF);
1350   }
1351 
1352   /// Decision that was taken during cost calculation for memory instruction.
1353   enum InstWidening {
1354     CM_Unknown,
1355     CM_Widen,         // For consecutive accesses with stride +1.
1356     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1357     CM_Interleave,
1358     CM_GatherScatter,
1359     CM_Scalarize
1360   };
1361 
1362   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1363   /// instruction \p I and vector width \p VF.
1364   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1365                            InstructionCost Cost) {
1366     assert(VF.isVector() && "Expected VF >=2");
1367     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1368   }
1369 
1370   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1371   /// interleaving group \p Grp and vector width \p VF.
1372   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1373                            ElementCount VF, InstWidening W,
1374                            InstructionCost Cost) {
1375     assert(VF.isVector() && "Expected VF >=2");
1376     /// Broadcast this decicion to all instructions inside the group.
1377     /// But the cost will be assigned to one instruction only.
1378     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1379       if (auto *I = Grp->getMember(i)) {
1380         if (Grp->getInsertPos() == I)
1381           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1382         else
1383           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1384       }
1385     }
1386   }
1387 
1388   /// Return the cost model decision for the given instruction \p I and vector
1389   /// width \p VF. Return CM_Unknown if this instruction did not pass
1390   /// through the cost modeling.
1391   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1392     assert(VF.isVector() && "Expected VF to be a vector VF");
1393     // Cost model is not run in the VPlan-native path - return conservative
1394     // result until this changes.
1395     if (EnableVPlanNativePath)
1396       return CM_GatherScatter;
1397 
1398     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1399     auto Itr = WideningDecisions.find(InstOnVF);
1400     if (Itr == WideningDecisions.end())
1401       return CM_Unknown;
1402     return Itr->second.first;
1403   }
1404 
1405   /// Return the vectorization cost for the given instruction \p I and vector
1406   /// width \p VF.
1407   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1408     assert(VF.isVector() && "Expected VF >=2");
1409     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1410     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1411            "The cost is not calculated");
1412     return WideningDecisions[InstOnVF].second;
1413   }
1414 
1415   /// Return True if instruction \p I is an optimizable truncate whose operand
1416   /// is an induction variable. Such a truncate will be removed by adding a new
1417   /// induction variable with the destination type.
1418   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1419     // If the instruction is not a truncate, return false.
1420     auto *Trunc = dyn_cast<TruncInst>(I);
1421     if (!Trunc)
1422       return false;
1423 
1424     // Get the source and destination types of the truncate.
1425     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1426     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1427 
1428     // If the truncate is free for the given types, return false. Replacing a
1429     // free truncate with an induction variable would add an induction variable
1430     // update instruction to each iteration of the loop. We exclude from this
1431     // check the primary induction variable since it will need an update
1432     // instruction regardless.
1433     Value *Op = Trunc->getOperand(0);
1434     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1435       return false;
1436 
1437     // If the truncated value is not an induction variable, return false.
1438     return Legal->isInductionPhi(Op);
1439   }
1440 
1441   /// Collects the instructions to scalarize for each predicated instruction in
1442   /// the loop.
1443   void collectInstsToScalarize(ElementCount VF);
1444 
1445   /// Collect Uniform and Scalar values for the given \p VF.
1446   /// The sets depend on CM decision for Load/Store instructions
1447   /// that may be vectorized as interleave, gather-scatter or scalarized.
1448   void collectUniformsAndScalars(ElementCount VF) {
1449     // Do the analysis once.
1450     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1451       return;
1452     setCostBasedWideningDecision(VF);
1453     collectLoopUniforms(VF);
1454     collectLoopScalars(VF);
1455   }
1456 
1457   /// Returns true if the target machine supports masked store operation
1458   /// for the given \p DataType and kind of access to \p Ptr.
1459   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1460     return Legal->isConsecutivePtr(Ptr) &&
1461            TTI.isLegalMaskedStore(DataType, Alignment);
1462   }
1463 
1464   /// Returns true if the target machine supports masked load operation
1465   /// for the given \p DataType and kind of access to \p Ptr.
1466   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1467     return Legal->isConsecutivePtr(Ptr) &&
1468            TTI.isLegalMaskedLoad(DataType, Alignment);
1469   }
1470 
1471   /// Returns true if the target machine supports masked scatter operation
1472   /// for the given \p DataType.
1473   bool isLegalMaskedScatter(Type *DataType, Align Alignment) const {
1474     return TTI.isLegalMaskedScatter(DataType, Alignment);
1475   }
1476 
1477   /// Returns true if the target machine supports masked gather operation
1478   /// for the given \p DataType.
1479   bool isLegalMaskedGather(Type *DataType, Align Alignment) const {
1480     return TTI.isLegalMaskedGather(DataType, Alignment);
1481   }
1482 
1483   /// Returns true if the target machine can represent \p V as a masked gather
1484   /// or scatter operation.
1485   bool isLegalGatherOrScatter(Value *V) {
1486     bool LI = isa<LoadInst>(V);
1487     bool SI = isa<StoreInst>(V);
1488     if (!LI && !SI)
1489       return false;
1490     auto *Ty = getMemInstValueType(V);
1491     Align Align = getLoadStoreAlignment(V);
1492     return (LI && isLegalMaskedGather(Ty, Align)) ||
1493            (SI && isLegalMaskedScatter(Ty, Align));
1494   }
1495 
1496   /// Returns true if the target machine supports all of the reduction
1497   /// variables found for the given VF.
1498   bool canVectorizeReductions(ElementCount VF) {
1499     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1500       RecurrenceDescriptor RdxDesc = Reduction.second;
1501       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1502     }));
1503   }
1504 
1505   /// Returns true if \p I is an instruction that will be scalarized with
1506   /// predication. Such instructions include conditional stores and
1507   /// instructions that may divide by zero.
1508   /// If a non-zero VF has been calculated, we check if I will be scalarized
1509   /// predication for that VF.
1510   bool
1511   isScalarWithPredication(Instruction *I,
1512                           ElementCount VF = ElementCount::getFixed(1)) const;
1513 
1514   // Returns true if \p I is an instruction that will be predicated either
1515   // through scalar predication or masked load/store or masked gather/scatter.
1516   // Superset of instructions that return true for isScalarWithPredication.
1517   bool isPredicatedInst(Instruction *I, ElementCount VF) {
1518     if (!blockNeedsPredication(I->getParent()))
1519       return false;
1520     // Loads and stores that need some form of masked operation are predicated
1521     // instructions.
1522     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1523       return Legal->isMaskRequired(I);
1524     return isScalarWithPredication(I, VF);
1525   }
1526 
1527   /// Returns true if \p I is a memory instruction with consecutive memory
1528   /// access that can be widened.
1529   bool
1530   memoryInstructionCanBeWidened(Instruction *I,
1531                                 ElementCount VF = ElementCount::getFixed(1));
1532 
1533   /// Returns true if \p I is a memory instruction in an interleaved-group
1534   /// of memory accesses that can be vectorized with wide vector loads/stores
1535   /// and shuffles.
1536   bool
1537   interleavedAccessCanBeWidened(Instruction *I,
1538                                 ElementCount VF = ElementCount::getFixed(1));
1539 
1540   /// Check if \p Instr belongs to any interleaved access group.
1541   bool isAccessInterleaved(Instruction *Instr) {
1542     return InterleaveInfo.isInterleaved(Instr);
1543   }
1544 
1545   /// Get the interleaved access group that \p Instr belongs to.
1546   const InterleaveGroup<Instruction> *
1547   getInterleavedAccessGroup(Instruction *Instr) {
1548     return InterleaveInfo.getInterleaveGroup(Instr);
1549   }
1550 
1551   /// Returns true if we're required to use a scalar epilogue for at least
1552   /// the final iteration of the original loop.
1553   bool requiresScalarEpilogue() const {
1554     if (!isScalarEpilogueAllowed())
1555       return false;
1556     // If we might exit from anywhere but the latch, must run the exiting
1557     // iteration in scalar form.
1558     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1559       return true;
1560     return InterleaveInfo.requiresScalarEpilogue();
1561   }
1562 
1563   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1564   /// loop hint annotation.
1565   bool isScalarEpilogueAllowed() const {
1566     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1567   }
1568 
1569   /// Returns true if all loop blocks should be masked to fold tail loop.
1570   bool foldTailByMasking() const { return FoldTailByMasking; }
1571 
1572   bool blockNeedsPredication(BasicBlock *BB) const {
1573     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1574   }
1575 
1576   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1577   /// nodes to the chain of instructions representing the reductions. Uses a
1578   /// MapVector to ensure deterministic iteration order.
1579   using ReductionChainMap =
1580       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1581 
1582   /// Return the chain of instructions representing an inloop reduction.
1583   const ReductionChainMap &getInLoopReductionChains() const {
1584     return InLoopReductionChains;
1585   }
1586 
1587   /// Returns true if the Phi is part of an inloop reduction.
1588   bool isInLoopReduction(PHINode *Phi) const {
1589     return InLoopReductionChains.count(Phi);
1590   }
1591 
1592   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1593   /// with factor VF.  Return the cost of the instruction, including
1594   /// scalarization overhead if it's needed.
1595   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1596 
1597   /// Estimate cost of a call instruction CI if it were vectorized with factor
1598   /// VF. Return the cost of the instruction, including scalarization overhead
1599   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1600   /// scalarized -
1601   /// i.e. either vector version isn't available, or is too expensive.
1602   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1603                                     bool &NeedToScalarize) const;
1604 
1605   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1606   /// that of B.
1607   bool isMoreProfitable(const VectorizationFactor &A,
1608                         const VectorizationFactor &B) const;
1609 
1610   /// Invalidates decisions already taken by the cost model.
1611   void invalidateCostModelingDecisions() {
1612     WideningDecisions.clear();
1613     Uniforms.clear();
1614     Scalars.clear();
1615   }
1616 
1617 private:
1618   unsigned NumPredStores = 0;
1619 
1620   /// \return An upper bound for the vectorization factor, a power-of-2 larger
1621   /// than zero. One is returned if vectorization should best be avoided due
1622   /// to cost.
1623   ElementCount computeFeasibleMaxVF(unsigned ConstTripCount,
1624                                     ElementCount UserVF);
1625 
1626   /// The vectorization cost is a combination of the cost itself and a boolean
1627   /// indicating whether any of the contributing operations will actually
1628   /// operate on
1629   /// vector values after type legalization in the backend. If this latter value
1630   /// is
1631   /// false, then all operations will be scalarized (i.e. no vectorization has
1632   /// actually taken place).
1633   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1634 
1635   /// Returns the expected execution cost. The unit of the cost does
1636   /// not matter because we use the 'cost' units to compare different
1637   /// vector widths. The cost that is returned is *not* normalized by
1638   /// the factor width.
1639   VectorizationCostTy expectedCost(ElementCount VF);
1640 
1641   /// Returns the execution time cost of an instruction for a given vector
1642   /// width. Vector width of one means scalar.
1643   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1644 
1645   /// The cost-computation logic from getInstructionCost which provides
1646   /// the vector type as an output parameter.
1647   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1648                                      Type *&VectorTy);
1649 
1650   /// Return the cost of instructions in an inloop reduction pattern, if I is
1651   /// part of that pattern.
1652   InstructionCost getReductionPatternCost(Instruction *I, ElementCount VF,
1653                                           Type *VectorTy,
1654                                           TTI::TargetCostKind CostKind);
1655 
1656   /// Calculate vectorization cost of memory instruction \p I.
1657   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1658 
1659   /// The cost computation for scalarized memory instruction.
1660   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1661 
1662   /// The cost computation for interleaving group of memory instructions.
1663   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1664 
1665   /// The cost computation for Gather/Scatter instruction.
1666   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1667 
1668   /// The cost computation for widening instruction \p I with consecutive
1669   /// memory access.
1670   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1671 
1672   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1673   /// Load: scalar load + broadcast.
1674   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1675   /// element)
1676   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1677 
1678   /// Estimate the overhead of scalarizing an instruction. This is a
1679   /// convenience wrapper for the type-based getScalarizationOverhead API.
1680   InstructionCost getScalarizationOverhead(Instruction *I,
1681                                            ElementCount VF) const;
1682 
1683   /// Returns whether the instruction is a load or store and will be a emitted
1684   /// as a vector operation.
1685   bool isConsecutiveLoadOrStore(Instruction *I);
1686 
1687   /// Returns true if an artificially high cost for emulated masked memrefs
1688   /// should be used.
1689   bool useEmulatedMaskMemRefHack(Instruction *I);
1690 
1691   /// Map of scalar integer values to the smallest bitwidth they can be legally
1692   /// represented as. The vector equivalents of these values should be truncated
1693   /// to this type.
1694   MapVector<Instruction *, uint64_t> MinBWs;
1695 
1696   /// A type representing the costs for instructions if they were to be
1697   /// scalarized rather than vectorized. The entries are Instruction-Cost
1698   /// pairs.
1699   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1700 
1701   /// A set containing all BasicBlocks that are known to present after
1702   /// vectorization as a predicated block.
1703   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1704 
1705   /// Records whether it is allowed to have the original scalar loop execute at
1706   /// least once. This may be needed as a fallback loop in case runtime
1707   /// aliasing/dependence checks fail, or to handle the tail/remainder
1708   /// iterations when the trip count is unknown or doesn't divide by the VF,
1709   /// or as a peel-loop to handle gaps in interleave-groups.
1710   /// Under optsize and when the trip count is very small we don't allow any
1711   /// iterations to execute in the scalar loop.
1712   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1713 
1714   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1715   bool FoldTailByMasking = false;
1716 
1717   /// A map holding scalar costs for different vectorization factors. The
1718   /// presence of a cost for an instruction in the mapping indicates that the
1719   /// instruction will be scalarized when vectorizing with the associated
1720   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1721   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1722 
1723   /// Holds the instructions known to be uniform after vectorization.
1724   /// The data is collected per VF.
1725   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1726 
1727   /// Holds the instructions known to be scalar after vectorization.
1728   /// The data is collected per VF.
1729   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1730 
1731   /// Holds the instructions (address computations) that are forced to be
1732   /// scalarized.
1733   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1734 
1735   /// PHINodes of the reductions that should be expanded in-loop along with
1736   /// their associated chains of reduction operations, in program order from top
1737   /// (PHI) to bottom
1738   ReductionChainMap InLoopReductionChains;
1739 
1740   /// A Map of inloop reduction operations and their immediate chain operand.
1741   /// FIXME: This can be removed once reductions can be costed correctly in
1742   /// vplan. This was added to allow quick lookup to the inloop operations,
1743   /// without having to loop through InLoopReductionChains.
1744   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1745 
1746   /// Returns the expected difference in cost from scalarizing the expression
1747   /// feeding a predicated instruction \p PredInst. The instructions to
1748   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1749   /// non-negative return value implies the expression will be scalarized.
1750   /// Currently, only single-use chains are considered for scalarization.
1751   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1752                               ElementCount VF);
1753 
1754   /// Collect the instructions that are uniform after vectorization. An
1755   /// instruction is uniform if we represent it with a single scalar value in
1756   /// the vectorized loop corresponding to each vector iteration. Examples of
1757   /// uniform instructions include pointer operands of consecutive or
1758   /// interleaved memory accesses. Note that although uniformity implies an
1759   /// instruction will be scalar, the reverse is not true. In general, a
1760   /// scalarized instruction will be represented by VF scalar values in the
1761   /// vectorized loop, each corresponding to an iteration of the original
1762   /// scalar loop.
1763   void collectLoopUniforms(ElementCount VF);
1764 
1765   /// Collect the instructions that are scalar after vectorization. An
1766   /// instruction is scalar if it is known to be uniform or will be scalarized
1767   /// during vectorization. Non-uniform scalarized instructions will be
1768   /// represented by VF values in the vectorized loop, each corresponding to an
1769   /// iteration of the original scalar loop.
1770   void collectLoopScalars(ElementCount VF);
1771 
1772   /// Keeps cost model vectorization decision and cost for instructions.
1773   /// Right now it is used for memory instructions only.
1774   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1775                                 std::pair<InstWidening, InstructionCost>>;
1776 
1777   DecisionList WideningDecisions;
1778 
1779   /// Returns true if \p V is expected to be vectorized and it needs to be
1780   /// extracted.
1781   bool needsExtract(Value *V, ElementCount VF) const {
1782     Instruction *I = dyn_cast<Instruction>(V);
1783     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1784         TheLoop->isLoopInvariant(I))
1785       return false;
1786 
1787     // Assume we can vectorize V (and hence we need extraction) if the
1788     // scalars are not computed yet. This can happen, because it is called
1789     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1790     // the scalars are collected. That should be a safe assumption in most
1791     // cases, because we check if the operands have vectorizable types
1792     // beforehand in LoopVectorizationLegality.
1793     return Scalars.find(VF) == Scalars.end() ||
1794            !isScalarAfterVectorization(I, VF);
1795   };
1796 
1797   /// Returns a range containing only operands needing to be extracted.
1798   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1799                                                    ElementCount VF) const {
1800     return SmallVector<Value *, 4>(make_filter_range(
1801         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1802   }
1803 
1804   /// Determines if we have the infrastructure to vectorize loop \p L and its
1805   /// epilogue, assuming the main loop is vectorized by \p VF.
1806   bool isCandidateForEpilogueVectorization(const Loop &L,
1807                                            const ElementCount VF) const;
1808 
1809   /// Returns true if epilogue vectorization is considered profitable, and
1810   /// false otherwise.
1811   /// \p VF is the vectorization factor chosen for the original loop.
1812   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1813 
1814 public:
1815   /// The loop that we evaluate.
1816   Loop *TheLoop;
1817 
1818   /// Predicated scalar evolution analysis.
1819   PredicatedScalarEvolution &PSE;
1820 
1821   /// Loop Info analysis.
1822   LoopInfo *LI;
1823 
1824   /// Vectorization legality.
1825   LoopVectorizationLegality *Legal;
1826 
1827   /// Vector target information.
1828   const TargetTransformInfo &TTI;
1829 
1830   /// Target Library Info.
1831   const TargetLibraryInfo *TLI;
1832 
1833   /// Demanded bits analysis.
1834   DemandedBits *DB;
1835 
1836   /// Assumption cache.
1837   AssumptionCache *AC;
1838 
1839   /// Interface to emit optimization remarks.
1840   OptimizationRemarkEmitter *ORE;
1841 
1842   const Function *TheFunction;
1843 
1844   /// Loop Vectorize Hint.
1845   const LoopVectorizeHints *Hints;
1846 
1847   /// The interleave access information contains groups of interleaved accesses
1848   /// with the same stride and close to each other.
1849   InterleavedAccessInfo &InterleaveInfo;
1850 
1851   /// Values to ignore in the cost model.
1852   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1853 
1854   /// Values to ignore in the cost model when VF > 1.
1855   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1856 
1857   /// Profitable vector factors.
1858   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1859 };
1860 } // end namespace llvm
1861 
1862 /// Helper struct to manage generating runtime checks for vectorization.
1863 ///
1864 /// The runtime checks are created up-front in temporary blocks to allow better
1865 /// estimating the cost and un-linked from the existing IR. After deciding to
1866 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1867 /// temporary blocks are completely removed.
1868 class GeneratedRTChecks {
1869   /// Basic block which contains the generated SCEV checks, if any.
1870   BasicBlock *SCEVCheckBlock = nullptr;
1871 
1872   /// The value representing the result of the generated SCEV checks. If it is
1873   /// nullptr, either no SCEV checks have been generated or they have been used.
1874   Value *SCEVCheckCond = nullptr;
1875 
1876   /// Basic block which contains the generated memory runtime checks, if any.
1877   BasicBlock *MemCheckBlock = nullptr;
1878 
1879   /// The value representing the result of the generated memory runtime checks.
1880   /// If it is nullptr, either no memory runtime checks have been generated or
1881   /// they have been used.
1882   Instruction *MemRuntimeCheckCond = nullptr;
1883 
1884   DominatorTree *DT;
1885   LoopInfo *LI;
1886 
1887   SCEVExpander SCEVExp;
1888   SCEVExpander MemCheckExp;
1889 
1890 public:
1891   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1892                     const DataLayout &DL)
1893       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1894         MemCheckExp(SE, DL, "scev.check") {}
1895 
1896   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1897   /// accurately estimate the cost of the runtime checks. The blocks are
1898   /// un-linked from the IR and is added back during vector code generation. If
1899   /// there is no vector code generation, the check blocks are removed
1900   /// completely.
1901   void Create(Loop *L, const LoopAccessInfo &LAI,
1902               const SCEVUnionPredicate &UnionPred) {
1903 
1904     BasicBlock *LoopHeader = L->getHeader();
1905     BasicBlock *Preheader = L->getLoopPreheader();
1906 
1907     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1908     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1909     // may be used by SCEVExpander. The blocks will be un-linked from their
1910     // predecessors and removed from LI & DT at the end of the function.
1911     if (!UnionPred.isAlwaysTrue()) {
1912       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1913                                   nullptr, "vector.scevcheck");
1914 
1915       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1916           &UnionPred, SCEVCheckBlock->getTerminator());
1917     }
1918 
1919     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1920     if (RtPtrChecking.Need) {
1921       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1922       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1923                                  "vector.memcheck");
1924 
1925       std::tie(std::ignore, MemRuntimeCheckCond) =
1926           addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1927                            RtPtrChecking.getChecks(), MemCheckExp);
1928       assert(MemRuntimeCheckCond &&
1929              "no RT checks generated although RtPtrChecking "
1930              "claimed checks are required");
1931     }
1932 
1933     if (!MemCheckBlock && !SCEVCheckBlock)
1934       return;
1935 
1936     // Unhook the temporary block with the checks, update various places
1937     // accordingly.
1938     if (SCEVCheckBlock)
1939       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1940     if (MemCheckBlock)
1941       MemCheckBlock->replaceAllUsesWith(Preheader);
1942 
1943     if (SCEVCheckBlock) {
1944       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1945       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1946       Preheader->getTerminator()->eraseFromParent();
1947     }
1948     if (MemCheckBlock) {
1949       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1950       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
1951       Preheader->getTerminator()->eraseFromParent();
1952     }
1953 
1954     DT->changeImmediateDominator(LoopHeader, Preheader);
1955     if (MemCheckBlock) {
1956       DT->eraseNode(MemCheckBlock);
1957       LI->removeBlock(MemCheckBlock);
1958     }
1959     if (SCEVCheckBlock) {
1960       DT->eraseNode(SCEVCheckBlock);
1961       LI->removeBlock(SCEVCheckBlock);
1962     }
1963   }
1964 
1965   /// Remove the created SCEV & memory runtime check blocks & instructions, if
1966   /// unused.
1967   ~GeneratedRTChecks() {
1968     SCEVExpanderCleaner SCEVCleaner(SCEVExp, *DT);
1969     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp, *DT);
1970     if (!SCEVCheckCond)
1971       SCEVCleaner.markResultUsed();
1972 
1973     if (!MemRuntimeCheckCond)
1974       MemCheckCleaner.markResultUsed();
1975 
1976     if (MemRuntimeCheckCond) {
1977       auto &SE = *MemCheckExp.getSE();
1978       // Memory runtime check generation creates compares that use expanded
1979       // values. Remove them before running the SCEVExpanderCleaners.
1980       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
1981         if (MemCheckExp.isInsertedInstruction(&I))
1982           continue;
1983         SE.forgetValue(&I);
1984         SE.eraseValueFromMap(&I);
1985         I.eraseFromParent();
1986       }
1987     }
1988     MemCheckCleaner.cleanup();
1989     SCEVCleaner.cleanup();
1990 
1991     if (SCEVCheckCond)
1992       SCEVCheckBlock->eraseFromParent();
1993     if (MemRuntimeCheckCond)
1994       MemCheckBlock->eraseFromParent();
1995   }
1996 
1997   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
1998   /// adjusts the branches to branch to the vector preheader or \p Bypass,
1999   /// depending on the generated condition.
2000   BasicBlock *emitSCEVChecks(Loop *L, BasicBlock *Bypass,
2001                              BasicBlock *LoopVectorPreHeader,
2002                              BasicBlock *LoopExitBlock) {
2003     if (!SCEVCheckCond)
2004       return nullptr;
2005     if (auto *C = dyn_cast<ConstantInt>(SCEVCheckCond))
2006       if (C->isZero())
2007         return nullptr;
2008 
2009     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2010 
2011     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2012     // Create new preheader for vector loop.
2013     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2014       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2015 
2016     SCEVCheckBlock->getTerminator()->eraseFromParent();
2017     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2018     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2019                                                 SCEVCheckBlock);
2020 
2021     DT->addNewBlock(SCEVCheckBlock, Pred);
2022     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2023 
2024     ReplaceInstWithInst(
2025         SCEVCheckBlock->getTerminator(),
2026         BranchInst::Create(Bypass, LoopVectorPreHeader, SCEVCheckCond));
2027     // Mark the check as used, to prevent it from being removed during cleanup.
2028     SCEVCheckCond = nullptr;
2029     return SCEVCheckBlock;
2030   }
2031 
2032   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2033   /// the branches to branch to the vector preheader or \p Bypass, depending on
2034   /// the generated condition.
2035   BasicBlock *emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass,
2036                                    BasicBlock *LoopVectorPreHeader) {
2037     // Check if we generated code that checks in runtime if arrays overlap.
2038     if (!MemRuntimeCheckCond)
2039       return nullptr;
2040 
2041     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2042     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2043                                                 MemCheckBlock);
2044 
2045     DT->addNewBlock(MemCheckBlock, Pred);
2046     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2047     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2048 
2049     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2050       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2051 
2052     ReplaceInstWithInst(
2053         MemCheckBlock->getTerminator(),
2054         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2055     MemCheckBlock->getTerminator()->setDebugLoc(
2056         Pred->getTerminator()->getDebugLoc());
2057 
2058     // Mark the check as used, to prevent it from being removed during cleanup.
2059     MemRuntimeCheckCond = nullptr;
2060     return MemCheckBlock;
2061   }
2062 };
2063 
2064 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2065 // vectorization. The loop needs to be annotated with #pragma omp simd
2066 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2067 // vector length information is not provided, vectorization is not considered
2068 // explicit. Interleave hints are not allowed either. These limitations will be
2069 // relaxed in the future.
2070 // Please, note that we are currently forced to abuse the pragma 'clang
2071 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2072 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2073 // provides *explicit vectorization hints* (LV can bypass legal checks and
2074 // assume that vectorization is legal). However, both hints are implemented
2075 // using the same metadata (llvm.loop.vectorize, processed by
2076 // LoopVectorizeHints). This will be fixed in the future when the native IR
2077 // representation for pragma 'omp simd' is introduced.
2078 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2079                                    OptimizationRemarkEmitter *ORE) {
2080   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2081   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2082 
2083   // Only outer loops with an explicit vectorization hint are supported.
2084   // Unannotated outer loops are ignored.
2085   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2086     return false;
2087 
2088   Function *Fn = OuterLp->getHeader()->getParent();
2089   if (!Hints.allowVectorization(Fn, OuterLp,
2090                                 true /*VectorizeOnlyWhenForced*/)) {
2091     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2092     return false;
2093   }
2094 
2095   if (Hints.getInterleave() > 1) {
2096     // TODO: Interleave support is future work.
2097     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2098                          "outer loops.\n");
2099     Hints.emitRemarkWithHints();
2100     return false;
2101   }
2102 
2103   return true;
2104 }
2105 
2106 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2107                                   OptimizationRemarkEmitter *ORE,
2108                                   SmallVectorImpl<Loop *> &V) {
2109   // Collect inner loops and outer loops without irreducible control flow. For
2110   // now, only collect outer loops that have explicit vectorization hints. If we
2111   // are stress testing the VPlan H-CFG construction, we collect the outermost
2112   // loop of every loop nest.
2113   if (L.isInnermost() || VPlanBuildStressTest ||
2114       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2115     LoopBlocksRPO RPOT(&L);
2116     RPOT.perform(LI);
2117     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2118       V.push_back(&L);
2119       // TODO: Collect inner loops inside marked outer loops in case
2120       // vectorization fails for the outer loop. Do not invoke
2121       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2122       // already known to be reducible. We can use an inherited attribute for
2123       // that.
2124       return;
2125     }
2126   }
2127   for (Loop *InnerL : L)
2128     collectSupportedLoops(*InnerL, LI, ORE, V);
2129 }
2130 
2131 namespace {
2132 
2133 /// The LoopVectorize Pass.
2134 struct LoopVectorize : public FunctionPass {
2135   /// Pass identification, replacement for typeid
2136   static char ID;
2137 
2138   LoopVectorizePass Impl;
2139 
2140   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2141                          bool VectorizeOnlyWhenForced = false)
2142       : FunctionPass(ID),
2143         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2144     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2145   }
2146 
2147   bool runOnFunction(Function &F) override {
2148     if (skipFunction(F))
2149       return false;
2150 
2151     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2152     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2153     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2154     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2155     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2156     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2157     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2158     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2159     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2160     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2161     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2162     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2163     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2164 
2165     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2166         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2167 
2168     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2169                         GetLAA, *ORE, PSI).MadeAnyChange;
2170   }
2171 
2172   void getAnalysisUsage(AnalysisUsage &AU) const override {
2173     AU.addRequired<AssumptionCacheTracker>();
2174     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2175     AU.addRequired<DominatorTreeWrapperPass>();
2176     AU.addRequired<LoopInfoWrapperPass>();
2177     AU.addRequired<ScalarEvolutionWrapperPass>();
2178     AU.addRequired<TargetTransformInfoWrapperPass>();
2179     AU.addRequired<AAResultsWrapperPass>();
2180     AU.addRequired<LoopAccessLegacyAnalysis>();
2181     AU.addRequired<DemandedBitsWrapperPass>();
2182     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2183     AU.addRequired<InjectTLIMappingsLegacy>();
2184 
2185     // We currently do not preserve loopinfo/dominator analyses with outer loop
2186     // vectorization. Until this is addressed, mark these analyses as preserved
2187     // only for non-VPlan-native path.
2188     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2189     if (!EnableVPlanNativePath) {
2190       AU.addPreserved<LoopInfoWrapperPass>();
2191       AU.addPreserved<DominatorTreeWrapperPass>();
2192     }
2193 
2194     AU.addPreserved<BasicAAWrapperPass>();
2195     AU.addPreserved<GlobalsAAWrapperPass>();
2196     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2197   }
2198 };
2199 
2200 } // end anonymous namespace
2201 
2202 //===----------------------------------------------------------------------===//
2203 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2204 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2205 //===----------------------------------------------------------------------===//
2206 
2207 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2208   // We need to place the broadcast of invariant variables outside the loop,
2209   // but only if it's proven safe to do so. Else, broadcast will be inside
2210   // vector loop body.
2211   Instruction *Instr = dyn_cast<Instruction>(V);
2212   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2213                      (!Instr ||
2214                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2215   // Place the code for broadcasting invariant variables in the new preheader.
2216   IRBuilder<>::InsertPointGuard Guard(Builder);
2217   if (SafeToHoist)
2218     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2219 
2220   // Broadcast the scalar into all locations in the vector.
2221   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2222 
2223   return Shuf;
2224 }
2225 
2226 void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
2227     const InductionDescriptor &II, Value *Step, Value *Start,
2228     Instruction *EntryVal, VPValue *Def, VPValue *CastDef,
2229     VPTransformState &State) {
2230   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2231          "Expected either an induction phi-node or a truncate of it!");
2232 
2233   // Construct the initial value of the vector IV in the vector loop preheader
2234   auto CurrIP = Builder.saveIP();
2235   Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2236   if (isa<TruncInst>(EntryVal)) {
2237     assert(Start->getType()->isIntegerTy() &&
2238            "Truncation requires an integer type");
2239     auto *TruncType = cast<IntegerType>(EntryVal->getType());
2240     Step = Builder.CreateTrunc(Step, TruncType);
2241     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
2242   }
2243   Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
2244   Value *SteppedStart =
2245       getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
2246 
2247   // We create vector phi nodes for both integer and floating-point induction
2248   // variables. Here, we determine the kind of arithmetic we will perform.
2249   Instruction::BinaryOps AddOp;
2250   Instruction::BinaryOps MulOp;
2251   if (Step->getType()->isIntegerTy()) {
2252     AddOp = Instruction::Add;
2253     MulOp = Instruction::Mul;
2254   } else {
2255     AddOp = II.getInductionOpcode();
2256     MulOp = Instruction::FMul;
2257   }
2258 
2259   // Multiply the vectorization factor by the step using integer or
2260   // floating-point arithmetic as appropriate.
2261   Type *StepType = Step->getType();
2262   if (Step->getType()->isFloatingPointTy())
2263     StepType = IntegerType::get(StepType->getContext(),
2264                                 StepType->getScalarSizeInBits());
2265   Value *RuntimeVF = getRuntimeVF(Builder, StepType, VF);
2266   if (Step->getType()->isFloatingPointTy())
2267     RuntimeVF = Builder.CreateSIToFP(RuntimeVF, Step->getType());
2268   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
2269 
2270   // Create a vector splat to use in the induction update.
2271   //
2272   // FIXME: If the step is non-constant, we create the vector splat with
2273   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
2274   //        handle a constant vector splat.
2275   Value *SplatVF = isa<Constant>(Mul)
2276                        ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
2277                        : Builder.CreateVectorSplat(VF, Mul);
2278   Builder.restoreIP(CurrIP);
2279 
2280   // We may need to add the step a number of times, depending on the unroll
2281   // factor. The last of those goes into the PHI.
2282   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
2283                                     &*LoopVectorBody->getFirstInsertionPt());
2284   VecInd->setDebugLoc(EntryVal->getDebugLoc());
2285   Instruction *LastInduction = VecInd;
2286   for (unsigned Part = 0; Part < UF; ++Part) {
2287     State.set(Def, LastInduction, Part);
2288 
2289     if (isa<TruncInst>(EntryVal))
2290       addMetadata(LastInduction, EntryVal);
2291     recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, CastDef,
2292                                           State, Part);
2293 
2294     LastInduction = cast<Instruction>(
2295         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
2296     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
2297   }
2298 
2299   // Move the last step to the end of the latch block. This ensures consistent
2300   // placement of all induction updates.
2301   auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
2302   auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
2303   auto *ICmp = cast<Instruction>(Br->getCondition());
2304   LastInduction->moveBefore(ICmp);
2305   LastInduction->setName("vec.ind.next");
2306 
2307   VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
2308   VecInd->addIncoming(LastInduction, LoopVectorLatch);
2309 }
2310 
2311 bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
2312   return Cost->isScalarAfterVectorization(I, VF) ||
2313          Cost->isProfitableToScalarize(I, VF);
2314 }
2315 
2316 bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
2317   if (shouldScalarizeInstruction(IV))
2318     return true;
2319   auto isScalarInst = [&](User *U) -> bool {
2320     auto *I = cast<Instruction>(U);
2321     return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
2322   };
2323   return llvm::any_of(IV->users(), isScalarInst);
2324 }
2325 
2326 void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
2327     const InductionDescriptor &ID, const Instruction *EntryVal,
2328     Value *VectorLoopVal, VPValue *CastDef, VPTransformState &State,
2329     unsigned Part, unsigned Lane) {
2330   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
2331          "Expected either an induction phi-node or a truncate of it!");
2332 
2333   // This induction variable is not the phi from the original loop but the
2334   // newly-created IV based on the proof that casted Phi is equal to the
2335   // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
2336   // re-uses the same InductionDescriptor that original IV uses but we don't
2337   // have to do any recording in this case - that is done when original IV is
2338   // processed.
2339   if (isa<TruncInst>(EntryVal))
2340     return;
2341 
2342   const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
2343   if (Casts.empty())
2344     return;
2345   // Only the first Cast instruction in the Casts vector is of interest.
2346   // The rest of the Casts (if exist) have no uses outside the
2347   // induction update chain itself.
2348   if (Lane < UINT_MAX)
2349     State.set(CastDef, VectorLoopVal, VPIteration(Part, Lane));
2350   else
2351     State.set(CastDef, VectorLoopVal, Part);
2352 }
2353 
2354 void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, Value *Start,
2355                                                 TruncInst *Trunc, VPValue *Def,
2356                                                 VPValue *CastDef,
2357                                                 VPTransformState &State) {
2358   assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
2359          "Primary induction variable must have an integer type");
2360 
2361   auto II = Legal->getInductionVars().find(IV);
2362   assert(II != Legal->getInductionVars().end() && "IV is not an induction");
2363 
2364   auto ID = II->second;
2365   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
2366 
2367   // The value from the original loop to which we are mapping the new induction
2368   // variable.
2369   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
2370 
2371   auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
2372 
2373   // Generate code for the induction step. Note that induction steps are
2374   // required to be loop-invariant
2375   auto CreateStepValue = [&](const SCEV *Step) -> Value * {
2376     assert(PSE.getSE()->isLoopInvariant(Step, OrigLoop) &&
2377            "Induction step should be loop invariant");
2378     if (PSE.getSE()->isSCEVable(IV->getType())) {
2379       SCEVExpander Exp(*PSE.getSE(), DL, "induction");
2380       return Exp.expandCodeFor(Step, Step->getType(),
2381                                LoopVectorPreHeader->getTerminator());
2382     }
2383     return cast<SCEVUnknown>(Step)->getValue();
2384   };
2385 
2386   // The scalar value to broadcast. This is derived from the canonical
2387   // induction variable. If a truncation type is given, truncate the canonical
2388   // induction variable and step. Otherwise, derive these values from the
2389   // induction descriptor.
2390   auto CreateScalarIV = [&](Value *&Step) -> Value * {
2391     Value *ScalarIV = Induction;
2392     if (IV != OldInduction) {
2393       ScalarIV = IV->getType()->isIntegerTy()
2394                      ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
2395                      : Builder.CreateCast(Instruction::SIToFP, Induction,
2396                                           IV->getType());
2397       ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
2398       ScalarIV->setName("offset.idx");
2399     }
2400     if (Trunc) {
2401       auto *TruncType = cast<IntegerType>(Trunc->getType());
2402       assert(Step->getType()->isIntegerTy() &&
2403              "Truncation requires an integer step");
2404       ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
2405       Step = Builder.CreateTrunc(Step, TruncType);
2406     }
2407     return ScalarIV;
2408   };
2409 
2410   // Create the vector values from the scalar IV, in the absence of creating a
2411   // vector IV.
2412   auto CreateSplatIV = [&](Value *ScalarIV, Value *Step) {
2413     Value *Broadcasted = getBroadcastInstrs(ScalarIV);
2414     for (unsigned Part = 0; Part < UF; ++Part) {
2415       assert(!VF.isScalable() && "scalable vectors not yet supported.");
2416       Value *EntryPart =
2417           getStepVector(Broadcasted, VF.getKnownMinValue() * Part, Step,
2418                         ID.getInductionOpcode());
2419       State.set(Def, EntryPart, Part);
2420       if (Trunc)
2421         addMetadata(EntryPart, Trunc);
2422       recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, CastDef,
2423                                             State, Part);
2424     }
2425   };
2426 
2427   // Fast-math-flags propagate from the original induction instruction.
2428   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
2429   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
2430     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
2431 
2432   // Now do the actual transformations, and start with creating the step value.
2433   Value *Step = CreateStepValue(ID.getStep());
2434   if (VF.isZero() || VF.isScalar()) {
2435     Value *ScalarIV = CreateScalarIV(Step);
2436     CreateSplatIV(ScalarIV, Step);
2437     return;
2438   }
2439 
2440   // Determine if we want a scalar version of the induction variable. This is
2441   // true if the induction variable itself is not widened, or if it has at
2442   // least one user in the loop that is not widened.
2443   auto NeedsScalarIV = needsScalarInduction(EntryVal);
2444   if (!NeedsScalarIV) {
2445     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2446                                     State);
2447     return;
2448   }
2449 
2450   // Try to create a new independent vector induction variable. If we can't
2451   // create the phi node, we will splat the scalar induction variable in each
2452   // loop iteration.
2453   if (!shouldScalarizeInstruction(EntryVal)) {
2454     createVectorIntOrFpInductionPHI(ID, Step, Start, EntryVal, Def, CastDef,
2455                                     State);
2456     Value *ScalarIV = CreateScalarIV(Step);
2457     // Create scalar steps that can be used by instructions we will later
2458     // scalarize. Note that the addition of the scalar steps will not increase
2459     // the number of instructions in the loop in the common case prior to
2460     // InstCombine. We will be trading one vector extract for each scalar step.
2461     buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2462     return;
2463   }
2464 
2465   // All IV users are scalar instructions, so only emit a scalar IV, not a
2466   // vectorised IV. Except when we tail-fold, then the splat IV feeds the
2467   // predicate used by the masked loads/stores.
2468   Value *ScalarIV = CreateScalarIV(Step);
2469   if (!Cost->isScalarEpilogueAllowed())
2470     CreateSplatIV(ScalarIV, Step);
2471   buildScalarSteps(ScalarIV, Step, EntryVal, ID, Def, CastDef, State);
2472 }
2473 
2474 Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
2475                                           Instruction::BinaryOps BinOp) {
2476   // Create and check the types.
2477   auto *ValVTy = cast<VectorType>(Val->getType());
2478   ElementCount VLen = ValVTy->getElementCount();
2479 
2480   Type *STy = Val->getType()->getScalarType();
2481   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2482          "Induction Step must be an integer or FP");
2483   assert(Step->getType() == STy && "Step has wrong type");
2484 
2485   SmallVector<Constant *, 8> Indices;
2486 
2487   // Create a vector of consecutive numbers from zero to VF.
2488   VectorType *InitVecValVTy = ValVTy;
2489   Type *InitVecValSTy = STy;
2490   if (STy->isFloatingPointTy()) {
2491     InitVecValSTy =
2492         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2493     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2494   }
2495   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2496 
2497   // Add on StartIdx
2498   Value *StartIdxSplat = Builder.CreateVectorSplat(
2499       VLen, ConstantInt::get(InitVecValSTy, StartIdx));
2500   InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2501 
2502   if (STy->isIntegerTy()) {
2503     Step = Builder.CreateVectorSplat(VLen, Step);
2504     assert(Step->getType() == Val->getType() && "Invalid step vec");
2505     // FIXME: The newly created binary instructions should contain nsw/nuw flags,
2506     // which can be found from the original scalar operations.
2507     Step = Builder.CreateMul(InitVec, Step);
2508     return Builder.CreateAdd(Val, Step, "induction");
2509   }
2510 
2511   // Floating point induction.
2512   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2513          "Binary Opcode should be specified for FP induction");
2514   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2515   Step = Builder.CreateVectorSplat(VLen, Step);
2516   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2517   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2518 }
2519 
2520 void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
2521                                            Instruction *EntryVal,
2522                                            const InductionDescriptor &ID,
2523                                            VPValue *Def, VPValue *CastDef,
2524                                            VPTransformState &State) {
2525   // We shouldn't have to build scalar steps if we aren't vectorizing.
2526   assert(VF.isVector() && "VF should be greater than one");
2527   // Get the value type and ensure it and the step have the same integer type.
2528   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2529   assert(ScalarIVTy == Step->getType() &&
2530          "Val and Step should have the same type");
2531 
2532   // We build scalar steps for both integer and floating-point induction
2533   // variables. Here, we determine the kind of arithmetic we will perform.
2534   Instruction::BinaryOps AddOp;
2535   Instruction::BinaryOps MulOp;
2536   if (ScalarIVTy->isIntegerTy()) {
2537     AddOp = Instruction::Add;
2538     MulOp = Instruction::Mul;
2539   } else {
2540     AddOp = ID.getInductionOpcode();
2541     MulOp = Instruction::FMul;
2542   }
2543 
2544   // Determine the number of scalars we need to generate for each unroll
2545   // iteration. If EntryVal is uniform, we only need to generate the first
2546   // lane. Otherwise, we generate all VF values.
2547   bool IsUniform =
2548       Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF);
2549   unsigned Lanes = IsUniform ? 1 : VF.getKnownMinValue();
2550   // Compute the scalar steps and save the results in State.
2551   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2552                                      ScalarIVTy->getScalarSizeInBits());
2553   Type *VecIVTy = nullptr;
2554   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2555   if (!IsUniform && VF.isScalable()) {
2556     VecIVTy = VectorType::get(ScalarIVTy, VF);
2557     UnitStepVec = Builder.CreateStepVector(VectorType::get(IntStepTy, VF));
2558     SplatStep = Builder.CreateVectorSplat(VF, Step);
2559     SplatIV = Builder.CreateVectorSplat(VF, ScalarIV);
2560   }
2561 
2562   for (unsigned Part = 0; Part < UF; ++Part) {
2563     Value *StartIdx0 =
2564         createStepForVF(Builder, ConstantInt::get(IntStepTy, Part), VF);
2565 
2566     if (!IsUniform && VF.isScalable()) {
2567       auto *SplatStartIdx = Builder.CreateVectorSplat(VF, StartIdx0);
2568       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2569       if (ScalarIVTy->isFloatingPointTy())
2570         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2571       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2572       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2573       State.set(Def, Add, Part);
2574       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2575                                             Part);
2576       // It's useful to record the lane values too for the known minimum number
2577       // of elements so we do those below. This improves the code quality when
2578       // trying to extract the first element, for example.
2579     }
2580 
2581     if (ScalarIVTy->isFloatingPointTy())
2582       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2583 
2584     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2585       Value *StartIdx = Builder.CreateBinOp(
2586           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2587       // The step returned by `createStepForVF` is a runtime-evaluated value
2588       // when VF is scalable. Otherwise, it should be folded into a Constant.
2589       assert((VF.isScalable() || isa<Constant>(StartIdx)) &&
2590              "Expected StartIdx to be folded to a constant when VF is not "
2591              "scalable");
2592       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2593       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2594       State.set(Def, Add, VPIteration(Part, Lane));
2595       recordVectorLoopValueForInductionCast(ID, EntryVal, Add, CastDef, State,
2596                                             Part, Lane);
2597     }
2598   }
2599 }
2600 
2601 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2602                                                     const VPIteration &Instance,
2603                                                     VPTransformState &State) {
2604   Value *ScalarInst = State.get(Def, Instance);
2605   Value *VectorValue = State.get(Def, Instance.Part);
2606   VectorValue = Builder.CreateInsertElement(
2607       VectorValue, ScalarInst,
2608       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2609   State.set(Def, VectorValue, Instance.Part);
2610 }
2611 
2612 Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
2613   assert(Vec->getType()->isVectorTy() && "Invalid type");
2614   return Builder.CreateVectorReverse(Vec, "reverse");
2615 }
2616 
2617 // Return whether we allow using masked interleave-groups (for dealing with
2618 // strided loads/stores that reside in predicated blocks, or for dealing
2619 // with gaps).
2620 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2621   // If an override option has been passed in for interleaved accesses, use it.
2622   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2623     return EnableMaskedInterleavedMemAccesses;
2624 
2625   return TTI.enableMaskedInterleavedAccessVectorization();
2626 }
2627 
2628 // Try to vectorize the interleave group that \p Instr belongs to.
2629 //
2630 // E.g. Translate following interleaved load group (factor = 3):
2631 //   for (i = 0; i < N; i+=3) {
2632 //     R = Pic[i];             // Member of index 0
2633 //     G = Pic[i+1];           // Member of index 1
2634 //     B = Pic[i+2];           // Member of index 2
2635 //     ... // do something to R, G, B
2636 //   }
2637 // To:
2638 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2639 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2640 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2641 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2642 //
2643 // Or translate following interleaved store group (factor = 3):
2644 //   for (i = 0; i < N; i+=3) {
2645 //     ... do something to R, G, B
2646 //     Pic[i]   = R;           // Member of index 0
2647 //     Pic[i+1] = G;           // Member of index 1
2648 //     Pic[i+2] = B;           // Member of index 2
2649 //   }
2650 // To:
2651 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2652 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2653 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2654 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2655 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2656 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2657     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2658     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2659     VPValue *BlockInMask) {
2660   Instruction *Instr = Group->getInsertPos();
2661   const DataLayout &DL = Instr->getModule()->getDataLayout();
2662 
2663   // Prepare for the vector type of the interleaved load/store.
2664   Type *ScalarTy = getMemInstValueType(Instr);
2665   unsigned InterleaveFactor = Group->getFactor();
2666   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2667   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2668 
2669   // Prepare for the new pointers.
2670   SmallVector<Value *, 2> AddrParts;
2671   unsigned Index = Group->getIndex(Instr);
2672 
2673   // TODO: extend the masked interleaved-group support to reversed access.
2674   assert((!BlockInMask || !Group->isReverse()) &&
2675          "Reversed masked interleave-group not supported.");
2676 
2677   // If the group is reverse, adjust the index to refer to the last vector lane
2678   // instead of the first. We adjust the index from the first vector lane,
2679   // rather than directly getting the pointer for lane VF - 1, because the
2680   // pointer operand of the interleaved access is supposed to be uniform. For
2681   // uniform instructions, we're only required to generate a value for the
2682   // first vector lane in each unroll iteration.
2683   if (Group->isReverse())
2684     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2685 
2686   for (unsigned Part = 0; Part < UF; Part++) {
2687     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2688     setDebugLocFromInst(Builder, AddrPart);
2689 
2690     // Notice current instruction could be any index. Need to adjust the address
2691     // to the member of index 0.
2692     //
2693     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2694     //       b = A[i];       // Member of index 0
2695     // Current pointer is pointed to A[i+1], adjust it to A[i].
2696     //
2697     // E.g.  A[i+1] = a;     // Member of index 1
2698     //       A[i]   = b;     // Member of index 0
2699     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2700     // Current pointer is pointed to A[i+2], adjust it to A[i].
2701 
2702     bool InBounds = false;
2703     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2704       InBounds = gep->isInBounds();
2705     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2706     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2707 
2708     // Cast to the vector pointer type.
2709     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2710     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2711     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2712   }
2713 
2714   setDebugLocFromInst(Builder, Instr);
2715   Value *PoisonVec = PoisonValue::get(VecTy);
2716 
2717   Value *MaskForGaps = nullptr;
2718   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2719     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2720     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2721   }
2722 
2723   // Vectorize the interleaved load group.
2724   if (isa<LoadInst>(Instr)) {
2725     // For each unroll part, create a wide load for the group.
2726     SmallVector<Value *, 2> NewLoads;
2727     for (unsigned Part = 0; Part < UF; Part++) {
2728       Instruction *NewLoad;
2729       if (BlockInMask || MaskForGaps) {
2730         assert(useMaskedInterleavedAccesses(*TTI) &&
2731                "masked interleaved groups are not allowed.");
2732         Value *GroupMask = MaskForGaps;
2733         if (BlockInMask) {
2734           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2735           Value *ShuffledMask = Builder.CreateShuffleVector(
2736               BlockInMaskPart,
2737               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2738               "interleaved.mask");
2739           GroupMask = MaskForGaps
2740                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2741                                                 MaskForGaps)
2742                           : ShuffledMask;
2743         }
2744         NewLoad =
2745             Builder.CreateMaskedLoad(AddrParts[Part], Group->getAlign(),
2746                                      GroupMask, PoisonVec, "wide.masked.vec");
2747       }
2748       else
2749         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2750                                             Group->getAlign(), "wide.vec");
2751       Group->addMetadata(NewLoad);
2752       NewLoads.push_back(NewLoad);
2753     }
2754 
2755     // For each member in the group, shuffle out the appropriate data from the
2756     // wide loads.
2757     unsigned J = 0;
2758     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2759       Instruction *Member = Group->getMember(I);
2760 
2761       // Skip the gaps in the group.
2762       if (!Member)
2763         continue;
2764 
2765       auto StrideMask =
2766           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2767       for (unsigned Part = 0; Part < UF; Part++) {
2768         Value *StridedVec = Builder.CreateShuffleVector(
2769             NewLoads[Part], StrideMask, "strided.vec");
2770 
2771         // If this member has different type, cast the result type.
2772         if (Member->getType() != ScalarTy) {
2773           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2774           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2775           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2776         }
2777 
2778         if (Group->isReverse())
2779           StridedVec = reverseVector(StridedVec);
2780 
2781         State.set(VPDefs[J], StridedVec, Part);
2782       }
2783       ++J;
2784     }
2785     return;
2786   }
2787 
2788   // The sub vector type for current instruction.
2789   auto *SubVT = VectorType::get(ScalarTy, VF);
2790 
2791   // Vectorize the interleaved store group.
2792   for (unsigned Part = 0; Part < UF; Part++) {
2793     // Collect the stored vector from each member.
2794     SmallVector<Value *, 4> StoredVecs;
2795     for (unsigned i = 0; i < InterleaveFactor; i++) {
2796       // Interleaved store group doesn't allow a gap, so each index has a member
2797       assert(Group->getMember(i) && "Fail to get a member from an interleaved store group");
2798 
2799       Value *StoredVec = State.get(StoredValues[i], Part);
2800 
2801       if (Group->isReverse())
2802         StoredVec = reverseVector(StoredVec);
2803 
2804       // If this member has different type, cast it to a unified type.
2805 
2806       if (StoredVec->getType() != SubVT)
2807         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2808 
2809       StoredVecs.push_back(StoredVec);
2810     }
2811 
2812     // Concatenate all vectors into a wide vector.
2813     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2814 
2815     // Interleave the elements in the wide vector.
2816     Value *IVec = Builder.CreateShuffleVector(
2817         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2818         "interleaved.vec");
2819 
2820     Instruction *NewStoreInstr;
2821     if (BlockInMask) {
2822       Value *BlockInMaskPart = State.get(BlockInMask, Part);
2823       Value *ShuffledMask = Builder.CreateShuffleVector(
2824           BlockInMaskPart,
2825           createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2826           "interleaved.mask");
2827       NewStoreInstr = Builder.CreateMaskedStore(
2828           IVec, AddrParts[Part], Group->getAlign(), ShuffledMask);
2829     }
2830     else
2831       NewStoreInstr =
2832           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2833 
2834     Group->addMetadata(NewStoreInstr);
2835   }
2836 }
2837 
2838 void InnerLoopVectorizer::vectorizeMemoryInstruction(
2839     Instruction *Instr, VPTransformState &State, VPValue *Def, VPValue *Addr,
2840     VPValue *StoredValue, VPValue *BlockInMask) {
2841   // Attempt to issue a wide load.
2842   LoadInst *LI = dyn_cast<LoadInst>(Instr);
2843   StoreInst *SI = dyn_cast<StoreInst>(Instr);
2844 
2845   assert((LI || SI) && "Invalid Load/Store instruction");
2846   assert((!SI || StoredValue) && "No stored value provided for widened store");
2847   assert((!LI || !StoredValue) && "Stored value provided for widened load");
2848 
2849   LoopVectorizationCostModel::InstWidening Decision =
2850       Cost->getWideningDecision(Instr, VF);
2851   assert((Decision == LoopVectorizationCostModel::CM_Widen ||
2852           Decision == LoopVectorizationCostModel::CM_Widen_Reverse ||
2853           Decision == LoopVectorizationCostModel::CM_GatherScatter) &&
2854          "CM decision is not to widen the memory instruction");
2855 
2856   Type *ScalarDataTy = getMemInstValueType(Instr);
2857 
2858   auto *DataTy = VectorType::get(ScalarDataTy, VF);
2859   const Align Alignment = getLoadStoreAlignment(Instr);
2860 
2861   // Determine if the pointer operand of the access is either consecutive or
2862   // reverse consecutive.
2863   bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
2864   bool ConsecutiveStride =
2865       Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
2866   bool CreateGatherScatter =
2867       (Decision == LoopVectorizationCostModel::CM_GatherScatter);
2868 
2869   // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
2870   // gather/scatter. Otherwise Decision should have been to Scalarize.
2871   assert((ConsecutiveStride || CreateGatherScatter) &&
2872          "The instruction should be scalarized");
2873   (void)ConsecutiveStride;
2874 
2875   VectorParts BlockInMaskParts(UF);
2876   bool isMaskRequired = BlockInMask;
2877   if (isMaskRequired)
2878     for (unsigned Part = 0; Part < UF; ++Part)
2879       BlockInMaskParts[Part] = State.get(BlockInMask, Part);
2880 
2881   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
2882     // Calculate the pointer for the specific unroll-part.
2883     GetElementPtrInst *PartPtr = nullptr;
2884 
2885     bool InBounds = false;
2886     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
2887       InBounds = gep->isInBounds();
2888     if (Reverse) {
2889       // If the address is consecutive but reversed, then the
2890       // wide store needs to start at the last vector element.
2891       // RunTimeVF =  VScale * VF.getKnownMinValue()
2892       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
2893       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), VF);
2894       // NumElt = -Part * RunTimeVF
2895       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
2896       // LastLane = 1 - RunTimeVF
2897       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
2898       PartPtr =
2899           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
2900       PartPtr->setIsInBounds(InBounds);
2901       PartPtr = cast<GetElementPtrInst>(
2902           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
2903       PartPtr->setIsInBounds(InBounds);
2904       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
2905         BlockInMaskParts[Part] = reverseVector(BlockInMaskParts[Part]);
2906     } else {
2907       Value *Increment = createStepForVF(Builder, Builder.getInt32(Part), VF);
2908       PartPtr = cast<GetElementPtrInst>(
2909           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
2910       PartPtr->setIsInBounds(InBounds);
2911     }
2912 
2913     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
2914     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
2915   };
2916 
2917   // Handle Stores:
2918   if (SI) {
2919     setDebugLocFromInst(Builder, SI);
2920 
2921     for (unsigned Part = 0; Part < UF; ++Part) {
2922       Instruction *NewSI = nullptr;
2923       Value *StoredVal = State.get(StoredValue, Part);
2924       if (CreateGatherScatter) {
2925         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2926         Value *VectorGep = State.get(Addr, Part);
2927         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
2928                                             MaskPart);
2929       } else {
2930         if (Reverse) {
2931           // If we store to reverse consecutive memory locations, then we need
2932           // to reverse the order of elements in the stored value.
2933           StoredVal = reverseVector(StoredVal);
2934           // We don't want to update the value in the map as it might be used in
2935           // another expression. So don't call resetVectorValue(StoredVal).
2936         }
2937         auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2938         if (isMaskRequired)
2939           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
2940                                             BlockInMaskParts[Part]);
2941         else
2942           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
2943       }
2944       addMetadata(NewSI, SI);
2945     }
2946     return;
2947   }
2948 
2949   // Handle loads.
2950   assert(LI && "Must have a load instruction");
2951   setDebugLocFromInst(Builder, LI);
2952   for (unsigned Part = 0; Part < UF; ++Part) {
2953     Value *NewLI;
2954     if (CreateGatherScatter) {
2955       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
2956       Value *VectorGep = State.get(Addr, Part);
2957       NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
2958                                          nullptr, "wide.masked.gather");
2959       addMetadata(NewLI, LI);
2960     } else {
2961       auto *VecPtr = CreateVecPtr(Part, State.get(Addr, VPIteration(0, 0)));
2962       if (isMaskRequired)
2963         NewLI = Builder.CreateMaskedLoad(
2964             VecPtr, Alignment, BlockInMaskParts[Part], PoisonValue::get(DataTy),
2965             "wide.masked.load");
2966       else
2967         NewLI =
2968             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
2969 
2970       // Add metadata to the load, but setVectorValue to the reverse shuffle.
2971       addMetadata(NewLI, LI);
2972       if (Reverse)
2973         NewLI = reverseVector(NewLI);
2974     }
2975 
2976     State.set(Def, NewLI, Part);
2977   }
2978 }
2979 
2980 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr, VPValue *Def,
2981                                                VPUser &User,
2982                                                const VPIteration &Instance,
2983                                                bool IfPredicateInstr,
2984                                                VPTransformState &State) {
2985   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2986 
2987   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2988   // the first lane and part.
2989   if (isa<NoAliasScopeDeclInst>(Instr))
2990     if (!Instance.isFirstIteration())
2991       return;
2992 
2993   setDebugLocFromInst(Builder, Instr);
2994 
2995   // Does this instruction return a value ?
2996   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2997 
2998   Instruction *Cloned = Instr->clone();
2999   if (!IsVoidRetTy)
3000     Cloned->setName(Instr->getName() + ".cloned");
3001 
3002   State.Builder.SetInsertPoint(Builder.GetInsertBlock(),
3003                                Builder.GetInsertPoint());
3004   // Replace the operands of the cloned instructions with their scalar
3005   // equivalents in the new loop.
3006   for (unsigned op = 0, e = User.getNumOperands(); op != e; ++op) {
3007     auto *Operand = dyn_cast<Instruction>(Instr->getOperand(op));
3008     auto InputInstance = Instance;
3009     if (!Operand || !OrigLoop->contains(Operand) ||
3010         (Cost->isUniformAfterVectorization(Operand, State.VF)))
3011       InputInstance.Lane = VPLane::getFirstLane();
3012     auto *NewOp = State.get(User.getOperand(op), InputInstance);
3013     Cloned->setOperand(op, NewOp);
3014   }
3015   addNewMetadata(Cloned, Instr);
3016 
3017   // Place the cloned scalar in the new loop.
3018   Builder.Insert(Cloned);
3019 
3020   State.set(Def, Cloned, Instance);
3021 
3022   // If we just cloned a new assumption, add it the assumption cache.
3023   if (auto *II = dyn_cast<AssumeInst>(Cloned))
3024     AC->registerAssumption(II);
3025 
3026   // End if-block.
3027   if (IfPredicateInstr)
3028     PredicatedInstructions.push_back(Cloned);
3029 }
3030 
3031 PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
3032                                                       Value *End, Value *Step,
3033                                                       Instruction *DL) {
3034   BasicBlock *Header = L->getHeader();
3035   BasicBlock *Latch = L->getLoopLatch();
3036   // As we're just creating this loop, it's possible no latch exists
3037   // yet. If so, use the header as this will be a single block loop.
3038   if (!Latch)
3039     Latch = Header;
3040 
3041   IRBuilder<> Builder(&*Header->getFirstInsertionPt());
3042   Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
3043   setDebugLocFromInst(Builder, OldInst);
3044   auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
3045 
3046   Builder.SetInsertPoint(Latch->getTerminator());
3047   setDebugLocFromInst(Builder, OldInst);
3048 
3049   // Create i+1 and fill the PHINode.
3050   Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
3051   Induction->addIncoming(Start, L->getLoopPreheader());
3052   Induction->addIncoming(Next, Latch);
3053   // Create the compare.
3054   Value *ICmp = Builder.CreateICmpEQ(Next, End);
3055   Builder.CreateCondBr(ICmp, L->getUniqueExitBlock(), Header);
3056 
3057   // Now we have two terminators. Remove the old one from the block.
3058   Latch->getTerminator()->eraseFromParent();
3059 
3060   return Induction;
3061 }
3062 
3063 Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
3064   if (TripCount)
3065     return TripCount;
3066 
3067   assert(L && "Create Trip Count for null loop.");
3068   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3069   // Find the loop boundaries.
3070   ScalarEvolution *SE = PSE.getSE();
3071   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
3072   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
3073          "Invalid loop count");
3074 
3075   Type *IdxTy = Legal->getWidestInductionType();
3076   assert(IdxTy && "No type for induction");
3077 
3078   // The exit count might have the type of i64 while the phi is i32. This can
3079   // happen if we have an induction variable that is sign extended before the
3080   // compare. The only way that we get a backedge taken count is that the
3081   // induction variable was signed and as such will not overflow. In such a case
3082   // truncation is legal.
3083   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
3084       IdxTy->getPrimitiveSizeInBits())
3085     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
3086   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
3087 
3088   // Get the total trip count from the count by adding 1.
3089   const SCEV *ExitCount = SE->getAddExpr(
3090       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
3091 
3092   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
3093 
3094   // Expand the trip count and place the new instructions in the preheader.
3095   // Notice that the pre-header does not change, only the loop body.
3096   SCEVExpander Exp(*SE, DL, "induction");
3097 
3098   // Count holds the overall loop count (N).
3099   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
3100                                 L->getLoopPreheader()->getTerminator());
3101 
3102   if (TripCount->getType()->isPointerTy())
3103     TripCount =
3104         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
3105                                     L->getLoopPreheader()->getTerminator());
3106 
3107   return TripCount;
3108 }
3109 
3110 Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
3111   if (VectorTripCount)
3112     return VectorTripCount;
3113 
3114   Value *TC = getOrCreateTripCount(L);
3115   IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
3116 
3117   Type *Ty = TC->getType();
3118   // This is where we can make the step a runtime constant.
3119   Value *Step = createStepForVF(Builder, ConstantInt::get(Ty, UF), VF);
3120 
3121   // If the tail is to be folded by masking, round the number of iterations N
3122   // up to a multiple of Step instead of rounding down. This is done by first
3123   // adding Step-1 and then rounding down. Note that it's ok if this addition
3124   // overflows: the vector induction variable will eventually wrap to zero given
3125   // that it starts at zero and its Step is a power of two; the loop will then
3126   // exit, with the last early-exit vector comparison also producing all-true.
3127   if (Cost->foldTailByMasking()) {
3128     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
3129            "VF*UF must be a power of 2 when folding tail by masking");
3130     assert(!VF.isScalable() &&
3131            "Tail folding not yet supported for scalable vectors");
3132     TC = Builder.CreateAdd(
3133         TC, ConstantInt::get(Ty, VF.getKnownMinValue() * UF - 1), "n.rnd.up");
3134   }
3135 
3136   // Now we need to generate the expression for the part of the loop that the
3137   // vectorized body will execute. This is equal to N - (N % Step) if scalar
3138   // iterations are not required for correctness, or N - Step, otherwise. Step
3139   // is equal to the vectorization factor (number of SIMD elements) times the
3140   // unroll factor (number of SIMD instructions).
3141   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
3142 
3143   // There are two cases where we need to ensure (at least) the last iteration
3144   // runs in the scalar remainder loop. Thus, if the step evenly divides
3145   // the trip count, we set the remainder to be equal to the step. If the step
3146   // does not evenly divide the trip count, no adjustment is necessary since
3147   // there will already be scalar iterations. Note that the minimum iterations
3148   // check ensures that N >= Step. The cases are:
3149   // 1) If there is a non-reversed interleaved group that may speculatively
3150   //    access memory out-of-bounds.
3151   // 2) If any instruction may follow a conditionally taken exit. That is, if
3152   //    the loop contains multiple exiting blocks, or a single exiting block
3153   //    which is not the latch.
3154   if (VF.isVector() && Cost->requiresScalarEpilogue()) {
3155     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
3156     R = Builder.CreateSelect(IsZero, Step, R);
3157   }
3158 
3159   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
3160 
3161   return VectorTripCount;
3162 }
3163 
3164 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
3165                                                    const DataLayout &DL) {
3166   // Verify that V is a vector type with same number of elements as DstVTy.
3167   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
3168   unsigned VF = DstFVTy->getNumElements();
3169   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
3170   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
3171   Type *SrcElemTy = SrcVecTy->getElementType();
3172   Type *DstElemTy = DstFVTy->getElementType();
3173   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
3174          "Vector elements must have same size");
3175 
3176   // Do a direct cast if element types are castable.
3177   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
3178     return Builder.CreateBitOrPointerCast(V, DstFVTy);
3179   }
3180   // V cannot be directly casted to desired vector type.
3181   // May happen when V is a floating point vector but DstVTy is a vector of
3182   // pointers or vice-versa. Handle this using a two-step bitcast using an
3183   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
3184   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
3185          "Only one type should be a pointer type");
3186   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
3187          "Only one type should be a floating point type");
3188   Type *IntTy =
3189       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
3190   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
3191   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
3192   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
3193 }
3194 
3195 void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
3196                                                          BasicBlock *Bypass) {
3197   Value *Count = getOrCreateTripCount(L);
3198   // Reuse existing vector loop preheader for TC checks.
3199   // Note that new preheader block is generated for vector loop.
3200   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
3201   IRBuilder<> Builder(TCCheckBlock->getTerminator());
3202 
3203   // Generate code to check if the loop's trip count is less than VF * UF, or
3204   // equal to it in case a scalar epilogue is required; this implies that the
3205   // vector trip count is zero. This check also covers the case where adding one
3206   // to the backedge-taken count overflowed leading to an incorrect trip count
3207   // of zero. In this case we will also jump to the scalar loop.
3208   auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
3209                                           : ICmpInst::ICMP_ULT;
3210 
3211   // If tail is to be folded, vector loop takes care of all iterations.
3212   Value *CheckMinIters = Builder.getFalse();
3213   if (!Cost->foldTailByMasking()) {
3214     Value *Step =
3215         createStepForVF(Builder, ConstantInt::get(Count->getType(), UF), VF);
3216     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
3217   }
3218   // Create new preheader for vector loop.
3219   LoopVectorPreHeader =
3220       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
3221                  "vector.ph");
3222 
3223   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
3224                                DT->getNode(Bypass)->getIDom()) &&
3225          "TC check is expected to dominate Bypass");
3226 
3227   // Update dominator for Bypass & LoopExit.
3228   DT->changeImmediateDominator(Bypass, TCCheckBlock);
3229   DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
3230 
3231   ReplaceInstWithInst(
3232       TCCheckBlock->getTerminator(),
3233       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
3234   LoopBypassBlocks.push_back(TCCheckBlock);
3235 }
3236 
3237 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
3238 
3239   BasicBlock *const SCEVCheckBlock =
3240       RTChecks.emitSCEVChecks(L, Bypass, LoopVectorPreHeader, LoopExitBlock);
3241   if (!SCEVCheckBlock)
3242     return nullptr;
3243 
3244   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3245            (OptForSizeBasedOnProfile &&
3246             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3247          "Cannot SCEV check stride or overflow when optimizing for size");
3248 
3249 
3250   // Update dominator only if this is first RT check.
3251   if (LoopBypassBlocks.empty()) {
3252     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3253     DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3254   }
3255 
3256   LoopBypassBlocks.push_back(SCEVCheckBlock);
3257   AddedSafetyChecks = true;
3258   return SCEVCheckBlock;
3259 }
3260 
3261 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
3262                                                       BasicBlock *Bypass) {
3263   // VPlan-native path does not do any analysis for runtime checks currently.
3264   if (EnableVPlanNativePath)
3265     return nullptr;
3266 
3267   BasicBlock *const MemCheckBlock =
3268       RTChecks.emitMemRuntimeChecks(L, Bypass, LoopVectorPreHeader);
3269 
3270   // Check if we generated code that checks in runtime if arrays overlap. We put
3271   // the checks into a separate block to make the more common case of few
3272   // elements faster.
3273   if (!MemCheckBlock)
3274     return nullptr;
3275 
3276   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3277     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3278            "Cannot emit memory checks when optimizing for size, unless forced "
3279            "to vectorize.");
3280     ORE->emit([&]() {
3281       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3282                                         L->getStartLoc(), L->getHeader())
3283              << "Code-size may be reduced by not forcing "
3284                 "vectorization, or by source-code modifications "
3285                 "eliminating the need for runtime checks "
3286                 "(e.g., adding 'restrict').";
3287     });
3288   }
3289 
3290   LoopBypassBlocks.push_back(MemCheckBlock);
3291 
3292   AddedSafetyChecks = true;
3293 
3294   // We currently don't use LoopVersioning for the actual loop cloning but we
3295   // still use it to add the noalias metadata.
3296   LVer = std::make_unique<LoopVersioning>(
3297       *Legal->getLAI(),
3298       Legal->getLAI()->getRuntimePointerChecking()->getChecks(), OrigLoop, LI,
3299       DT, PSE.getSE());
3300   LVer->prepareNoAliasMetadata();
3301   return MemCheckBlock;
3302 }
3303 
3304 Value *InnerLoopVectorizer::emitTransformedIndex(
3305     IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
3306     const InductionDescriptor &ID) const {
3307 
3308   SCEVExpander Exp(*SE, DL, "induction");
3309   auto Step = ID.getStep();
3310   auto StartValue = ID.getStartValue();
3311   assert(Index->getType() == Step->getType() &&
3312          "Index type does not match StepValue type");
3313 
3314   // Note: the IR at this point is broken. We cannot use SE to create any new
3315   // SCEV and then expand it, hoping that SCEV's simplification will give us
3316   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
3317   // lead to various SCEV crashes. So all we can do is to use builder and rely
3318   // on InstCombine for future simplifications. Here we handle some trivial
3319   // cases only.
3320   auto CreateAdd = [&B](Value *X, Value *Y) {
3321     assert(X->getType() == Y->getType() && "Types don't match!");
3322     if (auto *CX = dyn_cast<ConstantInt>(X))
3323       if (CX->isZero())
3324         return Y;
3325     if (auto *CY = dyn_cast<ConstantInt>(Y))
3326       if (CY->isZero())
3327         return X;
3328     return B.CreateAdd(X, Y);
3329   };
3330 
3331   auto CreateMul = [&B](Value *X, Value *Y) {
3332     assert(X->getType() == Y->getType() && "Types don't match!");
3333     if (auto *CX = dyn_cast<ConstantInt>(X))
3334       if (CX->isOne())
3335         return Y;
3336     if (auto *CY = dyn_cast<ConstantInt>(Y))
3337       if (CY->isOne())
3338         return X;
3339     return B.CreateMul(X, Y);
3340   };
3341 
3342   // Get a suitable insert point for SCEV expansion. For blocks in the vector
3343   // loop, choose the end of the vector loop header (=LoopVectorBody), because
3344   // the DomTree is not kept up-to-date for additional blocks generated in the
3345   // vector loop. By using the header as insertion point, we guarantee that the
3346   // expanded instructions dominate all their uses.
3347   auto GetInsertPoint = [this, &B]() {
3348     BasicBlock *InsertBB = B.GetInsertPoint()->getParent();
3349     if (InsertBB != LoopVectorBody &&
3350         LI->getLoopFor(LoopVectorBody) == LI->getLoopFor(InsertBB))
3351       return LoopVectorBody->getTerminator();
3352     return &*B.GetInsertPoint();
3353   };
3354 
3355   switch (ID.getKind()) {
3356   case InductionDescriptor::IK_IntInduction: {
3357     assert(Index->getType() == StartValue->getType() &&
3358            "Index type does not match StartValue type");
3359     if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
3360       return B.CreateSub(StartValue, Index);
3361     auto *Offset = CreateMul(
3362         Index, Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint()));
3363     return CreateAdd(StartValue, Offset);
3364   }
3365   case InductionDescriptor::IK_PtrInduction: {
3366     assert(isa<SCEVConstant>(Step) &&
3367            "Expected constant step for pointer induction");
3368     return B.CreateGEP(
3369         StartValue->getType()->getPointerElementType(), StartValue,
3370         CreateMul(Index,
3371                   Exp.expandCodeFor(Step, Index->getType(), GetInsertPoint())));
3372   }
3373   case InductionDescriptor::IK_FpInduction: {
3374     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
3375     auto InductionBinOp = ID.getInductionBinOp();
3376     assert(InductionBinOp &&
3377            (InductionBinOp->getOpcode() == Instruction::FAdd ||
3378             InductionBinOp->getOpcode() == Instruction::FSub) &&
3379            "Original bin op should be defined for FP induction");
3380 
3381     Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
3382     Value *MulExp = B.CreateFMul(StepValue, Index);
3383     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
3384                          "induction");
3385   }
3386   case InductionDescriptor::IK_NoInduction:
3387     return nullptr;
3388   }
3389   llvm_unreachable("invalid enum");
3390 }
3391 
3392 Loop *InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3393   LoopScalarBody = OrigLoop->getHeader();
3394   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3395   LoopExitBlock = OrigLoop->getUniqueExitBlock();
3396   assert(LoopExitBlock && "Must have an exit block");
3397   assert(LoopVectorPreHeader && "Invalid loop structure");
3398 
3399   LoopMiddleBlock =
3400       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3401                  LI, nullptr, Twine(Prefix) + "middle.block");
3402   LoopScalarPreHeader =
3403       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3404                  nullptr, Twine(Prefix) + "scalar.ph");
3405 
3406   // Set up branch from middle block to the exit and scalar preheader blocks.
3407   // completeLoopSkeleton will update the condition to use an iteration check,
3408   // if required to decide whether to execute the remainder.
3409   BranchInst *BrInst =
3410       BranchInst::Create(LoopExitBlock, LoopScalarPreHeader, Builder.getTrue());
3411   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3412   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3413   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3414 
3415   // We intentionally don't let SplitBlock to update LoopInfo since
3416   // LoopVectorBody should belong to another loop than LoopVectorPreHeader.
3417   // LoopVectorBody is explicitly added to the correct place few lines later.
3418   LoopVectorBody =
3419       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3420                  nullptr, nullptr, Twine(Prefix) + "vector.body");
3421 
3422   // Update dominator for loop exit.
3423   DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3424 
3425   // Create and register the new vector loop.
3426   Loop *Lp = LI->AllocateLoop();
3427   Loop *ParentLoop = OrigLoop->getParentLoop();
3428 
3429   // Insert the new loop into the loop nest and register the new basic blocks
3430   // before calling any utilities such as SCEV that require valid LoopInfo.
3431   if (ParentLoop) {
3432     ParentLoop->addChildLoop(Lp);
3433   } else {
3434     LI->addTopLevelLoop(Lp);
3435   }
3436   Lp->addBasicBlockToLoop(LoopVectorBody, *LI);
3437   return Lp;
3438 }
3439 
3440 void InnerLoopVectorizer::createInductionResumeValues(
3441     Loop *L, Value *VectorTripCount,
3442     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3443   assert(VectorTripCount && L && "Expected valid arguments");
3444   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3445           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3446          "Inconsistent information about additional bypass.");
3447   // We are going to resume the execution of the scalar loop.
3448   // Go over all of the induction variables that we found and fix the
3449   // PHIs that are left in the scalar version of the loop.
3450   // The starting values of PHI nodes depend on the counter of the last
3451   // iteration in the vectorized loop.
3452   // If we come from a bypass edge then we need to start from the original
3453   // start value.
3454   for (auto &InductionEntry : Legal->getInductionVars()) {
3455     PHINode *OrigPhi = InductionEntry.first;
3456     InductionDescriptor II = InductionEntry.second;
3457 
3458     // Create phi nodes to merge from the  backedge-taken check block.
3459     PHINode *BCResumeVal =
3460         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3461                         LoopScalarPreHeader->getTerminator());
3462     // Copy original phi DL over to the new one.
3463     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3464     Value *&EndValue = IVEndValues[OrigPhi];
3465     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3466     if (OrigPhi == OldInduction) {
3467       // We know what the end value is.
3468       EndValue = VectorTripCount;
3469     } else {
3470       IRBuilder<> B(L->getLoopPreheader()->getTerminator());
3471 
3472       // Fast-math-flags propagate from the original induction instruction.
3473       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3474         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3475 
3476       Type *StepType = II.getStep()->getType();
3477       Instruction::CastOps CastOp =
3478           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3479       Value *CRD = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.crd");
3480       const DataLayout &DL = LoopScalarBody->getModule()->getDataLayout();
3481       EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3482       EndValue->setName("ind.end");
3483 
3484       // Compute the end value for the additional bypass (if applicable).
3485       if (AdditionalBypass.first) {
3486         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3487         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3488                                          StepType, true);
3489         CRD =
3490             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.crd");
3491         EndValueFromAdditionalBypass =
3492             emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
3493         EndValueFromAdditionalBypass->setName("ind.end");
3494       }
3495     }
3496     // The new PHI merges the original incoming value, in case of a bypass,
3497     // or the value at the end of the vectorized loop.
3498     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3499 
3500     // Fix the scalar body counter (PHI node).
3501     // The old induction's phi node in the scalar body needs the truncated
3502     // value.
3503     for (BasicBlock *BB : LoopBypassBlocks)
3504       BCResumeVal->addIncoming(II.getStartValue(), BB);
3505 
3506     if (AdditionalBypass.first)
3507       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3508                                             EndValueFromAdditionalBypass);
3509 
3510     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3511   }
3512 }
3513 
3514 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(Loop *L,
3515                                                       MDNode *OrigLoopID) {
3516   assert(L && "Expected valid loop.");
3517 
3518   // The trip counts should be cached by now.
3519   Value *Count = getOrCreateTripCount(L);
3520   Value *VectorTripCount = getOrCreateVectorTripCount(L);
3521 
3522   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3523 
3524   // Add a check in the middle block to see if we have completed
3525   // all of the iterations in the first vector loop.
3526   // If (N - N%VF) == N, then we *don't* need to run the remainder.
3527   // If tail is to be folded, we know we don't need to run the remainder.
3528   if (!Cost->foldTailByMasking()) {
3529     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3530                                         Count, VectorTripCount, "cmp.n",
3531                                         LoopMiddleBlock->getTerminator());
3532 
3533     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3534     // of the corresponding compare because they may have ended up with
3535     // different line numbers and we want to avoid awkward line stepping while
3536     // debugging. Eg. if the compare has got a line number inside the loop.
3537     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3538     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3539   }
3540 
3541   // Get ready to start creating new instructions into the vectorized body.
3542   assert(LoopVectorPreHeader == L->getLoopPreheader() &&
3543          "Inconsistent vector loop preheader");
3544   Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
3545 
3546   Optional<MDNode *> VectorizedLoopID =
3547       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
3548                                       LLVMLoopVectorizeFollowupVectorized});
3549   if (VectorizedLoopID.hasValue()) {
3550     L->setLoopID(VectorizedLoopID.getValue());
3551 
3552     // Do not setAlreadyVectorized if loop attributes have been defined
3553     // explicitly.
3554     return LoopVectorPreHeader;
3555   }
3556 
3557   // Keep all loop hints from the original loop on the vector loop (we'll
3558   // replace the vectorizer-specific hints below).
3559   if (MDNode *LID = OrigLoop->getLoopID())
3560     L->setLoopID(LID);
3561 
3562   LoopVectorizeHints Hints(L, true, *ORE);
3563   Hints.setAlreadyVectorized();
3564 
3565 #ifdef EXPENSIVE_CHECKS
3566   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3567   LI->verify(*DT);
3568 #endif
3569 
3570   return LoopVectorPreHeader;
3571 }
3572 
3573 BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3574   /*
3575    In this function we generate a new loop. The new loop will contain
3576    the vectorized instructions while the old loop will continue to run the
3577    scalar remainder.
3578 
3579        [ ] <-- loop iteration number check.
3580     /   |
3581    /    v
3582   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3583   |  /  |
3584   | /   v
3585   ||   [ ]     <-- vector pre header.
3586   |/    |
3587   |     v
3588   |    [  ] \
3589   |    [  ]_|   <-- vector loop.
3590   |     |
3591   |     v
3592   |   -[ ]   <--- middle-block.
3593   |  /  |
3594   | /   v
3595   -|- >[ ]     <--- new preheader.
3596    |    |
3597    |    v
3598    |   [ ] \
3599    |   [ ]_|   <-- old scalar loop to handle remainder.
3600     \   |
3601      \  v
3602       >[ ]     <-- exit block.
3603    ...
3604    */
3605 
3606   // Get the metadata of the original loop before it gets modified.
3607   MDNode *OrigLoopID = OrigLoop->getLoopID();
3608 
3609   // Create an empty vector loop, and prepare basic blocks for the runtime
3610   // checks.
3611   Loop *Lp = createVectorLoopSkeleton("");
3612 
3613   // Now, compare the new count to zero. If it is zero skip the vector loop and
3614   // jump to the scalar loop. This check also covers the case where the
3615   // backedge-taken count is uint##_max: adding one to it will overflow leading
3616   // to an incorrect trip count of zero. In this (rare) case we will also jump
3617   // to the scalar loop.
3618   emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader);
3619 
3620   // Generate the code to check any assumptions that we've made for SCEV
3621   // expressions.
3622   emitSCEVChecks(Lp, LoopScalarPreHeader);
3623 
3624   // Generate the code that checks in runtime if arrays overlap. We put the
3625   // checks into a separate block to make the more common case of few elements
3626   // faster.
3627   emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
3628 
3629   // Some loops have a single integer induction variable, while other loops
3630   // don't. One example is c++ iterators that often have multiple pointer
3631   // induction variables. In the code below we also support a case where we
3632   // don't have a single induction variable.
3633   //
3634   // We try to obtain an induction variable from the original loop as hard
3635   // as possible. However if we don't find one that:
3636   //   - is an integer
3637   //   - counts from zero, stepping by one
3638   //   - is the size of the widest induction variable type
3639   // then we create a new one.
3640   OldInduction = Legal->getPrimaryInduction();
3641   Type *IdxTy = Legal->getWidestInductionType();
3642   Value *StartIdx = ConstantInt::get(IdxTy, 0);
3643   // The loop step is equal to the vectorization factor (num of SIMD elements)
3644   // times the unroll factor (num of SIMD instructions).
3645   Builder.SetInsertPoint(&*Lp->getHeader()->getFirstInsertionPt());
3646   Value *Step = createStepForVF(Builder, ConstantInt::get(IdxTy, UF), VF);
3647   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
3648   Induction =
3649       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
3650                               getDebugLocFromInstOrOperands(OldInduction));
3651 
3652   // Emit phis for the new starting index of the scalar loop.
3653   createInductionResumeValues(Lp, CountRoundDown);
3654 
3655   return completeLoopSkeleton(Lp, OrigLoopID);
3656 }
3657 
3658 // Fix up external users of the induction variable. At this point, we are
3659 // in LCSSA form, with all external PHIs that use the IV having one input value,
3660 // coming from the remainder loop. We need those PHIs to also have a correct
3661 // value for the IV when arriving directly from the middle block.
3662 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3663                                        const InductionDescriptor &II,
3664                                        Value *CountRoundDown, Value *EndValue,
3665                                        BasicBlock *MiddleBlock) {
3666   // There are two kinds of external IV usages - those that use the value
3667   // computed in the last iteration (the PHI) and those that use the penultimate
3668   // value (the value that feeds into the phi from the loop latch).
3669   // We allow both, but they, obviously, have different values.
3670 
3671   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3672 
3673   DenseMap<Value *, Value *> MissingVals;
3674 
3675   // An external user of the last iteration's value should see the value that
3676   // the remainder loop uses to initialize its own IV.
3677   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3678   for (User *U : PostInc->users()) {
3679     Instruction *UI = cast<Instruction>(U);
3680     if (!OrigLoop->contains(UI)) {
3681       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3682       MissingVals[UI] = EndValue;
3683     }
3684   }
3685 
3686   // An external user of the penultimate value need to see EndValue - Step.
3687   // The simplest way to get this is to recompute it from the constituent SCEVs,
3688   // that is Start + (Step * (CRD - 1)).
3689   for (User *U : OrigPhi->users()) {
3690     auto *UI = cast<Instruction>(U);
3691     if (!OrigLoop->contains(UI)) {
3692       const DataLayout &DL =
3693           OrigLoop->getHeader()->getModule()->getDataLayout();
3694       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3695 
3696       IRBuilder<> B(MiddleBlock->getTerminator());
3697 
3698       // Fast-math-flags propagate from the original induction instruction.
3699       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3700         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3701 
3702       Value *CountMinusOne = B.CreateSub(
3703           CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
3704       Value *CMO =
3705           !II.getStep()->getType()->isIntegerTy()
3706               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3707                              II.getStep()->getType())
3708               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3709       CMO->setName("cast.cmo");
3710       Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
3711       Escape->setName("ind.escape");
3712       MissingVals[UI] = Escape;
3713     }
3714   }
3715 
3716   for (auto &I : MissingVals) {
3717     PHINode *PHI = cast<PHINode>(I.first);
3718     // One corner case we have to handle is two IVs "chasing" each-other,
3719     // that is %IV2 = phi [...], [ %IV1, %latch ]
3720     // In this case, if IV1 has an external use, we need to avoid adding both
3721     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3722     // don't already have an incoming value for the middle block.
3723     if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
3724       PHI->addIncoming(I.second, MiddleBlock);
3725   }
3726 }
3727 
3728 namespace {
3729 
3730 struct CSEDenseMapInfo {
3731   static bool canHandle(const Instruction *I) {
3732     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3733            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3734   }
3735 
3736   static inline Instruction *getEmptyKey() {
3737     return DenseMapInfo<Instruction *>::getEmptyKey();
3738   }
3739 
3740   static inline Instruction *getTombstoneKey() {
3741     return DenseMapInfo<Instruction *>::getTombstoneKey();
3742   }
3743 
3744   static unsigned getHashValue(const Instruction *I) {
3745     assert(canHandle(I) && "Unknown instruction!");
3746     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3747                                                            I->value_op_end()));
3748   }
3749 
3750   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3751     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3752         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3753       return LHS == RHS;
3754     return LHS->isIdenticalTo(RHS);
3755   }
3756 };
3757 
3758 } // end anonymous namespace
3759 
3760 ///Perform cse of induction variable instructions.
3761 static void cse(BasicBlock *BB) {
3762   // Perform simple cse.
3763   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3764   for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
3765     Instruction *In = &*I++;
3766 
3767     if (!CSEDenseMapInfo::canHandle(In))
3768       continue;
3769 
3770     // Check if we can replace this instruction with any of the
3771     // visited instructions.
3772     if (Instruction *V = CSEMap.lookup(In)) {
3773       In->replaceAllUsesWith(V);
3774       In->eraseFromParent();
3775       continue;
3776     }
3777 
3778     CSEMap[In] = In;
3779   }
3780 }
3781 
3782 InstructionCost
3783 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3784                                               bool &NeedToScalarize) const {
3785   Function *F = CI->getCalledFunction();
3786   Type *ScalarRetTy = CI->getType();
3787   SmallVector<Type *, 4> Tys, ScalarTys;
3788   for (auto &ArgOp : CI->arg_operands())
3789     ScalarTys.push_back(ArgOp->getType());
3790 
3791   // Estimate cost of scalarized vector call. The source operands are assumed
3792   // to be vectors, so we need to extract individual elements from there,
3793   // execute VF scalar calls, and then gather the result into the vector return
3794   // value.
3795   InstructionCost ScalarCallCost =
3796       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3797   if (VF.isScalar())
3798     return ScalarCallCost;
3799 
3800   // Compute corresponding vector type for return value and arguments.
3801   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3802   for (Type *ScalarTy : ScalarTys)
3803     Tys.push_back(ToVectorTy(ScalarTy, VF));
3804 
3805   // Compute costs of unpacking argument values for the scalar calls and
3806   // packing the return values to a vector.
3807   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3808 
3809   InstructionCost Cost =
3810       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3811 
3812   // If we can't emit a vector call for this function, then the currently found
3813   // cost is the cost we need to return.
3814   NeedToScalarize = true;
3815   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3816   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3817 
3818   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3819     return Cost;
3820 
3821   // If the corresponding vector cost is cheaper, return its cost.
3822   InstructionCost VectorCallCost =
3823       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3824   if (VectorCallCost < Cost) {
3825     NeedToScalarize = false;
3826     Cost = VectorCallCost;
3827   }
3828   return Cost;
3829 }
3830 
3831 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3832   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3833     return Elt;
3834   return VectorType::get(Elt, VF);
3835 }
3836 
3837 InstructionCost
3838 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3839                                                    ElementCount VF) const {
3840   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3841   assert(ID && "Expected intrinsic call!");
3842   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3843   FastMathFlags FMF;
3844   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3845     FMF = FPMO->getFastMathFlags();
3846 
3847   SmallVector<const Value *> Arguments(CI->arg_begin(), CI->arg_end());
3848   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3849   SmallVector<Type *> ParamTys;
3850   std::transform(FTy->param_begin(), FTy->param_end(),
3851                  std::back_inserter(ParamTys),
3852                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3853 
3854   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3855                                     dyn_cast<IntrinsicInst>(CI));
3856   return TTI.getIntrinsicInstrCost(CostAttrs,
3857                                    TargetTransformInfo::TCK_RecipThroughput);
3858 }
3859 
3860 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3861   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3862   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3863   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3864 }
3865 
3866 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3867   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3868   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3869   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3870 }
3871 
3872 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3873   // For every instruction `I` in MinBWs, truncate the operands, create a
3874   // truncated version of `I` and reextend its result. InstCombine runs
3875   // later and will remove any ext/trunc pairs.
3876   SmallPtrSet<Value *, 4> Erased;
3877   for (const auto &KV : Cost->getMinimalBitwidths()) {
3878     // If the value wasn't vectorized, we must maintain the original scalar
3879     // type. The absence of the value from State indicates that it
3880     // wasn't vectorized.
3881     VPValue *Def = State.Plan->getVPValue(KV.first);
3882     if (!State.hasAnyVectorValue(Def))
3883       continue;
3884     for (unsigned Part = 0; Part < UF; ++Part) {
3885       Value *I = State.get(Def, Part);
3886       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3887         continue;
3888       Type *OriginalTy = I->getType();
3889       Type *ScalarTruncatedTy =
3890           IntegerType::get(OriginalTy->getContext(), KV.second);
3891       auto *TruncatedTy = FixedVectorType::get(
3892           ScalarTruncatedTy,
3893           cast<FixedVectorType>(OriginalTy)->getNumElements());
3894       if (TruncatedTy == OriginalTy)
3895         continue;
3896 
3897       IRBuilder<> B(cast<Instruction>(I));
3898       auto ShrinkOperand = [&](Value *V) -> Value * {
3899         if (auto *ZI = dyn_cast<ZExtInst>(V))
3900           if (ZI->getSrcTy() == TruncatedTy)
3901             return ZI->getOperand(0);
3902         return B.CreateZExtOrTrunc(V, TruncatedTy);
3903       };
3904 
3905       // The actual instruction modification depends on the instruction type,
3906       // unfortunately.
3907       Value *NewI = nullptr;
3908       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3909         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3910                              ShrinkOperand(BO->getOperand(1)));
3911 
3912         // Any wrapping introduced by shrinking this operation shouldn't be
3913         // considered undefined behavior. So, we can't unconditionally copy
3914         // arithmetic wrapping flags to NewI.
3915         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3916       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3917         NewI =
3918             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3919                          ShrinkOperand(CI->getOperand(1)));
3920       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3921         NewI = B.CreateSelect(SI->getCondition(),
3922                               ShrinkOperand(SI->getTrueValue()),
3923                               ShrinkOperand(SI->getFalseValue()));
3924       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3925         switch (CI->getOpcode()) {
3926         default:
3927           llvm_unreachable("Unhandled cast!");
3928         case Instruction::Trunc:
3929           NewI = ShrinkOperand(CI->getOperand(0));
3930           break;
3931         case Instruction::SExt:
3932           NewI = B.CreateSExtOrTrunc(
3933               CI->getOperand(0),
3934               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3935           break;
3936         case Instruction::ZExt:
3937           NewI = B.CreateZExtOrTrunc(
3938               CI->getOperand(0),
3939               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3940           break;
3941         }
3942       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3943         auto Elements0 = cast<FixedVectorType>(SI->getOperand(0)->getType())
3944                              ->getNumElements();
3945         auto *O0 = B.CreateZExtOrTrunc(
3946             SI->getOperand(0),
3947             FixedVectorType::get(ScalarTruncatedTy, Elements0));
3948         auto Elements1 = cast<FixedVectorType>(SI->getOperand(1)->getType())
3949                              ->getNumElements();
3950         auto *O1 = B.CreateZExtOrTrunc(
3951             SI->getOperand(1),
3952             FixedVectorType::get(ScalarTruncatedTy, Elements1));
3953 
3954         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3955       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3956         // Don't do anything with the operands, just extend the result.
3957         continue;
3958       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3959         auto Elements = cast<FixedVectorType>(IE->getOperand(0)->getType())
3960                             ->getNumElements();
3961         auto *O0 = B.CreateZExtOrTrunc(
3962             IE->getOperand(0),
3963             FixedVectorType::get(ScalarTruncatedTy, Elements));
3964         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3965         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3966       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3967         auto Elements = cast<FixedVectorType>(EE->getOperand(0)->getType())
3968                             ->getNumElements();
3969         auto *O0 = B.CreateZExtOrTrunc(
3970             EE->getOperand(0),
3971             FixedVectorType::get(ScalarTruncatedTy, Elements));
3972         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3973       } else {
3974         // If we don't know what to do, be conservative and don't do anything.
3975         continue;
3976       }
3977 
3978       // Lastly, extend the result.
3979       NewI->takeName(cast<Instruction>(I));
3980       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3981       I->replaceAllUsesWith(Res);
3982       cast<Instruction>(I)->eraseFromParent();
3983       Erased.insert(I);
3984       State.reset(Def, Res, Part);
3985     }
3986   }
3987 
3988   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3989   for (const auto &KV : Cost->getMinimalBitwidths()) {
3990     // If the value wasn't vectorized, we must maintain the original scalar
3991     // type. The absence of the value from State indicates that it
3992     // wasn't vectorized.
3993     VPValue *Def = State.Plan->getVPValue(KV.first);
3994     if (!State.hasAnyVectorValue(Def))
3995       continue;
3996     for (unsigned Part = 0; Part < UF; ++Part) {
3997       Value *I = State.get(Def, Part);
3998       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3999       if (Inst && Inst->use_empty()) {
4000         Value *NewI = Inst->getOperand(0);
4001         Inst->eraseFromParent();
4002         State.reset(Def, NewI, Part);
4003       }
4004     }
4005   }
4006 }
4007 
4008 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State) {
4009   // Insert truncates and extends for any truncated instructions as hints to
4010   // InstCombine.
4011   if (VF.isVector())
4012     truncateToMinimalBitwidths(State);
4013 
4014   // Fix widened non-induction PHIs by setting up the PHI operands.
4015   if (OrigPHIsToFix.size()) {
4016     assert(EnableVPlanNativePath &&
4017            "Unexpected non-induction PHIs for fixup in non VPlan-native path");
4018     fixNonInductionPHIs(State);
4019   }
4020 
4021   // At this point every instruction in the original loop is widened to a
4022   // vector form. Now we need to fix the recurrences in the loop. These PHI
4023   // nodes are currently empty because we did not want to introduce cycles.
4024   // This is the second stage of vectorizing recurrences.
4025   fixCrossIterationPHIs(State);
4026 
4027   // Forget the original basic block.
4028   PSE.getSE()->forgetLoop(OrigLoop);
4029 
4030   // Fix-up external users of the induction variables.
4031   for (auto &Entry : Legal->getInductionVars())
4032     fixupIVUsers(Entry.first, Entry.second,
4033                  getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
4034                  IVEndValues[Entry.first], LoopMiddleBlock);
4035 
4036   fixLCSSAPHIs(State);
4037   for (Instruction *PI : PredicatedInstructions)
4038     sinkScalarOperands(&*PI);
4039 
4040   // Remove redundant induction instructions.
4041   cse(LoopVectorBody);
4042 
4043   // Set/update profile weights for the vector and remainder loops as original
4044   // loop iterations are now distributed among them. Note that original loop
4045   // represented by LoopScalarBody becomes remainder loop after vectorization.
4046   //
4047   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
4048   // end up getting slightly roughened result but that should be OK since
4049   // profile is not inherently precise anyway. Note also possible bypass of
4050   // vector code caused by legality checks is ignored, assigning all the weight
4051   // to the vector loop, optimistically.
4052   //
4053   // For scalable vectorization we can't know at compile time how many iterations
4054   // of the loop are handled in one vector iteration, so instead assume a pessimistic
4055   // vscale of '1'.
4056   setProfileInfoAfterUnrolling(
4057       LI->getLoopFor(LoopScalarBody), LI->getLoopFor(LoopVectorBody),
4058       LI->getLoopFor(LoopScalarBody), VF.getKnownMinValue() * UF);
4059 }
4060 
4061 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
4062   // In order to support recurrences we need to be able to vectorize Phi nodes.
4063   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4064   // stage #2: We now need to fix the recurrences by adding incoming edges to
4065   // the currently empty PHI nodes. At this point every instruction in the
4066   // original loop is widened to a vector form so we can use them to construct
4067   // the incoming edges.
4068   VPBasicBlock *Header = State.Plan->getEntry()->getEntryBasicBlock();
4069   for (VPRecipeBase &R : Header->phis()) {
4070     auto *PhiR = dyn_cast<VPWidenPHIRecipe>(&R);
4071     if (!PhiR)
4072       continue;
4073     auto *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4074     if (PhiR->getRecurrenceDescriptor()) {
4075       fixReduction(PhiR, State);
4076     } else if (Legal->isFirstOrderRecurrence(OrigPhi))
4077       fixFirstOrderRecurrence(OrigPhi, State);
4078   }
4079 }
4080 
4081 void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi,
4082                                                   VPTransformState &State) {
4083   // This is the second phase of vectorizing first-order recurrences. An
4084   // overview of the transformation is described below. Suppose we have the
4085   // following loop.
4086   //
4087   //   for (int i = 0; i < n; ++i)
4088   //     b[i] = a[i] - a[i - 1];
4089   //
4090   // There is a first-order recurrence on "a". For this loop, the shorthand
4091   // scalar IR looks like:
4092   //
4093   //   scalar.ph:
4094   //     s_init = a[-1]
4095   //     br scalar.body
4096   //
4097   //   scalar.body:
4098   //     i = phi [0, scalar.ph], [i+1, scalar.body]
4099   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
4100   //     s2 = a[i]
4101   //     b[i] = s2 - s1
4102   //     br cond, scalar.body, ...
4103   //
4104   // In this example, s1 is a recurrence because it's value depends on the
4105   // previous iteration. In the first phase of vectorization, we created a
4106   // temporary value for s1. We now complete the vectorization and produce the
4107   // shorthand vector IR shown below (for VF = 4, UF = 1).
4108   //
4109   //   vector.ph:
4110   //     v_init = vector(..., ..., ..., a[-1])
4111   //     br vector.body
4112   //
4113   //   vector.body
4114   //     i = phi [0, vector.ph], [i+4, vector.body]
4115   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
4116   //     v2 = a[i, i+1, i+2, i+3];
4117   //     v3 = vector(v1(3), v2(0, 1, 2))
4118   //     b[i, i+1, i+2, i+3] = v2 - v3
4119   //     br cond, vector.body, middle.block
4120   //
4121   //   middle.block:
4122   //     x = v2(3)
4123   //     br scalar.ph
4124   //
4125   //   scalar.ph:
4126   //     s_init = phi [x, middle.block], [a[-1], otherwise]
4127   //     br scalar.body
4128   //
4129   // After execution completes the vector loop, we extract the next value of
4130   // the recurrence (x) to use as the initial value in the scalar loop.
4131 
4132   // Get the original loop preheader and single loop latch.
4133   auto *Preheader = OrigLoop->getLoopPreheader();
4134   auto *Latch = OrigLoop->getLoopLatch();
4135 
4136   // Get the initial and previous values of the scalar recurrence.
4137   auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
4138   auto *Previous = Phi->getIncomingValueForBlock(Latch);
4139 
4140   // Create a vector from the initial value.
4141   auto *VectorInit = ScalarInit;
4142   if (VF.isVector()) {
4143     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4144     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
4145     VectorInit = Builder.CreateInsertElement(
4146         PoisonValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
4147         Builder.getInt32(VF.getKnownMinValue() - 1), "vector.recur.init");
4148   }
4149 
4150   VPValue *PhiDef = State.Plan->getVPValue(Phi);
4151   VPValue *PreviousDef = State.Plan->getVPValue(Previous);
4152   // We constructed a temporary phi node in the first phase of vectorization.
4153   // This phi node will eventually be deleted.
4154   Builder.SetInsertPoint(cast<Instruction>(State.get(PhiDef, 0)));
4155 
4156   // Create a phi node for the new recurrence. The current value will either be
4157   // the initial value inserted into a vector or loop-varying vector value.
4158   auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
4159   VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
4160 
4161   // Get the vectorized previous value of the last part UF - 1. It appears last
4162   // among all unrolled iterations, due to the order of their construction.
4163   Value *PreviousLastPart = State.get(PreviousDef, UF - 1);
4164 
4165   // Find and set the insertion point after the previous value if it is an
4166   // instruction.
4167   BasicBlock::iterator InsertPt;
4168   // Note that the previous value may have been constant-folded so it is not
4169   // guaranteed to be an instruction in the vector loop.
4170   // FIXME: Loop invariant values do not form recurrences. We should deal with
4171   //        them earlier.
4172   if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart))
4173     InsertPt = LoopVectorBody->getFirstInsertionPt();
4174   else {
4175     Instruction *PreviousInst = cast<Instruction>(PreviousLastPart);
4176     if (isa<PHINode>(PreviousLastPart))
4177       // If the previous value is a phi node, we should insert after all the phi
4178       // nodes in the block containing the PHI to avoid breaking basic block
4179       // verification. Note that the basic block may be different to
4180       // LoopVectorBody, in case we predicate the loop.
4181       InsertPt = PreviousInst->getParent()->getFirstInsertionPt();
4182     else
4183       InsertPt = ++PreviousInst->getIterator();
4184   }
4185   Builder.SetInsertPoint(&*InsertPt);
4186 
4187   // We will construct a vector for the recurrence by combining the values for
4188   // the current and previous iterations. This is the required shuffle mask.
4189   assert(!VF.isScalable());
4190   SmallVector<int, 8> ShuffleMask(VF.getKnownMinValue());
4191   ShuffleMask[0] = VF.getKnownMinValue() - 1;
4192   for (unsigned I = 1; I < VF.getKnownMinValue(); ++I)
4193     ShuffleMask[I] = I + VF.getKnownMinValue() - 1;
4194 
4195   // The vector from which to take the initial value for the current iteration
4196   // (actual or unrolled). Initially, this is the vector phi node.
4197   Value *Incoming = VecPhi;
4198 
4199   // Shuffle the current and previous vector and update the vector parts.
4200   for (unsigned Part = 0; Part < UF; ++Part) {
4201     Value *PreviousPart = State.get(PreviousDef, Part);
4202     Value *PhiPart = State.get(PhiDef, Part);
4203     auto *Shuffle =
4204         VF.isVector()
4205             ? Builder.CreateShuffleVector(Incoming, PreviousPart, ShuffleMask)
4206             : Incoming;
4207     PhiPart->replaceAllUsesWith(Shuffle);
4208     cast<Instruction>(PhiPart)->eraseFromParent();
4209     State.reset(PhiDef, Shuffle, Part);
4210     Incoming = PreviousPart;
4211   }
4212 
4213   // Fix the latch value of the new recurrence in the vector loop.
4214   VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
4215 
4216   // Extract the last vector element in the middle block. This will be the
4217   // initial value for the recurrence when jumping to the scalar loop.
4218   auto *ExtractForScalar = Incoming;
4219   if (VF.isVector()) {
4220     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4221     ExtractForScalar = Builder.CreateExtractElement(
4222         ExtractForScalar, Builder.getInt32(VF.getKnownMinValue() - 1),
4223         "vector.recur.extract");
4224   }
4225   // Extract the second last element in the middle block if the
4226   // Phi is used outside the loop. We need to extract the phi itself
4227   // and not the last element (the phi update in the current iteration). This
4228   // will be the value when jumping to the exit block from the LoopMiddleBlock,
4229   // when the scalar loop is not run at all.
4230   Value *ExtractForPhiUsedOutsideLoop = nullptr;
4231   if (VF.isVector())
4232     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
4233         Incoming, Builder.getInt32(VF.getKnownMinValue() - 2),
4234         "vector.recur.extract.for.phi");
4235   // When loop is unrolled without vectorizing, initialize
4236   // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
4237   // `Incoming`. This is analogous to the vectorized case above: extracting the
4238   // second last element when VF > 1.
4239   else if (UF > 1)
4240     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
4241 
4242   // Fix the initial value of the original recurrence in the scalar loop.
4243   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
4244   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
4245   for (auto *BB : predecessors(LoopScalarPreHeader)) {
4246     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
4247     Start->addIncoming(Incoming, BB);
4248   }
4249 
4250   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
4251   Phi->setName("scalar.recur");
4252 
4253   // Finally, fix users of the recurrence outside the loop. The users will need
4254   // either the last value of the scalar recurrence or the last value of the
4255   // vector recurrence we extracted in the middle block. Since the loop is in
4256   // LCSSA form, we just need to find all the phi nodes for the original scalar
4257   // recurrence in the exit block, and then add an edge for the middle block.
4258   // Note that LCSSA does not imply single entry when the original scalar loop
4259   // had multiple exiting edges (as we always run the last iteration in the
4260   // scalar epilogue); in that case, the exiting path through middle will be
4261   // dynamically dead and the value picked for the phi doesn't matter.
4262   for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4263     if (any_of(LCSSAPhi.incoming_values(),
4264                [Phi](Value *V) { return V == Phi; }))
4265       LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
4266 }
4267 
4268 static bool useOrderedReductions(RecurrenceDescriptor &RdxDesc) {
4269   return EnableStrictReductions && RdxDesc.isOrdered();
4270 }
4271 
4272 void InnerLoopVectorizer::fixReduction(VPWidenPHIRecipe *PhiR,
4273                                        VPTransformState &State) {
4274   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
4275   // Get it's reduction variable descriptor.
4276   assert(Legal->isReductionVariable(OrigPhi) &&
4277          "Unable to find the reduction variable");
4278   RecurrenceDescriptor RdxDesc = *PhiR->getRecurrenceDescriptor();
4279 
4280   RecurKind RK = RdxDesc.getRecurrenceKind();
4281   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
4282   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
4283   setDebugLocFromInst(Builder, ReductionStartValue);
4284   bool IsInLoopReductionPhi = Cost->isInLoopReduction(OrigPhi);
4285 
4286   VPValue *LoopExitInstDef = State.Plan->getVPValue(LoopExitInst);
4287   // This is the vector-clone of the value that leaves the loop.
4288   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
4289 
4290   // Wrap flags are in general invalid after vectorization, clear them.
4291   clearReductionWrapFlags(RdxDesc, State);
4292 
4293   // Fix the vector-loop phi.
4294 
4295   // Reductions do not have to start at zero. They can start with
4296   // any loop invariant values.
4297   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
4298   Value *OrigLoopVal = OrigPhi->getIncomingValueForBlock(OrigLatch);
4299   BasicBlock *VectorLoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4300 
4301   bool IsOrdered = State.VF.isVector() && IsInLoopReductionPhi &&
4302                    useOrderedReductions(RdxDesc);
4303 
4304   for (unsigned Part = 0; Part < UF; ++Part) {
4305     if (IsOrdered && Part > 0)
4306       break;
4307     Value *VecRdxPhi = State.get(PhiR->getVPSingleValue(), Part);
4308     Value *Val = State.get(State.Plan->getVPValue(OrigLoopVal), Part);
4309     if (IsOrdered)
4310       Val = State.get(State.Plan->getVPValue(OrigLoopVal), UF - 1);
4311     cast<PHINode>(VecRdxPhi)->addIncoming(Val, VectorLoopLatch);
4312   }
4313 
4314   // Before each round, move the insertion point right between
4315   // the PHIs and the values we are going to write.
4316   // This allows us to write both PHINodes and the extractelement
4317   // instructions.
4318   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4319 
4320   setDebugLocFromInst(Builder, LoopExitInst);
4321 
4322   Type *PhiTy = OrigPhi->getType();
4323   // If tail is folded by masking, the vector value to leave the loop should be
4324   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
4325   // instead of the former. For an inloop reduction the reduction will already
4326   // be predicated, and does not need to be handled here.
4327   if (Cost->foldTailByMasking() && !IsInLoopReductionPhi) {
4328     for (unsigned Part = 0; Part < UF; ++Part) {
4329       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
4330       Value *Sel = nullptr;
4331       for (User *U : VecLoopExitInst->users()) {
4332         if (isa<SelectInst>(U)) {
4333           assert(!Sel && "Reduction exit feeding two selects");
4334           Sel = U;
4335         } else
4336           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
4337       }
4338       assert(Sel && "Reduction exit feeds no select");
4339       State.reset(LoopExitInstDef, Sel, Part);
4340 
4341       // If the target can create a predicated operator for the reduction at no
4342       // extra cost in the loop (for example a predicated vadd), it can be
4343       // cheaper for the select to remain in the loop than be sunk out of it,
4344       // and so use the select value for the phi instead of the old
4345       // LoopExitValue.
4346       if (PreferPredicatedReductionSelect ||
4347           TTI->preferPredicatedReductionSelect(
4348               RdxDesc.getOpcode(), PhiTy,
4349               TargetTransformInfo::ReductionFlags())) {
4350         auto *VecRdxPhi =
4351             cast<PHINode>(State.get(PhiR->getVPSingleValue(), Part));
4352         VecRdxPhi->setIncomingValueForBlock(
4353             LI->getLoopFor(LoopVectorBody)->getLoopLatch(), Sel);
4354       }
4355     }
4356   }
4357 
4358   // If the vector reduction can be performed in a smaller type, we truncate
4359   // then extend the loop exit value to enable InstCombine to evaluate the
4360   // entire expression in the smaller type.
4361   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
4362     assert(!IsInLoopReductionPhi && "Unexpected truncated inloop reduction!");
4363     assert(!VF.isScalable() && "scalable vectors not yet supported.");
4364     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
4365     Builder.SetInsertPoint(
4366         LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
4367     VectorParts RdxParts(UF);
4368     for (unsigned Part = 0; Part < UF; ++Part) {
4369       RdxParts[Part] = State.get(LoopExitInstDef, Part);
4370       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4371       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
4372                                         : Builder.CreateZExt(Trunc, VecTy);
4373       for (Value::user_iterator UI = RdxParts[Part]->user_begin();
4374            UI != RdxParts[Part]->user_end();)
4375         if (*UI != Trunc) {
4376           (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
4377           RdxParts[Part] = Extnd;
4378         } else {
4379           ++UI;
4380         }
4381     }
4382     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
4383     for (unsigned Part = 0; Part < UF; ++Part) {
4384       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
4385       State.reset(LoopExitInstDef, RdxParts[Part], Part);
4386     }
4387   }
4388 
4389   // Reduce all of the unrolled parts into a single vector.
4390   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
4391   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
4392 
4393   // The middle block terminator has already been assigned a DebugLoc here (the
4394   // OrigLoop's single latch terminator). We want the whole middle block to
4395   // appear to execute on this line because: (a) it is all compiler generated,
4396   // (b) these instructions are always executed after evaluating the latch
4397   // conditional branch, and (c) other passes may add new predecessors which
4398   // terminate on this line. This is the easiest way to ensure we don't
4399   // accidentally cause an extra step back into the loop while debugging.
4400   setDebugLocFromInst(Builder, LoopMiddleBlock->getTerminator());
4401   if (IsOrdered)
4402     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
4403   else {
4404     // Floating-point operations should have some FMF to enable the reduction.
4405     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
4406     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
4407     for (unsigned Part = 1; Part < UF; ++Part) {
4408       Value *RdxPart = State.get(LoopExitInstDef, Part);
4409       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
4410         ReducedPartRdx = Builder.CreateBinOp(
4411             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
4412       } else {
4413         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
4414       }
4415     }
4416   }
4417 
4418   // Create the reduction after the loop. Note that inloop reductions create the
4419   // target reduction in the loop using a Reduction recipe.
4420   if (VF.isVector() && !IsInLoopReductionPhi) {
4421     ReducedPartRdx =
4422         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx);
4423     // If the reduction can be performed in a smaller type, we need to extend
4424     // the reduction to the wider type before we branch to the original loop.
4425     if (PhiTy != RdxDesc.getRecurrenceType())
4426       ReducedPartRdx = RdxDesc.isSigned()
4427                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
4428                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
4429   }
4430 
4431   // Create a phi node that merges control-flow from the backedge-taken check
4432   // block and the middle block.
4433   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
4434                                         LoopScalarPreHeader->getTerminator());
4435   for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
4436     BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
4437   BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
4438 
4439   // Now, we need to fix the users of the reduction variable
4440   // inside and outside of the scalar remainder loop.
4441 
4442   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4443   // in the exit blocks.  See comment on analogous loop in
4444   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4445   for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4446     if (any_of(LCSSAPhi.incoming_values(),
4447                [LoopExitInst](Value *V) { return V == LoopExitInst; }))
4448       LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4449 
4450   // Fix the scalar loop reduction variable with the incoming reduction sum
4451   // from the vector body and from the backedge value.
4452   int IncomingEdgeBlockIdx =
4453       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4454   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4455   // Pick the other block.
4456   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4457   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4458   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4459 }
4460 
4461 void InnerLoopVectorizer::clearReductionWrapFlags(RecurrenceDescriptor &RdxDesc,
4462                                                   VPTransformState &State) {
4463   RecurKind RK = RdxDesc.getRecurrenceKind();
4464   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4465     return;
4466 
4467   Instruction *LoopExitInstr = RdxDesc.getLoopExitInstr();
4468   assert(LoopExitInstr && "null loop exit instruction");
4469   SmallVector<Instruction *, 8> Worklist;
4470   SmallPtrSet<Instruction *, 8> Visited;
4471   Worklist.push_back(LoopExitInstr);
4472   Visited.insert(LoopExitInstr);
4473 
4474   while (!Worklist.empty()) {
4475     Instruction *Cur = Worklist.pop_back_val();
4476     if (isa<OverflowingBinaryOperator>(Cur))
4477       for (unsigned Part = 0; Part < UF; ++Part) {
4478         Value *V = State.get(State.Plan->getVPValue(Cur), Part);
4479         cast<Instruction>(V)->dropPoisonGeneratingFlags();
4480       }
4481 
4482     for (User *U : Cur->users()) {
4483       Instruction *UI = cast<Instruction>(U);
4484       if ((Cur != LoopExitInstr || OrigLoop->contains(UI->getParent())) &&
4485           Visited.insert(UI).second)
4486         Worklist.push_back(UI);
4487     }
4488   }
4489 }
4490 
4491 void InnerLoopVectorizer::fixLCSSAPHIs(VPTransformState &State) {
4492   for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
4493     if (LCSSAPhi.getBasicBlockIndex(LoopMiddleBlock) != -1)
4494       // Some phis were already hand updated by the reduction and recurrence
4495       // code above, leave them alone.
4496       continue;
4497 
4498     auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
4499     // Non-instruction incoming values will have only one value.
4500 
4501     VPLane Lane = VPLane::getFirstLane();
4502     if (isa<Instruction>(IncomingValue) &&
4503         !Cost->isUniformAfterVectorization(cast<Instruction>(IncomingValue),
4504                                            VF))
4505       Lane = VPLane::getLastLaneForVF(VF);
4506 
4507     // Can be a loop invariant incoming value or the last scalar value to be
4508     // extracted from the vectorized loop.
4509     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
4510     Value *lastIncomingValue =
4511         OrigLoop->isLoopInvariant(IncomingValue)
4512             ? IncomingValue
4513             : State.get(State.Plan->getVPValue(IncomingValue),
4514                         VPIteration(UF - 1, Lane));
4515     LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
4516   }
4517 }
4518 
4519 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4520   // The basic block and loop containing the predicated instruction.
4521   auto *PredBB = PredInst->getParent();
4522   auto *VectorLoop = LI->getLoopFor(PredBB);
4523 
4524   // Initialize a worklist with the operands of the predicated instruction.
4525   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4526 
4527   // Holds instructions that we need to analyze again. An instruction may be
4528   // reanalyzed if we don't yet know if we can sink it or not.
4529   SmallVector<Instruction *, 8> InstsToReanalyze;
4530 
4531   // Returns true if a given use occurs in the predicated block. Phi nodes use
4532   // their operands in their corresponding predecessor blocks.
4533   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4534     auto *I = cast<Instruction>(U.getUser());
4535     BasicBlock *BB = I->getParent();
4536     if (auto *Phi = dyn_cast<PHINode>(I))
4537       BB = Phi->getIncomingBlock(
4538           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4539     return BB == PredBB;
4540   };
4541 
4542   // Iteratively sink the scalarized operands of the predicated instruction
4543   // into the block we created for it. When an instruction is sunk, it's
4544   // operands are then added to the worklist. The algorithm ends after one pass
4545   // through the worklist doesn't sink a single instruction.
4546   bool Changed;
4547   do {
4548     // Add the instructions that need to be reanalyzed to the worklist, and
4549     // reset the changed indicator.
4550     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4551     InstsToReanalyze.clear();
4552     Changed = false;
4553 
4554     while (!Worklist.empty()) {
4555       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4556 
4557       // We can't sink an instruction if it is a phi node, is already in the
4558       // predicated block, is not in the loop, or may have side effects.
4559       if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
4560           !VectorLoop->contains(I) || I->mayHaveSideEffects())
4561         continue;
4562 
4563       // It's legal to sink the instruction if all its uses occur in the
4564       // predicated block. Otherwise, there's nothing to do yet, and we may
4565       // need to reanalyze the instruction.
4566       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4567         InstsToReanalyze.push_back(I);
4568         continue;
4569       }
4570 
4571       // Move the instruction to the beginning of the predicated block, and add
4572       // it's operands to the worklist.
4573       I->moveBefore(&*PredBB->getFirstInsertionPt());
4574       Worklist.insert(I->op_begin(), I->op_end());
4575 
4576       // The sinking may have enabled other instructions to be sunk, so we will
4577       // need to iterate.
4578       Changed = true;
4579     }
4580   } while (Changed);
4581 }
4582 
4583 void InnerLoopVectorizer::fixNonInductionPHIs(VPTransformState &State) {
4584   for (PHINode *OrigPhi : OrigPHIsToFix) {
4585     VPWidenPHIRecipe *VPPhi =
4586         cast<VPWidenPHIRecipe>(State.Plan->getVPValue(OrigPhi));
4587     PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4588     // Make sure the builder has a valid insert point.
4589     Builder.SetInsertPoint(NewPhi);
4590     for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4591       VPValue *Inc = VPPhi->getIncomingValue(i);
4592       VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4593       NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4594     }
4595   }
4596 }
4597 
4598 void InnerLoopVectorizer::widenGEP(GetElementPtrInst *GEP, VPValue *VPDef,
4599                                    VPUser &Operands, unsigned UF,
4600                                    ElementCount VF, bool IsPtrLoopInvariant,
4601                                    SmallBitVector &IsIndexLoopInvariant,
4602                                    VPTransformState &State) {
4603   // Construct a vector GEP by widening the operands of the scalar GEP as
4604   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
4605   // results in a vector of pointers when at least one operand of the GEP
4606   // is vector-typed. Thus, to keep the representation compact, we only use
4607   // vector-typed operands for loop-varying values.
4608 
4609   if (VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
4610     // If we are vectorizing, but the GEP has only loop-invariant operands,
4611     // the GEP we build (by only using vector-typed operands for
4612     // loop-varying values) would be a scalar pointer. Thus, to ensure we
4613     // produce a vector of pointers, we need to either arbitrarily pick an
4614     // operand to broadcast, or broadcast a clone of the original GEP.
4615     // Here, we broadcast a clone of the original.
4616     //
4617     // TODO: If at some point we decide to scalarize instructions having
4618     //       loop-invariant operands, this special case will no longer be
4619     //       required. We would add the scalarization decision to
4620     //       collectLoopScalars() and teach getVectorValue() to broadcast
4621     //       the lane-zero scalar value.
4622     auto *Clone = Builder.Insert(GEP->clone());
4623     for (unsigned Part = 0; Part < UF; ++Part) {
4624       Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
4625       State.set(VPDef, EntryPart, Part);
4626       addMetadata(EntryPart, GEP);
4627     }
4628   } else {
4629     // If the GEP has at least one loop-varying operand, we are sure to
4630     // produce a vector of pointers. But if we are only unrolling, we want
4631     // to produce a scalar GEP for each unroll part. Thus, the GEP we
4632     // produce with the code below will be scalar (if VF == 1) or vector
4633     // (otherwise). Note that for the unroll-only case, we still maintain
4634     // values in the vector mapping with initVector, as we do for other
4635     // instructions.
4636     for (unsigned Part = 0; Part < UF; ++Part) {
4637       // The pointer operand of the new GEP. If it's loop-invariant, we
4638       // won't broadcast it.
4639       auto *Ptr = IsPtrLoopInvariant
4640                       ? State.get(Operands.getOperand(0), VPIteration(0, 0))
4641                       : State.get(Operands.getOperand(0), Part);
4642 
4643       // Collect all the indices for the new GEP. If any index is
4644       // loop-invariant, we won't broadcast it.
4645       SmallVector<Value *, 4> Indices;
4646       for (unsigned I = 1, E = Operands.getNumOperands(); I < E; I++) {
4647         VPValue *Operand = Operands.getOperand(I);
4648         if (IsIndexLoopInvariant[I - 1])
4649           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
4650         else
4651           Indices.push_back(State.get(Operand, Part));
4652       }
4653 
4654       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
4655       // but it should be a vector, otherwise.
4656       auto *NewGEP =
4657           GEP->isInBounds()
4658               ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
4659                                           Indices)
4660               : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
4661       assert((VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
4662              "NewGEP is not a pointer vector");
4663       State.set(VPDef, NewGEP, Part);
4664       addMetadata(NewGEP, GEP);
4665     }
4666   }
4667 }
4668 
4669 void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
4670                                               RecurrenceDescriptor *RdxDesc,
4671                                               VPWidenPHIRecipe *PhiR,
4672                                               VPTransformState &State) {
4673   PHINode *P = cast<PHINode>(PN);
4674   if (EnableVPlanNativePath) {
4675     // Currently we enter here in the VPlan-native path for non-induction
4676     // PHIs where all control flow is uniform. We simply widen these PHIs.
4677     // Create a vector phi with no operands - the vector phi operands will be
4678     // set at the end of vector code generation.
4679     Type *VecTy = (State.VF.isScalar())
4680                       ? PN->getType()
4681                       : VectorType::get(PN->getType(), State.VF);
4682     Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
4683     State.set(PhiR, VecPhi, 0);
4684     OrigPHIsToFix.push_back(P);
4685 
4686     return;
4687   }
4688 
4689   assert(PN->getParent() == OrigLoop->getHeader() &&
4690          "Non-header phis should have been handled elsewhere");
4691 
4692   VPValue *StartVPV = PhiR->getStartValue();
4693   Value *StartV = StartVPV ? StartVPV->getLiveInIRValue() : nullptr;
4694   // In order to support recurrences we need to be able to vectorize Phi nodes.
4695   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
4696   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
4697   // this value when we vectorize all of the instructions that use the PHI.
4698   if (RdxDesc || Legal->isFirstOrderRecurrence(P)) {
4699     Value *Iden = nullptr;
4700     bool ScalarPHI =
4701         (State.VF.isScalar()) || Cost->isInLoopReduction(cast<PHINode>(PN));
4702     Type *VecTy =
4703         ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF);
4704 
4705     if (RdxDesc) {
4706       assert(Legal->isReductionVariable(P) && StartV &&
4707              "RdxDesc should only be set for reduction variables; in that case "
4708              "a StartV is also required");
4709       RecurKind RK = RdxDesc->getRecurrenceKind();
4710       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK)) {
4711         // MinMax reduction have the start value as their identify.
4712         if (ScalarPHI) {
4713           Iden = StartV;
4714         } else {
4715           IRBuilderBase::InsertPointGuard IPBuilder(Builder);
4716           Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4717           StartV = Iden =
4718               Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident");
4719         }
4720       } else {
4721         Constant *IdenC = RecurrenceDescriptor::getRecurrenceIdentity(
4722             RK, VecTy->getScalarType(), RdxDesc->getFastMathFlags());
4723         Iden = IdenC;
4724 
4725         if (!ScalarPHI) {
4726           Iden = ConstantVector::getSplat(State.VF, IdenC);
4727           IRBuilderBase::InsertPointGuard IPBuilder(Builder);
4728           Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
4729           Constant *Zero = Builder.getInt32(0);
4730           StartV = Builder.CreateInsertElement(Iden, StartV, Zero);
4731         }
4732       }
4733     }
4734 
4735     bool IsOrdered = State.VF.isVector() &&
4736                      Cost->isInLoopReduction(cast<PHINode>(PN)) &&
4737                      useOrderedReductions(*RdxDesc);
4738 
4739     for (unsigned Part = 0; Part < State.UF; ++Part) {
4740       // This is phase one of vectorizing PHIs.
4741       if (Part > 0 && IsOrdered)
4742         return;
4743       Value *EntryPart = PHINode::Create(
4744           VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
4745       State.set(PhiR, EntryPart, Part);
4746       if (StartV) {
4747         // Make sure to add the reduction start value only to the
4748         // first unroll part.
4749         Value *StartVal = (Part == 0) ? StartV : Iden;
4750         cast<PHINode>(EntryPart)->addIncoming(StartVal, LoopVectorPreHeader);
4751       }
4752     }
4753     return;
4754   }
4755 
4756   assert(!Legal->isReductionVariable(P) &&
4757          "reductions should be handled above");
4758 
4759   setDebugLocFromInst(Builder, P);
4760 
4761   // This PHINode must be an induction variable.
4762   // Make sure that we know about it.
4763   assert(Legal->getInductionVars().count(P) && "Not an induction variable");
4764 
4765   InductionDescriptor II = Legal->getInductionVars().lookup(P);
4766   const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
4767 
4768   // FIXME: The newly created binary instructions should contain nsw/nuw flags,
4769   // which can be found from the original scalar operations.
4770   switch (II.getKind()) {
4771   case InductionDescriptor::IK_NoInduction:
4772     llvm_unreachable("Unknown induction");
4773   case InductionDescriptor::IK_IntInduction:
4774   case InductionDescriptor::IK_FpInduction:
4775     llvm_unreachable("Integer/fp induction is handled elsewhere.");
4776   case InductionDescriptor::IK_PtrInduction: {
4777     // Handle the pointer induction variable case.
4778     assert(P->getType()->isPointerTy() && "Unexpected type.");
4779 
4780     if (Cost->isScalarAfterVectorization(P, State.VF)) {
4781       // This is the normalized GEP that starts counting at zero.
4782       Value *PtrInd =
4783           Builder.CreateSExtOrTrunc(Induction, II.getStep()->getType());
4784       // Determine the number of scalars we need to generate for each unroll
4785       // iteration. If the instruction is uniform, we only need to generate the
4786       // first lane. Otherwise, we generate all VF values.
4787       bool IsUniform = Cost->isUniformAfterVectorization(P, State.VF);
4788       assert((IsUniform || !VF.isScalable()) &&
4789              "Currently unsupported for scalable vectors");
4790       unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
4791 
4792       for (unsigned Part = 0; Part < UF; ++Part) {
4793         Value *PartStart = createStepForVF(
4794             Builder, ConstantInt::get(PtrInd->getType(), Part), VF);
4795         for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
4796           Value *Idx = Builder.CreateAdd(
4797               PartStart, ConstantInt::get(PtrInd->getType(), Lane));
4798           Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
4799           Value *SclrGep =
4800               emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
4801           SclrGep->setName("next.gep");
4802           State.set(PhiR, SclrGep, VPIteration(Part, Lane));
4803         }
4804       }
4805       return;
4806     }
4807     assert(isa<SCEVConstant>(II.getStep()) &&
4808            "Induction step not a SCEV constant!");
4809     Type *PhiType = II.getStep()->getType();
4810 
4811     // Build a pointer phi
4812     Value *ScalarStartValue = II.getStartValue();
4813     Type *ScStValueType = ScalarStartValue->getType();
4814     PHINode *NewPointerPhi =
4815         PHINode::Create(ScStValueType, 2, "pointer.phi", Induction);
4816     NewPointerPhi->addIncoming(ScalarStartValue, LoopVectorPreHeader);
4817 
4818     // A pointer induction, performed by using a gep
4819     BasicBlock *LoopLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
4820     Instruction *InductionLoc = LoopLatch->getTerminator();
4821     const SCEV *ScalarStep = II.getStep();
4822     SCEVExpander Exp(*PSE.getSE(), DL, "induction");
4823     Value *ScalarStepValue =
4824         Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
4825     Value *RuntimeVF = getRuntimeVF(Builder, PhiType, VF);
4826     Value *NumUnrolledElems =
4827         Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
4828     Value *InductionGEP = GetElementPtrInst::Create(
4829         ScStValueType->getPointerElementType(), NewPointerPhi,
4830         Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
4831         InductionLoc);
4832     NewPointerPhi->addIncoming(InductionGEP, LoopLatch);
4833 
4834     // Create UF many actual address geps that use the pointer
4835     // phi as base and a vectorized version of the step value
4836     // (<step*0, ..., step*N>) as offset.
4837     for (unsigned Part = 0; Part < State.UF; ++Part) {
4838       Type *VecPhiType = VectorType::get(PhiType, State.VF);
4839       Value *StartOffsetScalar =
4840           Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
4841       Value *StartOffset =
4842           Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
4843       // Create a vector of consecutive numbers from zero to VF.
4844       StartOffset =
4845           Builder.CreateAdd(StartOffset, Builder.CreateStepVector(VecPhiType));
4846 
4847       Value *GEP = Builder.CreateGEP(
4848           ScStValueType->getPointerElementType(), NewPointerPhi,
4849           Builder.CreateMul(
4850               StartOffset, Builder.CreateVectorSplat(State.VF, ScalarStepValue),
4851               "vector.gep"));
4852       State.set(PhiR, GEP, Part);
4853     }
4854   }
4855   }
4856 }
4857 
4858 /// A helper function for checking whether an integer division-related
4859 /// instruction may divide by zero (in which case it must be predicated if
4860 /// executed conditionally in the scalar code).
4861 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4862 /// Non-zero divisors that are non compile-time constants will not be
4863 /// converted into multiplication, so we will still end up scalarizing
4864 /// the division, but can do so w/o predication.
4865 static bool mayDivideByZero(Instruction &I) {
4866   assert((I.getOpcode() == Instruction::UDiv ||
4867           I.getOpcode() == Instruction::SDiv ||
4868           I.getOpcode() == Instruction::URem ||
4869           I.getOpcode() == Instruction::SRem) &&
4870          "Unexpected instruction");
4871   Value *Divisor = I.getOperand(1);
4872   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4873   return !CInt || CInt->isZero();
4874 }
4875 
4876 void InnerLoopVectorizer::widenInstruction(Instruction &I, VPValue *Def,
4877                                            VPUser &User,
4878                                            VPTransformState &State) {
4879   switch (I.getOpcode()) {
4880   case Instruction::Call:
4881   case Instruction::Br:
4882   case Instruction::PHI:
4883   case Instruction::GetElementPtr:
4884   case Instruction::Select:
4885     llvm_unreachable("This instruction is handled by a different recipe.");
4886   case Instruction::UDiv:
4887   case Instruction::SDiv:
4888   case Instruction::SRem:
4889   case Instruction::URem:
4890   case Instruction::Add:
4891   case Instruction::FAdd:
4892   case Instruction::Sub:
4893   case Instruction::FSub:
4894   case Instruction::FNeg:
4895   case Instruction::Mul:
4896   case Instruction::FMul:
4897   case Instruction::FDiv:
4898   case Instruction::FRem:
4899   case Instruction::Shl:
4900   case Instruction::LShr:
4901   case Instruction::AShr:
4902   case Instruction::And:
4903   case Instruction::Or:
4904   case Instruction::Xor: {
4905     // Just widen unops and binops.
4906     setDebugLocFromInst(Builder, &I);
4907 
4908     for (unsigned Part = 0; Part < UF; ++Part) {
4909       SmallVector<Value *, 2> Ops;
4910       for (VPValue *VPOp : User.operands())
4911         Ops.push_back(State.get(VPOp, Part));
4912 
4913       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
4914 
4915       if (auto *VecOp = dyn_cast<Instruction>(V))
4916         VecOp->copyIRFlags(&I);
4917 
4918       // Use this vector value for all users of the original instruction.
4919       State.set(Def, V, Part);
4920       addMetadata(V, &I);
4921     }
4922 
4923     break;
4924   }
4925   case Instruction::ICmp:
4926   case Instruction::FCmp: {
4927     // Widen compares. Generate vector compares.
4928     bool FCmp = (I.getOpcode() == Instruction::FCmp);
4929     auto *Cmp = cast<CmpInst>(&I);
4930     setDebugLocFromInst(Builder, Cmp);
4931     for (unsigned Part = 0; Part < UF; ++Part) {
4932       Value *A = State.get(User.getOperand(0), Part);
4933       Value *B = State.get(User.getOperand(1), Part);
4934       Value *C = nullptr;
4935       if (FCmp) {
4936         // Propagate fast math flags.
4937         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
4938         Builder.setFastMathFlags(Cmp->getFastMathFlags());
4939         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
4940       } else {
4941         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
4942       }
4943       State.set(Def, C, Part);
4944       addMetadata(C, &I);
4945     }
4946 
4947     break;
4948   }
4949 
4950   case Instruction::ZExt:
4951   case Instruction::SExt:
4952   case Instruction::FPToUI:
4953   case Instruction::FPToSI:
4954   case Instruction::FPExt:
4955   case Instruction::PtrToInt:
4956   case Instruction::IntToPtr:
4957   case Instruction::SIToFP:
4958   case Instruction::UIToFP:
4959   case Instruction::Trunc:
4960   case Instruction::FPTrunc:
4961   case Instruction::BitCast: {
4962     auto *CI = cast<CastInst>(&I);
4963     setDebugLocFromInst(Builder, CI);
4964 
4965     /// Vectorize casts.
4966     Type *DestTy =
4967         (VF.isScalar()) ? CI->getType() : VectorType::get(CI->getType(), VF);
4968 
4969     for (unsigned Part = 0; Part < UF; ++Part) {
4970       Value *A = State.get(User.getOperand(0), Part);
4971       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
4972       State.set(Def, Cast, Part);
4973       addMetadata(Cast, &I);
4974     }
4975     break;
4976   }
4977   default:
4978     // This instruction is not vectorized by simple widening.
4979     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
4980     llvm_unreachable("Unhandled instruction!");
4981   } // end of switch.
4982 }
4983 
4984 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4985                                                VPUser &ArgOperands,
4986                                                VPTransformState &State) {
4987   assert(!isa<DbgInfoIntrinsic>(I) &&
4988          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4989   setDebugLocFromInst(Builder, &I);
4990 
4991   Module *M = I.getParent()->getParent()->getParent();
4992   auto *CI = cast<CallInst>(&I);
4993 
4994   SmallVector<Type *, 4> Tys;
4995   for (Value *ArgOperand : CI->arg_operands())
4996     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4997 
4998   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4999 
5000   // The flag shows whether we use Intrinsic or a usual Call for vectorized
5001   // version of the instruction.
5002   // Is it beneficial to perform intrinsic call compared to lib call?
5003   bool NeedToScalarize = false;
5004   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
5005   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
5006   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
5007   assert((UseVectorIntrinsic || !NeedToScalarize) &&
5008          "Instruction should be scalarized elsewhere.");
5009   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
5010          "Either the intrinsic cost or vector call cost must be valid");
5011 
5012   for (unsigned Part = 0; Part < UF; ++Part) {
5013     SmallVector<Value *, 4> Args;
5014     for (auto &I : enumerate(ArgOperands.operands())) {
5015       // Some intrinsics have a scalar argument - don't replace it with a
5016       // vector.
5017       Value *Arg;
5018       if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, I.index()))
5019         Arg = State.get(I.value(), Part);
5020       else
5021         Arg = State.get(I.value(), VPIteration(0, 0));
5022       Args.push_back(Arg);
5023     }
5024 
5025     Function *VectorF;
5026     if (UseVectorIntrinsic) {
5027       // Use vector version of the intrinsic.
5028       Type *TysForDecl[] = {CI->getType()};
5029       if (VF.isVector())
5030         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
5031       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
5032       assert(VectorF && "Can't retrieve vector intrinsic.");
5033     } else {
5034       // Use vector version of the function call.
5035       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
5036 #ifndef NDEBUG
5037       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
5038              "Can't create vector function.");
5039 #endif
5040         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
5041     }
5042       SmallVector<OperandBundleDef, 1> OpBundles;
5043       CI->getOperandBundlesAsDefs(OpBundles);
5044       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
5045 
5046       if (isa<FPMathOperator>(V))
5047         V->copyFastMathFlags(CI);
5048 
5049       State.set(Def, V, Part);
5050       addMetadata(V, &I);
5051   }
5052 }
5053 
5054 void InnerLoopVectorizer::widenSelectInstruction(SelectInst &I, VPValue *VPDef,
5055                                                  VPUser &Operands,
5056                                                  bool InvariantCond,
5057                                                  VPTransformState &State) {
5058   setDebugLocFromInst(Builder, &I);
5059 
5060   // The condition can be loop invariant  but still defined inside the
5061   // loop. This means that we can't just use the original 'cond' value.
5062   // We have to take the 'vectorized' value and pick the first lane.
5063   // Instcombine will make this a no-op.
5064   auto *InvarCond = InvariantCond
5065                         ? State.get(Operands.getOperand(0), VPIteration(0, 0))
5066                         : nullptr;
5067 
5068   for (unsigned Part = 0; Part < UF; ++Part) {
5069     Value *Cond =
5070         InvarCond ? InvarCond : State.get(Operands.getOperand(0), Part);
5071     Value *Op0 = State.get(Operands.getOperand(1), Part);
5072     Value *Op1 = State.get(Operands.getOperand(2), Part);
5073     Value *Sel = Builder.CreateSelect(Cond, Op0, Op1);
5074     State.set(VPDef, Sel, Part);
5075     addMetadata(Sel, &I);
5076   }
5077 }
5078 
5079 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
5080   // We should not collect Scalars more than once per VF. Right now, this
5081   // function is called from collectUniformsAndScalars(), which already does
5082   // this check. Collecting Scalars for VF=1 does not make any sense.
5083   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
5084          "This function should not be visited twice for the same VF");
5085 
5086   SmallSetVector<Instruction *, 8> Worklist;
5087 
5088   // These sets are used to seed the analysis with pointers used by memory
5089   // accesses that will remain scalar.
5090   SmallSetVector<Instruction *, 8> ScalarPtrs;
5091   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
5092   auto *Latch = TheLoop->getLoopLatch();
5093 
5094   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
5095   // The pointer operands of loads and stores will be scalar as long as the
5096   // memory access is not a gather or scatter operation. The value operand of a
5097   // store will remain scalar if the store is scalarized.
5098   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
5099     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
5100     assert(WideningDecision != CM_Unknown &&
5101            "Widening decision should be ready at this moment");
5102     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
5103       if (Ptr == Store->getValueOperand())
5104         return WideningDecision == CM_Scalarize;
5105     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
5106            "Ptr is neither a value or pointer operand");
5107     return WideningDecision != CM_GatherScatter;
5108   };
5109 
5110   // A helper that returns true if the given value is a bitcast or
5111   // getelementptr instruction contained in the loop.
5112   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
5113     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
5114             isa<GetElementPtrInst>(V)) &&
5115            !TheLoop->isLoopInvariant(V);
5116   };
5117 
5118   auto isScalarPtrInduction = [&](Instruction *MemAccess, Value *Ptr) {
5119     if (!isa<PHINode>(Ptr) ||
5120         !Legal->getInductionVars().count(cast<PHINode>(Ptr)))
5121       return false;
5122     auto &Induction = Legal->getInductionVars()[cast<PHINode>(Ptr)];
5123     if (Induction.getKind() != InductionDescriptor::IK_PtrInduction)
5124       return false;
5125     return isScalarUse(MemAccess, Ptr);
5126   };
5127 
5128   // A helper that evaluates a memory access's use of a pointer. If the
5129   // pointer is actually the pointer induction of a loop, it is being
5130   // inserted into Worklist. If the use will be a scalar use, and the
5131   // pointer is only used by memory accesses, we place the pointer in
5132   // ScalarPtrs. Otherwise, the pointer is placed in PossibleNonScalarPtrs.
5133   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
5134     if (isScalarPtrInduction(MemAccess, Ptr)) {
5135       Worklist.insert(cast<Instruction>(Ptr));
5136       Instruction *Update = cast<Instruction>(
5137           cast<PHINode>(Ptr)->getIncomingValueForBlock(Latch));
5138       Worklist.insert(Update);
5139       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Ptr
5140                         << "\n");
5141       LLVM_DEBUG(dbgs() << "LV: Found new scalar instruction: " << *Update
5142                         << "\n");
5143       return;
5144     }
5145     // We only care about bitcast and getelementptr instructions contained in
5146     // the loop.
5147     if (!isLoopVaryingBitCastOrGEP(Ptr))
5148       return;
5149 
5150     // If the pointer has already been identified as scalar (e.g., if it was
5151     // also identified as uniform), there's nothing to do.
5152     auto *I = cast<Instruction>(Ptr);
5153     if (Worklist.count(I))
5154       return;
5155 
5156     // If the use of the pointer will be a scalar use, and all users of the
5157     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
5158     // place the pointer in PossibleNonScalarPtrs.
5159     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
5160           return isa<LoadInst>(U) || isa<StoreInst>(U);
5161         }))
5162       ScalarPtrs.insert(I);
5163     else
5164       PossibleNonScalarPtrs.insert(I);
5165   };
5166 
5167   // We seed the scalars analysis with three classes of instructions: (1)
5168   // instructions marked uniform-after-vectorization and (2) bitcast,
5169   // getelementptr and (pointer) phi instructions used by memory accesses
5170   // requiring a scalar use.
5171   //
5172   // (1) Add to the worklist all instructions that have been identified as
5173   // uniform-after-vectorization.
5174   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
5175 
5176   // (2) Add to the worklist all bitcast and getelementptr instructions used by
5177   // memory accesses requiring a scalar use. The pointer operands of loads and
5178   // stores will be scalar as long as the memory accesses is not a gather or
5179   // scatter operation. The value operand of a store will remain scalar if the
5180   // store is scalarized.
5181   for (auto *BB : TheLoop->blocks())
5182     for (auto &I : *BB) {
5183       if (auto *Load = dyn_cast<LoadInst>(&I)) {
5184         evaluatePtrUse(Load, Load->getPointerOperand());
5185       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
5186         evaluatePtrUse(Store, Store->getPointerOperand());
5187         evaluatePtrUse(Store, Store->getValueOperand());
5188       }
5189     }
5190   for (auto *I : ScalarPtrs)
5191     if (!PossibleNonScalarPtrs.count(I)) {
5192       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
5193       Worklist.insert(I);
5194     }
5195 
5196   // Insert the forced scalars.
5197   // FIXME: Currently widenPHIInstruction() often creates a dead vector
5198   // induction variable when the PHI user is scalarized.
5199   auto ForcedScalar = ForcedScalars.find(VF);
5200   if (ForcedScalar != ForcedScalars.end())
5201     for (auto *I : ForcedScalar->second)
5202       Worklist.insert(I);
5203 
5204   // Expand the worklist by looking through any bitcasts and getelementptr
5205   // instructions we've already identified as scalar. This is similar to the
5206   // expansion step in collectLoopUniforms(); however, here we're only
5207   // expanding to include additional bitcasts and getelementptr instructions.
5208   unsigned Idx = 0;
5209   while (Idx != Worklist.size()) {
5210     Instruction *Dst = Worklist[Idx++];
5211     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
5212       continue;
5213     auto *Src = cast<Instruction>(Dst->getOperand(0));
5214     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
5215           auto *J = cast<Instruction>(U);
5216           return !TheLoop->contains(J) || Worklist.count(J) ||
5217                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
5218                   isScalarUse(J, Src));
5219         })) {
5220       Worklist.insert(Src);
5221       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
5222     }
5223   }
5224 
5225   // An induction variable will remain scalar if all users of the induction
5226   // variable and induction variable update remain scalar.
5227   for (auto &Induction : Legal->getInductionVars()) {
5228     auto *Ind = Induction.first;
5229     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5230 
5231     // If tail-folding is applied, the primary induction variable will be used
5232     // to feed a vector compare.
5233     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
5234       continue;
5235 
5236     // Determine if all users of the induction variable are scalar after
5237     // vectorization.
5238     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5239       auto *I = cast<Instruction>(U);
5240       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
5241     });
5242     if (!ScalarInd)
5243       continue;
5244 
5245     // Determine if all users of the induction variable update instruction are
5246     // scalar after vectorization.
5247     auto ScalarIndUpdate =
5248         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5249           auto *I = cast<Instruction>(U);
5250           return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
5251         });
5252     if (!ScalarIndUpdate)
5253       continue;
5254 
5255     // The induction variable and its update instruction will remain scalar.
5256     Worklist.insert(Ind);
5257     Worklist.insert(IndUpdate);
5258     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
5259     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
5260                       << "\n");
5261   }
5262 
5263   Scalars[VF].insert(Worklist.begin(), Worklist.end());
5264 }
5265 
5266 bool LoopVectorizationCostModel::isScalarWithPredication(
5267     Instruction *I, ElementCount VF) const {
5268   if (!blockNeedsPredication(I->getParent()))
5269     return false;
5270   switch(I->getOpcode()) {
5271   default:
5272     break;
5273   case Instruction::Load:
5274   case Instruction::Store: {
5275     if (!Legal->isMaskRequired(I))
5276       return false;
5277     auto *Ptr = getLoadStorePointerOperand(I);
5278     auto *Ty = getMemInstValueType(I);
5279     // We have already decided how to vectorize this instruction, get that
5280     // result.
5281     if (VF.isVector()) {
5282       InstWidening WideningDecision = getWideningDecision(I, VF);
5283       assert(WideningDecision != CM_Unknown &&
5284              "Widening decision should be ready at this moment");
5285       return WideningDecision == CM_Scalarize;
5286     }
5287     const Align Alignment = getLoadStoreAlignment(I);
5288     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
5289                                 isLegalMaskedGather(Ty, Alignment))
5290                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
5291                                 isLegalMaskedScatter(Ty, Alignment));
5292   }
5293   case Instruction::UDiv:
5294   case Instruction::SDiv:
5295   case Instruction::SRem:
5296   case Instruction::URem:
5297     return mayDivideByZero(*I);
5298   }
5299   return false;
5300 }
5301 
5302 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
5303     Instruction *I, ElementCount VF) {
5304   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
5305   assert(getWideningDecision(I, VF) == CM_Unknown &&
5306          "Decision should not be set yet.");
5307   auto *Group = getInterleavedAccessGroup(I);
5308   assert(Group && "Must have a group.");
5309 
5310   // If the instruction's allocated size doesn't equal it's type size, it
5311   // requires padding and will be scalarized.
5312   auto &DL = I->getModule()->getDataLayout();
5313   auto *ScalarTy = getMemInstValueType(I);
5314   if (hasIrregularType(ScalarTy, DL))
5315     return false;
5316 
5317   // Check if masking is required.
5318   // A Group may need masking for one of two reasons: it resides in a block that
5319   // needs predication, or it was decided to use masking to deal with gaps.
5320   bool PredicatedAccessRequiresMasking =
5321       Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
5322   bool AccessWithGapsRequiresMasking =
5323       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
5324   if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
5325     return true;
5326 
5327   // If masked interleaving is required, we expect that the user/target had
5328   // enabled it, because otherwise it either wouldn't have been created or
5329   // it should have been invalidated by the CostModel.
5330   assert(useMaskedInterleavedAccesses(TTI) &&
5331          "Masked interleave-groups for predicated accesses are not enabled.");
5332 
5333   auto *Ty = getMemInstValueType(I);
5334   const Align Alignment = getLoadStoreAlignment(I);
5335   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
5336                           : TTI.isLegalMaskedStore(Ty, Alignment);
5337 }
5338 
5339 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
5340     Instruction *I, ElementCount VF) {
5341   // Get and ensure we have a valid memory instruction.
5342   LoadInst *LI = dyn_cast<LoadInst>(I);
5343   StoreInst *SI = dyn_cast<StoreInst>(I);
5344   assert((LI || SI) && "Invalid memory instruction");
5345 
5346   auto *Ptr = getLoadStorePointerOperand(I);
5347 
5348   // In order to be widened, the pointer should be consecutive, first of all.
5349   if (!Legal->isConsecutivePtr(Ptr))
5350     return false;
5351 
5352   // If the instruction is a store located in a predicated block, it will be
5353   // scalarized.
5354   if (isScalarWithPredication(I))
5355     return false;
5356 
5357   // If the instruction's allocated size doesn't equal it's type size, it
5358   // requires padding and will be scalarized.
5359   auto &DL = I->getModule()->getDataLayout();
5360   auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
5361   if (hasIrregularType(ScalarTy, DL))
5362     return false;
5363 
5364   return true;
5365 }
5366 
5367 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
5368   // We should not collect Uniforms more than once per VF. Right now,
5369   // this function is called from collectUniformsAndScalars(), which
5370   // already does this check. Collecting Uniforms for VF=1 does not make any
5371   // sense.
5372 
5373   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
5374          "This function should not be visited twice for the same VF");
5375 
5376   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
5377   // not analyze again.  Uniforms.count(VF) will return 1.
5378   Uniforms[VF].clear();
5379 
5380   // We now know that the loop is vectorizable!
5381   // Collect instructions inside the loop that will remain uniform after
5382   // vectorization.
5383 
5384   // Global values, params and instructions outside of current loop are out of
5385   // scope.
5386   auto isOutOfScope = [&](Value *V) -> bool {
5387     Instruction *I = dyn_cast<Instruction>(V);
5388     return (!I || !TheLoop->contains(I));
5389   };
5390 
5391   SetVector<Instruction *> Worklist;
5392   BasicBlock *Latch = TheLoop->getLoopLatch();
5393 
5394   // Instructions that are scalar with predication must not be considered
5395   // uniform after vectorization, because that would create an erroneous
5396   // replicating region where only a single instance out of VF should be formed.
5397   // TODO: optimize such seldom cases if found important, see PR40816.
5398   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
5399     if (isOutOfScope(I)) {
5400       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
5401                         << *I << "\n");
5402       return;
5403     }
5404     if (isScalarWithPredication(I, VF)) {
5405       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
5406                         << *I << "\n");
5407       return;
5408     }
5409     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
5410     Worklist.insert(I);
5411   };
5412 
5413   // Start with the conditional branch. If the branch condition is an
5414   // instruction contained in the loop that is only used by the branch, it is
5415   // uniform.
5416   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
5417   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
5418     addToWorklistIfAllowed(Cmp);
5419 
5420   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
5421     InstWidening WideningDecision = getWideningDecision(I, VF);
5422     assert(WideningDecision != CM_Unknown &&
5423            "Widening decision should be ready at this moment");
5424 
5425     // A uniform memory op is itself uniform.  We exclude uniform stores
5426     // here as they demand the last lane, not the first one.
5427     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
5428       assert(WideningDecision == CM_Scalarize);
5429       return true;
5430     }
5431 
5432     return (WideningDecision == CM_Widen ||
5433             WideningDecision == CM_Widen_Reverse ||
5434             WideningDecision == CM_Interleave);
5435   };
5436 
5437 
5438   // Returns true if Ptr is the pointer operand of a memory access instruction
5439   // I, and I is known to not require scalarization.
5440   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
5441     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
5442   };
5443 
5444   // Holds a list of values which are known to have at least one uniform use.
5445   // Note that there may be other uses which aren't uniform.  A "uniform use"
5446   // here is something which only demands lane 0 of the unrolled iterations;
5447   // it does not imply that all lanes produce the same value (e.g. this is not
5448   // the usual meaning of uniform)
5449   SetVector<Value *> HasUniformUse;
5450 
5451   // Scan the loop for instructions which are either a) known to have only
5452   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
5453   for (auto *BB : TheLoop->blocks())
5454     for (auto &I : *BB) {
5455       // If there's no pointer operand, there's nothing to do.
5456       auto *Ptr = getLoadStorePointerOperand(&I);
5457       if (!Ptr)
5458         continue;
5459 
5460       // A uniform memory op is itself uniform.  We exclude uniform stores
5461       // here as they demand the last lane, not the first one.
5462       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
5463         addToWorklistIfAllowed(&I);
5464 
5465       if (isUniformDecision(&I, VF)) {
5466         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
5467         HasUniformUse.insert(Ptr);
5468       }
5469     }
5470 
5471   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
5472   // demanding) users.  Since loops are assumed to be in LCSSA form, this
5473   // disallows uses outside the loop as well.
5474   for (auto *V : HasUniformUse) {
5475     if (isOutOfScope(V))
5476       continue;
5477     auto *I = cast<Instruction>(V);
5478     auto UsersAreMemAccesses =
5479       llvm::all_of(I->users(), [&](User *U) -> bool {
5480         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
5481       });
5482     if (UsersAreMemAccesses)
5483       addToWorklistIfAllowed(I);
5484   }
5485 
5486   // Expand Worklist in topological order: whenever a new instruction
5487   // is added , its users should be already inside Worklist.  It ensures
5488   // a uniform instruction will only be used by uniform instructions.
5489   unsigned idx = 0;
5490   while (idx != Worklist.size()) {
5491     Instruction *I = Worklist[idx++];
5492 
5493     for (auto OV : I->operand_values()) {
5494       // isOutOfScope operands cannot be uniform instructions.
5495       if (isOutOfScope(OV))
5496         continue;
5497       // First order recurrence Phi's should typically be considered
5498       // non-uniform.
5499       auto *OP = dyn_cast<PHINode>(OV);
5500       if (OP && Legal->isFirstOrderRecurrence(OP))
5501         continue;
5502       // If all the users of the operand are uniform, then add the
5503       // operand into the uniform worklist.
5504       auto *OI = cast<Instruction>(OV);
5505       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
5506             auto *J = cast<Instruction>(U);
5507             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
5508           }))
5509         addToWorklistIfAllowed(OI);
5510     }
5511   }
5512 
5513   // For an instruction to be added into Worklist above, all its users inside
5514   // the loop should also be in Worklist. However, this condition cannot be
5515   // true for phi nodes that form a cyclic dependence. We must process phi
5516   // nodes separately. An induction variable will remain uniform if all users
5517   // of the induction variable and induction variable update remain uniform.
5518   // The code below handles both pointer and non-pointer induction variables.
5519   for (auto &Induction : Legal->getInductionVars()) {
5520     auto *Ind = Induction.first;
5521     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
5522 
5523     // Determine if all users of the induction variable are uniform after
5524     // vectorization.
5525     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
5526       auto *I = cast<Instruction>(U);
5527       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
5528              isVectorizedMemAccessUse(I, Ind);
5529     });
5530     if (!UniformInd)
5531       continue;
5532 
5533     // Determine if all users of the induction variable update instruction are
5534     // uniform after vectorization.
5535     auto UniformIndUpdate =
5536         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
5537           auto *I = cast<Instruction>(U);
5538           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
5539                  isVectorizedMemAccessUse(I, IndUpdate);
5540         });
5541     if (!UniformIndUpdate)
5542       continue;
5543 
5544     // The induction variable and its update instruction will remain uniform.
5545     addToWorklistIfAllowed(Ind);
5546     addToWorklistIfAllowed(IndUpdate);
5547   }
5548 
5549   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
5550 }
5551 
5552 bool LoopVectorizationCostModel::runtimeChecksRequired() {
5553   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
5554 
5555   if (Legal->getRuntimePointerChecking()->Need) {
5556     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
5557         "runtime pointer checks needed. Enable vectorization of this "
5558         "loop with '#pragma clang loop vectorize(enable)' when "
5559         "compiling with -Os/-Oz",
5560         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5561     return true;
5562   }
5563 
5564   if (!PSE.getUnionPredicate().getPredicates().empty()) {
5565     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
5566         "runtime SCEV checks needed. Enable vectorization of this "
5567         "loop with '#pragma clang loop vectorize(enable)' when "
5568         "compiling with -Os/-Oz",
5569         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5570     return true;
5571   }
5572 
5573   // FIXME: Avoid specializing for stride==1 instead of bailing out.
5574   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
5575     reportVectorizationFailure("Runtime stride check for small trip count",
5576         "runtime stride == 1 checks needed. Enable vectorization of "
5577         "this loop without such check by compiling with -Os/-Oz",
5578         "CantVersionLoopWithOptForSize", ORE, TheLoop);
5579     return true;
5580   }
5581 
5582   return false;
5583 }
5584 
5585 Optional<ElementCount>
5586 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
5587   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
5588     // TODO: It may by useful to do since it's still likely to be dynamically
5589     // uniform if the target can skip.
5590     reportVectorizationFailure(
5591         "Not inserting runtime ptr check for divergent target",
5592         "runtime pointer checks needed. Not enabled for divergent target",
5593         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
5594     return None;
5595   }
5596 
5597   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
5598   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
5599   if (TC == 1) {
5600     reportVectorizationFailure("Single iteration (non) loop",
5601         "loop trip count is one, irrelevant for vectorization",
5602         "SingleIterationLoop", ORE, TheLoop);
5603     return None;
5604   }
5605 
5606   switch (ScalarEpilogueStatus) {
5607   case CM_ScalarEpilogueAllowed:
5608     return computeFeasibleMaxVF(TC, UserVF);
5609   case CM_ScalarEpilogueNotAllowedUsePredicate:
5610     LLVM_FALLTHROUGH;
5611   case CM_ScalarEpilogueNotNeededUsePredicate:
5612     LLVM_DEBUG(
5613         dbgs() << "LV: vector predicate hint/switch found.\n"
5614                << "LV: Not allowing scalar epilogue, creating predicated "
5615                << "vector loop.\n");
5616     break;
5617   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5618     // fallthrough as a special case of OptForSize
5619   case CM_ScalarEpilogueNotAllowedOptSize:
5620     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5621       LLVM_DEBUG(
5622           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5623     else
5624       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5625                         << "count.\n");
5626 
5627     // Bail if runtime checks are required, which are not good when optimising
5628     // for size.
5629     if (runtimeChecksRequired())
5630       return None;
5631 
5632     break;
5633   }
5634 
5635   // The only loops we can vectorize without a scalar epilogue, are loops with
5636   // a bottom-test and a single exiting block. We'd have to handle the fact
5637   // that not every instruction executes on the last iteration.  This will
5638   // require a lane mask which varies through the vector loop body.  (TODO)
5639   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5640     // If there was a tail-folding hint/switch, but we can't fold the tail by
5641     // masking, fallback to a vectorization with a scalar epilogue.
5642     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5643       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5644                            "scalar epilogue instead.\n");
5645       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5646       return computeFeasibleMaxVF(TC, UserVF);
5647     }
5648     return None;
5649   }
5650 
5651   // Now try the tail folding
5652 
5653   // Invalidate interleave groups that require an epilogue if we can't mask
5654   // the interleave-group.
5655   if (!useMaskedInterleavedAccesses(TTI)) {
5656     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5657            "No decisions should have been taken at this point");
5658     // Note: There is no need to invalidate any cost modeling decisions here, as
5659     // non where taken so far.
5660     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5661   }
5662 
5663   ElementCount MaxVF = computeFeasibleMaxVF(TC, UserVF);
5664   assert(!MaxVF.isScalable() &&
5665          "Scalable vectors do not yet support tail folding");
5666   assert((UserVF.isNonZero() || isPowerOf2_32(MaxVF.getFixedValue())) &&
5667          "MaxVF must be a power of 2");
5668   unsigned MaxVFtimesIC =
5669       UserIC ? MaxVF.getFixedValue() * UserIC : MaxVF.getFixedValue();
5670   // Avoid tail folding if the trip count is known to be a multiple of any VF we
5671   // chose.
5672   ScalarEvolution *SE = PSE.getSE();
5673   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5674   const SCEV *ExitCount = SE->getAddExpr(
5675       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5676   const SCEV *Rem = SE->getURemExpr(
5677       SE->applyLoopGuards(ExitCount, TheLoop),
5678       SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5679   if (Rem->isZero()) {
5680     // Accept MaxVF if we do not have a tail.
5681     LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5682     return MaxVF;
5683   }
5684 
5685   // If we don't know the precise trip count, or if the trip count that we
5686   // found modulo the vectorization factor is not zero, try to fold the tail
5687   // by masking.
5688   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5689   if (Legal->prepareToFoldTailByMasking()) {
5690     FoldTailByMasking = true;
5691     return MaxVF;
5692   }
5693 
5694   // If there was a tail-folding hint/switch, but we can't fold the tail by
5695   // masking, fallback to a vectorization with a scalar epilogue.
5696   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5697     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5698                          "scalar epilogue instead.\n");
5699     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5700     return MaxVF;
5701   }
5702 
5703   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5704     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5705     return None;
5706   }
5707 
5708   if (TC == 0) {
5709     reportVectorizationFailure(
5710         "Unable to calculate the loop count due to complex control flow",
5711         "unable to calculate the loop count due to complex control flow",
5712         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5713     return None;
5714   }
5715 
5716   reportVectorizationFailure(
5717       "Cannot optimize for size and vectorize at the same time.",
5718       "cannot optimize for size and vectorize at the same time. "
5719       "Enable vectorization of this loop with '#pragma clang loop "
5720       "vectorize(enable)' when compiling with -Os/-Oz",
5721       "NoTailLoopWithOptForSize", ORE, TheLoop);
5722   return None;
5723 }
5724 
5725 ElementCount
5726 LoopVectorizationCostModel::computeFeasibleMaxVF(unsigned ConstTripCount,
5727                                                  ElementCount UserVF) {
5728   bool IgnoreScalableUserVF = UserVF.isScalable() &&
5729                               !TTI.supportsScalableVectors() &&
5730                               !ForceTargetSupportsScalableVectors;
5731   if (IgnoreScalableUserVF) {
5732     LLVM_DEBUG(
5733         dbgs() << "LV: Ignoring VF=" << UserVF
5734                << " because target does not support scalable vectors.\n");
5735     ORE->emit([&]() {
5736       return OptimizationRemarkAnalysis(DEBUG_TYPE, "IgnoreScalableUserVF",
5737                                         TheLoop->getStartLoc(),
5738                                         TheLoop->getHeader())
5739              << "Ignoring VF=" << ore::NV("UserVF", UserVF)
5740              << " because target does not support scalable vectors.";
5741     });
5742   }
5743 
5744   // Beyond this point two scenarios are handled. If UserVF isn't specified
5745   // then a suitable VF is chosen. If UserVF is specified and there are
5746   // dependencies, check if it's legal. However, if a UserVF is specified and
5747   // there are no dependencies, then there's nothing to do.
5748   if (UserVF.isNonZero() && !IgnoreScalableUserVF) {
5749     if (!canVectorizeReductions(UserVF)) {
5750       reportVectorizationFailure(
5751           "LV: Scalable vectorization not supported for the reduction "
5752           "operations found in this loop. Using fixed-width "
5753           "vectorization instead.",
5754           "Scalable vectorization not supported for the reduction operations "
5755           "found in this loop. Using fixed-width vectorization instead.",
5756           "ScalableVFUnfeasible", ORE, TheLoop);
5757       return computeFeasibleMaxVF(
5758           ConstTripCount, ElementCount::getFixed(UserVF.getKnownMinValue()));
5759     }
5760 
5761     if (Legal->isSafeForAnyVectorWidth())
5762       return UserVF;
5763   }
5764 
5765   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
5766   unsigned SmallestType, WidestType;
5767   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
5768   unsigned WidestRegister =
5769       TTI.getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
5770           .getFixedSize();
5771 
5772   // Get the maximum safe dependence distance in bits computed by LAA.
5773   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
5774   // the memory accesses that is most restrictive (involved in the smallest
5775   // dependence distance).
5776   unsigned MaxSafeVectorWidthInBits = Legal->getMaxSafeVectorWidthInBits();
5777 
5778   // If the user vectorization factor is legally unsafe, clamp it to a safe
5779   // value. Otherwise, return as is.
5780   if (UserVF.isNonZero() && !IgnoreScalableUserVF) {
5781     unsigned MaxSafeElements =
5782         PowerOf2Floor(MaxSafeVectorWidthInBits / WidestType);
5783     ElementCount MaxSafeVF = ElementCount::getFixed(MaxSafeElements);
5784 
5785     if (UserVF.isScalable()) {
5786       Optional<unsigned> MaxVScale = TTI.getMaxVScale();
5787 
5788       // Scale VF by vscale before checking if it's safe.
5789       MaxSafeVF = ElementCount::getScalable(
5790           MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
5791 
5792       if (MaxSafeVF.isZero()) {
5793         // The dependence distance is too small to use scalable vectors,
5794         // fallback on fixed.
5795         LLVM_DEBUG(
5796             dbgs()
5797             << "LV: Max legal vector width too small, scalable vectorization "
5798                "unfeasible. Using fixed-width vectorization instead.\n");
5799         ORE->emit([&]() {
5800           return OptimizationRemarkAnalysis(DEBUG_TYPE, "ScalableVFUnfeasible",
5801                                             TheLoop->getStartLoc(),
5802                                             TheLoop->getHeader())
5803                  << "Max legal vector width too small, scalable vectorization "
5804                  << "unfeasible. Using fixed-width vectorization instead.";
5805         });
5806         return computeFeasibleMaxVF(
5807             ConstTripCount, ElementCount::getFixed(UserVF.getKnownMinValue()));
5808       }
5809     }
5810 
5811     LLVM_DEBUG(dbgs() << "LV: The max safe VF is: " << MaxSafeVF << ".\n");
5812 
5813     if (ElementCount::isKnownLE(UserVF, MaxSafeVF))
5814       return UserVF;
5815 
5816     LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
5817                       << " is unsafe, clamping to max safe VF=" << MaxSafeVF
5818                       << ".\n");
5819     ORE->emit([&]() {
5820       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
5821                                         TheLoop->getStartLoc(),
5822                                         TheLoop->getHeader())
5823              << "User-specified vectorization factor "
5824              << ore::NV("UserVectorizationFactor", UserVF)
5825              << " is unsafe, clamping to maximum safe vectorization factor "
5826              << ore::NV("VectorizationFactor", MaxSafeVF);
5827     });
5828     return MaxSafeVF;
5829   }
5830 
5831   WidestRegister = std::min(WidestRegister, MaxSafeVectorWidthInBits);
5832 
5833   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5834   // Note that both WidestRegister and WidestType may not be a powers of 2.
5835   auto MaxVectorSize =
5836       ElementCount::getFixed(PowerOf2Floor(WidestRegister / WidestType));
5837 
5838   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
5839                     << " / " << WidestType << " bits.\n");
5840   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5841                     << WidestRegister << " bits.\n");
5842 
5843   assert(MaxVectorSize.getFixedValue() <= WidestRegister &&
5844          "Did not expect to pack so many elements"
5845          " into one vector!");
5846   if (MaxVectorSize.getFixedValue() == 0) {
5847     LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
5848     return ElementCount::getFixed(1);
5849   } else if (ConstTripCount && ConstTripCount < MaxVectorSize.getFixedValue() &&
5850              isPowerOf2_32(ConstTripCount)) {
5851     // We need to clamp the VF to be the ConstTripCount. There is no point in
5852     // choosing a higher viable VF as done in the loop below.
5853     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
5854                       << ConstTripCount << "\n");
5855     return ElementCount::getFixed(ConstTripCount);
5856   }
5857 
5858   ElementCount MaxVF = MaxVectorSize;
5859   if (TTI.shouldMaximizeVectorBandwidth() ||
5860       (MaximizeBandwidth && isScalarEpilogueAllowed())) {
5861     // Collect all viable vectorization factors larger than the default MaxVF
5862     // (i.e. MaxVectorSize).
5863     SmallVector<ElementCount, 8> VFs;
5864     auto MaxVectorSizeMaxBW =
5865         ElementCount::getFixed(WidestRegister / SmallestType);
5866     for (ElementCount VS = MaxVectorSize * 2;
5867          ElementCount::isKnownLE(VS, MaxVectorSizeMaxBW); VS *= 2)
5868       VFs.push_back(VS);
5869 
5870     // For each VF calculate its register usage.
5871     auto RUs = calculateRegisterUsage(VFs);
5872 
5873     // Select the largest VF which doesn't require more registers than existing
5874     // ones.
5875     for (int i = RUs.size() - 1; i >= 0; --i) {
5876       bool Selected = true;
5877       for (auto &pair : RUs[i].MaxLocalUsers) {
5878         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5879         if (pair.second > TargetNumRegisters)
5880           Selected = false;
5881       }
5882       if (Selected) {
5883         MaxVF = VFs[i];
5884         break;
5885       }
5886     }
5887     if (ElementCount MinVF =
5888             TTI.getMinimumVF(SmallestType, /*IsScalable=*/false)) {
5889       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5890         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5891                           << ") with target's minimum: " << MinVF << '\n');
5892         MaxVF = MinVF;
5893       }
5894     }
5895   }
5896   return MaxVF;
5897 }
5898 
5899 bool LoopVectorizationCostModel::isMoreProfitable(
5900     const VectorizationFactor &A, const VectorizationFactor &B) const {
5901   InstructionCost::CostType CostA = *A.Cost.getValue();
5902   InstructionCost::CostType CostB = *B.Cost.getValue();
5903 
5904   // To avoid the need for FP division:
5905   //      (CostA / A.Width) < (CostB / B.Width)
5906   // <=>  (CostA * B.Width) < (CostB * A.Width)
5907   return (CostA * B.Width.getKnownMinValue()) <
5908          (CostB * A.Width.getKnownMinValue());
5909 }
5910 
5911 VectorizationFactor
5912 LoopVectorizationCostModel::selectVectorizationFactor(ElementCount MaxVF) {
5913   // FIXME: This can be fixed for scalable vectors later, because at this stage
5914   // the LoopVectorizer will only consider vectorizing a loop with scalable
5915   // vectors when the loop has a hint to enable vectorization for a given VF.
5916   assert(!MaxVF.isScalable() && "scalable vectors not yet supported");
5917 
5918   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5919   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5920   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5921 
5922   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost);
5923   VectorizationFactor ChosenFactor = ScalarCost;
5924 
5925   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5926   if (ForceVectorization && MaxVF.isVector()) {
5927     // Ignore scalar width, because the user explicitly wants vectorization.
5928     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5929     // evaluation.
5930     ChosenFactor.Cost = std::numeric_limits<InstructionCost::CostType>::max();
5931   }
5932 
5933   for (auto i = ElementCount::getFixed(2); ElementCount::isKnownLE(i, MaxVF);
5934        i *= 2) {
5935     // Notice that the vector loop needs to be executed less times, so
5936     // we need to divide the cost of the vector loops by the width of
5937     // the vector elements.
5938     VectorizationCostTy C = expectedCost(i);
5939 
5940     assert(C.first.isValid() && "Unexpected invalid cost for vector loop");
5941     VectorizationFactor Candidate(i, C.first);
5942     LLVM_DEBUG(
5943         dbgs() << "LV: Vector loop of width " << i << " costs: "
5944                << (*Candidate.Cost.getValue() / Candidate.Width.getFixedValue())
5945                << ".\n");
5946 
5947     if (!C.second && !ForceVectorization) {
5948       LLVM_DEBUG(
5949           dbgs() << "LV: Not considering vector loop of width " << i
5950                  << " because it will not generate any vector instructions.\n");
5951       continue;
5952     }
5953 
5954     // If profitable add it to ProfitableVF list.
5955     if (isMoreProfitable(Candidate, ScalarCost))
5956       ProfitableVFs.push_back(Candidate);
5957 
5958     if (isMoreProfitable(Candidate, ChosenFactor))
5959       ChosenFactor = Candidate;
5960   }
5961 
5962   if (!EnableCondStoresVectorization && NumPredStores) {
5963     reportVectorizationFailure("There are conditional stores.",
5964         "store that is conditionally executed prevents vectorization",
5965         "ConditionalStore", ORE, TheLoop);
5966     ChosenFactor = ScalarCost;
5967   }
5968 
5969   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
5970                  *ChosenFactor.Cost.getValue() >= *ScalarCost.Cost.getValue())
5971                  dbgs()
5972              << "LV: Vectorization seems to be not beneficial, "
5973              << "but was forced by a user.\n");
5974   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
5975   return ChosenFactor;
5976 }
5977 
5978 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5979     const Loop &L, ElementCount VF) const {
5980   // Cross iteration phis such as reductions need special handling and are
5981   // currently unsupported.
5982   if (any_of(L.getHeader()->phis(), [&](PHINode &Phi) {
5983         return Legal->isFirstOrderRecurrence(&Phi) ||
5984                Legal->isReductionVariable(&Phi);
5985       }))
5986     return false;
5987 
5988   // Phis with uses outside of the loop require special handling and are
5989   // currently unsupported.
5990   for (auto &Entry : Legal->getInductionVars()) {
5991     // Look for uses of the value of the induction at the last iteration.
5992     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5993     for (User *U : PostInc->users())
5994       if (!L.contains(cast<Instruction>(U)))
5995         return false;
5996     // Look for uses of penultimate value of the induction.
5997     for (User *U : Entry.first->users())
5998       if (!L.contains(cast<Instruction>(U)))
5999         return false;
6000   }
6001 
6002   // Induction variables that are widened require special handling that is
6003   // currently not supported.
6004   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
6005         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
6006                  this->isProfitableToScalarize(Entry.first, VF));
6007       }))
6008     return false;
6009 
6010   return true;
6011 }
6012 
6013 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
6014     const ElementCount VF) const {
6015   // FIXME: We need a much better cost-model to take different parameters such
6016   // as register pressure, code size increase and cost of extra branches into
6017   // account. For now we apply a very crude heuristic and only consider loops
6018   // with vectorization factors larger than a certain value.
6019   // We also consider epilogue vectorization unprofitable for targets that don't
6020   // consider interleaving beneficial (eg. MVE).
6021   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
6022     return false;
6023   if (VF.getFixedValue() >= EpilogueVectorizationMinVF)
6024     return true;
6025   return false;
6026 }
6027 
6028 VectorizationFactor
6029 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
6030     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
6031   VectorizationFactor Result = VectorizationFactor::Disabled();
6032   if (!EnableEpilogueVectorization) {
6033     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
6034     return Result;
6035   }
6036 
6037   if (!isScalarEpilogueAllowed()) {
6038     LLVM_DEBUG(
6039         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
6040                   "allowed.\n";);
6041     return Result;
6042   }
6043 
6044   // FIXME: This can be fixed for scalable vectors later, because at this stage
6045   // the LoopVectorizer will only consider vectorizing a loop with scalable
6046   // vectors when the loop has a hint to enable vectorization for a given VF.
6047   if (MainLoopVF.isScalable()) {
6048     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization for scalable vectors not "
6049                          "yet supported.\n");
6050     return Result;
6051   }
6052 
6053   // Not really a cost consideration, but check for unsupported cases here to
6054   // simplify the logic.
6055   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
6056     LLVM_DEBUG(
6057         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
6058                   "not a supported candidate.\n";);
6059     return Result;
6060   }
6061 
6062   if (EpilogueVectorizationForceVF > 1) {
6063     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
6064     if (LVP.hasPlanWithVFs(
6065             {MainLoopVF, ElementCount::getFixed(EpilogueVectorizationForceVF)}))
6066       return {ElementCount::getFixed(EpilogueVectorizationForceVF), 0};
6067     else {
6068       LLVM_DEBUG(
6069           dbgs()
6070               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
6071       return Result;
6072     }
6073   }
6074 
6075   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
6076       TheLoop->getHeader()->getParent()->hasMinSize()) {
6077     LLVM_DEBUG(
6078         dbgs()
6079             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
6080     return Result;
6081   }
6082 
6083   if (!isEpilogueVectorizationProfitable(MainLoopVF))
6084     return Result;
6085 
6086   for (auto &NextVF : ProfitableVFs)
6087     if (ElementCount::isKnownLT(NextVF.Width, MainLoopVF) &&
6088         (Result.Width.getFixedValue() == 1 ||
6089          isMoreProfitable(NextVF, Result)) &&
6090         LVP.hasPlanWithVFs({MainLoopVF, NextVF.Width}))
6091       Result = NextVF;
6092 
6093   if (Result != VectorizationFactor::Disabled())
6094     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
6095                       << Result.Width.getFixedValue() << "\n";);
6096   return Result;
6097 }
6098 
6099 std::pair<unsigned, unsigned>
6100 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
6101   unsigned MinWidth = -1U;
6102   unsigned MaxWidth = 8;
6103   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
6104 
6105   // For each block.
6106   for (BasicBlock *BB : TheLoop->blocks()) {
6107     // For each instruction in the loop.
6108     for (Instruction &I : BB->instructionsWithoutDebug()) {
6109       Type *T = I.getType();
6110 
6111       // Skip ignored values.
6112       if (ValuesToIgnore.count(&I))
6113         continue;
6114 
6115       // Only examine Loads, Stores and PHINodes.
6116       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
6117         continue;
6118 
6119       // Examine PHI nodes that are reduction variables. Update the type to
6120       // account for the recurrence type.
6121       if (auto *PN = dyn_cast<PHINode>(&I)) {
6122         if (!Legal->isReductionVariable(PN))
6123           continue;
6124         RecurrenceDescriptor RdxDesc = Legal->getReductionVars()[PN];
6125         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
6126             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
6127                                       RdxDesc.getRecurrenceType(),
6128                                       TargetTransformInfo::ReductionFlags()))
6129           continue;
6130         T = RdxDesc.getRecurrenceType();
6131       }
6132 
6133       // Examine the stored values.
6134       if (auto *ST = dyn_cast<StoreInst>(&I))
6135         T = ST->getValueOperand()->getType();
6136 
6137       // Ignore loaded pointer types and stored pointer types that are not
6138       // vectorizable.
6139       //
6140       // FIXME: The check here attempts to predict whether a load or store will
6141       //        be vectorized. We only know this for certain after a VF has
6142       //        been selected. Here, we assume that if an access can be
6143       //        vectorized, it will be. We should also look at extending this
6144       //        optimization to non-pointer types.
6145       //
6146       if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
6147           !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
6148         continue;
6149 
6150       MinWidth = std::min(MinWidth,
6151                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6152       MaxWidth = std::max(MaxWidth,
6153                           (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
6154     }
6155   }
6156 
6157   return {MinWidth, MaxWidth};
6158 }
6159 
6160 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
6161                                                            unsigned LoopCost) {
6162   // -- The interleave heuristics --
6163   // We interleave the loop in order to expose ILP and reduce the loop overhead.
6164   // There are many micro-architectural considerations that we can't predict
6165   // at this level. For example, frontend pressure (on decode or fetch) due to
6166   // code size, or the number and capabilities of the execution ports.
6167   //
6168   // We use the following heuristics to select the interleave count:
6169   // 1. If the code has reductions, then we interleave to break the cross
6170   // iteration dependency.
6171   // 2. If the loop is really small, then we interleave to reduce the loop
6172   // overhead.
6173   // 3. We don't interleave if we think that we will spill registers to memory
6174   // due to the increased register pressure.
6175 
6176   if (!isScalarEpilogueAllowed())
6177     return 1;
6178 
6179   // We used the distance for the interleave count.
6180   if (Legal->getMaxSafeDepDistBytes() != -1U)
6181     return 1;
6182 
6183   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
6184   const bool HasReductions = !Legal->getReductionVars().empty();
6185   // Do not interleave loops with a relatively small known or estimated trip
6186   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
6187   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
6188   // because with the above conditions interleaving can expose ILP and break
6189   // cross iteration dependences for reductions.
6190   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
6191       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
6192     return 1;
6193 
6194   RegisterUsage R = calculateRegisterUsage({VF})[0];
6195   // We divide by these constants so assume that we have at least one
6196   // instruction that uses at least one register.
6197   for (auto& pair : R.MaxLocalUsers) {
6198     pair.second = std::max(pair.second, 1U);
6199   }
6200 
6201   // We calculate the interleave count using the following formula.
6202   // Subtract the number of loop invariants from the number of available
6203   // registers. These registers are used by all of the interleaved instances.
6204   // Next, divide the remaining registers by the number of registers that is
6205   // required by the loop, in order to estimate how many parallel instances
6206   // fit without causing spills. All of this is rounded down if necessary to be
6207   // a power of two. We want power of two interleave count to simplify any
6208   // addressing operations or alignment considerations.
6209   // We also want power of two interleave counts to ensure that the induction
6210   // variable of the vector loop wraps to zero, when tail is folded by masking;
6211   // this currently happens when OptForSize, in which case IC is set to 1 above.
6212   unsigned IC = UINT_MAX;
6213 
6214   for (auto& pair : R.MaxLocalUsers) {
6215     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
6216     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
6217                       << " registers of "
6218                       << TTI.getRegisterClassName(pair.first) << " register class\n");
6219     if (VF.isScalar()) {
6220       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
6221         TargetNumRegisters = ForceTargetNumScalarRegs;
6222     } else {
6223       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
6224         TargetNumRegisters = ForceTargetNumVectorRegs;
6225     }
6226     unsigned MaxLocalUsers = pair.second;
6227     unsigned LoopInvariantRegs = 0;
6228     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
6229       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
6230 
6231     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
6232     // Don't count the induction variable as interleaved.
6233     if (EnableIndVarRegisterHeur) {
6234       TmpIC =
6235           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
6236                         std::max(1U, (MaxLocalUsers - 1)));
6237     }
6238 
6239     IC = std::min(IC, TmpIC);
6240   }
6241 
6242   // Clamp the interleave ranges to reasonable counts.
6243   unsigned MaxInterleaveCount =
6244       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
6245 
6246   // Check if the user has overridden the max.
6247   if (VF.isScalar()) {
6248     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
6249       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
6250   } else {
6251     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
6252       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
6253   }
6254 
6255   // If trip count is known or estimated compile time constant, limit the
6256   // interleave count to be less than the trip count divided by VF, provided it
6257   // is at least 1.
6258   //
6259   // For scalable vectors we can't know if interleaving is beneficial. It may
6260   // not be beneficial for small loops if none of the lanes in the second vector
6261   // iterations is enabled. However, for larger loops, there is likely to be a
6262   // similar benefit as for fixed-width vectors. For now, we choose to leave
6263   // the InterleaveCount as if vscale is '1', although if some information about
6264   // the vector is known (e.g. min vector size), we can make a better decision.
6265   if (BestKnownTC) {
6266     MaxInterleaveCount =
6267         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
6268     // Make sure MaxInterleaveCount is greater than 0.
6269     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
6270   }
6271 
6272   assert(MaxInterleaveCount > 0 &&
6273          "Maximum interleave count must be greater than 0");
6274 
6275   // Clamp the calculated IC to be between the 1 and the max interleave count
6276   // that the target and trip count allows.
6277   if (IC > MaxInterleaveCount)
6278     IC = MaxInterleaveCount;
6279   else
6280     // Make sure IC is greater than 0.
6281     IC = std::max(1u, IC);
6282 
6283   assert(IC > 0 && "Interleave count must be greater than 0.");
6284 
6285   // If we did not calculate the cost for VF (because the user selected the VF)
6286   // then we calculate the cost of VF here.
6287   if (LoopCost == 0) {
6288     assert(expectedCost(VF).first.isValid() && "Expected a valid cost");
6289     LoopCost = *expectedCost(VF).first.getValue();
6290   }
6291 
6292   assert(LoopCost && "Non-zero loop cost expected");
6293 
6294   // Interleave if we vectorized this loop and there is a reduction that could
6295   // benefit from interleaving.
6296   if (VF.isVector() && HasReductions) {
6297     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
6298     return IC;
6299   }
6300 
6301   // Note that if we've already vectorized the loop we will have done the
6302   // runtime check and so interleaving won't require further checks.
6303   bool InterleavingRequiresRuntimePointerCheck =
6304       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
6305 
6306   // We want to interleave small loops in order to reduce the loop overhead and
6307   // potentially expose ILP opportunities.
6308   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
6309                     << "LV: IC is " << IC << '\n'
6310                     << "LV: VF is " << VF << '\n');
6311   const bool AggressivelyInterleaveReductions =
6312       TTI.enableAggressiveInterleaving(HasReductions);
6313   if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
6314     // We assume that the cost overhead is 1 and we use the cost model
6315     // to estimate the cost of the loop and interleave until the cost of the
6316     // loop overhead is about 5% of the cost of the loop.
6317     unsigned SmallIC =
6318         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
6319 
6320     // Interleave until store/load ports (estimated by max interleave count) are
6321     // saturated.
6322     unsigned NumStores = Legal->getNumStores();
6323     unsigned NumLoads = Legal->getNumLoads();
6324     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
6325     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
6326 
6327     // If we have a scalar reduction (vector reductions are already dealt with
6328     // by this point), we can increase the critical path length if the loop
6329     // we're interleaving is inside another loop. Limit, by default to 2, so the
6330     // critical path only gets increased by one reduction operation.
6331     if (HasReductions && TheLoop->getLoopDepth() > 1) {
6332       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
6333       SmallIC = std::min(SmallIC, F);
6334       StoresIC = std::min(StoresIC, F);
6335       LoadsIC = std::min(LoadsIC, F);
6336     }
6337 
6338     if (EnableLoadStoreRuntimeInterleave &&
6339         std::max(StoresIC, LoadsIC) > SmallIC) {
6340       LLVM_DEBUG(
6341           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
6342       return std::max(StoresIC, LoadsIC);
6343     }
6344 
6345     // If there are scalar reductions and TTI has enabled aggressive
6346     // interleaving for reductions, we will interleave to expose ILP.
6347     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
6348         AggressivelyInterleaveReductions) {
6349       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6350       // Interleave no less than SmallIC but not as aggressive as the normal IC
6351       // to satisfy the rare situation when resources are too limited.
6352       return std::max(IC / 2, SmallIC);
6353     } else {
6354       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
6355       return SmallIC;
6356     }
6357   }
6358 
6359   // Interleave if this is a large loop (small loops are already dealt with by
6360   // this point) that could benefit from interleaving.
6361   if (AggressivelyInterleaveReductions) {
6362     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
6363     return IC;
6364   }
6365 
6366   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
6367   return 1;
6368 }
6369 
6370 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
6371 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
6372   // This function calculates the register usage by measuring the highest number
6373   // of values that are alive at a single location. Obviously, this is a very
6374   // rough estimation. We scan the loop in a topological order in order and
6375   // assign a number to each instruction. We use RPO to ensure that defs are
6376   // met before their users. We assume that each instruction that has in-loop
6377   // users starts an interval. We record every time that an in-loop value is
6378   // used, so we have a list of the first and last occurrences of each
6379   // instruction. Next, we transpose this data structure into a multi map that
6380   // holds the list of intervals that *end* at a specific location. This multi
6381   // map allows us to perform a linear search. We scan the instructions linearly
6382   // and record each time that a new interval starts, by placing it in a set.
6383   // If we find this value in the multi-map then we remove it from the set.
6384   // The max register usage is the maximum size of the set.
6385   // We also search for instructions that are defined outside the loop, but are
6386   // used inside the loop. We need this number separately from the max-interval
6387   // usage number because when we unroll, loop-invariant values do not take
6388   // more register.
6389   LoopBlocksDFS DFS(TheLoop);
6390   DFS.perform(LI);
6391 
6392   RegisterUsage RU;
6393 
6394   // Each 'key' in the map opens a new interval. The values
6395   // of the map are the index of the 'last seen' usage of the
6396   // instruction that is the key.
6397   using IntervalMap = DenseMap<Instruction *, unsigned>;
6398 
6399   // Maps instruction to its index.
6400   SmallVector<Instruction *, 64> IdxToInstr;
6401   // Marks the end of each interval.
6402   IntervalMap EndPoint;
6403   // Saves the list of instruction indices that are used in the loop.
6404   SmallPtrSet<Instruction *, 8> Ends;
6405   // Saves the list of values that are used in the loop but are
6406   // defined outside the loop, such as arguments and constants.
6407   SmallPtrSet<Value *, 8> LoopInvariants;
6408 
6409   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
6410     for (Instruction &I : BB->instructionsWithoutDebug()) {
6411       IdxToInstr.push_back(&I);
6412 
6413       // Save the end location of each USE.
6414       for (Value *U : I.operands()) {
6415         auto *Instr = dyn_cast<Instruction>(U);
6416 
6417         // Ignore non-instruction values such as arguments, constants, etc.
6418         if (!Instr)
6419           continue;
6420 
6421         // If this instruction is outside the loop then record it and continue.
6422         if (!TheLoop->contains(Instr)) {
6423           LoopInvariants.insert(Instr);
6424           continue;
6425         }
6426 
6427         // Overwrite previous end points.
6428         EndPoint[Instr] = IdxToInstr.size();
6429         Ends.insert(Instr);
6430       }
6431     }
6432   }
6433 
6434   // Saves the list of intervals that end with the index in 'key'.
6435   using InstrList = SmallVector<Instruction *, 2>;
6436   DenseMap<unsigned, InstrList> TransposeEnds;
6437 
6438   // Transpose the EndPoints to a list of values that end at each index.
6439   for (auto &Interval : EndPoint)
6440     TransposeEnds[Interval.second].push_back(Interval.first);
6441 
6442   SmallPtrSet<Instruction *, 8> OpenIntervals;
6443   SmallVector<RegisterUsage, 8> RUs(VFs.size());
6444   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
6445 
6446   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
6447 
6448   // A lambda that gets the register usage for the given type and VF.
6449   const auto &TTICapture = TTI;
6450   auto GetRegUsage = [&TTICapture](Type *Ty, ElementCount VF) {
6451     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
6452       return 0U;
6453     return TTICapture.getRegUsageForType(VectorType::get(Ty, VF));
6454   };
6455 
6456   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
6457     Instruction *I = IdxToInstr[i];
6458 
6459     // Remove all of the instructions that end at this location.
6460     InstrList &List = TransposeEnds[i];
6461     for (Instruction *ToRemove : List)
6462       OpenIntervals.erase(ToRemove);
6463 
6464     // Ignore instructions that are never used within the loop.
6465     if (!Ends.count(I))
6466       continue;
6467 
6468     // Skip ignored values.
6469     if (ValuesToIgnore.count(I))
6470       continue;
6471 
6472     // For each VF find the maximum usage of registers.
6473     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
6474       // Count the number of live intervals.
6475       SmallMapVector<unsigned, unsigned, 4> RegUsage;
6476 
6477       if (VFs[j].isScalar()) {
6478         for (auto Inst : OpenIntervals) {
6479           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6480           if (RegUsage.find(ClassID) == RegUsage.end())
6481             RegUsage[ClassID] = 1;
6482           else
6483             RegUsage[ClassID] += 1;
6484         }
6485       } else {
6486         collectUniformsAndScalars(VFs[j]);
6487         for (auto Inst : OpenIntervals) {
6488           // Skip ignored values for VF > 1.
6489           if (VecValuesToIgnore.count(Inst))
6490             continue;
6491           if (isScalarAfterVectorization(Inst, VFs[j])) {
6492             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
6493             if (RegUsage.find(ClassID) == RegUsage.end())
6494               RegUsage[ClassID] = 1;
6495             else
6496               RegUsage[ClassID] += 1;
6497           } else {
6498             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
6499             if (RegUsage.find(ClassID) == RegUsage.end())
6500               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6501             else
6502               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6503           }
6504         }
6505       }
6506 
6507       for (auto& pair : RegUsage) {
6508         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6509           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6510         else
6511           MaxUsages[j][pair.first] = pair.second;
6512       }
6513     }
6514 
6515     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6516                       << OpenIntervals.size() << '\n');
6517 
6518     // Add the current instruction to the list of open intervals.
6519     OpenIntervals.insert(I);
6520   }
6521 
6522   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6523     SmallMapVector<unsigned, unsigned, 4> Invariant;
6524 
6525     for (auto Inst : LoopInvariants) {
6526       unsigned Usage =
6527           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6528       unsigned ClassID =
6529           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6530       if (Invariant.find(ClassID) == Invariant.end())
6531         Invariant[ClassID] = Usage;
6532       else
6533         Invariant[ClassID] += Usage;
6534     }
6535 
6536     LLVM_DEBUG({
6537       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6538       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6539              << " item\n";
6540       for (const auto &pair : MaxUsages[i]) {
6541         dbgs() << "LV(REG): RegisterClass: "
6542                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6543                << " registers\n";
6544       }
6545       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6546              << " item\n";
6547       for (const auto &pair : Invariant) {
6548         dbgs() << "LV(REG): RegisterClass: "
6549                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6550                << " registers\n";
6551       }
6552     });
6553 
6554     RU.LoopInvariantRegs = Invariant;
6555     RU.MaxLocalUsers = MaxUsages[i];
6556     RUs[i] = RU;
6557   }
6558 
6559   return RUs;
6560 }
6561 
6562 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
6563   // TODO: Cost model for emulated masked load/store is completely
6564   // broken. This hack guides the cost model to use an artificially
6565   // high enough value to practically disable vectorization with such
6566   // operations, except where previously deployed legality hack allowed
6567   // using very low cost values. This is to avoid regressions coming simply
6568   // from moving "masked load/store" check from legality to cost model.
6569   // Masked Load/Gather emulation was previously never allowed.
6570   // Limited number of Masked Store/Scatter emulation was allowed.
6571   assert(isPredicatedInst(I, ElementCount::getFixed(1)) &&
6572          "Expecting a scalar emulated instruction");
6573   return isa<LoadInst>(I) ||
6574          (isa<StoreInst>(I) &&
6575           NumPredStores > NumberOfStoresToPredicate);
6576 }
6577 
6578 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6579   // If we aren't vectorizing the loop, or if we've already collected the
6580   // instructions to scalarize, there's nothing to do. Collection may already
6581   // have occurred if we have a user-selected VF and are now computing the
6582   // expected cost for interleaving.
6583   if (VF.isScalar() || VF.isZero() ||
6584       InstsToScalarize.find(VF) != InstsToScalarize.end())
6585     return;
6586 
6587   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6588   // not profitable to scalarize any instructions, the presence of VF in the
6589   // map will indicate that we've analyzed it already.
6590   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6591 
6592   // Find all the instructions that are scalar with predication in the loop and
6593   // determine if it would be better to not if-convert the blocks they are in.
6594   // If so, we also record the instructions to scalarize.
6595   for (BasicBlock *BB : TheLoop->blocks()) {
6596     if (!blockNeedsPredication(BB))
6597       continue;
6598     for (Instruction &I : *BB)
6599       if (isScalarWithPredication(&I)) {
6600         ScalarCostsTy ScalarCosts;
6601         // Do not apply discount logic if hacked cost is needed
6602         // for emulated masked memrefs.
6603         if (!useEmulatedMaskMemRefHack(&I) &&
6604             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6605           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6606         // Remember that BB will remain after vectorization.
6607         PredicatedBBsAfterVectorization.insert(BB);
6608       }
6609   }
6610 }
6611 
6612 int LoopVectorizationCostModel::computePredInstDiscount(
6613     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6614   assert(!isUniformAfterVectorization(PredInst, VF) &&
6615          "Instruction marked uniform-after-vectorization will be predicated");
6616 
6617   // Initialize the discount to zero, meaning that the scalar version and the
6618   // vector version cost the same.
6619   InstructionCost Discount = 0;
6620 
6621   // Holds instructions to analyze. The instructions we visit are mapped in
6622   // ScalarCosts. Those instructions are the ones that would be scalarized if
6623   // we find that the scalar version costs less.
6624   SmallVector<Instruction *, 8> Worklist;
6625 
6626   // Returns true if the given instruction can be scalarized.
6627   auto canBeScalarized = [&](Instruction *I) -> bool {
6628     // We only attempt to scalarize instructions forming a single-use chain
6629     // from the original predicated block that would otherwise be vectorized.
6630     // Although not strictly necessary, we give up on instructions we know will
6631     // already be scalar to avoid traversing chains that are unlikely to be
6632     // beneficial.
6633     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6634         isScalarAfterVectorization(I, VF))
6635       return false;
6636 
6637     // If the instruction is scalar with predication, it will be analyzed
6638     // separately. We ignore it within the context of PredInst.
6639     if (isScalarWithPredication(I))
6640       return false;
6641 
6642     // If any of the instruction's operands are uniform after vectorization,
6643     // the instruction cannot be scalarized. This prevents, for example, a
6644     // masked load from being scalarized.
6645     //
6646     // We assume we will only emit a value for lane zero of an instruction
6647     // marked uniform after vectorization, rather than VF identical values.
6648     // Thus, if we scalarize an instruction that uses a uniform, we would
6649     // create uses of values corresponding to the lanes we aren't emitting code
6650     // for. This behavior can be changed by allowing getScalarValue to clone
6651     // the lane zero values for uniforms rather than asserting.
6652     for (Use &U : I->operands())
6653       if (auto *J = dyn_cast<Instruction>(U.get()))
6654         if (isUniformAfterVectorization(J, VF))
6655           return false;
6656 
6657     // Otherwise, we can scalarize the instruction.
6658     return true;
6659   };
6660 
6661   // Compute the expected cost discount from scalarizing the entire expression
6662   // feeding the predicated instruction. We currently only consider expressions
6663   // that are single-use instruction chains.
6664   Worklist.push_back(PredInst);
6665   while (!Worklist.empty()) {
6666     Instruction *I = Worklist.pop_back_val();
6667 
6668     // If we've already analyzed the instruction, there's nothing to do.
6669     if (ScalarCosts.find(I) != ScalarCosts.end())
6670       continue;
6671 
6672     // Compute the cost of the vector instruction. Note that this cost already
6673     // includes the scalarization overhead of the predicated instruction.
6674     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6675 
6676     // Compute the cost of the scalarized instruction. This cost is the cost of
6677     // the instruction as if it wasn't if-converted and instead remained in the
6678     // predicated block. We will scale this cost by block probability after
6679     // computing the scalarization overhead.
6680     assert(!VF.isScalable() && "scalable vectors not yet supported.");
6681     InstructionCost ScalarCost =
6682         VF.getKnownMinValue() *
6683         getInstructionCost(I, ElementCount::getFixed(1)).first;
6684 
6685     // Compute the scalarization overhead of needed insertelement instructions
6686     // and phi nodes.
6687     if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
6688       ScalarCost += TTI.getScalarizationOverhead(
6689           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6690           APInt::getAllOnesValue(VF.getKnownMinValue()), true, false);
6691       assert(!VF.isScalable() && "scalable vectors not yet supported.");
6692       ScalarCost +=
6693           VF.getKnownMinValue() *
6694           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6695     }
6696 
6697     // Compute the scalarization overhead of needed extractelement
6698     // instructions. For each of the instruction's operands, if the operand can
6699     // be scalarized, add it to the worklist; otherwise, account for the
6700     // overhead.
6701     for (Use &U : I->operands())
6702       if (auto *J = dyn_cast<Instruction>(U.get())) {
6703         assert(VectorType::isValidElementType(J->getType()) &&
6704                "Instruction has non-scalar type");
6705         if (canBeScalarized(J))
6706           Worklist.push_back(J);
6707         else if (needsExtract(J, VF)) {
6708           assert(!VF.isScalable() && "scalable vectors not yet supported.");
6709           ScalarCost += TTI.getScalarizationOverhead(
6710               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6711               APInt::getAllOnesValue(VF.getKnownMinValue()), false, true);
6712         }
6713       }
6714 
6715     // Scale the total scalar cost by block probability.
6716     ScalarCost /= getReciprocalPredBlockProb();
6717 
6718     // Compute the discount. A non-negative discount means the vector version
6719     // of the instruction costs more, and scalarizing would be beneficial.
6720     Discount += VectorCost - ScalarCost;
6721     ScalarCosts[I] = ScalarCost;
6722   }
6723 
6724   return *Discount.getValue();
6725 }
6726 
6727 LoopVectorizationCostModel::VectorizationCostTy
6728 LoopVectorizationCostModel::expectedCost(ElementCount VF) {
6729   VectorizationCostTy Cost;
6730 
6731   // For each block.
6732   for (BasicBlock *BB : TheLoop->blocks()) {
6733     VectorizationCostTy BlockCost;
6734 
6735     // For each instruction in the old loop.
6736     for (Instruction &I : BB->instructionsWithoutDebug()) {
6737       // Skip ignored values.
6738       if (ValuesToIgnore.count(&I) ||
6739           (VF.isVector() && VecValuesToIgnore.count(&I)))
6740         continue;
6741 
6742       VectorizationCostTy C = getInstructionCost(&I, VF);
6743 
6744       // Check if we should override the cost.
6745       if (ForceTargetInstructionCost.getNumOccurrences() > 0)
6746         C.first = InstructionCost(ForceTargetInstructionCost);
6747 
6748       BlockCost.first += C.first;
6749       BlockCost.second |= C.second;
6750       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6751                         << " for VF " << VF << " For instruction: " << I
6752                         << '\n');
6753     }
6754 
6755     // If we are vectorizing a predicated block, it will have been
6756     // if-converted. This means that the block's instructions (aside from
6757     // stores and instructions that may divide by zero) will now be
6758     // unconditionally executed. For the scalar case, we may not always execute
6759     // the predicated block, if it is an if-else block. Thus, scale the block's
6760     // cost by the probability of executing it. blockNeedsPredication from
6761     // Legal is used so as to not include all blocks in tail folded loops.
6762     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6763       BlockCost.first /= getReciprocalPredBlockProb();
6764 
6765     Cost.first += BlockCost.first;
6766     Cost.second |= BlockCost.second;
6767   }
6768 
6769   return Cost;
6770 }
6771 
6772 /// Gets Address Access SCEV after verifying that the access pattern
6773 /// is loop invariant except the induction variable dependence.
6774 ///
6775 /// This SCEV can be sent to the Target in order to estimate the address
6776 /// calculation cost.
6777 static const SCEV *getAddressAccessSCEV(
6778               Value *Ptr,
6779               LoopVectorizationLegality *Legal,
6780               PredicatedScalarEvolution &PSE,
6781               const Loop *TheLoop) {
6782 
6783   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6784   if (!Gep)
6785     return nullptr;
6786 
6787   // We are looking for a gep with all loop invariant indices except for one
6788   // which should be an induction variable.
6789   auto SE = PSE.getSE();
6790   unsigned NumOperands = Gep->getNumOperands();
6791   for (unsigned i = 1; i < NumOperands; ++i) {
6792     Value *Opd = Gep->getOperand(i);
6793     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6794         !Legal->isInductionVariable(Opd))
6795       return nullptr;
6796   }
6797 
6798   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6799   return PSE.getSCEV(Ptr);
6800 }
6801 
6802 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6803   return Legal->hasStride(I->getOperand(0)) ||
6804          Legal->hasStride(I->getOperand(1));
6805 }
6806 
6807 InstructionCost
6808 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6809                                                         ElementCount VF) {
6810   assert(VF.isVector() &&
6811          "Scalarization cost of instruction implies vectorization.");
6812   if (VF.isScalable())
6813     return InstructionCost::getInvalid();
6814 
6815   Type *ValTy = getMemInstValueType(I);
6816   auto SE = PSE.getSE();
6817 
6818   unsigned AS = getLoadStoreAddressSpace(I);
6819   Value *Ptr = getLoadStorePointerOperand(I);
6820   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6821 
6822   // Figure out whether the access is strided and get the stride value
6823   // if it's known in compile time
6824   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6825 
6826   // Get the cost of the scalar memory instruction and address computation.
6827   InstructionCost Cost =
6828       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6829 
6830   // Don't pass *I here, since it is scalar but will actually be part of a
6831   // vectorized loop where the user of it is a vectorized instruction.
6832   const Align Alignment = getLoadStoreAlignment(I);
6833   Cost += VF.getKnownMinValue() *
6834           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6835                               AS, TTI::TCK_RecipThroughput);
6836 
6837   // Get the overhead of the extractelement and insertelement instructions
6838   // we might create due to scalarization.
6839   Cost += getScalarizationOverhead(I, VF);
6840 
6841   // If we have a predicated load/store, it will need extra i1 extracts and
6842   // conditional branches, but may not be executed for each vector lane. Scale
6843   // the cost by the probability of executing the predicated block.
6844   if (isPredicatedInst(I, ElementCount::getFixed(1))) {
6845     Cost /= getReciprocalPredBlockProb();
6846 
6847     // Add the cost of an i1 extract and a branch
6848     auto *Vec_i1Ty =
6849         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6850     Cost += TTI.getScalarizationOverhead(
6851         Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
6852         /*Insert=*/false, /*Extract=*/true);
6853     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6854 
6855     if (useEmulatedMaskMemRefHack(I))
6856       // Artificially setting to a high enough value to practically disable
6857       // vectorization with such operations.
6858       Cost = 3000000;
6859   }
6860 
6861   return Cost;
6862 }
6863 
6864 InstructionCost
6865 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6866                                                     ElementCount VF) {
6867   Type *ValTy = getMemInstValueType(I);
6868   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6869   Value *Ptr = getLoadStorePointerOperand(I);
6870   unsigned AS = getLoadStoreAddressSpace(I);
6871   int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
6872   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6873 
6874   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6875          "Stride should be 1 or -1 for consecutive memory access");
6876   const Align Alignment = getLoadStoreAlignment(I);
6877   InstructionCost Cost = 0;
6878   if (Legal->isMaskRequired(I))
6879     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6880                                       CostKind);
6881   else
6882     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6883                                 CostKind, I);
6884 
6885   bool Reverse = ConsecutiveStride < 0;
6886   if (Reverse)
6887     Cost +=
6888         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6889   return Cost;
6890 }
6891 
6892 InstructionCost
6893 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6894                                                 ElementCount VF) {
6895   assert(Legal->isUniformMemOp(*I));
6896 
6897   Type *ValTy = getMemInstValueType(I);
6898   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6899   const Align Alignment = getLoadStoreAlignment(I);
6900   unsigned AS = getLoadStoreAddressSpace(I);
6901   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6902   if (isa<LoadInst>(I)) {
6903     return TTI.getAddressComputationCost(ValTy) +
6904            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6905                                CostKind) +
6906            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6907   }
6908   StoreInst *SI = cast<StoreInst>(I);
6909 
6910   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6911   return TTI.getAddressComputationCost(ValTy) +
6912          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6913                              CostKind) +
6914          (isLoopInvariantStoreValue
6915               ? 0
6916               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6917                                        VF.getKnownMinValue() - 1));
6918 }
6919 
6920 InstructionCost
6921 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6922                                                  ElementCount VF) {
6923   Type *ValTy = getMemInstValueType(I);
6924   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6925   const Align Alignment = getLoadStoreAlignment(I);
6926   const Value *Ptr = getLoadStorePointerOperand(I);
6927 
6928   return TTI.getAddressComputationCost(VectorTy) +
6929          TTI.getGatherScatterOpCost(
6930              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6931              TargetTransformInfo::TCK_RecipThroughput, I);
6932 }
6933 
6934 InstructionCost
6935 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6936                                                    ElementCount VF) {
6937   // TODO: Once we have support for interleaving with scalable vectors
6938   // we can calculate the cost properly here.
6939   if (VF.isScalable())
6940     return InstructionCost::getInvalid();
6941 
6942   Type *ValTy = getMemInstValueType(I);
6943   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6944   unsigned AS = getLoadStoreAddressSpace(I);
6945 
6946   auto Group = getInterleavedAccessGroup(I);
6947   assert(Group && "Fail to get an interleaved access group.");
6948 
6949   unsigned InterleaveFactor = Group->getFactor();
6950   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6951 
6952   // Holds the indices of existing members in an interleaved load group.
6953   // An interleaved store group doesn't need this as it doesn't allow gaps.
6954   SmallVector<unsigned, 4> Indices;
6955   if (isa<LoadInst>(I)) {
6956     for (unsigned i = 0; i < InterleaveFactor; i++)
6957       if (Group->getMember(i))
6958         Indices.push_back(i);
6959   }
6960 
6961   // Calculate the cost of the whole interleaved group.
6962   bool UseMaskForGaps =
6963       Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed();
6964   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6965       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6966       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6967 
6968   if (Group->isReverse()) {
6969     // TODO: Add support for reversed masked interleaved access.
6970     assert(!Legal->isMaskRequired(I) &&
6971            "Reverse masked interleaved access not supported.");
6972     Cost +=
6973         Group->getNumMembers() *
6974         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6975   }
6976   return Cost;
6977 }
6978 
6979 InstructionCost LoopVectorizationCostModel::getReductionPatternCost(
6980     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6981   // Early exit for no inloop reductions
6982   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6983     return InstructionCost::getInvalid();
6984   auto *VectorTy = cast<VectorType>(Ty);
6985 
6986   // We are looking for a pattern of, and finding the minimal acceptable cost:
6987   //  reduce(mul(ext(A), ext(B))) or
6988   //  reduce(mul(A, B)) or
6989   //  reduce(ext(A)) or
6990   //  reduce(A).
6991   // The basic idea is that we walk down the tree to do that, finding the root
6992   // reduction instruction in InLoopReductionImmediateChains. From there we find
6993   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6994   // of the components. If the reduction cost is lower then we return it for the
6995   // reduction instruction and 0 for the other instructions in the pattern. If
6996   // it is not we return an invalid cost specifying the orignal cost method
6997   // should be used.
6998   Instruction *RetI = I;
6999   if ((RetI->getOpcode() == Instruction::SExt ||
7000        RetI->getOpcode() == Instruction::ZExt)) {
7001     if (!RetI->hasOneUser())
7002       return InstructionCost::getInvalid();
7003     RetI = RetI->user_back();
7004   }
7005   if (RetI->getOpcode() == Instruction::Mul &&
7006       RetI->user_back()->getOpcode() == Instruction::Add) {
7007     if (!RetI->hasOneUser())
7008       return InstructionCost::getInvalid();
7009     RetI = RetI->user_back();
7010   }
7011 
7012   // Test if the found instruction is a reduction, and if not return an invalid
7013   // cost specifying the parent to use the original cost modelling.
7014   if (!InLoopReductionImmediateChains.count(RetI))
7015     return InstructionCost::getInvalid();
7016 
7017   // Find the reduction this chain is a part of and calculate the basic cost of
7018   // the reduction on its own.
7019   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
7020   Instruction *ReductionPhi = LastChain;
7021   while (!isa<PHINode>(ReductionPhi))
7022     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
7023 
7024   RecurrenceDescriptor RdxDesc =
7025       Legal->getReductionVars()[cast<PHINode>(ReductionPhi)];
7026   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
7027       RdxDesc.getOpcode(), VectorTy, false, CostKind);
7028 
7029   // Get the operand that was not the reduction chain and match it to one of the
7030   // patterns, returning the better cost if it is found.
7031   Instruction *RedOp = RetI->getOperand(1) == LastChain
7032                            ? dyn_cast<Instruction>(RetI->getOperand(0))
7033                            : dyn_cast<Instruction>(RetI->getOperand(1));
7034 
7035   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
7036 
7037   if (RedOp && (isa<SExtInst>(RedOp) || isa<ZExtInst>(RedOp)) &&
7038       !TheLoop->isLoopInvariant(RedOp)) {
7039     bool IsUnsigned = isa<ZExtInst>(RedOp);
7040     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
7041     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7042         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7043         CostKind);
7044 
7045     InstructionCost ExtCost =
7046         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
7047                              TTI::CastContextHint::None, CostKind, RedOp);
7048     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
7049       return I == RetI ? *RedCost.getValue() : 0;
7050   } else if (RedOp && RedOp->getOpcode() == Instruction::Mul) {
7051     Instruction *Mul = RedOp;
7052     Instruction *Op0 = dyn_cast<Instruction>(Mul->getOperand(0));
7053     Instruction *Op1 = dyn_cast<Instruction>(Mul->getOperand(1));
7054     if (Op0 && Op1 && (isa<SExtInst>(Op0) || isa<ZExtInst>(Op0)) &&
7055         Op0->getOpcode() == Op1->getOpcode() &&
7056         Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
7057         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
7058       bool IsUnsigned = isa<ZExtInst>(Op0);
7059       auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
7060       // reduce(mul(ext, ext))
7061       InstructionCost ExtCost =
7062           TTI.getCastInstrCost(Op0->getOpcode(), VectorTy, ExtType,
7063                                TTI::CastContextHint::None, CostKind, Op0);
7064       InstructionCost MulCost =
7065           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7066 
7067       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7068           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
7069           CostKind);
7070 
7071       if (RedCost.isValid() && RedCost < ExtCost * 2 + MulCost + BaseCost)
7072         return I == RetI ? *RedCost.getValue() : 0;
7073     } else {
7074       InstructionCost MulCost =
7075           TTI.getArithmeticInstrCost(Mul->getOpcode(), VectorTy, CostKind);
7076 
7077       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
7078           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
7079           CostKind);
7080 
7081       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
7082         return I == RetI ? *RedCost.getValue() : 0;
7083     }
7084   }
7085 
7086   return I == RetI ? BaseCost : InstructionCost::getInvalid();
7087 }
7088 
7089 InstructionCost
7090 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
7091                                                      ElementCount VF) {
7092   // Calculate scalar cost only. Vectorization cost should be ready at this
7093   // moment.
7094   if (VF.isScalar()) {
7095     Type *ValTy = getMemInstValueType(I);
7096     const Align Alignment = getLoadStoreAlignment(I);
7097     unsigned AS = getLoadStoreAddressSpace(I);
7098 
7099     return TTI.getAddressComputationCost(ValTy) +
7100            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
7101                                TTI::TCK_RecipThroughput, I);
7102   }
7103   return getWideningCost(I, VF);
7104 }
7105 
7106 LoopVectorizationCostModel::VectorizationCostTy
7107 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
7108                                                ElementCount VF) {
7109   // If we know that this instruction will remain uniform, check the cost of
7110   // the scalar version.
7111   if (isUniformAfterVectorization(I, VF))
7112     VF = ElementCount::getFixed(1);
7113 
7114   if (VF.isVector() && isProfitableToScalarize(I, VF))
7115     return VectorizationCostTy(InstsToScalarize[VF][I], false);
7116 
7117   // Forced scalars do not have any scalarization overhead.
7118   auto ForcedScalar = ForcedScalars.find(VF);
7119   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
7120     auto InstSet = ForcedScalar->second;
7121     if (InstSet.count(I))
7122       return VectorizationCostTy(
7123           (getInstructionCost(I, ElementCount::getFixed(1)).first *
7124            VF.getKnownMinValue()),
7125           false);
7126   }
7127 
7128   Type *VectorTy;
7129   InstructionCost C = getInstructionCost(I, VF, VectorTy);
7130 
7131   bool TypeNotScalarized =
7132       VF.isVector() && VectorTy->isVectorTy() &&
7133       TTI.getNumberOfParts(VectorTy) < VF.getKnownMinValue();
7134   return VectorizationCostTy(C, TypeNotScalarized);
7135 }
7136 
7137 InstructionCost
7138 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
7139                                                      ElementCount VF) const {
7140 
7141   if (VF.isScalable())
7142     return InstructionCost::getInvalid();
7143 
7144   if (VF.isScalar())
7145     return 0;
7146 
7147   InstructionCost Cost = 0;
7148   Type *RetTy = ToVectorTy(I->getType(), VF);
7149   if (!RetTy->isVoidTy() &&
7150       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
7151     Cost += TTI.getScalarizationOverhead(
7152         cast<VectorType>(RetTy), APInt::getAllOnesValue(VF.getKnownMinValue()),
7153         true, false);
7154 
7155   // Some targets keep addresses scalar.
7156   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
7157     return Cost;
7158 
7159   // Some targets support efficient element stores.
7160   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
7161     return Cost;
7162 
7163   // Collect operands to consider.
7164   CallInst *CI = dyn_cast<CallInst>(I);
7165   Instruction::op_range Ops = CI ? CI->arg_operands() : I->operands();
7166 
7167   // Skip operands that do not require extraction/scalarization and do not incur
7168   // any overhead.
7169   SmallVector<Type *> Tys;
7170   for (auto *V : filterExtractingOperands(Ops, VF))
7171     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
7172   return Cost + TTI.getOperandsScalarizationOverhead(
7173                     filterExtractingOperands(Ops, VF), Tys);
7174 }
7175 
7176 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
7177   if (VF.isScalar())
7178     return;
7179   NumPredStores = 0;
7180   for (BasicBlock *BB : TheLoop->blocks()) {
7181     // For each instruction in the old loop.
7182     for (Instruction &I : *BB) {
7183       Value *Ptr =  getLoadStorePointerOperand(&I);
7184       if (!Ptr)
7185         continue;
7186 
7187       // TODO: We should generate better code and update the cost model for
7188       // predicated uniform stores. Today they are treated as any other
7189       // predicated store (see added test cases in
7190       // invariant-store-vectorization.ll).
7191       if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
7192         NumPredStores++;
7193 
7194       if (Legal->isUniformMemOp(I)) {
7195         // TODO: Avoid replicating loads and stores instead of
7196         // relying on instcombine to remove them.
7197         // Load: Scalar load + broadcast
7198         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
7199         InstructionCost Cost = getUniformMemOpCost(&I, VF);
7200         setWideningDecision(&I, VF, CM_Scalarize, Cost);
7201         continue;
7202       }
7203 
7204       // We assume that widening is the best solution when possible.
7205       if (memoryInstructionCanBeWidened(&I, VF)) {
7206         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
7207         int ConsecutiveStride =
7208                Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
7209         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
7210                "Expected consecutive stride.");
7211         InstWidening Decision =
7212             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
7213         setWideningDecision(&I, VF, Decision, Cost);
7214         continue;
7215       }
7216 
7217       // Choose between Interleaving, Gather/Scatter or Scalarization.
7218       InstructionCost InterleaveCost = InstructionCost::getInvalid();
7219       unsigned NumAccesses = 1;
7220       if (isAccessInterleaved(&I)) {
7221         auto Group = getInterleavedAccessGroup(&I);
7222         assert(Group && "Fail to get an interleaved access group.");
7223 
7224         // Make one decision for the whole group.
7225         if (getWideningDecision(&I, VF) != CM_Unknown)
7226           continue;
7227 
7228         NumAccesses = Group->getNumMembers();
7229         if (interleavedAccessCanBeWidened(&I, VF))
7230           InterleaveCost = getInterleaveGroupCost(&I, VF);
7231       }
7232 
7233       InstructionCost GatherScatterCost =
7234           isLegalGatherOrScatter(&I)
7235               ? getGatherScatterCost(&I, VF) * NumAccesses
7236               : InstructionCost::getInvalid();
7237 
7238       InstructionCost ScalarizationCost =
7239           getMemInstScalarizationCost(&I, VF) * NumAccesses;
7240 
7241       // Choose better solution for the current VF,
7242       // write down this decision and use it during vectorization.
7243       InstructionCost Cost;
7244       InstWidening Decision;
7245       if (InterleaveCost <= GatherScatterCost &&
7246           InterleaveCost < ScalarizationCost) {
7247         Decision = CM_Interleave;
7248         Cost = InterleaveCost;
7249       } else if (GatherScatterCost < ScalarizationCost) {
7250         Decision = CM_GatherScatter;
7251         Cost = GatherScatterCost;
7252       } else {
7253         assert(!VF.isScalable() &&
7254                "We cannot yet scalarise for scalable vectors");
7255         Decision = CM_Scalarize;
7256         Cost = ScalarizationCost;
7257       }
7258       // If the instructions belongs to an interleave group, the whole group
7259       // receives the same decision. The whole group receives the cost, but
7260       // the cost will actually be assigned to one instruction.
7261       if (auto Group = getInterleavedAccessGroup(&I))
7262         setWideningDecision(Group, VF, Decision, Cost);
7263       else
7264         setWideningDecision(&I, VF, Decision, Cost);
7265     }
7266   }
7267 
7268   // Make sure that any load of address and any other address computation
7269   // remains scalar unless there is gather/scatter support. This avoids
7270   // inevitable extracts into address registers, and also has the benefit of
7271   // activating LSR more, since that pass can't optimize vectorized
7272   // addresses.
7273   if (TTI.prefersVectorizedAddressing())
7274     return;
7275 
7276   // Start with all scalar pointer uses.
7277   SmallPtrSet<Instruction *, 8> AddrDefs;
7278   for (BasicBlock *BB : TheLoop->blocks())
7279     for (Instruction &I : *BB) {
7280       Instruction *PtrDef =
7281         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
7282       if (PtrDef && TheLoop->contains(PtrDef) &&
7283           getWideningDecision(&I, VF) != CM_GatherScatter)
7284         AddrDefs.insert(PtrDef);
7285     }
7286 
7287   // Add all instructions used to generate the addresses.
7288   SmallVector<Instruction *, 4> Worklist;
7289   append_range(Worklist, AddrDefs);
7290   while (!Worklist.empty()) {
7291     Instruction *I = Worklist.pop_back_val();
7292     for (auto &Op : I->operands())
7293       if (auto *InstOp = dyn_cast<Instruction>(Op))
7294         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
7295             AddrDefs.insert(InstOp).second)
7296           Worklist.push_back(InstOp);
7297   }
7298 
7299   for (auto *I : AddrDefs) {
7300     if (isa<LoadInst>(I)) {
7301       // Setting the desired widening decision should ideally be handled in
7302       // by cost functions, but since this involves the task of finding out
7303       // if the loaded register is involved in an address computation, it is
7304       // instead changed here when we know this is the case.
7305       InstWidening Decision = getWideningDecision(I, VF);
7306       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
7307         // Scalarize a widened load of address.
7308         setWideningDecision(
7309             I, VF, CM_Scalarize,
7310             (VF.getKnownMinValue() *
7311              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
7312       else if (auto Group = getInterleavedAccessGroup(I)) {
7313         // Scalarize an interleave group of address loads.
7314         for (unsigned I = 0; I < Group->getFactor(); ++I) {
7315           if (Instruction *Member = Group->getMember(I))
7316             setWideningDecision(
7317                 Member, VF, CM_Scalarize,
7318                 (VF.getKnownMinValue() *
7319                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
7320         }
7321       }
7322     } else
7323       // Make sure I gets scalarized and a cost estimate without
7324       // scalarization overhead.
7325       ForcedScalars[VF].insert(I);
7326   }
7327 }
7328 
7329 InstructionCost
7330 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
7331                                                Type *&VectorTy) {
7332   Type *RetTy = I->getType();
7333   if (canTruncateToMinimalBitwidth(I, VF))
7334     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
7335   auto SE = PSE.getSE();
7336   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
7337 
7338   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
7339                                                 ElementCount VF) -> bool {
7340     if (VF.isScalar())
7341       return true;
7342 
7343     auto Scalarized = InstsToScalarize.find(VF);
7344     assert(Scalarized != InstsToScalarize.end() &&
7345            "VF not yet analyzed for scalarization profitability");
7346     return !Scalarized->second.count(I) &&
7347            llvm::all_of(I->users(), [&](User *U) {
7348              auto *UI = cast<Instruction>(U);
7349              return !Scalarized->second.count(UI);
7350            });
7351   };
7352   (void) hasSingleCopyAfterVectorization;
7353 
7354   if (isScalarAfterVectorization(I, VF)) {
7355     // With the exception of GEPs and PHIs, after scalarization there should
7356     // only be one copy of the instruction generated in the loop. This is
7357     // because the VF is either 1, or any instructions that need scalarizing
7358     // have already been dealt with by the the time we get here. As a result,
7359     // it means we don't have to multiply the instruction cost by VF.
7360     assert(I->getOpcode() == Instruction::GetElementPtr ||
7361            I->getOpcode() == Instruction::PHI ||
7362            (I->getOpcode() == Instruction::BitCast &&
7363             I->getType()->isPointerTy()) ||
7364            hasSingleCopyAfterVectorization(I, VF));
7365     VectorTy = RetTy;
7366   } else
7367     VectorTy = ToVectorTy(RetTy, VF);
7368 
7369   // TODO: We need to estimate the cost of intrinsic calls.
7370   switch (I->getOpcode()) {
7371   case Instruction::GetElementPtr:
7372     // We mark this instruction as zero-cost because the cost of GEPs in
7373     // vectorized code depends on whether the corresponding memory instruction
7374     // is scalarized or not. Therefore, we handle GEPs with the memory
7375     // instruction cost.
7376     return 0;
7377   case Instruction::Br: {
7378     // In cases of scalarized and predicated instructions, there will be VF
7379     // predicated blocks in the vectorized loop. Each branch around these
7380     // blocks requires also an extract of its vector compare i1 element.
7381     bool ScalarPredicatedBB = false;
7382     BranchInst *BI = cast<BranchInst>(I);
7383     if (VF.isVector() && BI->isConditional() &&
7384         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
7385          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
7386       ScalarPredicatedBB = true;
7387 
7388     if (ScalarPredicatedBB) {
7389       // Return cost for branches around scalarized and predicated blocks.
7390       assert(!VF.isScalable() && "scalable vectors not yet supported.");
7391       auto *Vec_i1Ty =
7392           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
7393       return (TTI.getScalarizationOverhead(
7394                   Vec_i1Ty, APInt::getAllOnesValue(VF.getKnownMinValue()),
7395                   false, true) +
7396               (TTI.getCFInstrCost(Instruction::Br, CostKind) *
7397                VF.getKnownMinValue()));
7398     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
7399       // The back-edge branch will remain, as will all scalar branches.
7400       return TTI.getCFInstrCost(Instruction::Br, CostKind);
7401     else
7402       // This branch will be eliminated by if-conversion.
7403       return 0;
7404     // Note: We currently assume zero cost for an unconditional branch inside
7405     // a predicated block since it will become a fall-through, although we
7406     // may decide in the future to call TTI for all branches.
7407   }
7408   case Instruction::PHI: {
7409     auto *Phi = cast<PHINode>(I);
7410 
7411     // First-order recurrences are replaced by vector shuffles inside the loop.
7412     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7413     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7414       return TTI.getShuffleCost(
7415           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7416           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7417 
7418     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7419     // converted into select instructions. We require N - 1 selects per phi
7420     // node, where N is the number of incoming values.
7421     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7422       return (Phi->getNumIncomingValues() - 1) *
7423              TTI.getCmpSelInstrCost(
7424                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7425                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7426                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7427 
7428     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7429   }
7430   case Instruction::UDiv:
7431   case Instruction::SDiv:
7432   case Instruction::URem:
7433   case Instruction::SRem:
7434     // If we have a predicated instruction, it may not be executed for each
7435     // vector lane. Get the scalarization cost and scale this amount by the
7436     // probability of executing the predicated block. If the instruction is not
7437     // predicated, we fall through to the next case.
7438     if (VF.isVector() && isScalarWithPredication(I)) {
7439       InstructionCost Cost = 0;
7440 
7441       // These instructions have a non-void type, so account for the phi nodes
7442       // that we will create. This cost is likely to be zero. The phi node
7443       // cost, if any, should be scaled by the block probability because it
7444       // models a copy at the end of each predicated block.
7445       Cost += VF.getKnownMinValue() *
7446               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7447 
7448       // The cost of the non-predicated instruction.
7449       Cost += VF.getKnownMinValue() *
7450               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7451 
7452       // The cost of insertelement and extractelement instructions needed for
7453       // scalarization.
7454       Cost += getScalarizationOverhead(I, VF);
7455 
7456       // Scale the cost by the probability of executing the predicated blocks.
7457       // This assumes the predicated block for each vector lane is equally
7458       // likely.
7459       return Cost / getReciprocalPredBlockProb();
7460     }
7461     LLVM_FALLTHROUGH;
7462   case Instruction::Add:
7463   case Instruction::FAdd:
7464   case Instruction::Sub:
7465   case Instruction::FSub:
7466   case Instruction::Mul:
7467   case Instruction::FMul:
7468   case Instruction::FDiv:
7469   case Instruction::FRem:
7470   case Instruction::Shl:
7471   case Instruction::LShr:
7472   case Instruction::AShr:
7473   case Instruction::And:
7474   case Instruction::Or:
7475   case Instruction::Xor: {
7476     // Since we will replace the stride by 1 the multiplication should go away.
7477     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7478       return 0;
7479 
7480     // Detect reduction patterns
7481     InstructionCost RedCost;
7482     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7483             .isValid())
7484       return RedCost;
7485 
7486     // Certain instructions can be cheaper to vectorize if they have a constant
7487     // second vector operand. One example of this are shifts on x86.
7488     Value *Op2 = I->getOperand(1);
7489     TargetTransformInfo::OperandValueProperties Op2VP;
7490     TargetTransformInfo::OperandValueKind Op2VK =
7491         TTI.getOperandInfo(Op2, Op2VP);
7492     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7493       Op2VK = TargetTransformInfo::OK_UniformValue;
7494 
7495     SmallVector<const Value *, 4> Operands(I->operand_values());
7496     return TTI.getArithmeticInstrCost(
7497         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7498         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7499   }
7500   case Instruction::FNeg: {
7501     return TTI.getArithmeticInstrCost(
7502         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7503         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7504         TargetTransformInfo::OP_None, I->getOperand(0), I);
7505   }
7506   case Instruction::Select: {
7507     SelectInst *SI = cast<SelectInst>(I);
7508     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7509     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7510 
7511     const Value *Op0, *Op1;
7512     using namespace llvm::PatternMatch;
7513     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7514                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7515       // select x, y, false --> x & y
7516       // select x, true, y --> x | y
7517       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7518       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7519       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7520       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7521       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7522               Op1->getType()->getScalarSizeInBits() == 1);
7523 
7524       SmallVector<const Value *, 2> Operands{Op0, Op1};
7525       return TTI.getArithmeticInstrCost(
7526           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7527           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7528     }
7529 
7530     Type *CondTy = SI->getCondition()->getType();
7531     if (!ScalarCond)
7532       CondTy = VectorType::get(CondTy, VF);
7533     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy,
7534                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7535   }
7536   case Instruction::ICmp:
7537   case Instruction::FCmp: {
7538     Type *ValTy = I->getOperand(0)->getType();
7539     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7540     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7541       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7542     VectorTy = ToVectorTy(ValTy, VF);
7543     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7544                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, I);
7545   }
7546   case Instruction::Store:
7547   case Instruction::Load: {
7548     ElementCount Width = VF;
7549     if (Width.isVector()) {
7550       InstWidening Decision = getWideningDecision(I, Width);
7551       assert(Decision != CM_Unknown &&
7552              "CM decision should be taken at this point");
7553       if (Decision == CM_Scalarize)
7554         Width = ElementCount::getFixed(1);
7555     }
7556     VectorTy = ToVectorTy(getMemInstValueType(I), Width);
7557     return getMemoryInstructionCost(I, VF);
7558   }
7559   case Instruction::BitCast:
7560     if (I->getType()->isPointerTy())
7561       return 0;
7562     LLVM_FALLTHROUGH;
7563   case Instruction::ZExt:
7564   case Instruction::SExt:
7565   case Instruction::FPToUI:
7566   case Instruction::FPToSI:
7567   case Instruction::FPExt:
7568   case Instruction::PtrToInt:
7569   case Instruction::IntToPtr:
7570   case Instruction::SIToFP:
7571   case Instruction::UIToFP:
7572   case Instruction::Trunc:
7573   case Instruction::FPTrunc: {
7574     // Computes the CastContextHint from a Load/Store instruction.
7575     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7576       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7577              "Expected a load or a store!");
7578 
7579       if (VF.isScalar() || !TheLoop->contains(I))
7580         return TTI::CastContextHint::Normal;
7581 
7582       switch (getWideningDecision(I, VF)) {
7583       case LoopVectorizationCostModel::CM_GatherScatter:
7584         return TTI::CastContextHint::GatherScatter;
7585       case LoopVectorizationCostModel::CM_Interleave:
7586         return TTI::CastContextHint::Interleave;
7587       case LoopVectorizationCostModel::CM_Scalarize:
7588       case LoopVectorizationCostModel::CM_Widen:
7589         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7590                                         : TTI::CastContextHint::Normal;
7591       case LoopVectorizationCostModel::CM_Widen_Reverse:
7592         return TTI::CastContextHint::Reversed;
7593       case LoopVectorizationCostModel::CM_Unknown:
7594         llvm_unreachable("Instr did not go through cost modelling?");
7595       }
7596 
7597       llvm_unreachable("Unhandled case!");
7598     };
7599 
7600     unsigned Opcode = I->getOpcode();
7601     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7602     // For Trunc, the context is the only user, which must be a StoreInst.
7603     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7604       if (I->hasOneUse())
7605         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7606           CCH = ComputeCCH(Store);
7607     }
7608     // For Z/Sext, the context is the operand, which must be a LoadInst.
7609     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7610              Opcode == Instruction::FPExt) {
7611       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7612         CCH = ComputeCCH(Load);
7613     }
7614 
7615     // We optimize the truncation of induction variables having constant
7616     // integer steps. The cost of these truncations is the same as the scalar
7617     // operation.
7618     if (isOptimizableIVTruncate(I, VF)) {
7619       auto *Trunc = cast<TruncInst>(I);
7620       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7621                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7622     }
7623 
7624     // Detect reduction patterns
7625     InstructionCost RedCost;
7626     if ((RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7627             .isValid())
7628       return RedCost;
7629 
7630     Type *SrcScalarTy = I->getOperand(0)->getType();
7631     Type *SrcVecTy =
7632         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7633     if (canTruncateToMinimalBitwidth(I, VF)) {
7634       // This cast is going to be shrunk. This may remove the cast or it might
7635       // turn it into slightly different cast. For example, if MinBW == 16,
7636       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7637       //
7638       // Calculate the modified src and dest types.
7639       Type *MinVecTy = VectorTy;
7640       if (Opcode == Instruction::Trunc) {
7641         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7642         VectorTy =
7643             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7644       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7645         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7646         VectorTy =
7647             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7648       }
7649     }
7650 
7651     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7652   }
7653   case Instruction::Call: {
7654     bool NeedToScalarize;
7655     CallInst *CI = cast<CallInst>(I);
7656     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7657     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7658       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7659       return std::min(CallCost, IntrinsicCost);
7660     }
7661     return CallCost;
7662   }
7663   case Instruction::ExtractValue:
7664     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7665   default:
7666     // This opcode is unknown. Assume that it is the same as 'mul'.
7667     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7668   } // end of switch.
7669 }
7670 
7671 char LoopVectorize::ID = 0;
7672 
7673 static const char lv_name[] = "Loop Vectorization";
7674 
7675 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7676 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7677 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7678 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7679 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7680 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7681 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7682 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7683 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7684 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7685 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7686 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7687 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7688 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7689 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7690 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7691 
7692 namespace llvm {
7693 
7694 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7695 
7696 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7697                               bool VectorizeOnlyWhenForced) {
7698   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7699 }
7700 
7701 } // end namespace llvm
7702 
7703 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7704   // Check if the pointer operand of a load or store instruction is
7705   // consecutive.
7706   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7707     return Legal->isConsecutivePtr(Ptr);
7708   return false;
7709 }
7710 
7711 void LoopVectorizationCostModel::collectValuesToIgnore() {
7712   // Ignore ephemeral values.
7713   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7714 
7715   // Ignore type-promoting instructions we identified during reduction
7716   // detection.
7717   for (auto &Reduction : Legal->getReductionVars()) {
7718     RecurrenceDescriptor &RedDes = Reduction.second;
7719     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7720     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7721   }
7722   // Ignore type-casting instructions we identified during induction
7723   // detection.
7724   for (auto &Induction : Legal->getInductionVars()) {
7725     InductionDescriptor &IndDes = Induction.second;
7726     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7727     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7728   }
7729 }
7730 
7731 void LoopVectorizationCostModel::collectInLoopReductions() {
7732   for (auto &Reduction : Legal->getReductionVars()) {
7733     PHINode *Phi = Reduction.first;
7734     RecurrenceDescriptor &RdxDesc = Reduction.second;
7735 
7736     // We don't collect reductions that are type promoted (yet).
7737     if (RdxDesc.getRecurrenceType() != Phi->getType())
7738       continue;
7739 
7740     // If the target would prefer this reduction to happen "in-loop", then we
7741     // want to record it as such.
7742     unsigned Opcode = RdxDesc.getOpcode();
7743     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7744         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7745                                    TargetTransformInfo::ReductionFlags()))
7746       continue;
7747 
7748     // Check that we can correctly put the reductions into the loop, by
7749     // finding the chain of operations that leads from the phi to the loop
7750     // exit value.
7751     SmallVector<Instruction *, 4> ReductionOperations =
7752         RdxDesc.getReductionOpChain(Phi, TheLoop);
7753     bool InLoop = !ReductionOperations.empty();
7754     if (InLoop) {
7755       InLoopReductionChains[Phi] = ReductionOperations;
7756       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7757       Instruction *LastChain = Phi;
7758       for (auto *I : ReductionOperations) {
7759         InLoopReductionImmediateChains[I] = LastChain;
7760         LastChain = I;
7761       }
7762     }
7763     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7764                       << " reduction for phi: " << *Phi << "\n");
7765   }
7766 }
7767 
7768 // TODO: we could return a pair of values that specify the max VF and
7769 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7770 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7771 // doesn't have a cost model that can choose which plan to execute if
7772 // more than one is generated.
7773 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7774                                  LoopVectorizationCostModel &CM) {
7775   unsigned WidestType;
7776   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7777   return WidestVectorRegBits / WidestType;
7778 }
7779 
7780 VectorizationFactor
7781 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7782   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7783   ElementCount VF = UserVF;
7784   // Outer loop handling: They may require CFG and instruction level
7785   // transformations before even evaluating whether vectorization is profitable.
7786   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7787   // the vectorization pipeline.
7788   if (!OrigLoop->isInnermost()) {
7789     // If the user doesn't provide a vectorization factor, determine a
7790     // reasonable one.
7791     if (UserVF.isZero()) {
7792       VF = ElementCount::getFixed(determineVPlanVF(
7793           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7794               .getFixedSize(),
7795           CM));
7796       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7797 
7798       // Make sure we have a VF > 1 for stress testing.
7799       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7800         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7801                           << "overriding computed VF.\n");
7802         VF = ElementCount::getFixed(4);
7803       }
7804     }
7805     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7806     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7807            "VF needs to be a power of two");
7808     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7809                       << "VF " << VF << " to build VPlans.\n");
7810     buildVPlans(VF, VF);
7811 
7812     // For VPlan build stress testing, we bail out after VPlan construction.
7813     if (VPlanBuildStressTest)
7814       return VectorizationFactor::Disabled();
7815 
7816     return {VF, 0 /*Cost*/};
7817   }
7818 
7819   LLVM_DEBUG(
7820       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7821                 "VPlan-native path.\n");
7822   return VectorizationFactor::Disabled();
7823 }
7824 
7825 Optional<VectorizationFactor>
7826 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7827   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7828   Optional<ElementCount> MaybeMaxVF = CM.computeMaxVF(UserVF, UserIC);
7829   if (!MaybeMaxVF) // Cases that should not to be vectorized nor interleaved.
7830     return None;
7831 
7832   // Invalidate interleave groups if all blocks of loop will be predicated.
7833   if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
7834       !useMaskedInterleavedAccesses(*TTI)) {
7835     LLVM_DEBUG(
7836         dbgs()
7837         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7838            "which requires masked-interleaved support.\n");
7839     if (CM.InterleaveInfo.invalidateGroups())
7840       // Invalidating interleave groups also requires invalidating all decisions
7841       // based on them, which includes widening decisions and uniform and scalar
7842       // values.
7843       CM.invalidateCostModelingDecisions();
7844   }
7845 
7846   ElementCount MaxVF = MaybeMaxVF.getValue();
7847   assert(MaxVF.isNonZero() && "MaxVF is zero.");
7848 
7849   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxVF);
7850   if (!UserVF.isZero() &&
7851       (UserVFIsLegal || (UserVF.isScalable() && MaxVF.isScalable()))) {
7852     // FIXME: MaxVF is temporarily used inplace of UserVF for illegal scalable
7853     // VFs here, this should be reverted to only use legal UserVFs once the
7854     // loop below supports scalable VFs.
7855     ElementCount VF = UserVFIsLegal ? UserVF : MaxVF;
7856     LLVM_DEBUG(dbgs() << "LV: Using " << (UserVFIsLegal ? "user" : "max")
7857                       << " VF " << VF << ".\n");
7858     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7859            "VF needs to be a power of two");
7860     // Collect the instructions (and their associated costs) that will be more
7861     // profitable to scalarize.
7862     CM.selectUserVectorizationFactor(VF);
7863     CM.collectInLoopReductions();
7864     buildVPlansWithVPRecipes(VF, VF);
7865     LLVM_DEBUG(printPlans(dbgs()));
7866     return {{VF, 0}};
7867   }
7868 
7869   assert(!MaxVF.isScalable() &&
7870          "Scalable vectors not yet supported beyond this point");
7871 
7872   for (ElementCount VF = ElementCount::getFixed(1);
7873        ElementCount::isKnownLE(VF, MaxVF); VF *= 2) {
7874     // Collect Uniform and Scalar instructions after vectorization with VF.
7875     CM.collectUniformsAndScalars(VF);
7876 
7877     // Collect the instructions (and their associated costs) that will be more
7878     // profitable to scalarize.
7879     if (VF.isVector())
7880       CM.collectInstsToScalarize(VF);
7881   }
7882 
7883   CM.collectInLoopReductions();
7884 
7885   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxVF);
7886   LLVM_DEBUG(printPlans(dbgs()));
7887   if (MaxVF.isScalar())
7888     return VectorizationFactor::Disabled();
7889 
7890   // Select the optimal vectorization factor.
7891   auto SelectedVF = CM.selectVectorizationFactor(MaxVF);
7892 
7893   // Check if it is profitable to vectorize with runtime checks.
7894   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
7895   if (SelectedVF.Width.getKnownMinValue() > 1 && NumRuntimePointerChecks) {
7896     bool PragmaThresholdReached =
7897         NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
7898     bool ThresholdReached =
7899         NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
7900     if ((ThresholdReached && !Hints.allowReordering()) ||
7901         PragmaThresholdReached) {
7902       ORE->emit([&]() {
7903         return OptimizationRemarkAnalysisAliasing(
7904                    DEBUG_TYPE, "CantReorderMemOps", OrigLoop->getStartLoc(),
7905                    OrigLoop->getHeader())
7906                << "loop not vectorized: cannot prove it is safe to reorder "
7907                   "memory operations";
7908       });
7909       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
7910       Hints.emitRemarkWithHints();
7911       return VectorizationFactor::Disabled();
7912     }
7913   }
7914   return SelectedVF;
7915 }
7916 
7917 void LoopVectorizationPlanner::setBestPlan(ElementCount VF, unsigned UF) {
7918   LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
7919                     << '\n');
7920   BestVF = VF;
7921   BestUF = UF;
7922 
7923   erase_if(VPlans, [VF](const VPlanPtr &Plan) {
7924     return !Plan->hasVF(VF);
7925   });
7926   assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
7927 }
7928 
7929 void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
7930                                            DominatorTree *DT) {
7931   // Perform the actual loop transformation.
7932 
7933   // 1. Create a new empty loop. Unlink the old loop and connect the new one.
7934   assert(BestVF.hasValue() && "Vectorization Factor is missing");
7935   assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
7936 
7937   VPTransformState State{
7938       *BestVF, BestUF, LI, DT, ILV.Builder, &ILV, VPlans.front().get()};
7939   State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
7940   State.TripCount = ILV.getOrCreateTripCount(nullptr);
7941   State.CanonicalIV = ILV.Induction;
7942 
7943   ILV.printDebugTracesAtStart();
7944 
7945   //===------------------------------------------------===//
7946   //
7947   // Notice: any optimization or new instruction that go
7948   // into the code below should also be implemented in
7949   // the cost-model.
7950   //
7951   //===------------------------------------------------===//
7952 
7953   // 2. Copy and widen instructions from the old loop into the new loop.
7954   VPlans.front()->execute(&State);
7955 
7956   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7957   //    predication, updating analyses.
7958   ILV.fixVectorizedLoop(State);
7959 
7960   ILV.printDebugTracesAtEnd();
7961 }
7962 
7963 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7964 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
7965   for (const auto &Plan : VPlans)
7966     if (PrintVPlansInDotFormat)
7967       Plan->printDOT(O);
7968     else
7969       Plan->print(O);
7970 }
7971 #endif
7972 
7973 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7974     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7975 
7976   // We create new control-flow for the vectorized loop, so the original exit
7977   // conditions will be dead after vectorization if it's only used by the
7978   // terminator
7979   SmallVector<BasicBlock*> ExitingBlocks;
7980   OrigLoop->getExitingBlocks(ExitingBlocks);
7981   for (auto *BB : ExitingBlocks) {
7982     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
7983     if (!Cmp || !Cmp->hasOneUse())
7984       continue;
7985 
7986     // TODO: we should introduce a getUniqueExitingBlocks on Loop
7987     if (!DeadInstructions.insert(Cmp).second)
7988       continue;
7989 
7990     // The operands of the icmp is often a dead trunc, used by IndUpdate.
7991     // TODO: can recurse through operands in general
7992     for (Value *Op : Cmp->operands()) {
7993       if (isa<TruncInst>(Op) && Op->hasOneUse())
7994           DeadInstructions.insert(cast<Instruction>(Op));
7995     }
7996   }
7997 
7998   // We create new "steps" for induction variable updates to which the original
7999   // induction variables map. An original update instruction will be dead if
8000   // all its users except the induction variable are dead.
8001   auto *Latch = OrigLoop->getLoopLatch();
8002   for (auto &Induction : Legal->getInductionVars()) {
8003     PHINode *Ind = Induction.first;
8004     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
8005 
8006     // If the tail is to be folded by masking, the primary induction variable,
8007     // if exists, isn't dead: it will be used for masking. Don't kill it.
8008     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
8009       continue;
8010 
8011     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
8012           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
8013         }))
8014       DeadInstructions.insert(IndUpdate);
8015 
8016     // We record as "Dead" also the type-casting instructions we had identified
8017     // during induction analysis. We don't need any handling for them in the
8018     // vectorized loop because we have proven that, under a proper runtime
8019     // test guarding the vectorized loop, the value of the phi, and the casted
8020     // value of the phi, are the same. The last instruction in this casting chain
8021     // will get its scalar/vector/widened def from the scalar/vector/widened def
8022     // of the respective phi node. Any other casts in the induction def-use chain
8023     // have no other uses outside the phi update chain, and will be ignored.
8024     InductionDescriptor &IndDes = Induction.second;
8025     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
8026     DeadInstructions.insert(Casts.begin(), Casts.end());
8027   }
8028 }
8029 
8030 Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
8031 
8032 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
8033 
8034 Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
8035                                         Instruction::BinaryOps BinOp) {
8036   // When unrolling and the VF is 1, we only need to add a simple scalar.
8037   Type *Ty = Val->getType();
8038   assert(!Ty->isVectorTy() && "Val must be a scalar");
8039 
8040   if (Ty->isFloatingPointTy()) {
8041     Constant *C = ConstantFP::get(Ty, (double)StartIdx);
8042 
8043     // Floating-point operations inherit FMF via the builder's flags.
8044     Value *MulOp = Builder.CreateFMul(C, Step);
8045     return Builder.CreateBinOp(BinOp, Val, MulOp);
8046   }
8047   Constant *C = ConstantInt::get(Ty, StartIdx);
8048   return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
8049 }
8050 
8051 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
8052   SmallVector<Metadata *, 4> MDs;
8053   // Reserve first location for self reference to the LoopID metadata node.
8054   MDs.push_back(nullptr);
8055   bool IsUnrollMetadata = false;
8056   MDNode *LoopID = L->getLoopID();
8057   if (LoopID) {
8058     // First find existing loop unrolling disable metadata.
8059     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
8060       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
8061       if (MD) {
8062         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
8063         IsUnrollMetadata =
8064             S && S->getString().startswith("llvm.loop.unroll.disable");
8065       }
8066       MDs.push_back(LoopID->getOperand(i));
8067     }
8068   }
8069 
8070   if (!IsUnrollMetadata) {
8071     // Add runtime unroll disable metadata.
8072     LLVMContext &Context = L->getHeader()->getContext();
8073     SmallVector<Metadata *, 1> DisableOperands;
8074     DisableOperands.push_back(
8075         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
8076     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
8077     MDs.push_back(DisableNode);
8078     MDNode *NewLoopID = MDNode::get(Context, MDs);
8079     // Set operand 0 to refer to the loop id itself.
8080     NewLoopID->replaceOperandWith(0, NewLoopID);
8081     L->setLoopID(NewLoopID);
8082   }
8083 }
8084 
8085 //===--------------------------------------------------------------------===//
8086 // EpilogueVectorizerMainLoop
8087 //===--------------------------------------------------------------------===//
8088 
8089 /// This function is partially responsible for generating the control flow
8090 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8091 BasicBlock *EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
8092   MDNode *OrigLoopID = OrigLoop->getLoopID();
8093   Loop *Lp = createVectorLoopSkeleton("");
8094 
8095   // Generate the code to check the minimum iteration count of the vector
8096   // epilogue (see below).
8097   EPI.EpilogueIterationCountCheck =
8098       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, true);
8099   EPI.EpilogueIterationCountCheck->setName("iter.check");
8100 
8101   // Generate the code to check any assumptions that we've made for SCEV
8102   // expressions.
8103   EPI.SCEVSafetyCheck = emitSCEVChecks(Lp, LoopScalarPreHeader);
8104 
8105   // Generate the code that checks at runtime if arrays overlap. We put the
8106   // checks into a separate block to make the more common case of few elements
8107   // faster.
8108   EPI.MemSafetyCheck = emitMemRuntimeChecks(Lp, LoopScalarPreHeader);
8109 
8110   // Generate the iteration count check for the main loop, *after* the check
8111   // for the epilogue loop, so that the path-length is shorter for the case
8112   // that goes directly through the vector epilogue. The longer-path length for
8113   // the main loop is compensated for, by the gain from vectorizing the larger
8114   // trip count. Note: the branch will get updated later on when we vectorize
8115   // the epilogue.
8116   EPI.MainLoopIterationCountCheck =
8117       emitMinimumIterationCountCheck(Lp, LoopScalarPreHeader, false);
8118 
8119   // Generate the induction variable.
8120   OldInduction = Legal->getPrimaryInduction();
8121   Type *IdxTy = Legal->getWidestInductionType();
8122   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8123   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8124   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8125   EPI.VectorTripCount = CountRoundDown;
8126   Induction =
8127       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8128                               getDebugLocFromInstOrOperands(OldInduction));
8129 
8130   // Skip induction resume value creation here because they will be created in
8131   // the second pass. If we created them here, they wouldn't be used anyway,
8132   // because the vplan in the second pass still contains the inductions from the
8133   // original loop.
8134 
8135   return completeLoopSkeleton(Lp, OrigLoopID);
8136 }
8137 
8138 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
8139   LLVM_DEBUG({
8140     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
8141            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
8142            << ", Main Loop UF:" << EPI.MainLoopUF
8143            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8144            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8145   });
8146 }
8147 
8148 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
8149   DEBUG_WITH_TYPE(VerboseDebug, {
8150     dbgs() << "intermediate fn:\n" << *Induction->getFunction() << "\n";
8151   });
8152 }
8153 
8154 BasicBlock *EpilogueVectorizerMainLoop::emitMinimumIterationCountCheck(
8155     Loop *L, BasicBlock *Bypass, bool ForEpilogue) {
8156   assert(L && "Expected valid Loop.");
8157   assert(Bypass && "Expected valid bypass basic block.");
8158   unsigned VFactor =
8159       ForEpilogue ? EPI.EpilogueVF.getKnownMinValue() : VF.getKnownMinValue();
8160   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
8161   Value *Count = getOrCreateTripCount(L);
8162   // Reuse existing vector loop preheader for TC checks.
8163   // Note that new preheader block is generated for vector loop.
8164   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
8165   IRBuilder<> Builder(TCCheckBlock->getTerminator());
8166 
8167   // Generate code to check if the loop's trip count is less than VF * UF of the
8168   // main vector loop.
8169   auto P =
8170       Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8171 
8172   Value *CheckMinIters = Builder.CreateICmp(
8173       P, Count, ConstantInt::get(Count->getType(), VFactor * UFactor),
8174       "min.iters.check");
8175 
8176   if (!ForEpilogue)
8177     TCCheckBlock->setName("vector.main.loop.iter.check");
8178 
8179   // Create new preheader for vector loop.
8180   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
8181                                    DT, LI, nullptr, "vector.ph");
8182 
8183   if (ForEpilogue) {
8184     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
8185                                  DT->getNode(Bypass)->getIDom()) &&
8186            "TC check is expected to dominate Bypass");
8187 
8188     // Update dominator for Bypass & LoopExit.
8189     DT->changeImmediateDominator(Bypass, TCCheckBlock);
8190     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
8191 
8192     LoopBypassBlocks.push_back(TCCheckBlock);
8193 
8194     // Save the trip count so we don't have to regenerate it in the
8195     // vec.epilog.iter.check. This is safe to do because the trip count
8196     // generated here dominates the vector epilog iter check.
8197     EPI.TripCount = Count;
8198   }
8199 
8200   ReplaceInstWithInst(
8201       TCCheckBlock->getTerminator(),
8202       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8203 
8204   return TCCheckBlock;
8205 }
8206 
8207 //===--------------------------------------------------------------------===//
8208 // EpilogueVectorizerEpilogueLoop
8209 //===--------------------------------------------------------------------===//
8210 
8211 /// This function is partially responsible for generating the control flow
8212 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
8213 BasicBlock *
8214 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
8215   MDNode *OrigLoopID = OrigLoop->getLoopID();
8216   Loop *Lp = createVectorLoopSkeleton("vec.epilog.");
8217 
8218   // Now, compare the remaining count and if there aren't enough iterations to
8219   // execute the vectorized epilogue skip to the scalar part.
8220   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
8221   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
8222   LoopVectorPreHeader =
8223       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
8224                  LI, nullptr, "vec.epilog.ph");
8225   emitMinimumVectorEpilogueIterCountCheck(Lp, LoopScalarPreHeader,
8226                                           VecEpilogueIterationCountCheck);
8227 
8228   // Adjust the control flow taking the state info from the main loop
8229   // vectorization into account.
8230   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
8231          "expected this to be saved from the previous pass.");
8232   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
8233       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
8234 
8235   DT->changeImmediateDominator(LoopVectorPreHeader,
8236                                EPI.MainLoopIterationCountCheck);
8237 
8238   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
8239       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8240 
8241   if (EPI.SCEVSafetyCheck)
8242     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
8243         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8244   if (EPI.MemSafetyCheck)
8245     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
8246         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
8247 
8248   DT->changeImmediateDominator(
8249       VecEpilogueIterationCountCheck,
8250       VecEpilogueIterationCountCheck->getSinglePredecessor());
8251 
8252   DT->changeImmediateDominator(LoopScalarPreHeader,
8253                                EPI.EpilogueIterationCountCheck);
8254   DT->changeImmediateDominator(LoopExitBlock, EPI.EpilogueIterationCountCheck);
8255 
8256   // Keep track of bypass blocks, as they feed start values to the induction
8257   // phis in the scalar loop preheader.
8258   if (EPI.SCEVSafetyCheck)
8259     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
8260   if (EPI.MemSafetyCheck)
8261     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
8262   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
8263 
8264   // Generate a resume induction for the vector epilogue and put it in the
8265   // vector epilogue preheader
8266   Type *IdxTy = Legal->getWidestInductionType();
8267   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
8268                                          LoopVectorPreHeader->getFirstNonPHI());
8269   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
8270   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
8271                            EPI.MainLoopIterationCountCheck);
8272 
8273   // Generate the induction variable.
8274   OldInduction = Legal->getPrimaryInduction();
8275   Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
8276   Constant *Step = ConstantInt::get(IdxTy, VF.getKnownMinValue() * UF);
8277   Value *StartIdx = EPResumeVal;
8278   Induction =
8279       createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
8280                               getDebugLocFromInstOrOperands(OldInduction));
8281 
8282   // Generate induction resume values. These variables save the new starting
8283   // indexes for the scalar loop. They are used to test if there are any tail
8284   // iterations left once the vector loop has completed.
8285   // Note that when the vectorized epilogue is skipped due to iteration count
8286   // check, then the resume value for the induction variable comes from
8287   // the trip count of the main vector loop, hence passing the AdditionalBypass
8288   // argument.
8289   createInductionResumeValues(Lp, CountRoundDown,
8290                               {VecEpilogueIterationCountCheck,
8291                                EPI.VectorTripCount} /* AdditionalBypass */);
8292 
8293   AddRuntimeUnrollDisableMetaData(Lp);
8294   return completeLoopSkeleton(Lp, OrigLoopID);
8295 }
8296 
8297 BasicBlock *
8298 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
8299     Loop *L, BasicBlock *Bypass, BasicBlock *Insert) {
8300 
8301   assert(EPI.TripCount &&
8302          "Expected trip count to have been safed in the first pass.");
8303   assert(
8304       (!isa<Instruction>(EPI.TripCount) ||
8305        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
8306       "saved trip count does not dominate insertion point.");
8307   Value *TC = EPI.TripCount;
8308   IRBuilder<> Builder(Insert->getTerminator());
8309   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
8310 
8311   // Generate code to check if the loop's trip count is less than VF * UF of the
8312   // vector epilogue loop.
8313   auto P =
8314       Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
8315 
8316   Value *CheckMinIters = Builder.CreateICmp(
8317       P, Count,
8318       ConstantInt::get(Count->getType(),
8319                        EPI.EpilogueVF.getKnownMinValue() * EPI.EpilogueUF),
8320       "min.epilog.iters.check");
8321 
8322   ReplaceInstWithInst(
8323       Insert->getTerminator(),
8324       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
8325 
8326   LoopBypassBlocks.push_back(Insert);
8327   return Insert;
8328 }
8329 
8330 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
8331   LLVM_DEBUG({
8332     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
8333            << "Main Loop VF:" << EPI.MainLoopVF.getKnownMinValue()
8334            << ", Main Loop UF:" << EPI.MainLoopUF
8335            << ", Epilogue Loop VF:" << EPI.EpilogueVF.getKnownMinValue()
8336            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
8337   });
8338 }
8339 
8340 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
8341   DEBUG_WITH_TYPE(VerboseDebug, {
8342     dbgs() << "final fn:\n" << *Induction->getFunction() << "\n";
8343   });
8344 }
8345 
8346 bool LoopVectorizationPlanner::getDecisionAndClampRange(
8347     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
8348   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
8349   bool PredicateAtRangeStart = Predicate(Range.Start);
8350 
8351   for (ElementCount TmpVF = Range.Start * 2;
8352        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
8353     if (Predicate(TmpVF) != PredicateAtRangeStart) {
8354       Range.End = TmpVF;
8355       break;
8356     }
8357 
8358   return PredicateAtRangeStart;
8359 }
8360 
8361 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8362 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8363 /// of VF's starting at a given VF and extending it as much as possible. Each
8364 /// vectorization decision can potentially shorten this sub-range during
8365 /// buildVPlan().
8366 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8367                                            ElementCount MaxVF) {
8368   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8369   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8370     VFRange SubRange = {VF, MaxVFPlusOne};
8371     VPlans.push_back(buildVPlan(SubRange));
8372     VF = SubRange.End;
8373   }
8374 }
8375 
8376 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8377                                          VPlanPtr &Plan) {
8378   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8379 
8380   // Look for cached value.
8381   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8382   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8383   if (ECEntryIt != EdgeMaskCache.end())
8384     return ECEntryIt->second;
8385 
8386   VPValue *SrcMask = createBlockInMask(Src, Plan);
8387 
8388   // The terminator has to be a branch inst!
8389   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8390   assert(BI && "Unexpected terminator found");
8391 
8392   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8393     return EdgeMaskCache[Edge] = SrcMask;
8394 
8395   // If source is an exiting block, we know the exit edge is dynamically dead
8396   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8397   // adding uses of an otherwise potentially dead instruction.
8398   if (OrigLoop->isLoopExiting(Src))
8399     return EdgeMaskCache[Edge] = SrcMask;
8400 
8401   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8402   assert(EdgeMask && "No Edge Mask found for condition");
8403 
8404   if (BI->getSuccessor(0) != Dst)
8405     EdgeMask = Builder.createNot(EdgeMask);
8406 
8407   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8408     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8409     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8410     // The select version does not introduce new UB if SrcMask is false and
8411     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8412     VPValue *False = Plan->getOrAddVPValue(
8413         ConstantInt::getFalse(BI->getCondition()->getType()));
8414     EdgeMask = Builder.createSelect(SrcMask, EdgeMask, False);
8415   }
8416 
8417   return EdgeMaskCache[Edge] = EdgeMask;
8418 }
8419 
8420 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8421   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8422 
8423   // Look for cached value.
8424   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8425   if (BCEntryIt != BlockMaskCache.end())
8426     return BCEntryIt->second;
8427 
8428   // All-one mask is modelled as no-mask following the convention for masked
8429   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8430   VPValue *BlockMask = nullptr;
8431 
8432   if (OrigLoop->getHeader() == BB) {
8433     if (!CM.blockNeedsPredication(BB))
8434       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8435 
8436     // Create the block in mask as the first non-phi instruction in the block.
8437     VPBuilder::InsertPointGuard Guard(Builder);
8438     auto NewInsertionPoint = Builder.getInsertBlock()->getFirstNonPhi();
8439     Builder.setInsertPoint(Builder.getInsertBlock(), NewInsertionPoint);
8440 
8441     // Introduce the early-exit compare IV <= BTC to form header block mask.
8442     // This is used instead of IV < TC because TC may wrap, unlike BTC.
8443     // Start by constructing the desired canonical IV.
8444     VPValue *IV = nullptr;
8445     if (Legal->getPrimaryInduction())
8446       IV = Plan->getOrAddVPValue(Legal->getPrimaryInduction());
8447     else {
8448       auto IVRecipe = new VPWidenCanonicalIVRecipe();
8449       Builder.getInsertBlock()->insert(IVRecipe, NewInsertionPoint);
8450       IV = IVRecipe->getVPSingleValue();
8451     }
8452     VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8453     bool TailFolded = !CM.isScalarEpilogueAllowed();
8454 
8455     if (TailFolded && CM.TTI.emitGetActiveLaneMask()) {
8456       // While ActiveLaneMask is a binary op that consumes the loop tripcount
8457       // as a second argument, we only pass the IV here and extract the
8458       // tripcount from the transform state where codegen of the VP instructions
8459       // happen.
8460       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV});
8461     } else {
8462       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8463     }
8464     return BlockMaskCache[BB] = BlockMask;
8465   }
8466 
8467   // This is the block mask. We OR all incoming edges.
8468   for (auto *Predecessor : predecessors(BB)) {
8469     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8470     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8471       return BlockMaskCache[BB] = EdgeMask;
8472 
8473     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8474       BlockMask = EdgeMask;
8475       continue;
8476     }
8477 
8478     BlockMask = Builder.createOr(BlockMask, EdgeMask);
8479   }
8480 
8481   return BlockMaskCache[BB] = BlockMask;
8482 }
8483 
8484 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8485                                                 ArrayRef<VPValue *> Operands,
8486                                                 VFRange &Range,
8487                                                 VPlanPtr &Plan) {
8488   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8489          "Must be called with either a load or store");
8490 
8491   auto willWiden = [&](ElementCount VF) -> bool {
8492     if (VF.isScalar())
8493       return false;
8494     LoopVectorizationCostModel::InstWidening Decision =
8495         CM.getWideningDecision(I, VF);
8496     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8497            "CM decision should be taken at this point.");
8498     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8499       return true;
8500     if (CM.isScalarAfterVectorization(I, VF) ||
8501         CM.isProfitableToScalarize(I, VF))
8502       return false;
8503     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8504   };
8505 
8506   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8507     return nullptr;
8508 
8509   VPValue *Mask = nullptr;
8510   if (Legal->isMaskRequired(I))
8511     Mask = createBlockInMask(I->getParent(), Plan);
8512 
8513   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8514     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask);
8515 
8516   StoreInst *Store = cast<StoreInst>(I);
8517   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8518                                             Mask);
8519 }
8520 
8521 VPWidenIntOrFpInductionRecipe *
8522 VPRecipeBuilder::tryToOptimizeInductionPHI(PHINode *Phi,
8523                                            ArrayRef<VPValue *> Operands) const {
8524   // Check if this is an integer or fp induction. If so, build the recipe that
8525   // produces its scalar and vector values.
8526   InductionDescriptor II = Legal->getInductionVars().lookup(Phi);
8527   if (II.getKind() == InductionDescriptor::IK_IntInduction ||
8528       II.getKind() == InductionDescriptor::IK_FpInduction) {
8529     assert(II.getStartValue() ==
8530            Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8531     const SmallVectorImpl<Instruction *> &Casts = II.getCastInsts();
8532     return new VPWidenIntOrFpInductionRecipe(
8533         Phi, Operands[0], Casts.empty() ? nullptr : Casts.front());
8534   }
8535 
8536   return nullptr;
8537 }
8538 
8539 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8540     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range,
8541     VPlan &Plan) const {
8542   // Optimize the special case where the source is a constant integer
8543   // induction variable. Notice that we can only optimize the 'trunc' case
8544   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8545   // (c) other casts depend on pointer size.
8546 
8547   // Determine whether \p K is a truncation based on an induction variable that
8548   // can be optimized.
8549   auto isOptimizableIVTruncate =
8550       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8551     return [=](ElementCount VF) -> bool {
8552       return CM.isOptimizableIVTruncate(K, VF);
8553     };
8554   };
8555 
8556   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8557           isOptimizableIVTruncate(I), Range)) {
8558 
8559     InductionDescriptor II =
8560         Legal->getInductionVars().lookup(cast<PHINode>(I->getOperand(0)));
8561     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8562     return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
8563                                              Start, nullptr, I);
8564   }
8565   return nullptr;
8566 }
8567 
8568 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8569                                                 ArrayRef<VPValue *> Operands,
8570                                                 VPlanPtr &Plan) {
8571   // If all incoming values are equal, the incoming VPValue can be used directly
8572   // instead of creating a new VPBlendRecipe.
8573   VPValue *FirstIncoming = Operands[0];
8574   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8575         return FirstIncoming == Inc;
8576       })) {
8577     return Operands[0];
8578   }
8579 
8580   // We know that all PHIs in non-header blocks are converted into selects, so
8581   // we don't have to worry about the insertion order and we can just use the
8582   // builder. At this point we generate the predication tree. There may be
8583   // duplications since this is a simple recursive scan, but future
8584   // optimizations will clean it up.
8585   SmallVector<VPValue *, 2> OperandsWithMask;
8586   unsigned NumIncoming = Phi->getNumIncomingValues();
8587 
8588   for (unsigned In = 0; In < NumIncoming; In++) {
8589     VPValue *EdgeMask =
8590       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8591     assert((EdgeMask || NumIncoming == 1) &&
8592            "Multiple predecessors with one having a full mask");
8593     OperandsWithMask.push_back(Operands[In]);
8594     if (EdgeMask)
8595       OperandsWithMask.push_back(EdgeMask);
8596   }
8597   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8598 }
8599 
8600 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8601                                                    ArrayRef<VPValue *> Operands,
8602                                                    VFRange &Range) const {
8603 
8604   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8605       [this, CI](ElementCount VF) {
8606         return CM.isScalarWithPredication(CI, VF);
8607       },
8608       Range);
8609 
8610   if (IsPredicated)
8611     return nullptr;
8612 
8613   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8614   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8615              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8616              ID == Intrinsic::pseudoprobe ||
8617              ID == Intrinsic::experimental_noalias_scope_decl))
8618     return nullptr;
8619 
8620   auto willWiden = [&](ElementCount VF) -> bool {
8621     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8622     // The following case may be scalarized depending on the VF.
8623     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8624     // version of the instruction.
8625     // Is it beneficial to perform intrinsic call compared to lib call?
8626     bool NeedToScalarize = false;
8627     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8628     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8629     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8630     assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
8631            "Either the intrinsic cost or vector call cost must be valid");
8632     return UseVectorIntrinsic || !NeedToScalarize;
8633   };
8634 
8635   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8636     return nullptr;
8637 
8638   ArrayRef<VPValue *> Ops = Operands.take_front(CI->getNumArgOperands());
8639   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8640 }
8641 
8642 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8643   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8644          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8645   // Instruction should be widened, unless it is scalar after vectorization,
8646   // scalarization is profitable or it is predicated.
8647   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8648     return CM.isScalarAfterVectorization(I, VF) ||
8649            CM.isProfitableToScalarize(I, VF) ||
8650            CM.isScalarWithPredication(I, VF);
8651   };
8652   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8653                                                              Range);
8654 }
8655 
8656 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8657                                            ArrayRef<VPValue *> Operands) const {
8658   auto IsVectorizableOpcode = [](unsigned Opcode) {
8659     switch (Opcode) {
8660     case Instruction::Add:
8661     case Instruction::And:
8662     case Instruction::AShr:
8663     case Instruction::BitCast:
8664     case Instruction::FAdd:
8665     case Instruction::FCmp:
8666     case Instruction::FDiv:
8667     case Instruction::FMul:
8668     case Instruction::FNeg:
8669     case Instruction::FPExt:
8670     case Instruction::FPToSI:
8671     case Instruction::FPToUI:
8672     case Instruction::FPTrunc:
8673     case Instruction::FRem:
8674     case Instruction::FSub:
8675     case Instruction::ICmp:
8676     case Instruction::IntToPtr:
8677     case Instruction::LShr:
8678     case Instruction::Mul:
8679     case Instruction::Or:
8680     case Instruction::PtrToInt:
8681     case Instruction::SDiv:
8682     case Instruction::Select:
8683     case Instruction::SExt:
8684     case Instruction::Shl:
8685     case Instruction::SIToFP:
8686     case Instruction::SRem:
8687     case Instruction::Sub:
8688     case Instruction::Trunc:
8689     case Instruction::UDiv:
8690     case Instruction::UIToFP:
8691     case Instruction::URem:
8692     case Instruction::Xor:
8693     case Instruction::ZExt:
8694       return true;
8695     }
8696     return false;
8697   };
8698 
8699   if (!IsVectorizableOpcode(I->getOpcode()))
8700     return nullptr;
8701 
8702   // Success: widen this instruction.
8703   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8704 }
8705 
8706 VPBasicBlock *VPRecipeBuilder::handleReplication(
8707     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8708     VPlanPtr &Plan) {
8709   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8710       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8711       Range);
8712 
8713   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8714       [&](ElementCount VF) { return CM.isPredicatedInst(I, VF); }, Range);
8715 
8716   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8717                                        IsUniform, IsPredicated);
8718   setRecipe(I, Recipe);
8719   Plan->addVPValue(I, Recipe);
8720 
8721   // Find if I uses a predicated instruction. If so, it will use its scalar
8722   // value. Avoid hoisting the insert-element which packs the scalar value into
8723   // a vector value, as that happens iff all users use the vector value.
8724   for (VPValue *Op : Recipe->operands()) {
8725     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8726     if (!PredR)
8727       continue;
8728     auto *RepR =
8729         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8730     assert(RepR->isPredicated() &&
8731            "expected Replicate recipe to be predicated");
8732     RepR->setAlsoPack(false);
8733   }
8734 
8735   // Finalize the recipe for Instr, first if it is not predicated.
8736   if (!IsPredicated) {
8737     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8738     VPBB->appendRecipe(Recipe);
8739     return VPBB;
8740   }
8741   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8742   assert(VPBB->getSuccessors().empty() &&
8743          "VPBB has successors when handling predicated replication.");
8744   // Record predicated instructions for above packing optimizations.
8745   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8746   VPBlockUtils::insertBlockAfter(Region, VPBB);
8747   auto *RegSucc = new VPBasicBlock();
8748   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8749   return RegSucc;
8750 }
8751 
8752 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8753                                                       VPRecipeBase *PredRecipe,
8754                                                       VPlanPtr &Plan) {
8755   // Instructions marked for predication are replicated and placed under an
8756   // if-then construct to prevent side-effects.
8757 
8758   // Generate recipes to compute the block mask for this region.
8759   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8760 
8761   // Build the triangular if-then region.
8762   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8763   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8764   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8765   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8766   auto *PHIRecipe = Instr->getType()->isVoidTy()
8767                         ? nullptr
8768                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8769   if (PHIRecipe) {
8770     Plan->removeVPValueFor(Instr);
8771     Plan->addVPValue(Instr, PHIRecipe);
8772   }
8773   auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8774   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8775   VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
8776 
8777   // Note: first set Entry as region entry and then connect successors starting
8778   // from it in order, to propagate the "parent" of each VPBasicBlock.
8779   VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
8780   VPBlockUtils::connectBlocks(Pred, Exit);
8781 
8782   return Region;
8783 }
8784 
8785 VPRecipeOrVPValueTy
8786 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8787                                         ArrayRef<VPValue *> Operands,
8788                                         VFRange &Range, VPlanPtr &Plan) {
8789   // First, check for specific widening recipes that deal with calls, memory
8790   // operations, inductions and Phi nodes.
8791   if (auto *CI = dyn_cast<CallInst>(Instr))
8792     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8793 
8794   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8795     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8796 
8797   VPRecipeBase *Recipe;
8798   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8799     if (Phi->getParent() != OrigLoop->getHeader())
8800       return tryToBlend(Phi, Operands, Plan);
8801     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands)))
8802       return toVPRecipeResult(Recipe);
8803 
8804     if (Legal->isReductionVariable(Phi)) {
8805       RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
8806       assert(RdxDesc.getRecurrenceStartValue() ==
8807              Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8808       VPValue *StartV = Operands[0];
8809       return toVPRecipeResult(new VPWidenPHIRecipe(Phi, RdxDesc, *StartV));
8810     }
8811 
8812     return toVPRecipeResult(new VPWidenPHIRecipe(Phi));
8813   }
8814 
8815   if (isa<TruncInst>(Instr) &&
8816       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8817                                                Range, *Plan)))
8818     return toVPRecipeResult(Recipe);
8819 
8820   if (!shouldWiden(Instr, Range))
8821     return nullptr;
8822 
8823   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8824     return toVPRecipeResult(new VPWidenGEPRecipe(
8825         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8826 
8827   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8828     bool InvariantCond =
8829         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8830     return toVPRecipeResult(new VPWidenSelectRecipe(
8831         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8832   }
8833 
8834   return toVPRecipeResult(tryToWiden(Instr, Operands));
8835 }
8836 
8837 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8838                                                         ElementCount MaxVF) {
8839   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8840 
8841   // Collect instructions from the original loop that will become trivially dead
8842   // in the vectorized loop. We don't need to vectorize these instructions. For
8843   // example, original induction update instructions can become dead because we
8844   // separately emit induction "steps" when generating code for the new loop.
8845   // Similarly, we create a new latch condition when setting up the structure
8846   // of the new loop, so the old one can become dead.
8847   SmallPtrSet<Instruction *, 4> DeadInstructions;
8848   collectTriviallyDeadInstructions(DeadInstructions);
8849 
8850   // Add assume instructions we need to drop to DeadInstructions, to prevent
8851   // them from being added to the VPlan.
8852   // TODO: We only need to drop assumes in blocks that get flattend. If the
8853   // control flow is preserved, we should keep them.
8854   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8855   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8856 
8857   DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8858   // Dead instructions do not need sinking. Remove them from SinkAfter.
8859   for (Instruction *I : DeadInstructions)
8860     SinkAfter.erase(I);
8861 
8862   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8863   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8864     VFRange SubRange = {VF, MaxVFPlusOne};
8865     VPlans.push_back(
8866         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8867     VF = SubRange.End;
8868   }
8869 }
8870 
8871 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
8872     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
8873     const DenseMap<Instruction *, Instruction *> &SinkAfter) {
8874 
8875   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8876 
8877   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
8878 
8879   // ---------------------------------------------------------------------------
8880   // Pre-construction: record ingredients whose recipes we'll need to further
8881   // process after constructing the initial VPlan.
8882   // ---------------------------------------------------------------------------
8883 
8884   // Mark instructions we'll need to sink later and their targets as
8885   // ingredients whose recipe we'll need to record.
8886   for (auto &Entry : SinkAfter) {
8887     RecipeBuilder.recordRecipeOf(Entry.first);
8888     RecipeBuilder.recordRecipeOf(Entry.second);
8889   }
8890   for (auto &Reduction : CM.getInLoopReductionChains()) {
8891     PHINode *Phi = Reduction.first;
8892     RecurKind Kind = Legal->getReductionVars()[Phi].getRecurrenceKind();
8893     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8894 
8895     RecipeBuilder.recordRecipeOf(Phi);
8896     for (auto &R : ReductionOperations) {
8897       RecipeBuilder.recordRecipeOf(R);
8898       // For min/max reducitons, where we have a pair of icmp/select, we also
8899       // need to record the ICmp recipe, so it can be removed later.
8900       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
8901         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
8902     }
8903   }
8904 
8905   // For each interleave group which is relevant for this (possibly trimmed)
8906   // Range, add it to the set of groups to be later applied to the VPlan and add
8907   // placeholders for its members' Recipes which we'll be replacing with a
8908   // single VPInterleaveRecipe.
8909   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8910     auto applyIG = [IG, this](ElementCount VF) -> bool {
8911       return (VF.isVector() && // Query is illegal for VF == 1
8912               CM.getWideningDecision(IG->getInsertPos(), VF) ==
8913                   LoopVectorizationCostModel::CM_Interleave);
8914     };
8915     if (!getDecisionAndClampRange(applyIG, Range))
8916       continue;
8917     InterleaveGroups.insert(IG);
8918     for (unsigned i = 0; i < IG->getFactor(); i++)
8919       if (Instruction *Member = IG->getMember(i))
8920         RecipeBuilder.recordRecipeOf(Member);
8921   };
8922 
8923   // ---------------------------------------------------------------------------
8924   // Build initial VPlan: Scan the body of the loop in a topological order to
8925   // visit each basic block after having visited its predecessor basic blocks.
8926   // ---------------------------------------------------------------------------
8927 
8928   // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
8929   auto Plan = std::make_unique<VPlan>();
8930   VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
8931   Plan->setEntry(VPBB);
8932 
8933   // Scan the body of the loop in a topological order to visit each basic block
8934   // after having visited its predecessor basic blocks.
8935   LoopBlocksDFS DFS(OrigLoop);
8936   DFS.perform(LI);
8937 
8938   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8939     // Relevant instructions from basic block BB will be grouped into VPRecipe
8940     // ingredients and fill a new VPBasicBlock.
8941     unsigned VPBBsForBB = 0;
8942     auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
8943     VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
8944     VPBB = FirstVPBBForBB;
8945     Builder.setInsertPoint(VPBB);
8946 
8947     // Introduce each ingredient into VPlan.
8948     // TODO: Model and preserve debug instrinsics in VPlan.
8949     for (Instruction &I : BB->instructionsWithoutDebug()) {
8950       Instruction *Instr = &I;
8951 
8952       // First filter out irrelevant instructions, to ensure no recipes are
8953       // built for them.
8954       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
8955         continue;
8956 
8957       SmallVector<VPValue *, 4> Operands;
8958       auto *Phi = dyn_cast<PHINode>(Instr);
8959       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
8960         Operands.push_back(Plan->getOrAddVPValue(
8961             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
8962       } else {
8963         auto OpRange = Plan->mapToVPValues(Instr->operands());
8964         Operands = {OpRange.begin(), OpRange.end()};
8965       }
8966       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
8967               Instr, Operands, Range, Plan)) {
8968         // If Instr can be simplified to an existing VPValue, use it.
8969         if (RecipeOrValue.is<VPValue *>()) {
8970           Plan->addVPValue(Instr, RecipeOrValue.get<VPValue *>());
8971           continue;
8972         }
8973         // Otherwise, add the new recipe.
8974         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
8975         for (auto *Def : Recipe->definedValues()) {
8976           auto *UV = Def->getUnderlyingValue();
8977           Plan->addVPValue(UV, Def);
8978         }
8979 
8980         RecipeBuilder.setRecipe(Instr, Recipe);
8981         VPBB->appendRecipe(Recipe);
8982         continue;
8983       }
8984 
8985       // Otherwise, if all widening options failed, Instruction is to be
8986       // replicated. This may create a successor for VPBB.
8987       VPBasicBlock *NextVPBB =
8988           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
8989       if (NextVPBB != VPBB) {
8990         VPBB = NextVPBB;
8991         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8992                                     : "");
8993       }
8994     }
8995   }
8996 
8997   // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
8998   // may also be empty, such as the last one VPBB, reflecting original
8999   // basic-blocks with no recipes.
9000   VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
9001   assert(PreEntry->empty() && "Expecting empty pre-entry block.");
9002   VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
9003   VPBlockUtils::disconnectBlocks(PreEntry, Entry);
9004   delete PreEntry;
9005 
9006   // ---------------------------------------------------------------------------
9007   // Transform initial VPlan: Apply previously taken decisions, in order, to
9008   // bring the VPlan to its final state.
9009   // ---------------------------------------------------------------------------
9010 
9011   // Apply Sink-After legal constraints.
9012   for (auto &Entry : SinkAfter) {
9013     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
9014     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
9015     // If the target is in a replication region, make sure to move Sink to the
9016     // block after it, not into the replication region itself.
9017     if (auto *Region =
9018             dyn_cast_or_null<VPRegionBlock>(Target->getParent()->getParent())) {
9019       if (Region->isReplicator()) {
9020         assert(Region->getNumSuccessors() == 1 && "Expected SESE region!");
9021         VPBasicBlock *NextBlock =
9022             cast<VPBasicBlock>(Region->getSuccessors().front());
9023         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
9024         continue;
9025       }
9026     }
9027     Sink->moveAfter(Target);
9028   }
9029 
9030   // Interleave memory: for each Interleave Group we marked earlier as relevant
9031   // for this VPlan, replace the Recipes widening its memory instructions with a
9032   // single VPInterleaveRecipe at its insertion point.
9033   for (auto IG : InterleaveGroups) {
9034     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
9035         RecipeBuilder.getRecipe(IG->getInsertPos()));
9036     SmallVector<VPValue *, 4> StoredValues;
9037     for (unsigned i = 0; i < IG->getFactor(); ++i)
9038       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i)))
9039         StoredValues.push_back(Plan->getOrAddVPValue(SI->getOperand(0)));
9040 
9041     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9042                                         Recipe->getMask());
9043     VPIG->insertBefore(Recipe);
9044     unsigned J = 0;
9045     for (unsigned i = 0; i < IG->getFactor(); ++i)
9046       if (Instruction *Member = IG->getMember(i)) {
9047         if (!Member->getType()->isVoidTy()) {
9048           VPValue *OriginalV = Plan->getVPValue(Member);
9049           Plan->removeVPValueFor(Member);
9050           Plan->addVPValue(Member, VPIG->getVPValue(J));
9051           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9052           J++;
9053         }
9054         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9055       }
9056   }
9057 
9058   // Adjust the recipes for any inloop reductions.
9059   if (Range.Start.isVector())
9060     adjustRecipesForInLoopReductions(Plan, RecipeBuilder);
9061 
9062   // Finally, if tail is folded by masking, introduce selects between the phi
9063   // and the live-out instruction of each reduction, at the end of the latch.
9064   if (CM.foldTailByMasking() && !Legal->getReductionVars().empty()) {
9065     Builder.setInsertPoint(VPBB);
9066     auto *Cond = RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9067     for (auto &Reduction : Legal->getReductionVars()) {
9068       if (CM.isInLoopReduction(Reduction.first))
9069         continue;
9070       VPValue *Phi = Plan->getOrAddVPValue(Reduction.first);
9071       VPValue *Red = Plan->getOrAddVPValue(Reduction.second.getLoopExitInstr());
9072       Builder.createNaryOp(Instruction::Select, {Cond, Red, Phi});
9073     }
9074   }
9075 
9076   std::string PlanName;
9077   raw_string_ostream RSO(PlanName);
9078   ElementCount VF = Range.Start;
9079   Plan->addVF(VF);
9080   RSO << "Initial VPlan for VF={" << VF;
9081   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9082     Plan->addVF(VF);
9083     RSO << "," << VF;
9084   }
9085   RSO << "},UF>=1";
9086   RSO.flush();
9087   Plan->setName(PlanName);
9088 
9089   return Plan;
9090 }
9091 
9092 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9093   // Outer loop handling: They may require CFG and instruction level
9094   // transformations before even evaluating whether vectorization is profitable.
9095   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9096   // the vectorization pipeline.
9097   assert(!OrigLoop->isInnermost());
9098   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9099 
9100   // Create new empty VPlan
9101   auto Plan = std::make_unique<VPlan>();
9102 
9103   // Build hierarchical CFG
9104   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9105   HCFGBuilder.buildHierarchicalCFG();
9106 
9107   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9108        VF *= 2)
9109     Plan->addVF(VF);
9110 
9111   if (EnableVPlanPredication) {
9112     VPlanPredicator VPP(*Plan);
9113     VPP.predicate();
9114 
9115     // Avoid running transformation to recipes until masked code generation in
9116     // VPlan-native path is in place.
9117     return Plan;
9118   }
9119 
9120   SmallPtrSet<Instruction *, 1> DeadInstructions;
9121   VPlanTransforms::VPInstructionsToVPRecipes(OrigLoop, Plan,
9122                                              Legal->getInductionVars(),
9123                                              DeadInstructions, *PSE.getSE());
9124   return Plan;
9125 }
9126 
9127 // Adjust the recipes for any inloop reductions. The chain of instructions
9128 // leading from the loop exit instr to the phi need to be converted to
9129 // reductions, with one operand being vector and the other being the scalar
9130 // reduction chain.
9131 void LoopVectorizationPlanner::adjustRecipesForInLoopReductions(
9132     VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder) {
9133   for (auto &Reduction : CM.getInLoopReductionChains()) {
9134     PHINode *Phi = Reduction.first;
9135     RecurrenceDescriptor &RdxDesc = Legal->getReductionVars()[Phi];
9136     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9137 
9138     // ReductionOperations are orders top-down from the phi's use to the
9139     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9140     // which of the two operands will remain scalar and which will be reduced.
9141     // For minmax the chain will be the select instructions.
9142     Instruction *Chain = Phi;
9143     for (Instruction *R : ReductionOperations) {
9144       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9145       RecurKind Kind = RdxDesc.getRecurrenceKind();
9146 
9147       VPValue *ChainOp = Plan->getVPValue(Chain);
9148       unsigned FirstOpId;
9149       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9150         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9151                "Expected to replace a VPWidenSelectSC");
9152         FirstOpId = 1;
9153       } else {
9154         assert(isa<VPWidenRecipe>(WidenRecipe) &&
9155                "Expected to replace a VPWidenSC");
9156         FirstOpId = 0;
9157       }
9158       unsigned VecOpId =
9159           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9160       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9161 
9162       auto *CondOp = CM.foldTailByMasking()
9163                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9164                          : nullptr;
9165       VPReductionRecipe *RedRecipe = new VPReductionRecipe(
9166           &RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9167       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9168       Plan->removeVPValueFor(R);
9169       Plan->addVPValue(R, RedRecipe);
9170       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9171       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9172       WidenRecipe->eraseFromParent();
9173 
9174       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9175         VPRecipeBase *CompareRecipe =
9176             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9177         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9178                "Expected to replace a VPWidenSC");
9179         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9180                "Expected no remaining users");
9181         CompareRecipe->eraseFromParent();
9182       }
9183       Chain = R;
9184     }
9185   }
9186 }
9187 
9188 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9189 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9190                                VPSlotTracker &SlotTracker) const {
9191   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9192   IG->getInsertPos()->printAsOperand(O, false);
9193   O << ", ";
9194   getAddr()->printAsOperand(O, SlotTracker);
9195   VPValue *Mask = getMask();
9196   if (Mask) {
9197     O << ", ";
9198     Mask->printAsOperand(O, SlotTracker);
9199   }
9200   for (unsigned i = 0; i < IG->getFactor(); ++i)
9201     if (Instruction *I = IG->getMember(i))
9202       O << "\n" << Indent << "  " << VPlanIngredient(I) << " " << i;
9203 }
9204 #endif
9205 
9206 void VPWidenCallRecipe::execute(VPTransformState &State) {
9207   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9208                                   *this, State);
9209 }
9210 
9211 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9212   State.ILV->widenSelectInstruction(*cast<SelectInst>(getUnderlyingInstr()),
9213                                     this, *this, InvariantCond, State);
9214 }
9215 
9216 void VPWidenRecipe::execute(VPTransformState &State) {
9217   State.ILV->widenInstruction(*getUnderlyingInstr(), this, *this, State);
9218 }
9219 
9220 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9221   State.ILV->widenGEP(cast<GetElementPtrInst>(getUnderlyingInstr()), this,
9222                       *this, State.UF, State.VF, IsPtrLoopInvariant,
9223                       IsIndexLoopInvariant, State);
9224 }
9225 
9226 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9227   assert(!State.Instance && "Int or FP induction being replicated.");
9228   State.ILV->widenIntOrFpInduction(IV, getStartValue()->getLiveInIRValue(),
9229                                    getTruncInst(), getVPValue(0),
9230                                    getCastValue(), State);
9231 }
9232 
9233 void VPWidenPHIRecipe::execute(VPTransformState &State) {
9234   State.ILV->widenPHIInstruction(cast<PHINode>(getUnderlyingValue()), RdxDesc,
9235                                  this, State);
9236 }
9237 
9238 void VPBlendRecipe::execute(VPTransformState &State) {
9239   State.ILV->setDebugLocFromInst(State.Builder, Phi);
9240   // We know that all PHIs in non-header blocks are converted into
9241   // selects, so we don't have to worry about the insertion order and we
9242   // can just use the builder.
9243   // At this point we generate the predication tree. There may be
9244   // duplications since this is a simple recursive scan, but future
9245   // optimizations will clean it up.
9246 
9247   unsigned NumIncoming = getNumIncomingValues();
9248 
9249   // Generate a sequence of selects of the form:
9250   // SELECT(Mask3, In3,
9251   //        SELECT(Mask2, In2,
9252   //               SELECT(Mask1, In1,
9253   //                      In0)))
9254   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9255   // are essentially undef are taken from In0.
9256   InnerLoopVectorizer::VectorParts Entry(State.UF);
9257   for (unsigned In = 0; In < NumIncoming; ++In) {
9258     for (unsigned Part = 0; Part < State.UF; ++Part) {
9259       // We might have single edge PHIs (blocks) - use an identity
9260       // 'select' for the first PHI operand.
9261       Value *In0 = State.get(getIncomingValue(In), Part);
9262       if (In == 0)
9263         Entry[Part] = In0; // Initialize with the first incoming value.
9264       else {
9265         // Select between the current value and the previous incoming edge
9266         // based on the incoming mask.
9267         Value *Cond = State.get(getMask(In), Part);
9268         Entry[Part] =
9269             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9270       }
9271     }
9272   }
9273   for (unsigned Part = 0; Part < State.UF; ++Part)
9274     State.set(this, Entry[Part], Part);
9275 }
9276 
9277 void VPInterleaveRecipe::execute(VPTransformState &State) {
9278   assert(!State.Instance && "Interleave group being replicated.");
9279   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9280                                       getStoredValues(), getMask());
9281 }
9282 
9283 void VPReductionRecipe::execute(VPTransformState &State) {
9284   assert(!State.Instance && "Reduction being replicated.");
9285   Value *PrevInChain = State.get(getChainOp(), 0);
9286   for (unsigned Part = 0; Part < State.UF; ++Part) {
9287     RecurKind Kind = RdxDesc->getRecurrenceKind();
9288     bool IsOrdered = useOrderedReductions(*RdxDesc);
9289     Value *NewVecOp = State.get(getVecOp(), Part);
9290     if (VPValue *Cond = getCondOp()) {
9291       Value *NewCond = State.get(Cond, Part);
9292       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9293       Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
9294           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9295       Constant *IdenVec =
9296           ConstantVector::getSplat(VecTy->getElementCount(), Iden);
9297       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9298       NewVecOp = Select;
9299     }
9300     Value *NewRed;
9301     Value *NextInChain;
9302     if (IsOrdered) {
9303       NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9304                                       PrevInChain);
9305       PrevInChain = NewRed;
9306     } else {
9307       PrevInChain = State.get(getChainOp(), Part);
9308       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9309     }
9310     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9311       NextInChain =
9312           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9313                          NewRed, PrevInChain);
9314     } else if (IsOrdered)
9315       NextInChain = NewRed;
9316     else {
9317       NextInChain = State.Builder.CreateBinOp(
9318           (Instruction::BinaryOps)getUnderlyingInstr()->getOpcode(), NewRed,
9319           PrevInChain);
9320     }
9321     State.set(this, NextInChain, Part);
9322   }
9323 }
9324 
9325 void VPReplicateRecipe::execute(VPTransformState &State) {
9326   if (State.Instance) { // Generate a single instance.
9327     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9328     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9329                                     *State.Instance, IsPredicated, State);
9330     // Insert scalar instance packing it into a vector.
9331     if (AlsoPack && State.VF.isVector()) {
9332       // If we're constructing lane 0, initialize to start from poison.
9333       if (State.Instance->Lane.isFirstLane()) {
9334         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9335         Value *Poison = PoisonValue::get(
9336             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9337         State.set(this, Poison, State.Instance->Part);
9338       }
9339       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9340     }
9341     return;
9342   }
9343 
9344   // Generate scalar instances for all VF lanes of all UF parts, unless the
9345   // instruction is uniform inwhich case generate only the first lane for each
9346   // of the UF parts.
9347   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9348   assert((!State.VF.isScalable() || IsUniform) &&
9349          "Can't scalarize a scalable vector");
9350   for (unsigned Part = 0; Part < State.UF; ++Part)
9351     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9352       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *this,
9353                                       VPIteration(Part, Lane), IsPredicated,
9354                                       State);
9355 }
9356 
9357 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9358   assert(State.Instance && "Branch on Mask works only on single instance.");
9359 
9360   unsigned Part = State.Instance->Part;
9361   unsigned Lane = State.Instance->Lane.getKnownLane();
9362 
9363   Value *ConditionBit = nullptr;
9364   VPValue *BlockInMask = getMask();
9365   if (BlockInMask) {
9366     ConditionBit = State.get(BlockInMask, Part);
9367     if (ConditionBit->getType()->isVectorTy())
9368       ConditionBit = State.Builder.CreateExtractElement(
9369           ConditionBit, State.Builder.getInt32(Lane));
9370   } else // Block in mask is all-one.
9371     ConditionBit = State.Builder.getTrue();
9372 
9373   // Replace the temporary unreachable terminator with a new conditional branch,
9374   // whose two destinations will be set later when they are created.
9375   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9376   assert(isa<UnreachableInst>(CurrentTerminator) &&
9377          "Expected to replace unreachable terminator with conditional branch.");
9378   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9379   CondBr->setSuccessor(0, nullptr);
9380   ReplaceInstWithInst(CurrentTerminator, CondBr);
9381 }
9382 
9383 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9384   assert(State.Instance && "Predicated instruction PHI works per instance.");
9385   Instruction *ScalarPredInst =
9386       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9387   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9388   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9389   assert(PredicatingBB && "Predicated block has no single predecessor.");
9390   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9391          "operand must be VPReplicateRecipe");
9392 
9393   // By current pack/unpack logic we need to generate only a single phi node: if
9394   // a vector value for the predicated instruction exists at this point it means
9395   // the instruction has vector users only, and a phi for the vector value is
9396   // needed. In this case the recipe of the predicated instruction is marked to
9397   // also do that packing, thereby "hoisting" the insert-element sequence.
9398   // Otherwise, a phi node for the scalar value is needed.
9399   unsigned Part = State.Instance->Part;
9400   if (State.hasVectorValue(getOperand(0), Part)) {
9401     Value *VectorValue = State.get(getOperand(0), Part);
9402     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9403     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9404     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9405     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9406     if (State.hasVectorValue(this, Part))
9407       State.reset(this, VPhi, Part);
9408     else
9409       State.set(this, VPhi, Part);
9410     // NOTE: Currently we need to update the value of the operand, so the next
9411     // predicated iteration inserts its generated value in the correct vector.
9412     State.reset(getOperand(0), VPhi, Part);
9413   } else {
9414     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9415     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9416     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9417                      PredicatingBB);
9418     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9419     if (State.hasScalarValue(this, *State.Instance))
9420       State.reset(this, Phi, *State.Instance);
9421     else
9422       State.set(this, Phi, *State.Instance);
9423     // NOTE: Currently we need to update the value of the operand, so the next
9424     // predicated iteration inserts its generated value in the correct vector.
9425     State.reset(getOperand(0), Phi, *State.Instance);
9426   }
9427 }
9428 
9429 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9430   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9431   State.ILV->vectorizeMemoryInstruction(
9432       &Ingredient, State, StoredValue ? nullptr : getVPSingleValue(), getAddr(),
9433       StoredValue, getMask());
9434 }
9435 
9436 // Determine how to lower the scalar epilogue, which depends on 1) optimising
9437 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
9438 // predication, and 4) a TTI hook that analyses whether the loop is suitable
9439 // for predication.
9440 static ScalarEpilogueLowering getScalarEpilogueLowering(
9441     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
9442     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
9443     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
9444     LoopVectorizationLegality &LVL) {
9445   // 1) OptSize takes precedence over all other options, i.e. if this is set,
9446   // don't look at hints or options, and don't request a scalar epilogue.
9447   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
9448   // LoopAccessInfo (due to code dependency and not being able to reliably get
9449   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
9450   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
9451   // versioning when the vectorization is forced, unlike hasOptSize. So revert
9452   // back to the old way and vectorize with versioning when forced. See D81345.)
9453   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
9454                                                       PGSOQueryType::IRPass) &&
9455                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
9456     return CM_ScalarEpilogueNotAllowedOptSize;
9457 
9458   // 2) If set, obey the directives
9459   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
9460     switch (PreferPredicateOverEpilogue) {
9461     case PreferPredicateTy::ScalarEpilogue:
9462       return CM_ScalarEpilogueAllowed;
9463     case PreferPredicateTy::PredicateElseScalarEpilogue:
9464       return CM_ScalarEpilogueNotNeededUsePredicate;
9465     case PreferPredicateTy::PredicateOrDontVectorize:
9466       return CM_ScalarEpilogueNotAllowedUsePredicate;
9467     };
9468   }
9469 
9470   // 3) If set, obey the hints
9471   switch (Hints.getPredicate()) {
9472   case LoopVectorizeHints::FK_Enabled:
9473     return CM_ScalarEpilogueNotNeededUsePredicate;
9474   case LoopVectorizeHints::FK_Disabled:
9475     return CM_ScalarEpilogueAllowed;
9476   };
9477 
9478   // 4) if the TTI hook indicates this is profitable, request predication.
9479   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
9480                                        LVL.getLAI()))
9481     return CM_ScalarEpilogueNotNeededUsePredicate;
9482 
9483   return CM_ScalarEpilogueAllowed;
9484 }
9485 
9486 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
9487   // If Values have been set for this Def return the one relevant for \p Part.
9488   if (hasVectorValue(Def, Part))
9489     return Data.PerPartOutput[Def][Part];
9490 
9491   if (!hasScalarValue(Def, {Part, 0})) {
9492     Value *IRV = Def->getLiveInIRValue();
9493     Value *B = ILV->getBroadcastInstrs(IRV);
9494     set(Def, B, Part);
9495     return B;
9496   }
9497 
9498   Value *ScalarValue = get(Def, {Part, 0});
9499   // If we aren't vectorizing, we can just copy the scalar map values over
9500   // to the vector map.
9501   if (VF.isScalar()) {
9502     set(Def, ScalarValue, Part);
9503     return ScalarValue;
9504   }
9505 
9506   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
9507   bool IsUniform = RepR && RepR->isUniform();
9508 
9509   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
9510   // Check if there is a scalar value for the selected lane.
9511   if (!hasScalarValue(Def, {Part, LastLane})) {
9512     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
9513     assert(isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) &&
9514            "unexpected recipe found to be invariant");
9515     IsUniform = true;
9516     LastLane = 0;
9517   }
9518 
9519   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
9520 
9521   // Set the insert point after the last scalarized instruction. This
9522   // ensures the insertelement sequence will directly follow the scalar
9523   // definitions.
9524   auto OldIP = Builder.saveIP();
9525   auto NewIP = std::next(BasicBlock::iterator(LastInst));
9526   Builder.SetInsertPoint(&*NewIP);
9527 
9528   // However, if we are vectorizing, we need to construct the vector values.
9529   // If the value is known to be uniform after vectorization, we can just
9530   // broadcast the scalar value corresponding to lane zero for each unroll
9531   // iteration. Otherwise, we construct the vector values using
9532   // insertelement instructions. Since the resulting vectors are stored in
9533   // State, we will only generate the insertelements once.
9534   Value *VectorValue = nullptr;
9535   if (IsUniform) {
9536     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
9537     set(Def, VectorValue, Part);
9538   } else {
9539     // Initialize packing with insertelements to start from undef.
9540     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
9541     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
9542     set(Def, Undef, Part);
9543     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
9544       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
9545     VectorValue = get(Def, Part);
9546   }
9547   Builder.restoreIP(OldIP);
9548   return VectorValue;
9549 }
9550 
9551 // Process the loop in the VPlan-native vectorization path. This path builds
9552 // VPlan upfront in the vectorization pipeline, which allows to apply
9553 // VPlan-to-VPlan transformations from the very beginning without modifying the
9554 // input LLVM IR.
9555 static bool processLoopInVPlanNativePath(
9556     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
9557     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
9558     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
9559     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
9560     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
9561     LoopVectorizationRequirements &Requirements) {
9562 
9563   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
9564     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
9565     return false;
9566   }
9567   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
9568   Function *F = L->getHeader()->getParent();
9569   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
9570 
9571   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9572       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
9573 
9574   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
9575                                 &Hints, IAI);
9576   // Use the planner for outer loop vectorization.
9577   // TODO: CM is not used at this point inside the planner. Turn CM into an
9578   // optional argument if we don't need it in the future.
9579   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
9580                                Requirements, ORE);
9581 
9582   // Get user vectorization factor.
9583   ElementCount UserVF = Hints.getWidth();
9584 
9585   // Plan how to best vectorize, return the best VF and its cost.
9586   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
9587 
9588   // If we are stress testing VPlan builds, do not attempt to generate vector
9589   // code. Masked vector code generation support will follow soon.
9590   // Also, do not attempt to vectorize if no vector code will be produced.
9591   if (VPlanBuildStressTest || EnableVPlanPredication ||
9592       VectorizationFactor::Disabled() == VF)
9593     return false;
9594 
9595   LVP.setBestPlan(VF.Width, 1);
9596 
9597   {
9598     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
9599                              F->getParent()->getDataLayout());
9600     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
9601                            &CM, BFI, PSI, Checks);
9602     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
9603                       << L->getHeader()->getParent()->getName() << "\"\n");
9604     LVP.executePlan(LB, DT);
9605   }
9606 
9607   // Mark the loop as already vectorized to avoid vectorizing again.
9608   Hints.setAlreadyVectorized();
9609   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
9610   return true;
9611 }
9612 
9613 // Emit a remark if there are stores to floats that required a floating point
9614 // extension. If the vectorized loop was generated with floating point there
9615 // will be a performance penalty from the conversion overhead and the change in
9616 // the vector width.
9617 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
9618   SmallVector<Instruction *, 4> Worklist;
9619   for (BasicBlock *BB : L->getBlocks()) {
9620     for (Instruction &Inst : *BB) {
9621       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
9622         if (S->getValueOperand()->getType()->isFloatTy())
9623           Worklist.push_back(S);
9624       }
9625     }
9626   }
9627 
9628   // Traverse the floating point stores upwards searching, for floating point
9629   // conversions.
9630   SmallPtrSet<const Instruction *, 4> Visited;
9631   SmallPtrSet<const Instruction *, 4> EmittedRemark;
9632   while (!Worklist.empty()) {
9633     auto *I = Worklist.pop_back_val();
9634     if (!L->contains(I))
9635       continue;
9636     if (!Visited.insert(I).second)
9637       continue;
9638 
9639     // Emit a remark if the floating point store required a floating
9640     // point conversion.
9641     // TODO: More work could be done to identify the root cause such as a
9642     // constant or a function return type and point the user to it.
9643     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
9644       ORE->emit([&]() {
9645         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
9646                                           I->getDebugLoc(), L->getHeader())
9647                << "floating point conversion changes vector width. "
9648                << "Mixed floating point precision requires an up/down "
9649                << "cast that will negatively impact performance.";
9650       });
9651 
9652     for (Use &Op : I->operands())
9653       if (auto *OpI = dyn_cast<Instruction>(Op))
9654         Worklist.push_back(OpI);
9655   }
9656 }
9657 
9658 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
9659     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
9660                                !EnableLoopInterleaving),
9661       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
9662                               !EnableLoopVectorization) {}
9663 
9664 bool LoopVectorizePass::processLoop(Loop *L) {
9665   assert((EnableVPlanNativePath || L->isInnermost()) &&
9666          "VPlan-native path is not enabled. Only process inner loops.");
9667 
9668 #ifndef NDEBUG
9669   const std::string DebugLocStr = getDebugLocString(L);
9670 #endif /* NDEBUG */
9671 
9672   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
9673                     << L->getHeader()->getParent()->getName() << "\" from "
9674                     << DebugLocStr << "\n");
9675 
9676   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
9677 
9678   LLVM_DEBUG(
9679       dbgs() << "LV: Loop hints:"
9680              << " force="
9681              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
9682                      ? "disabled"
9683                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
9684                             ? "enabled"
9685                             : "?"))
9686              << " width=" << Hints.getWidth()
9687              << " interleave=" << Hints.getInterleave() << "\n");
9688 
9689   // Function containing loop
9690   Function *F = L->getHeader()->getParent();
9691 
9692   // Looking at the diagnostic output is the only way to determine if a loop
9693   // was vectorized (other than looking at the IR or machine code), so it
9694   // is important to generate an optimization remark for each loop. Most of
9695   // these messages are generated as OptimizationRemarkAnalysis. Remarks
9696   // generated as OptimizationRemark and OptimizationRemarkMissed are
9697   // less verbose reporting vectorized loops and unvectorized loops that may
9698   // benefit from vectorization, respectively.
9699 
9700   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
9701     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
9702     return false;
9703   }
9704 
9705   PredicatedScalarEvolution PSE(*SE, *L);
9706 
9707   // Check if it is legal to vectorize the loop.
9708   LoopVectorizationRequirements Requirements;
9709   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
9710                                 &Requirements, &Hints, DB, AC, BFI, PSI);
9711   if (!LVL.canVectorize(EnableVPlanNativePath)) {
9712     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
9713     Hints.emitRemarkWithHints();
9714     return false;
9715   }
9716 
9717   // Check the function attributes and profiles to find out if this function
9718   // should be optimized for size.
9719   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
9720       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
9721 
9722   // Entrance to the VPlan-native vectorization path. Outer loops are processed
9723   // here. They may require CFG and instruction level transformations before
9724   // even evaluating whether vectorization is profitable. Since we cannot modify
9725   // the incoming IR, we need to build VPlan upfront in the vectorization
9726   // pipeline.
9727   if (!L->isInnermost())
9728     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
9729                                         ORE, BFI, PSI, Hints, Requirements);
9730 
9731   assert(L->isInnermost() && "Inner loop expected.");
9732 
9733   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
9734   // count by optimizing for size, to minimize overheads.
9735   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
9736   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
9737     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
9738                       << "This loop is worth vectorizing only if no scalar "
9739                       << "iteration overheads are incurred.");
9740     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
9741       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
9742     else {
9743       LLVM_DEBUG(dbgs() << "\n");
9744       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
9745     }
9746   }
9747 
9748   // Check the function attributes to see if implicit floats are allowed.
9749   // FIXME: This check doesn't seem possibly correct -- what if the loop is
9750   // an integer loop and the vector instructions selected are purely integer
9751   // vector instructions?
9752   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
9753     reportVectorizationFailure(
9754         "Can't vectorize when the NoImplicitFloat attribute is used",
9755         "loop not vectorized due to NoImplicitFloat attribute",
9756         "NoImplicitFloat", ORE, L);
9757     Hints.emitRemarkWithHints();
9758     return false;
9759   }
9760 
9761   // Check if the target supports potentially unsafe FP vectorization.
9762   // FIXME: Add a check for the type of safety issue (denormal, signaling)
9763   // for the target we're vectorizing for, to make sure none of the
9764   // additional fp-math flags can help.
9765   if (Hints.isPotentiallyUnsafe() &&
9766       TTI->isFPVectorizationPotentiallyUnsafe()) {
9767     reportVectorizationFailure(
9768         "Potentially unsafe FP op prevents vectorization",
9769         "loop not vectorized due to unsafe FP support.",
9770         "UnsafeFP", ORE, L);
9771     Hints.emitRemarkWithHints();
9772     return false;
9773   }
9774 
9775   if (!Requirements.canVectorizeFPMath(Hints)) {
9776     ORE->emit([&]() {
9777       auto *ExactFPMathInst = Requirements.getExactFPInst();
9778       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
9779                                                  ExactFPMathInst->getDebugLoc(),
9780                                                  ExactFPMathInst->getParent())
9781              << "loop not vectorized: cannot prove it is safe to reorder "
9782                 "floating-point operations";
9783     });
9784     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
9785                          "reorder floating-point operations\n");
9786     Hints.emitRemarkWithHints();
9787     return false;
9788   }
9789 
9790   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
9791   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
9792 
9793   // If an override option has been passed in for interleaved accesses, use it.
9794   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
9795     UseInterleaved = EnableInterleavedMemAccesses;
9796 
9797   // Analyze interleaved memory accesses.
9798   if (UseInterleaved) {
9799     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
9800   }
9801 
9802   // Use the cost model.
9803   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
9804                                 F, &Hints, IAI);
9805   CM.collectValuesToIgnore();
9806 
9807   // Use the planner for vectorization.
9808   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
9809                                Requirements, ORE);
9810 
9811   // Get user vectorization factor and interleave count.
9812   ElementCount UserVF = Hints.getWidth();
9813   unsigned UserIC = Hints.getInterleave();
9814 
9815   // Plan how to best vectorize, return the best VF and its cost.
9816   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
9817 
9818   VectorizationFactor VF = VectorizationFactor::Disabled();
9819   unsigned IC = 1;
9820 
9821   if (MaybeVF) {
9822     VF = *MaybeVF;
9823     // Select the interleave count.
9824     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
9825   }
9826 
9827   // Identify the diagnostic messages that should be produced.
9828   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
9829   bool VectorizeLoop = true, InterleaveLoop = true;
9830   if (VF.Width.isScalar()) {
9831     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
9832     VecDiagMsg = std::make_pair(
9833         "VectorizationNotBeneficial",
9834         "the cost-model indicates that vectorization is not beneficial");
9835     VectorizeLoop = false;
9836   }
9837 
9838   if (!MaybeVF && UserIC > 1) {
9839     // Tell the user interleaving was avoided up-front, despite being explicitly
9840     // requested.
9841     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
9842                          "interleaving should be avoided up front\n");
9843     IntDiagMsg = std::make_pair(
9844         "InterleavingAvoided",
9845         "Ignoring UserIC, because interleaving was avoided up front");
9846     InterleaveLoop = false;
9847   } else if (IC == 1 && UserIC <= 1) {
9848     // Tell the user interleaving is not beneficial.
9849     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
9850     IntDiagMsg = std::make_pair(
9851         "InterleavingNotBeneficial",
9852         "the cost-model indicates that interleaving is not beneficial");
9853     InterleaveLoop = false;
9854     if (UserIC == 1) {
9855       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
9856       IntDiagMsg.second +=
9857           " and is explicitly disabled or interleave count is set to 1";
9858     }
9859   } else if (IC > 1 && UserIC == 1) {
9860     // Tell the user interleaving is beneficial, but it explicitly disabled.
9861     LLVM_DEBUG(
9862         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
9863     IntDiagMsg = std::make_pair(
9864         "InterleavingBeneficialButDisabled",
9865         "the cost-model indicates that interleaving is beneficial "
9866         "but is explicitly disabled or interleave count is set to 1");
9867     InterleaveLoop = false;
9868   }
9869 
9870   // Override IC if user provided an interleave count.
9871   IC = UserIC > 0 ? UserIC : IC;
9872 
9873   // Emit diagnostic messages, if any.
9874   const char *VAPassName = Hints.vectorizeAnalysisPassName();
9875   if (!VectorizeLoop && !InterleaveLoop) {
9876     // Do not vectorize or interleaving the loop.
9877     ORE->emit([&]() {
9878       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
9879                                       L->getStartLoc(), L->getHeader())
9880              << VecDiagMsg.second;
9881     });
9882     ORE->emit([&]() {
9883       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
9884                                       L->getStartLoc(), L->getHeader())
9885              << IntDiagMsg.second;
9886     });
9887     return false;
9888   } else if (!VectorizeLoop && InterleaveLoop) {
9889     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
9890     ORE->emit([&]() {
9891       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
9892                                         L->getStartLoc(), L->getHeader())
9893              << VecDiagMsg.second;
9894     });
9895   } else if (VectorizeLoop && !InterleaveLoop) {
9896     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
9897                       << ") in " << DebugLocStr << '\n');
9898     ORE->emit([&]() {
9899       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
9900                                         L->getStartLoc(), L->getHeader())
9901              << IntDiagMsg.second;
9902     });
9903   } else if (VectorizeLoop && InterleaveLoop) {
9904     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
9905                       << ") in " << DebugLocStr << '\n');
9906     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
9907   }
9908 
9909   bool DisableRuntimeUnroll = false;
9910   MDNode *OrigLoopID = L->getLoopID();
9911   {
9912     // Optimistically generate runtime checks. Drop them if they turn out to not
9913     // be profitable. Limit the scope of Checks, so the cleanup happens
9914     // immediately after vector codegeneration is done.
9915     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
9916                              F->getParent()->getDataLayout());
9917     if (!VF.Width.isScalar() || IC > 1)
9918       Checks.Create(L, *LVL.getLAI(), PSE.getUnionPredicate());
9919     LVP.setBestPlan(VF.Width, IC);
9920 
9921     using namespace ore;
9922     if (!VectorizeLoop) {
9923       assert(IC > 1 && "interleave count should not be 1 or 0");
9924       // If we decided that it is not legal to vectorize the loop, then
9925       // interleave it.
9926       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
9927                                  &CM, BFI, PSI, Checks);
9928       LVP.executePlan(Unroller, DT);
9929 
9930       ORE->emit([&]() {
9931         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
9932                                   L->getHeader())
9933                << "interleaved loop (interleaved count: "
9934                << NV("InterleaveCount", IC) << ")";
9935       });
9936     } else {
9937       // If we decided that it is *legal* to vectorize the loop, then do it.
9938 
9939       // Consider vectorizing the epilogue too if it's profitable.
9940       VectorizationFactor EpilogueVF =
9941           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
9942       if (EpilogueVF.Width.isVector()) {
9943 
9944         // The first pass vectorizes the main loop and creates a scalar epilogue
9945         // to be vectorized by executing the plan (potentially with a different
9946         // factor) again shortly afterwards.
9947         EpilogueLoopVectorizationInfo EPI(VF.Width.getKnownMinValue(), IC,
9948                                           EpilogueVF.Width.getKnownMinValue(),
9949                                           1);
9950         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
9951                                            EPI, &LVL, &CM, BFI, PSI, Checks);
9952 
9953         LVP.setBestPlan(EPI.MainLoopVF, EPI.MainLoopUF);
9954         LVP.executePlan(MainILV, DT);
9955         ++LoopsVectorized;
9956 
9957         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
9958         formLCSSARecursively(*L, *DT, LI, SE);
9959 
9960         // Second pass vectorizes the epilogue and adjusts the control flow
9961         // edges from the first pass.
9962         LVP.setBestPlan(EPI.EpilogueVF, EPI.EpilogueUF);
9963         EPI.MainLoopVF = EPI.EpilogueVF;
9964         EPI.MainLoopUF = EPI.EpilogueUF;
9965         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
9966                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
9967                                                  Checks);
9968         LVP.executePlan(EpilogILV, DT);
9969         ++LoopsEpilogueVectorized;
9970 
9971         if (!MainILV.areSafetyChecksAdded())
9972           DisableRuntimeUnroll = true;
9973       } else {
9974         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
9975                                &LVL, &CM, BFI, PSI, Checks);
9976         LVP.executePlan(LB, DT);
9977         ++LoopsVectorized;
9978 
9979         // Add metadata to disable runtime unrolling a scalar loop when there
9980         // are no runtime checks about strides and memory. A scalar loop that is
9981         // rarely used is not worth unrolling.
9982         if (!LB.areSafetyChecksAdded())
9983           DisableRuntimeUnroll = true;
9984       }
9985       // Report the vectorization decision.
9986       ORE->emit([&]() {
9987         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
9988                                   L->getHeader())
9989                << "vectorized loop (vectorization width: "
9990                << NV("VectorizationFactor", VF.Width)
9991                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
9992       });
9993     }
9994 
9995     if (ORE->allowExtraAnalysis(LV_NAME))
9996       checkMixedPrecision(L, ORE);
9997   }
9998 
9999   Optional<MDNode *> RemainderLoopID =
10000       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10001                                       LLVMLoopVectorizeFollowupEpilogue});
10002   if (RemainderLoopID.hasValue()) {
10003     L->setLoopID(RemainderLoopID.getValue());
10004   } else {
10005     if (DisableRuntimeUnroll)
10006       AddRuntimeUnrollDisableMetaData(L);
10007 
10008     // Mark the loop as already vectorized to avoid vectorizing again.
10009     Hints.setAlreadyVectorized();
10010   }
10011 
10012   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10013   return true;
10014 }
10015 
10016 LoopVectorizeResult LoopVectorizePass::runImpl(
10017     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10018     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10019     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10020     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10021     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10022   SE = &SE_;
10023   LI = &LI_;
10024   TTI = &TTI_;
10025   DT = &DT_;
10026   BFI = &BFI_;
10027   TLI = TLI_;
10028   AA = &AA_;
10029   AC = &AC_;
10030   GetLAA = &GetLAA_;
10031   DB = &DB_;
10032   ORE = &ORE_;
10033   PSI = PSI_;
10034 
10035   // Don't attempt if
10036   // 1. the target claims to have no vector registers, and
10037   // 2. interleaving won't help ILP.
10038   //
10039   // The second condition is necessary because, even if the target has no
10040   // vector registers, loop vectorization may still enable scalar
10041   // interleaving.
10042   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10043       TTI->getMaxInterleaveFactor(1) < 2)
10044     return LoopVectorizeResult(false, false);
10045 
10046   bool Changed = false, CFGChanged = false;
10047 
10048   // The vectorizer requires loops to be in simplified form.
10049   // Since simplification may add new inner loops, it has to run before the
10050   // legality and profitability checks. This means running the loop vectorizer
10051   // will simplify all loops, regardless of whether anything end up being
10052   // vectorized.
10053   for (auto &L : *LI)
10054     Changed |= CFGChanged |=
10055         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10056 
10057   // Build up a worklist of inner-loops to vectorize. This is necessary as
10058   // the act of vectorizing or partially unrolling a loop creates new loops
10059   // and can invalidate iterators across the loops.
10060   SmallVector<Loop *, 8> Worklist;
10061 
10062   for (Loop *L : *LI)
10063     collectSupportedLoops(*L, LI, ORE, Worklist);
10064 
10065   LoopsAnalyzed += Worklist.size();
10066 
10067   // Now walk the identified inner loops.
10068   while (!Worklist.empty()) {
10069     Loop *L = Worklist.pop_back_val();
10070 
10071     // For the inner loops we actually process, form LCSSA to simplify the
10072     // transform.
10073     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10074 
10075     Changed |= CFGChanged |= processLoop(L);
10076   }
10077 
10078   // Process each loop nest in the function.
10079   return LoopVectorizeResult(Changed, CFGChanged);
10080 }
10081 
10082 PreservedAnalyses LoopVectorizePass::run(Function &F,
10083                                          FunctionAnalysisManager &AM) {
10084     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10085     auto &LI = AM.getResult<LoopAnalysis>(F);
10086     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10087     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10088     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10089     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10090     auto &AA = AM.getResult<AAManager>(F);
10091     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10092     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10093     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10094     MemorySSA *MSSA = EnableMSSALoopDependency
10095                           ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
10096                           : nullptr;
10097 
10098     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10099     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10100         [&](Loop &L) -> const LoopAccessInfo & {
10101       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,  SE,
10102                                         TLI, TTI, nullptr, MSSA};
10103       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10104     };
10105     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10106     ProfileSummaryInfo *PSI =
10107         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10108     LoopVectorizeResult Result =
10109         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10110     if (!Result.MadeAnyChange)
10111       return PreservedAnalyses::all();
10112     PreservedAnalyses PA;
10113 
10114     // We currently do not preserve loopinfo/dominator analyses with outer loop
10115     // vectorization. Until this is addressed, mark these analyses as preserved
10116     // only for non-VPlan-native path.
10117     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10118     if (!EnableVPlanNativePath) {
10119       PA.preserve<LoopAnalysis>();
10120       PA.preserve<DominatorTreeAnalysis>();
10121     }
10122     PA.preserve<BasicAA>();
10123     PA.preserve<GlobalsAA>();
10124     if (!Result.MadeCFGChange)
10125       PA.preserveSet<CFGAnalyses>();
10126     return PA;
10127 }
10128