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 "VPlanTransforms.h"
62 #include "llvm/ADT/APInt.h"
63 #include "llvm/ADT/ArrayRef.h"
64 #include "llvm/ADT/DenseMap.h"
65 #include "llvm/ADT/DenseMapInfo.h"
66 #include "llvm/ADT/Hashing.h"
67 #include "llvm/ADT/MapVector.h"
68 #include "llvm/ADT/None.h"
69 #include "llvm/ADT/Optional.h"
70 #include "llvm/ADT/STLExtras.h"
71 #include "llvm/ADT/SmallPtrSet.h"
72 #include "llvm/ADT/SmallSet.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/OptimizationRemarkEmitter.h"
90 #include "llvm/Analysis/ProfileSummaryInfo.h"
91 #include "llvm/Analysis/ScalarEvolution.h"
92 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
93 #include "llvm/Analysis/TargetLibraryInfo.h"
94 #include "llvm/Analysis/TargetTransformInfo.h"
95 #include "llvm/Analysis/VectorUtils.h"
96 #include "llvm/IR/Attributes.h"
97 #include "llvm/IR/BasicBlock.h"
98 #include "llvm/IR/CFG.h"
99 #include "llvm/IR/Constant.h"
100 #include "llvm/IR/Constants.h"
101 #include "llvm/IR/DataLayout.h"
102 #include "llvm/IR/DebugInfoMetadata.h"
103 #include "llvm/IR/DebugLoc.h"
104 #include "llvm/IR/DerivedTypes.h"
105 #include "llvm/IR/DiagnosticInfo.h"
106 #include "llvm/IR/Dominators.h"
107 #include "llvm/IR/Function.h"
108 #include "llvm/IR/IRBuilder.h"
109 #include "llvm/IR/InstrTypes.h"
110 #include "llvm/IR/Instruction.h"
111 #include "llvm/IR/Instructions.h"
112 #include "llvm/IR/IntrinsicInst.h"
113 #include "llvm/IR/Intrinsics.h"
114 #include "llvm/IR/Metadata.h"
115 #include "llvm/IR/Module.h"
116 #include "llvm/IR/Operator.h"
117 #include "llvm/IR/PatternMatch.h"
118 #include "llvm/IR/Type.h"
119 #include "llvm/IR/Use.h"
120 #include "llvm/IR/User.h"
121 #include "llvm/IR/Value.h"
122 #include "llvm/IR/ValueHandle.h"
123 #include "llvm/IR/Verifier.h"
124 #include "llvm/InitializePasses.h"
125 #include "llvm/Pass.h"
126 #include "llvm/Support/Casting.h"
127 #include "llvm/Support/CommandLine.h"
128 #include "llvm/Support/Compiler.h"
129 #include "llvm/Support/Debug.h"
130 #include "llvm/Support/ErrorHandling.h"
131 #include "llvm/Support/InstructionCost.h"
132 #include "llvm/Support/MathExtras.h"
133 #include "llvm/Support/raw_ostream.h"
134 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
135 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
136 #include "llvm/Transforms/Utils/LoopSimplify.h"
137 #include "llvm/Transforms/Utils/LoopUtils.h"
138 #include "llvm/Transforms/Utils/LoopVersioning.h"
139 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
140 #include "llvm/Transforms/Utils/SizeOpts.h"
141 #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
142 #include <algorithm>
143 #include <cassert>
144 #include <cstdint>
145 #include <functional>
146 #include <iterator>
147 #include <limits>
148 #include <map>
149 #include <memory>
150 #include <string>
151 #include <tuple>
152 #include <utility>
153 
154 using namespace llvm;
155 
156 #define LV_NAME "loop-vectorize"
157 #define DEBUG_TYPE LV_NAME
158 
159 #ifndef NDEBUG
160 const char VerboseDebug[] = DEBUG_TYPE "-verbose";
161 #endif
162 
163 /// @{
164 /// Metadata attribute names
165 const char LLVMLoopVectorizeFollowupAll[] = "llvm.loop.vectorize.followup_all";
166 const char LLVMLoopVectorizeFollowupVectorized[] =
167     "llvm.loop.vectorize.followup_vectorized";
168 const char LLVMLoopVectorizeFollowupEpilogue[] =
169     "llvm.loop.vectorize.followup_epilogue";
170 /// @}
171 
172 STATISTIC(LoopsVectorized, "Number of loops vectorized");
173 STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
174 STATISTIC(LoopsEpilogueVectorized, "Number of epilogues vectorized");
175 
176 static cl::opt<bool> EnableEpilogueVectorization(
177     "enable-epilogue-vectorization", cl::init(true), cl::Hidden,
178     cl::desc("Enable vectorization of epilogue loops."));
179 
180 static cl::opt<unsigned> EpilogueVectorizationForceVF(
181     "epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
182     cl::desc("When epilogue vectorization is enabled, and a value greater than "
183              "1 is specified, forces the given VF for all applicable epilogue "
184              "loops."));
185 
186 static cl::opt<unsigned> EpilogueVectorizationMinVF(
187     "epilogue-vectorization-minimum-VF", cl::init(16), cl::Hidden,
188     cl::desc("Only loops with vectorization factor equal to or larger than "
189              "the specified value are considered for epilogue vectorization."));
190 
191 /// Loops with a known constant trip count below this number are vectorized only
192 /// if no scalar iteration overheads are incurred.
193 static cl::opt<unsigned> TinyTripCountVectorThreshold(
194     "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
195     cl::desc("Loops with a constant trip count that is smaller than this "
196              "value are vectorized only if no scalar iteration overheads "
197              "are incurred."));
198 
199 static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
200     "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
201     cl::desc("The maximum allowed number of runtime memory checks with a "
202              "vectorize(enable) pragma."));
203 
204 // Option prefer-predicate-over-epilogue indicates that an epilogue is undesired,
205 // that predication is preferred, and this lists all options. I.e., the
206 // vectorizer will try to fold the tail-loop (epilogue) into the vector body
207 // and predicate the instructions accordingly. If tail-folding fails, there are
208 // different fallback strategies depending on these values:
209 namespace PreferPredicateTy {
210   enum Option {
211     ScalarEpilogue = 0,
212     PredicateElseScalarEpilogue,
213     PredicateOrDontVectorize
214   };
215 } // namespace PreferPredicateTy
216 
217 static cl::opt<PreferPredicateTy::Option> PreferPredicateOverEpilogue(
218     "prefer-predicate-over-epilogue",
219     cl::init(PreferPredicateTy::ScalarEpilogue),
220     cl::Hidden,
221     cl::desc("Tail-folding and predication preferences over creating a scalar "
222              "epilogue loop."),
223     cl::values(clEnumValN(PreferPredicateTy::ScalarEpilogue,
224                          "scalar-epilogue",
225                          "Don't tail-predicate loops, create scalar epilogue"),
226               clEnumValN(PreferPredicateTy::PredicateElseScalarEpilogue,
227                          "predicate-else-scalar-epilogue",
228                          "prefer tail-folding, create scalar epilogue if tail "
229                          "folding fails."),
230               clEnumValN(PreferPredicateTy::PredicateOrDontVectorize,
231                          "predicate-dont-vectorize",
232                          "prefers tail-folding, don't attempt vectorization if "
233                          "tail-folding fails.")));
234 
235 static cl::opt<bool> MaximizeBandwidth(
236     "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
237     cl::desc("Maximize bandwidth when selecting vectorization factor which "
238              "will be determined by the smallest type in loop."));
239 
240 static cl::opt<bool> EnableInterleavedMemAccesses(
241     "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
242     cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
243 
244 /// An interleave-group may need masking if it resides in a block that needs
245 /// predication, or in order to mask away gaps.
246 static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
247     "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
248     cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
249 
250 static cl::opt<unsigned> TinyTripCountInterleaveThreshold(
251     "tiny-trip-count-interleave-threshold", cl::init(128), cl::Hidden,
252     cl::desc("We don't interleave loops with a estimated constant trip count "
253              "below this number"));
254 
255 static cl::opt<unsigned> ForceTargetNumScalarRegs(
256     "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
257     cl::desc("A flag that overrides the target's number of scalar registers."));
258 
259 static cl::opt<unsigned> ForceTargetNumVectorRegs(
260     "force-target-num-vector-regs", cl::init(0), cl::Hidden,
261     cl::desc("A flag that overrides the target's number of vector registers."));
262 
263 static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
264     "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
265     cl::desc("A flag that overrides the target's max interleave factor for "
266              "scalar loops."));
267 
268 static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
269     "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
270     cl::desc("A flag that overrides the target's max interleave factor for "
271              "vectorized loops."));
272 
273 static cl::opt<unsigned> ForceTargetInstructionCost(
274     "force-target-instruction-cost", cl::init(0), cl::Hidden,
275     cl::desc("A flag that overrides the target's expected cost for "
276              "an instruction to a single constant value. Mostly "
277              "useful for getting consistent testing."));
278 
279 static cl::opt<bool> ForceTargetSupportsScalableVectors(
280     "force-target-supports-scalable-vectors", cl::init(false), cl::Hidden,
281     cl::desc(
282         "Pretend that scalable vectors are supported, even if the target does "
283         "not support them. This flag should only be used for testing."));
284 
285 static cl::opt<unsigned> SmallLoopCost(
286     "small-loop-cost", cl::init(20), cl::Hidden,
287     cl::desc(
288         "The cost of a loop that is considered 'small' by the interleaver."));
289 
290 static cl::opt<bool> LoopVectorizeWithBlockFrequency(
291     "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
292     cl::desc("Enable the use of the block frequency analysis to access PGO "
293              "heuristics minimizing code growth in cold regions and being more "
294              "aggressive in hot regions."));
295 
296 // Runtime interleave loops for load/store throughput.
297 static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
298     "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
299     cl::desc(
300         "Enable runtime interleaving until load/store ports are saturated"));
301 
302 /// Interleave small loops with scalar reductions.
303 static cl::opt<bool> InterleaveSmallLoopScalarReduction(
304     "interleave-small-loop-scalar-reduction", cl::init(false), cl::Hidden,
305     cl::desc("Enable interleaving for loops with small iteration counts that "
306              "contain scalar reductions to expose ILP."));
307 
308 /// The number of stores in a loop that are allowed to need predication.
309 static cl::opt<unsigned> NumberOfStoresToPredicate(
310     "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
311     cl::desc("Max number of stores to be predicated behind an if."));
312 
313 static cl::opt<bool> EnableIndVarRegisterHeur(
314     "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
315     cl::desc("Count the induction variable only once when interleaving"));
316 
317 static cl::opt<bool> EnableCondStoresVectorization(
318     "enable-cond-stores-vec", cl::init(true), cl::Hidden,
319     cl::desc("Enable if predication of stores during vectorization."));
320 
321 static cl::opt<unsigned> MaxNestedScalarReductionIC(
322     "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
323     cl::desc("The maximum interleave count to use when interleaving a scalar "
324              "reduction in a nested loop."));
325 
326 static cl::opt<bool>
327     PreferInLoopReductions("prefer-inloop-reductions", cl::init(false),
328                            cl::Hidden,
329                            cl::desc("Prefer in-loop vector reductions, "
330                                     "overriding the targets preference."));
331 
332 static cl::opt<bool> ForceOrderedReductions(
333     "force-ordered-reductions", cl::init(false), cl::Hidden,
334     cl::desc("Enable the vectorisation of loops with in-order (strict) "
335              "FP reductions"));
336 
337 static cl::opt<bool> PreferPredicatedReductionSelect(
338     "prefer-predicated-reduction-select", cl::init(false), cl::Hidden,
339     cl::desc(
340         "Prefer predicating a reduction operation over an after loop select."));
341 
342 cl::opt<bool> EnableVPlanNativePath(
343     "enable-vplan-native-path", cl::init(false), cl::Hidden,
344     cl::desc("Enable VPlan-native vectorization path with "
345              "support for outer loop vectorization."));
346 
347 // This flag enables the stress testing of the VPlan H-CFG construction in the
348 // VPlan-native vectorization path. It must be used in conjuction with
349 // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
350 // verification of the H-CFGs built.
351 static cl::opt<bool> VPlanBuildStressTest(
352     "vplan-build-stress-test", cl::init(false), cl::Hidden,
353     cl::desc(
354         "Build VPlan for every supported loop nest in the function and bail "
355         "out right after the build (stress test the VPlan H-CFG construction "
356         "in the VPlan-native vectorization path)."));
357 
358 cl::opt<bool> llvm::EnableLoopInterleaving(
359     "interleave-loops", cl::init(true), cl::Hidden,
360     cl::desc("Enable loop interleaving in Loop vectorization passes"));
361 cl::opt<bool> llvm::EnableLoopVectorization(
362     "vectorize-loops", cl::init(true), cl::Hidden,
363     cl::desc("Run the Loop vectorization passes"));
364 
365 cl::opt<bool> PrintVPlansInDotFormat(
366     "vplan-print-in-dot-format", cl::init(false), cl::Hidden,
367     cl::desc("Use dot format instead of plain text when dumping VPlans"));
368 
369 /// A helper function that returns true if the given type is irregular. The
370 /// type is irregular if its allocated size doesn't equal the store size of an
371 /// element of the corresponding vector type.
372 static bool hasIrregularType(Type *Ty, const DataLayout &DL) {
373   // Determine if an array of N elements of type Ty is "bitcast compatible"
374   // with a <N x Ty> vector.
375   // This is only true if there is no padding between the array elements.
376   return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
377 }
378 
379 /// A helper function that returns the reciprocal of the block probability of
380 /// predicated blocks. If we return X, we are assuming the predicated block
381 /// will execute once for every X iterations of the loop header.
382 ///
383 /// TODO: We should use actual block probability here, if available. Currently,
384 ///       we always assume predicated blocks have a 50% chance of executing.
385 static unsigned getReciprocalPredBlockProb() { return 2; }
386 
387 /// A helper function that returns an integer or floating-point constant with
388 /// value C.
389 static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
390   return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
391                            : ConstantFP::get(Ty, C);
392 }
393 
394 /// Returns "best known" trip count for the specified loop \p L as defined by
395 /// the following procedure:
396 ///   1) Returns exact trip count if it is known.
397 ///   2) Returns expected trip count according to profile data if any.
398 ///   3) Returns upper bound estimate if it is known.
399 ///   4) Returns None if all of the above failed.
400 static Optional<unsigned> getSmallBestKnownTC(ScalarEvolution &SE, Loop *L) {
401   // Check if exact trip count is known.
402   if (unsigned ExpectedTC = SE.getSmallConstantTripCount(L))
403     return ExpectedTC;
404 
405   // Check if there is an expected trip count available from profile data.
406   if (LoopVectorizeWithBlockFrequency)
407     if (auto EstimatedTC = getLoopEstimatedTripCount(L))
408       return EstimatedTC;
409 
410   // Check if upper bound estimate is known.
411   if (unsigned ExpectedTC = SE.getSmallConstantMaxTripCount(L))
412     return ExpectedTC;
413 
414   return None;
415 }
416 
417 // Forward declare GeneratedRTChecks.
418 class GeneratedRTChecks;
419 
420 namespace llvm {
421 
422 AnalysisKey ShouldRunExtraVectorPasses::Key;
423 
424 /// InnerLoopVectorizer vectorizes loops which contain only one basic
425 /// block to a specified vectorization factor (VF).
426 /// This class performs the widening of scalars into vectors, or multiple
427 /// scalars. This class also implements the following features:
428 /// * It inserts an epilogue loop for handling loops that don't have iteration
429 ///   counts that are known to be a multiple of the vectorization factor.
430 /// * It handles the code generation for reduction variables.
431 /// * Scalarization (implementation using scalars) of un-vectorizable
432 ///   instructions.
433 /// InnerLoopVectorizer does not perform any vectorization-legality
434 /// checks, and relies on the caller to check for the different legality
435 /// aspects. The InnerLoopVectorizer relies on the
436 /// LoopVectorizationLegality class to provide information about the induction
437 /// and reduction variables that were found to a given vectorization factor.
438 class InnerLoopVectorizer {
439 public:
440   InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
441                       LoopInfo *LI, DominatorTree *DT,
442                       const TargetLibraryInfo *TLI,
443                       const TargetTransformInfo *TTI, AssumptionCache *AC,
444                       OptimizationRemarkEmitter *ORE, ElementCount VecWidth,
445                       unsigned UnrollFactor, LoopVectorizationLegality *LVL,
446                       LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
447                       ProfileSummaryInfo *PSI, GeneratedRTChecks &RTChecks)
448       : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
449         AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
450         Builder(PSE.getSE()->getContext()), Legal(LVL), Cost(CM), BFI(BFI),
451         PSI(PSI), RTChecks(RTChecks) {
452     // Query this against the original loop and save it here because the profile
453     // of the original loop header may change as the transformation happens.
454     OptForSizeBasedOnProfile = llvm::shouldOptimizeForSize(
455         OrigLoop->getHeader(), PSI, BFI, PGSOQueryType::IRPass);
456   }
457 
458   virtual ~InnerLoopVectorizer() = default;
459 
460   /// Create a new empty loop that will contain vectorized instructions later
461   /// on, while the old loop will be used as the scalar remainder. Control flow
462   /// is generated around the vectorized (and scalar epilogue) loops consisting
463   /// of various checks and bypasses. Return the pre-header block of the new
464   /// loop and the start value for the canonical induction, if it is != 0. The
465   /// latter is the case when vectorizing the epilogue loop. In the case of
466   /// epilogue vectorization, this function is overriden to handle the more
467   /// complex control flow around the loops.
468   virtual std::pair<BasicBlock *, Value *> createVectorizedLoopSkeleton();
469 
470   /// Widen a single call instruction within the innermost loop.
471   void widenCallInstruction(CallInst &I, VPValue *Def, VPUser &ArgOperands,
472                             VPTransformState &State);
473 
474   /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
475   void fixVectorizedLoop(VPTransformState &State, VPlan &Plan);
476 
477   // Return true if any runtime check is added.
478   bool areSafetyChecksAdded() { return AddedSafetyChecks; }
479 
480   /// A type for vectorized values in the new loop. Each value from the
481   /// original loop, when vectorized, is represented by UF vector values in the
482   /// new unrolled loop, where UF is the unroll factor.
483   using VectorParts = SmallVector<Value *, 2>;
484 
485   /// A helper function to scalarize a single Instruction in the innermost loop.
486   /// Generates a sequence of scalar instances for each lane between \p MinLane
487   /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
488   /// inclusive. Uses the VPValue operands from \p RepRecipe instead of \p
489   /// Instr's operands.
490   void scalarizeInstruction(Instruction *Instr, VPReplicateRecipe *RepRecipe,
491                             const VPIteration &Instance, bool IfPredicateInstr,
492                             VPTransformState &State);
493 
494   /// Construct the vector value of a scalarized value \p V one lane at a time.
495   void packScalarIntoVectorValue(VPValue *Def, const VPIteration &Instance,
496                                  VPTransformState &State);
497 
498   /// Try to vectorize interleaved access group \p Group with the base address
499   /// given in \p Addr, optionally masking the vector operations if \p
500   /// BlockInMask is non-null. Use \p State to translate given VPValues to IR
501   /// values in the vectorized loop.
502   void vectorizeInterleaveGroup(const InterleaveGroup<Instruction> *Group,
503                                 ArrayRef<VPValue *> VPDefs,
504                                 VPTransformState &State, VPValue *Addr,
505                                 ArrayRef<VPValue *> StoredValues,
506                                 VPValue *BlockInMask = nullptr);
507 
508   /// Set the debug location in the builder \p Ptr using the debug location in
509   /// \p V. If \p Ptr is None then it uses the class member's Builder.
510   void setDebugLocFromInst(const Value *V);
511 
512   /// Fix the non-induction PHIs in \p Plan.
513   void fixNonInductionPHIs(VPlan &Plan, VPTransformState &State);
514 
515   /// Returns true if the reordering of FP operations is not allowed, but we are
516   /// able to vectorize with strict in-order reductions for the given RdxDesc.
517   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc);
518 
519   /// Create a broadcast instruction. This method generates a broadcast
520   /// instruction (shuffle) for loop invariant values and for the induction
521   /// value. If this is the induction variable then we extend it to N, N+1, ...
522   /// this is needed because each iteration in the loop corresponds to a SIMD
523   /// element.
524   virtual Value *getBroadcastInstrs(Value *V);
525 
526   /// Add metadata from one instruction to another.
527   ///
528   /// This includes both the original MDs from \p From and additional ones (\see
529   /// addNewMetadata).  Use this for *newly created* instructions in the vector
530   /// loop.
531   void addMetadata(Instruction *To, Instruction *From);
532 
533   /// Similar to the previous function but it adds the metadata to a
534   /// vector of instructions.
535   void addMetadata(ArrayRef<Value *> To, Instruction *From);
536 
537   // Returns the resume value (bc.merge.rdx) for a reduction as
538   // generated by fixReduction.
539   PHINode *getReductionResumeValue(const RecurrenceDescriptor &RdxDesc);
540 
541 protected:
542   friend class LoopVectorizationPlanner;
543 
544   /// A small list of PHINodes.
545   using PhiVector = SmallVector<PHINode *, 4>;
546 
547   /// A type for scalarized values in the new loop. Each value from the
548   /// original loop, when scalarized, is represented by UF x VF scalar values
549   /// in the new unrolled loop, where UF is the unroll factor and VF is the
550   /// vectorization factor.
551   using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
552 
553   /// Set up the values of the IVs correctly when exiting the vector loop.
554   void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
555                     Value *VectorTripCount, Value *EndValue,
556                     BasicBlock *MiddleBlock, BasicBlock *VectorHeader,
557                     VPlan &Plan);
558 
559   /// Handle all cross-iteration phis in the header.
560   void fixCrossIterationPHIs(VPTransformState &State);
561 
562   /// Create the exit value of first order recurrences in the middle block and
563   /// update their users.
564   void fixFirstOrderRecurrence(VPFirstOrderRecurrencePHIRecipe *PhiR,
565                                VPTransformState &State);
566 
567   /// Create code for the loop exit value of the reduction.
568   void fixReduction(VPReductionPHIRecipe *Phi, VPTransformState &State);
569 
570   /// Clear NSW/NUW flags from reduction instructions if necessary.
571   void clearReductionWrapFlags(VPReductionPHIRecipe *PhiR,
572                                VPTransformState &State);
573 
574   /// Iteratively sink the scalarized operands of a predicated instruction into
575   /// the block that was created for it.
576   void sinkScalarOperands(Instruction *PredInst);
577 
578   /// Shrinks vector element sizes to the smallest bitwidth they can be legally
579   /// represented as.
580   void truncateToMinimalBitwidths(VPTransformState &State);
581 
582   /// Returns (and creates if needed) the original loop trip count.
583   Value *getOrCreateTripCount(BasicBlock *InsertBlock);
584 
585   /// Returns (and creates if needed) the trip count of the widened loop.
586   Value *getOrCreateVectorTripCount(BasicBlock *InsertBlock);
587 
588   /// Returns a bitcasted value to the requested vector type.
589   /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
590   Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
591                                 const DataLayout &DL);
592 
593   /// Emit a bypass check to see if the vector trip count is zero, including if
594   /// it overflows.
595   void emitIterationCountCheck(BasicBlock *Bypass);
596 
597   /// Emit a bypass check to see if all of the SCEV assumptions we've
598   /// had to make are correct. Returns the block containing the checks or
599   /// nullptr if no checks have been added.
600   BasicBlock *emitSCEVChecks(BasicBlock *Bypass);
601 
602   /// Emit bypass checks to check any memory assumptions we may have made.
603   /// Returns the block containing the checks or nullptr if no checks have been
604   /// added.
605   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass);
606 
607   /// Emit basic blocks (prefixed with \p Prefix) for the iteration check,
608   /// vector loop preheader, middle block and scalar preheader.
609   void createVectorLoopSkeleton(StringRef Prefix);
610 
611   /// Create new phi nodes for the induction variables to resume iteration count
612   /// in the scalar epilogue, from where the vectorized loop left off.
613   /// In cases where the loop skeleton is more complicated (eg. epilogue
614   /// vectorization) and the resume values can come from an additional bypass
615   /// block, the \p AdditionalBypass pair provides information about the bypass
616   /// block and the end value on the edge from bypass to this loop.
617   void createInductionResumeValues(
618       std::pair<BasicBlock *, Value *> AdditionalBypass = {nullptr, nullptr});
619 
620   /// Complete the loop skeleton by adding debug MDs, creating appropriate
621   /// conditional branches in the middle block, preparing the builder and
622   /// running the verifier. Return the preheader of the completed vector loop.
623   BasicBlock *completeLoopSkeleton(MDNode *OrigLoopID);
624 
625   /// Add additional metadata to \p To that was not present on \p Orig.
626   ///
627   /// Currently this is used to add the noalias annotations based on the
628   /// inserted memchecks.  Use this for instructions that are *cloned* into the
629   /// vector loop.
630   void addNewMetadata(Instruction *To, const Instruction *Orig);
631 
632   /// Collect poison-generating recipes that may generate a poison value that is
633   /// used after vectorization, even when their operands are not poison. Those
634   /// recipes meet the following conditions:
635   ///  * Contribute to the address computation of a recipe generating a widen
636   ///    memory load/store (VPWidenMemoryInstructionRecipe or
637   ///    VPInterleaveRecipe).
638   ///  * Such a widen memory load/store has at least one underlying Instruction
639   ///    that is in a basic block that needs predication and after vectorization
640   ///    the generated instruction won't be predicated.
641   void collectPoisonGeneratingRecipes(VPTransformState &State);
642 
643   /// Allow subclasses to override and print debug traces before/after vplan
644   /// execution, when trace information is requested.
645   virtual void printDebugTracesAtStart(){};
646   virtual void printDebugTracesAtEnd(){};
647 
648   /// The original loop.
649   Loop *OrigLoop;
650 
651   /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
652   /// dynamic knowledge to simplify SCEV expressions and converts them to a
653   /// more usable form.
654   PredicatedScalarEvolution &PSE;
655 
656   /// Loop Info.
657   LoopInfo *LI;
658 
659   /// Dominator Tree.
660   DominatorTree *DT;
661 
662   /// Alias Analysis.
663   AAResults *AA;
664 
665   /// Target Library Info.
666   const TargetLibraryInfo *TLI;
667 
668   /// Target Transform Info.
669   const TargetTransformInfo *TTI;
670 
671   /// Assumption Cache.
672   AssumptionCache *AC;
673 
674   /// Interface to emit optimization remarks.
675   OptimizationRemarkEmitter *ORE;
676 
677   /// LoopVersioning.  It's only set up (non-null) if memchecks were
678   /// used.
679   ///
680   /// This is currently only used to add no-alias metadata based on the
681   /// memchecks.  The actually versioning is performed manually.
682   std::unique_ptr<LoopVersioning> LVer;
683 
684   /// The vectorization SIMD factor to use. Each vector will have this many
685   /// vector elements.
686   ElementCount VF;
687 
688   /// The vectorization unroll factor to use. Each scalar is vectorized to this
689   /// many different vector instructions.
690   unsigned UF;
691 
692   /// The builder that we use
693   IRBuilder<> Builder;
694 
695   // --- Vectorization state ---
696 
697   /// The vector-loop preheader.
698   BasicBlock *LoopVectorPreHeader;
699 
700   /// The scalar-loop preheader.
701   BasicBlock *LoopScalarPreHeader;
702 
703   /// Middle Block between the vector and the scalar.
704   BasicBlock *LoopMiddleBlock;
705 
706   /// The unique ExitBlock of the scalar loop if one exists.  Note that
707   /// there can be multiple exiting edges reaching this block.
708   BasicBlock *LoopExitBlock;
709 
710   /// The scalar loop body.
711   BasicBlock *LoopScalarBody;
712 
713   /// A list of all bypass blocks. The first block is the entry of the loop.
714   SmallVector<BasicBlock *, 4> LoopBypassBlocks;
715 
716   /// Store instructions that were predicated.
717   SmallVector<Instruction *, 4> PredicatedInstructions;
718 
719   /// Trip count of the original loop.
720   Value *TripCount = nullptr;
721 
722   /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
723   Value *VectorTripCount = nullptr;
724 
725   /// The legality analysis.
726   LoopVectorizationLegality *Legal;
727 
728   /// The profitablity analysis.
729   LoopVectorizationCostModel *Cost;
730 
731   // Record whether runtime checks are added.
732   bool AddedSafetyChecks = false;
733 
734   // Holds the end values for each induction variable. We save the end values
735   // so we can later fix-up the external users of the induction variables.
736   DenseMap<PHINode *, Value *> IVEndValues;
737 
738   /// BFI and PSI are used to check for profile guided size optimizations.
739   BlockFrequencyInfo *BFI;
740   ProfileSummaryInfo *PSI;
741 
742   // Whether this loop should be optimized for size based on profile guided size
743   // optimizatios.
744   bool OptForSizeBasedOnProfile;
745 
746   /// Structure to hold information about generated runtime checks, responsible
747   /// for cleaning the checks, if vectorization turns out unprofitable.
748   GeneratedRTChecks &RTChecks;
749 
750   // Holds the resume values for reductions in the loops, used to set the
751   // correct start value of reduction PHIs when vectorizing the epilogue.
752   SmallMapVector<const RecurrenceDescriptor *, PHINode *, 4>
753       ReductionResumeValues;
754 };
755 
756 class InnerLoopUnroller : public InnerLoopVectorizer {
757 public:
758   InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
759                     LoopInfo *LI, DominatorTree *DT,
760                     const TargetLibraryInfo *TLI,
761                     const TargetTransformInfo *TTI, AssumptionCache *AC,
762                     OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
763                     LoopVectorizationLegality *LVL,
764                     LoopVectorizationCostModel *CM, BlockFrequencyInfo *BFI,
765                     ProfileSummaryInfo *PSI, GeneratedRTChecks &Check)
766       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
767                             ElementCount::getFixed(1), UnrollFactor, LVL, CM,
768                             BFI, PSI, Check) {}
769 
770 private:
771   Value *getBroadcastInstrs(Value *V) override;
772 };
773 
774 /// Encapsulate information regarding vectorization of a loop and its epilogue.
775 /// This information is meant to be updated and used across two stages of
776 /// epilogue vectorization.
777 struct EpilogueLoopVectorizationInfo {
778   ElementCount MainLoopVF = ElementCount::getFixed(0);
779   unsigned MainLoopUF = 0;
780   ElementCount EpilogueVF = ElementCount::getFixed(0);
781   unsigned EpilogueUF = 0;
782   BasicBlock *MainLoopIterationCountCheck = nullptr;
783   BasicBlock *EpilogueIterationCountCheck = nullptr;
784   BasicBlock *SCEVSafetyCheck = nullptr;
785   BasicBlock *MemSafetyCheck = nullptr;
786   Value *TripCount = nullptr;
787   Value *VectorTripCount = nullptr;
788 
789   EpilogueLoopVectorizationInfo(ElementCount MVF, unsigned MUF,
790                                 ElementCount EVF, unsigned EUF)
791       : MainLoopVF(MVF), MainLoopUF(MUF), EpilogueVF(EVF), EpilogueUF(EUF) {
792     assert(EUF == 1 &&
793            "A high UF for the epilogue loop is likely not beneficial.");
794   }
795 };
796 
797 /// An extension of the inner loop vectorizer that creates a skeleton for a
798 /// vectorized loop that has its epilogue (residual) also vectorized.
799 /// The idea is to run the vplan on a given loop twice, firstly to setup the
800 /// skeleton and vectorize the main loop, and secondly to complete the skeleton
801 /// from the first step and vectorize the epilogue.  This is achieved by
802 /// deriving two concrete strategy classes from this base class and invoking
803 /// them in succession from the loop vectorizer planner.
804 class InnerLoopAndEpilogueVectorizer : public InnerLoopVectorizer {
805 public:
806   InnerLoopAndEpilogueVectorizer(
807       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
808       DominatorTree *DT, const TargetLibraryInfo *TLI,
809       const TargetTransformInfo *TTI, AssumptionCache *AC,
810       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
811       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
812       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
813       GeneratedRTChecks &Checks)
814       : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
815                             EPI.MainLoopVF, EPI.MainLoopUF, LVL, CM, BFI, PSI,
816                             Checks),
817         EPI(EPI) {}
818 
819   // Override this function to handle the more complex control flow around the
820   // three loops.
821   std::pair<BasicBlock *, Value *>
822   createVectorizedLoopSkeleton() final override {
823     return createEpilogueVectorizedLoopSkeleton();
824   }
825 
826   /// The interface for creating a vectorized skeleton using one of two
827   /// different strategies, each corresponding to one execution of the vplan
828   /// as described above.
829   virtual std::pair<BasicBlock *, Value *>
830   createEpilogueVectorizedLoopSkeleton() = 0;
831 
832   /// Holds and updates state information required to vectorize the main loop
833   /// and its epilogue in two separate passes. This setup helps us avoid
834   /// regenerating and recomputing runtime safety checks. It also helps us to
835   /// shorten the iteration-count-check path length for the cases where the
836   /// iteration count of the loop is so small that the main vector loop is
837   /// completely skipped.
838   EpilogueLoopVectorizationInfo &EPI;
839 };
840 
841 /// A specialized derived class of inner loop vectorizer that performs
842 /// vectorization of *main* loops in the process of vectorizing loops and their
843 /// epilogues.
844 class EpilogueVectorizerMainLoop : public InnerLoopAndEpilogueVectorizer {
845 public:
846   EpilogueVectorizerMainLoop(
847       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
848       DominatorTree *DT, const TargetLibraryInfo *TLI,
849       const TargetTransformInfo *TTI, AssumptionCache *AC,
850       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
851       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
852       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
853       GeneratedRTChecks &Check)
854       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
855                                        EPI, LVL, CM, BFI, PSI, Check) {}
856   /// Implements the interface for creating a vectorized skeleton using the
857   /// *main loop* strategy (ie the first pass of vplan execution).
858   std::pair<BasicBlock *, Value *>
859   createEpilogueVectorizedLoopSkeleton() final override;
860 
861 protected:
862   /// Emits an iteration count bypass check once for the main loop (when \p
863   /// ForEpilogue is false) and once for the epilogue loop (when \p
864   /// ForEpilogue is true).
865   BasicBlock *emitIterationCountCheck(BasicBlock *Bypass, bool ForEpilogue);
866   void printDebugTracesAtStart() override;
867   void printDebugTracesAtEnd() override;
868 };
869 
870 // A specialized derived class of inner loop vectorizer that performs
871 // vectorization of *epilogue* loops in the process of vectorizing loops and
872 // their epilogues.
873 class EpilogueVectorizerEpilogueLoop : public InnerLoopAndEpilogueVectorizer {
874 public:
875   EpilogueVectorizerEpilogueLoop(
876       Loop *OrigLoop, PredicatedScalarEvolution &PSE, LoopInfo *LI,
877       DominatorTree *DT, const TargetLibraryInfo *TLI,
878       const TargetTransformInfo *TTI, AssumptionCache *AC,
879       OptimizationRemarkEmitter *ORE, EpilogueLoopVectorizationInfo &EPI,
880       LoopVectorizationLegality *LVL, llvm::LoopVectorizationCostModel *CM,
881       BlockFrequencyInfo *BFI, ProfileSummaryInfo *PSI,
882       GeneratedRTChecks &Checks)
883       : InnerLoopAndEpilogueVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE,
884                                        EPI, LVL, CM, BFI, PSI, Checks) {
885     TripCount = EPI.TripCount;
886   }
887   /// Implements the interface for creating a vectorized skeleton using the
888   /// *epilogue loop* strategy (ie the second pass of vplan execution).
889   std::pair<BasicBlock *, Value *>
890   createEpilogueVectorizedLoopSkeleton() final override;
891 
892 protected:
893   /// Emits an iteration count bypass check after the main vector loop has
894   /// finished to see if there are any iterations left to execute by either
895   /// the vector epilogue or the scalar epilogue.
896   BasicBlock *emitMinimumVectorEpilogueIterCountCheck(
897                                                       BasicBlock *Bypass,
898                                                       BasicBlock *Insert);
899   void printDebugTracesAtStart() override;
900   void printDebugTracesAtEnd() override;
901 };
902 } // end namespace llvm
903 
904 /// Look for a meaningful debug location on the instruction or it's
905 /// operands.
906 static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
907   if (!I)
908     return I;
909 
910   DebugLoc Empty;
911   if (I->getDebugLoc() != Empty)
912     return I;
913 
914   for (Use &Op : I->operands()) {
915     if (Instruction *OpInst = dyn_cast<Instruction>(Op))
916       if (OpInst->getDebugLoc() != Empty)
917         return OpInst;
918   }
919 
920   return I;
921 }
922 
923 void InnerLoopVectorizer::setDebugLocFromInst(
924     const Value *V) {
925   if (const Instruction *Inst = dyn_cast_or_null<Instruction>(V)) {
926     const DILocation *DIL = Inst->getDebugLoc();
927 
928     // When a FSDiscriminator is enabled, we don't need to add the multiply
929     // factors to the discriminators.
930     if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
931         !isa<DbgInfoIntrinsic>(Inst) && !EnableFSDiscriminator) {
932       // FIXME: For scalable vectors, assume vscale=1.
933       auto NewDIL =
934           DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
935       if (NewDIL)
936         Builder.SetCurrentDebugLocation(*NewDIL);
937       else
938         LLVM_DEBUG(dbgs()
939                    << "Failed to create new discriminator: "
940                    << DIL->getFilename() << " Line: " << DIL->getLine());
941     } else
942       Builder.SetCurrentDebugLocation(DIL);
943   } else
944     Builder.SetCurrentDebugLocation(DebugLoc());
945 }
946 
947 /// Write a \p DebugMsg about vectorization to the debug output stream. If \p I
948 /// is passed, the message relates to that particular instruction.
949 #ifndef NDEBUG
950 static void debugVectorizationMessage(const StringRef Prefix,
951                                       const StringRef DebugMsg,
952                                       Instruction *I) {
953   dbgs() << "LV: " << Prefix << DebugMsg;
954   if (I != nullptr)
955     dbgs() << " " << *I;
956   else
957     dbgs() << '.';
958   dbgs() << '\n';
959 }
960 #endif
961 
962 /// Create an analysis remark that explains why vectorization failed
963 ///
964 /// \p PassName is the name of the pass (e.g. can be AlwaysPrint).  \p
965 /// RemarkName is the identifier for the remark.  If \p I is passed it is an
966 /// instruction that prevents vectorization.  Otherwise \p TheLoop is used for
967 /// the location of the remark.  \return the remark object that can be
968 /// streamed to.
969 static OptimizationRemarkAnalysis createLVAnalysis(const char *PassName,
970     StringRef RemarkName, Loop *TheLoop, Instruction *I) {
971   Value *CodeRegion = TheLoop->getHeader();
972   DebugLoc DL = TheLoop->getStartLoc();
973 
974   if (I) {
975     CodeRegion = I->getParent();
976     // If there is no debug location attached to the instruction, revert back to
977     // using the loop's.
978     if (I->getDebugLoc())
979       DL = I->getDebugLoc();
980   }
981 
982   return OptimizationRemarkAnalysis(PassName, RemarkName, DL, CodeRegion);
983 }
984 
985 namespace llvm {
986 
987 /// Return a value for Step multiplied by VF.
988 Value *createStepForVF(IRBuilderBase &B, Type *Ty, ElementCount VF,
989                        int64_t Step) {
990   assert(Ty->isIntegerTy() && "Expected an integer step");
991   Constant *StepVal = ConstantInt::get(Ty, Step * VF.getKnownMinValue());
992   return VF.isScalable() ? B.CreateVScale(StepVal) : StepVal;
993 }
994 
995 /// Return the runtime value for VF.
996 Value *getRuntimeVF(IRBuilderBase &B, Type *Ty, ElementCount VF) {
997   Constant *EC = ConstantInt::get(Ty, VF.getKnownMinValue());
998   return VF.isScalable() ? B.CreateVScale(EC) : EC;
999 }
1000 
1001 static Value *getRuntimeVFAsFloat(IRBuilderBase &B, Type *FTy,
1002                                   ElementCount VF) {
1003   assert(FTy->isFloatingPointTy() && "Expected floating point type!");
1004   Type *IntTy = IntegerType::get(FTy->getContext(), FTy->getScalarSizeInBits());
1005   Value *RuntimeVF = getRuntimeVF(B, IntTy, VF);
1006   return B.CreateUIToFP(RuntimeVF, FTy);
1007 }
1008 
1009 void reportVectorizationFailure(const StringRef DebugMsg,
1010                                 const StringRef OREMsg, const StringRef ORETag,
1011                                 OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1012                                 Instruction *I) {
1013   LLVM_DEBUG(debugVectorizationMessage("Not vectorizing: ", DebugMsg, I));
1014   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1015   ORE->emit(
1016       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1017       << "loop not vectorized: " << OREMsg);
1018 }
1019 
1020 void reportVectorizationInfo(const StringRef Msg, const StringRef ORETag,
1021                              OptimizationRemarkEmitter *ORE, Loop *TheLoop,
1022                              Instruction *I) {
1023   LLVM_DEBUG(debugVectorizationMessage("", Msg, I));
1024   LoopVectorizeHints Hints(TheLoop, true /* doesn't matter */, *ORE);
1025   ORE->emit(
1026       createLVAnalysis(Hints.vectorizeAnalysisPassName(), ORETag, TheLoop, I)
1027       << Msg);
1028 }
1029 
1030 } // end namespace llvm
1031 
1032 #ifndef NDEBUG
1033 /// \return string containing a file name and a line # for the given loop.
1034 static std::string getDebugLocString(const Loop *L) {
1035   std::string Result;
1036   if (L) {
1037     raw_string_ostream OS(Result);
1038     if (const DebugLoc LoopDbgLoc = L->getStartLoc())
1039       LoopDbgLoc.print(OS);
1040     else
1041       // Just print the module name.
1042       OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
1043     OS.flush();
1044   }
1045   return Result;
1046 }
1047 #endif
1048 
1049 void InnerLoopVectorizer::addNewMetadata(Instruction *To,
1050                                          const Instruction *Orig) {
1051   // If the loop was versioned with memchecks, add the corresponding no-alias
1052   // metadata.
1053   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
1054     LVer->annotateInstWithNoAlias(To, Orig);
1055 }
1056 
1057 void InnerLoopVectorizer::collectPoisonGeneratingRecipes(
1058     VPTransformState &State) {
1059 
1060   // Collect recipes in the backward slice of `Root` that may generate a poison
1061   // value that is used after vectorization.
1062   SmallPtrSet<VPRecipeBase *, 16> Visited;
1063   auto collectPoisonGeneratingInstrsInBackwardSlice([&](VPRecipeBase *Root) {
1064     SmallVector<VPRecipeBase *, 16> Worklist;
1065     Worklist.push_back(Root);
1066 
1067     // Traverse the backward slice of Root through its use-def chain.
1068     while (!Worklist.empty()) {
1069       VPRecipeBase *CurRec = Worklist.back();
1070       Worklist.pop_back();
1071 
1072       if (!Visited.insert(CurRec).second)
1073         continue;
1074 
1075       // Prune search if we find another recipe generating a widen memory
1076       // instruction. Widen memory instructions involved in address computation
1077       // will lead to gather/scatter instructions, which don't need to be
1078       // handled.
1079       if (isa<VPWidenMemoryInstructionRecipe>(CurRec) ||
1080           isa<VPInterleaveRecipe>(CurRec) ||
1081           isa<VPScalarIVStepsRecipe>(CurRec) ||
1082           isa<VPCanonicalIVPHIRecipe>(CurRec))
1083         continue;
1084 
1085       // This recipe contributes to the address computation of a widen
1086       // load/store. Collect recipe if its underlying instruction has
1087       // poison-generating flags.
1088       Instruction *Instr = CurRec->getUnderlyingInstr();
1089       if (Instr && Instr->hasPoisonGeneratingFlags())
1090         State.MayGeneratePoisonRecipes.insert(CurRec);
1091 
1092       // Add new definitions to the worklist.
1093       for (VPValue *operand : CurRec->operands())
1094         if (VPDef *OpDef = operand->getDef())
1095           Worklist.push_back(cast<VPRecipeBase>(OpDef));
1096     }
1097   });
1098 
1099   // Traverse all the recipes in the VPlan and collect the poison-generating
1100   // recipes in the backward slice starting at the address of a VPWidenRecipe or
1101   // VPInterleaveRecipe.
1102   auto Iter = depth_first(
1103       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(State.Plan->getEntry()));
1104   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
1105     for (VPRecipeBase &Recipe : *VPBB) {
1106       if (auto *WidenRec = dyn_cast<VPWidenMemoryInstructionRecipe>(&Recipe)) {
1107         Instruction &UnderlyingInstr = WidenRec->getIngredient();
1108         VPDef *AddrDef = WidenRec->getAddr()->getDef();
1109         if (AddrDef && WidenRec->isConsecutive() &&
1110             Legal->blockNeedsPredication(UnderlyingInstr.getParent()))
1111           collectPoisonGeneratingInstrsInBackwardSlice(
1112               cast<VPRecipeBase>(AddrDef));
1113       } else if (auto *InterleaveRec = dyn_cast<VPInterleaveRecipe>(&Recipe)) {
1114         VPDef *AddrDef = InterleaveRec->getAddr()->getDef();
1115         if (AddrDef) {
1116           // Check if any member of the interleave group needs predication.
1117           const InterleaveGroup<Instruction> *InterGroup =
1118               InterleaveRec->getInterleaveGroup();
1119           bool NeedPredication = false;
1120           for (int I = 0, NumMembers = InterGroup->getNumMembers();
1121                I < NumMembers; ++I) {
1122             Instruction *Member = InterGroup->getMember(I);
1123             if (Member)
1124               NeedPredication |=
1125                   Legal->blockNeedsPredication(Member->getParent());
1126           }
1127 
1128           if (NeedPredication)
1129             collectPoisonGeneratingInstrsInBackwardSlice(
1130                 cast<VPRecipeBase>(AddrDef));
1131         }
1132       }
1133     }
1134   }
1135 }
1136 
1137 void InnerLoopVectorizer::addMetadata(Instruction *To,
1138                                       Instruction *From) {
1139   propagateMetadata(To, From);
1140   addNewMetadata(To, From);
1141 }
1142 
1143 void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
1144                                       Instruction *From) {
1145   for (Value *V : To) {
1146     if (Instruction *I = dyn_cast<Instruction>(V))
1147       addMetadata(I, From);
1148   }
1149 }
1150 
1151 PHINode *InnerLoopVectorizer::getReductionResumeValue(
1152     const RecurrenceDescriptor &RdxDesc) {
1153   auto It = ReductionResumeValues.find(&RdxDesc);
1154   assert(It != ReductionResumeValues.end() &&
1155          "Expected to find a resume value for the reduction.");
1156   return It->second;
1157 }
1158 
1159 namespace llvm {
1160 
1161 // Loop vectorization cost-model hints how the scalar epilogue loop should be
1162 // lowered.
1163 enum ScalarEpilogueLowering {
1164 
1165   // The default: allowing scalar epilogues.
1166   CM_ScalarEpilogueAllowed,
1167 
1168   // Vectorization with OptForSize: don't allow epilogues.
1169   CM_ScalarEpilogueNotAllowedOptSize,
1170 
1171   // A special case of vectorisation with OptForSize: loops with a very small
1172   // trip count are considered for vectorization under OptForSize, thereby
1173   // making sure the cost of their loop body is dominant, free of runtime
1174   // guards and scalar iteration overheads.
1175   CM_ScalarEpilogueNotAllowedLowTripLoop,
1176 
1177   // Loop hint predicate indicating an epilogue is undesired.
1178   CM_ScalarEpilogueNotNeededUsePredicate,
1179 
1180   // Directive indicating we must either tail fold or not vectorize
1181   CM_ScalarEpilogueNotAllowedUsePredicate
1182 };
1183 
1184 /// ElementCountComparator creates a total ordering for ElementCount
1185 /// for the purposes of using it in a set structure.
1186 struct ElementCountComparator {
1187   bool operator()(const ElementCount &LHS, const ElementCount &RHS) const {
1188     return std::make_tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
1189            std::make_tuple(RHS.isScalable(), RHS.getKnownMinValue());
1190   }
1191 };
1192 using ElementCountSet = SmallSet<ElementCount, 16, ElementCountComparator>;
1193 
1194 /// LoopVectorizationCostModel - estimates the expected speedups due to
1195 /// vectorization.
1196 /// In many cases vectorization is not profitable. This can happen because of
1197 /// a number of reasons. In this class we mainly attempt to predict the
1198 /// expected speedup/slowdowns due to the supported instruction set. We use the
1199 /// TargetTransformInfo to query the different backends for the cost of
1200 /// different operations.
1201 class LoopVectorizationCostModel {
1202 public:
1203   LoopVectorizationCostModel(ScalarEpilogueLowering SEL, Loop *L,
1204                              PredicatedScalarEvolution &PSE, LoopInfo *LI,
1205                              LoopVectorizationLegality *Legal,
1206                              const TargetTransformInfo &TTI,
1207                              const TargetLibraryInfo *TLI, DemandedBits *DB,
1208                              AssumptionCache *AC,
1209                              OptimizationRemarkEmitter *ORE, const Function *F,
1210                              const LoopVectorizeHints *Hints,
1211                              InterleavedAccessInfo &IAI)
1212       : ScalarEpilogueStatus(SEL), TheLoop(L), PSE(PSE), LI(LI), Legal(Legal),
1213         TTI(TTI), TLI(TLI), DB(DB), AC(AC), ORE(ORE), TheFunction(F),
1214         Hints(Hints), InterleaveInfo(IAI) {}
1215 
1216   /// \return An upper bound for the vectorization factors (both fixed and
1217   /// scalable). If the factors are 0, vectorization and interleaving should be
1218   /// avoided up front.
1219   FixedScalableVFPair computeMaxVF(ElementCount UserVF, unsigned UserIC);
1220 
1221   /// \return True if runtime checks are required for vectorization, and false
1222   /// otherwise.
1223   bool runtimeChecksRequired();
1224 
1225   /// \return The most profitable vectorization factor and the cost of that VF.
1226   /// This method checks every VF in \p CandidateVFs. If UserVF is not ZERO
1227   /// then this vectorization factor will be selected if vectorization is
1228   /// possible.
1229   VectorizationFactor
1230   selectVectorizationFactor(const ElementCountSet &CandidateVFs);
1231 
1232   VectorizationFactor
1233   selectEpilogueVectorizationFactor(const ElementCount MaxVF,
1234                                     const LoopVectorizationPlanner &LVP);
1235 
1236   /// Setup cost-based decisions for user vectorization factor.
1237   /// \return true if the UserVF is a feasible VF to be chosen.
1238   bool selectUserVectorizationFactor(ElementCount UserVF) {
1239     collectUniformsAndScalars(UserVF);
1240     collectInstsToScalarize(UserVF);
1241     return expectedCost(UserVF).first.isValid();
1242   }
1243 
1244   /// \return The size (in bits) of the smallest and widest types in the code
1245   /// that needs to be vectorized. We ignore values that remain scalar such as
1246   /// 64 bit loop indices.
1247   std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
1248 
1249   /// \return The desired interleave count.
1250   /// If interleave count has been specified by metadata it will be returned.
1251   /// Otherwise, the interleave count is computed and returned. VF and LoopCost
1252   /// are the selected vectorization factor and the cost of the selected VF.
1253   unsigned selectInterleaveCount(ElementCount VF, unsigned LoopCost);
1254 
1255   /// Memory access instruction may be vectorized in more than one way.
1256   /// Form of instruction after vectorization depends on cost.
1257   /// This function takes cost-based decisions for Load/Store instructions
1258   /// and collects them in a map. This decisions map is used for building
1259   /// the lists of loop-uniform and loop-scalar instructions.
1260   /// The calculated cost is saved with widening decision in order to
1261   /// avoid redundant calculations.
1262   void setCostBasedWideningDecision(ElementCount VF);
1263 
1264   /// A struct that represents some properties of the register usage
1265   /// of a loop.
1266   struct RegisterUsage {
1267     /// Holds the number of loop invariant values that are used in the loop.
1268     /// The key is ClassID of target-provided register class.
1269     SmallMapVector<unsigned, unsigned, 4> LoopInvariantRegs;
1270     /// Holds the maximum number of concurrent live intervals in the loop.
1271     /// The key is ClassID of target-provided register class.
1272     SmallMapVector<unsigned, unsigned, 4> MaxLocalUsers;
1273   };
1274 
1275   /// \return Returns information about the register usages of the loop for the
1276   /// given vectorization factors.
1277   SmallVector<RegisterUsage, 8>
1278   calculateRegisterUsage(ArrayRef<ElementCount> VFs);
1279 
1280   /// Collect values we want to ignore in the cost model.
1281   void collectValuesToIgnore();
1282 
1283   /// Collect all element types in the loop for which widening is needed.
1284   void collectElementTypesForWidening();
1285 
1286   /// Split reductions into those that happen in the loop, and those that happen
1287   /// outside. In loop reductions are collected into InLoopReductionChains.
1288   void collectInLoopReductions();
1289 
1290   /// Returns true if we should use strict in-order reductions for the given
1291   /// RdxDesc. This is true if the -enable-strict-reductions flag is passed,
1292   /// the IsOrdered flag of RdxDesc is set and we do not allow reordering
1293   /// of FP operations.
1294   bool useOrderedReductions(const RecurrenceDescriptor &RdxDesc) const {
1295     return !Hints->allowReordering() && RdxDesc.isOrdered();
1296   }
1297 
1298   /// \returns The smallest bitwidth each instruction can be represented with.
1299   /// The vector equivalents of these instructions should be truncated to this
1300   /// type.
1301   const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
1302     return MinBWs;
1303   }
1304 
1305   /// \returns True if it is more profitable to scalarize instruction \p I for
1306   /// vectorization factor \p VF.
1307   bool isProfitableToScalarize(Instruction *I, ElementCount VF) const {
1308     assert(VF.isVector() &&
1309            "Profitable to scalarize relevant only for VF > 1.");
1310 
1311     // Cost model is not run in the VPlan-native path - return conservative
1312     // result until this changes.
1313     if (EnableVPlanNativePath)
1314       return false;
1315 
1316     auto Scalars = InstsToScalarize.find(VF);
1317     assert(Scalars != InstsToScalarize.end() &&
1318            "VF not yet analyzed for scalarization profitability");
1319     return Scalars->second.find(I) != Scalars->second.end();
1320   }
1321 
1322   /// Returns true if \p I is known to be uniform after vectorization.
1323   bool isUniformAfterVectorization(Instruction *I, ElementCount VF) const {
1324     if (VF.isScalar())
1325       return true;
1326 
1327     // Cost model is not run in the VPlan-native path - return conservative
1328     // result until this changes.
1329     if (EnableVPlanNativePath)
1330       return false;
1331 
1332     auto UniformsPerVF = Uniforms.find(VF);
1333     assert(UniformsPerVF != Uniforms.end() &&
1334            "VF not yet analyzed for uniformity");
1335     return UniformsPerVF->second.count(I);
1336   }
1337 
1338   /// Returns true if \p I is known to be scalar after vectorization.
1339   bool isScalarAfterVectorization(Instruction *I, ElementCount VF) const {
1340     if (VF.isScalar())
1341       return true;
1342 
1343     // Cost model is not run in the VPlan-native path - return conservative
1344     // result until this changes.
1345     if (EnableVPlanNativePath)
1346       return false;
1347 
1348     auto ScalarsPerVF = Scalars.find(VF);
1349     assert(ScalarsPerVF != Scalars.end() &&
1350            "Scalar values are not calculated for VF");
1351     return ScalarsPerVF->second.count(I);
1352   }
1353 
1354   /// \returns True if instruction \p I can be truncated to a smaller bitwidth
1355   /// for vectorization factor \p VF.
1356   bool canTruncateToMinimalBitwidth(Instruction *I, ElementCount VF) const {
1357     return VF.isVector() && MinBWs.find(I) != MinBWs.end() &&
1358            !isProfitableToScalarize(I, VF) &&
1359            !isScalarAfterVectorization(I, VF);
1360   }
1361 
1362   /// Decision that was taken during cost calculation for memory instruction.
1363   enum InstWidening {
1364     CM_Unknown,
1365     CM_Widen,         // For consecutive accesses with stride +1.
1366     CM_Widen_Reverse, // For consecutive accesses with stride -1.
1367     CM_Interleave,
1368     CM_GatherScatter,
1369     CM_Scalarize
1370   };
1371 
1372   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1373   /// instruction \p I and vector width \p VF.
1374   void setWideningDecision(Instruction *I, ElementCount VF, InstWidening W,
1375                            InstructionCost Cost) {
1376     assert(VF.isVector() && "Expected VF >=2");
1377     WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1378   }
1379 
1380   /// Save vectorization decision \p W and \p Cost taken by the cost model for
1381   /// interleaving group \p Grp and vector width \p VF.
1382   void setWideningDecision(const InterleaveGroup<Instruction> *Grp,
1383                            ElementCount VF, InstWidening W,
1384                            InstructionCost Cost) {
1385     assert(VF.isVector() && "Expected VF >=2");
1386     /// Broadcast this decicion to all instructions inside the group.
1387     /// But the cost will be assigned to one instruction only.
1388     for (unsigned i = 0; i < Grp->getFactor(); ++i) {
1389       if (auto *I = Grp->getMember(i)) {
1390         if (Grp->getInsertPos() == I)
1391           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
1392         else
1393           WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
1394       }
1395     }
1396   }
1397 
1398   /// Return the cost model decision for the given instruction \p I and vector
1399   /// width \p VF. Return CM_Unknown if this instruction did not pass
1400   /// through the cost modeling.
1401   InstWidening getWideningDecision(Instruction *I, ElementCount VF) const {
1402     assert(VF.isVector() && "Expected VF to be a vector VF");
1403     // Cost model is not run in the VPlan-native path - return conservative
1404     // result until this changes.
1405     if (EnableVPlanNativePath)
1406       return CM_GatherScatter;
1407 
1408     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1409     auto Itr = WideningDecisions.find(InstOnVF);
1410     if (Itr == WideningDecisions.end())
1411       return CM_Unknown;
1412     return Itr->second.first;
1413   }
1414 
1415   /// Return the vectorization cost for the given instruction \p I and vector
1416   /// width \p VF.
1417   InstructionCost getWideningCost(Instruction *I, ElementCount VF) {
1418     assert(VF.isVector() && "Expected VF >=2");
1419     std::pair<Instruction *, ElementCount> InstOnVF = std::make_pair(I, VF);
1420     assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
1421            "The cost is not calculated");
1422     return WideningDecisions[InstOnVF].second;
1423   }
1424 
1425   /// Return True if instruction \p I is an optimizable truncate whose operand
1426   /// is an induction variable. Such a truncate will be removed by adding a new
1427   /// induction variable with the destination type.
1428   bool isOptimizableIVTruncate(Instruction *I, ElementCount VF) {
1429     // If the instruction is not a truncate, return false.
1430     auto *Trunc = dyn_cast<TruncInst>(I);
1431     if (!Trunc)
1432       return false;
1433 
1434     // Get the source and destination types of the truncate.
1435     Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
1436     Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
1437 
1438     // If the truncate is free for the given types, return false. Replacing a
1439     // free truncate with an induction variable would add an induction variable
1440     // update instruction to each iteration of the loop. We exclude from this
1441     // check the primary induction variable since it will need an update
1442     // instruction regardless.
1443     Value *Op = Trunc->getOperand(0);
1444     if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
1445       return false;
1446 
1447     // If the truncated value is not an induction variable, return false.
1448     return Legal->isInductionPhi(Op);
1449   }
1450 
1451   /// Collects the instructions to scalarize for each predicated instruction in
1452   /// the loop.
1453   void collectInstsToScalarize(ElementCount VF);
1454 
1455   /// Collect Uniform and Scalar values for the given \p VF.
1456   /// The sets depend on CM decision for Load/Store instructions
1457   /// that may be vectorized as interleave, gather-scatter or scalarized.
1458   void collectUniformsAndScalars(ElementCount VF) {
1459     // Do the analysis once.
1460     if (VF.isScalar() || Uniforms.find(VF) != Uniforms.end())
1461       return;
1462     setCostBasedWideningDecision(VF);
1463     collectLoopUniforms(VF);
1464     collectLoopScalars(VF);
1465   }
1466 
1467   /// Returns true if the target machine supports masked store operation
1468   /// for the given \p DataType and kind of access to \p Ptr.
1469   bool isLegalMaskedStore(Type *DataType, Value *Ptr, Align Alignment) const {
1470     return Legal->isConsecutivePtr(DataType, Ptr) &&
1471            TTI.isLegalMaskedStore(DataType, Alignment);
1472   }
1473 
1474   /// Returns true if the target machine supports masked load operation
1475   /// for the given \p DataType and kind of access to \p Ptr.
1476   bool isLegalMaskedLoad(Type *DataType, Value *Ptr, Align Alignment) const {
1477     return Legal->isConsecutivePtr(DataType, Ptr) &&
1478            TTI.isLegalMaskedLoad(DataType, Alignment);
1479   }
1480 
1481   /// Returns true if the target machine can represent \p V as a masked gather
1482   /// or scatter operation.
1483   bool isLegalGatherOrScatter(Value *V,
1484                               ElementCount VF = ElementCount::getFixed(1)) {
1485     bool LI = isa<LoadInst>(V);
1486     bool SI = isa<StoreInst>(V);
1487     if (!LI && !SI)
1488       return false;
1489     auto *Ty = getLoadStoreType(V);
1490     Align Align = getLoadStoreAlignment(V);
1491     if (VF.isVector())
1492       Ty = VectorType::get(Ty, VF);
1493     return (LI && TTI.isLegalMaskedGather(Ty, Align)) ||
1494            (SI && TTI.isLegalMaskedScatter(Ty, Align));
1495   }
1496 
1497   /// Returns true if the target machine supports all of the reduction
1498   /// variables found for the given VF.
1499   bool canVectorizeReductions(ElementCount VF) const {
1500     return (all_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
1501       const RecurrenceDescriptor &RdxDesc = Reduction.second;
1502       return TTI.isLegalToVectorizeReduction(RdxDesc, VF);
1503     }));
1504   }
1505 
1506   /// Returns true if \p I is an instruction that will be scalarized with
1507   /// predication when vectorizing \p I with vectorization factor \p VF. Such
1508   /// instructions include conditional stores and instructions that may divide
1509   /// by zero.
1510   bool isScalarWithPredication(Instruction *I, ElementCount VF) const;
1511 
1512   // Returns true if \p I is an instruction that will be predicated either
1513   // through scalar predication or masked load/store or masked gather/scatter.
1514   // \p VF is the vectorization factor that will be used to vectorize \p I.
1515   // Superset of instructions that return true for isScalarWithPredication.
1516   bool isPredicatedInst(Instruction *I, ElementCount VF,
1517                         bool IsKnownUniform = false) {
1518     // When we know the load is uniform and the original scalar loop was not
1519     // predicated we don't need to mark it as a predicated instruction. Any
1520     // vectorised blocks created when tail-folding are something artificial we
1521     // have introduced and we know there is always at least one active lane.
1522     // That's why we call Legal->blockNeedsPredication here because it doesn't
1523     // query tail-folding.
1524     if (IsKnownUniform && isa<LoadInst>(I) &&
1525         !Legal->blockNeedsPredication(I->getParent()))
1526       return false;
1527     if (!blockNeedsPredicationForAnyReason(I->getParent()))
1528       return false;
1529     // Loads and stores that need some form of masked operation are predicated
1530     // instructions.
1531     if (isa<LoadInst>(I) || isa<StoreInst>(I))
1532       return Legal->isMaskRequired(I);
1533     return isScalarWithPredication(I, VF);
1534   }
1535 
1536   /// Returns true if \p I is a memory instruction with consecutive memory
1537   /// access that can be widened.
1538   bool
1539   memoryInstructionCanBeWidened(Instruction *I,
1540                                 ElementCount VF = ElementCount::getFixed(1));
1541 
1542   /// Returns true if \p I is a memory instruction in an interleaved-group
1543   /// of memory accesses that can be vectorized with wide vector loads/stores
1544   /// and shuffles.
1545   bool
1546   interleavedAccessCanBeWidened(Instruction *I,
1547                                 ElementCount VF = ElementCount::getFixed(1));
1548 
1549   /// Check if \p Instr belongs to any interleaved access group.
1550   bool isAccessInterleaved(Instruction *Instr) {
1551     return InterleaveInfo.isInterleaved(Instr);
1552   }
1553 
1554   /// Get the interleaved access group that \p Instr belongs to.
1555   const InterleaveGroup<Instruction> *
1556   getInterleavedAccessGroup(Instruction *Instr) {
1557     return InterleaveInfo.getInterleaveGroup(Instr);
1558   }
1559 
1560   /// Returns true if we're required to use a scalar epilogue for at least
1561   /// the final iteration of the original loop.
1562   bool requiresScalarEpilogue(ElementCount VF) const {
1563     if (!isScalarEpilogueAllowed())
1564       return false;
1565     // If we might exit from anywhere but the latch, must run the exiting
1566     // iteration in scalar form.
1567     if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch())
1568       return true;
1569     return VF.isVector() && InterleaveInfo.requiresScalarEpilogue();
1570   }
1571 
1572   /// Returns true if a scalar epilogue is not allowed due to optsize or a
1573   /// loop hint annotation.
1574   bool isScalarEpilogueAllowed() const {
1575     return ScalarEpilogueStatus == CM_ScalarEpilogueAllowed;
1576   }
1577 
1578   /// Returns true if all loop blocks should be masked to fold tail loop.
1579   bool foldTailByMasking() const { return FoldTailByMasking; }
1580 
1581   /// Returns true if the instructions in this block requires predication
1582   /// for any reason, e.g. because tail folding now requires a predicate
1583   /// or because the block in the original loop was predicated.
1584   bool blockNeedsPredicationForAnyReason(BasicBlock *BB) const {
1585     return foldTailByMasking() || Legal->blockNeedsPredication(BB);
1586   }
1587 
1588   /// A SmallMapVector to store the InLoop reduction op chains, mapping phi
1589   /// nodes to the chain of instructions representing the reductions. Uses a
1590   /// MapVector to ensure deterministic iteration order.
1591   using ReductionChainMap =
1592       SmallMapVector<PHINode *, SmallVector<Instruction *, 4>, 4>;
1593 
1594   /// Return the chain of instructions representing an inloop reduction.
1595   const ReductionChainMap &getInLoopReductionChains() const {
1596     return InLoopReductionChains;
1597   }
1598 
1599   /// Returns true if the Phi is part of an inloop reduction.
1600   bool isInLoopReduction(PHINode *Phi) const {
1601     return InLoopReductionChains.count(Phi);
1602   }
1603 
1604   /// Estimate cost of an intrinsic call instruction CI if it were vectorized
1605   /// with factor VF.  Return the cost of the instruction, including
1606   /// scalarization overhead if it's needed.
1607   InstructionCost getVectorIntrinsicCost(CallInst *CI, ElementCount VF) const;
1608 
1609   /// Estimate cost of a call instruction CI if it were vectorized with factor
1610   /// VF. Return the cost of the instruction, including scalarization overhead
1611   /// if it's needed. The flag NeedToScalarize shows if the call needs to be
1612   /// scalarized -
1613   /// i.e. either vector version isn't available, or is too expensive.
1614   InstructionCost getVectorCallCost(CallInst *CI, ElementCount VF,
1615                                     bool &NeedToScalarize) const;
1616 
1617   /// Returns true if the per-lane cost of VectorizationFactor A is lower than
1618   /// that of B.
1619   bool isMoreProfitable(const VectorizationFactor &A,
1620                         const VectorizationFactor &B) const;
1621 
1622   /// Invalidates decisions already taken by the cost model.
1623   void invalidateCostModelingDecisions() {
1624     WideningDecisions.clear();
1625     Uniforms.clear();
1626     Scalars.clear();
1627   }
1628 
1629 private:
1630   unsigned NumPredStores = 0;
1631 
1632   /// Convenience function that returns the value of vscale_range iff
1633   /// vscale_range.min == vscale_range.max or otherwise returns the value
1634   /// returned by the corresponding TLI method.
1635   Optional<unsigned> getVScaleForTuning() const;
1636 
1637   /// \return An upper bound for the vectorization factors for both
1638   /// fixed and scalable vectorization, where the minimum-known number of
1639   /// elements is a power-of-2 larger than zero. If scalable vectorization is
1640   /// disabled or unsupported, then the scalable part will be equal to
1641   /// ElementCount::getScalable(0).
1642   FixedScalableVFPair computeFeasibleMaxVF(unsigned ConstTripCount,
1643                                            ElementCount UserVF,
1644                                            bool FoldTailByMasking);
1645 
1646   /// \return the maximized element count based on the targets vector
1647   /// registers and the loop trip-count, but limited to a maximum safe VF.
1648   /// This is a helper function of computeFeasibleMaxVF.
1649   ElementCount getMaximizedVFForTarget(unsigned ConstTripCount,
1650                                        unsigned SmallestType,
1651                                        unsigned WidestType,
1652                                        ElementCount MaxSafeVF,
1653                                        bool FoldTailByMasking);
1654 
1655   /// \return the maximum legal scalable VF, based on the safe max number
1656   /// of elements.
1657   ElementCount getMaxLegalScalableVF(unsigned MaxSafeElements);
1658 
1659   /// The vectorization cost is a combination of the cost itself and a boolean
1660   /// indicating whether any of the contributing operations will actually
1661   /// operate on vector values after type legalization in the backend. If this
1662   /// latter value is false, then all operations will be scalarized (i.e. no
1663   /// vectorization has actually taken place).
1664   using VectorizationCostTy = std::pair<InstructionCost, bool>;
1665 
1666   /// Returns the expected execution cost. The unit of the cost does
1667   /// not matter because we use the 'cost' units to compare different
1668   /// vector widths. The cost that is returned is *not* normalized by
1669   /// the factor width. If \p Invalid is not nullptr, this function
1670   /// will add a pair(Instruction*, ElementCount) to \p Invalid for
1671   /// each instruction that has an Invalid cost for the given VF.
1672   using InstructionVFPair = std::pair<Instruction *, ElementCount>;
1673   VectorizationCostTy
1674   expectedCost(ElementCount VF,
1675                SmallVectorImpl<InstructionVFPair> *Invalid = nullptr);
1676 
1677   /// Returns the execution time cost of an instruction for a given vector
1678   /// width. Vector width of one means scalar.
1679   VectorizationCostTy getInstructionCost(Instruction *I, ElementCount VF);
1680 
1681   /// The cost-computation logic from getInstructionCost which provides
1682   /// the vector type as an output parameter.
1683   InstructionCost getInstructionCost(Instruction *I, ElementCount VF,
1684                                      Type *&VectorTy);
1685 
1686   /// Return the cost of instructions in an inloop reduction pattern, if I is
1687   /// part of that pattern.
1688   Optional<InstructionCost>
1689   getReductionPatternCost(Instruction *I, ElementCount VF, Type *VectorTy,
1690                           TTI::TargetCostKind CostKind);
1691 
1692   /// Calculate vectorization cost of memory instruction \p I.
1693   InstructionCost getMemoryInstructionCost(Instruction *I, ElementCount VF);
1694 
1695   /// The cost computation for scalarized memory instruction.
1696   InstructionCost getMemInstScalarizationCost(Instruction *I, ElementCount VF);
1697 
1698   /// The cost computation for interleaving group of memory instructions.
1699   InstructionCost getInterleaveGroupCost(Instruction *I, ElementCount VF);
1700 
1701   /// The cost computation for Gather/Scatter instruction.
1702   InstructionCost getGatherScatterCost(Instruction *I, ElementCount VF);
1703 
1704   /// The cost computation for widening instruction \p I with consecutive
1705   /// memory access.
1706   InstructionCost getConsecutiveMemOpCost(Instruction *I, ElementCount VF);
1707 
1708   /// The cost calculation for Load/Store instruction \p I with uniform pointer -
1709   /// Load: scalar load + broadcast.
1710   /// Store: scalar store + (loop invariant value stored? 0 : extract of last
1711   /// element)
1712   InstructionCost getUniformMemOpCost(Instruction *I, ElementCount VF);
1713 
1714   /// Estimate the overhead of scalarizing an instruction. This is a
1715   /// convenience wrapper for the type-based getScalarizationOverhead API.
1716   InstructionCost getScalarizationOverhead(Instruction *I,
1717                                            ElementCount VF) const;
1718 
1719   /// Returns whether the instruction is a load or store and will be a emitted
1720   /// as a vector operation.
1721   bool isConsecutiveLoadOrStore(Instruction *I);
1722 
1723   /// Returns true if an artificially high cost for emulated masked memrefs
1724   /// should be used.
1725   bool useEmulatedMaskMemRefHack(Instruction *I, ElementCount VF);
1726 
1727   /// Map of scalar integer values to the smallest bitwidth they can be legally
1728   /// represented as. The vector equivalents of these values should be truncated
1729   /// to this type.
1730   MapVector<Instruction *, uint64_t> MinBWs;
1731 
1732   /// A type representing the costs for instructions if they were to be
1733   /// scalarized rather than vectorized. The entries are Instruction-Cost
1734   /// pairs.
1735   using ScalarCostsTy = DenseMap<Instruction *, InstructionCost>;
1736 
1737   /// A set containing all BasicBlocks that are known to present after
1738   /// vectorization as a predicated block.
1739   SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
1740 
1741   /// Records whether it is allowed to have the original scalar loop execute at
1742   /// least once. This may be needed as a fallback loop in case runtime
1743   /// aliasing/dependence checks fail, or to handle the tail/remainder
1744   /// iterations when the trip count is unknown or doesn't divide by the VF,
1745   /// or as a peel-loop to handle gaps in interleave-groups.
1746   /// Under optsize and when the trip count is very small we don't allow any
1747   /// iterations to execute in the scalar loop.
1748   ScalarEpilogueLowering ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
1749 
1750   /// All blocks of loop are to be masked to fold tail of scalar iterations.
1751   bool FoldTailByMasking = false;
1752 
1753   /// A map holding scalar costs for different vectorization factors. The
1754   /// presence of a cost for an instruction in the mapping indicates that the
1755   /// instruction will be scalarized when vectorizing with the associated
1756   /// vectorization factor. The entries are VF-ScalarCostTy pairs.
1757   DenseMap<ElementCount, ScalarCostsTy> InstsToScalarize;
1758 
1759   /// Holds the instructions known to be uniform after vectorization.
1760   /// The data is collected per VF.
1761   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Uniforms;
1762 
1763   /// Holds the instructions known to be scalar after vectorization.
1764   /// The data is collected per VF.
1765   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> Scalars;
1766 
1767   /// Holds the instructions (address computations) that are forced to be
1768   /// scalarized.
1769   DenseMap<ElementCount, SmallPtrSet<Instruction *, 4>> ForcedScalars;
1770 
1771   /// PHINodes of the reductions that should be expanded in-loop along with
1772   /// their associated chains of reduction operations, in program order from top
1773   /// (PHI) to bottom
1774   ReductionChainMap InLoopReductionChains;
1775 
1776   /// A Map of inloop reduction operations and their immediate chain operand.
1777   /// FIXME: This can be removed once reductions can be costed correctly in
1778   /// vplan. This was added to allow quick lookup to the inloop operations,
1779   /// without having to loop through InLoopReductionChains.
1780   DenseMap<Instruction *, Instruction *> InLoopReductionImmediateChains;
1781 
1782   /// Returns the expected difference in cost from scalarizing the expression
1783   /// feeding a predicated instruction \p PredInst. The instructions to
1784   /// scalarize and their scalar costs are collected in \p ScalarCosts. A
1785   /// non-negative return value implies the expression will be scalarized.
1786   /// Currently, only single-use chains are considered for scalarization.
1787   int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
1788                               ElementCount VF);
1789 
1790   /// Collect the instructions that are uniform after vectorization. An
1791   /// instruction is uniform if we represent it with a single scalar value in
1792   /// the vectorized loop corresponding to each vector iteration. Examples of
1793   /// uniform instructions include pointer operands of consecutive or
1794   /// interleaved memory accesses. Note that although uniformity implies an
1795   /// instruction will be scalar, the reverse is not true. In general, a
1796   /// scalarized instruction will be represented by VF scalar values in the
1797   /// vectorized loop, each corresponding to an iteration of the original
1798   /// scalar loop.
1799   void collectLoopUniforms(ElementCount VF);
1800 
1801   /// Collect the instructions that are scalar after vectorization. An
1802   /// instruction is scalar if it is known to be uniform or will be scalarized
1803   /// during vectorization. collectLoopScalars should only add non-uniform nodes
1804   /// to the list if they are used by a load/store instruction that is marked as
1805   /// CM_Scalarize. Non-uniform scalarized instructions will be represented by
1806   /// VF values in the vectorized loop, each corresponding to an iteration of
1807   /// the original scalar loop.
1808   void collectLoopScalars(ElementCount VF);
1809 
1810   /// Keeps cost model vectorization decision and cost for instructions.
1811   /// Right now it is used for memory instructions only.
1812   using DecisionList = DenseMap<std::pair<Instruction *, ElementCount>,
1813                                 std::pair<InstWidening, InstructionCost>>;
1814 
1815   DecisionList WideningDecisions;
1816 
1817   /// Returns true if \p V is expected to be vectorized and it needs to be
1818   /// extracted.
1819   bool needsExtract(Value *V, ElementCount VF) const {
1820     Instruction *I = dyn_cast<Instruction>(V);
1821     if (VF.isScalar() || !I || !TheLoop->contains(I) ||
1822         TheLoop->isLoopInvariant(I))
1823       return false;
1824 
1825     // Assume we can vectorize V (and hence we need extraction) if the
1826     // scalars are not computed yet. This can happen, because it is called
1827     // via getScalarizationOverhead from setCostBasedWideningDecision, before
1828     // the scalars are collected. That should be a safe assumption in most
1829     // cases, because we check if the operands have vectorizable types
1830     // beforehand in LoopVectorizationLegality.
1831     return Scalars.find(VF) == Scalars.end() ||
1832            !isScalarAfterVectorization(I, VF);
1833   };
1834 
1835   /// Returns a range containing only operands needing to be extracted.
1836   SmallVector<Value *, 4> filterExtractingOperands(Instruction::op_range Ops,
1837                                                    ElementCount VF) const {
1838     return SmallVector<Value *, 4>(make_filter_range(
1839         Ops, [this, VF](Value *V) { return this->needsExtract(V, VF); }));
1840   }
1841 
1842   /// Determines if we have the infrastructure to vectorize loop \p L and its
1843   /// epilogue, assuming the main loop is vectorized by \p VF.
1844   bool isCandidateForEpilogueVectorization(const Loop &L,
1845                                            const ElementCount VF) const;
1846 
1847   /// Returns true if epilogue vectorization is considered profitable, and
1848   /// false otherwise.
1849   /// \p VF is the vectorization factor chosen for the original loop.
1850   bool isEpilogueVectorizationProfitable(const ElementCount VF) const;
1851 
1852 public:
1853   /// The loop that we evaluate.
1854   Loop *TheLoop;
1855 
1856   /// Predicated scalar evolution analysis.
1857   PredicatedScalarEvolution &PSE;
1858 
1859   /// Loop Info analysis.
1860   LoopInfo *LI;
1861 
1862   /// Vectorization legality.
1863   LoopVectorizationLegality *Legal;
1864 
1865   /// Vector target information.
1866   const TargetTransformInfo &TTI;
1867 
1868   /// Target Library Info.
1869   const TargetLibraryInfo *TLI;
1870 
1871   /// Demanded bits analysis.
1872   DemandedBits *DB;
1873 
1874   /// Assumption cache.
1875   AssumptionCache *AC;
1876 
1877   /// Interface to emit optimization remarks.
1878   OptimizationRemarkEmitter *ORE;
1879 
1880   const Function *TheFunction;
1881 
1882   /// Loop Vectorize Hint.
1883   const LoopVectorizeHints *Hints;
1884 
1885   /// The interleave access information contains groups of interleaved accesses
1886   /// with the same stride and close to each other.
1887   InterleavedAccessInfo &InterleaveInfo;
1888 
1889   /// Values to ignore in the cost model.
1890   SmallPtrSet<const Value *, 16> ValuesToIgnore;
1891 
1892   /// Values to ignore in the cost model when VF > 1.
1893   SmallPtrSet<const Value *, 16> VecValuesToIgnore;
1894 
1895   /// All element types found in the loop.
1896   SmallPtrSet<Type *, 16> ElementTypesInLoop;
1897 
1898   /// Profitable vector factors.
1899   SmallVector<VectorizationFactor, 8> ProfitableVFs;
1900 };
1901 } // end namespace llvm
1902 
1903 /// Helper struct to manage generating runtime checks for vectorization.
1904 ///
1905 /// The runtime checks are created up-front in temporary blocks to allow better
1906 /// estimating the cost and un-linked from the existing IR. After deciding to
1907 /// vectorize, the checks are moved back. If deciding not to vectorize, the
1908 /// temporary blocks are completely removed.
1909 class GeneratedRTChecks {
1910   /// Basic block which contains the generated SCEV checks, if any.
1911   BasicBlock *SCEVCheckBlock = nullptr;
1912 
1913   /// The value representing the result of the generated SCEV checks. If it is
1914   /// nullptr, either no SCEV checks have been generated or they have been used.
1915   Value *SCEVCheckCond = nullptr;
1916 
1917   /// Basic block which contains the generated memory runtime checks, if any.
1918   BasicBlock *MemCheckBlock = nullptr;
1919 
1920   /// The value representing the result of the generated memory runtime checks.
1921   /// If it is nullptr, either no memory runtime checks have been generated or
1922   /// they have been used.
1923   Value *MemRuntimeCheckCond = nullptr;
1924 
1925   DominatorTree *DT;
1926   LoopInfo *LI;
1927 
1928   SCEVExpander SCEVExp;
1929   SCEVExpander MemCheckExp;
1930 
1931 public:
1932   GeneratedRTChecks(ScalarEvolution &SE, DominatorTree *DT, LoopInfo *LI,
1933                     const DataLayout &DL)
1934       : DT(DT), LI(LI), SCEVExp(SE, DL, "scev.check"),
1935         MemCheckExp(SE, DL, "scev.check") {}
1936 
1937   /// Generate runtime checks in SCEVCheckBlock and MemCheckBlock, so we can
1938   /// accurately estimate the cost of the runtime checks. The blocks are
1939   /// un-linked from the IR and is added back during vector code generation. If
1940   /// there is no vector code generation, the check blocks are removed
1941   /// completely.
1942   void Create(Loop *L, const LoopAccessInfo &LAI,
1943               const SCEVPredicate &UnionPred, ElementCount VF, unsigned IC) {
1944 
1945     BasicBlock *LoopHeader = L->getHeader();
1946     BasicBlock *Preheader = L->getLoopPreheader();
1947 
1948     // Use SplitBlock to create blocks for SCEV & memory runtime checks to
1949     // ensure the blocks are properly added to LoopInfo & DominatorTree. Those
1950     // may be used by SCEVExpander. The blocks will be un-linked from their
1951     // predecessors and removed from LI & DT at the end of the function.
1952     if (!UnionPred.isAlwaysTrue()) {
1953       SCEVCheckBlock = SplitBlock(Preheader, Preheader->getTerminator(), DT, LI,
1954                                   nullptr, "vector.scevcheck");
1955 
1956       SCEVCheckCond = SCEVExp.expandCodeForPredicate(
1957           &UnionPred, SCEVCheckBlock->getTerminator());
1958     }
1959 
1960     const auto &RtPtrChecking = *LAI.getRuntimePointerChecking();
1961     if (RtPtrChecking.Need) {
1962       auto *Pred = SCEVCheckBlock ? SCEVCheckBlock : Preheader;
1963       MemCheckBlock = SplitBlock(Pred, Pred->getTerminator(), DT, LI, nullptr,
1964                                  "vector.memcheck");
1965 
1966       auto DiffChecks = RtPtrChecking.getDiffChecks();
1967       if (DiffChecks) {
1968         MemRuntimeCheckCond = addDiffRuntimeChecks(
1969             MemCheckBlock->getTerminator(), L, *DiffChecks, MemCheckExp,
1970             [VF](IRBuilderBase &B, unsigned Bits) {
1971               return getRuntimeVF(B, B.getIntNTy(Bits), VF);
1972             },
1973             IC);
1974       } else {
1975         MemRuntimeCheckCond =
1976             addRuntimeChecks(MemCheckBlock->getTerminator(), L,
1977                              RtPtrChecking.getChecks(), MemCheckExp);
1978       }
1979       assert(MemRuntimeCheckCond &&
1980              "no RT checks generated although RtPtrChecking "
1981              "claimed checks are required");
1982     }
1983 
1984     if (!MemCheckBlock && !SCEVCheckBlock)
1985       return;
1986 
1987     // Unhook the temporary block with the checks, update various places
1988     // accordingly.
1989     if (SCEVCheckBlock)
1990       SCEVCheckBlock->replaceAllUsesWith(Preheader);
1991     if (MemCheckBlock)
1992       MemCheckBlock->replaceAllUsesWith(Preheader);
1993 
1994     if (SCEVCheckBlock) {
1995       SCEVCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
1996       new UnreachableInst(Preheader->getContext(), SCEVCheckBlock);
1997       Preheader->getTerminator()->eraseFromParent();
1998     }
1999     if (MemCheckBlock) {
2000       MemCheckBlock->getTerminator()->moveBefore(Preheader->getTerminator());
2001       new UnreachableInst(Preheader->getContext(), MemCheckBlock);
2002       Preheader->getTerminator()->eraseFromParent();
2003     }
2004 
2005     DT->changeImmediateDominator(LoopHeader, Preheader);
2006     if (MemCheckBlock) {
2007       DT->eraseNode(MemCheckBlock);
2008       LI->removeBlock(MemCheckBlock);
2009     }
2010     if (SCEVCheckBlock) {
2011       DT->eraseNode(SCEVCheckBlock);
2012       LI->removeBlock(SCEVCheckBlock);
2013     }
2014   }
2015 
2016   /// Remove the created SCEV & memory runtime check blocks & instructions, if
2017   /// unused.
2018   ~GeneratedRTChecks() {
2019     SCEVExpanderCleaner SCEVCleaner(SCEVExp);
2020     SCEVExpanderCleaner MemCheckCleaner(MemCheckExp);
2021     if (!SCEVCheckCond)
2022       SCEVCleaner.markResultUsed();
2023 
2024     if (!MemRuntimeCheckCond)
2025       MemCheckCleaner.markResultUsed();
2026 
2027     if (MemRuntimeCheckCond) {
2028       auto &SE = *MemCheckExp.getSE();
2029       // Memory runtime check generation creates compares that use expanded
2030       // values. Remove them before running the SCEVExpanderCleaners.
2031       for (auto &I : make_early_inc_range(reverse(*MemCheckBlock))) {
2032         if (MemCheckExp.isInsertedInstruction(&I))
2033           continue;
2034         SE.forgetValue(&I);
2035         I.eraseFromParent();
2036       }
2037     }
2038     MemCheckCleaner.cleanup();
2039     SCEVCleaner.cleanup();
2040 
2041     if (SCEVCheckCond)
2042       SCEVCheckBlock->eraseFromParent();
2043     if (MemRuntimeCheckCond)
2044       MemCheckBlock->eraseFromParent();
2045   }
2046 
2047   /// Adds the generated SCEVCheckBlock before \p LoopVectorPreHeader and
2048   /// adjusts the branches to branch to the vector preheader or \p Bypass,
2049   /// depending on the generated condition.
2050   BasicBlock *emitSCEVChecks(BasicBlock *Bypass,
2051                              BasicBlock *LoopVectorPreHeader,
2052                              BasicBlock *LoopExitBlock) {
2053     if (!SCEVCheckCond)
2054       return nullptr;
2055 
2056     Value *Cond = SCEVCheckCond;
2057     // Mark the check as used, to prevent it from being removed during cleanup.
2058     SCEVCheckCond = nullptr;
2059     if (auto *C = dyn_cast<ConstantInt>(Cond))
2060       if (C->isZero())
2061         return nullptr;
2062 
2063     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2064 
2065     BranchInst::Create(LoopVectorPreHeader, SCEVCheckBlock);
2066     // Create new preheader for vector loop.
2067     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2068       PL->addBasicBlockToLoop(SCEVCheckBlock, *LI);
2069 
2070     SCEVCheckBlock->getTerminator()->eraseFromParent();
2071     SCEVCheckBlock->moveBefore(LoopVectorPreHeader);
2072     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2073                                                 SCEVCheckBlock);
2074 
2075     DT->addNewBlock(SCEVCheckBlock, Pred);
2076     DT->changeImmediateDominator(LoopVectorPreHeader, SCEVCheckBlock);
2077 
2078     ReplaceInstWithInst(SCEVCheckBlock->getTerminator(),
2079                         BranchInst::Create(Bypass, LoopVectorPreHeader, Cond));
2080     return SCEVCheckBlock;
2081   }
2082 
2083   /// Adds the generated MemCheckBlock before \p LoopVectorPreHeader and adjusts
2084   /// the branches to branch to the vector preheader or \p Bypass, depending on
2085   /// the generated condition.
2086   BasicBlock *emitMemRuntimeChecks(BasicBlock *Bypass,
2087                                    BasicBlock *LoopVectorPreHeader) {
2088     // Check if we generated code that checks in runtime if arrays overlap.
2089     if (!MemRuntimeCheckCond)
2090       return nullptr;
2091 
2092     auto *Pred = LoopVectorPreHeader->getSinglePredecessor();
2093     Pred->getTerminator()->replaceSuccessorWith(LoopVectorPreHeader,
2094                                                 MemCheckBlock);
2095 
2096     DT->addNewBlock(MemCheckBlock, Pred);
2097     DT->changeImmediateDominator(LoopVectorPreHeader, MemCheckBlock);
2098     MemCheckBlock->moveBefore(LoopVectorPreHeader);
2099 
2100     if (auto *PL = LI->getLoopFor(LoopVectorPreHeader))
2101       PL->addBasicBlockToLoop(MemCheckBlock, *LI);
2102 
2103     ReplaceInstWithInst(
2104         MemCheckBlock->getTerminator(),
2105         BranchInst::Create(Bypass, LoopVectorPreHeader, MemRuntimeCheckCond));
2106     MemCheckBlock->getTerminator()->setDebugLoc(
2107         Pred->getTerminator()->getDebugLoc());
2108 
2109     // Mark the check as used, to prevent it from being removed during cleanup.
2110     MemRuntimeCheckCond = nullptr;
2111     return MemCheckBlock;
2112   }
2113 };
2114 
2115 // Return true if \p OuterLp is an outer loop annotated with hints for explicit
2116 // vectorization. The loop needs to be annotated with #pragma omp simd
2117 // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
2118 // vector length information is not provided, vectorization is not considered
2119 // explicit. Interleave hints are not allowed either. These limitations will be
2120 // relaxed in the future.
2121 // Please, note that we are currently forced to abuse the pragma 'clang
2122 // vectorize' semantics. This pragma provides *auto-vectorization hints*
2123 // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
2124 // provides *explicit vectorization hints* (LV can bypass legal checks and
2125 // assume that vectorization is legal). However, both hints are implemented
2126 // using the same metadata (llvm.loop.vectorize, processed by
2127 // LoopVectorizeHints). This will be fixed in the future when the native IR
2128 // representation for pragma 'omp simd' is introduced.
2129 static bool isExplicitVecOuterLoop(Loop *OuterLp,
2130                                    OptimizationRemarkEmitter *ORE) {
2131   assert(!OuterLp->isInnermost() && "This is not an outer loop");
2132   LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
2133 
2134   // Only outer loops with an explicit vectorization hint are supported.
2135   // Unannotated outer loops are ignored.
2136   if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
2137     return false;
2138 
2139   Function *Fn = OuterLp->getHeader()->getParent();
2140   if (!Hints.allowVectorization(Fn, OuterLp,
2141                                 true /*VectorizeOnlyWhenForced*/)) {
2142     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
2143     return false;
2144   }
2145 
2146   if (Hints.getInterleave() > 1) {
2147     // TODO: Interleave support is future work.
2148     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
2149                          "outer loops.\n");
2150     Hints.emitRemarkWithHints();
2151     return false;
2152   }
2153 
2154   return true;
2155 }
2156 
2157 static void collectSupportedLoops(Loop &L, LoopInfo *LI,
2158                                   OptimizationRemarkEmitter *ORE,
2159                                   SmallVectorImpl<Loop *> &V) {
2160   // Collect inner loops and outer loops without irreducible control flow. For
2161   // now, only collect outer loops that have explicit vectorization hints. If we
2162   // are stress testing the VPlan H-CFG construction, we collect the outermost
2163   // loop of every loop nest.
2164   if (L.isInnermost() || VPlanBuildStressTest ||
2165       (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
2166     LoopBlocksRPO RPOT(&L);
2167     RPOT.perform(LI);
2168     if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
2169       V.push_back(&L);
2170       // TODO: Collect inner loops inside marked outer loops in case
2171       // vectorization fails for the outer loop. Do not invoke
2172       // 'containsIrreducibleCFG' again for inner loops when the outer loop is
2173       // already known to be reducible. We can use an inherited attribute for
2174       // that.
2175       return;
2176     }
2177   }
2178   for (Loop *InnerL : L)
2179     collectSupportedLoops(*InnerL, LI, ORE, V);
2180 }
2181 
2182 namespace {
2183 
2184 /// The LoopVectorize Pass.
2185 struct LoopVectorize : public FunctionPass {
2186   /// Pass identification, replacement for typeid
2187   static char ID;
2188 
2189   LoopVectorizePass Impl;
2190 
2191   explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
2192                          bool VectorizeOnlyWhenForced = false)
2193       : FunctionPass(ID),
2194         Impl({InterleaveOnlyWhenForced, VectorizeOnlyWhenForced}) {
2195     initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
2196   }
2197 
2198   bool runOnFunction(Function &F) override {
2199     if (skipFunction(F))
2200       return false;
2201 
2202     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2203     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2204     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
2205     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2206     auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
2207     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2208     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
2209     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
2210     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
2211     auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
2212     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
2213     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
2214     auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
2215 
2216     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
2217         [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
2218 
2219     return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
2220                         GetLAA, *ORE, PSI).MadeAnyChange;
2221   }
2222 
2223   void getAnalysisUsage(AnalysisUsage &AU) const override {
2224     AU.addRequired<AssumptionCacheTracker>();
2225     AU.addRequired<BlockFrequencyInfoWrapperPass>();
2226     AU.addRequired<DominatorTreeWrapperPass>();
2227     AU.addRequired<LoopInfoWrapperPass>();
2228     AU.addRequired<ScalarEvolutionWrapperPass>();
2229     AU.addRequired<TargetTransformInfoWrapperPass>();
2230     AU.addRequired<AAResultsWrapperPass>();
2231     AU.addRequired<LoopAccessLegacyAnalysis>();
2232     AU.addRequired<DemandedBitsWrapperPass>();
2233     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
2234     AU.addRequired<InjectTLIMappingsLegacy>();
2235 
2236     // We currently do not preserve loopinfo/dominator analyses with outer loop
2237     // vectorization. Until this is addressed, mark these analyses as preserved
2238     // only for non-VPlan-native path.
2239     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
2240     if (!EnableVPlanNativePath) {
2241       AU.addPreserved<LoopInfoWrapperPass>();
2242       AU.addPreserved<DominatorTreeWrapperPass>();
2243     }
2244 
2245     AU.addPreserved<BasicAAWrapperPass>();
2246     AU.addPreserved<GlobalsAAWrapperPass>();
2247     AU.addRequired<ProfileSummaryInfoWrapperPass>();
2248   }
2249 };
2250 
2251 } // end anonymous namespace
2252 
2253 //===----------------------------------------------------------------------===//
2254 // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
2255 // LoopVectorizationCostModel and LoopVectorizationPlanner.
2256 //===----------------------------------------------------------------------===//
2257 
2258 Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
2259   // We need to place the broadcast of invariant variables outside the loop,
2260   // but only if it's proven safe to do so. Else, broadcast will be inside
2261   // vector loop body.
2262   Instruction *Instr = dyn_cast<Instruction>(V);
2263   bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
2264                      (!Instr ||
2265                       DT->dominates(Instr->getParent(), LoopVectorPreHeader));
2266   // Place the code for broadcasting invariant variables in the new preheader.
2267   IRBuilder<>::InsertPointGuard Guard(Builder);
2268   if (SafeToHoist)
2269     Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
2270 
2271   // Broadcast the scalar into all locations in the vector.
2272   Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
2273 
2274   return Shuf;
2275 }
2276 
2277 /// This function adds
2278 /// (StartIdx * Step, (StartIdx + 1) * Step, (StartIdx + 2) * Step, ...)
2279 /// to each vector element of Val. The sequence starts at StartIndex.
2280 /// \p Opcode is relevant for FP induction variable.
2281 static Value *getStepVector(Value *Val, Value *StartIdx, Value *Step,
2282                             Instruction::BinaryOps BinOp, ElementCount VF,
2283                             IRBuilderBase &Builder) {
2284   assert(VF.isVector() && "only vector VFs are supported");
2285 
2286   // Create and check the types.
2287   auto *ValVTy = cast<VectorType>(Val->getType());
2288   ElementCount VLen = ValVTy->getElementCount();
2289 
2290   Type *STy = Val->getType()->getScalarType();
2291   assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
2292          "Induction Step must be an integer or FP");
2293   assert(Step->getType() == STy && "Step has wrong type");
2294 
2295   SmallVector<Constant *, 8> Indices;
2296 
2297   // Create a vector of consecutive numbers from zero to VF.
2298   VectorType *InitVecValVTy = ValVTy;
2299   if (STy->isFloatingPointTy()) {
2300     Type *InitVecValSTy =
2301         IntegerType::get(STy->getContext(), STy->getScalarSizeInBits());
2302     InitVecValVTy = VectorType::get(InitVecValSTy, VLen);
2303   }
2304   Value *InitVec = Builder.CreateStepVector(InitVecValVTy);
2305 
2306   // Splat the StartIdx
2307   Value *StartIdxSplat = Builder.CreateVectorSplat(VLen, StartIdx);
2308 
2309   if (STy->isIntegerTy()) {
2310     InitVec = Builder.CreateAdd(InitVec, StartIdxSplat);
2311     Step = Builder.CreateVectorSplat(VLen, Step);
2312     assert(Step->getType() == Val->getType() && "Invalid step vec");
2313     // FIXME: The newly created binary instructions should contain nsw/nuw
2314     // flags, which can be found from the original scalar operations.
2315     Step = Builder.CreateMul(InitVec, Step);
2316     return Builder.CreateAdd(Val, Step, "induction");
2317   }
2318 
2319   // Floating point induction.
2320   assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
2321          "Binary Opcode should be specified for FP induction");
2322   InitVec = Builder.CreateUIToFP(InitVec, ValVTy);
2323   InitVec = Builder.CreateFAdd(InitVec, StartIdxSplat);
2324 
2325   Step = Builder.CreateVectorSplat(VLen, Step);
2326   Value *MulOp = Builder.CreateFMul(InitVec, Step);
2327   return Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
2328 }
2329 
2330 /// Compute scalar induction steps. \p ScalarIV is the scalar induction
2331 /// variable on which to base the steps, \p Step is the size of the step.
2332 static void buildScalarSteps(Value *ScalarIV, Value *Step,
2333                              const InductionDescriptor &ID, VPValue *Def,
2334                              VPTransformState &State) {
2335   IRBuilderBase &Builder = State.Builder;
2336   // We shouldn't have to build scalar steps if we aren't vectorizing.
2337   assert(State.VF.isVector() && "VF should be greater than one");
2338   // Get the value type and ensure it and the step have the same integer type.
2339   Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
2340   assert(ScalarIVTy == Step->getType() &&
2341          "Val and Step should have the same type");
2342 
2343   // We build scalar steps for both integer and floating-point induction
2344   // variables. Here, we determine the kind of arithmetic we will perform.
2345   Instruction::BinaryOps AddOp;
2346   Instruction::BinaryOps MulOp;
2347   if (ScalarIVTy->isIntegerTy()) {
2348     AddOp = Instruction::Add;
2349     MulOp = Instruction::Mul;
2350   } else {
2351     AddOp = ID.getInductionOpcode();
2352     MulOp = Instruction::FMul;
2353   }
2354 
2355   // Determine the number of scalars we need to generate for each unroll
2356   // iteration.
2357   bool FirstLaneOnly = vputils::onlyFirstLaneUsed(Def);
2358   unsigned Lanes = FirstLaneOnly ? 1 : State.VF.getKnownMinValue();
2359   // Compute the scalar steps and save the results in State.
2360   Type *IntStepTy = IntegerType::get(ScalarIVTy->getContext(),
2361                                      ScalarIVTy->getScalarSizeInBits());
2362   Type *VecIVTy = nullptr;
2363   Value *UnitStepVec = nullptr, *SplatStep = nullptr, *SplatIV = nullptr;
2364   if (!FirstLaneOnly && State.VF.isScalable()) {
2365     VecIVTy = VectorType::get(ScalarIVTy, State.VF);
2366     UnitStepVec =
2367         Builder.CreateStepVector(VectorType::get(IntStepTy, State.VF));
2368     SplatStep = Builder.CreateVectorSplat(State.VF, Step);
2369     SplatIV = Builder.CreateVectorSplat(State.VF, ScalarIV);
2370   }
2371 
2372   for (unsigned Part = 0; Part < State.UF; ++Part) {
2373     Value *StartIdx0 = createStepForVF(Builder, IntStepTy, State.VF, Part);
2374 
2375     if (!FirstLaneOnly && State.VF.isScalable()) {
2376       auto *SplatStartIdx = Builder.CreateVectorSplat(State.VF, StartIdx0);
2377       auto *InitVec = Builder.CreateAdd(SplatStartIdx, UnitStepVec);
2378       if (ScalarIVTy->isFloatingPointTy())
2379         InitVec = Builder.CreateSIToFP(InitVec, VecIVTy);
2380       auto *Mul = Builder.CreateBinOp(MulOp, InitVec, SplatStep);
2381       auto *Add = Builder.CreateBinOp(AddOp, SplatIV, Mul);
2382       State.set(Def, Add, Part);
2383       // It's useful to record the lane values too for the known minimum number
2384       // of elements so we do those below. This improves the code quality when
2385       // trying to extract the first element, for example.
2386     }
2387 
2388     if (ScalarIVTy->isFloatingPointTy())
2389       StartIdx0 = Builder.CreateSIToFP(StartIdx0, ScalarIVTy);
2390 
2391     for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
2392       Value *StartIdx = Builder.CreateBinOp(
2393           AddOp, StartIdx0, getSignedIntOrFpConstant(ScalarIVTy, Lane));
2394       // The step returned by `createStepForVF` is a runtime-evaluated value
2395       // when VF is scalable. Otherwise, it should be folded into a Constant.
2396       assert((State.VF.isScalable() || isa<Constant>(StartIdx)) &&
2397              "Expected StartIdx to be folded to a constant when VF is not "
2398              "scalable");
2399       auto *Mul = Builder.CreateBinOp(MulOp, StartIdx, Step);
2400       auto *Add = Builder.CreateBinOp(AddOp, ScalarIV, Mul);
2401       State.set(Def, Add, VPIteration(Part, Lane));
2402     }
2403   }
2404 }
2405 
2406 // Generate code for the induction step. Note that induction steps are
2407 // required to be loop-invariant
2408 static Value *CreateStepValue(const SCEV *Step, ScalarEvolution &SE,
2409                               Instruction *InsertBefore,
2410                               Loop *OrigLoop = nullptr) {
2411   const DataLayout &DL = SE.getDataLayout();
2412   assert((!OrigLoop || SE.isLoopInvariant(Step, OrigLoop)) &&
2413          "Induction step should be loop invariant");
2414   if (auto *E = dyn_cast<SCEVUnknown>(Step))
2415     return E->getValue();
2416 
2417   SCEVExpander Exp(SE, DL, "induction");
2418   return Exp.expandCodeFor(Step, Step->getType(), InsertBefore);
2419 }
2420 
2421 /// Compute the transformed value of Index at offset StartValue using step
2422 /// StepValue.
2423 /// For integer induction, returns StartValue + Index * StepValue.
2424 /// For pointer induction, returns StartValue[Index * StepValue].
2425 /// FIXME: The newly created binary instructions should contain nsw/nuw
2426 /// flags, which can be found from the original scalar operations.
2427 static Value *emitTransformedIndex(IRBuilderBase &B, Value *Index,
2428                                    Value *StartValue, Value *Step,
2429                                    const InductionDescriptor &ID) {
2430   assert(Index->getType()->getScalarType() == Step->getType() &&
2431          "Index scalar type does not match StepValue type");
2432 
2433   // Note: the IR at this point is broken. We cannot use SE to create any new
2434   // SCEV and then expand it, hoping that SCEV's simplification will give us
2435   // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
2436   // lead to various SCEV crashes. So all we can do is to use builder and rely
2437   // on InstCombine for future simplifications. Here we handle some trivial
2438   // cases only.
2439   auto CreateAdd = [&B](Value *X, Value *Y) {
2440     assert(X->getType() == Y->getType() && "Types don't match!");
2441     if (auto *CX = dyn_cast<ConstantInt>(X))
2442       if (CX->isZero())
2443         return Y;
2444     if (auto *CY = dyn_cast<ConstantInt>(Y))
2445       if (CY->isZero())
2446         return X;
2447     return B.CreateAdd(X, Y);
2448   };
2449 
2450   // We allow X to be a vector type, in which case Y will potentially be
2451   // splatted into a vector with the same element count.
2452   auto CreateMul = [&B](Value *X, Value *Y) {
2453     assert(X->getType()->getScalarType() == Y->getType() &&
2454            "Types don't match!");
2455     if (auto *CX = dyn_cast<ConstantInt>(X))
2456       if (CX->isOne())
2457         return Y;
2458     if (auto *CY = dyn_cast<ConstantInt>(Y))
2459       if (CY->isOne())
2460         return X;
2461     VectorType *XVTy = dyn_cast<VectorType>(X->getType());
2462     if (XVTy && !isa<VectorType>(Y->getType()))
2463       Y = B.CreateVectorSplat(XVTy->getElementCount(), Y);
2464     return B.CreateMul(X, Y);
2465   };
2466 
2467   switch (ID.getKind()) {
2468   case InductionDescriptor::IK_IntInduction: {
2469     assert(!isa<VectorType>(Index->getType()) &&
2470            "Vector indices not supported for integer inductions yet");
2471     assert(Index->getType() == StartValue->getType() &&
2472            "Index type does not match StartValue type");
2473     if (isa<ConstantInt>(Step) && cast<ConstantInt>(Step)->isMinusOne())
2474       return B.CreateSub(StartValue, Index);
2475     auto *Offset = CreateMul(Index, Step);
2476     return CreateAdd(StartValue, Offset);
2477   }
2478   case InductionDescriptor::IK_PtrInduction: {
2479     assert(isa<Constant>(Step) &&
2480            "Expected constant step for pointer induction");
2481     return B.CreateGEP(ID.getElementType(), StartValue, CreateMul(Index, Step));
2482   }
2483   case InductionDescriptor::IK_FpInduction: {
2484     assert(!isa<VectorType>(Index->getType()) &&
2485            "Vector indices not supported for FP inductions yet");
2486     assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
2487     auto InductionBinOp = ID.getInductionBinOp();
2488     assert(InductionBinOp &&
2489            (InductionBinOp->getOpcode() == Instruction::FAdd ||
2490             InductionBinOp->getOpcode() == Instruction::FSub) &&
2491            "Original bin op should be defined for FP induction");
2492 
2493     Value *MulExp = B.CreateFMul(Step, Index);
2494     return B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
2495                          "induction");
2496   }
2497   case InductionDescriptor::IK_NoInduction:
2498     return nullptr;
2499   }
2500   llvm_unreachable("invalid enum");
2501 }
2502 
2503 void InnerLoopVectorizer::packScalarIntoVectorValue(VPValue *Def,
2504                                                     const VPIteration &Instance,
2505                                                     VPTransformState &State) {
2506   Value *ScalarInst = State.get(Def, Instance);
2507   Value *VectorValue = State.get(Def, Instance.Part);
2508   VectorValue = Builder.CreateInsertElement(
2509       VectorValue, ScalarInst,
2510       Instance.Lane.getAsRuntimeExpr(State.Builder, VF));
2511   State.set(Def, VectorValue, Instance.Part);
2512 }
2513 
2514 // Return whether we allow using masked interleave-groups (for dealing with
2515 // strided loads/stores that reside in predicated blocks, or for dealing
2516 // with gaps).
2517 static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
2518   // If an override option has been passed in for interleaved accesses, use it.
2519   if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
2520     return EnableMaskedInterleavedMemAccesses;
2521 
2522   return TTI.enableMaskedInterleavedAccessVectorization();
2523 }
2524 
2525 // Try to vectorize the interleave group that \p Instr belongs to.
2526 //
2527 // E.g. Translate following interleaved load group (factor = 3):
2528 //   for (i = 0; i < N; i+=3) {
2529 //     R = Pic[i];             // Member of index 0
2530 //     G = Pic[i+1];           // Member of index 1
2531 //     B = Pic[i+2];           // Member of index 2
2532 //     ... // do something to R, G, B
2533 //   }
2534 // To:
2535 //   %wide.vec = load <12 x i32>                       ; Read 4 tuples of R,G,B
2536 //   %R.vec = shuffle %wide.vec, poison, <0, 3, 6, 9>   ; R elements
2537 //   %G.vec = shuffle %wide.vec, poison, <1, 4, 7, 10>  ; G elements
2538 //   %B.vec = shuffle %wide.vec, poison, <2, 5, 8, 11>  ; B elements
2539 //
2540 // Or translate following interleaved store group (factor = 3):
2541 //   for (i = 0; i < N; i+=3) {
2542 //     ... do something to R, G, B
2543 //     Pic[i]   = R;           // Member of index 0
2544 //     Pic[i+1] = G;           // Member of index 1
2545 //     Pic[i+2] = B;           // Member of index 2
2546 //   }
2547 // To:
2548 //   %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
2549 //   %B_U.vec = shuffle %B.vec, poison, <0, 1, 2, 3, u, u, u, u>
2550 //   %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
2551 //        <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>    ; Interleave R,G,B elements
2552 //   store <12 x i32> %interleaved.vec              ; Write 4 tuples of R,G,B
2553 void InnerLoopVectorizer::vectorizeInterleaveGroup(
2554     const InterleaveGroup<Instruction> *Group, ArrayRef<VPValue *> VPDefs,
2555     VPTransformState &State, VPValue *Addr, ArrayRef<VPValue *> StoredValues,
2556     VPValue *BlockInMask) {
2557   Instruction *Instr = Group->getInsertPos();
2558   const DataLayout &DL = Instr->getModule()->getDataLayout();
2559 
2560   // Prepare for the vector type of the interleaved load/store.
2561   Type *ScalarTy = getLoadStoreType(Instr);
2562   unsigned InterleaveFactor = Group->getFactor();
2563   assert(!VF.isScalable() && "scalable vectors not yet supported.");
2564   auto *VecTy = VectorType::get(ScalarTy, VF * InterleaveFactor);
2565 
2566   // Prepare for the new pointers.
2567   SmallVector<Value *, 2> AddrParts;
2568   unsigned Index = Group->getIndex(Instr);
2569 
2570   // TODO: extend the masked interleaved-group support to reversed access.
2571   assert((!BlockInMask || !Group->isReverse()) &&
2572          "Reversed masked interleave-group not supported.");
2573 
2574   // If the group is reverse, adjust the index to refer to the last vector lane
2575   // instead of the first. We adjust the index from the first vector lane,
2576   // rather than directly getting the pointer for lane VF - 1, because the
2577   // pointer operand of the interleaved access is supposed to be uniform. For
2578   // uniform instructions, we're only required to generate a value for the
2579   // first vector lane in each unroll iteration.
2580   if (Group->isReverse())
2581     Index += (VF.getKnownMinValue() - 1) * Group->getFactor();
2582 
2583   for (unsigned Part = 0; Part < UF; Part++) {
2584     Value *AddrPart = State.get(Addr, VPIteration(Part, 0));
2585     setDebugLocFromInst(AddrPart);
2586 
2587     // Notice current instruction could be any index. Need to adjust the address
2588     // to the member of index 0.
2589     //
2590     // E.g.  a = A[i+1];     // Member of index 1 (Current instruction)
2591     //       b = A[i];       // Member of index 0
2592     // Current pointer is pointed to A[i+1], adjust it to A[i].
2593     //
2594     // E.g.  A[i+1] = a;     // Member of index 1
2595     //       A[i]   = b;     // Member of index 0
2596     //       A[i+2] = c;     // Member of index 2 (Current instruction)
2597     // Current pointer is pointed to A[i+2], adjust it to A[i].
2598 
2599     bool InBounds = false;
2600     if (auto *gep = dyn_cast<GetElementPtrInst>(AddrPart->stripPointerCasts()))
2601       InBounds = gep->isInBounds();
2602     AddrPart = Builder.CreateGEP(ScalarTy, AddrPart, Builder.getInt32(-Index));
2603     cast<GetElementPtrInst>(AddrPart)->setIsInBounds(InBounds);
2604 
2605     // Cast to the vector pointer type.
2606     unsigned AddressSpace = AddrPart->getType()->getPointerAddressSpace();
2607     Type *PtrTy = VecTy->getPointerTo(AddressSpace);
2608     AddrParts.push_back(Builder.CreateBitCast(AddrPart, PtrTy));
2609   }
2610 
2611   setDebugLocFromInst(Instr);
2612   Value *PoisonVec = PoisonValue::get(VecTy);
2613 
2614   Value *MaskForGaps = nullptr;
2615   if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
2616     MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2617     assert(MaskForGaps && "Mask for Gaps is required but it is null");
2618   }
2619 
2620   // Vectorize the interleaved load group.
2621   if (isa<LoadInst>(Instr)) {
2622     // For each unroll part, create a wide load for the group.
2623     SmallVector<Value *, 2> NewLoads;
2624     for (unsigned Part = 0; Part < UF; Part++) {
2625       Instruction *NewLoad;
2626       if (BlockInMask || MaskForGaps) {
2627         assert(useMaskedInterleavedAccesses(*TTI) &&
2628                "masked interleaved groups are not allowed.");
2629         Value *GroupMask = MaskForGaps;
2630         if (BlockInMask) {
2631           Value *BlockInMaskPart = State.get(BlockInMask, Part);
2632           Value *ShuffledMask = Builder.CreateShuffleVector(
2633               BlockInMaskPart,
2634               createReplicatedMask(InterleaveFactor, VF.getKnownMinValue()),
2635               "interleaved.mask");
2636           GroupMask = MaskForGaps
2637                           ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
2638                                                 MaskForGaps)
2639                           : ShuffledMask;
2640         }
2641         NewLoad =
2642             Builder.CreateMaskedLoad(VecTy, AddrParts[Part], Group->getAlign(),
2643                                      GroupMask, PoisonVec, "wide.masked.vec");
2644       }
2645       else
2646         NewLoad = Builder.CreateAlignedLoad(VecTy, AddrParts[Part],
2647                                             Group->getAlign(), "wide.vec");
2648       Group->addMetadata(NewLoad);
2649       NewLoads.push_back(NewLoad);
2650     }
2651 
2652     // For each member in the group, shuffle out the appropriate data from the
2653     // wide loads.
2654     unsigned J = 0;
2655     for (unsigned I = 0; I < InterleaveFactor; ++I) {
2656       Instruction *Member = Group->getMember(I);
2657 
2658       // Skip the gaps in the group.
2659       if (!Member)
2660         continue;
2661 
2662       auto StrideMask =
2663           createStrideMask(I, InterleaveFactor, VF.getKnownMinValue());
2664       for (unsigned Part = 0; Part < UF; Part++) {
2665         Value *StridedVec = Builder.CreateShuffleVector(
2666             NewLoads[Part], StrideMask, "strided.vec");
2667 
2668         // If this member has different type, cast the result type.
2669         if (Member->getType() != ScalarTy) {
2670           assert(!VF.isScalable() && "VF is assumed to be non scalable.");
2671           VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
2672           StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
2673         }
2674 
2675         if (Group->isReverse())
2676           StridedVec = Builder.CreateVectorReverse(StridedVec, "reverse");
2677 
2678         State.set(VPDefs[J], StridedVec, Part);
2679       }
2680       ++J;
2681     }
2682     return;
2683   }
2684 
2685   // The sub vector type for current instruction.
2686   auto *SubVT = VectorType::get(ScalarTy, VF);
2687 
2688   // Vectorize the interleaved store group.
2689   MaskForGaps = createBitMaskForGaps(Builder, VF.getKnownMinValue(), *Group);
2690   assert((!MaskForGaps || useMaskedInterleavedAccesses(*TTI)) &&
2691          "masked interleaved groups are not allowed.");
2692   assert((!MaskForGaps || !VF.isScalable()) &&
2693          "masking gaps for scalable vectors is not yet supported.");
2694   for (unsigned Part = 0; Part < UF; Part++) {
2695     // Collect the stored vector from each member.
2696     SmallVector<Value *, 4> StoredVecs;
2697     for (unsigned i = 0; i < InterleaveFactor; i++) {
2698       assert((Group->getMember(i) || MaskForGaps) &&
2699              "Fail to get a member from an interleaved store group");
2700       Instruction *Member = Group->getMember(i);
2701 
2702       // Skip the gaps in the group.
2703       if (!Member) {
2704         Value *Undef = PoisonValue::get(SubVT);
2705         StoredVecs.push_back(Undef);
2706         continue;
2707       }
2708 
2709       Value *StoredVec = State.get(StoredValues[i], Part);
2710 
2711       if (Group->isReverse())
2712         StoredVec = Builder.CreateVectorReverse(StoredVec, "reverse");
2713 
2714       // If this member has different type, cast it to a unified type.
2715 
2716       if (StoredVec->getType() != SubVT)
2717         StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
2718 
2719       StoredVecs.push_back(StoredVec);
2720     }
2721 
2722     // Concatenate all vectors into a wide vector.
2723     Value *WideVec = concatenateVectors(Builder, StoredVecs);
2724 
2725     // Interleave the elements in the wide vector.
2726     Value *IVec = Builder.CreateShuffleVector(
2727         WideVec, createInterleaveMask(VF.getKnownMinValue(), InterleaveFactor),
2728         "interleaved.vec");
2729 
2730     Instruction *NewStoreInstr;
2731     if (BlockInMask || MaskForGaps) {
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 ? Builder.CreateBinOp(Instruction::And,
2740                                                       ShuffledMask, MaskForGaps)
2741                                 : ShuffledMask;
2742       }
2743       NewStoreInstr = Builder.CreateMaskedStore(IVec, AddrParts[Part],
2744                                                 Group->getAlign(), GroupMask);
2745     } else
2746       NewStoreInstr =
2747           Builder.CreateAlignedStore(IVec, AddrParts[Part], Group->getAlign());
2748 
2749     Group->addMetadata(NewStoreInstr);
2750   }
2751 }
2752 
2753 void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
2754                                                VPReplicateRecipe *RepRecipe,
2755                                                const VPIteration &Instance,
2756                                                bool IfPredicateInstr,
2757                                                VPTransformState &State) {
2758   assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
2759 
2760   // llvm.experimental.noalias.scope.decl intrinsics must only be duplicated for
2761   // the first lane and part.
2762   if (isa<NoAliasScopeDeclInst>(Instr))
2763     if (!Instance.isFirstIteration())
2764       return;
2765 
2766   // Does this instruction return a value ?
2767   bool IsVoidRetTy = Instr->getType()->isVoidTy();
2768 
2769   Instruction *Cloned = Instr->clone();
2770   if (!IsVoidRetTy)
2771     Cloned->setName(Instr->getName() + ".cloned");
2772 
2773   // If the scalarized instruction contributes to the address computation of a
2774   // widen masked load/store which was in a basic block that needed predication
2775   // and is not predicated after vectorization, we can't propagate
2776   // poison-generating flags (nuw/nsw, exact, inbounds, etc.). The scalarized
2777   // instruction could feed a poison value to the base address of the widen
2778   // load/store.
2779   if (State.MayGeneratePoisonRecipes.contains(RepRecipe))
2780     Cloned->dropPoisonGeneratingFlags();
2781 
2782   if (Instr->getDebugLoc())
2783     setDebugLocFromInst(Instr);
2784 
2785   // Replace the operands of the cloned instructions with their scalar
2786   // equivalents in the new loop.
2787   for (auto &I : enumerate(RepRecipe->operands())) {
2788     auto InputInstance = Instance;
2789     VPValue *Operand = I.value();
2790     VPReplicateRecipe *OperandR = dyn_cast<VPReplicateRecipe>(Operand);
2791     if (OperandR && OperandR->isUniform())
2792       InputInstance.Lane = VPLane::getFirstLane();
2793     Cloned->setOperand(I.index(), State.get(Operand, InputInstance));
2794   }
2795   addNewMetadata(Cloned, Instr);
2796 
2797   // Place the cloned scalar in the new loop.
2798   State.Builder.Insert(Cloned);
2799 
2800   State.set(RepRecipe, Cloned, Instance);
2801 
2802   // If we just cloned a new assumption, add it the assumption cache.
2803   if (auto *II = dyn_cast<AssumeInst>(Cloned))
2804     AC->registerAssumption(II);
2805 
2806   // End if-block.
2807   if (IfPredicateInstr)
2808     PredicatedInstructions.push_back(Cloned);
2809 }
2810 
2811 Value *InnerLoopVectorizer::getOrCreateTripCount(BasicBlock *InsertBlock) {
2812   if (TripCount)
2813     return TripCount;
2814 
2815   assert(InsertBlock);
2816   IRBuilder<> Builder(InsertBlock->getTerminator());
2817   // Find the loop boundaries.
2818   ScalarEvolution *SE = PSE.getSE();
2819   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
2820   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
2821          "Invalid loop count");
2822 
2823   Type *IdxTy = Legal->getWidestInductionType();
2824   assert(IdxTy && "No type for induction");
2825 
2826   // The exit count might have the type of i64 while the phi is i32. This can
2827   // happen if we have an induction variable that is sign extended before the
2828   // compare. The only way that we get a backedge taken count is that the
2829   // induction variable was signed and as such will not overflow. In such a case
2830   // truncation is legal.
2831   if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) >
2832       IdxTy->getPrimitiveSizeInBits())
2833     BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
2834   BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
2835 
2836   // Get the total trip count from the count by adding 1.
2837   const SCEV *ExitCount = SE->getAddExpr(
2838       BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
2839 
2840   const DataLayout &DL = InsertBlock->getModule()->getDataLayout();
2841 
2842   // Expand the trip count and place the new instructions in the preheader.
2843   // Notice that the pre-header does not change, only the loop body.
2844   SCEVExpander Exp(*SE, DL, "induction");
2845 
2846   // Count holds the overall loop count (N).
2847   TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
2848                                 InsertBlock->getTerminator());
2849 
2850   if (TripCount->getType()->isPointerTy())
2851     TripCount =
2852         CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
2853                                     InsertBlock->getTerminator());
2854 
2855   return TripCount;
2856 }
2857 
2858 Value *
2859 InnerLoopVectorizer::getOrCreateVectorTripCount(BasicBlock *InsertBlock) {
2860   if (VectorTripCount)
2861     return VectorTripCount;
2862 
2863   Value *TC = getOrCreateTripCount(InsertBlock);
2864   IRBuilder<> Builder(InsertBlock->getTerminator());
2865 
2866   Type *Ty = TC->getType();
2867   // This is where we can make the step a runtime constant.
2868   Value *Step = createStepForVF(Builder, Ty, VF, UF);
2869 
2870   // If the tail is to be folded by masking, round the number of iterations N
2871   // up to a multiple of Step instead of rounding down. This is done by first
2872   // adding Step-1 and then rounding down. Note that it's ok if this addition
2873   // overflows: the vector induction variable will eventually wrap to zero given
2874   // that it starts at zero and its Step is a power of two; the loop will then
2875   // exit, with the last early-exit vector comparison also producing all-true.
2876   // For scalable vectors the VF is not guaranteed to be a power of 2, but this
2877   // is accounted for in emitIterationCountCheck that adds an overflow check.
2878   if (Cost->foldTailByMasking()) {
2879     assert(isPowerOf2_32(VF.getKnownMinValue() * UF) &&
2880            "VF*UF must be a power of 2 when folding tail by masking");
2881     Value *NumLanes = getRuntimeVF(Builder, Ty, VF * UF);
2882     TC = Builder.CreateAdd(
2883         TC, Builder.CreateSub(NumLanes, ConstantInt::get(Ty, 1)), "n.rnd.up");
2884   }
2885 
2886   // Now we need to generate the expression for the part of the loop that the
2887   // vectorized body will execute. This is equal to N - (N % Step) if scalar
2888   // iterations are not required for correctness, or N - Step, otherwise. Step
2889   // is equal to the vectorization factor (number of SIMD elements) times the
2890   // unroll factor (number of SIMD instructions).
2891   Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
2892 
2893   // There are cases where we *must* run at least one iteration in the remainder
2894   // loop.  See the cost model for when this can happen.  If the step evenly
2895   // divides the trip count, we set the remainder to be equal to the step. If
2896   // the step does not evenly divide the trip count, no adjustment is necessary
2897   // since there will already be scalar iterations. Note that the minimum
2898   // iterations check ensures that N >= Step.
2899   if (Cost->requiresScalarEpilogue(VF)) {
2900     auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
2901     R = Builder.CreateSelect(IsZero, Step, R);
2902   }
2903 
2904   VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
2905 
2906   return VectorTripCount;
2907 }
2908 
2909 Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
2910                                                    const DataLayout &DL) {
2911   // Verify that V is a vector type with same number of elements as DstVTy.
2912   auto *DstFVTy = cast<FixedVectorType>(DstVTy);
2913   unsigned VF = DstFVTy->getNumElements();
2914   auto *SrcVecTy = cast<FixedVectorType>(V->getType());
2915   assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
2916   Type *SrcElemTy = SrcVecTy->getElementType();
2917   Type *DstElemTy = DstFVTy->getElementType();
2918   assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
2919          "Vector elements must have same size");
2920 
2921   // Do a direct cast if element types are castable.
2922   if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
2923     return Builder.CreateBitOrPointerCast(V, DstFVTy);
2924   }
2925   // V cannot be directly casted to desired vector type.
2926   // May happen when V is a floating point vector but DstVTy is a vector of
2927   // pointers or vice-versa. Handle this using a two-step bitcast using an
2928   // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
2929   assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
2930          "Only one type should be a pointer type");
2931   assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
2932          "Only one type should be a floating point type");
2933   Type *IntTy =
2934       IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
2935   auto *VecIntTy = FixedVectorType::get(IntTy, VF);
2936   Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
2937   return Builder.CreateBitOrPointerCast(CastVal, DstFVTy);
2938 }
2939 
2940 void InnerLoopVectorizer::emitIterationCountCheck(BasicBlock *Bypass) {
2941   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
2942   // Reuse existing vector loop preheader for TC checks.
2943   // Note that new preheader block is generated for vector loop.
2944   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
2945   IRBuilder<> Builder(TCCheckBlock->getTerminator());
2946 
2947   // Generate code to check if the loop's trip count is less than VF * UF, or
2948   // equal to it in case a scalar epilogue is required; this implies that the
2949   // vector trip count is zero. This check also covers the case where adding one
2950   // to the backedge-taken count overflowed leading to an incorrect trip count
2951   // of zero. In this case we will also jump to the scalar loop.
2952   auto P = Cost->requiresScalarEpilogue(VF) ? ICmpInst::ICMP_ULE
2953                                             : ICmpInst::ICMP_ULT;
2954 
2955   // If tail is to be folded, vector loop takes care of all iterations.
2956   Type *CountTy = Count->getType();
2957   Value *CheckMinIters = Builder.getFalse();
2958   Value *Step = createStepForVF(Builder, CountTy, VF, UF);
2959   if (!Cost->foldTailByMasking())
2960     CheckMinIters = Builder.CreateICmp(P, Count, Step, "min.iters.check");
2961   else if (VF.isScalable()) {
2962     // vscale is not necessarily a power-of-2, which means we cannot guarantee
2963     // an overflow to zero when updating induction variables and so an
2964     // additional overflow check is required before entering the vector loop.
2965 
2966     // Get the maximum unsigned value for the type.
2967     Value *MaxUIntTripCount =
2968         ConstantInt::get(CountTy, cast<IntegerType>(CountTy)->getMask());
2969     Value *LHS = Builder.CreateSub(MaxUIntTripCount, Count);
2970 
2971     // Don't execute the vector loop if (UMax - n) < (VF * UF).
2972     CheckMinIters = Builder.CreateICmp(ICmpInst::ICMP_ULT, LHS, Step);
2973   }
2974   // Create new preheader for vector loop.
2975   LoopVectorPreHeader =
2976       SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(), DT, LI, nullptr,
2977                  "vector.ph");
2978 
2979   assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
2980                                DT->getNode(Bypass)->getIDom()) &&
2981          "TC check is expected to dominate Bypass");
2982 
2983   // Update dominator for Bypass & LoopExit (if needed).
2984   DT->changeImmediateDominator(Bypass, TCCheckBlock);
2985   if (!Cost->requiresScalarEpilogue(VF))
2986     // If there is an epilogue which must run, there's no edge from the
2987     // middle block to exit blocks  and thus no need to update the immediate
2988     // dominator of the exit blocks.
2989     DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
2990 
2991   ReplaceInstWithInst(
2992       TCCheckBlock->getTerminator(),
2993       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
2994   LoopBypassBlocks.push_back(TCCheckBlock);
2995 }
2996 
2997 BasicBlock *InnerLoopVectorizer::emitSCEVChecks(BasicBlock *Bypass) {
2998 
2999   BasicBlock *const SCEVCheckBlock =
3000       RTChecks.emitSCEVChecks(Bypass, LoopVectorPreHeader, LoopExitBlock);
3001   if (!SCEVCheckBlock)
3002     return nullptr;
3003 
3004   assert(!(SCEVCheckBlock->getParent()->hasOptSize() ||
3005            (OptForSizeBasedOnProfile &&
3006             Cost->Hints->getForce() != LoopVectorizeHints::FK_Enabled)) &&
3007          "Cannot SCEV check stride or overflow when optimizing for size");
3008 
3009 
3010   // Update dominator only if this is first RT check.
3011   if (LoopBypassBlocks.empty()) {
3012     DT->changeImmediateDominator(Bypass, SCEVCheckBlock);
3013     if (!Cost->requiresScalarEpilogue(VF))
3014       // If there is an epilogue which must run, there's no edge from the
3015       // middle block to exit blocks  and thus no need to update the immediate
3016       // dominator of the exit blocks.
3017       DT->changeImmediateDominator(LoopExitBlock, SCEVCheckBlock);
3018   }
3019 
3020   LoopBypassBlocks.push_back(SCEVCheckBlock);
3021   AddedSafetyChecks = true;
3022   return SCEVCheckBlock;
3023 }
3024 
3025 BasicBlock *InnerLoopVectorizer::emitMemRuntimeChecks(BasicBlock *Bypass) {
3026   // VPlan-native path does not do any analysis for runtime checks currently.
3027   if (EnableVPlanNativePath)
3028     return nullptr;
3029 
3030   BasicBlock *const MemCheckBlock =
3031       RTChecks.emitMemRuntimeChecks(Bypass, LoopVectorPreHeader);
3032 
3033   // Check if we generated code that checks in runtime if arrays overlap. We put
3034   // the checks into a separate block to make the more common case of few
3035   // elements faster.
3036   if (!MemCheckBlock)
3037     return nullptr;
3038 
3039   if (MemCheckBlock->getParent()->hasOptSize() || OptForSizeBasedOnProfile) {
3040     assert(Cost->Hints->getForce() == LoopVectorizeHints::FK_Enabled &&
3041            "Cannot emit memory checks when optimizing for size, unless forced "
3042            "to vectorize.");
3043     ORE->emit([&]() {
3044       return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationCodeSize",
3045                                         OrigLoop->getStartLoc(),
3046                                         OrigLoop->getHeader())
3047              << "Code-size may be reduced by not forcing "
3048                 "vectorization, or by source-code modifications "
3049                 "eliminating the need for runtime checks "
3050                 "(e.g., adding 'restrict').";
3051     });
3052   }
3053 
3054   LoopBypassBlocks.push_back(MemCheckBlock);
3055 
3056   AddedSafetyChecks = true;
3057 
3058   return MemCheckBlock;
3059 }
3060 
3061 void InnerLoopVectorizer::createVectorLoopSkeleton(StringRef Prefix) {
3062   LoopScalarBody = OrigLoop->getHeader();
3063   LoopVectorPreHeader = OrigLoop->getLoopPreheader();
3064   assert(LoopVectorPreHeader && "Invalid loop structure");
3065   LoopExitBlock = OrigLoop->getUniqueExitBlock(); // may be nullptr
3066   assert((LoopExitBlock || Cost->requiresScalarEpilogue(VF)) &&
3067          "multiple exit loop without required epilogue?");
3068 
3069   LoopMiddleBlock =
3070       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
3071                  LI, nullptr, Twine(Prefix) + "middle.block");
3072   LoopScalarPreHeader =
3073       SplitBlock(LoopMiddleBlock, LoopMiddleBlock->getTerminator(), DT, LI,
3074                  nullptr, Twine(Prefix) + "scalar.ph");
3075 
3076   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3077 
3078   // Set up the middle block terminator.  Two cases:
3079   // 1) If we know that we must execute the scalar epilogue, emit an
3080   //    unconditional branch.
3081   // 2) Otherwise, we must have a single unique exit block (due to how we
3082   //    implement the multiple exit case).  In this case, set up a conditonal
3083   //    branch from the middle block to the loop scalar preheader, and the
3084   //    exit block.  completeLoopSkeleton will update the condition to use an
3085   //    iteration check, if required to decide whether to execute the remainder.
3086   BranchInst *BrInst = Cost->requiresScalarEpilogue(VF) ?
3087     BranchInst::Create(LoopScalarPreHeader) :
3088     BranchInst::Create(LoopExitBlock, LoopScalarPreHeader,
3089                        Builder.getTrue());
3090   BrInst->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3091   ReplaceInstWithInst(LoopMiddleBlock->getTerminator(), BrInst);
3092 
3093   // Update dominator for loop exit. During skeleton creation, only the vector
3094   // pre-header and the middle block are created. The vector loop is entirely
3095   // created during VPlan exection.
3096   if (!Cost->requiresScalarEpilogue(VF))
3097     // If there is an epilogue which must run, there's no edge from the
3098     // middle block to exit blocks  and thus no need to update the immediate
3099     // dominator of the exit blocks.
3100     DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
3101 }
3102 
3103 void InnerLoopVectorizer::createInductionResumeValues(
3104     std::pair<BasicBlock *, Value *> AdditionalBypass) {
3105   assert(((AdditionalBypass.first && AdditionalBypass.second) ||
3106           (!AdditionalBypass.first && !AdditionalBypass.second)) &&
3107          "Inconsistent information about additional bypass.");
3108 
3109   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3110   assert(VectorTripCount && "Expected valid arguments");
3111   // We are going to resume the execution of the scalar loop.
3112   // Go over all of the induction variables that we found and fix the
3113   // PHIs that are left in the scalar version of the loop.
3114   // The starting values of PHI nodes depend on the counter of the last
3115   // iteration in the vectorized loop.
3116   // If we come from a bypass edge then we need to start from the original
3117   // start value.
3118   Instruction *OldInduction = Legal->getPrimaryInduction();
3119   for (auto &InductionEntry : Legal->getInductionVars()) {
3120     PHINode *OrigPhi = InductionEntry.first;
3121     InductionDescriptor II = InductionEntry.second;
3122 
3123     Value *&EndValue = IVEndValues[OrigPhi];
3124     Value *EndValueFromAdditionalBypass = AdditionalBypass.second;
3125     if (OrigPhi == OldInduction) {
3126       // We know what the end value is.
3127       EndValue = VectorTripCount;
3128     } else {
3129       IRBuilder<> B(LoopVectorPreHeader->getTerminator());
3130 
3131       // Fast-math-flags propagate from the original induction instruction.
3132       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3133         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3134 
3135       Type *StepType = II.getStep()->getType();
3136       Instruction::CastOps CastOp =
3137           CastInst::getCastOpcode(VectorTripCount, true, StepType, true);
3138       Value *VTC = B.CreateCast(CastOp, VectorTripCount, StepType, "cast.vtc");
3139       Value *Step =
3140           CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3141       EndValue = emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3142       EndValue->setName("ind.end");
3143 
3144       // Compute the end value for the additional bypass (if applicable).
3145       if (AdditionalBypass.first) {
3146         B.SetInsertPoint(&(*AdditionalBypass.first->getFirstInsertionPt()));
3147         CastOp = CastInst::getCastOpcode(AdditionalBypass.second, true,
3148                                          StepType, true);
3149         Value *Step =
3150             CreateStepValue(II.getStep(), *PSE.getSE(), &*B.GetInsertPoint());
3151         VTC =
3152             B.CreateCast(CastOp, AdditionalBypass.second, StepType, "cast.vtc");
3153         EndValueFromAdditionalBypass =
3154             emitTransformedIndex(B, VTC, II.getStartValue(), Step, II);
3155         EndValueFromAdditionalBypass->setName("ind.end");
3156       }
3157     }
3158 
3159     // Create phi nodes to merge from the  backedge-taken check block.
3160     PHINode *BCResumeVal =
3161         PHINode::Create(OrigPhi->getType(), 3, "bc.resume.val",
3162                         LoopScalarPreHeader->getTerminator());
3163     // Copy original phi DL over to the new one.
3164     BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
3165 
3166     // The new PHI merges the original incoming value, in case of a bypass,
3167     // or the value at the end of the vectorized loop.
3168     BCResumeVal->addIncoming(EndValue, LoopMiddleBlock);
3169 
3170     // Fix the scalar body counter (PHI node).
3171     // The old induction's phi node in the scalar body needs the truncated
3172     // value.
3173     for (BasicBlock *BB : LoopBypassBlocks)
3174       BCResumeVal->addIncoming(II.getStartValue(), BB);
3175 
3176     if (AdditionalBypass.first)
3177       BCResumeVal->setIncomingValueForBlock(AdditionalBypass.first,
3178                                             EndValueFromAdditionalBypass);
3179 
3180     OrigPhi->setIncomingValueForBlock(LoopScalarPreHeader, BCResumeVal);
3181   }
3182 }
3183 
3184 BasicBlock *InnerLoopVectorizer::completeLoopSkeleton(MDNode *OrigLoopID) {
3185   // The trip counts should be cached by now.
3186   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
3187   Value *VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
3188 
3189   auto *ScalarLatchTerm = OrigLoop->getLoopLatch()->getTerminator();
3190 
3191   // Add a check in the middle block to see if we have completed
3192   // all of the iterations in the first vector loop.  Three cases:
3193   // 1) If we require a scalar epilogue, there is no conditional branch as
3194   //    we unconditionally branch to the scalar preheader.  Do nothing.
3195   // 2) If (N - N%VF) == N, then we *don't* need to run the remainder.
3196   //    Thus if tail is to be folded, we know we don't need to run the
3197   //    remainder and we can use the previous value for the condition (true).
3198   // 3) Otherwise, construct a runtime check.
3199   if (!Cost->requiresScalarEpilogue(VF) && !Cost->foldTailByMasking()) {
3200     Instruction *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ,
3201                                         Count, VectorTripCount, "cmp.n",
3202                                         LoopMiddleBlock->getTerminator());
3203 
3204     // Here we use the same DebugLoc as the scalar loop latch terminator instead
3205     // of the corresponding compare because they may have ended up with
3206     // different line numbers and we want to avoid awkward line stepping while
3207     // debugging. Eg. if the compare has got a line number inside the loop.
3208     CmpN->setDebugLoc(ScalarLatchTerm->getDebugLoc());
3209     cast<BranchInst>(LoopMiddleBlock->getTerminator())->setCondition(CmpN);
3210   }
3211 
3212 #ifdef EXPENSIVE_CHECKS
3213   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
3214 #endif
3215 
3216   return LoopVectorPreHeader;
3217 }
3218 
3219 std::pair<BasicBlock *, Value *>
3220 InnerLoopVectorizer::createVectorizedLoopSkeleton() {
3221   /*
3222    In this function we generate a new loop. The new loop will contain
3223    the vectorized instructions while the old loop will continue to run the
3224    scalar remainder.
3225 
3226        [ ] <-- loop iteration number check.
3227     /   |
3228    /    v
3229   |    [ ] <-- vector loop bypass (may consist of multiple blocks).
3230   |  /  |
3231   | /   v
3232   ||   [ ]     <-- vector pre header.
3233   |/    |
3234   |     v
3235   |    [  ] \
3236   |    [  ]_|   <-- vector loop (created during VPlan execution).
3237   |     |
3238   |     v
3239   \   -[ ]   <--- middle-block.
3240    \/   |
3241    /\   v
3242    | ->[ ]     <--- new preheader.
3243    |    |
3244  (opt)  v      <-- edge from middle to exit iff epilogue is not required.
3245    |   [ ] \
3246    |   [ ]_|   <-- old scalar loop to handle remainder (scalar epilogue).
3247     \   |
3248      \  v
3249       >[ ]     <-- exit block(s).
3250    ...
3251    */
3252 
3253   // Get the metadata of the original loop before it gets modified.
3254   MDNode *OrigLoopID = OrigLoop->getLoopID();
3255 
3256   // Workaround!  Compute the trip count of the original loop and cache it
3257   // before we start modifying the CFG.  This code has a systemic problem
3258   // wherein it tries to run analysis over partially constructed IR; this is
3259   // wrong, and not simply for SCEV.  The trip count of the original loop
3260   // simply happens to be prone to hitting this in practice.  In theory, we
3261   // can hit the same issue for any SCEV, or ValueTracking query done during
3262   // mutation.  See PR49900.
3263   getOrCreateTripCount(OrigLoop->getLoopPreheader());
3264 
3265   // Create an empty vector loop, and prepare basic blocks for the runtime
3266   // checks.
3267   createVectorLoopSkeleton("");
3268 
3269   // Now, compare the new count to zero. If it is zero skip the vector loop and
3270   // jump to the scalar loop. This check also covers the case where the
3271   // backedge-taken count is uint##_max: adding one to it will overflow leading
3272   // to an incorrect trip count of zero. In this (rare) case we will also jump
3273   // to the scalar loop.
3274   emitIterationCountCheck(LoopScalarPreHeader);
3275 
3276   // Generate the code to check any assumptions that we've made for SCEV
3277   // expressions.
3278   emitSCEVChecks(LoopScalarPreHeader);
3279 
3280   // Generate the code that checks in runtime if arrays overlap. We put the
3281   // checks into a separate block to make the more common case of few elements
3282   // faster.
3283   emitMemRuntimeChecks(LoopScalarPreHeader);
3284 
3285   // Emit phis for the new starting index of the scalar loop.
3286   createInductionResumeValues();
3287 
3288   return {completeLoopSkeleton(OrigLoopID), nullptr};
3289 }
3290 
3291 // Fix up external users of the induction variable. At this point, we are
3292 // in LCSSA form, with all external PHIs that use the IV having one input value,
3293 // coming from the remainder loop. We need those PHIs to also have a correct
3294 // value for the IV when arriving directly from the middle block.
3295 void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
3296                                        const InductionDescriptor &II,
3297                                        Value *VectorTripCount, Value *EndValue,
3298                                        BasicBlock *MiddleBlock,
3299                                        BasicBlock *VectorHeader, VPlan &Plan) {
3300   // There are two kinds of external IV usages - those that use the value
3301   // computed in the last iteration (the PHI) and those that use the penultimate
3302   // value (the value that feeds into the phi from the loop latch).
3303   // We allow both, but they, obviously, have different values.
3304 
3305   assert(OrigLoop->getUniqueExitBlock() && "Expected a single exit block");
3306 
3307   DenseMap<Value *, Value *> MissingVals;
3308 
3309   // An external user of the last iteration's value should see the value that
3310   // the remainder loop uses to initialize its own IV.
3311   Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
3312   for (User *U : PostInc->users()) {
3313     Instruction *UI = cast<Instruction>(U);
3314     if (!OrigLoop->contains(UI)) {
3315       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3316       MissingVals[UI] = EndValue;
3317     }
3318   }
3319 
3320   // An external user of the penultimate value need to see EndValue - Step.
3321   // The simplest way to get this is to recompute it from the constituent SCEVs,
3322   // that is Start + (Step * (CRD - 1)).
3323   for (User *U : OrigPhi->users()) {
3324     auto *UI = cast<Instruction>(U);
3325     if (!OrigLoop->contains(UI)) {
3326       assert(isa<PHINode>(UI) && "Expected LCSSA form");
3327 
3328       IRBuilder<> B(MiddleBlock->getTerminator());
3329 
3330       // Fast-math-flags propagate from the original induction instruction.
3331       if (II.getInductionBinOp() && isa<FPMathOperator>(II.getInductionBinOp()))
3332         B.setFastMathFlags(II.getInductionBinOp()->getFastMathFlags());
3333 
3334       Value *CountMinusOne = B.CreateSub(
3335           VectorTripCount, ConstantInt::get(VectorTripCount->getType(), 1));
3336       Value *CMO =
3337           !II.getStep()->getType()->isIntegerTy()
3338               ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
3339                              II.getStep()->getType())
3340               : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
3341       CMO->setName("cast.cmo");
3342 
3343       Value *Step = CreateStepValue(II.getStep(), *PSE.getSE(),
3344                                     VectorHeader->getTerminator());
3345       Value *Escape =
3346           emitTransformedIndex(B, CMO, II.getStartValue(), Step, II);
3347       Escape->setName("ind.escape");
3348       MissingVals[UI] = Escape;
3349     }
3350   }
3351 
3352   for (auto &I : MissingVals) {
3353     PHINode *PHI = cast<PHINode>(I.first);
3354     // One corner case we have to handle is two IVs "chasing" each-other,
3355     // that is %IV2 = phi [...], [ %IV1, %latch ]
3356     // In this case, if IV1 has an external use, we need to avoid adding both
3357     // "last value of IV1" and "penultimate value of IV2". So, verify that we
3358     // don't already have an incoming value for the middle block.
3359     if (PHI->getBasicBlockIndex(MiddleBlock) == -1) {
3360       PHI->addIncoming(I.second, MiddleBlock);
3361       Plan.removeLiveOut(PHI);
3362     }
3363   }
3364 }
3365 
3366 namespace {
3367 
3368 struct CSEDenseMapInfo {
3369   static bool canHandle(const Instruction *I) {
3370     return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
3371            isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
3372   }
3373 
3374   static inline Instruction *getEmptyKey() {
3375     return DenseMapInfo<Instruction *>::getEmptyKey();
3376   }
3377 
3378   static inline Instruction *getTombstoneKey() {
3379     return DenseMapInfo<Instruction *>::getTombstoneKey();
3380   }
3381 
3382   static unsigned getHashValue(const Instruction *I) {
3383     assert(canHandle(I) && "Unknown instruction!");
3384     return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
3385                                                            I->value_op_end()));
3386   }
3387 
3388   static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
3389     if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
3390         LHS == getTombstoneKey() || RHS == getTombstoneKey())
3391       return LHS == RHS;
3392     return LHS->isIdenticalTo(RHS);
3393   }
3394 };
3395 
3396 } // end anonymous namespace
3397 
3398 ///Perform cse of induction variable instructions.
3399 static void cse(BasicBlock *BB) {
3400   // Perform simple cse.
3401   SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
3402   for (Instruction &In : llvm::make_early_inc_range(*BB)) {
3403     if (!CSEDenseMapInfo::canHandle(&In))
3404       continue;
3405 
3406     // Check if we can replace this instruction with any of the
3407     // visited instructions.
3408     if (Instruction *V = CSEMap.lookup(&In)) {
3409       In.replaceAllUsesWith(V);
3410       In.eraseFromParent();
3411       continue;
3412     }
3413 
3414     CSEMap[&In] = &In;
3415   }
3416 }
3417 
3418 InstructionCost
3419 LoopVectorizationCostModel::getVectorCallCost(CallInst *CI, ElementCount VF,
3420                                               bool &NeedToScalarize) const {
3421   Function *F = CI->getCalledFunction();
3422   Type *ScalarRetTy = CI->getType();
3423   SmallVector<Type *, 4> Tys, ScalarTys;
3424   for (auto &ArgOp : CI->args())
3425     ScalarTys.push_back(ArgOp->getType());
3426 
3427   // Estimate cost of scalarized vector call. The source operands are assumed
3428   // to be vectors, so we need to extract individual elements from there,
3429   // execute VF scalar calls, and then gather the result into the vector return
3430   // value.
3431   InstructionCost ScalarCallCost =
3432       TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys, TTI::TCK_RecipThroughput);
3433   if (VF.isScalar())
3434     return ScalarCallCost;
3435 
3436   // Compute corresponding vector type for return value and arguments.
3437   Type *RetTy = ToVectorTy(ScalarRetTy, VF);
3438   for (Type *ScalarTy : ScalarTys)
3439     Tys.push_back(ToVectorTy(ScalarTy, VF));
3440 
3441   // Compute costs of unpacking argument values for the scalar calls and
3442   // packing the return values to a vector.
3443   InstructionCost ScalarizationCost = getScalarizationOverhead(CI, VF);
3444 
3445   InstructionCost Cost =
3446       ScalarCallCost * VF.getKnownMinValue() + ScalarizationCost;
3447 
3448   // If we can't emit a vector call for this function, then the currently found
3449   // cost is the cost we need to return.
3450   NeedToScalarize = true;
3451   VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
3452   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3453 
3454   if (!TLI || CI->isNoBuiltin() || !VecFunc)
3455     return Cost;
3456 
3457   // If the corresponding vector cost is cheaper, return its cost.
3458   InstructionCost VectorCallCost =
3459       TTI.getCallInstrCost(nullptr, RetTy, Tys, TTI::TCK_RecipThroughput);
3460   if (VectorCallCost < Cost) {
3461     NeedToScalarize = false;
3462     Cost = VectorCallCost;
3463   }
3464   return Cost;
3465 }
3466 
3467 static Type *MaybeVectorizeType(Type *Elt, ElementCount VF) {
3468   if (VF.isScalar() || (!Elt->isIntOrPtrTy() && !Elt->isFloatingPointTy()))
3469     return Elt;
3470   return VectorType::get(Elt, VF);
3471 }
3472 
3473 InstructionCost
3474 LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
3475                                                    ElementCount VF) const {
3476   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3477   assert(ID && "Expected intrinsic call!");
3478   Type *RetTy = MaybeVectorizeType(CI->getType(), VF);
3479   FastMathFlags FMF;
3480   if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
3481     FMF = FPMO->getFastMathFlags();
3482 
3483   SmallVector<const Value *> Arguments(CI->args());
3484   FunctionType *FTy = CI->getCalledFunction()->getFunctionType();
3485   SmallVector<Type *> ParamTys;
3486   std::transform(FTy->param_begin(), FTy->param_end(),
3487                  std::back_inserter(ParamTys),
3488                  [&](Type *Ty) { return MaybeVectorizeType(Ty, VF); });
3489 
3490   IntrinsicCostAttributes CostAttrs(ID, RetTy, Arguments, ParamTys, FMF,
3491                                     dyn_cast<IntrinsicInst>(CI));
3492   return TTI.getIntrinsicInstrCost(CostAttrs,
3493                                    TargetTransformInfo::TCK_RecipThroughput);
3494 }
3495 
3496 static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
3497   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3498   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3499   return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
3500 }
3501 
3502 static Type *largestIntegerVectorType(Type *T1, Type *T2) {
3503   auto *I1 = cast<IntegerType>(cast<VectorType>(T1)->getElementType());
3504   auto *I2 = cast<IntegerType>(cast<VectorType>(T2)->getElementType());
3505   return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
3506 }
3507 
3508 void InnerLoopVectorizer::truncateToMinimalBitwidths(VPTransformState &State) {
3509   // For every instruction `I` in MinBWs, truncate the operands, create a
3510   // truncated version of `I` and reextend its result. InstCombine runs
3511   // later and will remove any ext/trunc pairs.
3512   SmallPtrSet<Value *, 4> Erased;
3513   for (const auto &KV : Cost->getMinimalBitwidths()) {
3514     // If the value wasn't vectorized, we must maintain the original scalar
3515     // type. The absence of the value from State indicates that it
3516     // wasn't vectorized.
3517     // FIXME: Should not rely on getVPValue at this point.
3518     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3519     if (!State.hasAnyVectorValue(Def))
3520       continue;
3521     for (unsigned Part = 0; Part < UF; ++Part) {
3522       Value *I = State.get(Def, Part);
3523       if (Erased.count(I) || I->use_empty() || !isa<Instruction>(I))
3524         continue;
3525       Type *OriginalTy = I->getType();
3526       Type *ScalarTruncatedTy =
3527           IntegerType::get(OriginalTy->getContext(), KV.second);
3528       auto *TruncatedTy = VectorType::get(
3529           ScalarTruncatedTy, cast<VectorType>(OriginalTy)->getElementCount());
3530       if (TruncatedTy == OriginalTy)
3531         continue;
3532 
3533       IRBuilder<> B(cast<Instruction>(I));
3534       auto ShrinkOperand = [&](Value *V) -> Value * {
3535         if (auto *ZI = dyn_cast<ZExtInst>(V))
3536           if (ZI->getSrcTy() == TruncatedTy)
3537             return ZI->getOperand(0);
3538         return B.CreateZExtOrTrunc(V, TruncatedTy);
3539       };
3540 
3541       // The actual instruction modification depends on the instruction type,
3542       // unfortunately.
3543       Value *NewI = nullptr;
3544       if (auto *BO = dyn_cast<BinaryOperator>(I)) {
3545         NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
3546                              ShrinkOperand(BO->getOperand(1)));
3547 
3548         // Any wrapping introduced by shrinking this operation shouldn't be
3549         // considered undefined behavior. So, we can't unconditionally copy
3550         // arithmetic wrapping flags to NewI.
3551         cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
3552       } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
3553         NewI =
3554             B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
3555                          ShrinkOperand(CI->getOperand(1)));
3556       } else if (auto *SI = dyn_cast<SelectInst>(I)) {
3557         NewI = B.CreateSelect(SI->getCondition(),
3558                               ShrinkOperand(SI->getTrueValue()),
3559                               ShrinkOperand(SI->getFalseValue()));
3560       } else if (auto *CI = dyn_cast<CastInst>(I)) {
3561         switch (CI->getOpcode()) {
3562         default:
3563           llvm_unreachable("Unhandled cast!");
3564         case Instruction::Trunc:
3565           NewI = ShrinkOperand(CI->getOperand(0));
3566           break;
3567         case Instruction::SExt:
3568           NewI = B.CreateSExtOrTrunc(
3569               CI->getOperand(0),
3570               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3571           break;
3572         case Instruction::ZExt:
3573           NewI = B.CreateZExtOrTrunc(
3574               CI->getOperand(0),
3575               smallestIntegerVectorType(OriginalTy, TruncatedTy));
3576           break;
3577         }
3578       } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
3579         auto Elements0 =
3580             cast<VectorType>(SI->getOperand(0)->getType())->getElementCount();
3581         auto *O0 = B.CreateZExtOrTrunc(
3582             SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
3583         auto Elements1 =
3584             cast<VectorType>(SI->getOperand(1)->getType())->getElementCount();
3585         auto *O1 = B.CreateZExtOrTrunc(
3586             SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
3587 
3588         NewI = B.CreateShuffleVector(O0, O1, SI->getShuffleMask());
3589       } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
3590         // Don't do anything with the operands, just extend the result.
3591         continue;
3592       } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
3593         auto Elements =
3594             cast<VectorType>(IE->getOperand(0)->getType())->getElementCount();
3595         auto *O0 = B.CreateZExtOrTrunc(
3596             IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3597         auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
3598         NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
3599       } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
3600         auto Elements =
3601             cast<VectorType>(EE->getOperand(0)->getType())->getElementCount();
3602         auto *O0 = B.CreateZExtOrTrunc(
3603             EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
3604         NewI = B.CreateExtractElement(O0, EE->getOperand(2));
3605       } else {
3606         // If we don't know what to do, be conservative and don't do anything.
3607         continue;
3608       }
3609 
3610       // Lastly, extend the result.
3611       NewI->takeName(cast<Instruction>(I));
3612       Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
3613       I->replaceAllUsesWith(Res);
3614       cast<Instruction>(I)->eraseFromParent();
3615       Erased.insert(I);
3616       State.reset(Def, Res, Part);
3617     }
3618   }
3619 
3620   // We'll have created a bunch of ZExts that are now parentless. Clean up.
3621   for (const auto &KV : Cost->getMinimalBitwidths()) {
3622     // If the value wasn't vectorized, we must maintain the original scalar
3623     // type. The absence of the value from State indicates that it
3624     // wasn't vectorized.
3625     // FIXME: Should not rely on getVPValue at this point.
3626     VPValue *Def = State.Plan->getVPValue(KV.first, true);
3627     if (!State.hasAnyVectorValue(Def))
3628       continue;
3629     for (unsigned Part = 0; Part < UF; ++Part) {
3630       Value *I = State.get(Def, Part);
3631       ZExtInst *Inst = dyn_cast<ZExtInst>(I);
3632       if (Inst && Inst->use_empty()) {
3633         Value *NewI = Inst->getOperand(0);
3634         Inst->eraseFromParent();
3635         State.reset(Def, NewI, Part);
3636       }
3637     }
3638   }
3639 }
3640 
3641 void InnerLoopVectorizer::fixVectorizedLoop(VPTransformState &State,
3642                                             VPlan &Plan) {
3643   // Insert truncates and extends for any truncated instructions as hints to
3644   // InstCombine.
3645   if (VF.isVector())
3646     truncateToMinimalBitwidths(State);
3647 
3648   // Fix widened non-induction PHIs by setting up the PHI operands.
3649   if (EnableVPlanNativePath)
3650     fixNonInductionPHIs(Plan, State);
3651 
3652   // At this point every instruction in the original loop is widened to a
3653   // vector form. Now we need to fix the recurrences in the loop. These PHI
3654   // nodes are currently empty because we did not want to introduce cycles.
3655   // This is the second stage of vectorizing recurrences.
3656   fixCrossIterationPHIs(State);
3657 
3658   // Forget the original basic block.
3659   PSE.getSE()->forgetLoop(OrigLoop);
3660 
3661   VPBasicBlock *LatchVPBB = Plan.getVectorLoopRegion()->getExitingBasicBlock();
3662   Loop *VectorLoop = LI->getLoopFor(State.CFG.VPBB2IRBB[LatchVPBB]);
3663   if (Cost->requiresScalarEpilogue(VF)) {
3664     // No edge from the middle block to the unique exit block has been inserted
3665     // and there is nothing to fix from vector loop; phis should have incoming
3666     // from scalar loop only.
3667     Plan.clearLiveOuts();
3668   } else {
3669     // If we inserted an edge from the middle block to the unique exit block,
3670     // update uses outside the loop (phis) to account for the newly inserted
3671     // edge.
3672 
3673     // Fix-up external users of the induction variables.
3674     for (auto &Entry : Legal->getInductionVars())
3675       fixupIVUsers(Entry.first, Entry.second,
3676                    getOrCreateVectorTripCount(VectorLoop->getLoopPreheader()),
3677                    IVEndValues[Entry.first], LoopMiddleBlock,
3678                    VectorLoop->getHeader(), Plan);
3679   }
3680 
3681   // Fix LCSSA phis not already fixed earlier. Extracts may need to be generated
3682   // in the exit block, so update the builder.
3683   State.Builder.SetInsertPoint(State.CFG.ExitBB->getFirstNonPHI());
3684   for (auto &KV : Plan.getLiveOuts())
3685     KV.second->fixPhi(Plan, State);
3686 
3687   for (Instruction *PI : PredicatedInstructions)
3688     sinkScalarOperands(&*PI);
3689 
3690   // Remove redundant induction instructions.
3691   cse(VectorLoop->getHeader());
3692 
3693   // Set/update profile weights for the vector and remainder loops as original
3694   // loop iterations are now distributed among them. Note that original loop
3695   // represented by LoopScalarBody becomes remainder loop after vectorization.
3696   //
3697   // For cases like foldTailByMasking() and requiresScalarEpiloque() we may
3698   // end up getting slightly roughened result but that should be OK since
3699   // profile is not inherently precise anyway. Note also possible bypass of
3700   // vector code caused by legality checks is ignored, assigning all the weight
3701   // to the vector loop, optimistically.
3702   //
3703   // For scalable vectorization we can't know at compile time how many iterations
3704   // of the loop are handled in one vector iteration, so instead assume a pessimistic
3705   // vscale of '1'.
3706   setProfileInfoAfterUnrolling(LI->getLoopFor(LoopScalarBody), VectorLoop,
3707                                LI->getLoopFor(LoopScalarBody),
3708                                VF.getKnownMinValue() * UF);
3709 }
3710 
3711 void InnerLoopVectorizer::fixCrossIterationPHIs(VPTransformState &State) {
3712   // In order to support recurrences we need to be able to vectorize Phi nodes.
3713   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
3714   // stage #2: We now need to fix the recurrences by adding incoming edges to
3715   // the currently empty PHI nodes. At this point every instruction in the
3716   // original loop is widened to a vector form so we can use them to construct
3717   // the incoming edges.
3718   VPBasicBlock *Header =
3719       State.Plan->getVectorLoopRegion()->getEntryBasicBlock();
3720   for (VPRecipeBase &R : Header->phis()) {
3721     if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R))
3722       fixReduction(ReductionPhi, State);
3723     else if (auto *FOR = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R))
3724       fixFirstOrderRecurrence(FOR, State);
3725   }
3726 }
3727 
3728 void InnerLoopVectorizer::fixFirstOrderRecurrence(
3729     VPFirstOrderRecurrencePHIRecipe *PhiR, VPTransformState &State) {
3730   // This is the second phase of vectorizing first-order recurrences. An
3731   // overview of the transformation is described below. Suppose we have the
3732   // following loop.
3733   //
3734   //   for (int i = 0; i < n; ++i)
3735   //     b[i] = a[i] - a[i - 1];
3736   //
3737   // There is a first-order recurrence on "a". For this loop, the shorthand
3738   // scalar IR looks like:
3739   //
3740   //   scalar.ph:
3741   //     s_init = a[-1]
3742   //     br scalar.body
3743   //
3744   //   scalar.body:
3745   //     i = phi [0, scalar.ph], [i+1, scalar.body]
3746   //     s1 = phi [s_init, scalar.ph], [s2, scalar.body]
3747   //     s2 = a[i]
3748   //     b[i] = s2 - s1
3749   //     br cond, scalar.body, ...
3750   //
3751   // In this example, s1 is a recurrence because it's value depends on the
3752   // previous iteration. In the first phase of vectorization, we created a
3753   // vector phi v1 for s1. We now complete the vectorization and produce the
3754   // shorthand vector IR shown below (for VF = 4, UF = 1).
3755   //
3756   //   vector.ph:
3757   //     v_init = vector(..., ..., ..., a[-1])
3758   //     br vector.body
3759   //
3760   //   vector.body
3761   //     i = phi [0, vector.ph], [i+4, vector.body]
3762   //     v1 = phi [v_init, vector.ph], [v2, vector.body]
3763   //     v2 = a[i, i+1, i+2, i+3];
3764   //     v3 = vector(v1(3), v2(0, 1, 2))
3765   //     b[i, i+1, i+2, i+3] = v2 - v3
3766   //     br cond, vector.body, middle.block
3767   //
3768   //   middle.block:
3769   //     x = v2(3)
3770   //     br scalar.ph
3771   //
3772   //   scalar.ph:
3773   //     s_init = phi [x, middle.block], [a[-1], otherwise]
3774   //     br scalar.body
3775   //
3776   // After execution completes the vector loop, we extract the next value of
3777   // the recurrence (x) to use as the initial value in the scalar loop.
3778 
3779   // Extract the last vector element in the middle block. This will be the
3780   // initial value for the recurrence when jumping to the scalar loop.
3781   VPValue *PreviousDef = PhiR->getBackedgeValue();
3782   Value *Incoming = State.get(PreviousDef, UF - 1);
3783   auto *ExtractForScalar = Incoming;
3784   auto *IdxTy = Builder.getInt32Ty();
3785   if (VF.isVector()) {
3786     auto *One = ConstantInt::get(IdxTy, 1);
3787     Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
3788     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3789     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
3790     ExtractForScalar = Builder.CreateExtractElement(ExtractForScalar, LastIdx,
3791                                                     "vector.recur.extract");
3792   }
3793   // Extract the second last element in the middle block if the
3794   // Phi is used outside the loop. We need to extract the phi itself
3795   // and not the last element (the phi update in the current iteration). This
3796   // will be the value when jumping to the exit block from the LoopMiddleBlock,
3797   // when the scalar loop is not run at all.
3798   Value *ExtractForPhiUsedOutsideLoop = nullptr;
3799   if (VF.isVector()) {
3800     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, VF);
3801     auto *Idx = Builder.CreateSub(RuntimeVF, ConstantInt::get(IdxTy, 2));
3802     ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
3803         Incoming, Idx, "vector.recur.extract.for.phi");
3804   } else if (UF > 1)
3805     // When loop is unrolled without vectorizing, initialize
3806     // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value
3807     // of `Incoming`. This is analogous to the vectorized case above: extracting
3808     // the second last element when VF > 1.
3809     ExtractForPhiUsedOutsideLoop = State.get(PreviousDef, UF - 2);
3810 
3811   // Fix the initial value of the original recurrence in the scalar loop.
3812   Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
3813   PHINode *Phi = cast<PHINode>(PhiR->getUnderlyingValue());
3814   auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
3815   auto *ScalarInit = PhiR->getStartValue()->getLiveInIRValue();
3816   for (auto *BB : predecessors(LoopScalarPreHeader)) {
3817     auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
3818     Start->addIncoming(Incoming, BB);
3819   }
3820 
3821   Phi->setIncomingValueForBlock(LoopScalarPreHeader, Start);
3822   Phi->setName("scalar.recur");
3823 
3824   // Finally, fix users of the recurrence outside the loop. The users will need
3825   // either the last value of the scalar recurrence or the last value of the
3826   // vector recurrence we extracted in the middle block. Since the loop is in
3827   // LCSSA form, we just need to find all the phi nodes for the original scalar
3828   // recurrence in the exit block, and then add an edge for the middle block.
3829   // Note that LCSSA does not imply single entry when the original scalar loop
3830   // had multiple exiting edges (as we always run the last iteration in the
3831   // scalar epilogue); in that case, there is no edge from middle to exit and
3832   // and thus no phis which needed updated.
3833   if (!Cost->requiresScalarEpilogue(VF))
3834     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
3835       if (llvm::is_contained(LCSSAPhi.incoming_values(), Phi)) {
3836         LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
3837         State.Plan->removeLiveOut(&LCSSAPhi);
3838       }
3839 }
3840 
3841 void InnerLoopVectorizer::fixReduction(VPReductionPHIRecipe *PhiR,
3842                                        VPTransformState &State) {
3843   PHINode *OrigPhi = cast<PHINode>(PhiR->getUnderlyingValue());
3844   // Get it's reduction variable descriptor.
3845   assert(Legal->isReductionVariable(OrigPhi) &&
3846          "Unable to find the reduction variable");
3847   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
3848 
3849   RecurKind RK = RdxDesc.getRecurrenceKind();
3850   TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
3851   Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
3852   setDebugLocFromInst(ReductionStartValue);
3853 
3854   VPValue *LoopExitInstDef = PhiR->getBackedgeValue();
3855   // This is the vector-clone of the value that leaves the loop.
3856   Type *VecTy = State.get(LoopExitInstDef, 0)->getType();
3857 
3858   // Wrap flags are in general invalid after vectorization, clear them.
3859   clearReductionWrapFlags(PhiR, State);
3860 
3861   // Before each round, move the insertion point right between
3862   // the PHIs and the values we are going to write.
3863   // This allows us to write both PHINodes and the extractelement
3864   // instructions.
3865   Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3866 
3867   setDebugLocFromInst(LoopExitInst);
3868 
3869   Type *PhiTy = OrigPhi->getType();
3870 
3871   VPBasicBlock *LatchVPBB =
3872       PhiR->getParent()->getEnclosingLoopRegion()->getExitingBasicBlock();
3873   BasicBlock *VectorLoopLatch = State.CFG.VPBB2IRBB[LatchVPBB];
3874   // If tail is folded by masking, the vector value to leave the loop should be
3875   // a Select choosing between the vectorized LoopExitInst and vectorized Phi,
3876   // instead of the former. For an inloop reduction the reduction will already
3877   // be predicated, and does not need to be handled here.
3878   if (Cost->foldTailByMasking() && !PhiR->isInLoop()) {
3879     for (unsigned Part = 0; Part < UF; ++Part) {
3880       Value *VecLoopExitInst = State.get(LoopExitInstDef, Part);
3881       SelectInst *Sel = nullptr;
3882       for (User *U : VecLoopExitInst->users()) {
3883         if (isa<SelectInst>(U)) {
3884           assert(!Sel && "Reduction exit feeding two selects");
3885           Sel = cast<SelectInst>(U);
3886         } else
3887           assert(isa<PHINode>(U) && "Reduction exit must feed Phi's or select");
3888       }
3889       assert(Sel && "Reduction exit feeds no select");
3890       State.reset(LoopExitInstDef, Sel, Part);
3891 
3892       if (isa<FPMathOperator>(Sel))
3893         Sel->setFastMathFlags(RdxDesc.getFastMathFlags());
3894 
3895       // If the target can create a predicated operator for the reduction at no
3896       // extra cost in the loop (for example a predicated vadd), it can be
3897       // cheaper for the select to remain in the loop than be sunk out of it,
3898       // and so use the select value for the phi instead of the old
3899       // LoopExitValue.
3900       if (PreferPredicatedReductionSelect ||
3901           TTI->preferPredicatedReductionSelect(
3902               RdxDesc.getOpcode(), PhiTy,
3903               TargetTransformInfo::ReductionFlags())) {
3904         auto *VecRdxPhi =
3905             cast<PHINode>(State.get(PhiR, Part));
3906         VecRdxPhi->setIncomingValueForBlock(VectorLoopLatch, Sel);
3907       }
3908     }
3909   }
3910 
3911   // If the vector reduction can be performed in a smaller type, we truncate
3912   // then extend the loop exit value to enable InstCombine to evaluate the
3913   // entire expression in the smaller type.
3914   if (VF.isVector() && PhiTy != RdxDesc.getRecurrenceType()) {
3915     assert(!PhiR->isInLoop() && "Unexpected truncated inloop reduction!");
3916     Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
3917     Builder.SetInsertPoint(VectorLoopLatch->getTerminator());
3918     VectorParts RdxParts(UF);
3919     for (unsigned Part = 0; Part < UF; ++Part) {
3920       RdxParts[Part] = State.get(LoopExitInstDef, Part);
3921       Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3922       Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
3923                                         : Builder.CreateZExt(Trunc, VecTy);
3924       for (User *U : llvm::make_early_inc_range(RdxParts[Part]->users()))
3925         if (U != Trunc) {
3926           U->replaceUsesOfWith(RdxParts[Part], Extnd);
3927           RdxParts[Part] = Extnd;
3928         }
3929     }
3930     Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
3931     for (unsigned Part = 0; Part < UF; ++Part) {
3932       RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
3933       State.reset(LoopExitInstDef, RdxParts[Part], Part);
3934     }
3935   }
3936 
3937   // Reduce all of the unrolled parts into a single vector.
3938   Value *ReducedPartRdx = State.get(LoopExitInstDef, 0);
3939   unsigned Op = RecurrenceDescriptor::getOpcode(RK);
3940 
3941   // The middle block terminator has already been assigned a DebugLoc here (the
3942   // OrigLoop's single latch terminator). We want the whole middle block to
3943   // appear to execute on this line because: (a) it is all compiler generated,
3944   // (b) these instructions are always executed after evaluating the latch
3945   // conditional branch, and (c) other passes may add new predecessors which
3946   // terminate on this line. This is the easiest way to ensure we don't
3947   // accidentally cause an extra step back into the loop while debugging.
3948   setDebugLocFromInst(LoopMiddleBlock->getTerminator());
3949   if (PhiR->isOrdered())
3950     ReducedPartRdx = State.get(LoopExitInstDef, UF - 1);
3951   else {
3952     // Floating-point operations should have some FMF to enable the reduction.
3953     IRBuilderBase::FastMathFlagGuard FMFG(Builder);
3954     Builder.setFastMathFlags(RdxDesc.getFastMathFlags());
3955     for (unsigned Part = 1; Part < UF; ++Part) {
3956       Value *RdxPart = State.get(LoopExitInstDef, Part);
3957       if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
3958         ReducedPartRdx = Builder.CreateBinOp(
3959             (Instruction::BinaryOps)Op, RdxPart, ReducedPartRdx, "bin.rdx");
3960       } else if (RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK))
3961         ReducedPartRdx = createSelectCmpOp(Builder, ReductionStartValue, RK,
3962                                            ReducedPartRdx, RdxPart);
3963       else
3964         ReducedPartRdx = createMinMaxOp(Builder, RK, ReducedPartRdx, RdxPart);
3965     }
3966   }
3967 
3968   // Create the reduction after the loop. Note that inloop reductions create the
3969   // target reduction in the loop using a Reduction recipe.
3970   if (VF.isVector() && !PhiR->isInLoop()) {
3971     ReducedPartRdx =
3972         createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, OrigPhi);
3973     // If the reduction can be performed in a smaller type, we need to extend
3974     // the reduction to the wider type before we branch to the original loop.
3975     if (PhiTy != RdxDesc.getRecurrenceType())
3976       ReducedPartRdx = RdxDesc.isSigned()
3977                            ? Builder.CreateSExt(ReducedPartRdx, PhiTy)
3978                            : Builder.CreateZExt(ReducedPartRdx, PhiTy);
3979   }
3980 
3981   PHINode *ResumePhi =
3982       dyn_cast<PHINode>(PhiR->getStartValue()->getUnderlyingValue());
3983 
3984   // Create a phi node that merges control-flow from the backedge-taken check
3985   // block and the middle block.
3986   PHINode *BCBlockPhi = PHINode::Create(PhiTy, 2, "bc.merge.rdx",
3987                                         LoopScalarPreHeader->getTerminator());
3988 
3989   // If we are fixing reductions in the epilogue loop then we should already
3990   // have created a bc.merge.rdx Phi after the main vector body. Ensure that
3991   // we carry over the incoming values correctly.
3992   for (auto *Incoming : predecessors(LoopScalarPreHeader)) {
3993     if (Incoming == LoopMiddleBlock)
3994       BCBlockPhi->addIncoming(ReducedPartRdx, Incoming);
3995     else if (ResumePhi && llvm::is_contained(ResumePhi->blocks(), Incoming))
3996       BCBlockPhi->addIncoming(ResumePhi->getIncomingValueForBlock(Incoming),
3997                               Incoming);
3998     else
3999       BCBlockPhi->addIncoming(ReductionStartValue, Incoming);
4000   }
4001 
4002   // Set the resume value for this reduction
4003   ReductionResumeValues.insert({&RdxDesc, BCBlockPhi});
4004 
4005   // If there were stores of the reduction value to a uniform memory address
4006   // inside the loop, create the final store here.
4007   if (StoreInst *SI = RdxDesc.IntermediateStore) {
4008     StoreInst *NewSI =
4009         Builder.CreateStore(ReducedPartRdx, SI->getPointerOperand());
4010     propagateMetadata(NewSI, SI);
4011 
4012     // If the reduction value is used in other places,
4013     // then let the code below create PHI's for that.
4014   }
4015 
4016   // Now, we need to fix the users of the reduction variable
4017   // inside and outside of the scalar remainder loop.
4018 
4019   // We know that the loop is in LCSSA form. We need to update the PHI nodes
4020   // in the exit blocks.  See comment on analogous loop in
4021   // fixFirstOrderRecurrence for a more complete explaination of the logic.
4022   if (!Cost->requiresScalarEpilogue(VF))
4023     for (PHINode &LCSSAPhi : LoopExitBlock->phis())
4024       if (llvm::is_contained(LCSSAPhi.incoming_values(), LoopExitInst)) {
4025         LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
4026         State.Plan->removeLiveOut(&LCSSAPhi);
4027       }
4028 
4029   // Fix the scalar loop reduction variable with the incoming reduction sum
4030   // from the vector body and from the backedge value.
4031   int IncomingEdgeBlockIdx =
4032       OrigPhi->getBasicBlockIndex(OrigLoop->getLoopLatch());
4033   assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
4034   // Pick the other block.
4035   int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
4036   OrigPhi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
4037   OrigPhi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
4038 }
4039 
4040 void InnerLoopVectorizer::clearReductionWrapFlags(VPReductionPHIRecipe *PhiR,
4041                                                   VPTransformState &State) {
4042   const RecurrenceDescriptor &RdxDesc = PhiR->getRecurrenceDescriptor();
4043   RecurKind RK = RdxDesc.getRecurrenceKind();
4044   if (RK != RecurKind::Add && RK != RecurKind::Mul)
4045     return;
4046 
4047   SmallVector<VPValue *, 8> Worklist;
4048   SmallPtrSet<VPValue *, 8> Visited;
4049   Worklist.push_back(PhiR);
4050   Visited.insert(PhiR);
4051 
4052   while (!Worklist.empty()) {
4053     VPValue *Cur = Worklist.pop_back_val();
4054     for (unsigned Part = 0; Part < UF; ++Part) {
4055       Value *V = State.get(Cur, Part);
4056       if (!isa<OverflowingBinaryOperator>(V))
4057         break;
4058       cast<Instruction>(V)->dropPoisonGeneratingFlags();
4059       }
4060 
4061       for (VPUser *U : Cur->users()) {
4062         auto *UserRecipe = dyn_cast<VPRecipeBase>(U);
4063         if (!UserRecipe)
4064           continue;
4065         for (VPValue *V : UserRecipe->definedValues())
4066           if (Visited.insert(V).second)
4067             Worklist.push_back(V);
4068       }
4069   }
4070 }
4071 
4072 void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
4073   // The basic block and loop containing the predicated instruction.
4074   auto *PredBB = PredInst->getParent();
4075   auto *VectorLoop = LI->getLoopFor(PredBB);
4076 
4077   // Initialize a worklist with the operands of the predicated instruction.
4078   SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
4079 
4080   // Holds instructions that we need to analyze again. An instruction may be
4081   // reanalyzed if we don't yet know if we can sink it or not.
4082   SmallVector<Instruction *, 8> InstsToReanalyze;
4083 
4084   // Returns true if a given use occurs in the predicated block. Phi nodes use
4085   // their operands in their corresponding predecessor blocks.
4086   auto isBlockOfUsePredicated = [&](Use &U) -> bool {
4087     auto *I = cast<Instruction>(U.getUser());
4088     BasicBlock *BB = I->getParent();
4089     if (auto *Phi = dyn_cast<PHINode>(I))
4090       BB = Phi->getIncomingBlock(
4091           PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
4092     return BB == PredBB;
4093   };
4094 
4095   // Iteratively sink the scalarized operands of the predicated instruction
4096   // into the block we created for it. When an instruction is sunk, it's
4097   // operands are then added to the worklist. The algorithm ends after one pass
4098   // through the worklist doesn't sink a single instruction.
4099   bool Changed;
4100   do {
4101     // Add the instructions that need to be reanalyzed to the worklist, and
4102     // reset the changed indicator.
4103     Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
4104     InstsToReanalyze.clear();
4105     Changed = false;
4106 
4107     while (!Worklist.empty()) {
4108       auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
4109 
4110       // We can't sink an instruction if it is a phi node, is not in the loop,
4111       // or may have side effects.
4112       if (!I || isa<PHINode>(I) || !VectorLoop->contains(I) ||
4113           I->mayHaveSideEffects())
4114         continue;
4115 
4116       // If the instruction is already in PredBB, check if we can sink its
4117       // operands. In that case, VPlan's sinkScalarOperands() succeeded in
4118       // sinking the scalar instruction I, hence it appears in PredBB; but it
4119       // may have failed to sink I's operands (recursively), which we try
4120       // (again) here.
4121       if (I->getParent() == PredBB) {
4122         Worklist.insert(I->op_begin(), I->op_end());
4123         continue;
4124       }
4125 
4126       // It's legal to sink the instruction if all its uses occur in the
4127       // predicated block. Otherwise, there's nothing to do yet, and we may
4128       // need to reanalyze the instruction.
4129       if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
4130         InstsToReanalyze.push_back(I);
4131         continue;
4132       }
4133 
4134       // Move the instruction to the beginning of the predicated block, and add
4135       // it's operands to the worklist.
4136       I->moveBefore(&*PredBB->getFirstInsertionPt());
4137       Worklist.insert(I->op_begin(), I->op_end());
4138 
4139       // The sinking may have enabled other instructions to be sunk, so we will
4140       // need to iterate.
4141       Changed = true;
4142     }
4143   } while (Changed);
4144 }
4145 
4146 void InnerLoopVectorizer::fixNonInductionPHIs(VPlan &Plan,
4147                                               VPTransformState &State) {
4148   auto Iter = depth_first(
4149       VPBlockRecursiveTraversalWrapper<VPBlockBase *>(Plan.getEntry()));
4150   for (VPBasicBlock *VPBB : VPBlockUtils::blocksOnly<VPBasicBlock>(Iter)) {
4151     for (VPRecipeBase &P : VPBB->phis()) {
4152       VPWidenPHIRecipe *VPPhi = dyn_cast<VPWidenPHIRecipe>(&P);
4153       if (!VPPhi)
4154         continue;
4155       PHINode *NewPhi = cast<PHINode>(State.get(VPPhi, 0));
4156       // Make sure the builder has a valid insert point.
4157       Builder.SetInsertPoint(NewPhi);
4158       for (unsigned i = 0; i < VPPhi->getNumOperands(); ++i) {
4159         VPValue *Inc = VPPhi->getIncomingValue(i);
4160         VPBasicBlock *VPBB = VPPhi->getIncomingBlock(i);
4161         NewPhi->addIncoming(State.get(Inc, 0), State.CFG.VPBB2IRBB[VPBB]);
4162       }
4163     }
4164   }
4165 }
4166 
4167 bool InnerLoopVectorizer::useOrderedReductions(
4168     const RecurrenceDescriptor &RdxDesc) {
4169   return Cost->useOrderedReductions(RdxDesc);
4170 }
4171 
4172 /// A helper function for checking whether an integer division-related
4173 /// instruction may divide by zero (in which case it must be predicated if
4174 /// executed conditionally in the scalar code).
4175 /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
4176 /// Non-zero divisors that are non compile-time constants will not be
4177 /// converted into multiplication, so we will still end up scalarizing
4178 /// the division, but can do so w/o predication.
4179 static bool mayDivideByZero(Instruction &I) {
4180   assert((I.getOpcode() == Instruction::UDiv ||
4181           I.getOpcode() == Instruction::SDiv ||
4182           I.getOpcode() == Instruction::URem ||
4183           I.getOpcode() == Instruction::SRem) &&
4184          "Unexpected instruction");
4185   Value *Divisor = I.getOperand(1);
4186   auto *CInt = dyn_cast<ConstantInt>(Divisor);
4187   return !CInt || CInt->isZero();
4188 }
4189 
4190 void InnerLoopVectorizer::widenCallInstruction(CallInst &I, VPValue *Def,
4191                                                VPUser &ArgOperands,
4192                                                VPTransformState &State) {
4193   assert(!isa<DbgInfoIntrinsic>(I) &&
4194          "DbgInfoIntrinsic should have been dropped during VPlan construction");
4195   setDebugLocFromInst(&I);
4196 
4197   Module *M = I.getParent()->getParent()->getParent();
4198   auto *CI = cast<CallInst>(&I);
4199 
4200   SmallVector<Type *, 4> Tys;
4201   for (Value *ArgOperand : CI->args())
4202     Tys.push_back(ToVectorTy(ArgOperand->getType(), VF.getKnownMinValue()));
4203 
4204   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4205 
4206   // The flag shows whether we use Intrinsic or a usual Call for vectorized
4207   // version of the instruction.
4208   // Is it beneficial to perform intrinsic call compared to lib call?
4209   bool NeedToScalarize = false;
4210   InstructionCost CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
4211   InstructionCost IntrinsicCost = ID ? Cost->getVectorIntrinsicCost(CI, VF) : 0;
4212   bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
4213   assert((UseVectorIntrinsic || !NeedToScalarize) &&
4214          "Instruction should be scalarized elsewhere.");
4215   assert((IntrinsicCost.isValid() || CallCost.isValid()) &&
4216          "Either the intrinsic cost or vector call cost must be valid");
4217 
4218   for (unsigned Part = 0; Part < UF; ++Part) {
4219     SmallVector<Type *, 2> TysForDecl = {CI->getType()};
4220     SmallVector<Value *, 4> Args;
4221     for (auto &I : enumerate(ArgOperands.operands())) {
4222       // Some intrinsics have a scalar argument - don't replace it with a
4223       // vector.
4224       Value *Arg;
4225       if (!UseVectorIntrinsic ||
4226           !isVectorIntrinsicWithScalarOpAtArg(ID, I.index()))
4227         Arg = State.get(I.value(), Part);
4228       else
4229         Arg = State.get(I.value(), VPIteration(0, 0));
4230       if (isVectorIntrinsicWithOverloadTypeAtArg(ID, I.index()))
4231         TysForDecl.push_back(Arg->getType());
4232       Args.push_back(Arg);
4233     }
4234 
4235     Function *VectorF;
4236     if (UseVectorIntrinsic) {
4237       // Use vector version of the intrinsic.
4238       if (VF.isVector())
4239         TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
4240       VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
4241       assert(VectorF && "Can't retrieve vector intrinsic.");
4242     } else {
4243       // Use vector version of the function call.
4244       const VFShape Shape = VFShape::get(*CI, VF, false /*HasGlobalPred*/);
4245 #ifndef NDEBUG
4246       assert(VFDatabase(*CI).getVectorizedFunction(Shape) != nullptr &&
4247              "Can't create vector function.");
4248 #endif
4249         VectorF = VFDatabase(*CI).getVectorizedFunction(Shape);
4250     }
4251       SmallVector<OperandBundleDef, 1> OpBundles;
4252       CI->getOperandBundlesAsDefs(OpBundles);
4253       CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
4254 
4255       if (isa<FPMathOperator>(V))
4256         V->copyFastMathFlags(CI);
4257 
4258       State.set(Def, V, Part);
4259       addMetadata(V, &I);
4260   }
4261 }
4262 
4263 void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
4264   // We should not collect Scalars more than once per VF. Right now, this
4265   // function is called from collectUniformsAndScalars(), which already does
4266   // this check. Collecting Scalars for VF=1 does not make any sense.
4267   assert(VF.isVector() && Scalars.find(VF) == Scalars.end() &&
4268          "This function should not be visited twice for the same VF");
4269 
4270   // This avoids any chances of creating a REPLICATE recipe during planning
4271   // since that would result in generation of scalarized code during execution,
4272   // which is not supported for scalable vectors.
4273   if (VF.isScalable()) {
4274     Scalars[VF].insert(Uniforms[VF].begin(), Uniforms[VF].end());
4275     return;
4276   }
4277 
4278   SmallSetVector<Instruction *, 8> Worklist;
4279 
4280   // These sets are used to seed the analysis with pointers used by memory
4281   // accesses that will remain scalar.
4282   SmallSetVector<Instruction *, 8> ScalarPtrs;
4283   SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
4284   auto *Latch = TheLoop->getLoopLatch();
4285 
4286   // A helper that returns true if the use of Ptr by MemAccess will be scalar.
4287   // The pointer operands of loads and stores will be scalar as long as the
4288   // memory access is not a gather or scatter operation. The value operand of a
4289   // store will remain scalar if the store is scalarized.
4290   auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
4291     InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
4292     assert(WideningDecision != CM_Unknown &&
4293            "Widening decision should be ready at this moment");
4294     if (auto *Store = dyn_cast<StoreInst>(MemAccess))
4295       if (Ptr == Store->getValueOperand())
4296         return WideningDecision == CM_Scalarize;
4297     assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
4298            "Ptr is neither a value or pointer operand");
4299     return WideningDecision != CM_GatherScatter;
4300   };
4301 
4302   // A helper that returns true if the given value is a bitcast or
4303   // getelementptr instruction contained in the loop.
4304   auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
4305     return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
4306             isa<GetElementPtrInst>(V)) &&
4307            !TheLoop->isLoopInvariant(V);
4308   };
4309 
4310   // A helper that evaluates a memory access's use of a pointer. If the use will
4311   // be a scalar use and the pointer is only used by memory accesses, we place
4312   // the pointer in ScalarPtrs. Otherwise, the pointer is placed in
4313   // PossibleNonScalarPtrs.
4314   auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
4315     // We only care about bitcast and getelementptr instructions contained in
4316     // the loop.
4317     if (!isLoopVaryingBitCastOrGEP(Ptr))
4318       return;
4319 
4320     // If the pointer has already been identified as scalar (e.g., if it was
4321     // also identified as uniform), there's nothing to do.
4322     auto *I = cast<Instruction>(Ptr);
4323     if (Worklist.count(I))
4324       return;
4325 
4326     // If the use of the pointer will be a scalar use, and all users of the
4327     // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
4328     // place the pointer in PossibleNonScalarPtrs.
4329     if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
4330           return isa<LoadInst>(U) || isa<StoreInst>(U);
4331         }))
4332       ScalarPtrs.insert(I);
4333     else
4334       PossibleNonScalarPtrs.insert(I);
4335   };
4336 
4337   // We seed the scalars analysis with three classes of instructions: (1)
4338   // instructions marked uniform-after-vectorization and (2) bitcast,
4339   // getelementptr and (pointer) phi instructions used by memory accesses
4340   // requiring a scalar use.
4341   //
4342   // (1) Add to the worklist all instructions that have been identified as
4343   // uniform-after-vectorization.
4344   Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
4345 
4346   // (2) Add to the worklist all bitcast and getelementptr instructions used by
4347   // memory accesses requiring a scalar use. The pointer operands of loads and
4348   // stores will be scalar as long as the memory accesses is not a gather or
4349   // scatter operation. The value operand of a store will remain scalar if the
4350   // store is scalarized.
4351   for (auto *BB : TheLoop->blocks())
4352     for (auto &I : *BB) {
4353       if (auto *Load = dyn_cast<LoadInst>(&I)) {
4354         evaluatePtrUse(Load, Load->getPointerOperand());
4355       } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
4356         evaluatePtrUse(Store, Store->getPointerOperand());
4357         evaluatePtrUse(Store, Store->getValueOperand());
4358       }
4359     }
4360   for (auto *I : ScalarPtrs)
4361     if (!PossibleNonScalarPtrs.count(I)) {
4362       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
4363       Worklist.insert(I);
4364     }
4365 
4366   // Insert the forced scalars.
4367   // FIXME: Currently VPWidenPHIRecipe() often creates a dead vector
4368   // induction variable when the PHI user is scalarized.
4369   auto ForcedScalar = ForcedScalars.find(VF);
4370   if (ForcedScalar != ForcedScalars.end())
4371     for (auto *I : ForcedScalar->second)
4372       Worklist.insert(I);
4373 
4374   // Expand the worklist by looking through any bitcasts and getelementptr
4375   // instructions we've already identified as scalar. This is similar to the
4376   // expansion step in collectLoopUniforms(); however, here we're only
4377   // expanding to include additional bitcasts and getelementptr instructions.
4378   unsigned Idx = 0;
4379   while (Idx != Worklist.size()) {
4380     Instruction *Dst = Worklist[Idx++];
4381     if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
4382       continue;
4383     auto *Src = cast<Instruction>(Dst->getOperand(0));
4384     if (llvm::all_of(Src->users(), [&](User *U) -> bool {
4385           auto *J = cast<Instruction>(U);
4386           return !TheLoop->contains(J) || Worklist.count(J) ||
4387                  ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
4388                   isScalarUse(J, Src));
4389         })) {
4390       Worklist.insert(Src);
4391       LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
4392     }
4393   }
4394 
4395   // An induction variable will remain scalar if all users of the induction
4396   // variable and induction variable update remain scalar.
4397   for (auto &Induction : Legal->getInductionVars()) {
4398     auto *Ind = Induction.first;
4399     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4400 
4401     // If tail-folding is applied, the primary induction variable will be used
4402     // to feed a vector compare.
4403     if (Ind == Legal->getPrimaryInduction() && foldTailByMasking())
4404       continue;
4405 
4406     // Returns true if \p Indvar is a pointer induction that is used directly by
4407     // load/store instruction \p I.
4408     auto IsDirectLoadStoreFromPtrIndvar = [&](Instruction *Indvar,
4409                                               Instruction *I) {
4410       return Induction.second.getKind() ==
4411                  InductionDescriptor::IK_PtrInduction &&
4412              (isa<LoadInst>(I) || isa<StoreInst>(I)) &&
4413              Indvar == getLoadStorePointerOperand(I) && isScalarUse(I, Indvar);
4414     };
4415 
4416     // Determine if all users of the induction variable are scalar after
4417     // vectorization.
4418     auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4419       auto *I = cast<Instruction>(U);
4420       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4421              IsDirectLoadStoreFromPtrIndvar(Ind, I);
4422     });
4423     if (!ScalarInd)
4424       continue;
4425 
4426     // Determine if all users of the induction variable update instruction are
4427     // scalar after vectorization.
4428     auto ScalarIndUpdate =
4429         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4430           auto *I = cast<Instruction>(U);
4431           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4432                  IsDirectLoadStoreFromPtrIndvar(IndUpdate, I);
4433         });
4434     if (!ScalarIndUpdate)
4435       continue;
4436 
4437     // The induction variable and its update instruction will remain scalar.
4438     Worklist.insert(Ind);
4439     Worklist.insert(IndUpdate);
4440     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
4441     LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
4442                       << "\n");
4443   }
4444 
4445   Scalars[VF].insert(Worklist.begin(), Worklist.end());
4446 }
4447 
4448 bool LoopVectorizationCostModel::isScalarWithPredication(
4449     Instruction *I, ElementCount VF) const {
4450   if (!blockNeedsPredicationForAnyReason(I->getParent()))
4451     return false;
4452   switch(I->getOpcode()) {
4453   default:
4454     break;
4455   case Instruction::Load:
4456   case Instruction::Store: {
4457     if (!Legal->isMaskRequired(I))
4458       return false;
4459     auto *Ptr = getLoadStorePointerOperand(I);
4460     auto *Ty = getLoadStoreType(I);
4461     Type *VTy = Ty;
4462     if (VF.isVector())
4463       VTy = VectorType::get(Ty, VF);
4464     const Align Alignment = getLoadStoreAlignment(I);
4465     return isa<LoadInst>(I) ? !(isLegalMaskedLoad(Ty, Ptr, Alignment) ||
4466                                 TTI.isLegalMaskedGather(VTy, Alignment))
4467                             : !(isLegalMaskedStore(Ty, Ptr, Alignment) ||
4468                                 TTI.isLegalMaskedScatter(VTy, Alignment));
4469   }
4470   case Instruction::UDiv:
4471   case Instruction::SDiv:
4472   case Instruction::SRem:
4473   case Instruction::URem:
4474     return mayDivideByZero(*I);
4475   }
4476   return false;
4477 }
4478 
4479 bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(
4480     Instruction *I, ElementCount VF) {
4481   assert(isAccessInterleaved(I) && "Expecting interleaved access.");
4482   assert(getWideningDecision(I, VF) == CM_Unknown &&
4483          "Decision should not be set yet.");
4484   auto *Group = getInterleavedAccessGroup(I);
4485   assert(Group && "Must have a group.");
4486 
4487   // If the instruction's allocated size doesn't equal it's type size, it
4488   // requires padding and will be scalarized.
4489   auto &DL = I->getModule()->getDataLayout();
4490   auto *ScalarTy = getLoadStoreType(I);
4491   if (hasIrregularType(ScalarTy, DL))
4492     return false;
4493 
4494   // If the group involves a non-integral pointer, we may not be able to
4495   // losslessly cast all values to a common type.
4496   unsigned InterleaveFactor = Group->getFactor();
4497   bool ScalarNI = DL.isNonIntegralPointerType(ScalarTy);
4498   for (unsigned i = 0; i < InterleaveFactor; i++) {
4499     Instruction *Member = Group->getMember(i);
4500     if (!Member)
4501       continue;
4502     auto *MemberTy = getLoadStoreType(Member);
4503     bool MemberNI = DL.isNonIntegralPointerType(MemberTy);
4504     // Don't coerce non-integral pointers to integers or vice versa.
4505     if (MemberNI != ScalarNI) {
4506       // TODO: Consider adding special nullptr value case here
4507       return false;
4508     } else if (MemberNI && ScalarNI &&
4509                ScalarTy->getPointerAddressSpace() !=
4510                MemberTy->getPointerAddressSpace()) {
4511       return false;
4512     }
4513   }
4514 
4515   // Check if masking is required.
4516   // A Group may need masking for one of two reasons: it resides in a block that
4517   // needs predication, or it was decided to use masking to deal with gaps
4518   // (either a gap at the end of a load-access that may result in a speculative
4519   // load, or any gaps in a store-access).
4520   bool PredicatedAccessRequiresMasking =
4521       blockNeedsPredicationForAnyReason(I->getParent()) &&
4522       Legal->isMaskRequired(I);
4523   bool LoadAccessWithGapsRequiresEpilogMasking =
4524       isa<LoadInst>(I) && Group->requiresScalarEpilogue() &&
4525       !isScalarEpilogueAllowed();
4526   bool StoreAccessWithGapsRequiresMasking =
4527       isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor());
4528   if (!PredicatedAccessRequiresMasking &&
4529       !LoadAccessWithGapsRequiresEpilogMasking &&
4530       !StoreAccessWithGapsRequiresMasking)
4531     return true;
4532 
4533   // If masked interleaving is required, we expect that the user/target had
4534   // enabled it, because otherwise it either wouldn't have been created or
4535   // it should have been invalidated by the CostModel.
4536   assert(useMaskedInterleavedAccesses(TTI) &&
4537          "Masked interleave-groups for predicated accesses are not enabled.");
4538 
4539   if (Group->isReverse())
4540     return false;
4541 
4542   auto *Ty = getLoadStoreType(I);
4543   const Align Alignment = getLoadStoreAlignment(I);
4544   return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty, Alignment)
4545                           : TTI.isLegalMaskedStore(Ty, Alignment);
4546 }
4547 
4548 bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(
4549     Instruction *I, ElementCount VF) {
4550   // Get and ensure we have a valid memory instruction.
4551   assert((isa<LoadInst, StoreInst>(I)) && "Invalid memory instruction");
4552 
4553   auto *Ptr = getLoadStorePointerOperand(I);
4554   auto *ScalarTy = getLoadStoreType(I);
4555 
4556   // In order to be widened, the pointer should be consecutive, first of all.
4557   if (!Legal->isConsecutivePtr(ScalarTy, Ptr))
4558     return false;
4559 
4560   // If the instruction is a store located in a predicated block, it will be
4561   // scalarized.
4562   if (isScalarWithPredication(I, VF))
4563     return false;
4564 
4565   // If the instruction's allocated size doesn't equal it's type size, it
4566   // requires padding and will be scalarized.
4567   auto &DL = I->getModule()->getDataLayout();
4568   if (hasIrregularType(ScalarTy, DL))
4569     return false;
4570 
4571   return true;
4572 }
4573 
4574 void LoopVectorizationCostModel::collectLoopUniforms(ElementCount VF) {
4575   // We should not collect Uniforms more than once per VF. Right now,
4576   // this function is called from collectUniformsAndScalars(), which
4577   // already does this check. Collecting Uniforms for VF=1 does not make any
4578   // sense.
4579 
4580   assert(VF.isVector() && Uniforms.find(VF) == Uniforms.end() &&
4581          "This function should not be visited twice for the same VF");
4582 
4583   // Visit the list of Uniforms. If we'll not find any uniform value, we'll
4584   // not analyze again.  Uniforms.count(VF) will return 1.
4585   Uniforms[VF].clear();
4586 
4587   // We now know that the loop is vectorizable!
4588   // Collect instructions inside the loop that will remain uniform after
4589   // vectorization.
4590 
4591   // Global values, params and instructions outside of current loop are out of
4592   // scope.
4593   auto isOutOfScope = [&](Value *V) -> bool {
4594     Instruction *I = dyn_cast<Instruction>(V);
4595     return (!I || !TheLoop->contains(I));
4596   };
4597 
4598   // Worklist containing uniform instructions demanding lane 0.
4599   SetVector<Instruction *> Worklist;
4600   BasicBlock *Latch = TheLoop->getLoopLatch();
4601 
4602   // Add uniform instructions demanding lane 0 to the worklist. Instructions
4603   // that are scalar with predication must not be considered uniform after
4604   // vectorization, because that would create an erroneous replicating region
4605   // where only a single instance out of VF should be formed.
4606   // TODO: optimize such seldom cases if found important, see PR40816.
4607   auto addToWorklistIfAllowed = [&](Instruction *I) -> void {
4608     if (isOutOfScope(I)) {
4609       LLVM_DEBUG(dbgs() << "LV: Found not uniform due to scope: "
4610                         << *I << "\n");
4611       return;
4612     }
4613     if (isScalarWithPredication(I, VF)) {
4614       LLVM_DEBUG(dbgs() << "LV: Found not uniform being ScalarWithPredication: "
4615                         << *I << "\n");
4616       return;
4617     }
4618     LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *I << "\n");
4619     Worklist.insert(I);
4620   };
4621 
4622   // Start with the conditional branch. If the branch condition is an
4623   // instruction contained in the loop that is only used by the branch, it is
4624   // uniform.
4625   auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
4626   if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse())
4627     addToWorklistIfAllowed(Cmp);
4628 
4629   auto isUniformDecision = [&](Instruction *I, ElementCount VF) {
4630     InstWidening WideningDecision = getWideningDecision(I, VF);
4631     assert(WideningDecision != CM_Unknown &&
4632            "Widening decision should be ready at this moment");
4633 
4634     // A uniform memory op is itself uniform.  We exclude uniform stores
4635     // here as they demand the last lane, not the first one.
4636     if (isa<LoadInst>(I) && Legal->isUniformMemOp(*I)) {
4637       assert(WideningDecision == CM_Scalarize);
4638       return true;
4639     }
4640 
4641     return (WideningDecision == CM_Widen ||
4642             WideningDecision == CM_Widen_Reverse ||
4643             WideningDecision == CM_Interleave);
4644   };
4645 
4646 
4647   // Returns true if Ptr is the pointer operand of a memory access instruction
4648   // I, and I is known to not require scalarization.
4649   auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
4650     return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
4651   };
4652 
4653   // Holds a list of values which are known to have at least one uniform use.
4654   // Note that there may be other uses which aren't uniform.  A "uniform use"
4655   // here is something which only demands lane 0 of the unrolled iterations;
4656   // it does not imply that all lanes produce the same value (e.g. this is not
4657   // the usual meaning of uniform)
4658   SetVector<Value *> HasUniformUse;
4659 
4660   // Scan the loop for instructions which are either a) known to have only
4661   // lane 0 demanded or b) are uses which demand only lane 0 of their operand.
4662   for (auto *BB : TheLoop->blocks())
4663     for (auto &I : *BB) {
4664       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(&I)) {
4665         switch (II->getIntrinsicID()) {
4666         case Intrinsic::sideeffect:
4667         case Intrinsic::experimental_noalias_scope_decl:
4668         case Intrinsic::assume:
4669         case Intrinsic::lifetime_start:
4670         case Intrinsic::lifetime_end:
4671           if (TheLoop->hasLoopInvariantOperands(&I))
4672             addToWorklistIfAllowed(&I);
4673           break;
4674         default:
4675           break;
4676         }
4677       }
4678 
4679       // ExtractValue instructions must be uniform, because the operands are
4680       // known to be loop-invariant.
4681       if (auto *EVI = dyn_cast<ExtractValueInst>(&I)) {
4682         assert(isOutOfScope(EVI->getAggregateOperand()) &&
4683                "Expected aggregate value to be loop invariant");
4684         addToWorklistIfAllowed(EVI);
4685         continue;
4686       }
4687 
4688       // If there's no pointer operand, there's nothing to do.
4689       auto *Ptr = getLoadStorePointerOperand(&I);
4690       if (!Ptr)
4691         continue;
4692 
4693       // A uniform memory op is itself uniform.  We exclude uniform stores
4694       // here as they demand the last lane, not the first one.
4695       if (isa<LoadInst>(I) && Legal->isUniformMemOp(I))
4696         addToWorklistIfAllowed(&I);
4697 
4698       if (isUniformDecision(&I, VF)) {
4699         assert(isVectorizedMemAccessUse(&I, Ptr) && "consistency check");
4700         HasUniformUse.insert(Ptr);
4701       }
4702     }
4703 
4704   // Add to the worklist any operands which have *only* uniform (e.g. lane 0
4705   // demanding) users.  Since loops are assumed to be in LCSSA form, this
4706   // disallows uses outside the loop as well.
4707   for (auto *V : HasUniformUse) {
4708     if (isOutOfScope(V))
4709       continue;
4710     auto *I = cast<Instruction>(V);
4711     auto UsersAreMemAccesses =
4712       llvm::all_of(I->users(), [&](User *U) -> bool {
4713         return isVectorizedMemAccessUse(cast<Instruction>(U), V);
4714       });
4715     if (UsersAreMemAccesses)
4716       addToWorklistIfAllowed(I);
4717   }
4718 
4719   // Expand Worklist in topological order: whenever a new instruction
4720   // is added , its users should be already inside Worklist.  It ensures
4721   // a uniform instruction will only be used by uniform instructions.
4722   unsigned idx = 0;
4723   while (idx != Worklist.size()) {
4724     Instruction *I = Worklist[idx++];
4725 
4726     for (auto OV : I->operand_values()) {
4727       // isOutOfScope operands cannot be uniform instructions.
4728       if (isOutOfScope(OV))
4729         continue;
4730       // First order recurrence Phi's should typically be considered
4731       // non-uniform.
4732       auto *OP = dyn_cast<PHINode>(OV);
4733       if (OP && Legal->isFirstOrderRecurrence(OP))
4734         continue;
4735       // If all the users of the operand are uniform, then add the
4736       // operand into the uniform worklist.
4737       auto *OI = cast<Instruction>(OV);
4738       if (llvm::all_of(OI->users(), [&](User *U) -> bool {
4739             auto *J = cast<Instruction>(U);
4740             return Worklist.count(J) || isVectorizedMemAccessUse(J, OI);
4741           }))
4742         addToWorklistIfAllowed(OI);
4743     }
4744   }
4745 
4746   // For an instruction to be added into Worklist above, all its users inside
4747   // the loop should also be in Worklist. However, this condition cannot be
4748   // true for phi nodes that form a cyclic dependence. We must process phi
4749   // nodes separately. An induction variable will remain uniform if all users
4750   // of the induction variable and induction variable update remain uniform.
4751   // The code below handles both pointer and non-pointer induction variables.
4752   for (auto &Induction : Legal->getInductionVars()) {
4753     auto *Ind = Induction.first;
4754     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
4755 
4756     // Determine if all users of the induction variable are uniform after
4757     // vectorization.
4758     auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
4759       auto *I = cast<Instruction>(U);
4760       return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
4761              isVectorizedMemAccessUse(I, Ind);
4762     });
4763     if (!UniformInd)
4764       continue;
4765 
4766     // Determine if all users of the induction variable update instruction are
4767     // uniform after vectorization.
4768     auto UniformIndUpdate =
4769         llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
4770           auto *I = cast<Instruction>(U);
4771           return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
4772                  isVectorizedMemAccessUse(I, IndUpdate);
4773         });
4774     if (!UniformIndUpdate)
4775       continue;
4776 
4777     // The induction variable and its update instruction will remain uniform.
4778     addToWorklistIfAllowed(Ind);
4779     addToWorklistIfAllowed(IndUpdate);
4780   }
4781 
4782   Uniforms[VF].insert(Worklist.begin(), Worklist.end());
4783 }
4784 
4785 bool LoopVectorizationCostModel::runtimeChecksRequired() {
4786   LLVM_DEBUG(dbgs() << "LV: Performing code size checks.\n");
4787 
4788   if (Legal->getRuntimePointerChecking()->Need) {
4789     reportVectorizationFailure("Runtime ptr check is required with -Os/-Oz",
4790         "runtime pointer checks needed. Enable vectorization of this "
4791         "loop with '#pragma clang loop vectorize(enable)' when "
4792         "compiling with -Os/-Oz",
4793         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4794     return true;
4795   }
4796 
4797   if (!PSE.getPredicate().isAlwaysTrue()) {
4798     reportVectorizationFailure("Runtime SCEV check is required with -Os/-Oz",
4799         "runtime SCEV checks needed. Enable vectorization of this "
4800         "loop with '#pragma clang loop vectorize(enable)' when "
4801         "compiling with -Os/-Oz",
4802         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4803     return true;
4804   }
4805 
4806   // FIXME: Avoid specializing for stride==1 instead of bailing out.
4807   if (!Legal->getLAI()->getSymbolicStrides().empty()) {
4808     reportVectorizationFailure("Runtime stride check for small trip count",
4809         "runtime stride == 1 checks needed. Enable vectorization of "
4810         "this loop without such check by compiling with -Os/-Oz",
4811         "CantVersionLoopWithOptForSize", ORE, TheLoop);
4812     return true;
4813   }
4814 
4815   return false;
4816 }
4817 
4818 ElementCount
4819 LoopVectorizationCostModel::getMaxLegalScalableVF(unsigned MaxSafeElements) {
4820   if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors)
4821     return ElementCount::getScalable(0);
4822 
4823   if (Hints->isScalableVectorizationDisabled()) {
4824     reportVectorizationInfo("Scalable vectorization is explicitly disabled",
4825                             "ScalableVectorizationDisabled", ORE, TheLoop);
4826     return ElementCount::getScalable(0);
4827   }
4828 
4829   LLVM_DEBUG(dbgs() << "LV: Scalable vectorization is available\n");
4830 
4831   auto MaxScalableVF = ElementCount::getScalable(
4832       std::numeric_limits<ElementCount::ScalarTy>::max());
4833 
4834   // Test that the loop-vectorizer can legalize all operations for this MaxVF.
4835   // FIXME: While for scalable vectors this is currently sufficient, this should
4836   // be replaced by a more detailed mechanism that filters out specific VFs,
4837   // instead of invalidating vectorization for a whole set of VFs based on the
4838   // MaxVF.
4839 
4840   // Disable scalable vectorization if the loop contains unsupported reductions.
4841   if (!canVectorizeReductions(MaxScalableVF)) {
4842     reportVectorizationInfo(
4843         "Scalable vectorization not supported for the reduction "
4844         "operations found in this loop.",
4845         "ScalableVFUnfeasible", ORE, TheLoop);
4846     return ElementCount::getScalable(0);
4847   }
4848 
4849   // Disable scalable vectorization if the loop contains any instructions
4850   // with element types not supported for scalable vectors.
4851   if (any_of(ElementTypesInLoop, [&](Type *Ty) {
4852         return !Ty->isVoidTy() &&
4853                !this->TTI.isElementTypeLegalForScalableVector(Ty);
4854       })) {
4855     reportVectorizationInfo("Scalable vectorization is not supported "
4856                             "for all element types found in this loop.",
4857                             "ScalableVFUnfeasible", ORE, TheLoop);
4858     return ElementCount::getScalable(0);
4859   }
4860 
4861   if (Legal->isSafeForAnyVectorWidth())
4862     return MaxScalableVF;
4863 
4864   // Limit MaxScalableVF by the maximum safe dependence distance.
4865   Optional<unsigned> MaxVScale = TTI.getMaxVScale();
4866   if (!MaxVScale && TheFunction->hasFnAttribute(Attribute::VScaleRange))
4867     MaxVScale =
4868         TheFunction->getFnAttribute(Attribute::VScaleRange).getVScaleRangeMax();
4869   MaxScalableVF = ElementCount::getScalable(
4870       MaxVScale ? (MaxSafeElements / MaxVScale.getValue()) : 0);
4871   if (!MaxScalableVF)
4872     reportVectorizationInfo(
4873         "Max legal vector width too small, scalable vectorization "
4874         "unfeasible.",
4875         "ScalableVFUnfeasible", ORE, TheLoop);
4876 
4877   return MaxScalableVF;
4878 }
4879 
4880 FixedScalableVFPair LoopVectorizationCostModel::computeFeasibleMaxVF(
4881     unsigned ConstTripCount, ElementCount UserVF, bool FoldTailByMasking) {
4882   MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
4883   unsigned SmallestType, WidestType;
4884   std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
4885 
4886   // Get the maximum safe dependence distance in bits computed by LAA.
4887   // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
4888   // the memory accesses that is most restrictive (involved in the smallest
4889   // dependence distance).
4890   unsigned MaxSafeElements =
4891       PowerOf2Floor(Legal->getMaxSafeVectorWidthInBits() / WidestType);
4892 
4893   auto MaxSafeFixedVF = ElementCount::getFixed(MaxSafeElements);
4894   auto MaxSafeScalableVF = getMaxLegalScalableVF(MaxSafeElements);
4895 
4896   LLVM_DEBUG(dbgs() << "LV: The max safe fixed VF is: " << MaxSafeFixedVF
4897                     << ".\n");
4898   LLVM_DEBUG(dbgs() << "LV: The max safe scalable VF is: " << MaxSafeScalableVF
4899                     << ".\n");
4900 
4901   // First analyze the UserVF, fall back if the UserVF should be ignored.
4902   if (UserVF) {
4903     auto MaxSafeUserVF =
4904         UserVF.isScalable() ? MaxSafeScalableVF : MaxSafeFixedVF;
4905 
4906     if (ElementCount::isKnownLE(UserVF, MaxSafeUserVF)) {
4907       // If `VF=vscale x N` is safe, then so is `VF=N`
4908       if (UserVF.isScalable())
4909         return FixedScalableVFPair(
4910             ElementCount::getFixed(UserVF.getKnownMinValue()), UserVF);
4911       else
4912         return UserVF;
4913     }
4914 
4915     assert(ElementCount::isKnownGT(UserVF, MaxSafeUserVF));
4916 
4917     // Only clamp if the UserVF is not scalable. If the UserVF is scalable, it
4918     // is better to ignore the hint and let the compiler choose a suitable VF.
4919     if (!UserVF.isScalable()) {
4920       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4921                         << " is unsafe, clamping to max safe VF="
4922                         << MaxSafeFixedVF << ".\n");
4923       ORE->emit([&]() {
4924         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4925                                           TheLoop->getStartLoc(),
4926                                           TheLoop->getHeader())
4927                << "User-specified vectorization factor "
4928                << ore::NV("UserVectorizationFactor", UserVF)
4929                << " is unsafe, clamping to maximum safe vectorization factor "
4930                << ore::NV("VectorizationFactor", MaxSafeFixedVF);
4931       });
4932       return MaxSafeFixedVF;
4933     }
4934 
4935     if (!TTI.supportsScalableVectors() && !ForceTargetSupportsScalableVectors) {
4936       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4937                         << " is ignored because scalable vectors are not "
4938                            "available.\n");
4939       ORE->emit([&]() {
4940         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4941                                           TheLoop->getStartLoc(),
4942                                           TheLoop->getHeader())
4943                << "User-specified vectorization factor "
4944                << ore::NV("UserVectorizationFactor", UserVF)
4945                << " is ignored because the target does not support scalable "
4946                   "vectors. The compiler will pick a more suitable value.";
4947       });
4948     } else {
4949       LLVM_DEBUG(dbgs() << "LV: User VF=" << UserVF
4950                         << " is unsafe. Ignoring scalable UserVF.\n");
4951       ORE->emit([&]() {
4952         return OptimizationRemarkAnalysis(DEBUG_TYPE, "VectorizationFactor",
4953                                           TheLoop->getStartLoc(),
4954                                           TheLoop->getHeader())
4955                << "User-specified vectorization factor "
4956                << ore::NV("UserVectorizationFactor", UserVF)
4957                << " is unsafe. Ignoring the hint to let the compiler pick a "
4958                   "more suitable value.";
4959       });
4960     }
4961   }
4962 
4963   LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
4964                     << " / " << WidestType << " bits.\n");
4965 
4966   FixedScalableVFPair Result(ElementCount::getFixed(1),
4967                              ElementCount::getScalable(0));
4968   if (auto MaxVF =
4969           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
4970                                   MaxSafeFixedVF, FoldTailByMasking))
4971     Result.FixedVF = MaxVF;
4972 
4973   if (auto MaxVF =
4974           getMaximizedVFForTarget(ConstTripCount, SmallestType, WidestType,
4975                                   MaxSafeScalableVF, FoldTailByMasking))
4976     if (MaxVF.isScalable()) {
4977       Result.ScalableVF = MaxVF;
4978       LLVM_DEBUG(dbgs() << "LV: Found feasible scalable VF = " << MaxVF
4979                         << "\n");
4980     }
4981 
4982   return Result;
4983 }
4984 
4985 FixedScalableVFPair
4986 LoopVectorizationCostModel::computeMaxVF(ElementCount UserVF, unsigned UserIC) {
4987   if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
4988     // TODO: It may by useful to do since it's still likely to be dynamically
4989     // uniform if the target can skip.
4990     reportVectorizationFailure(
4991         "Not inserting runtime ptr check for divergent target",
4992         "runtime pointer checks needed. Not enabled for divergent target",
4993         "CantVersionLoopWithDivergentTarget", ORE, TheLoop);
4994     return FixedScalableVFPair::getNone();
4995   }
4996 
4997   unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
4998   LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
4999   if (TC == 1) {
5000     reportVectorizationFailure("Single iteration (non) loop",
5001         "loop trip count is one, irrelevant for vectorization",
5002         "SingleIterationLoop", ORE, TheLoop);
5003     return FixedScalableVFPair::getNone();
5004   }
5005 
5006   switch (ScalarEpilogueStatus) {
5007   case CM_ScalarEpilogueAllowed:
5008     return computeFeasibleMaxVF(TC, UserVF, false);
5009   case CM_ScalarEpilogueNotAllowedUsePredicate:
5010     LLVM_FALLTHROUGH;
5011   case CM_ScalarEpilogueNotNeededUsePredicate:
5012     LLVM_DEBUG(
5013         dbgs() << "LV: vector predicate hint/switch found.\n"
5014                << "LV: Not allowing scalar epilogue, creating predicated "
5015                << "vector loop.\n");
5016     break;
5017   case CM_ScalarEpilogueNotAllowedLowTripLoop:
5018     // fallthrough as a special case of OptForSize
5019   case CM_ScalarEpilogueNotAllowedOptSize:
5020     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedOptSize)
5021       LLVM_DEBUG(
5022           dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
5023     else
5024       LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to low trip "
5025                         << "count.\n");
5026 
5027     // Bail if runtime checks are required, which are not good when optimising
5028     // for size.
5029     if (runtimeChecksRequired())
5030       return FixedScalableVFPair::getNone();
5031 
5032     break;
5033   }
5034 
5035   // The only loops we can vectorize without a scalar epilogue, are loops with
5036   // a bottom-test and a single exiting block. We'd have to handle the fact
5037   // that not every instruction executes on the last iteration.  This will
5038   // require a lane mask which varies through the vector loop body.  (TODO)
5039   if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
5040     // If there was a tail-folding hint/switch, but we can't fold the tail by
5041     // masking, fallback to a vectorization with a scalar epilogue.
5042     if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5043       LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5044                            "scalar epilogue instead.\n");
5045       ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5046       return computeFeasibleMaxVF(TC, UserVF, false);
5047     }
5048     return FixedScalableVFPair::getNone();
5049   }
5050 
5051   // Now try the tail folding
5052 
5053   // Invalidate interleave groups that require an epilogue if we can't mask
5054   // the interleave-group.
5055   if (!useMaskedInterleavedAccesses(TTI)) {
5056     assert(WideningDecisions.empty() && Uniforms.empty() && Scalars.empty() &&
5057            "No decisions should have been taken at this point");
5058     // Note: There is no need to invalidate any cost modeling decisions here, as
5059     // non where taken so far.
5060     InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
5061   }
5062 
5063   FixedScalableVFPair MaxFactors = computeFeasibleMaxVF(TC, UserVF, true);
5064   // Avoid tail folding if the trip count is known to be a multiple of any VF
5065   // we chose.
5066   // FIXME: The condition below pessimises the case for fixed-width vectors,
5067   // when scalable VFs are also candidates for vectorization.
5068   if (MaxFactors.FixedVF.isVector() && !MaxFactors.ScalableVF) {
5069     ElementCount MaxFixedVF = MaxFactors.FixedVF;
5070     assert((UserVF.isNonZero() || isPowerOf2_32(MaxFixedVF.getFixedValue())) &&
5071            "MaxFixedVF must be a power of 2");
5072     unsigned MaxVFtimesIC = UserIC ? MaxFixedVF.getFixedValue() * UserIC
5073                                    : MaxFixedVF.getFixedValue();
5074     ScalarEvolution *SE = PSE.getSE();
5075     const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
5076     const SCEV *ExitCount = SE->getAddExpr(
5077         BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
5078     const SCEV *Rem = SE->getURemExpr(
5079         SE->applyLoopGuards(ExitCount, TheLoop),
5080         SE->getConstant(BackedgeTakenCount->getType(), MaxVFtimesIC));
5081     if (Rem->isZero()) {
5082       // Accept MaxFixedVF if we do not have a tail.
5083       LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
5084       return MaxFactors;
5085     }
5086   }
5087 
5088   // If we don't know the precise trip count, or if the trip count that we
5089   // found modulo the vectorization factor is not zero, try to fold the tail
5090   // by masking.
5091   // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
5092   if (Legal->prepareToFoldTailByMasking()) {
5093     FoldTailByMasking = true;
5094     return MaxFactors;
5095   }
5096 
5097   // If there was a tail-folding hint/switch, but we can't fold the tail by
5098   // masking, fallback to a vectorization with a scalar epilogue.
5099   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotNeededUsePredicate) {
5100     LLVM_DEBUG(dbgs() << "LV: Cannot fold tail by masking: vectorize with a "
5101                          "scalar epilogue instead.\n");
5102     ScalarEpilogueStatus = CM_ScalarEpilogueAllowed;
5103     return MaxFactors;
5104   }
5105 
5106   if (ScalarEpilogueStatus == CM_ScalarEpilogueNotAllowedUsePredicate) {
5107     LLVM_DEBUG(dbgs() << "LV: Can't fold tail by masking: don't vectorize\n");
5108     return FixedScalableVFPair::getNone();
5109   }
5110 
5111   if (TC == 0) {
5112     reportVectorizationFailure(
5113         "Unable to calculate the loop count due to complex control flow",
5114         "unable to calculate the loop count due to complex control flow",
5115         "UnknownLoopCountComplexCFG", ORE, TheLoop);
5116     return FixedScalableVFPair::getNone();
5117   }
5118 
5119   reportVectorizationFailure(
5120       "Cannot optimize for size and vectorize at the same time.",
5121       "cannot optimize for size and vectorize at the same time. "
5122       "Enable vectorization of this loop with '#pragma clang loop "
5123       "vectorize(enable)' when compiling with -Os/-Oz",
5124       "NoTailLoopWithOptForSize", ORE, TheLoop);
5125   return FixedScalableVFPair::getNone();
5126 }
5127 
5128 ElementCount LoopVectorizationCostModel::getMaximizedVFForTarget(
5129     unsigned ConstTripCount, unsigned SmallestType, unsigned WidestType,
5130     ElementCount MaxSafeVF, bool FoldTailByMasking) {
5131   bool ComputeScalableMaxVF = MaxSafeVF.isScalable();
5132   TypeSize WidestRegister = TTI.getRegisterBitWidth(
5133       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5134                            : TargetTransformInfo::RGK_FixedWidthVector);
5135 
5136   // Convenience function to return the minimum of two ElementCounts.
5137   auto MinVF = [](const ElementCount &LHS, const ElementCount &RHS) {
5138     assert((LHS.isScalable() == RHS.isScalable()) &&
5139            "Scalable flags must match");
5140     return ElementCount::isKnownLT(LHS, RHS) ? LHS : RHS;
5141   };
5142 
5143   // Ensure MaxVF is a power of 2; the dependence distance bound may not be.
5144   // Note that both WidestRegister and WidestType may not be a powers of 2.
5145   auto MaxVectorElementCount = ElementCount::get(
5146       PowerOf2Floor(WidestRegister.getKnownMinSize() / WidestType),
5147       ComputeScalableMaxVF);
5148   MaxVectorElementCount = MinVF(MaxVectorElementCount, MaxSafeVF);
5149   LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
5150                     << (MaxVectorElementCount * WidestType) << " bits.\n");
5151 
5152   if (!MaxVectorElementCount) {
5153     LLVM_DEBUG(dbgs() << "LV: The target has no "
5154                       << (ComputeScalableMaxVF ? "scalable" : "fixed")
5155                       << " vector registers.\n");
5156     return ElementCount::getFixed(1);
5157   }
5158 
5159   const auto TripCountEC = ElementCount::getFixed(ConstTripCount);
5160   if (ConstTripCount &&
5161       ElementCount::isKnownLE(TripCountEC, MaxVectorElementCount) &&
5162       (!FoldTailByMasking || isPowerOf2_32(ConstTripCount))) {
5163     // If loop trip count (TC) is known at compile time there is no point in
5164     // choosing VF greater than TC (as done in the loop below). Select maximum
5165     // power of two which doesn't exceed TC.
5166     // If MaxVectorElementCount is scalable, we only fall back on a fixed VF
5167     // when the TC is less than or equal to the known number of lanes.
5168     auto ClampedConstTripCount = PowerOf2Floor(ConstTripCount);
5169     LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to maximum power of two not "
5170                          "exceeding the constant trip count: "
5171                       << ClampedConstTripCount << "\n");
5172     return ElementCount::getFixed(ClampedConstTripCount);
5173   }
5174 
5175   TargetTransformInfo::RegisterKind RegKind =
5176       ComputeScalableMaxVF ? TargetTransformInfo::RGK_ScalableVector
5177                            : TargetTransformInfo::RGK_FixedWidthVector;
5178   ElementCount MaxVF = MaxVectorElementCount;
5179   if (MaximizeBandwidth || (MaximizeBandwidth.getNumOccurrences() == 0 &&
5180                             TTI.shouldMaximizeVectorBandwidth(RegKind))) {
5181     auto MaxVectorElementCountMaxBW = ElementCount::get(
5182         PowerOf2Floor(WidestRegister.getKnownMinSize() / SmallestType),
5183         ComputeScalableMaxVF);
5184     MaxVectorElementCountMaxBW = MinVF(MaxVectorElementCountMaxBW, MaxSafeVF);
5185 
5186     // Collect all viable vectorization factors larger than the default MaxVF
5187     // (i.e. MaxVectorElementCount).
5188     SmallVector<ElementCount, 8> VFs;
5189     for (ElementCount VS = MaxVectorElementCount * 2;
5190          ElementCount::isKnownLE(VS, MaxVectorElementCountMaxBW); VS *= 2)
5191       VFs.push_back(VS);
5192 
5193     // For each VF calculate its register usage.
5194     auto RUs = calculateRegisterUsage(VFs);
5195 
5196     // Select the largest VF which doesn't require more registers than existing
5197     // ones.
5198     for (int i = RUs.size() - 1; i >= 0; --i) {
5199       bool Selected = true;
5200       for (auto &pair : RUs[i].MaxLocalUsers) {
5201         unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5202         if (pair.second > TargetNumRegisters)
5203           Selected = false;
5204       }
5205       if (Selected) {
5206         MaxVF = VFs[i];
5207         break;
5208       }
5209     }
5210     if (ElementCount MinVF =
5211             TTI.getMinimumVF(SmallestType, ComputeScalableMaxVF)) {
5212       if (ElementCount::isKnownLT(MaxVF, MinVF)) {
5213         LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
5214                           << ") with target's minimum: " << MinVF << '\n');
5215         MaxVF = MinVF;
5216       }
5217     }
5218 
5219     // Invalidate any widening decisions we might have made, in case the loop
5220     // requires prediction (decided later), but we have already made some
5221     // load/store widening decisions.
5222     invalidateCostModelingDecisions();
5223   }
5224   return MaxVF;
5225 }
5226 
5227 Optional<unsigned> LoopVectorizationCostModel::getVScaleForTuning() const {
5228   if (TheFunction->hasFnAttribute(Attribute::VScaleRange)) {
5229     auto Attr = TheFunction->getFnAttribute(Attribute::VScaleRange);
5230     auto Min = Attr.getVScaleRangeMin();
5231     auto Max = Attr.getVScaleRangeMax();
5232     if (Max && Min == Max)
5233       return Max;
5234   }
5235 
5236   return TTI.getVScaleForTuning();
5237 }
5238 
5239 bool LoopVectorizationCostModel::isMoreProfitable(
5240     const VectorizationFactor &A, const VectorizationFactor &B) const {
5241   InstructionCost CostA = A.Cost;
5242   InstructionCost CostB = B.Cost;
5243 
5244   unsigned MaxTripCount = PSE.getSE()->getSmallConstantMaxTripCount(TheLoop);
5245 
5246   if (!A.Width.isScalable() && !B.Width.isScalable() && FoldTailByMasking &&
5247       MaxTripCount) {
5248     // If we are folding the tail and the trip count is a known (possibly small)
5249     // constant, the trip count will be rounded up to an integer number of
5250     // iterations. The total cost will be PerIterationCost*ceil(TripCount/VF),
5251     // which we compare directly. When not folding the tail, the total cost will
5252     // be PerIterationCost*floor(TC/VF) + Scalar remainder cost, and so is
5253     // approximated with the per-lane cost below instead of using the tripcount
5254     // as here.
5255     auto RTCostA = CostA * divideCeil(MaxTripCount, A.Width.getFixedValue());
5256     auto RTCostB = CostB * divideCeil(MaxTripCount, B.Width.getFixedValue());
5257     return RTCostA < RTCostB;
5258   }
5259 
5260   // Improve estimate for the vector width if it is scalable.
5261   unsigned EstimatedWidthA = A.Width.getKnownMinValue();
5262   unsigned EstimatedWidthB = B.Width.getKnownMinValue();
5263   if (Optional<unsigned> VScale = getVScaleForTuning()) {
5264     if (A.Width.isScalable())
5265       EstimatedWidthA *= VScale.getValue();
5266     if (B.Width.isScalable())
5267       EstimatedWidthB *= VScale.getValue();
5268   }
5269 
5270   // Assume vscale may be larger than 1 (or the value being tuned for),
5271   // so that scalable vectorization is slightly favorable over fixed-width
5272   // vectorization.
5273   if (A.Width.isScalable() && !B.Width.isScalable())
5274     return (CostA * B.Width.getFixedValue()) <= (CostB * EstimatedWidthA);
5275 
5276   // To avoid the need for FP division:
5277   //      (CostA / A.Width) < (CostB / B.Width)
5278   // <=>  (CostA * B.Width) < (CostB * A.Width)
5279   return (CostA * EstimatedWidthB) < (CostB * EstimatedWidthA);
5280 }
5281 
5282 VectorizationFactor LoopVectorizationCostModel::selectVectorizationFactor(
5283     const ElementCountSet &VFCandidates) {
5284   InstructionCost ExpectedCost = expectedCost(ElementCount::getFixed(1)).first;
5285   LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << ExpectedCost << ".\n");
5286   assert(ExpectedCost.isValid() && "Unexpected invalid cost for scalar loop");
5287   assert(VFCandidates.count(ElementCount::getFixed(1)) &&
5288          "Expected Scalar VF to be a candidate");
5289 
5290   const VectorizationFactor ScalarCost(ElementCount::getFixed(1), ExpectedCost,
5291                                        ExpectedCost);
5292   VectorizationFactor ChosenFactor = ScalarCost;
5293 
5294   bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
5295   if (ForceVectorization && VFCandidates.size() > 1) {
5296     // Ignore scalar width, because the user explicitly wants vectorization.
5297     // Initialize cost to max so that VF = 2 is, at least, chosen during cost
5298     // evaluation.
5299     ChosenFactor.Cost = InstructionCost::getMax();
5300   }
5301 
5302   SmallVector<InstructionVFPair> InvalidCosts;
5303   for (const auto &i : VFCandidates) {
5304     // The cost for scalar VF=1 is already calculated, so ignore it.
5305     if (i.isScalar())
5306       continue;
5307 
5308     VectorizationCostTy C = expectedCost(i, &InvalidCosts);
5309     VectorizationFactor Candidate(i, C.first, ScalarCost.ScalarCost);
5310 
5311 #ifndef NDEBUG
5312     unsigned AssumedMinimumVscale = 1;
5313     if (Optional<unsigned> VScale = getVScaleForTuning())
5314       AssumedMinimumVscale = *VScale;
5315     unsigned Width =
5316         Candidate.Width.isScalable()
5317             ? Candidate.Width.getKnownMinValue() * AssumedMinimumVscale
5318             : Candidate.Width.getFixedValue();
5319     LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
5320                       << " costs: " << (Candidate.Cost / Width));
5321     if (i.isScalable())
5322       LLVM_DEBUG(dbgs() << " (assuming a minimum vscale of "
5323                         << AssumedMinimumVscale << ")");
5324     LLVM_DEBUG(dbgs() << ".\n");
5325 #endif
5326 
5327     if (!C.second && !ForceVectorization) {
5328       LLVM_DEBUG(
5329           dbgs() << "LV: Not considering vector loop of width " << i
5330                  << " because it will not generate any vector instructions.\n");
5331       continue;
5332     }
5333 
5334     // If profitable add it to ProfitableVF list.
5335     if (isMoreProfitable(Candidate, ScalarCost))
5336       ProfitableVFs.push_back(Candidate);
5337 
5338     if (isMoreProfitable(Candidate, ChosenFactor))
5339       ChosenFactor = Candidate;
5340   }
5341 
5342   // Emit a report of VFs with invalid costs in the loop.
5343   if (!InvalidCosts.empty()) {
5344     // Group the remarks per instruction, keeping the instruction order from
5345     // InvalidCosts.
5346     std::map<Instruction *, unsigned> Numbering;
5347     unsigned I = 0;
5348     for (auto &Pair : InvalidCosts)
5349       if (!Numbering.count(Pair.first))
5350         Numbering[Pair.first] = I++;
5351 
5352     // Sort the list, first on instruction(number) then on VF.
5353     llvm::sort(InvalidCosts,
5354                [&Numbering](InstructionVFPair &A, InstructionVFPair &B) {
5355                  if (Numbering[A.first] != Numbering[B.first])
5356                    return Numbering[A.first] < Numbering[B.first];
5357                  ElementCountComparator ECC;
5358                  return ECC(A.second, B.second);
5359                });
5360 
5361     // For a list of ordered instruction-vf pairs:
5362     //   [(load, vf1), (load, vf2), (store, vf1)]
5363     // Group the instructions together to emit separate remarks for:
5364     //   load  (vf1, vf2)
5365     //   store (vf1)
5366     auto Tail = ArrayRef<InstructionVFPair>(InvalidCosts);
5367     auto Subset = ArrayRef<InstructionVFPair>();
5368     do {
5369       if (Subset.empty())
5370         Subset = Tail.take_front(1);
5371 
5372       Instruction *I = Subset.front().first;
5373 
5374       // If the next instruction is different, or if there are no other pairs,
5375       // emit a remark for the collated subset. e.g.
5376       //   [(load, vf1), (load, vf2))]
5377       // to emit:
5378       //  remark: invalid costs for 'load' at VF=(vf, vf2)
5379       if (Subset == Tail || Tail[Subset.size()].first != I) {
5380         std::string OutString;
5381         raw_string_ostream OS(OutString);
5382         assert(!Subset.empty() && "Unexpected empty range");
5383         OS << "Instruction with invalid costs prevented vectorization at VF=(";
5384         for (auto &Pair : Subset)
5385           OS << (Pair.second == Subset.front().second ? "" : ", ")
5386              << Pair.second;
5387         OS << "):";
5388         if (auto *CI = dyn_cast<CallInst>(I))
5389           OS << " call to " << CI->getCalledFunction()->getName();
5390         else
5391           OS << " " << I->getOpcodeName();
5392         OS.flush();
5393         reportVectorizationInfo(OutString, "InvalidCost", ORE, TheLoop, I);
5394         Tail = Tail.drop_front(Subset.size());
5395         Subset = {};
5396       } else
5397         // Grow the subset by one element
5398         Subset = Tail.take_front(Subset.size() + 1);
5399     } while (!Tail.empty());
5400   }
5401 
5402   if (!EnableCondStoresVectorization && NumPredStores) {
5403     reportVectorizationFailure("There are conditional stores.",
5404         "store that is conditionally executed prevents vectorization",
5405         "ConditionalStore", ORE, TheLoop);
5406     ChosenFactor = ScalarCost;
5407   }
5408 
5409   LLVM_DEBUG(if (ForceVectorization && !ChosenFactor.Width.isScalar() &&
5410                  ChosenFactor.Cost >= ScalarCost.Cost) dbgs()
5411              << "LV: Vectorization seems to be not beneficial, "
5412              << "but was forced by a user.\n");
5413   LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << ChosenFactor.Width << ".\n");
5414   return ChosenFactor;
5415 }
5416 
5417 bool LoopVectorizationCostModel::isCandidateForEpilogueVectorization(
5418     const Loop &L, ElementCount VF) const {
5419   // Cross iteration phis such as reductions need special handling and are
5420   // currently unsupported.
5421   if (any_of(L.getHeader()->phis(),
5422              [&](PHINode &Phi) { return Legal->isFirstOrderRecurrence(&Phi); }))
5423     return false;
5424 
5425   // Phis with uses outside of the loop require special handling and are
5426   // currently unsupported.
5427   for (auto &Entry : Legal->getInductionVars()) {
5428     // Look for uses of the value of the induction at the last iteration.
5429     Value *PostInc = Entry.first->getIncomingValueForBlock(L.getLoopLatch());
5430     for (User *U : PostInc->users())
5431       if (!L.contains(cast<Instruction>(U)))
5432         return false;
5433     // Look for uses of penultimate value of the induction.
5434     for (User *U : Entry.first->users())
5435       if (!L.contains(cast<Instruction>(U)))
5436         return false;
5437   }
5438 
5439   // Induction variables that are widened require special handling that is
5440   // currently not supported.
5441   if (any_of(Legal->getInductionVars(), [&](auto &Entry) {
5442         return !(this->isScalarAfterVectorization(Entry.first, VF) ||
5443                  this->isProfitableToScalarize(Entry.first, VF));
5444       }))
5445     return false;
5446 
5447   // Epilogue vectorization code has not been auditted to ensure it handles
5448   // non-latch exits properly.  It may be fine, but it needs auditted and
5449   // tested.
5450   if (L.getExitingBlock() != L.getLoopLatch())
5451     return false;
5452 
5453   return true;
5454 }
5455 
5456 bool LoopVectorizationCostModel::isEpilogueVectorizationProfitable(
5457     const ElementCount VF) const {
5458   // FIXME: We need a much better cost-model to take different parameters such
5459   // as register pressure, code size increase and cost of extra branches into
5460   // account. For now we apply a very crude heuristic and only consider loops
5461   // with vectorization factors larger than a certain value.
5462   // We also consider epilogue vectorization unprofitable for targets that don't
5463   // consider interleaving beneficial (eg. MVE).
5464   if (TTI.getMaxInterleaveFactor(VF.getKnownMinValue()) <= 1)
5465     return false;
5466   // FIXME: We should consider changing the threshold for scalable
5467   // vectors to take VScaleForTuning into account.
5468   if (VF.getKnownMinValue() >= EpilogueVectorizationMinVF)
5469     return true;
5470   return false;
5471 }
5472 
5473 VectorizationFactor
5474 LoopVectorizationCostModel::selectEpilogueVectorizationFactor(
5475     const ElementCount MainLoopVF, const LoopVectorizationPlanner &LVP) {
5476   VectorizationFactor Result = VectorizationFactor::Disabled();
5477   if (!EnableEpilogueVectorization) {
5478     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is disabled.\n";);
5479     return Result;
5480   }
5481 
5482   if (!isScalarEpilogueAllowed()) {
5483     LLVM_DEBUG(
5484         dbgs() << "LEV: Unable to vectorize epilogue because no epilogue is "
5485                   "allowed.\n";);
5486     return Result;
5487   }
5488 
5489   // Not really a cost consideration, but check for unsupported cases here to
5490   // simplify the logic.
5491   if (!isCandidateForEpilogueVectorization(*TheLoop, MainLoopVF)) {
5492     LLVM_DEBUG(
5493         dbgs() << "LEV: Unable to vectorize epilogue because the loop is "
5494                   "not a supported candidate.\n";);
5495     return Result;
5496   }
5497 
5498   if (EpilogueVectorizationForceVF > 1) {
5499     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization factor is forced.\n";);
5500     ElementCount ForcedEC = ElementCount::getFixed(EpilogueVectorizationForceVF);
5501     if (LVP.hasPlanWithVF(ForcedEC))
5502       return {ForcedEC, 0, 0};
5503     else {
5504       LLVM_DEBUG(
5505           dbgs()
5506               << "LEV: Epilogue vectorization forced factor is not viable.\n";);
5507       return Result;
5508     }
5509   }
5510 
5511   if (TheLoop->getHeader()->getParent()->hasOptSize() ||
5512       TheLoop->getHeader()->getParent()->hasMinSize()) {
5513     LLVM_DEBUG(
5514         dbgs()
5515             << "LEV: Epilogue vectorization skipped due to opt for size.\n";);
5516     return Result;
5517   }
5518 
5519   if (!isEpilogueVectorizationProfitable(MainLoopVF)) {
5520     LLVM_DEBUG(dbgs() << "LEV: Epilogue vectorization is not profitable for "
5521                          "this loop\n");
5522     return Result;
5523   }
5524 
5525   // If MainLoopVF = vscale x 2, and vscale is expected to be 4, then we know
5526   // the main loop handles 8 lanes per iteration. We could still benefit from
5527   // vectorizing the epilogue loop with VF=4.
5528   ElementCount EstimatedRuntimeVF = MainLoopVF;
5529   if (MainLoopVF.isScalable()) {
5530     EstimatedRuntimeVF = ElementCount::getFixed(MainLoopVF.getKnownMinValue());
5531     if (Optional<unsigned> VScale = getVScaleForTuning())
5532       EstimatedRuntimeVF *= *VScale;
5533   }
5534 
5535   for (auto &NextVF : ProfitableVFs)
5536     if (((!NextVF.Width.isScalable() && MainLoopVF.isScalable() &&
5537           ElementCount::isKnownLT(NextVF.Width, EstimatedRuntimeVF)) ||
5538          ElementCount::isKnownLT(NextVF.Width, MainLoopVF)) &&
5539         (Result.Width.isScalar() || isMoreProfitable(NextVF, Result)) &&
5540         LVP.hasPlanWithVF(NextVF.Width))
5541       Result = NextVF;
5542 
5543   if (Result != VectorizationFactor::Disabled())
5544     LLVM_DEBUG(dbgs() << "LEV: Vectorizing epilogue loop with VF = "
5545                       << Result.Width << "\n";);
5546   return Result;
5547 }
5548 
5549 std::pair<unsigned, unsigned>
5550 LoopVectorizationCostModel::getSmallestAndWidestTypes() {
5551   unsigned MinWidth = -1U;
5552   unsigned MaxWidth = 8;
5553   const DataLayout &DL = TheFunction->getParent()->getDataLayout();
5554   // For in-loop reductions, no element types are added to ElementTypesInLoop
5555   // if there are no loads/stores in the loop. In this case, check through the
5556   // reduction variables to determine the maximum width.
5557   if (ElementTypesInLoop.empty() && !Legal->getReductionVars().empty()) {
5558     // Reset MaxWidth so that we can find the smallest type used by recurrences
5559     // in the loop.
5560     MaxWidth = -1U;
5561     for (auto &PhiDescriptorPair : Legal->getReductionVars()) {
5562       const RecurrenceDescriptor &RdxDesc = PhiDescriptorPair.second;
5563       // When finding the min width used by the recurrence we need to account
5564       // for casts on the input operands of the recurrence.
5565       MaxWidth = std::min<unsigned>(
5566           MaxWidth, std::min<unsigned>(
5567                         RdxDesc.getMinWidthCastToRecurrenceTypeInBits(),
5568                         RdxDesc.getRecurrenceType()->getScalarSizeInBits()));
5569     }
5570   } else {
5571     for (Type *T : ElementTypesInLoop) {
5572       MinWidth = std::min<unsigned>(
5573           MinWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5574       MaxWidth = std::max<unsigned>(
5575           MaxWidth, DL.getTypeSizeInBits(T->getScalarType()).getFixedSize());
5576     }
5577   }
5578   return {MinWidth, MaxWidth};
5579 }
5580 
5581 void LoopVectorizationCostModel::collectElementTypesForWidening() {
5582   ElementTypesInLoop.clear();
5583   // For each block.
5584   for (BasicBlock *BB : TheLoop->blocks()) {
5585     // For each instruction in the loop.
5586     for (Instruction &I : BB->instructionsWithoutDebug()) {
5587       Type *T = I.getType();
5588 
5589       // Skip ignored values.
5590       if (ValuesToIgnore.count(&I))
5591         continue;
5592 
5593       // Only examine Loads, Stores and PHINodes.
5594       if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
5595         continue;
5596 
5597       // Examine PHI nodes that are reduction variables. Update the type to
5598       // account for the recurrence type.
5599       if (auto *PN = dyn_cast<PHINode>(&I)) {
5600         if (!Legal->isReductionVariable(PN))
5601           continue;
5602         const RecurrenceDescriptor &RdxDesc =
5603             Legal->getReductionVars().find(PN)->second;
5604         if (PreferInLoopReductions || useOrderedReductions(RdxDesc) ||
5605             TTI.preferInLoopReduction(RdxDesc.getOpcode(),
5606                                       RdxDesc.getRecurrenceType(),
5607                                       TargetTransformInfo::ReductionFlags()))
5608           continue;
5609         T = RdxDesc.getRecurrenceType();
5610       }
5611 
5612       // Examine the stored values.
5613       if (auto *ST = dyn_cast<StoreInst>(&I))
5614         T = ST->getValueOperand()->getType();
5615 
5616       assert(T->isSized() &&
5617              "Expected the load/store/recurrence type to be sized");
5618 
5619       ElementTypesInLoop.insert(T);
5620     }
5621   }
5622 }
5623 
5624 unsigned LoopVectorizationCostModel::selectInterleaveCount(ElementCount VF,
5625                                                            unsigned LoopCost) {
5626   // -- The interleave heuristics --
5627   // We interleave the loop in order to expose ILP and reduce the loop overhead.
5628   // There are many micro-architectural considerations that we can't predict
5629   // at this level. For example, frontend pressure (on decode or fetch) due to
5630   // code size, or the number and capabilities of the execution ports.
5631   //
5632   // We use the following heuristics to select the interleave count:
5633   // 1. If the code has reductions, then we interleave to break the cross
5634   // iteration dependency.
5635   // 2. If the loop is really small, then we interleave to reduce the loop
5636   // overhead.
5637   // 3. We don't interleave if we think that we will spill registers to memory
5638   // due to the increased register pressure.
5639 
5640   if (!isScalarEpilogueAllowed())
5641     return 1;
5642 
5643   // We used the distance for the interleave count.
5644   if (Legal->getMaxSafeDepDistBytes() != -1U)
5645     return 1;
5646 
5647   auto BestKnownTC = getSmallBestKnownTC(*PSE.getSE(), TheLoop);
5648   const bool HasReductions = !Legal->getReductionVars().empty();
5649   // Do not interleave loops with a relatively small known or estimated trip
5650   // count. But we will interleave when InterleaveSmallLoopScalarReduction is
5651   // enabled, and the code has scalar reductions(HasReductions && VF = 1),
5652   // because with the above conditions interleaving can expose ILP and break
5653   // cross iteration dependences for reductions.
5654   if (BestKnownTC && (*BestKnownTC < TinyTripCountInterleaveThreshold) &&
5655       !(InterleaveSmallLoopScalarReduction && HasReductions && VF.isScalar()))
5656     return 1;
5657 
5658   // If we did not calculate the cost for VF (because the user selected the VF)
5659   // then we calculate the cost of VF here.
5660   if (LoopCost == 0) {
5661     InstructionCost C = expectedCost(VF).first;
5662     assert(C.isValid() && "Expected to have chosen a VF with valid cost");
5663     LoopCost = *C.getValue();
5664 
5665     // Loop body is free and there is no need for interleaving.
5666     if (LoopCost == 0)
5667       return 1;
5668   }
5669 
5670   RegisterUsage R = calculateRegisterUsage({VF})[0];
5671   // We divide by these constants so assume that we have at least one
5672   // instruction that uses at least one register.
5673   for (auto& pair : R.MaxLocalUsers) {
5674     pair.second = std::max(pair.second, 1U);
5675   }
5676 
5677   // We calculate the interleave count using the following formula.
5678   // Subtract the number of loop invariants from the number of available
5679   // registers. These registers are used by all of the interleaved instances.
5680   // Next, divide the remaining registers by the number of registers that is
5681   // required by the loop, in order to estimate how many parallel instances
5682   // fit without causing spills. All of this is rounded down if necessary to be
5683   // a power of two. We want power of two interleave count to simplify any
5684   // addressing operations or alignment considerations.
5685   // We also want power of two interleave counts to ensure that the induction
5686   // variable of the vector loop wraps to zero, when tail is folded by masking;
5687   // this currently happens when OptForSize, in which case IC is set to 1 above.
5688   unsigned IC = UINT_MAX;
5689 
5690   for (auto& pair : R.MaxLocalUsers) {
5691     unsigned TargetNumRegisters = TTI.getNumberOfRegisters(pair.first);
5692     LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
5693                       << " registers of "
5694                       << TTI.getRegisterClassName(pair.first) << " register class\n");
5695     if (VF.isScalar()) {
5696       if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
5697         TargetNumRegisters = ForceTargetNumScalarRegs;
5698     } else {
5699       if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
5700         TargetNumRegisters = ForceTargetNumVectorRegs;
5701     }
5702     unsigned MaxLocalUsers = pair.second;
5703     unsigned LoopInvariantRegs = 0;
5704     if (R.LoopInvariantRegs.find(pair.first) != R.LoopInvariantRegs.end())
5705       LoopInvariantRegs = R.LoopInvariantRegs[pair.first];
5706 
5707     unsigned TmpIC = PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs) / MaxLocalUsers);
5708     // Don't count the induction variable as interleaved.
5709     if (EnableIndVarRegisterHeur) {
5710       TmpIC =
5711           PowerOf2Floor((TargetNumRegisters - LoopInvariantRegs - 1) /
5712                         std::max(1U, (MaxLocalUsers - 1)));
5713     }
5714 
5715     IC = std::min(IC, TmpIC);
5716   }
5717 
5718   // Clamp the interleave ranges to reasonable counts.
5719   unsigned MaxInterleaveCount =
5720       TTI.getMaxInterleaveFactor(VF.getKnownMinValue());
5721 
5722   // Check if the user has overridden the max.
5723   if (VF.isScalar()) {
5724     if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
5725       MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
5726   } else {
5727     if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
5728       MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
5729   }
5730 
5731   // If trip count is known or estimated compile time constant, limit the
5732   // interleave count to be less than the trip count divided by VF, provided it
5733   // is at least 1.
5734   //
5735   // For scalable vectors we can't know if interleaving is beneficial. It may
5736   // not be beneficial for small loops if none of the lanes in the second vector
5737   // iterations is enabled. However, for larger loops, there is likely to be a
5738   // similar benefit as for fixed-width vectors. For now, we choose to leave
5739   // the InterleaveCount as if vscale is '1', although if some information about
5740   // the vector is known (e.g. min vector size), we can make a better decision.
5741   if (BestKnownTC) {
5742     MaxInterleaveCount =
5743         std::min(*BestKnownTC / VF.getKnownMinValue(), MaxInterleaveCount);
5744     // Make sure MaxInterleaveCount is greater than 0.
5745     MaxInterleaveCount = std::max(1u, MaxInterleaveCount);
5746   }
5747 
5748   assert(MaxInterleaveCount > 0 &&
5749          "Maximum interleave count must be greater than 0");
5750 
5751   // Clamp the calculated IC to be between the 1 and the max interleave count
5752   // that the target and trip count allows.
5753   if (IC > MaxInterleaveCount)
5754     IC = MaxInterleaveCount;
5755   else
5756     // Make sure IC is greater than 0.
5757     IC = std::max(1u, IC);
5758 
5759   assert(IC > 0 && "Interleave count must be greater than 0.");
5760 
5761   // Interleave if we vectorized this loop and there is a reduction that could
5762   // benefit from interleaving.
5763   if (VF.isVector() && HasReductions) {
5764     LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
5765     return IC;
5766   }
5767 
5768   // For any scalar loop that either requires runtime checks or predication we
5769   // are better off leaving this to the unroller. Note that if we've already
5770   // vectorized the loop we will have done the runtime check and so interleaving
5771   // won't require further checks.
5772   bool ScalarInterleavingRequiresPredication =
5773       (VF.isScalar() && any_of(TheLoop->blocks(), [this](BasicBlock *BB) {
5774          return Legal->blockNeedsPredication(BB);
5775        }));
5776   bool ScalarInterleavingRequiresRuntimePointerCheck =
5777       (VF.isScalar() && Legal->getRuntimePointerChecking()->Need);
5778 
5779   // We want to interleave small loops in order to reduce the loop overhead and
5780   // potentially expose ILP opportunities.
5781   LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n'
5782                     << "LV: IC is " << IC << '\n'
5783                     << "LV: VF is " << VF << '\n');
5784   const bool AggressivelyInterleaveReductions =
5785       TTI.enableAggressiveInterleaving(HasReductions);
5786   if (!ScalarInterleavingRequiresRuntimePointerCheck &&
5787       !ScalarInterleavingRequiresPredication && LoopCost < SmallLoopCost) {
5788     // We assume that the cost overhead is 1 and we use the cost model
5789     // to estimate the cost of the loop and interleave until the cost of the
5790     // loop overhead is about 5% of the cost of the loop.
5791     unsigned SmallIC =
5792         std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
5793 
5794     // Interleave until store/load ports (estimated by max interleave count) are
5795     // saturated.
5796     unsigned NumStores = Legal->getNumStores();
5797     unsigned NumLoads = Legal->getNumLoads();
5798     unsigned StoresIC = IC / (NumStores ? NumStores : 1);
5799     unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
5800 
5801     // There is little point in interleaving for reductions containing selects
5802     // and compares when VF=1 since it may just create more overhead than it's
5803     // worth for loops with small trip counts. This is because we still have to
5804     // do the final reduction after the loop.
5805     bool HasSelectCmpReductions =
5806         HasReductions &&
5807         any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5808           const RecurrenceDescriptor &RdxDesc = Reduction.second;
5809           return RecurrenceDescriptor::isSelectCmpRecurrenceKind(
5810               RdxDesc.getRecurrenceKind());
5811         });
5812     if (HasSelectCmpReductions) {
5813       LLVM_DEBUG(dbgs() << "LV: Not interleaving select-cmp reductions.\n");
5814       return 1;
5815     }
5816 
5817     // If we have a scalar reduction (vector reductions are already dealt with
5818     // by this point), we can increase the critical path length if the loop
5819     // we're interleaving is inside another loop. For tree-wise reductions
5820     // set the limit to 2, and for ordered reductions it's best to disable
5821     // interleaving entirely.
5822     if (HasReductions && TheLoop->getLoopDepth() > 1) {
5823       bool HasOrderedReductions =
5824           any_of(Legal->getReductionVars(), [&](auto &Reduction) -> bool {
5825             const RecurrenceDescriptor &RdxDesc = Reduction.second;
5826             return RdxDesc.isOrdered();
5827           });
5828       if (HasOrderedReductions) {
5829         LLVM_DEBUG(
5830             dbgs() << "LV: Not interleaving scalar ordered reductions.\n");
5831         return 1;
5832       }
5833 
5834       unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
5835       SmallIC = std::min(SmallIC, F);
5836       StoresIC = std::min(StoresIC, F);
5837       LoadsIC = std::min(LoadsIC, F);
5838     }
5839 
5840     if (EnableLoadStoreRuntimeInterleave &&
5841         std::max(StoresIC, LoadsIC) > SmallIC) {
5842       LLVM_DEBUG(
5843           dbgs() << "LV: Interleaving to saturate store or load ports.\n");
5844       return std::max(StoresIC, LoadsIC);
5845     }
5846 
5847     // If there are scalar reductions and TTI has enabled aggressive
5848     // interleaving for reductions, we will interleave to expose ILP.
5849     if (InterleaveSmallLoopScalarReduction && VF.isScalar() &&
5850         AggressivelyInterleaveReductions) {
5851       LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5852       // Interleave no less than SmallIC but not as aggressive as the normal IC
5853       // to satisfy the rare situation when resources are too limited.
5854       return std::max(IC / 2, SmallIC);
5855     } else {
5856       LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
5857       return SmallIC;
5858     }
5859   }
5860 
5861   // Interleave if this is a large loop (small loops are already dealt with by
5862   // this point) that could benefit from interleaving.
5863   if (AggressivelyInterleaveReductions) {
5864     LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
5865     return IC;
5866   }
5867 
5868   LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
5869   return 1;
5870 }
5871 
5872 SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
5873 LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<ElementCount> VFs) {
5874   // This function calculates the register usage by measuring the highest number
5875   // of values that are alive at a single location. Obviously, this is a very
5876   // rough estimation. We scan the loop in a topological order in order and
5877   // assign a number to each instruction. We use RPO to ensure that defs are
5878   // met before their users. We assume that each instruction that has in-loop
5879   // users starts an interval. We record every time that an in-loop value is
5880   // used, so we have a list of the first and last occurrences of each
5881   // instruction. Next, we transpose this data structure into a multi map that
5882   // holds the list of intervals that *end* at a specific location. This multi
5883   // map allows us to perform a linear search. We scan the instructions linearly
5884   // and record each time that a new interval starts, by placing it in a set.
5885   // If we find this value in the multi-map then we remove it from the set.
5886   // The max register usage is the maximum size of the set.
5887   // We also search for instructions that are defined outside the loop, but are
5888   // used inside the loop. We need this number separately from the max-interval
5889   // usage number because when we unroll, loop-invariant values do not take
5890   // more register.
5891   LoopBlocksDFS DFS(TheLoop);
5892   DFS.perform(LI);
5893 
5894   RegisterUsage RU;
5895 
5896   // Each 'key' in the map opens a new interval. The values
5897   // of the map are the index of the 'last seen' usage of the
5898   // instruction that is the key.
5899   using IntervalMap = DenseMap<Instruction *, unsigned>;
5900 
5901   // Maps instruction to its index.
5902   SmallVector<Instruction *, 64> IdxToInstr;
5903   // Marks the end of each interval.
5904   IntervalMap EndPoint;
5905   // Saves the list of instruction indices that are used in the loop.
5906   SmallPtrSet<Instruction *, 8> Ends;
5907   // Saves the list of values that are used in the loop but are
5908   // defined outside the loop, such as arguments and constants.
5909   SmallPtrSet<Value *, 8> LoopInvariants;
5910 
5911   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
5912     for (Instruction &I : BB->instructionsWithoutDebug()) {
5913       IdxToInstr.push_back(&I);
5914 
5915       // Save the end location of each USE.
5916       for (Value *U : I.operands()) {
5917         auto *Instr = dyn_cast<Instruction>(U);
5918 
5919         // Ignore non-instruction values such as arguments, constants, etc.
5920         if (!Instr)
5921           continue;
5922 
5923         // If this instruction is outside the loop then record it and continue.
5924         if (!TheLoop->contains(Instr)) {
5925           LoopInvariants.insert(Instr);
5926           continue;
5927         }
5928 
5929         // Overwrite previous end points.
5930         EndPoint[Instr] = IdxToInstr.size();
5931         Ends.insert(Instr);
5932       }
5933     }
5934   }
5935 
5936   // Saves the list of intervals that end with the index in 'key'.
5937   using InstrList = SmallVector<Instruction *, 2>;
5938   DenseMap<unsigned, InstrList> TransposeEnds;
5939 
5940   // Transpose the EndPoints to a list of values that end at each index.
5941   for (auto &Interval : EndPoint)
5942     TransposeEnds[Interval.second].push_back(Interval.first);
5943 
5944   SmallPtrSet<Instruction *, 8> OpenIntervals;
5945   SmallVector<RegisterUsage, 8> RUs(VFs.size());
5946   SmallVector<SmallMapVector<unsigned, unsigned, 4>, 8> MaxUsages(VFs.size());
5947 
5948   LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
5949 
5950   auto GetRegUsage = [&TTI = TTI](Type *Ty, ElementCount VF) -> unsigned {
5951     if (Ty->isTokenTy() || !VectorType::isValidElementType(Ty))
5952       return 0;
5953     return TTI.getRegUsageForType(VectorType::get(Ty, VF));
5954   };
5955 
5956   for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
5957     Instruction *I = IdxToInstr[i];
5958 
5959     // Remove all of the instructions that end at this location.
5960     InstrList &List = TransposeEnds[i];
5961     for (Instruction *ToRemove : List)
5962       OpenIntervals.erase(ToRemove);
5963 
5964     // Ignore instructions that are never used within the loop.
5965     if (!Ends.count(I))
5966       continue;
5967 
5968     // Skip ignored values.
5969     if (ValuesToIgnore.count(I))
5970       continue;
5971 
5972     // For each VF find the maximum usage of registers.
5973     for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
5974       // Count the number of live intervals.
5975       SmallMapVector<unsigned, unsigned, 4> RegUsage;
5976 
5977       if (VFs[j].isScalar()) {
5978         for (auto Inst : OpenIntervals) {
5979           unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
5980           if (RegUsage.find(ClassID) == RegUsage.end())
5981             RegUsage[ClassID] = 1;
5982           else
5983             RegUsage[ClassID] += 1;
5984         }
5985       } else {
5986         collectUniformsAndScalars(VFs[j]);
5987         for (auto Inst : OpenIntervals) {
5988           // Skip ignored values for VF > 1.
5989           if (VecValuesToIgnore.count(Inst))
5990             continue;
5991           if (isScalarAfterVectorization(Inst, VFs[j])) {
5992             unsigned ClassID = TTI.getRegisterClassForType(false, Inst->getType());
5993             if (RegUsage.find(ClassID) == RegUsage.end())
5994               RegUsage[ClassID] = 1;
5995             else
5996               RegUsage[ClassID] += 1;
5997           } else {
5998             unsigned ClassID = TTI.getRegisterClassForType(true, Inst->getType());
5999             if (RegUsage.find(ClassID) == RegUsage.end())
6000               RegUsage[ClassID] = GetRegUsage(Inst->getType(), VFs[j]);
6001             else
6002               RegUsage[ClassID] += GetRegUsage(Inst->getType(), VFs[j]);
6003           }
6004         }
6005       }
6006 
6007       for (auto& pair : RegUsage) {
6008         if (MaxUsages[j].find(pair.first) != MaxUsages[j].end())
6009           MaxUsages[j][pair.first] = std::max(MaxUsages[j][pair.first], pair.second);
6010         else
6011           MaxUsages[j][pair.first] = pair.second;
6012       }
6013     }
6014 
6015     LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
6016                       << OpenIntervals.size() << '\n');
6017 
6018     // Add the current instruction to the list of open intervals.
6019     OpenIntervals.insert(I);
6020   }
6021 
6022   for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
6023     SmallMapVector<unsigned, unsigned, 4> Invariant;
6024 
6025     for (auto Inst : LoopInvariants) {
6026       unsigned Usage =
6027           VFs[i].isScalar() ? 1 : GetRegUsage(Inst->getType(), VFs[i]);
6028       unsigned ClassID =
6029           TTI.getRegisterClassForType(VFs[i].isVector(), Inst->getType());
6030       if (Invariant.find(ClassID) == Invariant.end())
6031         Invariant[ClassID] = Usage;
6032       else
6033         Invariant[ClassID] += Usage;
6034     }
6035 
6036     LLVM_DEBUG({
6037       dbgs() << "LV(REG): VF = " << VFs[i] << '\n';
6038       dbgs() << "LV(REG): Found max usage: " << MaxUsages[i].size()
6039              << " item\n";
6040       for (const auto &pair : MaxUsages[i]) {
6041         dbgs() << "LV(REG): RegisterClass: "
6042                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6043                << " registers\n";
6044       }
6045       dbgs() << "LV(REG): Found invariant usage: " << Invariant.size()
6046              << " item\n";
6047       for (const auto &pair : Invariant) {
6048         dbgs() << "LV(REG): RegisterClass: "
6049                << TTI.getRegisterClassName(pair.first) << ", " << pair.second
6050                << " registers\n";
6051       }
6052     });
6053 
6054     RU.LoopInvariantRegs = Invariant;
6055     RU.MaxLocalUsers = MaxUsages[i];
6056     RUs[i] = RU;
6057   }
6058 
6059   return RUs;
6060 }
6061 
6062 bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I,
6063                                                            ElementCount VF) {
6064   // TODO: Cost model for emulated masked load/store is completely
6065   // broken. This hack guides the cost model to use an artificially
6066   // high enough value to practically disable vectorization with such
6067   // operations, except where previously deployed legality hack allowed
6068   // using very low cost values. This is to avoid regressions coming simply
6069   // from moving "masked load/store" check from legality to cost model.
6070   // Masked Load/Gather emulation was previously never allowed.
6071   // Limited number of Masked Store/Scatter emulation was allowed.
6072   assert(isPredicatedInst(I, VF) && "Expecting a scalar emulated instruction");
6073   return isa<LoadInst>(I) ||
6074          (isa<StoreInst>(I) &&
6075           NumPredStores > NumberOfStoresToPredicate);
6076 }
6077 
6078 void LoopVectorizationCostModel::collectInstsToScalarize(ElementCount VF) {
6079   // If we aren't vectorizing the loop, or if we've already collected the
6080   // instructions to scalarize, there's nothing to do. Collection may already
6081   // have occurred if we have a user-selected VF and are now computing the
6082   // expected cost for interleaving.
6083   if (VF.isScalar() || VF.isZero() ||
6084       InstsToScalarize.find(VF) != InstsToScalarize.end())
6085     return;
6086 
6087   // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
6088   // not profitable to scalarize any instructions, the presence of VF in the
6089   // map will indicate that we've analyzed it already.
6090   ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
6091 
6092   // Find all the instructions that are scalar with predication in the loop and
6093   // determine if it would be better to not if-convert the blocks they are in.
6094   // If so, we also record the instructions to scalarize.
6095   for (BasicBlock *BB : TheLoop->blocks()) {
6096     if (!blockNeedsPredicationForAnyReason(BB))
6097       continue;
6098     for (Instruction &I : *BB)
6099       if (isScalarWithPredication(&I, VF)) {
6100         ScalarCostsTy ScalarCosts;
6101         // Do not apply discount if scalable, because that would lead to
6102         // invalid scalarization costs.
6103         // Do not apply discount logic if hacked cost is needed
6104         // for emulated masked memrefs.
6105         if (!VF.isScalable() && !useEmulatedMaskMemRefHack(&I, VF) &&
6106             computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
6107           ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
6108         // Remember that BB will remain after vectorization.
6109         PredicatedBBsAfterVectorization.insert(BB);
6110       }
6111   }
6112 }
6113 
6114 int LoopVectorizationCostModel::computePredInstDiscount(
6115     Instruction *PredInst, ScalarCostsTy &ScalarCosts, ElementCount VF) {
6116   assert(!isUniformAfterVectorization(PredInst, VF) &&
6117          "Instruction marked uniform-after-vectorization will be predicated");
6118 
6119   // Initialize the discount to zero, meaning that the scalar version and the
6120   // vector version cost the same.
6121   InstructionCost Discount = 0;
6122 
6123   // Holds instructions to analyze. The instructions we visit are mapped in
6124   // ScalarCosts. Those instructions are the ones that would be scalarized if
6125   // we find that the scalar version costs less.
6126   SmallVector<Instruction *, 8> Worklist;
6127 
6128   // Returns true if the given instruction can be scalarized.
6129   auto canBeScalarized = [&](Instruction *I) -> bool {
6130     // We only attempt to scalarize instructions forming a single-use chain
6131     // from the original predicated block that would otherwise be vectorized.
6132     // Although not strictly necessary, we give up on instructions we know will
6133     // already be scalar to avoid traversing chains that are unlikely to be
6134     // beneficial.
6135     if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
6136         isScalarAfterVectorization(I, VF))
6137       return false;
6138 
6139     // If the instruction is scalar with predication, it will be analyzed
6140     // separately. We ignore it within the context of PredInst.
6141     if (isScalarWithPredication(I, VF))
6142       return false;
6143 
6144     // If any of the instruction's operands are uniform after vectorization,
6145     // the instruction cannot be scalarized. This prevents, for example, a
6146     // masked load from being scalarized.
6147     //
6148     // We assume we will only emit a value for lane zero of an instruction
6149     // marked uniform after vectorization, rather than VF identical values.
6150     // Thus, if we scalarize an instruction that uses a uniform, we would
6151     // create uses of values corresponding to the lanes we aren't emitting code
6152     // for. This behavior can be changed by allowing getScalarValue to clone
6153     // the lane zero values for uniforms rather than asserting.
6154     for (Use &U : I->operands())
6155       if (auto *J = dyn_cast<Instruction>(U.get()))
6156         if (isUniformAfterVectorization(J, VF))
6157           return false;
6158 
6159     // Otherwise, we can scalarize the instruction.
6160     return true;
6161   };
6162 
6163   // Compute the expected cost discount from scalarizing the entire expression
6164   // feeding the predicated instruction. We currently only consider expressions
6165   // that are single-use instruction chains.
6166   Worklist.push_back(PredInst);
6167   while (!Worklist.empty()) {
6168     Instruction *I = Worklist.pop_back_val();
6169 
6170     // If we've already analyzed the instruction, there's nothing to do.
6171     if (ScalarCosts.find(I) != ScalarCosts.end())
6172       continue;
6173 
6174     // Compute the cost of the vector instruction. Note that this cost already
6175     // includes the scalarization overhead of the predicated instruction.
6176     InstructionCost VectorCost = getInstructionCost(I, VF).first;
6177 
6178     // Compute the cost of the scalarized instruction. This cost is the cost of
6179     // the instruction as if it wasn't if-converted and instead remained in the
6180     // predicated block. We will scale this cost by block probability after
6181     // computing the scalarization overhead.
6182     InstructionCost ScalarCost =
6183         VF.getFixedValue() *
6184         getInstructionCost(I, ElementCount::getFixed(1)).first;
6185 
6186     // Compute the scalarization overhead of needed insertelement instructions
6187     // and phi nodes.
6188     if (isScalarWithPredication(I, VF) && !I->getType()->isVoidTy()) {
6189       ScalarCost += TTI.getScalarizationOverhead(
6190           cast<VectorType>(ToVectorTy(I->getType(), VF)),
6191           APInt::getAllOnes(VF.getFixedValue()), true, false);
6192       ScalarCost +=
6193           VF.getFixedValue() *
6194           TTI.getCFInstrCost(Instruction::PHI, TTI::TCK_RecipThroughput);
6195     }
6196 
6197     // Compute the scalarization overhead of needed extractelement
6198     // instructions. For each of the instruction's operands, if the operand can
6199     // be scalarized, add it to the worklist; otherwise, account for the
6200     // overhead.
6201     for (Use &U : I->operands())
6202       if (auto *J = dyn_cast<Instruction>(U.get())) {
6203         assert(VectorType::isValidElementType(J->getType()) &&
6204                "Instruction has non-scalar type");
6205         if (canBeScalarized(J))
6206           Worklist.push_back(J);
6207         else if (needsExtract(J, VF)) {
6208           ScalarCost += TTI.getScalarizationOverhead(
6209               cast<VectorType>(ToVectorTy(J->getType(), VF)),
6210               APInt::getAllOnes(VF.getFixedValue()), false, true);
6211         }
6212       }
6213 
6214     // Scale the total scalar cost by block probability.
6215     ScalarCost /= getReciprocalPredBlockProb();
6216 
6217     // Compute the discount. A non-negative discount means the vector version
6218     // of the instruction costs more, and scalarizing would be beneficial.
6219     Discount += VectorCost - ScalarCost;
6220     ScalarCosts[I] = ScalarCost;
6221   }
6222 
6223   return *Discount.getValue();
6224 }
6225 
6226 LoopVectorizationCostModel::VectorizationCostTy
6227 LoopVectorizationCostModel::expectedCost(
6228     ElementCount VF, SmallVectorImpl<InstructionVFPair> *Invalid) {
6229   VectorizationCostTy Cost;
6230 
6231   // For each block.
6232   for (BasicBlock *BB : TheLoop->blocks()) {
6233     VectorizationCostTy BlockCost;
6234 
6235     // For each instruction in the old loop.
6236     for (Instruction &I : BB->instructionsWithoutDebug()) {
6237       // Skip ignored values.
6238       if (ValuesToIgnore.count(&I) ||
6239           (VF.isVector() && VecValuesToIgnore.count(&I)))
6240         continue;
6241 
6242       VectorizationCostTy C = getInstructionCost(&I, VF);
6243 
6244       // Check if we should override the cost.
6245       if (C.first.isValid() &&
6246           ForceTargetInstructionCost.getNumOccurrences() > 0)
6247         C.first = InstructionCost(ForceTargetInstructionCost);
6248 
6249       // Keep a list of instructions with invalid costs.
6250       if (Invalid && !C.first.isValid())
6251         Invalid->emplace_back(&I, VF);
6252 
6253       BlockCost.first += C.first;
6254       BlockCost.second |= C.second;
6255       LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
6256                         << " for VF " << VF << " For instruction: " << I
6257                         << '\n');
6258     }
6259 
6260     // If we are vectorizing a predicated block, it will have been
6261     // if-converted. This means that the block's instructions (aside from
6262     // stores and instructions that may divide by zero) will now be
6263     // unconditionally executed. For the scalar case, we may not always execute
6264     // the predicated block, if it is an if-else block. Thus, scale the block's
6265     // cost by the probability of executing it. blockNeedsPredication from
6266     // Legal is used so as to not include all blocks in tail folded loops.
6267     if (VF.isScalar() && Legal->blockNeedsPredication(BB))
6268       BlockCost.first /= getReciprocalPredBlockProb();
6269 
6270     Cost.first += BlockCost.first;
6271     Cost.second |= BlockCost.second;
6272   }
6273 
6274   return Cost;
6275 }
6276 
6277 /// Gets Address Access SCEV after verifying that the access pattern
6278 /// is loop invariant except the induction variable dependence.
6279 ///
6280 /// This SCEV can be sent to the Target in order to estimate the address
6281 /// calculation cost.
6282 static const SCEV *getAddressAccessSCEV(
6283               Value *Ptr,
6284               LoopVectorizationLegality *Legal,
6285               PredicatedScalarEvolution &PSE,
6286               const Loop *TheLoop) {
6287 
6288   auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
6289   if (!Gep)
6290     return nullptr;
6291 
6292   // We are looking for a gep with all loop invariant indices except for one
6293   // which should be an induction variable.
6294   auto SE = PSE.getSE();
6295   unsigned NumOperands = Gep->getNumOperands();
6296   for (unsigned i = 1; i < NumOperands; ++i) {
6297     Value *Opd = Gep->getOperand(i);
6298     if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
6299         !Legal->isInductionVariable(Opd))
6300       return nullptr;
6301   }
6302 
6303   // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
6304   return PSE.getSCEV(Ptr);
6305 }
6306 
6307 static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
6308   return Legal->hasStride(I->getOperand(0)) ||
6309          Legal->hasStride(I->getOperand(1));
6310 }
6311 
6312 InstructionCost
6313 LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
6314                                                         ElementCount VF) {
6315   assert(VF.isVector() &&
6316          "Scalarization cost of instruction implies vectorization.");
6317   if (VF.isScalable())
6318     return InstructionCost::getInvalid();
6319 
6320   Type *ValTy = getLoadStoreType(I);
6321   auto SE = PSE.getSE();
6322 
6323   unsigned AS = getLoadStoreAddressSpace(I);
6324   Value *Ptr = getLoadStorePointerOperand(I);
6325   Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
6326   // NOTE: PtrTy is a vector to signal `TTI::getAddressComputationCost`
6327   //       that it is being called from this specific place.
6328 
6329   // Figure out whether the access is strided and get the stride value
6330   // if it's known in compile time
6331   const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
6332 
6333   // Get the cost of the scalar memory instruction and address computation.
6334   InstructionCost Cost =
6335       VF.getKnownMinValue() * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
6336 
6337   // Don't pass *I here, since it is scalar but will actually be part of a
6338   // vectorized loop where the user of it is a vectorized instruction.
6339   const Align Alignment = getLoadStoreAlignment(I);
6340   Cost += VF.getKnownMinValue() *
6341           TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
6342                               AS, TTI::TCK_RecipThroughput);
6343 
6344   // Get the overhead of the extractelement and insertelement instructions
6345   // we might create due to scalarization.
6346   Cost += getScalarizationOverhead(I, VF);
6347 
6348   // If we have a predicated load/store, it will need extra i1 extracts and
6349   // conditional branches, but may not be executed for each vector lane. Scale
6350   // the cost by the probability of executing the predicated block.
6351   if (isPredicatedInst(I, VF)) {
6352     Cost /= getReciprocalPredBlockProb();
6353 
6354     // Add the cost of an i1 extract and a branch
6355     auto *Vec_i1Ty =
6356         VectorType::get(IntegerType::getInt1Ty(ValTy->getContext()), VF);
6357     Cost += TTI.getScalarizationOverhead(
6358         Vec_i1Ty, APInt::getAllOnes(VF.getKnownMinValue()),
6359         /*Insert=*/false, /*Extract=*/true);
6360     Cost += TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
6361 
6362     if (useEmulatedMaskMemRefHack(I, VF))
6363       // Artificially setting to a high enough value to practically disable
6364       // vectorization with such operations.
6365       Cost = 3000000;
6366   }
6367 
6368   return Cost;
6369 }
6370 
6371 InstructionCost
6372 LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
6373                                                     ElementCount VF) {
6374   Type *ValTy = getLoadStoreType(I);
6375   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6376   Value *Ptr = getLoadStorePointerOperand(I);
6377   unsigned AS = getLoadStoreAddressSpace(I);
6378   int ConsecutiveStride = Legal->isConsecutivePtr(ValTy, Ptr);
6379   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6380 
6381   assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6382          "Stride should be 1 or -1 for consecutive memory access");
6383   const Align Alignment = getLoadStoreAlignment(I);
6384   InstructionCost Cost = 0;
6385   if (Legal->isMaskRequired(I))
6386     Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6387                                       CostKind);
6388   else
6389     Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS,
6390                                 CostKind, I);
6391 
6392   bool Reverse = ConsecutiveStride < 0;
6393   if (Reverse)
6394     Cost +=
6395         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6396   return Cost;
6397 }
6398 
6399 InstructionCost
6400 LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
6401                                                 ElementCount VF) {
6402   assert(Legal->isUniformMemOp(*I));
6403 
6404   Type *ValTy = getLoadStoreType(I);
6405   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6406   const Align Alignment = getLoadStoreAlignment(I);
6407   unsigned AS = getLoadStoreAddressSpace(I);
6408   enum TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6409   if (isa<LoadInst>(I)) {
6410     return TTI.getAddressComputationCost(ValTy) +
6411            TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS,
6412                                CostKind) +
6413            TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
6414   }
6415   StoreInst *SI = cast<StoreInst>(I);
6416 
6417   bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
6418   return TTI.getAddressComputationCost(ValTy) +
6419          TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS,
6420                              CostKind) +
6421          (isLoopInvariantStoreValue
6422               ? 0
6423               : TTI.getVectorInstrCost(Instruction::ExtractElement, VectorTy,
6424                                        VF.getKnownMinValue() - 1));
6425 }
6426 
6427 InstructionCost
6428 LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
6429                                                  ElementCount VF) {
6430   Type *ValTy = getLoadStoreType(I);
6431   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6432   const Align Alignment = getLoadStoreAlignment(I);
6433   const Value *Ptr = getLoadStorePointerOperand(I);
6434 
6435   return TTI.getAddressComputationCost(VectorTy) +
6436          TTI.getGatherScatterOpCost(
6437              I->getOpcode(), VectorTy, Ptr, Legal->isMaskRequired(I), Alignment,
6438              TargetTransformInfo::TCK_RecipThroughput, I);
6439 }
6440 
6441 InstructionCost
6442 LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
6443                                                    ElementCount VF) {
6444   // TODO: Once we have support for interleaving with scalable vectors
6445   // we can calculate the cost properly here.
6446   if (VF.isScalable())
6447     return InstructionCost::getInvalid();
6448 
6449   Type *ValTy = getLoadStoreType(I);
6450   auto *VectorTy = cast<VectorType>(ToVectorTy(ValTy, VF));
6451   unsigned AS = getLoadStoreAddressSpace(I);
6452 
6453   auto Group = getInterleavedAccessGroup(I);
6454   assert(Group && "Fail to get an interleaved access group.");
6455 
6456   unsigned InterleaveFactor = Group->getFactor();
6457   auto *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
6458 
6459   // Holds the indices of existing members in the interleaved group.
6460   SmallVector<unsigned, 4> Indices;
6461   for (unsigned IF = 0; IF < InterleaveFactor; IF++)
6462     if (Group->getMember(IF))
6463       Indices.push_back(IF);
6464 
6465   // Calculate the cost of the whole interleaved group.
6466   bool UseMaskForGaps =
6467       (Group->requiresScalarEpilogue() && !isScalarEpilogueAllowed()) ||
6468       (isa<StoreInst>(I) && (Group->getNumMembers() < Group->getFactor()));
6469   InstructionCost Cost = TTI.getInterleavedMemoryOpCost(
6470       I->getOpcode(), WideVecTy, Group->getFactor(), Indices, Group->getAlign(),
6471       AS, TTI::TCK_RecipThroughput, Legal->isMaskRequired(I), UseMaskForGaps);
6472 
6473   if (Group->isReverse()) {
6474     // TODO: Add support for reversed masked interleaved access.
6475     assert(!Legal->isMaskRequired(I) &&
6476            "Reverse masked interleaved access not supported.");
6477     Cost +=
6478         Group->getNumMembers() *
6479         TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, None, 0);
6480   }
6481   return Cost;
6482 }
6483 
6484 Optional<InstructionCost> LoopVectorizationCostModel::getReductionPatternCost(
6485     Instruction *I, ElementCount VF, Type *Ty, TTI::TargetCostKind CostKind) {
6486   using namespace llvm::PatternMatch;
6487   // Early exit for no inloop reductions
6488   if (InLoopReductionChains.empty() || VF.isScalar() || !isa<VectorType>(Ty))
6489     return None;
6490   auto *VectorTy = cast<VectorType>(Ty);
6491 
6492   // We are looking for a pattern of, and finding the minimal acceptable cost:
6493   //  reduce(mul(ext(A), ext(B))) or
6494   //  reduce(mul(A, B)) or
6495   //  reduce(ext(A)) or
6496   //  reduce(A).
6497   // The basic idea is that we walk down the tree to do that, finding the root
6498   // reduction instruction in InLoopReductionImmediateChains. From there we find
6499   // the pattern of mul/ext and test the cost of the entire pattern vs the cost
6500   // of the components. If the reduction cost is lower then we return it for the
6501   // reduction instruction and 0 for the other instructions in the pattern. If
6502   // it is not we return an invalid cost specifying the orignal cost method
6503   // should be used.
6504   Instruction *RetI = I;
6505   if (match(RetI, m_ZExtOrSExt(m_Value()))) {
6506     if (!RetI->hasOneUser())
6507       return None;
6508     RetI = RetI->user_back();
6509   }
6510   if (match(RetI, m_Mul(m_Value(), m_Value())) &&
6511       RetI->user_back()->getOpcode() == Instruction::Add) {
6512     if (!RetI->hasOneUser())
6513       return None;
6514     RetI = RetI->user_back();
6515   }
6516 
6517   // Test if the found instruction is a reduction, and if not return an invalid
6518   // cost specifying the parent to use the original cost modelling.
6519   if (!InLoopReductionImmediateChains.count(RetI))
6520     return None;
6521 
6522   // Find the reduction this chain is a part of and calculate the basic cost of
6523   // the reduction on its own.
6524   Instruction *LastChain = InLoopReductionImmediateChains[RetI];
6525   Instruction *ReductionPhi = LastChain;
6526   while (!isa<PHINode>(ReductionPhi))
6527     ReductionPhi = InLoopReductionImmediateChains[ReductionPhi];
6528 
6529   const RecurrenceDescriptor &RdxDesc =
6530       Legal->getReductionVars().find(cast<PHINode>(ReductionPhi))->second;
6531 
6532   InstructionCost BaseCost = TTI.getArithmeticReductionCost(
6533       RdxDesc.getOpcode(), VectorTy, RdxDesc.getFastMathFlags(), CostKind);
6534 
6535   // For a call to the llvm.fmuladd intrinsic we need to add the cost of a
6536   // normal fmul instruction to the cost of the fadd reduction.
6537   if (RdxDesc.getRecurrenceKind() == RecurKind::FMulAdd)
6538     BaseCost +=
6539         TTI.getArithmeticInstrCost(Instruction::FMul, VectorTy, CostKind);
6540 
6541   // If we're using ordered reductions then we can just return the base cost
6542   // here, since getArithmeticReductionCost calculates the full ordered
6543   // reduction cost when FP reassociation is not allowed.
6544   if (useOrderedReductions(RdxDesc))
6545     return BaseCost;
6546 
6547   // Get the operand that was not the reduction chain and match it to one of the
6548   // patterns, returning the better cost if it is found.
6549   Instruction *RedOp = RetI->getOperand(1) == LastChain
6550                            ? dyn_cast<Instruction>(RetI->getOperand(0))
6551                            : dyn_cast<Instruction>(RetI->getOperand(1));
6552 
6553   VectorTy = VectorType::get(I->getOperand(0)->getType(), VectorTy);
6554 
6555   Instruction *Op0, *Op1;
6556   if (RedOp &&
6557       match(RedOp,
6558             m_ZExtOrSExt(m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) &&
6559       match(Op0, m_ZExtOrSExt(m_Value())) &&
6560       Op0->getOpcode() == Op1->getOpcode() &&
6561       Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
6562       !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1) &&
6563       (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
6564 
6565     // Matched reduce(ext(mul(ext(A), ext(B)))
6566     // Note that the extend opcodes need to all match, or if A==B they will have
6567     // been converted to zext(mul(sext(A), sext(A))) as it is known positive,
6568     // which is equally fine.
6569     bool IsUnsigned = isa<ZExtInst>(Op0);
6570     auto *ExtType = VectorType::get(Op0->getOperand(0)->getType(), VectorTy);
6571     auto *MulType = VectorType::get(Op0->getType(), VectorTy);
6572 
6573     InstructionCost ExtCost =
6574         TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
6575                              TTI::CastContextHint::None, CostKind, Op0);
6576     InstructionCost MulCost =
6577         TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
6578     InstructionCost Ext2Cost =
6579         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, MulType,
6580                              TTI::CastContextHint::None, CostKind, RedOp);
6581 
6582     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6583         /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6584         CostKind);
6585 
6586     if (RedCost.isValid() &&
6587         RedCost < ExtCost * 2 + MulCost + Ext2Cost + BaseCost)
6588       return I == RetI ? RedCost : 0;
6589   } else if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value())) &&
6590              !TheLoop->isLoopInvariant(RedOp)) {
6591     // Matched reduce(ext(A))
6592     bool IsUnsigned = isa<ZExtInst>(RedOp);
6593     auto *ExtType = VectorType::get(RedOp->getOperand(0)->getType(), VectorTy);
6594     InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6595         /*IsMLA=*/false, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6596         CostKind);
6597 
6598     InstructionCost ExtCost =
6599         TTI.getCastInstrCost(RedOp->getOpcode(), VectorTy, ExtType,
6600                              TTI::CastContextHint::None, CostKind, RedOp);
6601     if (RedCost.isValid() && RedCost < BaseCost + ExtCost)
6602       return I == RetI ? RedCost : 0;
6603   } else if (RedOp &&
6604              match(RedOp, m_Mul(m_Instruction(Op0), m_Instruction(Op1)))) {
6605     if (match(Op0, m_ZExtOrSExt(m_Value())) &&
6606         Op0->getOpcode() == Op1->getOpcode() &&
6607         !TheLoop->isLoopInvariant(Op0) && !TheLoop->isLoopInvariant(Op1)) {
6608       bool IsUnsigned = isa<ZExtInst>(Op0);
6609       Type *Op0Ty = Op0->getOperand(0)->getType();
6610       Type *Op1Ty = Op1->getOperand(0)->getType();
6611       Type *LargestOpTy =
6612           Op0Ty->getIntegerBitWidth() < Op1Ty->getIntegerBitWidth() ? Op1Ty
6613                                                                     : Op0Ty;
6614       auto *ExtType = VectorType::get(LargestOpTy, VectorTy);
6615 
6616       // Matched reduce(mul(ext(A), ext(B))), where the two ext may be of
6617       // different sizes. We take the largest type as the ext to reduce, and add
6618       // the remaining cost as, for example reduce(mul(ext(ext(A)), ext(B))).
6619       InstructionCost ExtCost0 = TTI.getCastInstrCost(
6620           Op0->getOpcode(), VectorTy, VectorType::get(Op0Ty, VectorTy),
6621           TTI::CastContextHint::None, CostKind, Op0);
6622       InstructionCost ExtCost1 = TTI.getCastInstrCost(
6623           Op1->getOpcode(), VectorTy, VectorType::get(Op1Ty, VectorTy),
6624           TTI::CastContextHint::None, CostKind, Op1);
6625       InstructionCost MulCost =
6626           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6627 
6628       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6629           /*IsMLA=*/true, IsUnsigned, RdxDesc.getRecurrenceType(), ExtType,
6630           CostKind);
6631       InstructionCost ExtraExtCost = 0;
6632       if (Op0Ty != LargestOpTy || Op1Ty != LargestOpTy) {
6633         Instruction *ExtraExtOp = (Op0Ty != LargestOpTy) ? Op0 : Op1;
6634         ExtraExtCost = TTI.getCastInstrCost(
6635             ExtraExtOp->getOpcode(), ExtType,
6636             VectorType::get(ExtraExtOp->getOperand(0)->getType(), VectorTy),
6637             TTI::CastContextHint::None, CostKind, ExtraExtOp);
6638       }
6639 
6640       if (RedCost.isValid() &&
6641           (RedCost + ExtraExtCost) < (ExtCost0 + ExtCost1 + MulCost + BaseCost))
6642         return I == RetI ? RedCost : 0;
6643     } else if (!match(I, m_ZExtOrSExt(m_Value()))) {
6644       // Matched reduce(mul())
6645       InstructionCost MulCost =
6646           TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
6647 
6648       InstructionCost RedCost = TTI.getExtendedAddReductionCost(
6649           /*IsMLA=*/true, true, RdxDesc.getRecurrenceType(), VectorTy,
6650           CostKind);
6651 
6652       if (RedCost.isValid() && RedCost < MulCost + BaseCost)
6653         return I == RetI ? RedCost : 0;
6654     }
6655   }
6656 
6657   return I == RetI ? Optional<InstructionCost>(BaseCost) : None;
6658 }
6659 
6660 InstructionCost
6661 LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
6662                                                      ElementCount VF) {
6663   // Calculate scalar cost only. Vectorization cost should be ready at this
6664   // moment.
6665   if (VF.isScalar()) {
6666     Type *ValTy = getLoadStoreType(I);
6667     const Align Alignment = getLoadStoreAlignment(I);
6668     unsigned AS = getLoadStoreAddressSpace(I);
6669 
6670     return TTI.getAddressComputationCost(ValTy) +
6671            TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS,
6672                                TTI::TCK_RecipThroughput, I);
6673   }
6674   return getWideningCost(I, VF);
6675 }
6676 
6677 LoopVectorizationCostModel::VectorizationCostTy
6678 LoopVectorizationCostModel::getInstructionCost(Instruction *I,
6679                                                ElementCount VF) {
6680   // If we know that this instruction will remain uniform, check the cost of
6681   // the scalar version.
6682   if (isUniformAfterVectorization(I, VF))
6683     VF = ElementCount::getFixed(1);
6684 
6685   if (VF.isVector() && isProfitableToScalarize(I, VF))
6686     return VectorizationCostTy(InstsToScalarize[VF][I], false);
6687 
6688   // Forced scalars do not have any scalarization overhead.
6689   auto ForcedScalar = ForcedScalars.find(VF);
6690   if (VF.isVector() && ForcedScalar != ForcedScalars.end()) {
6691     auto InstSet = ForcedScalar->second;
6692     if (InstSet.count(I))
6693       return VectorizationCostTy(
6694           (getInstructionCost(I, ElementCount::getFixed(1)).first *
6695            VF.getKnownMinValue()),
6696           false);
6697   }
6698 
6699   Type *VectorTy;
6700   InstructionCost C = getInstructionCost(I, VF, VectorTy);
6701 
6702   bool TypeNotScalarized = false;
6703   if (VF.isVector() && VectorTy->isVectorTy()) {
6704     if (unsigned NumParts = TTI.getNumberOfParts(VectorTy)) {
6705       if (VF.isScalable())
6706         // <vscale x 1 x iN> is assumed to be profitable over iN because
6707         // scalable registers are a distinct register class from scalar ones.
6708         // If we ever find a target which wants to lower scalable vectors
6709         // back to scalars, we'll need to update this code to explicitly
6710         // ask TTI about the register class uses for each part.
6711         TypeNotScalarized = NumParts <= VF.getKnownMinValue();
6712       else
6713         TypeNotScalarized = NumParts < VF.getKnownMinValue();
6714     } else
6715       C = InstructionCost::getInvalid();
6716   }
6717   return VectorizationCostTy(C, TypeNotScalarized);
6718 }
6719 
6720 InstructionCost
6721 LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
6722                                                      ElementCount VF) const {
6723 
6724   // There is no mechanism yet to create a scalable scalarization loop,
6725   // so this is currently Invalid.
6726   if (VF.isScalable())
6727     return InstructionCost::getInvalid();
6728 
6729   if (VF.isScalar())
6730     return 0;
6731 
6732   InstructionCost Cost = 0;
6733   Type *RetTy = ToVectorTy(I->getType(), VF);
6734   if (!RetTy->isVoidTy() &&
6735       (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
6736     Cost += TTI.getScalarizationOverhead(
6737         cast<VectorType>(RetTy), APInt::getAllOnes(VF.getKnownMinValue()), true,
6738         false);
6739 
6740   // Some targets keep addresses scalar.
6741   if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
6742     return Cost;
6743 
6744   // Some targets support efficient element stores.
6745   if (isa<StoreInst>(I) && TTI.supportsEfficientVectorElementLoadStore())
6746     return Cost;
6747 
6748   // Collect operands to consider.
6749   CallInst *CI = dyn_cast<CallInst>(I);
6750   Instruction::op_range Ops = CI ? CI->args() : I->operands();
6751 
6752   // Skip operands that do not require extraction/scalarization and do not incur
6753   // any overhead.
6754   SmallVector<Type *> Tys;
6755   for (auto *V : filterExtractingOperands(Ops, VF))
6756     Tys.push_back(MaybeVectorizeType(V->getType(), VF));
6757   return Cost + TTI.getOperandsScalarizationOverhead(
6758                     filterExtractingOperands(Ops, VF), Tys);
6759 }
6760 
6761 void LoopVectorizationCostModel::setCostBasedWideningDecision(ElementCount VF) {
6762   if (VF.isScalar())
6763     return;
6764   NumPredStores = 0;
6765   for (BasicBlock *BB : TheLoop->blocks()) {
6766     // For each instruction in the old loop.
6767     for (Instruction &I : *BB) {
6768       Value *Ptr =  getLoadStorePointerOperand(&I);
6769       if (!Ptr)
6770         continue;
6771 
6772       // TODO: We should generate better code and update the cost model for
6773       // predicated uniform stores. Today they are treated as any other
6774       // predicated store (see added test cases in
6775       // invariant-store-vectorization.ll).
6776       if (isa<StoreInst>(&I) && isScalarWithPredication(&I, VF))
6777         NumPredStores++;
6778 
6779       if (Legal->isUniformMemOp(I)) {
6780         // TODO: Avoid replicating loads and stores instead of
6781         // relying on instcombine to remove them.
6782         // Load: Scalar load + broadcast
6783         // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
6784         InstructionCost Cost;
6785         if (isa<StoreInst>(&I) && VF.isScalable() &&
6786             isLegalGatherOrScatter(&I, VF)) {
6787           Cost = getGatherScatterCost(&I, VF);
6788           setWideningDecision(&I, VF, CM_GatherScatter, Cost);
6789         } else {
6790           Cost = getUniformMemOpCost(&I, VF);
6791           setWideningDecision(&I, VF, CM_Scalarize, Cost);
6792         }
6793         continue;
6794       }
6795 
6796       // We assume that widening is the best solution when possible.
6797       if (memoryInstructionCanBeWidened(&I, VF)) {
6798         InstructionCost Cost = getConsecutiveMemOpCost(&I, VF);
6799         int ConsecutiveStride = Legal->isConsecutivePtr(
6800             getLoadStoreType(&I), getLoadStorePointerOperand(&I));
6801         assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
6802                "Expected consecutive stride.");
6803         InstWidening Decision =
6804             ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
6805         setWideningDecision(&I, VF, Decision, Cost);
6806         continue;
6807       }
6808 
6809       // Choose between Interleaving, Gather/Scatter or Scalarization.
6810       InstructionCost InterleaveCost = InstructionCost::getInvalid();
6811       unsigned NumAccesses = 1;
6812       if (isAccessInterleaved(&I)) {
6813         auto Group = getInterleavedAccessGroup(&I);
6814         assert(Group && "Fail to get an interleaved access group.");
6815 
6816         // Make one decision for the whole group.
6817         if (getWideningDecision(&I, VF) != CM_Unknown)
6818           continue;
6819 
6820         NumAccesses = Group->getNumMembers();
6821         if (interleavedAccessCanBeWidened(&I, VF))
6822           InterleaveCost = getInterleaveGroupCost(&I, VF);
6823       }
6824 
6825       InstructionCost GatherScatterCost =
6826           isLegalGatherOrScatter(&I, VF)
6827               ? getGatherScatterCost(&I, VF) * NumAccesses
6828               : InstructionCost::getInvalid();
6829 
6830       InstructionCost ScalarizationCost =
6831           getMemInstScalarizationCost(&I, VF) * NumAccesses;
6832 
6833       // Choose better solution for the current VF,
6834       // write down this decision and use it during vectorization.
6835       InstructionCost Cost;
6836       InstWidening Decision;
6837       if (InterleaveCost <= GatherScatterCost &&
6838           InterleaveCost < ScalarizationCost) {
6839         Decision = CM_Interleave;
6840         Cost = InterleaveCost;
6841       } else if (GatherScatterCost < ScalarizationCost) {
6842         Decision = CM_GatherScatter;
6843         Cost = GatherScatterCost;
6844       } else {
6845         Decision = CM_Scalarize;
6846         Cost = ScalarizationCost;
6847       }
6848       // If the instructions belongs to an interleave group, the whole group
6849       // receives the same decision. The whole group receives the cost, but
6850       // the cost will actually be assigned to one instruction.
6851       if (auto Group = getInterleavedAccessGroup(&I))
6852         setWideningDecision(Group, VF, Decision, Cost);
6853       else
6854         setWideningDecision(&I, VF, Decision, Cost);
6855     }
6856   }
6857 
6858   // Make sure that any load of address and any other address computation
6859   // remains scalar unless there is gather/scatter support. This avoids
6860   // inevitable extracts into address registers, and also has the benefit of
6861   // activating LSR more, since that pass can't optimize vectorized
6862   // addresses.
6863   if (TTI.prefersVectorizedAddressing())
6864     return;
6865 
6866   // Start with all scalar pointer uses.
6867   SmallPtrSet<Instruction *, 8> AddrDefs;
6868   for (BasicBlock *BB : TheLoop->blocks())
6869     for (Instruction &I : *BB) {
6870       Instruction *PtrDef =
6871         dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
6872       if (PtrDef && TheLoop->contains(PtrDef) &&
6873           getWideningDecision(&I, VF) != CM_GatherScatter)
6874         AddrDefs.insert(PtrDef);
6875     }
6876 
6877   // Add all instructions used to generate the addresses.
6878   SmallVector<Instruction *, 4> Worklist;
6879   append_range(Worklist, AddrDefs);
6880   while (!Worklist.empty()) {
6881     Instruction *I = Worklist.pop_back_val();
6882     for (auto &Op : I->operands())
6883       if (auto *InstOp = dyn_cast<Instruction>(Op))
6884         if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
6885             AddrDefs.insert(InstOp).second)
6886           Worklist.push_back(InstOp);
6887   }
6888 
6889   for (auto *I : AddrDefs) {
6890     if (isa<LoadInst>(I)) {
6891       // Setting the desired widening decision should ideally be handled in
6892       // by cost functions, but since this involves the task of finding out
6893       // if the loaded register is involved in an address computation, it is
6894       // instead changed here when we know this is the case.
6895       InstWidening Decision = getWideningDecision(I, VF);
6896       if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
6897         // Scalarize a widened load of address.
6898         setWideningDecision(
6899             I, VF, CM_Scalarize,
6900             (VF.getKnownMinValue() *
6901              getMemoryInstructionCost(I, ElementCount::getFixed(1))));
6902       else if (auto Group = getInterleavedAccessGroup(I)) {
6903         // Scalarize an interleave group of address loads.
6904         for (unsigned I = 0; I < Group->getFactor(); ++I) {
6905           if (Instruction *Member = Group->getMember(I))
6906             setWideningDecision(
6907                 Member, VF, CM_Scalarize,
6908                 (VF.getKnownMinValue() *
6909                  getMemoryInstructionCost(Member, ElementCount::getFixed(1))));
6910         }
6911       }
6912     } else
6913       // Make sure I gets scalarized and a cost estimate without
6914       // scalarization overhead.
6915       ForcedScalars[VF].insert(I);
6916   }
6917 }
6918 
6919 InstructionCost
6920 LoopVectorizationCostModel::getInstructionCost(Instruction *I, ElementCount VF,
6921                                                Type *&VectorTy) {
6922   Type *RetTy = I->getType();
6923   if (canTruncateToMinimalBitwidth(I, VF))
6924     RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
6925   auto SE = PSE.getSE();
6926   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
6927 
6928   auto hasSingleCopyAfterVectorization = [this](Instruction *I,
6929                                                 ElementCount VF) -> bool {
6930     if (VF.isScalar())
6931       return true;
6932 
6933     auto Scalarized = InstsToScalarize.find(VF);
6934     assert(Scalarized != InstsToScalarize.end() &&
6935            "VF not yet analyzed for scalarization profitability");
6936     return !Scalarized->second.count(I) &&
6937            llvm::all_of(I->users(), [&](User *U) {
6938              auto *UI = cast<Instruction>(U);
6939              return !Scalarized->second.count(UI);
6940            });
6941   };
6942   (void) hasSingleCopyAfterVectorization;
6943 
6944   if (isScalarAfterVectorization(I, VF)) {
6945     // With the exception of GEPs and PHIs, after scalarization there should
6946     // only be one copy of the instruction generated in the loop. This is
6947     // because the VF is either 1, or any instructions that need scalarizing
6948     // have already been dealt with by the the time we get here. As a result,
6949     // it means we don't have to multiply the instruction cost by VF.
6950     assert(I->getOpcode() == Instruction::GetElementPtr ||
6951            I->getOpcode() == Instruction::PHI ||
6952            (I->getOpcode() == Instruction::BitCast &&
6953             I->getType()->isPointerTy()) ||
6954            hasSingleCopyAfterVectorization(I, VF));
6955     VectorTy = RetTy;
6956   } else
6957     VectorTy = ToVectorTy(RetTy, VF);
6958 
6959   // TODO: We need to estimate the cost of intrinsic calls.
6960   switch (I->getOpcode()) {
6961   case Instruction::GetElementPtr:
6962     // We mark this instruction as zero-cost because the cost of GEPs in
6963     // vectorized code depends on whether the corresponding memory instruction
6964     // is scalarized or not. Therefore, we handle GEPs with the memory
6965     // instruction cost.
6966     return 0;
6967   case Instruction::Br: {
6968     // In cases of scalarized and predicated instructions, there will be VF
6969     // predicated blocks in the vectorized loop. Each branch around these
6970     // blocks requires also an extract of its vector compare i1 element.
6971     bool ScalarPredicatedBB = false;
6972     BranchInst *BI = cast<BranchInst>(I);
6973     if (VF.isVector() && BI->isConditional() &&
6974         (PredicatedBBsAfterVectorization.count(BI->getSuccessor(0)) ||
6975          PredicatedBBsAfterVectorization.count(BI->getSuccessor(1))))
6976       ScalarPredicatedBB = true;
6977 
6978     if (ScalarPredicatedBB) {
6979       // Not possible to scalarize scalable vector with predicated instructions.
6980       if (VF.isScalable())
6981         return InstructionCost::getInvalid();
6982       // Return cost for branches around scalarized and predicated blocks.
6983       auto *Vec_i1Ty =
6984           VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
6985       return (
6986           TTI.getScalarizationOverhead(
6987               Vec_i1Ty, APInt::getAllOnes(VF.getFixedValue()), false, true) +
6988           (TTI.getCFInstrCost(Instruction::Br, CostKind) * VF.getFixedValue()));
6989     } else if (I->getParent() == TheLoop->getLoopLatch() || VF.isScalar())
6990       // The back-edge branch will remain, as will all scalar branches.
6991       return TTI.getCFInstrCost(Instruction::Br, CostKind);
6992     else
6993       // This branch will be eliminated by if-conversion.
6994       return 0;
6995     // Note: We currently assume zero cost for an unconditional branch inside
6996     // a predicated block since it will become a fall-through, although we
6997     // may decide in the future to call TTI for all branches.
6998   }
6999   case Instruction::PHI: {
7000     auto *Phi = cast<PHINode>(I);
7001 
7002     // First-order recurrences are replaced by vector shuffles inside the loop.
7003     // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
7004     if (VF.isVector() && Legal->isFirstOrderRecurrence(Phi))
7005       return TTI.getShuffleCost(
7006           TargetTransformInfo::SK_ExtractSubvector, cast<VectorType>(VectorTy),
7007           None, VF.getKnownMinValue() - 1, FixedVectorType::get(RetTy, 1));
7008 
7009     // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
7010     // converted into select instructions. We require N - 1 selects per phi
7011     // node, where N is the number of incoming values.
7012     if (VF.isVector() && Phi->getParent() != TheLoop->getHeader())
7013       return (Phi->getNumIncomingValues() - 1) *
7014              TTI.getCmpSelInstrCost(
7015                  Instruction::Select, ToVectorTy(Phi->getType(), VF),
7016                  ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF),
7017                  CmpInst::BAD_ICMP_PREDICATE, CostKind);
7018 
7019     return TTI.getCFInstrCost(Instruction::PHI, CostKind);
7020   }
7021   case Instruction::UDiv:
7022   case Instruction::SDiv:
7023   case Instruction::URem:
7024   case Instruction::SRem:
7025     // If we have a predicated instruction, it may not be executed for each
7026     // vector lane. Get the scalarization cost and scale this amount by the
7027     // probability of executing the predicated block. If the instruction is not
7028     // predicated, we fall through to the next case.
7029     if (VF.isVector() && isScalarWithPredication(I, VF)) {
7030       InstructionCost Cost = 0;
7031 
7032       // These instructions have a non-void type, so account for the phi nodes
7033       // that we will create. This cost is likely to be zero. The phi node
7034       // cost, if any, should be scaled by the block probability because it
7035       // models a copy at the end of each predicated block.
7036       Cost += VF.getKnownMinValue() *
7037               TTI.getCFInstrCost(Instruction::PHI, CostKind);
7038 
7039       // The cost of the non-predicated instruction.
7040       Cost += VF.getKnownMinValue() *
7041               TTI.getArithmeticInstrCost(I->getOpcode(), RetTy, CostKind);
7042 
7043       // The cost of insertelement and extractelement instructions needed for
7044       // scalarization.
7045       Cost += getScalarizationOverhead(I, VF);
7046 
7047       // Scale the cost by the probability of executing the predicated blocks.
7048       // This assumes the predicated block for each vector lane is equally
7049       // likely.
7050       return Cost / getReciprocalPredBlockProb();
7051     }
7052     LLVM_FALLTHROUGH;
7053   case Instruction::Add:
7054   case Instruction::FAdd:
7055   case Instruction::Sub:
7056   case Instruction::FSub:
7057   case Instruction::Mul:
7058   case Instruction::FMul:
7059   case Instruction::FDiv:
7060   case Instruction::FRem:
7061   case Instruction::Shl:
7062   case Instruction::LShr:
7063   case Instruction::AShr:
7064   case Instruction::And:
7065   case Instruction::Or:
7066   case Instruction::Xor: {
7067     // Since we will replace the stride by 1 the multiplication should go away.
7068     if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
7069       return 0;
7070 
7071     // Detect reduction patterns
7072     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7073       return *RedCost;
7074 
7075     // Certain instructions can be cheaper to vectorize if they have a constant
7076     // second vector operand. One example of this are shifts on x86.
7077     Value *Op2 = I->getOperand(1);
7078     TargetTransformInfo::OperandValueProperties Op2VP;
7079     TargetTransformInfo::OperandValueKind Op2VK =
7080         TTI.getOperandInfo(Op2, Op2VP);
7081     if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
7082       Op2VK = TargetTransformInfo::OK_UniformValue;
7083 
7084     SmallVector<const Value *, 4> Operands(I->operand_values());
7085     return TTI.getArithmeticInstrCost(
7086         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7087         Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands, I);
7088   }
7089   case Instruction::FNeg: {
7090     return TTI.getArithmeticInstrCost(
7091         I->getOpcode(), VectorTy, CostKind, TargetTransformInfo::OK_AnyValue,
7092         TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None,
7093         TargetTransformInfo::OP_None, I->getOperand(0), I);
7094   }
7095   case Instruction::Select: {
7096     SelectInst *SI = cast<SelectInst>(I);
7097     const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
7098     bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
7099 
7100     const Value *Op0, *Op1;
7101     using namespace llvm::PatternMatch;
7102     if (!ScalarCond && (match(I, m_LogicalAnd(m_Value(Op0), m_Value(Op1))) ||
7103                         match(I, m_LogicalOr(m_Value(Op0), m_Value(Op1))))) {
7104       // select x, y, false --> x & y
7105       // select x, true, y --> x | y
7106       TTI::OperandValueProperties Op1VP = TTI::OP_None;
7107       TTI::OperandValueProperties Op2VP = TTI::OP_None;
7108       TTI::OperandValueKind Op1VK = TTI::getOperandInfo(Op0, Op1VP);
7109       TTI::OperandValueKind Op2VK = TTI::getOperandInfo(Op1, Op2VP);
7110       assert(Op0->getType()->getScalarSizeInBits() == 1 &&
7111               Op1->getType()->getScalarSizeInBits() == 1);
7112 
7113       SmallVector<const Value *, 2> Operands{Op0, Op1};
7114       return TTI.getArithmeticInstrCost(
7115           match(I, m_LogicalOr()) ? Instruction::Or : Instruction::And, VectorTy,
7116           CostKind, Op1VK, Op2VK, Op1VP, Op2VP, Operands, I);
7117     }
7118 
7119     Type *CondTy = SI->getCondition()->getType();
7120     if (!ScalarCond)
7121       CondTy = VectorType::get(CondTy, VF);
7122 
7123     CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
7124     if (auto *Cmp = dyn_cast<CmpInst>(SI->getCondition()))
7125       Pred = Cmp->getPredicate();
7126     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, Pred,
7127                                   CostKind, I);
7128   }
7129   case Instruction::ICmp:
7130   case Instruction::FCmp: {
7131     Type *ValTy = I->getOperand(0)->getType();
7132     Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
7133     if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
7134       ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
7135     VectorTy = ToVectorTy(ValTy, VF);
7136     return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr,
7137                                   cast<CmpInst>(I)->getPredicate(), CostKind,
7138                                   I);
7139   }
7140   case Instruction::Store:
7141   case Instruction::Load: {
7142     ElementCount Width = VF;
7143     if (Width.isVector()) {
7144       InstWidening Decision = getWideningDecision(I, Width);
7145       assert(Decision != CM_Unknown &&
7146              "CM decision should be taken at this point");
7147       if (Decision == CM_Scalarize) {
7148         if (VF.isScalable() && isa<StoreInst>(I))
7149           // We can't scalarize a scalable vector store (even a uniform one
7150           // currently), return an invalid cost so as to prevent vectorization.
7151           return InstructionCost::getInvalid();
7152         Width = ElementCount::getFixed(1);
7153       }
7154     }
7155     VectorTy = ToVectorTy(getLoadStoreType(I), Width);
7156     return getMemoryInstructionCost(I, VF);
7157   }
7158   case Instruction::BitCast:
7159     if (I->getType()->isPointerTy())
7160       return 0;
7161     LLVM_FALLTHROUGH;
7162   case Instruction::ZExt:
7163   case Instruction::SExt:
7164   case Instruction::FPToUI:
7165   case Instruction::FPToSI:
7166   case Instruction::FPExt:
7167   case Instruction::PtrToInt:
7168   case Instruction::IntToPtr:
7169   case Instruction::SIToFP:
7170   case Instruction::UIToFP:
7171   case Instruction::Trunc:
7172   case Instruction::FPTrunc: {
7173     // Computes the CastContextHint from a Load/Store instruction.
7174     auto ComputeCCH = [&](Instruction *I) -> TTI::CastContextHint {
7175       assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
7176              "Expected a load or a store!");
7177 
7178       if (VF.isScalar() || !TheLoop->contains(I))
7179         return TTI::CastContextHint::Normal;
7180 
7181       switch (getWideningDecision(I, VF)) {
7182       case LoopVectorizationCostModel::CM_GatherScatter:
7183         return TTI::CastContextHint::GatherScatter;
7184       case LoopVectorizationCostModel::CM_Interleave:
7185         return TTI::CastContextHint::Interleave;
7186       case LoopVectorizationCostModel::CM_Scalarize:
7187       case LoopVectorizationCostModel::CM_Widen:
7188         return Legal->isMaskRequired(I) ? TTI::CastContextHint::Masked
7189                                         : TTI::CastContextHint::Normal;
7190       case LoopVectorizationCostModel::CM_Widen_Reverse:
7191         return TTI::CastContextHint::Reversed;
7192       case LoopVectorizationCostModel::CM_Unknown:
7193         llvm_unreachable("Instr did not go through cost modelling?");
7194       }
7195 
7196       llvm_unreachable("Unhandled case!");
7197     };
7198 
7199     unsigned Opcode = I->getOpcode();
7200     TTI::CastContextHint CCH = TTI::CastContextHint::None;
7201     // For Trunc, the context is the only user, which must be a StoreInst.
7202     if (Opcode == Instruction::Trunc || Opcode == Instruction::FPTrunc) {
7203       if (I->hasOneUse())
7204         if (StoreInst *Store = dyn_cast<StoreInst>(*I->user_begin()))
7205           CCH = ComputeCCH(Store);
7206     }
7207     // For Z/Sext, the context is the operand, which must be a LoadInst.
7208     else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt ||
7209              Opcode == Instruction::FPExt) {
7210       if (LoadInst *Load = dyn_cast<LoadInst>(I->getOperand(0)))
7211         CCH = ComputeCCH(Load);
7212     }
7213 
7214     // We optimize the truncation of induction variables having constant
7215     // integer steps. The cost of these truncations is the same as the scalar
7216     // operation.
7217     if (isOptimizableIVTruncate(I, VF)) {
7218       auto *Trunc = cast<TruncInst>(I);
7219       return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
7220                                   Trunc->getSrcTy(), CCH, CostKind, Trunc);
7221     }
7222 
7223     // Detect reduction patterns
7224     if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7225       return *RedCost;
7226 
7227     Type *SrcScalarTy = I->getOperand(0)->getType();
7228     Type *SrcVecTy =
7229         VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
7230     if (canTruncateToMinimalBitwidth(I, VF)) {
7231       // This cast is going to be shrunk. This may remove the cast or it might
7232       // turn it into slightly different cast. For example, if MinBW == 16,
7233       // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
7234       //
7235       // Calculate the modified src and dest types.
7236       Type *MinVecTy = VectorTy;
7237       if (Opcode == Instruction::Trunc) {
7238         SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
7239         VectorTy =
7240             largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7241       } else if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
7242         SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
7243         VectorTy =
7244             smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
7245       }
7246     }
7247 
7248     return TTI.getCastInstrCost(Opcode, VectorTy, SrcVecTy, CCH, CostKind, I);
7249   }
7250   case Instruction::Call: {
7251     if (RecurrenceDescriptor::isFMulAddIntrinsic(I))
7252       if (auto RedCost = getReductionPatternCost(I, VF, VectorTy, CostKind))
7253         return *RedCost;
7254     bool NeedToScalarize;
7255     CallInst *CI = cast<CallInst>(I);
7256     InstructionCost CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
7257     if (getVectorIntrinsicIDForCall(CI, TLI)) {
7258       InstructionCost IntrinsicCost = getVectorIntrinsicCost(CI, VF);
7259       return std::min(CallCost, IntrinsicCost);
7260     }
7261     return CallCost;
7262   }
7263   case Instruction::ExtractValue:
7264     return TTI.getInstructionCost(I, TTI::TCK_RecipThroughput);
7265   case Instruction::Alloca:
7266     // We cannot easily widen alloca to a scalable alloca, as
7267     // the result would need to be a vector of pointers.
7268     if (VF.isScalable())
7269       return InstructionCost::getInvalid();
7270     LLVM_FALLTHROUGH;
7271   default:
7272     // This opcode is unknown. Assume that it is the same as 'mul'.
7273     return TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy, CostKind);
7274   } // end of switch.
7275 }
7276 
7277 char LoopVectorize::ID = 0;
7278 
7279 static const char lv_name[] = "Loop Vectorization";
7280 
7281 INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
7282 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7283 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
7284 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7285 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
7286 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7287 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
7288 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
7289 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7290 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
7291 INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
7292 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7293 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7294 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
7295 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7296 INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
7297 
7298 namespace llvm {
7299 
7300 Pass *createLoopVectorizePass() { return new LoopVectorize(); }
7301 
7302 Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
7303                               bool VectorizeOnlyWhenForced) {
7304   return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
7305 }
7306 
7307 } // end namespace llvm
7308 
7309 bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
7310   // Check if the pointer operand of a load or store instruction is
7311   // consecutive.
7312   if (auto *Ptr = getLoadStorePointerOperand(Inst))
7313     return Legal->isConsecutivePtr(getLoadStoreType(Inst), Ptr);
7314   return false;
7315 }
7316 
7317 void LoopVectorizationCostModel::collectValuesToIgnore() {
7318   // Ignore ephemeral values.
7319   CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
7320 
7321   // Find all stores to invariant variables. Since they are going to sink
7322   // outside the loop we do not need calculate cost for them.
7323   for (BasicBlock *BB : TheLoop->blocks())
7324     for (Instruction &I : *BB) {
7325       StoreInst *SI;
7326       if ((SI = dyn_cast<StoreInst>(&I)) &&
7327           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
7328         ValuesToIgnore.insert(&I);
7329     }
7330 
7331   // Ignore type-promoting instructions we identified during reduction
7332   // detection.
7333   for (auto &Reduction : Legal->getReductionVars()) {
7334     const RecurrenceDescriptor &RedDes = Reduction.second;
7335     const SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
7336     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7337   }
7338   // Ignore type-casting instructions we identified during induction
7339   // detection.
7340   for (auto &Induction : Legal->getInductionVars()) {
7341     const InductionDescriptor &IndDes = Induction.second;
7342     const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
7343     VecValuesToIgnore.insert(Casts.begin(), Casts.end());
7344   }
7345 }
7346 
7347 void LoopVectorizationCostModel::collectInLoopReductions() {
7348   for (auto &Reduction : Legal->getReductionVars()) {
7349     PHINode *Phi = Reduction.first;
7350     const RecurrenceDescriptor &RdxDesc = Reduction.second;
7351 
7352     // We don't collect reductions that are type promoted (yet).
7353     if (RdxDesc.getRecurrenceType() != Phi->getType())
7354       continue;
7355 
7356     // If the target would prefer this reduction to happen "in-loop", then we
7357     // want to record it as such.
7358     unsigned Opcode = RdxDesc.getOpcode();
7359     if (!PreferInLoopReductions && !useOrderedReductions(RdxDesc) &&
7360         !TTI.preferInLoopReduction(Opcode, Phi->getType(),
7361                                    TargetTransformInfo::ReductionFlags()))
7362       continue;
7363 
7364     // Check that we can correctly put the reductions into the loop, by
7365     // finding the chain of operations that leads from the phi to the loop
7366     // exit value.
7367     SmallVector<Instruction *, 4> ReductionOperations =
7368         RdxDesc.getReductionOpChain(Phi, TheLoop);
7369     bool InLoop = !ReductionOperations.empty();
7370     if (InLoop) {
7371       InLoopReductionChains[Phi] = ReductionOperations;
7372       // Add the elements to InLoopReductionImmediateChains for cost modelling.
7373       Instruction *LastChain = Phi;
7374       for (auto *I : ReductionOperations) {
7375         InLoopReductionImmediateChains[I] = LastChain;
7376         LastChain = I;
7377       }
7378     }
7379     LLVM_DEBUG(dbgs() << "LV: Using " << (InLoop ? "inloop" : "out of loop")
7380                       << " reduction for phi: " << *Phi << "\n");
7381   }
7382 }
7383 
7384 // TODO: we could return a pair of values that specify the max VF and
7385 // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
7386 // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
7387 // doesn't have a cost model that can choose which plan to execute if
7388 // more than one is generated.
7389 static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
7390                                  LoopVectorizationCostModel &CM) {
7391   unsigned WidestType;
7392   std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
7393   return WidestVectorRegBits / WidestType;
7394 }
7395 
7396 VectorizationFactor
7397 LoopVectorizationPlanner::planInVPlanNativePath(ElementCount UserVF) {
7398   assert(!UserVF.isScalable() && "scalable vectors not yet supported");
7399   ElementCount VF = UserVF;
7400   // Outer loop handling: They may require CFG and instruction level
7401   // transformations before even evaluating whether vectorization is profitable.
7402   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
7403   // the vectorization pipeline.
7404   if (!OrigLoop->isInnermost()) {
7405     // If the user doesn't provide a vectorization factor, determine a
7406     // reasonable one.
7407     if (UserVF.isZero()) {
7408       VF = ElementCount::getFixed(determineVPlanVF(
7409           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
7410               .getFixedSize(),
7411           CM));
7412       LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
7413 
7414       // Make sure we have a VF > 1 for stress testing.
7415       if (VPlanBuildStressTest && (VF.isScalar() || VF.isZero())) {
7416         LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
7417                           << "overriding computed VF.\n");
7418         VF = ElementCount::getFixed(4);
7419       }
7420     }
7421     assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
7422     assert(isPowerOf2_32(VF.getKnownMinValue()) &&
7423            "VF needs to be a power of two");
7424     LLVM_DEBUG(dbgs() << "LV: Using " << (!UserVF.isZero() ? "user " : "")
7425                       << "VF " << VF << " to build VPlans.\n");
7426     buildVPlans(VF, VF);
7427 
7428     // For VPlan build stress testing, we bail out after VPlan construction.
7429     if (VPlanBuildStressTest)
7430       return VectorizationFactor::Disabled();
7431 
7432     return {VF, 0 /*Cost*/, 0 /* ScalarCost */};
7433   }
7434 
7435   LLVM_DEBUG(
7436       dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
7437                 "VPlan-native path.\n");
7438   return VectorizationFactor::Disabled();
7439 }
7440 
7441 bool LoopVectorizationPlanner::requiresTooManyRuntimeChecks() const {
7442   unsigned NumRuntimePointerChecks = Requirements.getNumRuntimePointerChecks();
7443   return (NumRuntimePointerChecks >
7444               VectorizerParams::RuntimeMemoryCheckThreshold &&
7445           !Hints.allowReordering()) ||
7446          NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
7447 }
7448 
7449 Optional<VectorizationFactor>
7450 LoopVectorizationPlanner::plan(ElementCount UserVF, unsigned UserIC) {
7451   assert(OrigLoop->isInnermost() && "Inner loop expected.");
7452   FixedScalableVFPair MaxFactors = CM.computeMaxVF(UserVF, UserIC);
7453   if (!MaxFactors) // Cases that should not to be vectorized nor interleaved.
7454     return None;
7455 
7456   // Invalidate interleave groups if all blocks of loop will be predicated.
7457   if (CM.blockNeedsPredicationForAnyReason(OrigLoop->getHeader()) &&
7458       !useMaskedInterleavedAccesses(*TTI)) {
7459     LLVM_DEBUG(
7460         dbgs()
7461         << "LV: Invalidate all interleaved groups due to fold-tail by masking "
7462            "which requires masked-interleaved support.\n");
7463     if (CM.InterleaveInfo.invalidateGroups())
7464       // Invalidating interleave groups also requires invalidating all decisions
7465       // based on them, which includes widening decisions and uniform and scalar
7466       // values.
7467       CM.invalidateCostModelingDecisions();
7468   }
7469 
7470   ElementCount MaxUserVF =
7471       UserVF.isScalable() ? MaxFactors.ScalableVF : MaxFactors.FixedVF;
7472   bool UserVFIsLegal = ElementCount::isKnownLE(UserVF, MaxUserVF);
7473   if (!UserVF.isZero() && UserVFIsLegal) {
7474     assert(isPowerOf2_32(UserVF.getKnownMinValue()) &&
7475            "VF needs to be a power of two");
7476     // Collect the instructions (and their associated costs) that will be more
7477     // profitable to scalarize.
7478     if (CM.selectUserVectorizationFactor(UserVF)) {
7479       LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
7480       CM.collectInLoopReductions();
7481       buildVPlansWithVPRecipes(UserVF, UserVF);
7482       LLVM_DEBUG(printPlans(dbgs()));
7483       return {{UserVF, 0, 0}};
7484     } else
7485       reportVectorizationInfo("UserVF ignored because of invalid costs.",
7486                               "InvalidCost", ORE, OrigLoop);
7487   }
7488 
7489   // Populate the set of Vectorization Factor Candidates.
7490   ElementCountSet VFCandidates;
7491   for (auto VF = ElementCount::getFixed(1);
7492        ElementCount::isKnownLE(VF, MaxFactors.FixedVF); VF *= 2)
7493     VFCandidates.insert(VF);
7494   for (auto VF = ElementCount::getScalable(1);
7495        ElementCount::isKnownLE(VF, MaxFactors.ScalableVF); VF *= 2)
7496     VFCandidates.insert(VF);
7497 
7498   for (const auto &VF : VFCandidates) {
7499     // Collect Uniform and Scalar instructions after vectorization with VF.
7500     CM.collectUniformsAndScalars(VF);
7501 
7502     // Collect the instructions (and their associated costs) that will be more
7503     // profitable to scalarize.
7504     if (VF.isVector())
7505       CM.collectInstsToScalarize(VF);
7506   }
7507 
7508   CM.collectInLoopReductions();
7509   buildVPlansWithVPRecipes(ElementCount::getFixed(1), MaxFactors.FixedVF);
7510   buildVPlansWithVPRecipes(ElementCount::getScalable(1), MaxFactors.ScalableVF);
7511 
7512   LLVM_DEBUG(printPlans(dbgs()));
7513   if (!MaxFactors.hasVector())
7514     return VectorizationFactor::Disabled();
7515 
7516   // Select the optimal vectorization factor.
7517   return CM.selectVectorizationFactor(VFCandidates);
7518 }
7519 
7520 VPlan &LoopVectorizationPlanner::getBestPlanFor(ElementCount VF) const {
7521   assert(count_if(VPlans,
7522                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
7523              1 &&
7524          "Best VF has not a single VPlan.");
7525 
7526   for (const VPlanPtr &Plan : VPlans) {
7527     if (Plan->hasVF(VF))
7528       return *Plan.get();
7529   }
7530   llvm_unreachable("No plan found!");
7531 }
7532 
7533 static void AddRuntimeUnrollDisableMetaData(Loop *L) {
7534   SmallVector<Metadata *, 4> MDs;
7535   // Reserve first location for self reference to the LoopID metadata node.
7536   MDs.push_back(nullptr);
7537   bool IsUnrollMetadata = false;
7538   MDNode *LoopID = L->getLoopID();
7539   if (LoopID) {
7540     // First find existing loop unrolling disable metadata.
7541     for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
7542       auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
7543       if (MD) {
7544         const auto *S = dyn_cast<MDString>(MD->getOperand(0));
7545         IsUnrollMetadata =
7546             S && S->getString().startswith("llvm.loop.unroll.disable");
7547       }
7548       MDs.push_back(LoopID->getOperand(i));
7549     }
7550   }
7551 
7552   if (!IsUnrollMetadata) {
7553     // Add runtime unroll disable metadata.
7554     LLVMContext &Context = L->getHeader()->getContext();
7555     SmallVector<Metadata *, 1> DisableOperands;
7556     DisableOperands.push_back(
7557         MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
7558     MDNode *DisableNode = MDNode::get(Context, DisableOperands);
7559     MDs.push_back(DisableNode);
7560     MDNode *NewLoopID = MDNode::get(Context, MDs);
7561     // Set operand 0 to refer to the loop id itself.
7562     NewLoopID->replaceOperandWith(0, NewLoopID);
7563     L->setLoopID(NewLoopID);
7564   }
7565 }
7566 
7567 void LoopVectorizationPlanner::executePlan(ElementCount BestVF, unsigned BestUF,
7568                                            VPlan &BestVPlan,
7569                                            InnerLoopVectorizer &ILV,
7570                                            DominatorTree *DT) {
7571   LLVM_DEBUG(dbgs() << "Executing best plan with VF=" << BestVF << ", UF=" << BestUF
7572                     << '\n');
7573 
7574   // Perform the actual loop transformation.
7575 
7576   // 1. Set up the skeleton for vectorization, including vector pre-header and
7577   // middle block. The vector loop is created during VPlan execution.
7578   VPTransformState State{BestVF, BestUF, LI, DT, ILV.Builder, &ILV, &BestVPlan};
7579   Value *CanonicalIVStartValue;
7580   std::tie(State.CFG.PrevBB, CanonicalIVStartValue) =
7581       ILV.createVectorizedLoopSkeleton();
7582 
7583   // Only use noalias metadata when using memory checks guaranteeing no overlap
7584   // across all iterations.
7585   const LoopAccessInfo *LAI = ILV.Legal->getLAI();
7586   if (LAI && !LAI->getRuntimePointerChecking()->getChecks().empty() &&
7587       !LAI->getRuntimePointerChecking()->getDiffChecks()) {
7588     //  We currently don't use LoopVersioning for the actual loop cloning but we
7589     //  still use it to add the noalias metadata.
7590     //  TODO: Find a better way to re-use LoopVersioning functionality to add
7591     //        metadata.
7592     ILV.LVer = std::make_unique<LoopVersioning>(
7593         *LAI, LAI->getRuntimePointerChecking()->getChecks(), OrigLoop, LI, DT,
7594         PSE.getSE());
7595     ILV.LVer->prepareNoAliasMetadata();
7596   }
7597 
7598   ILV.collectPoisonGeneratingRecipes(State);
7599 
7600   ILV.printDebugTracesAtStart();
7601 
7602   //===------------------------------------------------===//
7603   //
7604   // Notice: any optimization or new instruction that go
7605   // into the code below should also be implemented in
7606   // the cost-model.
7607   //
7608   //===------------------------------------------------===//
7609 
7610   // 2. Copy and widen instructions from the old loop into the new loop.
7611   BestVPlan.prepareToExecute(ILV.getOrCreateTripCount(nullptr),
7612                              ILV.getOrCreateVectorTripCount(nullptr),
7613                              CanonicalIVStartValue, State);
7614 
7615   BestVPlan.execute(&State);
7616 
7617   // Keep all loop hints from the original loop on the vector loop (we'll
7618   // replace the vectorizer-specific hints below).
7619   MDNode *OrigLoopID = OrigLoop->getLoopID();
7620 
7621   Optional<MDNode *> VectorizedLoopID =
7622       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
7623                                       LLVMLoopVectorizeFollowupVectorized});
7624 
7625   VPBasicBlock *HeaderVPBB =
7626       BestVPlan.getVectorLoopRegion()->getEntryBasicBlock();
7627   Loop *L = LI->getLoopFor(State.CFG.VPBB2IRBB[HeaderVPBB]);
7628   if (VectorizedLoopID)
7629     L->setLoopID(VectorizedLoopID.getValue());
7630   else {
7631     // Keep all loop hints from the original loop on the vector loop (we'll
7632     // replace the vectorizer-specific hints below).
7633     if (MDNode *LID = OrigLoop->getLoopID())
7634       L->setLoopID(LID);
7635 
7636     LoopVectorizeHints Hints(L, true, *ORE);
7637     Hints.setAlreadyVectorized();
7638   }
7639   // Disable runtime unrolling when vectorizing the epilogue loop.
7640   if (CanonicalIVStartValue)
7641     AddRuntimeUnrollDisableMetaData(L);
7642 
7643   // 3. Fix the vectorized code: take care of header phi's, live-outs,
7644   //    predication, updating analyses.
7645   ILV.fixVectorizedLoop(State, BestVPlan);
7646 
7647   ILV.printDebugTracesAtEnd();
7648 }
7649 
7650 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
7651 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
7652   for (const auto &Plan : VPlans)
7653     if (PrintVPlansInDotFormat)
7654       Plan->printDOT(O);
7655     else
7656       Plan->print(O);
7657 }
7658 #endif
7659 
7660 void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
7661     SmallPtrSetImpl<Instruction *> &DeadInstructions) {
7662 
7663   // We create new control-flow for the vectorized loop, so the original exit
7664   // conditions will be dead after vectorization if it's only used by the
7665   // terminator
7666   SmallVector<BasicBlock*> ExitingBlocks;
7667   OrigLoop->getExitingBlocks(ExitingBlocks);
7668   for (auto *BB : ExitingBlocks) {
7669     auto *Cmp = dyn_cast<Instruction>(BB->getTerminator()->getOperand(0));
7670     if (!Cmp || !Cmp->hasOneUse())
7671       continue;
7672 
7673     // TODO: we should introduce a getUniqueExitingBlocks on Loop
7674     if (!DeadInstructions.insert(Cmp).second)
7675       continue;
7676 
7677     // The operands of the icmp is often a dead trunc, used by IndUpdate.
7678     // TODO: can recurse through operands in general
7679     for (Value *Op : Cmp->operands()) {
7680       if (isa<TruncInst>(Op) && Op->hasOneUse())
7681           DeadInstructions.insert(cast<Instruction>(Op));
7682     }
7683   }
7684 
7685   // We create new "steps" for induction variable updates to which the original
7686   // induction variables map. An original update instruction will be dead if
7687   // all its users except the induction variable are dead.
7688   auto *Latch = OrigLoop->getLoopLatch();
7689   for (auto &Induction : Legal->getInductionVars()) {
7690     PHINode *Ind = Induction.first;
7691     auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
7692 
7693     // If the tail is to be folded by masking, the primary induction variable,
7694     // if exists, isn't dead: it will be used for masking. Don't kill it.
7695     if (CM.foldTailByMasking() && IndUpdate == Legal->getPrimaryInduction())
7696       continue;
7697 
7698     if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
7699           return U == Ind || DeadInstructions.count(cast<Instruction>(U));
7700         }))
7701       DeadInstructions.insert(IndUpdate);
7702   }
7703 }
7704 
7705 Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
7706 
7707 //===--------------------------------------------------------------------===//
7708 // EpilogueVectorizerMainLoop
7709 //===--------------------------------------------------------------------===//
7710 
7711 /// This function is partially responsible for generating the control flow
7712 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7713 std::pair<BasicBlock *, Value *>
7714 EpilogueVectorizerMainLoop::createEpilogueVectorizedLoopSkeleton() {
7715   MDNode *OrigLoopID = OrigLoop->getLoopID();
7716 
7717   // Workaround!  Compute the trip count of the original loop and cache it
7718   // before we start modifying the CFG.  This code has a systemic problem
7719   // wherein it tries to run analysis over partially constructed IR; this is
7720   // wrong, and not simply for SCEV.  The trip count of the original loop
7721   // simply happens to be prone to hitting this in practice.  In theory, we
7722   // can hit the same issue for any SCEV, or ValueTracking query done during
7723   // mutation.  See PR49900.
7724   getOrCreateTripCount(OrigLoop->getLoopPreheader());
7725   createVectorLoopSkeleton("");
7726 
7727   // Generate the code to check the minimum iteration count of the vector
7728   // epilogue (see below).
7729   EPI.EpilogueIterationCountCheck =
7730       emitIterationCountCheck(LoopScalarPreHeader, true);
7731   EPI.EpilogueIterationCountCheck->setName("iter.check");
7732 
7733   // Generate the code to check any assumptions that we've made for SCEV
7734   // expressions.
7735   EPI.SCEVSafetyCheck = emitSCEVChecks(LoopScalarPreHeader);
7736 
7737   // Generate the code that checks at runtime if arrays overlap. We put the
7738   // checks into a separate block to make the more common case of few elements
7739   // faster.
7740   EPI.MemSafetyCheck = emitMemRuntimeChecks(LoopScalarPreHeader);
7741 
7742   // Generate the iteration count check for the main loop, *after* the check
7743   // for the epilogue loop, so that the path-length is shorter for the case
7744   // that goes directly through the vector epilogue. The longer-path length for
7745   // the main loop is compensated for, by the gain from vectorizing the larger
7746   // trip count. Note: the branch will get updated later on when we vectorize
7747   // the epilogue.
7748   EPI.MainLoopIterationCountCheck =
7749       emitIterationCountCheck(LoopScalarPreHeader, false);
7750 
7751   // Generate the induction variable.
7752   EPI.VectorTripCount = getOrCreateVectorTripCount(LoopVectorPreHeader);
7753 
7754   // Skip induction resume value creation here because they will be created in
7755   // the second pass. If we created them here, they wouldn't be used anyway,
7756   // because the vplan in the second pass still contains the inductions from the
7757   // original loop.
7758 
7759   return {completeLoopSkeleton(OrigLoopID), nullptr};
7760 }
7761 
7762 void EpilogueVectorizerMainLoop::printDebugTracesAtStart() {
7763   LLVM_DEBUG({
7764     dbgs() << "Create Skeleton for epilogue vectorized loop (first pass)\n"
7765            << "Main Loop VF:" << EPI.MainLoopVF
7766            << ", Main Loop UF:" << EPI.MainLoopUF
7767            << ", Epilogue Loop VF:" << EPI.EpilogueVF
7768            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7769   });
7770 }
7771 
7772 void EpilogueVectorizerMainLoop::printDebugTracesAtEnd() {
7773   DEBUG_WITH_TYPE(VerboseDebug, {
7774     dbgs() << "intermediate fn:\n"
7775            << *OrigLoop->getHeader()->getParent() << "\n";
7776   });
7777 }
7778 
7779 BasicBlock *
7780 EpilogueVectorizerMainLoop::emitIterationCountCheck(BasicBlock *Bypass,
7781                                                     bool ForEpilogue) {
7782   assert(Bypass && "Expected valid bypass basic block.");
7783   ElementCount VFactor = ForEpilogue ? EPI.EpilogueVF : VF;
7784   unsigned UFactor = ForEpilogue ? EPI.EpilogueUF : UF;
7785   Value *Count = getOrCreateTripCount(LoopVectorPreHeader);
7786   // Reuse existing vector loop preheader for TC checks.
7787   // Note that new preheader block is generated for vector loop.
7788   BasicBlock *const TCCheckBlock = LoopVectorPreHeader;
7789   IRBuilder<> Builder(TCCheckBlock->getTerminator());
7790 
7791   // Generate code to check if the loop's trip count is less than VF * UF of the
7792   // main vector loop.
7793   auto P = Cost->requiresScalarEpilogue(ForEpilogue ? EPI.EpilogueVF : VF) ?
7794       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7795 
7796   Value *CheckMinIters = Builder.CreateICmp(
7797       P, Count, createStepForVF(Builder, Count->getType(), VFactor, UFactor),
7798       "min.iters.check");
7799 
7800   if (!ForEpilogue)
7801     TCCheckBlock->setName("vector.main.loop.iter.check");
7802 
7803   // Create new preheader for vector loop.
7804   LoopVectorPreHeader = SplitBlock(TCCheckBlock, TCCheckBlock->getTerminator(),
7805                                    DT, LI, nullptr, "vector.ph");
7806 
7807   if (ForEpilogue) {
7808     assert(DT->properlyDominates(DT->getNode(TCCheckBlock),
7809                                  DT->getNode(Bypass)->getIDom()) &&
7810            "TC check is expected to dominate Bypass");
7811 
7812     // Update dominator for Bypass & LoopExit.
7813     DT->changeImmediateDominator(Bypass, TCCheckBlock);
7814     if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7815       // For loops with multiple exits, there's no edge from the middle block
7816       // to exit blocks (as the epilogue must run) and thus no need to update
7817       // the immediate dominator of the exit blocks.
7818       DT->changeImmediateDominator(LoopExitBlock, TCCheckBlock);
7819 
7820     LoopBypassBlocks.push_back(TCCheckBlock);
7821 
7822     // Save the trip count so we don't have to regenerate it in the
7823     // vec.epilog.iter.check. This is safe to do because the trip count
7824     // generated here dominates the vector epilog iter check.
7825     EPI.TripCount = Count;
7826   }
7827 
7828   ReplaceInstWithInst(
7829       TCCheckBlock->getTerminator(),
7830       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7831 
7832   return TCCheckBlock;
7833 }
7834 
7835 //===--------------------------------------------------------------------===//
7836 // EpilogueVectorizerEpilogueLoop
7837 //===--------------------------------------------------------------------===//
7838 
7839 /// This function is partially responsible for generating the control flow
7840 /// depicted in https://llvm.org/docs/Vectorizers.html#epilogue-vectorization.
7841 std::pair<BasicBlock *, Value *>
7842 EpilogueVectorizerEpilogueLoop::createEpilogueVectorizedLoopSkeleton() {
7843   MDNode *OrigLoopID = OrigLoop->getLoopID();
7844   createVectorLoopSkeleton("vec.epilog.");
7845 
7846   // Now, compare the remaining count and if there aren't enough iterations to
7847   // execute the vectorized epilogue skip to the scalar part.
7848   BasicBlock *VecEpilogueIterationCountCheck = LoopVectorPreHeader;
7849   VecEpilogueIterationCountCheck->setName("vec.epilog.iter.check");
7850   LoopVectorPreHeader =
7851       SplitBlock(LoopVectorPreHeader, LoopVectorPreHeader->getTerminator(), DT,
7852                  LI, nullptr, "vec.epilog.ph");
7853   emitMinimumVectorEpilogueIterCountCheck(LoopScalarPreHeader,
7854                                           VecEpilogueIterationCountCheck);
7855 
7856   // Adjust the control flow taking the state info from the main loop
7857   // vectorization into account.
7858   assert(EPI.MainLoopIterationCountCheck && EPI.EpilogueIterationCountCheck &&
7859          "expected this to be saved from the previous pass.");
7860   EPI.MainLoopIterationCountCheck->getTerminator()->replaceUsesOfWith(
7861       VecEpilogueIterationCountCheck, LoopVectorPreHeader);
7862 
7863   DT->changeImmediateDominator(LoopVectorPreHeader,
7864                                EPI.MainLoopIterationCountCheck);
7865 
7866   EPI.EpilogueIterationCountCheck->getTerminator()->replaceUsesOfWith(
7867       VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7868 
7869   if (EPI.SCEVSafetyCheck)
7870     EPI.SCEVSafetyCheck->getTerminator()->replaceUsesOfWith(
7871         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7872   if (EPI.MemSafetyCheck)
7873     EPI.MemSafetyCheck->getTerminator()->replaceUsesOfWith(
7874         VecEpilogueIterationCountCheck, LoopScalarPreHeader);
7875 
7876   DT->changeImmediateDominator(
7877       VecEpilogueIterationCountCheck,
7878       VecEpilogueIterationCountCheck->getSinglePredecessor());
7879 
7880   DT->changeImmediateDominator(LoopScalarPreHeader,
7881                                EPI.EpilogueIterationCountCheck);
7882   if (!Cost->requiresScalarEpilogue(EPI.EpilogueVF))
7883     // If there is an epilogue which must run, there's no edge from the
7884     // middle block to exit blocks  and thus no need to update the immediate
7885     // dominator of the exit blocks.
7886     DT->changeImmediateDominator(LoopExitBlock,
7887                                  EPI.EpilogueIterationCountCheck);
7888 
7889   // Keep track of bypass blocks, as they feed start values to the induction
7890   // phis in the scalar loop preheader.
7891   if (EPI.SCEVSafetyCheck)
7892     LoopBypassBlocks.push_back(EPI.SCEVSafetyCheck);
7893   if (EPI.MemSafetyCheck)
7894     LoopBypassBlocks.push_back(EPI.MemSafetyCheck);
7895   LoopBypassBlocks.push_back(EPI.EpilogueIterationCountCheck);
7896 
7897   // The vec.epilog.iter.check block may contain Phi nodes from reductions which
7898   // merge control-flow from the latch block and the middle block. Update the
7899   // incoming values here and move the Phi into the preheader.
7900   SmallVector<PHINode *, 4> PhisInBlock;
7901   for (PHINode &Phi : VecEpilogueIterationCountCheck->phis())
7902     PhisInBlock.push_back(&Phi);
7903 
7904   for (PHINode *Phi : PhisInBlock) {
7905     Phi->replaceIncomingBlockWith(
7906         VecEpilogueIterationCountCheck->getSinglePredecessor(),
7907         VecEpilogueIterationCountCheck);
7908     Phi->removeIncomingValue(EPI.EpilogueIterationCountCheck);
7909     if (EPI.SCEVSafetyCheck)
7910       Phi->removeIncomingValue(EPI.SCEVSafetyCheck);
7911     if (EPI.MemSafetyCheck)
7912       Phi->removeIncomingValue(EPI.MemSafetyCheck);
7913     Phi->moveBefore(LoopVectorPreHeader->getFirstNonPHI());
7914   }
7915 
7916   // Generate a resume induction for the vector epilogue and put it in the
7917   // vector epilogue preheader
7918   Type *IdxTy = Legal->getWidestInductionType();
7919   PHINode *EPResumeVal = PHINode::Create(IdxTy, 2, "vec.epilog.resume.val",
7920                                          LoopVectorPreHeader->getFirstNonPHI());
7921   EPResumeVal->addIncoming(EPI.VectorTripCount, VecEpilogueIterationCountCheck);
7922   EPResumeVal->addIncoming(ConstantInt::get(IdxTy, 0),
7923                            EPI.MainLoopIterationCountCheck);
7924 
7925   // Generate induction resume values. These variables save the new starting
7926   // indexes for the scalar loop. They are used to test if there are any tail
7927   // iterations left once the vector loop has completed.
7928   // Note that when the vectorized epilogue is skipped due to iteration count
7929   // check, then the resume value for the induction variable comes from
7930   // the trip count of the main vector loop, hence passing the AdditionalBypass
7931   // argument.
7932   createInductionResumeValues({VecEpilogueIterationCountCheck,
7933                                EPI.VectorTripCount} /* AdditionalBypass */);
7934 
7935   return {completeLoopSkeleton(OrigLoopID), EPResumeVal};
7936 }
7937 
7938 BasicBlock *
7939 EpilogueVectorizerEpilogueLoop::emitMinimumVectorEpilogueIterCountCheck(
7940     BasicBlock *Bypass, BasicBlock *Insert) {
7941 
7942   assert(EPI.TripCount &&
7943          "Expected trip count to have been safed in the first pass.");
7944   assert(
7945       (!isa<Instruction>(EPI.TripCount) ||
7946        DT->dominates(cast<Instruction>(EPI.TripCount)->getParent(), Insert)) &&
7947       "saved trip count does not dominate insertion point.");
7948   Value *TC = EPI.TripCount;
7949   IRBuilder<> Builder(Insert->getTerminator());
7950   Value *Count = Builder.CreateSub(TC, EPI.VectorTripCount, "n.vec.remaining");
7951 
7952   // Generate code to check if the loop's trip count is less than VF * UF of the
7953   // vector epilogue loop.
7954   auto P = Cost->requiresScalarEpilogue(EPI.EpilogueVF) ?
7955       ICmpInst::ICMP_ULE : ICmpInst::ICMP_ULT;
7956 
7957   Value *CheckMinIters =
7958       Builder.CreateICmp(P, Count,
7959                          createStepForVF(Builder, Count->getType(),
7960                                          EPI.EpilogueVF, EPI.EpilogueUF),
7961                          "min.epilog.iters.check");
7962 
7963   ReplaceInstWithInst(
7964       Insert->getTerminator(),
7965       BranchInst::Create(Bypass, LoopVectorPreHeader, CheckMinIters));
7966 
7967   LoopBypassBlocks.push_back(Insert);
7968   return Insert;
7969 }
7970 
7971 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtStart() {
7972   LLVM_DEBUG({
7973     dbgs() << "Create Skeleton for epilogue vectorized loop (second pass)\n"
7974            << "Epilogue Loop VF:" << EPI.EpilogueVF
7975            << ", Epilogue Loop UF:" << EPI.EpilogueUF << "\n";
7976   });
7977 }
7978 
7979 void EpilogueVectorizerEpilogueLoop::printDebugTracesAtEnd() {
7980   DEBUG_WITH_TYPE(VerboseDebug, {
7981     dbgs() << "final fn:\n" << *OrigLoop->getHeader()->getParent() << "\n";
7982   });
7983 }
7984 
7985 bool LoopVectorizationPlanner::getDecisionAndClampRange(
7986     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
7987   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
7988   bool PredicateAtRangeStart = Predicate(Range.Start);
7989 
7990   for (ElementCount TmpVF = Range.Start * 2;
7991        ElementCount::isKnownLT(TmpVF, Range.End); TmpVF *= 2)
7992     if (Predicate(TmpVF) != PredicateAtRangeStart) {
7993       Range.End = TmpVF;
7994       break;
7995     }
7996 
7997   return PredicateAtRangeStart;
7998 }
7999 
8000 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
8001 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
8002 /// of VF's starting at a given VF and extending it as much as possible. Each
8003 /// vectorization decision can potentially shorten this sub-range during
8004 /// buildVPlan().
8005 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
8006                                            ElementCount MaxVF) {
8007   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8008   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8009     VFRange SubRange = {VF, MaxVFPlusOne};
8010     VPlans.push_back(buildVPlan(SubRange));
8011     VF = SubRange.End;
8012   }
8013 }
8014 
8015 VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
8016                                          VPlanPtr &Plan) {
8017   assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
8018 
8019   // Look for cached value.
8020   std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
8021   EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
8022   if (ECEntryIt != EdgeMaskCache.end())
8023     return ECEntryIt->second;
8024 
8025   VPValue *SrcMask = createBlockInMask(Src, Plan);
8026 
8027   // The terminator has to be a branch inst!
8028   BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
8029   assert(BI && "Unexpected terminator found");
8030 
8031   if (!BI->isConditional() || BI->getSuccessor(0) == BI->getSuccessor(1))
8032     return EdgeMaskCache[Edge] = SrcMask;
8033 
8034   // If source is an exiting block, we know the exit edge is dynamically dead
8035   // in the vector loop, and thus we don't need to restrict the mask.  Avoid
8036   // adding uses of an otherwise potentially dead instruction.
8037   if (OrigLoop->isLoopExiting(Src))
8038     return EdgeMaskCache[Edge] = SrcMask;
8039 
8040   VPValue *EdgeMask = Plan->getOrAddVPValue(BI->getCondition());
8041   assert(EdgeMask && "No Edge Mask found for condition");
8042 
8043   if (BI->getSuccessor(0) != Dst)
8044     EdgeMask = Builder.createNot(EdgeMask, BI->getDebugLoc());
8045 
8046   if (SrcMask) { // Otherwise block in-mask is all-one, no need to AND.
8047     // The condition is 'SrcMask && EdgeMask', which is equivalent to
8048     // 'select i1 SrcMask, i1 EdgeMask, i1 false'.
8049     // The select version does not introduce new UB if SrcMask is false and
8050     // EdgeMask is poison. Using 'and' here introduces undefined behavior.
8051     VPValue *False = Plan->getOrAddVPValue(
8052         ConstantInt::getFalse(BI->getCondition()->getType()));
8053     EdgeMask =
8054         Builder.createSelect(SrcMask, EdgeMask, False, BI->getDebugLoc());
8055   }
8056 
8057   return EdgeMaskCache[Edge] = EdgeMask;
8058 }
8059 
8060 VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
8061   assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
8062 
8063   // Look for cached value.
8064   BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
8065   if (BCEntryIt != BlockMaskCache.end())
8066     return BCEntryIt->second;
8067 
8068   // All-one mask is modelled as no-mask following the convention for masked
8069   // load/store/gather/scatter. Initialize BlockMask to no-mask.
8070   VPValue *BlockMask = nullptr;
8071 
8072   if (OrigLoop->getHeader() == BB) {
8073     if (!CM.blockNeedsPredicationForAnyReason(BB))
8074       return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
8075 
8076     // Introduce the early-exit compare IV <= BTC to form header block mask.
8077     // This is used instead of IV < TC because TC may wrap, unlike BTC. Start by
8078     // constructing the desired canonical IV in the header block as its first
8079     // non-phi instructions.
8080     assert(CM.foldTailByMasking() && "must fold the tail");
8081     VPBasicBlock *HeaderVPBB =
8082         Plan->getVectorLoopRegion()->getEntryBasicBlock();
8083     auto NewInsertionPoint = HeaderVPBB->getFirstNonPhi();
8084     auto *IV = new VPWidenCanonicalIVRecipe(Plan->getCanonicalIV());
8085     HeaderVPBB->insert(IV, HeaderVPBB->getFirstNonPhi());
8086 
8087     VPBuilder::InsertPointGuard Guard(Builder);
8088     Builder.setInsertPoint(HeaderVPBB, NewInsertionPoint);
8089     if (CM.TTI.emitGetActiveLaneMask()) {
8090       VPValue *TC = Plan->getOrCreateTripCount();
8091       BlockMask = Builder.createNaryOp(VPInstruction::ActiveLaneMask, {IV, TC});
8092     } else {
8093       VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
8094       BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
8095     }
8096     return BlockMaskCache[BB] = BlockMask;
8097   }
8098 
8099   // This is the block mask. We OR all incoming edges.
8100   for (auto *Predecessor : predecessors(BB)) {
8101     VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
8102     if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
8103       return BlockMaskCache[BB] = EdgeMask;
8104 
8105     if (!BlockMask) { // BlockMask has its initialized nullptr value.
8106       BlockMask = EdgeMask;
8107       continue;
8108     }
8109 
8110     BlockMask = Builder.createOr(BlockMask, EdgeMask, {});
8111   }
8112 
8113   return BlockMaskCache[BB] = BlockMask;
8114 }
8115 
8116 VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(Instruction *I,
8117                                                 ArrayRef<VPValue *> Operands,
8118                                                 VFRange &Range,
8119                                                 VPlanPtr &Plan) {
8120   assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
8121          "Must be called with either a load or store");
8122 
8123   auto willWiden = [&](ElementCount VF) -> bool {
8124     LoopVectorizationCostModel::InstWidening Decision =
8125         CM.getWideningDecision(I, VF);
8126     assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
8127            "CM decision should be taken at this point.");
8128     if (Decision == LoopVectorizationCostModel::CM_Interleave)
8129       return true;
8130     if (CM.isScalarAfterVectorization(I, VF) ||
8131         CM.isProfitableToScalarize(I, VF))
8132       return false;
8133     return Decision != LoopVectorizationCostModel::CM_Scalarize;
8134   };
8135 
8136   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8137     return nullptr;
8138 
8139   VPValue *Mask = nullptr;
8140   if (Legal->isMaskRequired(I))
8141     Mask = createBlockInMask(I->getParent(), Plan);
8142 
8143   // Determine if the pointer operand of the access is either consecutive or
8144   // reverse consecutive.
8145   LoopVectorizationCostModel::InstWidening Decision =
8146       CM.getWideningDecision(I, Range.Start);
8147   bool Reverse = Decision == LoopVectorizationCostModel::CM_Widen_Reverse;
8148   bool Consecutive =
8149       Reverse || Decision == LoopVectorizationCostModel::CM_Widen;
8150 
8151   if (LoadInst *Load = dyn_cast<LoadInst>(I))
8152     return new VPWidenMemoryInstructionRecipe(*Load, Operands[0], Mask,
8153                                               Consecutive, Reverse);
8154 
8155   StoreInst *Store = cast<StoreInst>(I);
8156   return new VPWidenMemoryInstructionRecipe(*Store, Operands[1], Operands[0],
8157                                             Mask, Consecutive, Reverse);
8158 }
8159 
8160 /// Creates a VPWidenIntOrFpInductionRecpipe for \p Phi. If needed, it will also
8161 /// insert a recipe to expand the step for the induction recipe.
8162 static VPWidenIntOrFpInductionRecipe *createWidenInductionRecipes(
8163     PHINode *Phi, Instruction *PhiOrTrunc, VPValue *Start,
8164     const InductionDescriptor &IndDesc, LoopVectorizationCostModel &CM,
8165     VPlan &Plan, ScalarEvolution &SE, Loop &OrigLoop, VFRange &Range) {
8166   // Returns true if an instruction \p I should be scalarized instead of
8167   // vectorized for the chosen vectorization factor.
8168   auto ShouldScalarizeInstruction = [&CM](Instruction *I, ElementCount VF) {
8169     return CM.isScalarAfterVectorization(I, VF) ||
8170            CM.isProfitableToScalarize(I, VF);
8171   };
8172 
8173   bool NeedsScalarIVOnly = LoopVectorizationPlanner::getDecisionAndClampRange(
8174       [&](ElementCount VF) {
8175         return ShouldScalarizeInstruction(PhiOrTrunc, VF);
8176       },
8177       Range);
8178   assert(IndDesc.getStartValue() ==
8179          Phi->getIncomingValueForBlock(OrigLoop.getLoopPreheader()));
8180   assert(SE.isLoopInvariant(IndDesc.getStep(), &OrigLoop) &&
8181          "step must be loop invariant");
8182 
8183   VPValue *Step =
8184       vputils::getOrCreateVPValueForSCEVExpr(Plan, IndDesc.getStep(), SE);
8185   if (auto *TruncI = dyn_cast<TruncInst>(PhiOrTrunc)) {
8186     return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc, TruncI,
8187                                              !NeedsScalarIVOnly);
8188   }
8189   assert(isa<PHINode>(PhiOrTrunc) && "must be a phi node here");
8190   return new VPWidenIntOrFpInductionRecipe(Phi, Start, Step, IndDesc,
8191                                            !NeedsScalarIVOnly);
8192 }
8193 
8194 VPRecipeBase *VPRecipeBuilder::tryToOptimizeInductionPHI(
8195     PHINode *Phi, ArrayRef<VPValue *> Operands, VPlan &Plan, VFRange &Range) {
8196 
8197   // Check if this is an integer or fp induction. If so, build the recipe that
8198   // produces its scalar and vector values.
8199   if (auto *II = Legal->getIntOrFpInductionDescriptor(Phi))
8200     return createWidenInductionRecipes(Phi, Phi, Operands[0], *II, CM, Plan,
8201                                        *PSE.getSE(), *OrigLoop, Range);
8202 
8203   // Check if this is pointer induction. If so, build the recipe for it.
8204   if (auto *II = Legal->getPointerInductionDescriptor(Phi))
8205     return new VPWidenPointerInductionRecipe(Phi, Operands[0], *II,
8206                                              *PSE.getSE());
8207   return nullptr;
8208 }
8209 
8210 VPWidenIntOrFpInductionRecipe *VPRecipeBuilder::tryToOptimizeInductionTruncate(
8211     TruncInst *I, ArrayRef<VPValue *> Operands, VFRange &Range, VPlan &Plan) {
8212   // Optimize the special case where the source is a constant integer
8213   // induction variable. Notice that we can only optimize the 'trunc' case
8214   // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
8215   // (c) other casts depend on pointer size.
8216 
8217   // Determine whether \p K is a truncation based on an induction variable that
8218   // can be optimized.
8219   auto isOptimizableIVTruncate =
8220       [&](Instruction *K) -> std::function<bool(ElementCount)> {
8221     return [=](ElementCount VF) -> bool {
8222       return CM.isOptimizableIVTruncate(K, VF);
8223     };
8224   };
8225 
8226   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8227           isOptimizableIVTruncate(I), Range)) {
8228 
8229     auto *Phi = cast<PHINode>(I->getOperand(0));
8230     const InductionDescriptor &II = *Legal->getIntOrFpInductionDescriptor(Phi);
8231     VPValue *Start = Plan.getOrAddVPValue(II.getStartValue());
8232     return createWidenInductionRecipes(Phi, I, Start, II, CM, Plan,
8233                                        *PSE.getSE(), *OrigLoop, Range);
8234   }
8235   return nullptr;
8236 }
8237 
8238 VPRecipeOrVPValueTy VPRecipeBuilder::tryToBlend(PHINode *Phi,
8239                                                 ArrayRef<VPValue *> Operands,
8240                                                 VPlanPtr &Plan) {
8241   // If all incoming values are equal, the incoming VPValue can be used directly
8242   // instead of creating a new VPBlendRecipe.
8243   VPValue *FirstIncoming = Operands[0];
8244   if (all_of(Operands, [FirstIncoming](const VPValue *Inc) {
8245         return FirstIncoming == Inc;
8246       })) {
8247     return Operands[0];
8248   }
8249 
8250   unsigned NumIncoming = Phi->getNumIncomingValues();
8251   // For in-loop reductions, we do not need to create an additional select.
8252   VPValue *InLoopVal = nullptr;
8253   for (unsigned In = 0; In < NumIncoming; In++) {
8254     PHINode *PhiOp =
8255         dyn_cast_or_null<PHINode>(Operands[In]->getUnderlyingValue());
8256     if (PhiOp && CM.isInLoopReduction(PhiOp)) {
8257       assert(!InLoopVal && "Found more than one in-loop reduction!");
8258       InLoopVal = Operands[In];
8259     }
8260   }
8261 
8262   assert((!InLoopVal || NumIncoming == 2) &&
8263          "Found an in-loop reduction for PHI with unexpected number of "
8264          "incoming values");
8265   if (InLoopVal)
8266     return Operands[Operands[0] == InLoopVal ? 1 : 0];
8267 
8268   // We know that all PHIs in non-header blocks are converted into selects, so
8269   // we don't have to worry about the insertion order and we can just use the
8270   // builder. At this point we generate the predication tree. There may be
8271   // duplications since this is a simple recursive scan, but future
8272   // optimizations will clean it up.
8273   SmallVector<VPValue *, 2> OperandsWithMask;
8274 
8275   for (unsigned In = 0; In < NumIncoming; In++) {
8276     VPValue *EdgeMask =
8277       createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
8278     assert((EdgeMask || NumIncoming == 1) &&
8279            "Multiple predecessors with one having a full mask");
8280     OperandsWithMask.push_back(Operands[In]);
8281     if (EdgeMask)
8282       OperandsWithMask.push_back(EdgeMask);
8283   }
8284   return toVPRecipeResult(new VPBlendRecipe(Phi, OperandsWithMask));
8285 }
8286 
8287 VPWidenCallRecipe *VPRecipeBuilder::tryToWidenCall(CallInst *CI,
8288                                                    ArrayRef<VPValue *> Operands,
8289                                                    VFRange &Range) const {
8290 
8291   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8292       [this, CI](ElementCount VF) {
8293         return CM.isScalarWithPredication(CI, VF);
8294       },
8295       Range);
8296 
8297   if (IsPredicated)
8298     return nullptr;
8299 
8300   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8301   if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
8302              ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect ||
8303              ID == Intrinsic::pseudoprobe ||
8304              ID == Intrinsic::experimental_noalias_scope_decl))
8305     return nullptr;
8306 
8307   auto willWiden = [&](ElementCount VF) -> bool {
8308     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
8309     // The following case may be scalarized depending on the VF.
8310     // The flag shows whether we use Intrinsic or a usual Call for vectorized
8311     // version of the instruction.
8312     // Is it beneficial to perform intrinsic call compared to lib call?
8313     bool NeedToScalarize = false;
8314     InstructionCost CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
8315     InstructionCost IntrinsicCost = ID ? CM.getVectorIntrinsicCost(CI, VF) : 0;
8316     bool UseVectorIntrinsic = ID && IntrinsicCost <= CallCost;
8317     return UseVectorIntrinsic || !NeedToScalarize;
8318   };
8319 
8320   if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
8321     return nullptr;
8322 
8323   ArrayRef<VPValue *> Ops = Operands.take_front(CI->arg_size());
8324   return new VPWidenCallRecipe(*CI, make_range(Ops.begin(), Ops.end()));
8325 }
8326 
8327 bool VPRecipeBuilder::shouldWiden(Instruction *I, VFRange &Range) const {
8328   assert(!isa<BranchInst>(I) && !isa<PHINode>(I) && !isa<LoadInst>(I) &&
8329          !isa<StoreInst>(I) && "Instruction should have been handled earlier");
8330   // Instruction should be widened, unless it is scalar after vectorization,
8331   // scalarization is profitable or it is predicated.
8332   auto WillScalarize = [this, I](ElementCount VF) -> bool {
8333     return CM.isScalarAfterVectorization(I, VF) ||
8334            CM.isProfitableToScalarize(I, VF) ||
8335            CM.isScalarWithPredication(I, VF);
8336   };
8337   return !LoopVectorizationPlanner::getDecisionAndClampRange(WillScalarize,
8338                                                              Range);
8339 }
8340 
8341 VPWidenRecipe *VPRecipeBuilder::tryToWiden(Instruction *I,
8342                                            ArrayRef<VPValue *> Operands) const {
8343   auto IsVectorizableOpcode = [](unsigned Opcode) {
8344     switch (Opcode) {
8345     case Instruction::Add:
8346     case Instruction::And:
8347     case Instruction::AShr:
8348     case Instruction::BitCast:
8349     case Instruction::FAdd:
8350     case Instruction::FCmp:
8351     case Instruction::FDiv:
8352     case Instruction::FMul:
8353     case Instruction::FNeg:
8354     case Instruction::FPExt:
8355     case Instruction::FPToSI:
8356     case Instruction::FPToUI:
8357     case Instruction::FPTrunc:
8358     case Instruction::FRem:
8359     case Instruction::FSub:
8360     case Instruction::ICmp:
8361     case Instruction::IntToPtr:
8362     case Instruction::LShr:
8363     case Instruction::Mul:
8364     case Instruction::Or:
8365     case Instruction::PtrToInt:
8366     case Instruction::SDiv:
8367     case Instruction::Select:
8368     case Instruction::SExt:
8369     case Instruction::Shl:
8370     case Instruction::SIToFP:
8371     case Instruction::SRem:
8372     case Instruction::Sub:
8373     case Instruction::Trunc:
8374     case Instruction::UDiv:
8375     case Instruction::UIToFP:
8376     case Instruction::URem:
8377     case Instruction::Xor:
8378     case Instruction::ZExt:
8379     case Instruction::Freeze:
8380       return true;
8381     }
8382     return false;
8383   };
8384 
8385   if (!IsVectorizableOpcode(I->getOpcode()))
8386     return nullptr;
8387 
8388   // Success: widen this instruction.
8389   return new VPWidenRecipe(*I, make_range(Operands.begin(), Operands.end()));
8390 }
8391 
8392 void VPRecipeBuilder::fixHeaderPhis() {
8393   BasicBlock *OrigLatch = OrigLoop->getLoopLatch();
8394   for (VPHeaderPHIRecipe *R : PhisToFix) {
8395     auto *PN = cast<PHINode>(R->getUnderlyingValue());
8396     VPRecipeBase *IncR =
8397         getRecipe(cast<Instruction>(PN->getIncomingValueForBlock(OrigLatch)));
8398     R->addOperand(IncR->getVPSingleValue());
8399   }
8400 }
8401 
8402 VPBasicBlock *VPRecipeBuilder::handleReplication(
8403     Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
8404     VPlanPtr &Plan) {
8405   bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
8406       [&](ElementCount VF) { return CM.isUniformAfterVectorization(I, VF); },
8407       Range);
8408 
8409   bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
8410       [&](ElementCount VF) { return CM.isPredicatedInst(I, VF, IsUniform); },
8411       Range);
8412 
8413   // Even if the instruction is not marked as uniform, there are certain
8414   // intrinsic calls that can be effectively treated as such, so we check for
8415   // them here. Conservatively, we only do this for scalable vectors, since
8416   // for fixed-width VFs we can always fall back on full scalarization.
8417   if (!IsUniform && Range.Start.isScalable() && isa<IntrinsicInst>(I)) {
8418     switch (cast<IntrinsicInst>(I)->getIntrinsicID()) {
8419     case Intrinsic::assume:
8420     case Intrinsic::lifetime_start:
8421     case Intrinsic::lifetime_end:
8422       // For scalable vectors if one of the operands is variant then we still
8423       // want to mark as uniform, which will generate one instruction for just
8424       // the first lane of the vector. We can't scalarize the call in the same
8425       // way as for fixed-width vectors because we don't know how many lanes
8426       // there are.
8427       //
8428       // The reasons for doing it this way for scalable vectors are:
8429       //   1. For the assume intrinsic generating the instruction for the first
8430       //      lane is still be better than not generating any at all. For
8431       //      example, the input may be a splat across all lanes.
8432       //   2. For the lifetime start/end intrinsics the pointer operand only
8433       //      does anything useful when the input comes from a stack object,
8434       //      which suggests it should always be uniform. For non-stack objects
8435       //      the effect is to poison the object, which still allows us to
8436       //      remove the call.
8437       IsUniform = true;
8438       break;
8439     default:
8440       break;
8441     }
8442   }
8443 
8444   auto *Recipe = new VPReplicateRecipe(I, Plan->mapToVPValues(I->operands()),
8445                                        IsUniform, IsPredicated);
8446   setRecipe(I, Recipe);
8447   Plan->addVPValue(I, Recipe);
8448 
8449   // Find if I uses a predicated instruction. If so, it will use its scalar
8450   // value. Avoid hoisting the insert-element which packs the scalar value into
8451   // a vector value, as that happens iff all users use the vector value.
8452   for (VPValue *Op : Recipe->operands()) {
8453     auto *PredR = dyn_cast_or_null<VPPredInstPHIRecipe>(Op->getDef());
8454     if (!PredR)
8455       continue;
8456     auto *RepR =
8457         cast_or_null<VPReplicateRecipe>(PredR->getOperand(0)->getDef());
8458     assert(RepR->isPredicated() &&
8459            "expected Replicate recipe to be predicated");
8460     RepR->setAlsoPack(false);
8461   }
8462 
8463   // Finalize the recipe for Instr, first if it is not predicated.
8464   if (!IsPredicated) {
8465     LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
8466     VPBB->appendRecipe(Recipe);
8467     return VPBB;
8468   }
8469   LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
8470 
8471   VPBlockBase *SingleSucc = VPBB->getSingleSuccessor();
8472   assert(SingleSucc && "VPBB must have a single successor when handling "
8473                        "predicated replication.");
8474   VPBlockUtils::disconnectBlocks(VPBB, SingleSucc);
8475   // Record predicated instructions for above packing optimizations.
8476   VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
8477   VPBlockUtils::insertBlockAfter(Region, VPBB);
8478   auto *RegSucc = new VPBasicBlock();
8479   VPBlockUtils::insertBlockAfter(RegSucc, Region);
8480   VPBlockUtils::connectBlocks(RegSucc, SingleSucc);
8481   return RegSucc;
8482 }
8483 
8484 VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
8485                                                       VPRecipeBase *PredRecipe,
8486                                                       VPlanPtr &Plan) {
8487   // Instructions marked for predication are replicated and placed under an
8488   // if-then construct to prevent side-effects.
8489 
8490   // Generate recipes to compute the block mask for this region.
8491   VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
8492 
8493   // Build the triangular if-then region.
8494   std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
8495   assert(Instr->getParent() && "Predicated instruction not in any basic block");
8496   auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
8497   auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
8498   auto *PHIRecipe = Instr->getType()->isVoidTy()
8499                         ? nullptr
8500                         : new VPPredInstPHIRecipe(Plan->getOrAddVPValue(Instr));
8501   if (PHIRecipe) {
8502     Plan->removeVPValueFor(Instr);
8503     Plan->addVPValue(Instr, PHIRecipe);
8504   }
8505   auto *Exiting = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
8506   auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
8507   VPRegionBlock *Region = new VPRegionBlock(Entry, Exiting, RegionName, true);
8508 
8509   // Note: first set Entry as region entry and then connect successors starting
8510   // from it in order, to propagate the "parent" of each VPBasicBlock.
8511   VPBlockUtils::insertTwoBlocksAfter(Pred, Exiting, Entry);
8512   VPBlockUtils::connectBlocks(Pred, Exiting);
8513 
8514   return Region;
8515 }
8516 
8517 VPRecipeOrVPValueTy
8518 VPRecipeBuilder::tryToCreateWidenRecipe(Instruction *Instr,
8519                                         ArrayRef<VPValue *> Operands,
8520                                         VFRange &Range, VPlanPtr &Plan) {
8521   // First, check for specific widening recipes that deal with inductions, Phi
8522   // nodes, calls and memory operations.
8523   VPRecipeBase *Recipe;
8524   if (auto Phi = dyn_cast<PHINode>(Instr)) {
8525     if (Phi->getParent() != OrigLoop->getHeader())
8526       return tryToBlend(Phi, Operands, Plan);
8527     if ((Recipe = tryToOptimizeInductionPHI(Phi, Operands, *Plan, Range)))
8528       return toVPRecipeResult(Recipe);
8529 
8530     VPHeaderPHIRecipe *PhiRecipe = nullptr;
8531     assert((Legal->isReductionVariable(Phi) ||
8532             Legal->isFirstOrderRecurrence(Phi)) &&
8533            "can only widen reductions and first-order recurrences here");
8534     VPValue *StartV = Operands[0];
8535     if (Legal->isReductionVariable(Phi)) {
8536       const RecurrenceDescriptor &RdxDesc =
8537           Legal->getReductionVars().find(Phi)->second;
8538       assert(RdxDesc.getRecurrenceStartValue() ==
8539              Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader()));
8540       PhiRecipe = new VPReductionPHIRecipe(Phi, RdxDesc, *StartV,
8541                                            CM.isInLoopReduction(Phi),
8542                                            CM.useOrderedReductions(RdxDesc));
8543     } else {
8544       PhiRecipe = new VPFirstOrderRecurrencePHIRecipe(Phi, *StartV);
8545     }
8546 
8547     // Record the incoming value from the backedge, so we can add the incoming
8548     // value from the backedge after all recipes have been created.
8549     recordRecipeOf(cast<Instruction>(
8550         Phi->getIncomingValueForBlock(OrigLoop->getLoopLatch())));
8551     PhisToFix.push_back(PhiRecipe);
8552     return toVPRecipeResult(PhiRecipe);
8553   }
8554 
8555   if (isa<TruncInst>(Instr) &&
8556       (Recipe = tryToOptimizeInductionTruncate(cast<TruncInst>(Instr), Operands,
8557                                                Range, *Plan)))
8558     return toVPRecipeResult(Recipe);
8559 
8560   // All widen recipes below deal only with VF > 1.
8561   if (LoopVectorizationPlanner::getDecisionAndClampRange(
8562           [&](ElementCount VF) { return VF.isScalar(); }, Range))
8563     return nullptr;
8564 
8565   if (auto *CI = dyn_cast<CallInst>(Instr))
8566     return toVPRecipeResult(tryToWidenCall(CI, Operands, Range));
8567 
8568   if (isa<LoadInst>(Instr) || isa<StoreInst>(Instr))
8569     return toVPRecipeResult(tryToWidenMemory(Instr, Operands, Range, Plan));
8570 
8571   if (!shouldWiden(Instr, Range))
8572     return nullptr;
8573 
8574   if (auto GEP = dyn_cast<GetElementPtrInst>(Instr))
8575     return toVPRecipeResult(new VPWidenGEPRecipe(
8576         GEP, make_range(Operands.begin(), Operands.end()), OrigLoop));
8577 
8578   if (auto *SI = dyn_cast<SelectInst>(Instr)) {
8579     bool InvariantCond =
8580         PSE.getSE()->isLoopInvariant(PSE.getSCEV(SI->getOperand(0)), OrigLoop);
8581     return toVPRecipeResult(new VPWidenSelectRecipe(
8582         *SI, make_range(Operands.begin(), Operands.end()), InvariantCond));
8583   }
8584 
8585   return toVPRecipeResult(tryToWiden(Instr, Operands));
8586 }
8587 
8588 void LoopVectorizationPlanner::buildVPlansWithVPRecipes(ElementCount MinVF,
8589                                                         ElementCount MaxVF) {
8590   assert(OrigLoop->isInnermost() && "Inner loop expected.");
8591 
8592   // Collect instructions from the original loop that will become trivially dead
8593   // in the vectorized loop. We don't need to vectorize these instructions. For
8594   // example, original induction update instructions can become dead because we
8595   // separately emit induction "steps" when generating code for the new loop.
8596   // Similarly, we create a new latch condition when setting up the structure
8597   // of the new loop, so the old one can become dead.
8598   SmallPtrSet<Instruction *, 4> DeadInstructions;
8599   collectTriviallyDeadInstructions(DeadInstructions);
8600 
8601   // Add assume instructions we need to drop to DeadInstructions, to prevent
8602   // them from being added to the VPlan.
8603   // TODO: We only need to drop assumes in blocks that get flattend. If the
8604   // control flow is preserved, we should keep them.
8605   auto &ConditionalAssumes = Legal->getConditionalAssumes();
8606   DeadInstructions.insert(ConditionalAssumes.begin(), ConditionalAssumes.end());
8607 
8608   MapVector<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
8609   // Dead instructions do not need sinking. Remove them from SinkAfter.
8610   for (Instruction *I : DeadInstructions)
8611     SinkAfter.erase(I);
8612 
8613   // Cannot sink instructions after dead instructions (there won't be any
8614   // recipes for them). Instead, find the first non-dead previous instruction.
8615   for (auto &P : Legal->getSinkAfter()) {
8616     Instruction *SinkTarget = P.second;
8617     Instruction *FirstInst = &*SinkTarget->getParent()->begin();
8618     (void)FirstInst;
8619     while (DeadInstructions.contains(SinkTarget)) {
8620       assert(
8621           SinkTarget != FirstInst &&
8622           "Must find a live instruction (at least the one feeding the "
8623           "first-order recurrence PHI) before reaching beginning of the block");
8624       SinkTarget = SinkTarget->getPrevNode();
8625       assert(SinkTarget != P.first &&
8626              "sink source equals target, no sinking required");
8627     }
8628     P.second = SinkTarget;
8629   }
8630 
8631   auto MaxVFPlusOne = MaxVF.getWithIncrement(1);
8632   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFPlusOne);) {
8633     VFRange SubRange = {VF, MaxVFPlusOne};
8634     VPlans.push_back(
8635         buildVPlanWithVPRecipes(SubRange, DeadInstructions, SinkAfter));
8636     VF = SubRange.End;
8637   }
8638 }
8639 
8640 // Add a VPCanonicalIVPHIRecipe starting at 0 to the header, a
8641 // CanonicalIVIncrement{NUW} VPInstruction to increment it by VF * UF and a
8642 // BranchOnCount VPInstruction to the latch.
8643 static void addCanonicalIVRecipes(VPlan &Plan, Type *IdxTy, DebugLoc DL,
8644                                   bool HasNUW) {
8645   Value *StartIdx = ConstantInt::get(IdxTy, 0);
8646   auto *StartV = Plan.getOrAddVPValue(StartIdx);
8647 
8648   auto *CanonicalIVPHI = new VPCanonicalIVPHIRecipe(StartV, DL);
8649   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
8650   VPBasicBlock *Header = TopRegion->getEntryBasicBlock();
8651   Header->insert(CanonicalIVPHI, Header->begin());
8652 
8653   auto *CanonicalIVIncrement =
8654       new VPInstruction(HasNUW ? VPInstruction::CanonicalIVIncrementNUW
8655                                : VPInstruction::CanonicalIVIncrement,
8656                         {CanonicalIVPHI}, DL);
8657   CanonicalIVPHI->addOperand(CanonicalIVIncrement);
8658 
8659   VPBasicBlock *EB = TopRegion->getExitingBasicBlock();
8660   EB->appendRecipe(CanonicalIVIncrement);
8661 
8662   auto *BranchOnCount =
8663       new VPInstruction(VPInstruction::BranchOnCount,
8664                         {CanonicalIVIncrement, &Plan.getVectorTripCount()}, DL);
8665   EB->appendRecipe(BranchOnCount);
8666 }
8667 
8668 // Add exit values to \p Plan. VPLiveOuts are added for each LCSSA phi in the
8669 // original exit block.
8670 static void addUsersInExitBlock(VPBasicBlock *HeaderVPBB,
8671                                 VPBasicBlock *MiddleVPBB, Loop *OrigLoop,
8672                                 VPlan &Plan) {
8673   BasicBlock *ExitBB = OrigLoop->getUniqueExitBlock();
8674   BasicBlock *ExitingBB = OrigLoop->getExitingBlock();
8675   // Only handle single-exit loops with unique exit blocks for now.
8676   if (!ExitBB || !ExitBB->getSinglePredecessor() || !ExitingBB)
8677     return;
8678 
8679   // Introduce VPUsers modeling the exit values.
8680   for (PHINode &ExitPhi : ExitBB->phis()) {
8681     Value *IncomingValue =
8682         ExitPhi.getIncomingValueForBlock(ExitingBB);
8683     VPValue *V = Plan.getOrAddVPValue(IncomingValue, true);
8684     Plan.addLiveOut(&ExitPhi, V);
8685   }
8686 }
8687 
8688 VPlanPtr LoopVectorizationPlanner::buildVPlanWithVPRecipes(
8689     VFRange &Range, SmallPtrSetImpl<Instruction *> &DeadInstructions,
8690     const MapVector<Instruction *, Instruction *> &SinkAfter) {
8691 
8692   SmallPtrSet<const InterleaveGroup<Instruction> *, 1> InterleaveGroups;
8693 
8694   VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, PSE, Builder);
8695 
8696   // ---------------------------------------------------------------------------
8697   // Pre-construction: record ingredients whose recipes we'll need to further
8698   // process after constructing the initial VPlan.
8699   // ---------------------------------------------------------------------------
8700 
8701   // Mark instructions we'll need to sink later and their targets as
8702   // ingredients whose recipe we'll need to record.
8703   for (auto &Entry : SinkAfter) {
8704     RecipeBuilder.recordRecipeOf(Entry.first);
8705     RecipeBuilder.recordRecipeOf(Entry.second);
8706   }
8707   for (auto &Reduction : CM.getInLoopReductionChains()) {
8708     PHINode *Phi = Reduction.first;
8709     RecurKind Kind =
8710         Legal->getReductionVars().find(Phi)->second.getRecurrenceKind();
8711     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
8712 
8713     RecipeBuilder.recordRecipeOf(Phi);
8714     for (auto &R : ReductionOperations) {
8715       RecipeBuilder.recordRecipeOf(R);
8716       // For min/max reductions, where we have a pair of icmp/select, we also
8717       // need to record the ICmp recipe, so it can be removed later.
8718       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
8719              "Only min/max recurrences allowed for inloop reductions");
8720       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind))
8721         RecipeBuilder.recordRecipeOf(cast<Instruction>(R->getOperand(0)));
8722     }
8723   }
8724 
8725   // For each interleave group which is relevant for this (possibly trimmed)
8726   // Range, add it to the set of groups to be later applied to the VPlan and add
8727   // placeholders for its members' Recipes which we'll be replacing with a
8728   // single VPInterleaveRecipe.
8729   for (InterleaveGroup<Instruction> *IG : IAI.getInterleaveGroups()) {
8730     auto applyIG = [IG, this](ElementCount VF) -> bool {
8731       return (VF.isVector() && // Query is illegal for VF == 1
8732               CM.getWideningDecision(IG->getInsertPos(), VF) ==
8733                   LoopVectorizationCostModel::CM_Interleave);
8734     };
8735     if (!getDecisionAndClampRange(applyIG, Range))
8736       continue;
8737     InterleaveGroups.insert(IG);
8738     for (unsigned i = 0; i < IG->getFactor(); i++)
8739       if (Instruction *Member = IG->getMember(i))
8740         RecipeBuilder.recordRecipeOf(Member);
8741   };
8742 
8743   // ---------------------------------------------------------------------------
8744   // Build initial VPlan: Scan the body of the loop in a topological order to
8745   // visit each basic block after having visited its predecessor basic blocks.
8746   // ---------------------------------------------------------------------------
8747 
8748   // Create initial VPlan skeleton, starting with a block for the pre-header,
8749   // followed by a region for the vector loop, followed by the middle block. The
8750   // skeleton vector loop region contains a header and latch block.
8751   VPBasicBlock *Preheader = new VPBasicBlock("vector.ph");
8752   auto Plan = std::make_unique<VPlan>(Preheader);
8753 
8754   VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");
8755   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
8756   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
8757   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop");
8758   VPBlockUtils::insertBlockAfter(TopRegion, Preheader);
8759   VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
8760   VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
8761 
8762   Instruction *DLInst =
8763       getDebugLocFromInstOrOperands(Legal->getPrimaryInduction());
8764   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(),
8765                         DLInst ? DLInst->getDebugLoc() : DebugLoc(),
8766                         !CM.foldTailByMasking());
8767 
8768   // Scan the body of the loop in a topological order to visit each basic block
8769   // after having visited its predecessor basic blocks.
8770   LoopBlocksDFS DFS(OrigLoop);
8771   DFS.perform(LI);
8772 
8773   VPBasicBlock *VPBB = HeaderVPBB;
8774   SmallVector<VPWidenIntOrFpInductionRecipe *> InductionsToMove;
8775   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
8776     // Relevant instructions from basic block BB will be grouped into VPRecipe
8777     // ingredients and fill a new VPBasicBlock.
8778     unsigned VPBBsForBB = 0;
8779     if (VPBB != HeaderVPBB)
8780       VPBB->setName(BB->getName());
8781     Builder.setInsertPoint(VPBB);
8782 
8783     // Introduce each ingredient into VPlan.
8784     // TODO: Model and preserve debug intrinsics in VPlan.
8785     for (Instruction &I : BB->instructionsWithoutDebug()) {
8786       Instruction *Instr = &I;
8787 
8788       // First filter out irrelevant instructions, to ensure no recipes are
8789       // built for them.
8790       if (isa<BranchInst>(Instr) || DeadInstructions.count(Instr))
8791         continue;
8792 
8793       SmallVector<VPValue *, 4> Operands;
8794       auto *Phi = dyn_cast<PHINode>(Instr);
8795       if (Phi && Phi->getParent() == OrigLoop->getHeader()) {
8796         Operands.push_back(Plan->getOrAddVPValue(
8797             Phi->getIncomingValueForBlock(OrigLoop->getLoopPreheader())));
8798       } else {
8799         auto OpRange = Plan->mapToVPValues(Instr->operands());
8800         Operands = {OpRange.begin(), OpRange.end()};
8801       }
8802 
8803       // Invariant stores inside loop will be deleted and a single store
8804       // with the final reduction value will be added to the exit block
8805       StoreInst *SI;
8806       if ((SI = dyn_cast<StoreInst>(&I)) &&
8807           Legal->isInvariantAddressOfReduction(SI->getPointerOperand()))
8808         continue;
8809 
8810       if (auto RecipeOrValue = RecipeBuilder.tryToCreateWidenRecipe(
8811               Instr, Operands, Range, Plan)) {
8812         // If Instr can be simplified to an existing VPValue, use it.
8813         if (RecipeOrValue.is<VPValue *>()) {
8814           auto *VPV = RecipeOrValue.get<VPValue *>();
8815           Plan->addVPValue(Instr, VPV);
8816           // If the re-used value is a recipe, register the recipe for the
8817           // instruction, in case the recipe for Instr needs to be recorded.
8818           if (auto *R = dyn_cast_or_null<VPRecipeBase>(VPV->getDef()))
8819             RecipeBuilder.setRecipe(Instr, R);
8820           continue;
8821         }
8822         // Otherwise, add the new recipe.
8823         VPRecipeBase *Recipe = RecipeOrValue.get<VPRecipeBase *>();
8824         for (auto *Def : Recipe->definedValues()) {
8825           auto *UV = Def->getUnderlyingValue();
8826           Plan->addVPValue(UV, Def);
8827         }
8828 
8829         if (isa<VPWidenIntOrFpInductionRecipe>(Recipe) &&
8830             HeaderVPBB->getFirstNonPhi() != VPBB->end()) {
8831           // Keep track of VPWidenIntOrFpInductionRecipes not in the phi section
8832           // of the header block. That can happen for truncates of induction
8833           // variables. Those recipes are moved to the phi section of the header
8834           // block after applying SinkAfter, which relies on the original
8835           // position of the trunc.
8836           assert(isa<TruncInst>(Instr));
8837           InductionsToMove.push_back(
8838               cast<VPWidenIntOrFpInductionRecipe>(Recipe));
8839         }
8840         RecipeBuilder.setRecipe(Instr, Recipe);
8841         VPBB->appendRecipe(Recipe);
8842         continue;
8843       }
8844 
8845       // Otherwise, if all widening options failed, Instruction is to be
8846       // replicated. This may create a successor for VPBB.
8847       VPBasicBlock *NextVPBB =
8848           RecipeBuilder.handleReplication(Instr, Range, VPBB, Plan);
8849       if (NextVPBB != VPBB) {
8850         VPBB = NextVPBB;
8851         VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
8852                                     : "");
8853       }
8854     }
8855 
8856     VPBlockUtils::insertBlockAfter(new VPBasicBlock(), VPBB);
8857     VPBB = cast<VPBasicBlock>(VPBB->getSingleSuccessor());
8858   }
8859 
8860   HeaderVPBB->setName("vector.body");
8861 
8862   // Fold the last, empty block into its predecessor.
8863   VPBB = VPBlockUtils::tryToMergeBlockIntoPredecessor(VPBB);
8864   assert(VPBB && "expected to fold last (empty) block");
8865   // After here, VPBB should not be used.
8866   VPBB = nullptr;
8867 
8868   addUsersInExitBlock(HeaderVPBB, MiddleVPBB, OrigLoop, *Plan);
8869 
8870   assert(isa<VPRegionBlock>(Plan->getVectorLoopRegion()) &&
8871          !Plan->getVectorLoopRegion()->getEntryBasicBlock()->empty() &&
8872          "entry block must be set to a VPRegionBlock having a non-empty entry "
8873          "VPBasicBlock");
8874   RecipeBuilder.fixHeaderPhis();
8875 
8876   // ---------------------------------------------------------------------------
8877   // Transform initial VPlan: Apply previously taken decisions, in order, to
8878   // bring the VPlan to its final state.
8879   // ---------------------------------------------------------------------------
8880 
8881   // Apply Sink-After legal constraints.
8882   auto GetReplicateRegion = [](VPRecipeBase *R) -> VPRegionBlock * {
8883     auto *Region = dyn_cast_or_null<VPRegionBlock>(R->getParent()->getParent());
8884     if (Region && Region->isReplicator()) {
8885       assert(Region->getNumSuccessors() == 1 &&
8886              Region->getNumPredecessors() == 1 && "Expected SESE region!");
8887       assert(R->getParent()->size() == 1 &&
8888              "A recipe in an original replicator region must be the only "
8889              "recipe in its block");
8890       return Region;
8891     }
8892     return nullptr;
8893   };
8894   for (auto &Entry : SinkAfter) {
8895     VPRecipeBase *Sink = RecipeBuilder.getRecipe(Entry.first);
8896     VPRecipeBase *Target = RecipeBuilder.getRecipe(Entry.second);
8897 
8898     auto *TargetRegion = GetReplicateRegion(Target);
8899     auto *SinkRegion = GetReplicateRegion(Sink);
8900     if (!SinkRegion) {
8901       // If the sink source is not a replicate region, sink the recipe directly.
8902       if (TargetRegion) {
8903         // The target is in a replication region, make sure to move Sink to
8904         // the block after it, not into the replication region itself.
8905         VPBasicBlock *NextBlock =
8906             cast<VPBasicBlock>(TargetRegion->getSuccessors().front());
8907         Sink->moveBefore(*NextBlock, NextBlock->getFirstNonPhi());
8908       } else
8909         Sink->moveAfter(Target);
8910       continue;
8911     }
8912 
8913     // The sink source is in a replicate region. Unhook the region from the CFG.
8914     auto *SinkPred = SinkRegion->getSinglePredecessor();
8915     auto *SinkSucc = SinkRegion->getSingleSuccessor();
8916     VPBlockUtils::disconnectBlocks(SinkPred, SinkRegion);
8917     VPBlockUtils::disconnectBlocks(SinkRegion, SinkSucc);
8918     VPBlockUtils::connectBlocks(SinkPred, SinkSucc);
8919 
8920     if (TargetRegion) {
8921       // The target recipe is also in a replicate region, move the sink region
8922       // after the target region.
8923       auto *TargetSucc = TargetRegion->getSingleSuccessor();
8924       VPBlockUtils::disconnectBlocks(TargetRegion, TargetSucc);
8925       VPBlockUtils::connectBlocks(TargetRegion, SinkRegion);
8926       VPBlockUtils::connectBlocks(SinkRegion, TargetSucc);
8927     } else {
8928       // The sink source is in a replicate region, we need to move the whole
8929       // replicate region, which should only contain a single recipe in the
8930       // main block.
8931       auto *SplitBlock =
8932           Target->getParent()->splitAt(std::next(Target->getIterator()));
8933 
8934       auto *SplitPred = SplitBlock->getSinglePredecessor();
8935 
8936       VPBlockUtils::disconnectBlocks(SplitPred, SplitBlock);
8937       VPBlockUtils::connectBlocks(SplitPred, SinkRegion);
8938       VPBlockUtils::connectBlocks(SinkRegion, SplitBlock);
8939     }
8940   }
8941 
8942   VPlanTransforms::removeRedundantCanonicalIVs(*Plan);
8943   VPlanTransforms::removeRedundantInductionCasts(*Plan);
8944 
8945   // Now that sink-after is done, move induction recipes for optimized truncates
8946   // to the phi section of the header block.
8947   for (VPWidenIntOrFpInductionRecipe *Ind : InductionsToMove)
8948     Ind->moveBefore(*HeaderVPBB, HeaderVPBB->getFirstNonPhi());
8949 
8950   // Adjust the recipes for any inloop reductions.
8951   adjustRecipesForReductions(cast<VPBasicBlock>(TopRegion->getExiting()), Plan,
8952                              RecipeBuilder, Range.Start);
8953 
8954   // Introduce a recipe to combine the incoming and previous values of a
8955   // first-order recurrence.
8956   for (VPRecipeBase &R :
8957        Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
8958     auto *RecurPhi = dyn_cast<VPFirstOrderRecurrencePHIRecipe>(&R);
8959     if (!RecurPhi)
8960       continue;
8961 
8962     VPRecipeBase *PrevRecipe = RecurPhi->getBackedgeRecipe();
8963     VPBasicBlock *InsertBlock = PrevRecipe->getParent();
8964     auto *Region = GetReplicateRegion(PrevRecipe);
8965     if (Region)
8966       InsertBlock = dyn_cast<VPBasicBlock>(Region->getSingleSuccessor());
8967     if (!InsertBlock) {
8968       InsertBlock = new VPBasicBlock(Region->getName() + ".succ");
8969       VPBlockUtils::insertBlockAfter(InsertBlock, Region);
8970     }
8971     if (Region || PrevRecipe->isPhi())
8972       Builder.setInsertPoint(InsertBlock, InsertBlock->getFirstNonPhi());
8973     else
8974       Builder.setInsertPoint(InsertBlock, std::next(PrevRecipe->getIterator()));
8975 
8976     auto *RecurSplice = cast<VPInstruction>(
8977         Builder.createNaryOp(VPInstruction::FirstOrderRecurrenceSplice,
8978                              {RecurPhi, RecurPhi->getBackedgeValue()}));
8979 
8980     RecurPhi->replaceAllUsesWith(RecurSplice);
8981     // Set the first operand of RecurSplice to RecurPhi again, after replacing
8982     // all users.
8983     RecurSplice->setOperand(0, RecurPhi);
8984   }
8985 
8986   // Interleave memory: for each Interleave Group we marked earlier as relevant
8987   // for this VPlan, replace the Recipes widening its memory instructions with a
8988   // single VPInterleaveRecipe at its insertion point.
8989   for (auto IG : InterleaveGroups) {
8990     auto *Recipe = cast<VPWidenMemoryInstructionRecipe>(
8991         RecipeBuilder.getRecipe(IG->getInsertPos()));
8992     SmallVector<VPValue *, 4> StoredValues;
8993     for (unsigned i = 0; i < IG->getFactor(); ++i)
8994       if (auto *SI = dyn_cast_or_null<StoreInst>(IG->getMember(i))) {
8995         auto *StoreR =
8996             cast<VPWidenMemoryInstructionRecipe>(RecipeBuilder.getRecipe(SI));
8997         StoredValues.push_back(StoreR->getStoredValue());
8998       }
8999 
9000     auto *VPIG = new VPInterleaveRecipe(IG, Recipe->getAddr(), StoredValues,
9001                                         Recipe->getMask());
9002     VPIG->insertBefore(Recipe);
9003     unsigned J = 0;
9004     for (unsigned i = 0; i < IG->getFactor(); ++i)
9005       if (Instruction *Member = IG->getMember(i)) {
9006         if (!Member->getType()->isVoidTy()) {
9007           VPValue *OriginalV = Plan->getVPValue(Member);
9008           Plan->removeVPValueFor(Member);
9009           Plan->addVPValue(Member, VPIG->getVPValue(J));
9010           OriginalV->replaceAllUsesWith(VPIG->getVPValue(J));
9011           J++;
9012         }
9013         RecipeBuilder.getRecipe(Member)->eraseFromParent();
9014       }
9015   }
9016 
9017   std::string PlanName;
9018   raw_string_ostream RSO(PlanName);
9019   ElementCount VF = Range.Start;
9020   Plan->addVF(VF);
9021   RSO << "Initial VPlan for VF={" << VF;
9022   for (VF *= 2; ElementCount::isKnownLT(VF, Range.End); VF *= 2) {
9023     Plan->addVF(VF);
9024     RSO << "," << VF;
9025   }
9026   RSO << "},UF>=1";
9027   RSO.flush();
9028   Plan->setName(PlanName);
9029 
9030   // From this point onwards, VPlan-to-VPlan transformations may change the plan
9031   // in ways that accessing values using original IR values is incorrect.
9032   Plan->disableValue2VPValue();
9033 
9034   VPlanTransforms::optimizeInductions(*Plan, *PSE.getSE());
9035   VPlanTransforms::sinkScalarOperands(*Plan);
9036   VPlanTransforms::mergeReplicateRegions(*Plan);
9037   VPlanTransforms::removeDeadRecipes(*Plan);
9038   VPlanTransforms::removeRedundantExpandSCEVRecipes(*Plan);
9039 
9040   // Fold Exit block into its predecessor if possible.
9041   // TODO: Fold block earlier once all VPlan transforms properly maintain a
9042   // VPBasicBlock as exit.
9043   VPBlockUtils::tryToMergeBlockIntoPredecessor(TopRegion->getExiting());
9044 
9045   assert(VPlanVerifier::verifyPlanIsValid(*Plan) && "VPlan is invalid");
9046   return Plan;
9047 }
9048 
9049 VPlanPtr LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
9050   // Outer loop handling: They may require CFG and instruction level
9051   // transformations before even evaluating whether vectorization is profitable.
9052   // Since we cannot modify the incoming IR, we need to build VPlan upfront in
9053   // the vectorization pipeline.
9054   assert(!OrigLoop->isInnermost());
9055   assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
9056 
9057   // Create new empty VPlan
9058   auto Plan = std::make_unique<VPlan>();
9059 
9060   // Build hierarchical CFG
9061   VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
9062   HCFGBuilder.buildHierarchicalCFG();
9063 
9064   for (ElementCount VF = Range.Start; ElementCount::isKnownLT(VF, Range.End);
9065        VF *= 2)
9066     Plan->addVF(VF);
9067 
9068   SmallPtrSet<Instruction *, 1> DeadInstructions;
9069   VPlanTransforms::VPInstructionsToVPRecipes(
9070       OrigLoop, Plan,
9071       [this](PHINode *P) { return Legal->getIntOrFpInductionDescriptor(P); },
9072       DeadInstructions, *PSE.getSE());
9073 
9074   // Remove the existing terminator of the exiting block of the top-most region.
9075   // A BranchOnCount will be added instead when adding the canonical IV recipes.
9076   auto *Term =
9077       Plan->getVectorLoopRegion()->getExitingBasicBlock()->getTerminator();
9078   Term->eraseFromParent();
9079 
9080   addCanonicalIVRecipes(*Plan, Legal->getWidestInductionType(), DebugLoc(),
9081                         true);
9082   return Plan;
9083 }
9084 
9085 // Adjust the recipes for reductions. For in-loop reductions the chain of
9086 // instructions leading from the loop exit instr to the phi need to be converted
9087 // to reductions, with one operand being vector and the other being the scalar
9088 // reduction chain. For other reductions, a select is introduced between the phi
9089 // and live-out recipes when folding the tail.
9090 void LoopVectorizationPlanner::adjustRecipesForReductions(
9091     VPBasicBlock *LatchVPBB, VPlanPtr &Plan, VPRecipeBuilder &RecipeBuilder,
9092     ElementCount MinVF) {
9093   for (auto &Reduction : CM.getInLoopReductionChains()) {
9094     PHINode *Phi = Reduction.first;
9095     const RecurrenceDescriptor &RdxDesc =
9096         Legal->getReductionVars().find(Phi)->second;
9097     const SmallVector<Instruction *, 4> &ReductionOperations = Reduction.second;
9098 
9099     if (MinVF.isScalar() && !CM.useOrderedReductions(RdxDesc))
9100       continue;
9101 
9102     // ReductionOperations are orders top-down from the phi's use to the
9103     // LoopExitValue. We keep a track of the previous item (the Chain) to tell
9104     // which of the two operands will remain scalar and which will be reduced.
9105     // For minmax the chain will be the select instructions.
9106     Instruction *Chain = Phi;
9107     for (Instruction *R : ReductionOperations) {
9108       VPRecipeBase *WidenRecipe = RecipeBuilder.getRecipe(R);
9109       RecurKind Kind = RdxDesc.getRecurrenceKind();
9110 
9111       VPValue *ChainOp = Plan->getVPValue(Chain);
9112       unsigned FirstOpId;
9113       assert(!RecurrenceDescriptor::isSelectCmpRecurrenceKind(Kind) &&
9114              "Only min/max recurrences allowed for inloop reductions");
9115       // Recognize a call to the llvm.fmuladd intrinsic.
9116       bool IsFMulAdd = (Kind == RecurKind::FMulAdd);
9117       assert((!IsFMulAdd || RecurrenceDescriptor::isFMulAddIntrinsic(R)) &&
9118              "Expected instruction to be a call to the llvm.fmuladd intrinsic");
9119       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9120         assert(isa<VPWidenSelectRecipe>(WidenRecipe) &&
9121                "Expected to replace a VPWidenSelectSC");
9122         FirstOpId = 1;
9123       } else {
9124         assert((MinVF.isScalar() || isa<VPWidenRecipe>(WidenRecipe) ||
9125                 (IsFMulAdd && isa<VPWidenCallRecipe>(WidenRecipe))) &&
9126                "Expected to replace a VPWidenSC");
9127         FirstOpId = 0;
9128       }
9129       unsigned VecOpId =
9130           R->getOperand(FirstOpId) == Chain ? FirstOpId + 1 : FirstOpId;
9131       VPValue *VecOp = Plan->getVPValue(R->getOperand(VecOpId));
9132 
9133       auto *CondOp = CM.blockNeedsPredicationForAnyReason(R->getParent())
9134                          ? RecipeBuilder.createBlockInMask(R->getParent(), Plan)
9135                          : nullptr;
9136 
9137       if (IsFMulAdd) {
9138         // If the instruction is a call to the llvm.fmuladd intrinsic then we
9139         // need to create an fmul recipe to use as the vector operand for the
9140         // fadd reduction.
9141         VPInstruction *FMulRecipe = new VPInstruction(
9142             Instruction::FMul, {VecOp, Plan->getVPValue(R->getOperand(1))});
9143         FMulRecipe->setFastMathFlags(R->getFastMathFlags());
9144         WidenRecipe->getParent()->insert(FMulRecipe,
9145                                          WidenRecipe->getIterator());
9146         VecOp = FMulRecipe;
9147       }
9148       VPReductionRecipe *RedRecipe =
9149           new VPReductionRecipe(&RdxDesc, R, ChainOp, VecOp, CondOp, TTI);
9150       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9151       Plan->removeVPValueFor(R);
9152       Plan->addVPValue(R, RedRecipe);
9153       WidenRecipe->getParent()->insert(RedRecipe, WidenRecipe->getIterator());
9154       WidenRecipe->getVPSingleValue()->replaceAllUsesWith(RedRecipe);
9155       WidenRecipe->eraseFromParent();
9156 
9157       if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9158         VPRecipeBase *CompareRecipe =
9159             RecipeBuilder.getRecipe(cast<Instruction>(R->getOperand(0)));
9160         assert(isa<VPWidenRecipe>(CompareRecipe) &&
9161                "Expected to replace a VPWidenSC");
9162         assert(cast<VPWidenRecipe>(CompareRecipe)->getNumUsers() == 0 &&
9163                "Expected no remaining users");
9164         CompareRecipe->eraseFromParent();
9165       }
9166       Chain = R;
9167     }
9168   }
9169 
9170   // If tail is folded by masking, introduce selects between the phi
9171   // and the live-out instruction of each reduction, at the beginning of the
9172   // dedicated latch block.
9173   if (CM.foldTailByMasking()) {
9174     Builder.setInsertPoint(LatchVPBB, LatchVPBB->begin());
9175     for (VPRecipeBase &R :
9176          Plan->getVectorLoopRegion()->getEntryBasicBlock()->phis()) {
9177       VPReductionPHIRecipe *PhiR = dyn_cast<VPReductionPHIRecipe>(&R);
9178       if (!PhiR || PhiR->isInLoop())
9179         continue;
9180       VPValue *Cond =
9181           RecipeBuilder.createBlockInMask(OrigLoop->getHeader(), Plan);
9182       VPValue *Red = PhiR->getBackedgeValue();
9183       assert(cast<VPRecipeBase>(Red->getDef())->getParent() != LatchVPBB &&
9184              "reduction recipe must be defined before latch");
9185       Builder.createNaryOp(Instruction::Select, {Cond, Red, PhiR});
9186     }
9187   }
9188 }
9189 
9190 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
9191 void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent,
9192                                VPSlotTracker &SlotTracker) const {
9193   O << Indent << "INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
9194   IG->getInsertPos()->printAsOperand(O, false);
9195   O << ", ";
9196   getAddr()->printAsOperand(O, SlotTracker);
9197   VPValue *Mask = getMask();
9198   if (Mask) {
9199     O << ", ";
9200     Mask->printAsOperand(O, SlotTracker);
9201   }
9202 
9203   unsigned OpIdx = 0;
9204   for (unsigned i = 0; i < IG->getFactor(); ++i) {
9205     if (!IG->getMember(i))
9206       continue;
9207     if (getNumStoreOperands() > 0) {
9208       O << "\n" << Indent << "  store ";
9209       getOperand(1 + OpIdx)->printAsOperand(O, SlotTracker);
9210       O << " to index " << i;
9211     } else {
9212       O << "\n" << Indent << "  ";
9213       getVPValue(OpIdx)->printAsOperand(O, SlotTracker);
9214       O << " = load from index " << i;
9215     }
9216     ++OpIdx;
9217   }
9218 }
9219 #endif
9220 
9221 void VPWidenCallRecipe::execute(VPTransformState &State) {
9222   State.ILV->widenCallInstruction(*cast<CallInst>(getUnderlyingInstr()), this,
9223                                   *this, State);
9224 }
9225 
9226 void VPWidenSelectRecipe::execute(VPTransformState &State) {
9227   auto &I = *cast<SelectInst>(getUnderlyingInstr());
9228   State.ILV->setDebugLocFromInst(&I);
9229 
9230   // The condition can be loop invariant  but still defined inside the
9231   // loop. This means that we can't just use the original 'cond' value.
9232   // We have to take the 'vectorized' value and pick the first lane.
9233   // Instcombine will make this a no-op.
9234   auto *InvarCond =
9235       InvariantCond ? State.get(getOperand(0), VPIteration(0, 0)) : nullptr;
9236 
9237   for (unsigned Part = 0; Part < State.UF; ++Part) {
9238     Value *Cond = InvarCond ? InvarCond : State.get(getOperand(0), Part);
9239     Value *Op0 = State.get(getOperand(1), Part);
9240     Value *Op1 = State.get(getOperand(2), Part);
9241     Value *Sel = State.Builder.CreateSelect(Cond, Op0, Op1);
9242     State.set(this, Sel, Part);
9243     State.ILV->addMetadata(Sel, &I);
9244   }
9245 }
9246 
9247 void VPWidenRecipe::execute(VPTransformState &State) {
9248   auto &I = *cast<Instruction>(getUnderlyingValue());
9249   auto &Builder = State.Builder;
9250   switch (I.getOpcode()) {
9251   case Instruction::Call:
9252   case Instruction::Br:
9253   case Instruction::PHI:
9254   case Instruction::GetElementPtr:
9255   case Instruction::Select:
9256     llvm_unreachable("This instruction is handled by a different recipe.");
9257   case Instruction::UDiv:
9258   case Instruction::SDiv:
9259   case Instruction::SRem:
9260   case Instruction::URem:
9261   case Instruction::Add:
9262   case Instruction::FAdd:
9263   case Instruction::Sub:
9264   case Instruction::FSub:
9265   case Instruction::FNeg:
9266   case Instruction::Mul:
9267   case Instruction::FMul:
9268   case Instruction::FDiv:
9269   case Instruction::FRem:
9270   case Instruction::Shl:
9271   case Instruction::LShr:
9272   case Instruction::AShr:
9273   case Instruction::And:
9274   case Instruction::Or:
9275   case Instruction::Xor: {
9276     // Just widen unops and binops.
9277     State.ILV->setDebugLocFromInst(&I);
9278 
9279     for (unsigned Part = 0; Part < State.UF; ++Part) {
9280       SmallVector<Value *, 2> Ops;
9281       for (VPValue *VPOp : operands())
9282         Ops.push_back(State.get(VPOp, Part));
9283 
9284       Value *V = Builder.CreateNAryOp(I.getOpcode(), Ops);
9285 
9286       if (auto *VecOp = dyn_cast<Instruction>(V)) {
9287         VecOp->copyIRFlags(&I);
9288 
9289         // If the instruction is vectorized and was in a basic block that needed
9290         // predication, we can't propagate poison-generating flags (nuw/nsw,
9291         // exact, etc.). The control flow has been linearized and the
9292         // instruction is no longer guarded by the predicate, which could make
9293         // the flag properties to no longer hold.
9294         if (State.MayGeneratePoisonRecipes.contains(this))
9295           VecOp->dropPoisonGeneratingFlags();
9296       }
9297 
9298       // Use this vector value for all users of the original instruction.
9299       State.set(this, V, Part);
9300       State.ILV->addMetadata(V, &I);
9301     }
9302 
9303     break;
9304   }
9305   case Instruction::Freeze: {
9306     State.ILV->setDebugLocFromInst(&I);
9307 
9308     for (unsigned Part = 0; Part < State.UF; ++Part) {
9309       Value *Op = State.get(getOperand(0), Part);
9310 
9311       Value *Freeze = Builder.CreateFreeze(Op);
9312       State.set(this, Freeze, Part);
9313     }
9314     break;
9315   }
9316   case Instruction::ICmp:
9317   case Instruction::FCmp: {
9318     // Widen compares. Generate vector compares.
9319     bool FCmp = (I.getOpcode() == Instruction::FCmp);
9320     auto *Cmp = cast<CmpInst>(&I);
9321     State.ILV->setDebugLocFromInst(Cmp);
9322     for (unsigned Part = 0; Part < State.UF; ++Part) {
9323       Value *A = State.get(getOperand(0), Part);
9324       Value *B = State.get(getOperand(1), Part);
9325       Value *C = nullptr;
9326       if (FCmp) {
9327         // Propagate fast math flags.
9328         IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9329         Builder.setFastMathFlags(Cmp->getFastMathFlags());
9330         C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
9331       } else {
9332         C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
9333       }
9334       State.set(this, C, Part);
9335       State.ILV->addMetadata(C, &I);
9336     }
9337 
9338     break;
9339   }
9340 
9341   case Instruction::ZExt:
9342   case Instruction::SExt:
9343   case Instruction::FPToUI:
9344   case Instruction::FPToSI:
9345   case Instruction::FPExt:
9346   case Instruction::PtrToInt:
9347   case Instruction::IntToPtr:
9348   case Instruction::SIToFP:
9349   case Instruction::UIToFP:
9350   case Instruction::Trunc:
9351   case Instruction::FPTrunc:
9352   case Instruction::BitCast: {
9353     auto *CI = cast<CastInst>(&I);
9354     State.ILV->setDebugLocFromInst(CI);
9355 
9356     /// Vectorize casts.
9357     Type *DestTy = (State.VF.isScalar())
9358                        ? CI->getType()
9359                        : VectorType::get(CI->getType(), State.VF);
9360 
9361     for (unsigned Part = 0; Part < State.UF; ++Part) {
9362       Value *A = State.get(getOperand(0), Part);
9363       Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
9364       State.set(this, Cast, Part);
9365       State.ILV->addMetadata(Cast, &I);
9366     }
9367     break;
9368   }
9369   default:
9370     // This instruction is not vectorized by simple widening.
9371     LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
9372     llvm_unreachable("Unhandled instruction!");
9373   } // end of switch.
9374 }
9375 
9376 void VPWidenGEPRecipe::execute(VPTransformState &State) {
9377   auto *GEP = cast<GetElementPtrInst>(getUnderlyingInstr());
9378   // Construct a vector GEP by widening the operands of the scalar GEP as
9379   // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
9380   // results in a vector of pointers when at least one operand of the GEP
9381   // is vector-typed. Thus, to keep the representation compact, we only use
9382   // vector-typed operands for loop-varying values.
9383 
9384   if (State.VF.isVector() && IsPtrLoopInvariant && IsIndexLoopInvariant.all()) {
9385     // If we are vectorizing, but the GEP has only loop-invariant operands,
9386     // the GEP we build (by only using vector-typed operands for
9387     // loop-varying values) would be a scalar pointer. Thus, to ensure we
9388     // produce a vector of pointers, we need to either arbitrarily pick an
9389     // operand to broadcast, or broadcast a clone of the original GEP.
9390     // Here, we broadcast a clone of the original.
9391     //
9392     // TODO: If at some point we decide to scalarize instructions having
9393     //       loop-invariant operands, this special case will no longer be
9394     //       required. We would add the scalarization decision to
9395     //       collectLoopScalars() and teach getVectorValue() to broadcast
9396     //       the lane-zero scalar value.
9397     auto *Clone = State.Builder.Insert(GEP->clone());
9398     for (unsigned Part = 0; Part < State.UF; ++Part) {
9399       Value *EntryPart = State.Builder.CreateVectorSplat(State.VF, Clone);
9400       State.set(this, EntryPart, Part);
9401       State.ILV->addMetadata(EntryPart, GEP);
9402     }
9403   } else {
9404     // If the GEP has at least one loop-varying operand, we are sure to
9405     // produce a vector of pointers. But if we are only unrolling, we want
9406     // to produce a scalar GEP for each unroll part. Thus, the GEP we
9407     // produce with the code below will be scalar (if VF == 1) or vector
9408     // (otherwise). Note that for the unroll-only case, we still maintain
9409     // values in the vector mapping with initVector, as we do for other
9410     // instructions.
9411     for (unsigned Part = 0; Part < State.UF; ++Part) {
9412       // The pointer operand of the new GEP. If it's loop-invariant, we
9413       // won't broadcast it.
9414       auto *Ptr = IsPtrLoopInvariant
9415                       ? State.get(getOperand(0), VPIteration(0, 0))
9416                       : State.get(getOperand(0), Part);
9417 
9418       // Collect all the indices for the new GEP. If any index is
9419       // loop-invariant, we won't broadcast it.
9420       SmallVector<Value *, 4> Indices;
9421       for (unsigned I = 1, E = getNumOperands(); I < E; I++) {
9422         VPValue *Operand = getOperand(I);
9423         if (IsIndexLoopInvariant[I - 1])
9424           Indices.push_back(State.get(Operand, VPIteration(0, 0)));
9425         else
9426           Indices.push_back(State.get(Operand, Part));
9427       }
9428 
9429       // If the GEP instruction is vectorized and was in a basic block that
9430       // needed predication, we can't propagate the poison-generating 'inbounds'
9431       // flag. The control flow has been linearized and the GEP is no longer
9432       // guarded by the predicate, which could make the 'inbounds' properties to
9433       // no longer hold.
9434       bool IsInBounds =
9435           GEP->isInBounds() && State.MayGeneratePoisonRecipes.count(this) == 0;
9436 
9437       // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
9438       // but it should be a vector, otherwise.
9439       auto *NewGEP = State.Builder.CreateGEP(GEP->getSourceElementType(), Ptr,
9440                                              Indices, "", IsInBounds);
9441       assert((State.VF.isScalar() || NewGEP->getType()->isVectorTy()) &&
9442              "NewGEP is not a pointer vector");
9443       State.set(this, NewGEP, Part);
9444       State.ILV->addMetadata(NewGEP, GEP);
9445     }
9446   }
9447 }
9448 
9449 void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
9450   assert(!State.Instance && "Int or FP induction being replicated.");
9451 
9452   Value *Start = getStartValue()->getLiveInIRValue();
9453   const InductionDescriptor &ID = getInductionDescriptor();
9454   TruncInst *Trunc = getTruncInst();
9455   IRBuilderBase &Builder = State.Builder;
9456   assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
9457   assert(State.VF.isVector() && "must have vector VF");
9458 
9459   // The value from the original loop to which we are mapping the new induction
9460   // variable.
9461   Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
9462 
9463   // Fast-math-flags propagate from the original induction instruction.
9464   IRBuilder<>::FastMathFlagGuard FMFG(Builder);
9465   if (ID.getInductionBinOp() && isa<FPMathOperator>(ID.getInductionBinOp()))
9466     Builder.setFastMathFlags(ID.getInductionBinOp()->getFastMathFlags());
9467 
9468   // Now do the actual transformations, and start with fetching the step value.
9469   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9470 
9471   assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
9472          "Expected either an induction phi-node or a truncate of it!");
9473 
9474   // Construct the initial value of the vector IV in the vector loop preheader
9475   auto CurrIP = Builder.saveIP();
9476   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9477   Builder.SetInsertPoint(VectorPH->getTerminator());
9478   if (isa<TruncInst>(EntryVal)) {
9479     assert(Start->getType()->isIntegerTy() &&
9480            "Truncation requires an integer type");
9481     auto *TruncType = cast<IntegerType>(EntryVal->getType());
9482     Step = Builder.CreateTrunc(Step, TruncType);
9483     Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
9484   }
9485 
9486   Value *Zero = getSignedIntOrFpConstant(Start->getType(), 0);
9487   Value *SplatStart = Builder.CreateVectorSplat(State.VF, Start);
9488   Value *SteppedStart = getStepVector(
9489       SplatStart, Zero, Step, ID.getInductionOpcode(), State.VF, State.Builder);
9490 
9491   // We create vector phi nodes for both integer and floating-point induction
9492   // variables. Here, we determine the kind of arithmetic we will perform.
9493   Instruction::BinaryOps AddOp;
9494   Instruction::BinaryOps MulOp;
9495   if (Step->getType()->isIntegerTy()) {
9496     AddOp = Instruction::Add;
9497     MulOp = Instruction::Mul;
9498   } else {
9499     AddOp = ID.getInductionOpcode();
9500     MulOp = Instruction::FMul;
9501   }
9502 
9503   // Multiply the vectorization factor by the step using integer or
9504   // floating-point arithmetic as appropriate.
9505   Type *StepType = Step->getType();
9506   Value *RuntimeVF;
9507   if (Step->getType()->isFloatingPointTy())
9508     RuntimeVF = getRuntimeVFAsFloat(Builder, StepType, State.VF);
9509   else
9510     RuntimeVF = getRuntimeVF(Builder, StepType, State.VF);
9511   Value *Mul = Builder.CreateBinOp(MulOp, Step, RuntimeVF);
9512 
9513   // Create a vector splat to use in the induction update.
9514   //
9515   // FIXME: If the step is non-constant, we create the vector splat with
9516   //        IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
9517   //        handle a constant vector splat.
9518   Value *SplatVF = isa<Constant>(Mul)
9519                        ? ConstantVector::getSplat(State.VF, cast<Constant>(Mul))
9520                        : Builder.CreateVectorSplat(State.VF, Mul);
9521   Builder.restoreIP(CurrIP);
9522 
9523   // We may need to add the step a number of times, depending on the unroll
9524   // factor. The last of those goes into the PHI.
9525   PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
9526                                     &*State.CFG.PrevBB->getFirstInsertionPt());
9527   VecInd->setDebugLoc(EntryVal->getDebugLoc());
9528   Instruction *LastInduction = VecInd;
9529   for (unsigned Part = 0; Part < State.UF; ++Part) {
9530     State.set(this, LastInduction, Part);
9531 
9532     if (isa<TruncInst>(EntryVal))
9533       State.ILV->addMetadata(LastInduction, EntryVal);
9534 
9535     LastInduction = cast<Instruction>(
9536         Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add"));
9537     LastInduction->setDebugLoc(EntryVal->getDebugLoc());
9538   }
9539 
9540   LastInduction->setName("vec.ind.next");
9541   VecInd->addIncoming(SteppedStart, VectorPH);
9542   // Add induction update using an incorrect block temporarily. The phi node
9543   // will be fixed after VPlan execution. Note that at this point the latch
9544   // block cannot be used, as it does not exist yet.
9545   // TODO: Model increment value in VPlan, by turning the recipe into a
9546   // multi-def and a subclass of VPHeaderPHIRecipe.
9547   VecInd->addIncoming(LastInduction, VectorPH);
9548 }
9549 
9550 void VPWidenPointerInductionRecipe::execute(VPTransformState &State) {
9551   assert(IndDesc.getKind() == InductionDescriptor::IK_PtrInduction &&
9552          "Not a pointer induction according to InductionDescriptor!");
9553   assert(cast<PHINode>(getUnderlyingInstr())->getType()->isPointerTy() &&
9554          "Unexpected type.");
9555 
9556   auto *IVR = getParent()->getPlan()->getCanonicalIV();
9557   PHINode *CanonicalIV = cast<PHINode>(State.get(IVR, 0));
9558 
9559   if (onlyScalarsGenerated(State.VF)) {
9560     // This is the normalized GEP that starts counting at zero.
9561     Value *PtrInd = State.Builder.CreateSExtOrTrunc(
9562         CanonicalIV, IndDesc.getStep()->getType());
9563     // Determine the number of scalars we need to generate for each unroll
9564     // iteration. If the instruction is uniform, we only need to generate the
9565     // first lane. Otherwise, we generate all VF values.
9566     bool IsUniform = vputils::onlyFirstLaneUsed(this);
9567     assert((IsUniform || !State.VF.isScalable()) &&
9568            "Cannot scalarize a scalable VF");
9569     unsigned Lanes = IsUniform ? 1 : State.VF.getFixedValue();
9570 
9571     for (unsigned Part = 0; Part < State.UF; ++Part) {
9572       Value *PartStart =
9573           createStepForVF(State.Builder, PtrInd->getType(), State.VF, Part);
9574 
9575       for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
9576         Value *Idx = State.Builder.CreateAdd(
9577             PartStart, ConstantInt::get(PtrInd->getType(), Lane));
9578         Value *GlobalIdx = State.Builder.CreateAdd(PtrInd, Idx);
9579 
9580         Value *Step = CreateStepValue(IndDesc.getStep(), SE,
9581                                       State.CFG.PrevBB->getTerminator());
9582         Value *SclrGep = emitTransformedIndex(
9583             State.Builder, GlobalIdx, IndDesc.getStartValue(), Step, IndDesc);
9584         SclrGep->setName("next.gep");
9585         State.set(this, SclrGep, VPIteration(Part, Lane));
9586       }
9587     }
9588     return;
9589   }
9590 
9591   assert(isa<SCEVConstant>(IndDesc.getStep()) &&
9592          "Induction step not a SCEV constant!");
9593   Type *PhiType = IndDesc.getStep()->getType();
9594 
9595   // Build a pointer phi
9596   Value *ScalarStartValue = getStartValue()->getLiveInIRValue();
9597   Type *ScStValueType = ScalarStartValue->getType();
9598   PHINode *NewPointerPhi =
9599       PHINode::Create(ScStValueType, 2, "pointer.phi", CanonicalIV);
9600 
9601   BasicBlock *VectorPH = State.CFG.getPreheaderBBFor(this);
9602   NewPointerPhi->addIncoming(ScalarStartValue, VectorPH);
9603 
9604   // A pointer induction, performed by using a gep
9605   const DataLayout &DL = NewPointerPhi->getModule()->getDataLayout();
9606   Instruction *InductionLoc = &*State.Builder.GetInsertPoint();
9607 
9608   const SCEV *ScalarStep = IndDesc.getStep();
9609   SCEVExpander Exp(SE, DL, "induction");
9610   Value *ScalarStepValue = Exp.expandCodeFor(ScalarStep, PhiType, InductionLoc);
9611   Value *RuntimeVF = getRuntimeVF(State.Builder, PhiType, State.VF);
9612   Value *NumUnrolledElems =
9613       State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, State.UF));
9614   Value *InductionGEP = GetElementPtrInst::Create(
9615       IndDesc.getElementType(), NewPointerPhi,
9616       State.Builder.CreateMul(ScalarStepValue, NumUnrolledElems), "ptr.ind",
9617       InductionLoc);
9618   // Add induction update using an incorrect block temporarily. The phi node
9619   // will be fixed after VPlan execution. Note that at this point the latch
9620   // block cannot be used, as it does not exist yet.
9621   // TODO: Model increment value in VPlan, by turning the recipe into a
9622   // multi-def and a subclass of VPHeaderPHIRecipe.
9623   NewPointerPhi->addIncoming(InductionGEP, VectorPH);
9624 
9625   // Create UF many actual address geps that use the pointer
9626   // phi as base and a vectorized version of the step value
9627   // (<step*0, ..., step*N>) as offset.
9628   for (unsigned Part = 0; Part < State.UF; ++Part) {
9629     Type *VecPhiType = VectorType::get(PhiType, State.VF);
9630     Value *StartOffsetScalar =
9631         State.Builder.CreateMul(RuntimeVF, ConstantInt::get(PhiType, Part));
9632     Value *StartOffset =
9633         State.Builder.CreateVectorSplat(State.VF, StartOffsetScalar);
9634     // Create a vector of consecutive numbers from zero to VF.
9635     StartOffset = State.Builder.CreateAdd(
9636         StartOffset, State.Builder.CreateStepVector(VecPhiType));
9637 
9638     Value *GEP = State.Builder.CreateGEP(
9639         IndDesc.getElementType(), NewPointerPhi,
9640         State.Builder.CreateMul(
9641             StartOffset,
9642             State.Builder.CreateVectorSplat(State.VF, ScalarStepValue),
9643             "vector.gep"));
9644     State.set(this, GEP, Part);
9645   }
9646 }
9647 
9648 void VPScalarIVStepsRecipe::execute(VPTransformState &State) {
9649   assert(!State.Instance && "VPScalarIVStepsRecipe being replicated.");
9650 
9651   // Fast-math-flags propagate from the original induction instruction.
9652   IRBuilder<>::FastMathFlagGuard FMFG(State.Builder);
9653   if (IndDesc.getInductionBinOp() &&
9654       isa<FPMathOperator>(IndDesc.getInductionBinOp()))
9655     State.Builder.setFastMathFlags(
9656         IndDesc.getInductionBinOp()->getFastMathFlags());
9657 
9658   Value *Step = State.get(getStepValue(), VPIteration(0, 0));
9659   auto CreateScalarIV = [&](Value *&Step) -> Value * {
9660     Value *ScalarIV = State.get(getCanonicalIV(), VPIteration(0, 0));
9661     auto *CanonicalIV = State.get(getParent()->getPlan()->getCanonicalIV(), 0);
9662     if (!isCanonical() || CanonicalIV->getType() != Ty) {
9663       ScalarIV =
9664           Ty->isIntegerTy()
9665               ? State.Builder.CreateSExtOrTrunc(ScalarIV, Ty)
9666               : State.Builder.CreateCast(Instruction::SIToFP, ScalarIV, Ty);
9667       ScalarIV = emitTransformedIndex(State.Builder, ScalarIV,
9668                                       getStartValue()->getLiveInIRValue(), Step,
9669                                       IndDesc);
9670       ScalarIV->setName("offset.idx");
9671     }
9672     if (TruncToTy) {
9673       assert(Step->getType()->isIntegerTy() &&
9674              "Truncation requires an integer step");
9675       ScalarIV = State.Builder.CreateTrunc(ScalarIV, TruncToTy);
9676       Step = State.Builder.CreateTrunc(Step, TruncToTy);
9677     }
9678     return ScalarIV;
9679   };
9680 
9681   Value *ScalarIV = CreateScalarIV(Step);
9682   if (State.VF.isVector()) {
9683     buildScalarSteps(ScalarIV, Step, IndDesc, this, State);
9684     return;
9685   }
9686 
9687   for (unsigned Part = 0; Part < State.UF; ++Part) {
9688     assert(!State.VF.isScalable() && "scalable vectors not yet supported.");
9689     Value *EntryPart;
9690     if (Step->getType()->isFloatingPointTy()) {
9691       Value *StartIdx =
9692           getRuntimeVFAsFloat(State.Builder, Step->getType(), State.VF * Part);
9693       // Floating-point operations inherit FMF via the builder's flags.
9694       Value *MulOp = State.Builder.CreateFMul(StartIdx, Step);
9695       EntryPart = State.Builder.CreateBinOp(IndDesc.getInductionOpcode(),
9696                                             ScalarIV, MulOp);
9697     } else {
9698       Value *StartIdx =
9699           getRuntimeVF(State.Builder, Step->getType(), State.VF * Part);
9700       EntryPart = State.Builder.CreateAdd(
9701           ScalarIV, State.Builder.CreateMul(StartIdx, Step), "induction");
9702     }
9703     State.set(this, EntryPart, Part);
9704   }
9705 }
9706 
9707 void VPBlendRecipe::execute(VPTransformState &State) {
9708   State.ILV->setDebugLocFromInst(Phi);
9709   // We know that all PHIs in non-header blocks are converted into
9710   // selects, so we don't have to worry about the insertion order and we
9711   // can just use the builder.
9712   // At this point we generate the predication tree. There may be
9713   // duplications since this is a simple recursive scan, but future
9714   // optimizations will clean it up.
9715 
9716   unsigned NumIncoming = getNumIncomingValues();
9717 
9718   // Generate a sequence of selects of the form:
9719   // SELECT(Mask3, In3,
9720   //        SELECT(Mask2, In2,
9721   //               SELECT(Mask1, In1,
9722   //                      In0)))
9723   // Note that Mask0 is never used: lanes for which no path reaches this phi and
9724   // are essentially undef are taken from In0.
9725   InnerLoopVectorizer::VectorParts Entry(State.UF);
9726   for (unsigned In = 0; In < NumIncoming; ++In) {
9727     for (unsigned Part = 0; Part < State.UF; ++Part) {
9728       // We might have single edge PHIs (blocks) - use an identity
9729       // 'select' for the first PHI operand.
9730       Value *In0 = State.get(getIncomingValue(In), Part);
9731       if (In == 0)
9732         Entry[Part] = In0; // Initialize with the first incoming value.
9733       else {
9734         // Select between the current value and the previous incoming edge
9735         // based on the incoming mask.
9736         Value *Cond = State.get(getMask(In), Part);
9737         Entry[Part] =
9738             State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
9739       }
9740     }
9741   }
9742   for (unsigned Part = 0; Part < State.UF; ++Part)
9743     State.set(this, Entry[Part], Part);
9744 }
9745 
9746 void VPInterleaveRecipe::execute(VPTransformState &State) {
9747   assert(!State.Instance && "Interleave group being replicated.");
9748   State.ILV->vectorizeInterleaveGroup(IG, definedValues(), State, getAddr(),
9749                                       getStoredValues(), getMask());
9750 }
9751 
9752 void VPReductionRecipe::execute(VPTransformState &State) {
9753   assert(!State.Instance && "Reduction being replicated.");
9754   Value *PrevInChain = State.get(getChainOp(), 0);
9755   RecurKind Kind = RdxDesc->getRecurrenceKind();
9756   bool IsOrdered = State.ILV->useOrderedReductions(*RdxDesc);
9757   // Propagate the fast-math flags carried by the underlying instruction.
9758   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
9759   State.Builder.setFastMathFlags(RdxDesc->getFastMathFlags());
9760   for (unsigned Part = 0; Part < State.UF; ++Part) {
9761     Value *NewVecOp = State.get(getVecOp(), Part);
9762     if (VPValue *Cond = getCondOp()) {
9763       Value *NewCond = State.get(Cond, Part);
9764       VectorType *VecTy = cast<VectorType>(NewVecOp->getType());
9765       Value *Iden = RdxDesc->getRecurrenceIdentity(
9766           Kind, VecTy->getElementType(), RdxDesc->getFastMathFlags());
9767       Value *IdenVec =
9768           State.Builder.CreateVectorSplat(VecTy->getElementCount(), Iden);
9769       Value *Select = State.Builder.CreateSelect(NewCond, NewVecOp, IdenVec);
9770       NewVecOp = Select;
9771     }
9772     Value *NewRed;
9773     Value *NextInChain;
9774     if (IsOrdered) {
9775       if (State.VF.isVector())
9776         NewRed = createOrderedReduction(State.Builder, *RdxDesc, NewVecOp,
9777                                         PrevInChain);
9778       else
9779         NewRed = State.Builder.CreateBinOp(
9780             (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), PrevInChain,
9781             NewVecOp);
9782       PrevInChain = NewRed;
9783     } else {
9784       PrevInChain = State.get(getChainOp(), Part);
9785       NewRed = createTargetReduction(State.Builder, TTI, *RdxDesc, NewVecOp);
9786     }
9787     if (RecurrenceDescriptor::isMinMaxRecurrenceKind(Kind)) {
9788       NextInChain =
9789           createMinMaxOp(State.Builder, RdxDesc->getRecurrenceKind(),
9790                          NewRed, PrevInChain);
9791     } else if (IsOrdered)
9792       NextInChain = NewRed;
9793     else
9794       NextInChain = State.Builder.CreateBinOp(
9795           (Instruction::BinaryOps)RdxDesc->getOpcode(Kind), NewRed,
9796           PrevInChain);
9797     State.set(this, NextInChain, Part);
9798   }
9799 }
9800 
9801 void VPReplicateRecipe::execute(VPTransformState &State) {
9802   if (State.Instance) { // Generate a single instance.
9803     assert(!State.VF.isScalable() && "Can't scalarize a scalable vector");
9804     State.ILV->scalarizeInstruction(getUnderlyingInstr(), this, *State.Instance,
9805                                     IsPredicated, State);
9806     // Insert scalar instance packing it into a vector.
9807     if (AlsoPack && State.VF.isVector()) {
9808       // If we're constructing lane 0, initialize to start from poison.
9809       if (State.Instance->Lane.isFirstLane()) {
9810         assert(!State.VF.isScalable() && "VF is assumed to be non scalable.");
9811         Value *Poison = PoisonValue::get(
9812             VectorType::get(getUnderlyingValue()->getType(), State.VF));
9813         State.set(this, Poison, State.Instance->Part);
9814       }
9815       State.ILV->packScalarIntoVectorValue(this, *State.Instance, State);
9816     }
9817     return;
9818   }
9819 
9820   // Generate scalar instances for all VF lanes of all UF parts, unless the
9821   // instruction is uniform inwhich case generate only the first lane for each
9822   // of the UF parts.
9823   unsigned EndLane = IsUniform ? 1 : State.VF.getKnownMinValue();
9824   assert((!State.VF.isScalable() || IsUniform) &&
9825          "Can't scalarize a scalable vector");
9826   for (unsigned Part = 0; Part < State.UF; ++Part)
9827     for (unsigned Lane = 0; Lane < EndLane; ++Lane)
9828       State.ILV->scalarizeInstruction(getUnderlyingInstr(), this,
9829                                       VPIteration(Part, Lane), IsPredicated,
9830                                       State);
9831 }
9832 
9833 void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
9834   assert(State.Instance && "Branch on Mask works only on single instance.");
9835 
9836   unsigned Part = State.Instance->Part;
9837   unsigned Lane = State.Instance->Lane.getKnownLane();
9838 
9839   Value *ConditionBit = nullptr;
9840   VPValue *BlockInMask = getMask();
9841   if (BlockInMask) {
9842     ConditionBit = State.get(BlockInMask, Part);
9843     if (ConditionBit->getType()->isVectorTy())
9844       ConditionBit = State.Builder.CreateExtractElement(
9845           ConditionBit, State.Builder.getInt32(Lane));
9846   } else // Block in mask is all-one.
9847     ConditionBit = State.Builder.getTrue();
9848 
9849   // Replace the temporary unreachable terminator with a new conditional branch,
9850   // whose two destinations will be set later when they are created.
9851   auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
9852   assert(isa<UnreachableInst>(CurrentTerminator) &&
9853          "Expected to replace unreachable terminator with conditional branch.");
9854   auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
9855   CondBr->setSuccessor(0, nullptr);
9856   ReplaceInstWithInst(CurrentTerminator, CondBr);
9857 }
9858 
9859 void VPPredInstPHIRecipe::execute(VPTransformState &State) {
9860   assert(State.Instance && "Predicated instruction PHI works per instance.");
9861   Instruction *ScalarPredInst =
9862       cast<Instruction>(State.get(getOperand(0), *State.Instance));
9863   BasicBlock *PredicatedBB = ScalarPredInst->getParent();
9864   BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
9865   assert(PredicatingBB && "Predicated block has no single predecessor.");
9866   assert(isa<VPReplicateRecipe>(getOperand(0)) &&
9867          "operand must be VPReplicateRecipe");
9868 
9869   // By current pack/unpack logic we need to generate only a single phi node: if
9870   // a vector value for the predicated instruction exists at this point it means
9871   // the instruction has vector users only, and a phi for the vector value is
9872   // needed. In this case the recipe of the predicated instruction is marked to
9873   // also do that packing, thereby "hoisting" the insert-element sequence.
9874   // Otherwise, a phi node for the scalar value is needed.
9875   unsigned Part = State.Instance->Part;
9876   if (State.hasVectorValue(getOperand(0), Part)) {
9877     Value *VectorValue = State.get(getOperand(0), Part);
9878     InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
9879     PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
9880     VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
9881     VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
9882     if (State.hasVectorValue(this, Part))
9883       State.reset(this, VPhi, Part);
9884     else
9885       State.set(this, VPhi, Part);
9886     // NOTE: Currently we need to update the value of the operand, so the next
9887     // predicated iteration inserts its generated value in the correct vector.
9888     State.reset(getOperand(0), VPhi, Part);
9889   } else {
9890     Type *PredInstType = getOperand(0)->getUnderlyingValue()->getType();
9891     PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
9892     Phi->addIncoming(PoisonValue::get(ScalarPredInst->getType()),
9893                      PredicatingBB);
9894     Phi->addIncoming(ScalarPredInst, PredicatedBB);
9895     if (State.hasScalarValue(this, *State.Instance))
9896       State.reset(this, Phi, *State.Instance);
9897     else
9898       State.set(this, Phi, *State.Instance);
9899     // NOTE: Currently we need to update the value of the operand, so the next
9900     // predicated iteration inserts its generated value in the correct vector.
9901     State.reset(getOperand(0), Phi, *State.Instance);
9902   }
9903 }
9904 
9905 void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
9906   VPValue *StoredValue = isStore() ? getStoredValue() : nullptr;
9907 
9908   // Attempt to issue a wide load.
9909   LoadInst *LI = dyn_cast<LoadInst>(&Ingredient);
9910   StoreInst *SI = dyn_cast<StoreInst>(&Ingredient);
9911 
9912   assert((LI || SI) && "Invalid Load/Store instruction");
9913   assert((!SI || StoredValue) && "No stored value provided for widened store");
9914   assert((!LI || !StoredValue) && "Stored value provided for widened load");
9915 
9916   Type *ScalarDataTy = getLoadStoreType(&Ingredient);
9917 
9918   auto *DataTy = VectorType::get(ScalarDataTy, State.VF);
9919   const Align Alignment = getLoadStoreAlignment(&Ingredient);
9920   bool CreateGatherScatter = !Consecutive;
9921 
9922   auto &Builder = State.Builder;
9923   InnerLoopVectorizer::VectorParts BlockInMaskParts(State.UF);
9924   bool isMaskRequired = getMask();
9925   if (isMaskRequired)
9926     for (unsigned Part = 0; Part < State.UF; ++Part)
9927       BlockInMaskParts[Part] = State.get(getMask(), Part);
9928 
9929   const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
9930     // Calculate the pointer for the specific unroll-part.
9931     GetElementPtrInst *PartPtr = nullptr;
9932 
9933     bool InBounds = false;
9934     if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
9935       InBounds = gep->isInBounds();
9936     if (Reverse) {
9937       // If the address is consecutive but reversed, then the
9938       // wide store needs to start at the last vector element.
9939       // RunTimeVF =  VScale * VF.getKnownMinValue()
9940       // For fixed-width VScale is 1, then RunTimeVF = VF.getKnownMinValue()
9941       Value *RunTimeVF = getRuntimeVF(Builder, Builder.getInt32Ty(), State.VF);
9942       // NumElt = -Part * RunTimeVF
9943       Value *NumElt = Builder.CreateMul(Builder.getInt32(-Part), RunTimeVF);
9944       // LastLane = 1 - RunTimeVF
9945       Value *LastLane = Builder.CreateSub(Builder.getInt32(1), RunTimeVF);
9946       PartPtr =
9947           cast<GetElementPtrInst>(Builder.CreateGEP(ScalarDataTy, Ptr, NumElt));
9948       PartPtr->setIsInBounds(InBounds);
9949       PartPtr = cast<GetElementPtrInst>(
9950           Builder.CreateGEP(ScalarDataTy, PartPtr, LastLane));
9951       PartPtr->setIsInBounds(InBounds);
9952       if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
9953         BlockInMaskParts[Part] =
9954             Builder.CreateVectorReverse(BlockInMaskParts[Part], "reverse");
9955     } else {
9956       Value *Increment =
9957           createStepForVF(Builder, Builder.getInt32Ty(), State.VF, Part);
9958       PartPtr = cast<GetElementPtrInst>(
9959           Builder.CreateGEP(ScalarDataTy, Ptr, Increment));
9960       PartPtr->setIsInBounds(InBounds);
9961     }
9962 
9963     unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
9964     return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
9965   };
9966 
9967   // Handle Stores:
9968   if (SI) {
9969     State.ILV->setDebugLocFromInst(SI);
9970 
9971     for (unsigned Part = 0; Part < State.UF; ++Part) {
9972       Instruction *NewSI = nullptr;
9973       Value *StoredVal = State.get(StoredValue, Part);
9974       if (CreateGatherScatter) {
9975         Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
9976         Value *VectorGep = State.get(getAddr(), Part);
9977         NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
9978                                             MaskPart);
9979       } else {
9980         if (Reverse) {
9981           // If we store to reverse consecutive memory locations, then we need
9982           // to reverse the order of elements in the stored value.
9983           StoredVal = Builder.CreateVectorReverse(StoredVal, "reverse");
9984           // We don't want to update the value in the map as it might be used in
9985           // another expression. So don't call resetVectorValue(StoredVal).
9986         }
9987         auto *VecPtr =
9988             CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
9989         if (isMaskRequired)
9990           NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
9991                                             BlockInMaskParts[Part]);
9992         else
9993           NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
9994       }
9995       State.ILV->addMetadata(NewSI, SI);
9996     }
9997     return;
9998   }
9999 
10000   // Handle loads.
10001   assert(LI && "Must have a load instruction");
10002   State.ILV->setDebugLocFromInst(LI);
10003   for (unsigned Part = 0; Part < State.UF; ++Part) {
10004     Value *NewLI;
10005     if (CreateGatherScatter) {
10006       Value *MaskPart = isMaskRequired ? BlockInMaskParts[Part] : nullptr;
10007       Value *VectorGep = State.get(getAddr(), Part);
10008       NewLI = Builder.CreateMaskedGather(DataTy, VectorGep, Alignment, MaskPart,
10009                                          nullptr, "wide.masked.gather");
10010       State.ILV->addMetadata(NewLI, LI);
10011     } else {
10012       auto *VecPtr =
10013           CreateVecPtr(Part, State.get(getAddr(), VPIteration(0, 0)));
10014       if (isMaskRequired)
10015         NewLI = Builder.CreateMaskedLoad(
10016             DataTy, VecPtr, Alignment, BlockInMaskParts[Part],
10017             PoisonValue::get(DataTy), "wide.masked.load");
10018       else
10019         NewLI =
10020             Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
10021 
10022       // Add metadata to the load, but setVectorValue to the reverse shuffle.
10023       State.ILV->addMetadata(NewLI, LI);
10024       if (Reverse)
10025         NewLI = Builder.CreateVectorReverse(NewLI, "reverse");
10026     }
10027 
10028     State.set(getVPSingleValue(), NewLI, Part);
10029   }
10030 }
10031 
10032 // Determine how to lower the scalar epilogue, which depends on 1) optimising
10033 // for minimum code-size, 2) predicate compiler options, 3) loop hints forcing
10034 // predication, and 4) a TTI hook that analyses whether the loop is suitable
10035 // for predication.
10036 static ScalarEpilogueLowering getScalarEpilogueLowering(
10037     Function *F, Loop *L, LoopVectorizeHints &Hints, ProfileSummaryInfo *PSI,
10038     BlockFrequencyInfo *BFI, TargetTransformInfo *TTI, TargetLibraryInfo *TLI,
10039     AssumptionCache *AC, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
10040     LoopVectorizationLegality &LVL) {
10041   // 1) OptSize takes precedence over all other options, i.e. if this is set,
10042   // don't look at hints or options, and don't request a scalar epilogue.
10043   // (For PGSO, as shouldOptimizeForSize isn't currently accessible from
10044   // LoopAccessInfo (due to code dependency and not being able to reliably get
10045   // PSI/BFI from a loop analysis under NPM), we cannot suppress the collection
10046   // of strides in LoopAccessInfo::analyzeLoop() and vectorize without
10047   // versioning when the vectorization is forced, unlike hasOptSize. So revert
10048   // back to the old way and vectorize with versioning when forced. See D81345.)
10049   if (F->hasOptSize() || (llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI,
10050                                                       PGSOQueryType::IRPass) &&
10051                           Hints.getForce() != LoopVectorizeHints::FK_Enabled))
10052     return CM_ScalarEpilogueNotAllowedOptSize;
10053 
10054   // 2) If set, obey the directives
10055   if (PreferPredicateOverEpilogue.getNumOccurrences()) {
10056     switch (PreferPredicateOverEpilogue) {
10057     case PreferPredicateTy::ScalarEpilogue:
10058       return CM_ScalarEpilogueAllowed;
10059     case PreferPredicateTy::PredicateElseScalarEpilogue:
10060       return CM_ScalarEpilogueNotNeededUsePredicate;
10061     case PreferPredicateTy::PredicateOrDontVectorize:
10062       return CM_ScalarEpilogueNotAllowedUsePredicate;
10063     };
10064   }
10065 
10066   // 3) If set, obey the hints
10067   switch (Hints.getPredicate()) {
10068   case LoopVectorizeHints::FK_Enabled:
10069     return CM_ScalarEpilogueNotNeededUsePredicate;
10070   case LoopVectorizeHints::FK_Disabled:
10071     return CM_ScalarEpilogueAllowed;
10072   };
10073 
10074   // 4) if the TTI hook indicates this is profitable, request predication.
10075   if (TTI->preferPredicateOverEpilogue(L, LI, *SE, *AC, TLI, DT,
10076                                        LVL.getLAI()))
10077     return CM_ScalarEpilogueNotNeededUsePredicate;
10078 
10079   return CM_ScalarEpilogueAllowed;
10080 }
10081 
10082 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
10083   // If Values have been set for this Def return the one relevant for \p Part.
10084   if (hasVectorValue(Def, Part))
10085     return Data.PerPartOutput[Def][Part];
10086 
10087   if (!hasScalarValue(Def, {Part, 0})) {
10088     Value *IRV = Def->getLiveInIRValue();
10089     Value *B = ILV->getBroadcastInstrs(IRV);
10090     set(Def, B, Part);
10091     return B;
10092   }
10093 
10094   Value *ScalarValue = get(Def, {Part, 0});
10095   // If we aren't vectorizing, we can just copy the scalar map values over
10096   // to the vector map.
10097   if (VF.isScalar()) {
10098     set(Def, ScalarValue, Part);
10099     return ScalarValue;
10100   }
10101 
10102   auto *RepR = dyn_cast<VPReplicateRecipe>(Def);
10103   bool IsUniform = RepR && RepR->isUniform();
10104 
10105   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
10106   // Check if there is a scalar value for the selected lane.
10107   if (!hasScalarValue(Def, {Part, LastLane})) {
10108     // At the moment, VPWidenIntOrFpInductionRecipes can also be uniform.
10109     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDef()) ||
10110             isa<VPScalarIVStepsRecipe>(Def->getDef())) &&
10111            "unexpected recipe found to be invariant");
10112     IsUniform = true;
10113     LastLane = 0;
10114   }
10115 
10116   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
10117   // Set the insert point after the last scalarized instruction or after the
10118   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
10119   // will directly follow the scalar definitions.
10120   auto OldIP = Builder.saveIP();
10121   auto NewIP =
10122       isa<PHINode>(LastInst)
10123           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
10124           : std::next(BasicBlock::iterator(LastInst));
10125   Builder.SetInsertPoint(&*NewIP);
10126 
10127   // However, if we are vectorizing, we need to construct the vector values.
10128   // If the value is known to be uniform after vectorization, we can just
10129   // broadcast the scalar value corresponding to lane zero for each unroll
10130   // iteration. Otherwise, we construct the vector values using
10131   // insertelement instructions. Since the resulting vectors are stored in
10132   // State, we will only generate the insertelements once.
10133   Value *VectorValue = nullptr;
10134   if (IsUniform) {
10135     VectorValue = ILV->getBroadcastInstrs(ScalarValue);
10136     set(Def, VectorValue, Part);
10137   } else {
10138     // Initialize packing with insertelements to start from undef.
10139     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
10140     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
10141     set(Def, Undef, Part);
10142     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
10143       ILV->packScalarIntoVectorValue(Def, {Part, Lane}, *this);
10144     VectorValue = get(Def, Part);
10145   }
10146   Builder.restoreIP(OldIP);
10147   return VectorValue;
10148 }
10149 
10150 // Process the loop in the VPlan-native vectorization path. This path builds
10151 // VPlan upfront in the vectorization pipeline, which allows to apply
10152 // VPlan-to-VPlan transformations from the very beginning without modifying the
10153 // input LLVM IR.
10154 static bool processLoopInVPlanNativePath(
10155     Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
10156     LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
10157     TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
10158     OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
10159     ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints,
10160     LoopVectorizationRequirements &Requirements) {
10161 
10162   if (isa<SCEVCouldNotCompute>(PSE.getBackedgeTakenCount())) {
10163     LLVM_DEBUG(dbgs() << "LV: cannot compute the outer-loop trip count\n");
10164     return false;
10165   }
10166   assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
10167   Function *F = L->getHeader()->getParent();
10168   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
10169 
10170   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10171       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, *LVL);
10172 
10173   LoopVectorizationCostModel CM(SEL, L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
10174                                 &Hints, IAI);
10175   // Use the planner for outer loop vectorization.
10176   // TODO: CM is not used at this point inside the planner. Turn CM into an
10177   // optional argument if we don't need it in the future.
10178   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM, IAI, PSE, Hints,
10179                                Requirements, ORE);
10180 
10181   // Get user vectorization factor.
10182   ElementCount UserVF = Hints.getWidth();
10183 
10184   CM.collectElementTypesForWidening();
10185 
10186   // Plan how to best vectorize, return the best VF and its cost.
10187   const VectorizationFactor VF = LVP.planInVPlanNativePath(UserVF);
10188 
10189   // If we are stress testing VPlan builds, do not attempt to generate vector
10190   // code. Masked vector code generation support will follow soon.
10191   // Also, do not attempt to vectorize if no vector code will be produced.
10192   if (VPlanBuildStressTest || VectorizationFactor::Disabled() == VF)
10193     return false;
10194 
10195   VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10196 
10197   {
10198     GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10199                              F->getParent()->getDataLayout());
10200     InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
10201                            &CM, BFI, PSI, Checks);
10202     LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
10203                       << L->getHeader()->getParent()->getName() << "\"\n");
10204     LVP.executePlan(VF.Width, 1, BestPlan, LB, DT);
10205   }
10206 
10207   // Mark the loop as already vectorized to avoid vectorizing again.
10208   Hints.setAlreadyVectorized();
10209   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10210   return true;
10211 }
10212 
10213 // Emit a remark if there are stores to floats that required a floating point
10214 // extension. If the vectorized loop was generated with floating point there
10215 // will be a performance penalty from the conversion overhead and the change in
10216 // the vector width.
10217 static void checkMixedPrecision(Loop *L, OptimizationRemarkEmitter *ORE) {
10218   SmallVector<Instruction *, 4> Worklist;
10219   for (BasicBlock *BB : L->getBlocks()) {
10220     for (Instruction &Inst : *BB) {
10221       if (auto *S = dyn_cast<StoreInst>(&Inst)) {
10222         if (S->getValueOperand()->getType()->isFloatTy())
10223           Worklist.push_back(S);
10224       }
10225     }
10226   }
10227 
10228   // Traverse the floating point stores upwards searching, for floating point
10229   // conversions.
10230   SmallPtrSet<const Instruction *, 4> Visited;
10231   SmallPtrSet<const Instruction *, 4> EmittedRemark;
10232   while (!Worklist.empty()) {
10233     auto *I = Worklist.pop_back_val();
10234     if (!L->contains(I))
10235       continue;
10236     if (!Visited.insert(I).second)
10237       continue;
10238 
10239     // Emit a remark if the floating point store required a floating
10240     // point conversion.
10241     // TODO: More work could be done to identify the root cause such as a
10242     // constant or a function return type and point the user to it.
10243     if (isa<FPExtInst>(I) && EmittedRemark.insert(I).second)
10244       ORE->emit([&]() {
10245         return OptimizationRemarkAnalysis(LV_NAME, "VectorMixedPrecision",
10246                                           I->getDebugLoc(), L->getHeader())
10247                << "floating point conversion changes vector width. "
10248                << "Mixed floating point precision requires an up/down "
10249                << "cast that will negatively impact performance.";
10250       });
10251 
10252     for (Use &Op : I->operands())
10253       if (auto *OpI = dyn_cast<Instruction>(Op))
10254         Worklist.push_back(OpI);
10255   }
10256 }
10257 
10258 LoopVectorizePass::LoopVectorizePass(LoopVectorizeOptions Opts)
10259     : InterleaveOnlyWhenForced(Opts.InterleaveOnlyWhenForced ||
10260                                !EnableLoopInterleaving),
10261       VectorizeOnlyWhenForced(Opts.VectorizeOnlyWhenForced ||
10262                               !EnableLoopVectorization) {}
10263 
10264 bool LoopVectorizePass::processLoop(Loop *L) {
10265   assert((EnableVPlanNativePath || L->isInnermost()) &&
10266          "VPlan-native path is not enabled. Only process inner loops.");
10267 
10268 #ifndef NDEBUG
10269   const std::string DebugLocStr = getDebugLocString(L);
10270 #endif /* NDEBUG */
10271 
10272   LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in '"
10273                     << L->getHeader()->getParent()->getName() << "' from "
10274                     << DebugLocStr << "\n");
10275 
10276   LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE, TTI);
10277 
10278   LLVM_DEBUG(
10279       dbgs() << "LV: Loop hints:"
10280              << " force="
10281              << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
10282                      ? "disabled"
10283                      : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
10284                             ? "enabled"
10285                             : "?"))
10286              << " width=" << Hints.getWidth()
10287              << " interleave=" << Hints.getInterleave() << "\n");
10288 
10289   // Function containing loop
10290   Function *F = L->getHeader()->getParent();
10291 
10292   // Looking at the diagnostic output is the only way to determine if a loop
10293   // was vectorized (other than looking at the IR or machine code), so it
10294   // is important to generate an optimization remark for each loop. Most of
10295   // these messages are generated as OptimizationRemarkAnalysis. Remarks
10296   // generated as OptimizationRemark and OptimizationRemarkMissed are
10297   // less verbose reporting vectorized loops and unvectorized loops that may
10298   // benefit from vectorization, respectively.
10299 
10300   if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
10301     LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
10302     return false;
10303   }
10304 
10305   PredicatedScalarEvolution PSE(*SE, *L);
10306 
10307   // Check if it is legal to vectorize the loop.
10308   LoopVectorizationRequirements Requirements;
10309   LoopVectorizationLegality LVL(L, PSE, DT, TTI, TLI, AA, F, GetLAA, LI, ORE,
10310                                 &Requirements, &Hints, DB, AC, BFI, PSI);
10311   if (!LVL.canVectorize(EnableVPlanNativePath)) {
10312     LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
10313     Hints.emitRemarkWithHints();
10314     return false;
10315   }
10316 
10317   // Check the function attributes and profiles to find out if this function
10318   // should be optimized for size.
10319   ScalarEpilogueLowering SEL = getScalarEpilogueLowering(
10320       F, L, Hints, PSI, BFI, TTI, TLI, AC, LI, PSE.getSE(), DT, LVL);
10321 
10322   // Entrance to the VPlan-native vectorization path. Outer loops are processed
10323   // here. They may require CFG and instruction level transformations before
10324   // even evaluating whether vectorization is profitable. Since we cannot modify
10325   // the incoming IR, we need to build VPlan upfront in the vectorization
10326   // pipeline.
10327   if (!L->isInnermost())
10328     return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
10329                                         ORE, BFI, PSI, Hints, Requirements);
10330 
10331   assert(L->isInnermost() && "Inner loop expected.");
10332 
10333   // Check the loop for a trip count threshold: vectorize loops with a tiny trip
10334   // count by optimizing for size, to minimize overheads.
10335   auto ExpectedTC = getSmallBestKnownTC(*SE, L);
10336   if (ExpectedTC && *ExpectedTC < TinyTripCountVectorThreshold) {
10337     LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
10338                       << "This loop is worth vectorizing only if no scalar "
10339                       << "iteration overheads are incurred.");
10340     if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
10341       LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
10342     else {
10343       LLVM_DEBUG(dbgs() << "\n");
10344       SEL = CM_ScalarEpilogueNotAllowedLowTripLoop;
10345     }
10346   }
10347 
10348   // Check the function attributes to see if implicit floats are allowed.
10349   // FIXME: This check doesn't seem possibly correct -- what if the loop is
10350   // an integer loop and the vector instructions selected are purely integer
10351   // vector instructions?
10352   if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
10353     reportVectorizationFailure(
10354         "Can't vectorize when the NoImplicitFloat attribute is used",
10355         "loop not vectorized due to NoImplicitFloat attribute",
10356         "NoImplicitFloat", ORE, L);
10357     Hints.emitRemarkWithHints();
10358     return false;
10359   }
10360 
10361   // Check if the target supports potentially unsafe FP vectorization.
10362   // FIXME: Add a check for the type of safety issue (denormal, signaling)
10363   // for the target we're vectorizing for, to make sure none of the
10364   // additional fp-math flags can help.
10365   if (Hints.isPotentiallyUnsafe() &&
10366       TTI->isFPVectorizationPotentiallyUnsafe()) {
10367     reportVectorizationFailure(
10368         "Potentially unsafe FP op prevents vectorization",
10369         "loop not vectorized due to unsafe FP support.",
10370         "UnsafeFP", ORE, L);
10371     Hints.emitRemarkWithHints();
10372     return false;
10373   }
10374 
10375   bool AllowOrderedReductions;
10376   // If the flag is set, use that instead and override the TTI behaviour.
10377   if (ForceOrderedReductions.getNumOccurrences() > 0)
10378     AllowOrderedReductions = ForceOrderedReductions;
10379   else
10380     AllowOrderedReductions = TTI->enableOrderedReductions();
10381   if (!LVL.canVectorizeFPMath(AllowOrderedReductions)) {
10382     ORE->emit([&]() {
10383       auto *ExactFPMathInst = Requirements.getExactFPInst();
10384       return OptimizationRemarkAnalysisFPCommute(DEBUG_TYPE, "CantReorderFPOps",
10385                                                  ExactFPMathInst->getDebugLoc(),
10386                                                  ExactFPMathInst->getParent())
10387              << "loop not vectorized: cannot prove it is safe to reorder "
10388                 "floating-point operations";
10389     });
10390     LLVM_DEBUG(dbgs() << "LV: loop not vectorized: cannot prove it is safe to "
10391                          "reorder floating-point operations\n");
10392     Hints.emitRemarkWithHints();
10393     return false;
10394   }
10395 
10396   bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
10397   InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
10398 
10399   // If an override option has been passed in for interleaved accesses, use it.
10400   if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
10401     UseInterleaved = EnableInterleavedMemAccesses;
10402 
10403   // Analyze interleaved memory accesses.
10404   if (UseInterleaved) {
10405     IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
10406   }
10407 
10408   // Use the cost model.
10409   LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE,
10410                                 F, &Hints, IAI);
10411   CM.collectValuesToIgnore();
10412   CM.collectElementTypesForWidening();
10413 
10414   // Use the planner for vectorization.
10415   LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM, IAI, PSE, Hints,
10416                                Requirements, ORE);
10417 
10418   // Get user vectorization factor and interleave count.
10419   ElementCount UserVF = Hints.getWidth();
10420   unsigned UserIC = Hints.getInterleave();
10421 
10422   // Plan how to best vectorize, return the best VF and its cost.
10423   Optional<VectorizationFactor> MaybeVF = LVP.plan(UserVF, UserIC);
10424 
10425   VectorizationFactor VF = VectorizationFactor::Disabled();
10426   unsigned IC = 1;
10427 
10428   GeneratedRTChecks Checks(*PSE.getSE(), DT, LI,
10429                            F->getParent()->getDataLayout());
10430   if (MaybeVF) {
10431     if (LVP.requiresTooManyRuntimeChecks()) {
10432       ORE->emit([&]() {
10433         return OptimizationRemarkAnalysisAliasing(
10434                    DEBUG_TYPE, "CantReorderMemOps", L->getStartLoc(),
10435                    L->getHeader())
10436                << "loop not vectorized: cannot prove it is safe to reorder "
10437                   "memory operations";
10438       });
10439       LLVM_DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
10440       Hints.emitRemarkWithHints();
10441       return false;
10442     }
10443     VF = *MaybeVF;
10444     // Select the interleave count.
10445     IC = CM.selectInterleaveCount(VF.Width, *VF.Cost.getValue());
10446 
10447     unsigned SelectedIC = std::max(IC, UserIC);
10448     //  Optimistically generate runtime checks if they are needed. Drop them if
10449     //  they turn out to not be profitable.
10450     if (VF.Width.isVector() || SelectedIC > 1)
10451       Checks.Create(L, *LVL.getLAI(), PSE.getPredicate(), VF.Width, SelectedIC);
10452   }
10453 
10454   // Identify the diagnostic messages that should be produced.
10455   std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
10456   bool VectorizeLoop = true, InterleaveLoop = true;
10457   if (VF.Width.isScalar()) {
10458     LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
10459     VecDiagMsg = std::make_pair(
10460         "VectorizationNotBeneficial",
10461         "the cost-model indicates that vectorization is not beneficial");
10462     VectorizeLoop = false;
10463   }
10464 
10465   if (!MaybeVF && UserIC > 1) {
10466     // Tell the user interleaving was avoided up-front, despite being explicitly
10467     // requested.
10468     LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
10469                          "interleaving should be avoided up front\n");
10470     IntDiagMsg = std::make_pair(
10471         "InterleavingAvoided",
10472         "Ignoring UserIC, because interleaving was avoided up front");
10473     InterleaveLoop = false;
10474   } else if (IC == 1 && UserIC <= 1) {
10475     // Tell the user interleaving is not beneficial.
10476     LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
10477     IntDiagMsg = std::make_pair(
10478         "InterleavingNotBeneficial",
10479         "the cost-model indicates that interleaving is not beneficial");
10480     InterleaveLoop = false;
10481     if (UserIC == 1) {
10482       IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
10483       IntDiagMsg.second +=
10484           " and is explicitly disabled or interleave count is set to 1";
10485     }
10486   } else if (IC > 1 && UserIC == 1) {
10487     // Tell the user interleaving is beneficial, but it explicitly disabled.
10488     LLVM_DEBUG(
10489         dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
10490     IntDiagMsg = std::make_pair(
10491         "InterleavingBeneficialButDisabled",
10492         "the cost-model indicates that interleaving is beneficial "
10493         "but is explicitly disabled or interleave count is set to 1");
10494     InterleaveLoop = false;
10495   }
10496 
10497   // Override IC if user provided an interleave count.
10498   IC = UserIC > 0 ? UserIC : IC;
10499 
10500   // Emit diagnostic messages, if any.
10501   const char *VAPassName = Hints.vectorizeAnalysisPassName();
10502   if (!VectorizeLoop && !InterleaveLoop) {
10503     // Do not vectorize or interleaving the loop.
10504     ORE->emit([&]() {
10505       return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
10506                                       L->getStartLoc(), L->getHeader())
10507              << VecDiagMsg.second;
10508     });
10509     ORE->emit([&]() {
10510       return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
10511                                       L->getStartLoc(), L->getHeader())
10512              << IntDiagMsg.second;
10513     });
10514     return false;
10515   } else if (!VectorizeLoop && InterleaveLoop) {
10516     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10517     ORE->emit([&]() {
10518       return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
10519                                         L->getStartLoc(), L->getHeader())
10520              << VecDiagMsg.second;
10521     });
10522   } else if (VectorizeLoop && !InterleaveLoop) {
10523     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10524                       << ") in " << DebugLocStr << '\n');
10525     ORE->emit([&]() {
10526       return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
10527                                         L->getStartLoc(), L->getHeader())
10528              << IntDiagMsg.second;
10529     });
10530   } else if (VectorizeLoop && InterleaveLoop) {
10531     LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
10532                       << ") in " << DebugLocStr << '\n');
10533     LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
10534   }
10535 
10536   bool DisableRuntimeUnroll = false;
10537   MDNode *OrigLoopID = L->getLoopID();
10538   {
10539     using namespace ore;
10540     if (!VectorizeLoop) {
10541       assert(IC > 1 && "interleave count should not be 1 or 0");
10542       // If we decided that it is not legal to vectorize the loop, then
10543       // interleave it.
10544       InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
10545                                  &CM, BFI, PSI, Checks);
10546 
10547       VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10548       LVP.executePlan(VF.Width, IC, BestPlan, Unroller, DT);
10549 
10550       ORE->emit([&]() {
10551         return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
10552                                   L->getHeader())
10553                << "interleaved loop (interleaved count: "
10554                << NV("InterleaveCount", IC) << ")";
10555       });
10556     } else {
10557       // If we decided that it is *legal* to vectorize the loop, then do it.
10558 
10559       // Consider vectorizing the epilogue too if it's profitable.
10560       VectorizationFactor EpilogueVF =
10561           CM.selectEpilogueVectorizationFactor(VF.Width, LVP);
10562       if (EpilogueVF.Width.isVector()) {
10563 
10564         // The first pass vectorizes the main loop and creates a scalar epilogue
10565         // to be vectorized by executing the plan (potentially with a different
10566         // factor) again shortly afterwards.
10567         EpilogueLoopVectorizationInfo EPI(VF.Width, IC, EpilogueVF.Width, 1);
10568         EpilogueVectorizerMainLoop MainILV(L, PSE, LI, DT, TLI, TTI, AC, ORE,
10569                                            EPI, &LVL, &CM, BFI, PSI, Checks);
10570 
10571         VPlan &BestMainPlan = LVP.getBestPlanFor(EPI.MainLoopVF);
10572         LVP.executePlan(EPI.MainLoopVF, EPI.MainLoopUF, BestMainPlan, MainILV,
10573                         DT);
10574         ++LoopsVectorized;
10575 
10576         // Second pass vectorizes the epilogue and adjusts the control flow
10577         // edges from the first pass.
10578         EPI.MainLoopVF = EPI.EpilogueVF;
10579         EPI.MainLoopUF = EPI.EpilogueUF;
10580         EpilogueVectorizerEpilogueLoop EpilogILV(L, PSE, LI, DT, TLI, TTI, AC,
10581                                                  ORE, EPI, &LVL, &CM, BFI, PSI,
10582                                                  Checks);
10583 
10584         VPlan &BestEpiPlan = LVP.getBestPlanFor(EPI.EpilogueVF);
10585         VPRegionBlock *VectorLoop = BestEpiPlan.getVectorLoopRegion();
10586         VPBasicBlock *Header = VectorLoop->getEntryBasicBlock();
10587         Header->setName("vec.epilog.vector.body");
10588 
10589         // Ensure that the start values for any VPReductionPHIRecipes are
10590         // updated before vectorising the epilogue loop.
10591         for (VPRecipeBase &R : Header->phis()) {
10592           if (auto *ReductionPhi = dyn_cast<VPReductionPHIRecipe>(&R)) {
10593             if (auto *Resume = MainILV.getReductionResumeValue(
10594                     ReductionPhi->getRecurrenceDescriptor())) {
10595               VPValue *StartVal = BestEpiPlan.getOrAddExternalDef(Resume);
10596               ReductionPhi->setOperand(0, StartVal);
10597             }
10598           }
10599         }
10600 
10601         LVP.executePlan(EPI.EpilogueVF, EPI.EpilogueUF, BestEpiPlan, EpilogILV,
10602                         DT);
10603         ++LoopsEpilogueVectorized;
10604 
10605         if (!MainILV.areSafetyChecksAdded())
10606           DisableRuntimeUnroll = true;
10607       } else {
10608         InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
10609                                &LVL, &CM, BFI, PSI, Checks);
10610 
10611         VPlan &BestPlan = LVP.getBestPlanFor(VF.Width);
10612         LVP.executePlan(VF.Width, IC, BestPlan, LB, DT);
10613         ++LoopsVectorized;
10614 
10615         // Add metadata to disable runtime unrolling a scalar loop when there
10616         // are no runtime checks about strides and memory. A scalar loop that is
10617         // rarely used is not worth unrolling.
10618         if (!LB.areSafetyChecksAdded())
10619           DisableRuntimeUnroll = true;
10620       }
10621       // Report the vectorization decision.
10622       ORE->emit([&]() {
10623         return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
10624                                   L->getHeader())
10625                << "vectorized loop (vectorization width: "
10626                << NV("VectorizationFactor", VF.Width)
10627                << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
10628       });
10629     }
10630 
10631     if (ORE->allowExtraAnalysis(LV_NAME))
10632       checkMixedPrecision(L, ORE);
10633   }
10634 
10635   Optional<MDNode *> RemainderLoopID =
10636       makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
10637                                       LLVMLoopVectorizeFollowupEpilogue});
10638   if (RemainderLoopID) {
10639     L->setLoopID(RemainderLoopID.getValue());
10640   } else {
10641     if (DisableRuntimeUnroll)
10642       AddRuntimeUnrollDisableMetaData(L);
10643 
10644     // Mark the loop as already vectorized to avoid vectorizing again.
10645     Hints.setAlreadyVectorized();
10646   }
10647 
10648   assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()));
10649   return true;
10650 }
10651 
10652 LoopVectorizeResult LoopVectorizePass::runImpl(
10653     Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
10654     DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
10655     DemandedBits &DB_, AAResults &AA_, AssumptionCache &AC_,
10656     std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
10657     OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
10658   SE = &SE_;
10659   LI = &LI_;
10660   TTI = &TTI_;
10661   DT = &DT_;
10662   BFI = &BFI_;
10663   TLI = TLI_;
10664   AA = &AA_;
10665   AC = &AC_;
10666   GetLAA = &GetLAA_;
10667   DB = &DB_;
10668   ORE = &ORE_;
10669   PSI = PSI_;
10670 
10671   // Don't attempt if
10672   // 1. the target claims to have no vector registers, and
10673   // 2. interleaving won't help ILP.
10674   //
10675   // The second condition is necessary because, even if the target has no
10676   // vector registers, loop vectorization may still enable scalar
10677   // interleaving.
10678   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)) &&
10679       TTI->getMaxInterleaveFactor(1) < 2)
10680     return LoopVectorizeResult(false, false);
10681 
10682   bool Changed = false, CFGChanged = false;
10683 
10684   // The vectorizer requires loops to be in simplified form.
10685   // Since simplification may add new inner loops, it has to run before the
10686   // legality and profitability checks. This means running the loop vectorizer
10687   // will simplify all loops, regardless of whether anything end up being
10688   // vectorized.
10689   for (auto &L : *LI)
10690     Changed |= CFGChanged |=
10691         simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
10692 
10693   // Build up a worklist of inner-loops to vectorize. This is necessary as
10694   // the act of vectorizing or partially unrolling a loop creates new loops
10695   // and can invalidate iterators across the loops.
10696   SmallVector<Loop *, 8> Worklist;
10697 
10698   for (Loop *L : *LI)
10699     collectSupportedLoops(*L, LI, ORE, Worklist);
10700 
10701   LoopsAnalyzed += Worklist.size();
10702 
10703   // Now walk the identified inner loops.
10704   while (!Worklist.empty()) {
10705     Loop *L = Worklist.pop_back_val();
10706 
10707     // For the inner loops we actually process, form LCSSA to simplify the
10708     // transform.
10709     Changed |= formLCSSARecursively(*L, *DT, LI, SE);
10710 
10711     Changed |= CFGChanged |= processLoop(L);
10712   }
10713 
10714   // Process each loop nest in the function.
10715   return LoopVectorizeResult(Changed, CFGChanged);
10716 }
10717 
10718 PreservedAnalyses LoopVectorizePass::run(Function &F,
10719                                          FunctionAnalysisManager &AM) {
10720     auto &LI = AM.getResult<LoopAnalysis>(F);
10721     // There are no loops in the function. Return before computing other expensive
10722     // analyses.
10723     if (LI.empty())
10724       return PreservedAnalyses::all();
10725     auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
10726     auto &TTI = AM.getResult<TargetIRAnalysis>(F);
10727     auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
10728     auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
10729     auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
10730     auto &AA = AM.getResult<AAManager>(F);
10731     auto &AC = AM.getResult<AssumptionAnalysis>(F);
10732     auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
10733     auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
10734 
10735     auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
10736     std::function<const LoopAccessInfo &(Loop &)> GetLAA =
10737         [&](Loop &L) -> const LoopAccessInfo & {
10738       LoopStandardAnalysisResults AR = {AA,  AC,  DT,      LI,      SE,
10739                                         TLI, TTI, nullptr, nullptr, nullptr};
10740       return LAM.getResult<LoopAccessAnalysis>(L, AR);
10741     };
10742     auto &MAMProxy = AM.getResult<ModuleAnalysisManagerFunctionProxy>(F);
10743     ProfileSummaryInfo *PSI =
10744         MAMProxy.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
10745     LoopVectorizeResult Result =
10746         runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
10747     if (!Result.MadeAnyChange)
10748       return PreservedAnalyses::all();
10749     PreservedAnalyses PA;
10750 
10751     // We currently do not preserve loopinfo/dominator analyses with outer loop
10752     // vectorization. Until this is addressed, mark these analyses as preserved
10753     // only for non-VPlan-native path.
10754     // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
10755     if (!EnableVPlanNativePath) {
10756       PA.preserve<LoopAnalysis>();
10757       PA.preserve<DominatorTreeAnalysis>();
10758     }
10759 
10760     if (Result.MadeCFGChange) {
10761       // Making CFG changes likely means a loop got vectorized. Indicate that
10762       // extra simplification passes should be run.
10763       // TODO: MadeCFGChanges is not a prefect proxy. Extra passes should only
10764       // be run if runtime checks have been added.
10765       AM.getResult<ShouldRunExtraVectorPasses>(F);
10766       PA.preserve<ShouldRunExtraVectorPasses>();
10767     } else {
10768       PA.preserveSet<CFGAnalyses>();
10769     }
10770     return PA;
10771 }
10772 
10773 void LoopVectorizePass::printPipeline(
10774     raw_ostream &OS, function_ref<StringRef(StringRef)> MapClassName2PassName) {
10775   static_cast<PassInfoMixin<LoopVectorizePass> *>(this)->printPipeline(
10776       OS, MapClassName2PassName);
10777 
10778   OS << "<";
10779   OS << (InterleaveOnlyWhenForced ? "" : "no-") << "interleave-forced-only;";
10780   OS << (VectorizeOnlyWhenForced ? "" : "no-") << "vectorize-forced-only;";
10781   OS << ">";
10782 }
10783