xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 4eb98384099cbd1d901d8ef6a210af95d9c36adf)
1 //===- VPlan.cpp - Vectorizer Plan ----------------------------------------===//
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 /// \file
10 /// This is the LLVM vectorization plan. It represents a candidate for
11 /// vectorization, allowing to plan and optimize how to vectorize a given loop
12 /// before generating LLVM-IR.
13 /// The vectorizer uses vectorization plans to estimate the costs of potential
14 /// candidates and if profitable to execute the desired plan, generating vector
15 /// LLVM-IR code.
16 ///
17 //===----------------------------------------------------------------------===//
18 
19 #include "VPlan.h"
20 #include "LoopVectorizationPlanner.h"
21 #include "VPlanCFG.h"
22 #include "VPlanDominatorTree.h"
23 #include "VPlanPatternMatch.h"
24 #include "VPlanTransforms.h"
25 #include "VPlanUtils.h"
26 #include "llvm/ADT/PostOrderIterator.h"
27 #include "llvm/ADT/STLExtras.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/Twine.h"
31 #include "llvm/Analysis/DomTreeUpdater.h"
32 #include "llvm/Analysis/LoopInfo.h"
33 #include "llvm/IR/BasicBlock.h"
34 #include "llvm/IR/CFG.h"
35 #include "llvm/IR/IRBuilder.h"
36 #include "llvm/IR/Instruction.h"
37 #include "llvm/IR/Instructions.h"
38 #include "llvm/IR/Type.h"
39 #include "llvm/IR/Value.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/CommandLine.h"
42 #include "llvm/Support/Debug.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/LoopVersioning.h"
47 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
48 #include <cassert>
49 #include <string>
50 #include <vector>
51 
52 using namespace llvm;
53 using namespace llvm::VPlanPatternMatch;
54 
55 namespace llvm {
56 extern cl::opt<bool> EnableVPlanNativePath;
57 }
58 extern cl::opt<unsigned> ForceTargetInstructionCost;
59 
60 static cl::opt<bool> PrintVPlansInDotFormat(
61     "vplan-print-in-dot-format", cl::Hidden,
62     cl::desc("Use dot format instead of plain text when dumping VPlans"));
63 
64 #define DEBUG_TYPE "vplan"
65 
66 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
67 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
68   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
69   VPSlotTracker SlotTracker(
70       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
71   V.print(OS, SlotTracker);
72   return OS;
73 }
74 #endif
75 
76 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
77                                 const ElementCount &VF) const {
78   switch (LaneKind) {
79   case VPLane::Kind::ScalableLast:
80     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
81     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
82                              Builder.getInt32(VF.getKnownMinValue() - Lane));
83   case VPLane::Kind::First:
84     return Builder.getInt32(Lane);
85   }
86   llvm_unreachable("Unknown lane kind");
87 }
88 
89 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
90     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
91   if (Def)
92     Def->addDefinedValue(this);
93 }
94 
95 VPValue::~VPValue() {
96   assert(Users.empty() && "trying to delete a VPValue with remaining users");
97   if (Def)
98     Def->removeDefinedValue(this);
99 }
100 
101 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
102 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
103   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
104     R->print(OS, "", SlotTracker);
105   else
106     printAsOperand(OS, SlotTracker);
107 }
108 
109 void VPValue::dump() const {
110   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
111   VPSlotTracker SlotTracker(
112       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
113   print(dbgs(), SlotTracker);
114   dbgs() << "\n";
115 }
116 
117 void VPDef::dump() const {
118   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
119   VPSlotTracker SlotTracker(
120       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
121   print(dbgs(), "", SlotTracker);
122   dbgs() << "\n";
123 }
124 #endif
125 
126 VPRecipeBase *VPValue::getDefiningRecipe() {
127   return cast_or_null<VPRecipeBase>(Def);
128 }
129 
130 const VPRecipeBase *VPValue::getDefiningRecipe() const {
131   return cast_or_null<VPRecipeBase>(Def);
132 }
133 
134 // Get the top-most entry block of \p Start. This is the entry block of the
135 // containing VPlan. This function is templated to support both const and non-const blocks
136 template <typename T> static T *getPlanEntry(T *Start) {
137   T *Next = Start;
138   T *Current = Start;
139   while ((Next = Next->getParent()))
140     Current = Next;
141 
142   SmallSetVector<T *, 8> WorkList;
143   WorkList.insert(Current);
144 
145   for (unsigned i = 0; i < WorkList.size(); i++) {
146     T *Current = WorkList[i];
147     if (Current->getNumPredecessors() == 0)
148       return Current;
149     auto &Predecessors = Current->getPredecessors();
150     WorkList.insert(Predecessors.begin(), Predecessors.end());
151   }
152 
153   llvm_unreachable("VPlan without any entry node without predecessors");
154 }
155 
156 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
157 
158 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
159 
160 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
161 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
162   const VPBlockBase *Block = this;
163   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
164     Block = Region->getEntry();
165   return cast<VPBasicBlock>(Block);
166 }
167 
168 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
169   VPBlockBase *Block = this;
170   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
171     Block = Region->getEntry();
172   return cast<VPBasicBlock>(Block);
173 }
174 
175 void VPBlockBase::setPlan(VPlan *ParentPlan) {
176   assert(
177       (ParentPlan->getEntry() == this || ParentPlan->getPreheader() == this) &&
178       "Can only set plan on its entry or preheader block.");
179   Plan = ParentPlan;
180 }
181 
182 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
183 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const {
184   const VPBlockBase *Block = this;
185   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
186     Block = Region->getExiting();
187   return cast<VPBasicBlock>(Block);
188 }
189 
190 VPBasicBlock *VPBlockBase::getExitingBasicBlock() {
191   VPBlockBase *Block = this;
192   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
193     Block = Region->getExiting();
194   return cast<VPBasicBlock>(Block);
195 }
196 
197 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
198   if (!Successors.empty() || !Parent)
199     return this;
200   assert(Parent->getExiting() == this &&
201          "Block w/o successors not the exiting block of its parent.");
202   return Parent->getEnclosingBlockWithSuccessors();
203 }
204 
205 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
206   if (!Predecessors.empty() || !Parent)
207     return this;
208   assert(Parent->getEntry() == this &&
209          "Block w/o predecessors not the entry of its parent.");
210   return Parent->getEnclosingBlockWithPredecessors();
211 }
212 
213 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
214   for (VPBlockBase *Block : to_vector(vp_depth_first_shallow(Entry)))
215     delete Block;
216 }
217 
218 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
219   iterator It = begin();
220   while (It != end() && It->isPhi())
221     It++;
222   return It;
223 }
224 
225 VPTransformState::VPTransformState(ElementCount VF, unsigned UF, LoopInfo *LI,
226                                    DominatorTree *DT, IRBuilderBase &Builder,
227                                    InnerLoopVectorizer *ILV, VPlan *Plan)
228     : VF(VF), UF(UF), CFG(DT), LI(LI), Builder(Builder), ILV(ILV), Plan(Plan),
229       LVer(nullptr), TypeAnalysis(Plan->getCanonicalIV()->getScalarType()) {}
230 
231 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
232   if (Def->isLiveIn())
233     return Def->getLiveInIRValue();
234 
235   if (hasScalarValue(Def, Instance)) {
236     return Data
237         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
238   }
239   if (!Instance.Lane.isFirstLane() &&
240       vputils::isUniformAfterVectorization(Def) &&
241       hasScalarValue(Def, {Instance.Part, VPLane::getFirstLane()})) {
242     return Data.PerPartScalars[Def][Instance.Part][0];
243   }
244 
245   assert(hasVectorValue(Def, Instance.Part));
246   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
247   if (!VecPart->getType()->isVectorTy()) {
248     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
249     return VecPart;
250   }
251   // TODO: Cache created scalar values.
252   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
253   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
254   // set(Def, Extract, Instance);
255   return Extract;
256 }
257 
258 Value *VPTransformState::get(VPValue *Def, unsigned Part, bool NeedsScalar) {
259   if (NeedsScalar) {
260     assert((VF.isScalar() || Def->isLiveIn() || hasVectorValue(Def, Part) ||
261             !vputils::onlyFirstLaneUsed(Def) ||
262             (hasScalarValue(Def, VPIteration(Part, 0)) &&
263              Data.PerPartScalars[Def][Part].size() == 1)) &&
264            "Trying to access a single scalar per part but has multiple scalars "
265            "per part.");
266     return get(Def, VPIteration(Part, 0));
267   }
268 
269   // If Values have been set for this Def return the one relevant for \p Part.
270   if (hasVectorValue(Def, Part))
271     return Data.PerPartOutput[Def][Part];
272 
273   auto GetBroadcastInstrs = [this, Def](Value *V) {
274     bool SafeToHoist = Def->isDefinedOutsideLoopRegions();
275     if (VF.isScalar())
276       return V;
277     // Place the code for broadcasting invariant variables in the new preheader.
278     IRBuilder<>::InsertPointGuard Guard(Builder);
279     if (SafeToHoist) {
280       BasicBlock *LoopVectorPreHeader = CFG.VPBB2IRBB[cast<VPBasicBlock>(
281           Plan->getVectorLoopRegion()->getSinglePredecessor())];
282       if (LoopVectorPreHeader)
283         Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
284     }
285 
286     // Place the code for broadcasting invariant variables in the new preheader.
287     // Broadcast the scalar into all locations in the vector.
288     Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
289 
290     return Shuf;
291   };
292 
293   if (!hasScalarValue(Def, {Part, 0})) {
294     assert(Def->isLiveIn() && "expected a live-in");
295     if (Part != 0)
296       return get(Def, 0);
297     Value *IRV = Def->getLiveInIRValue();
298     Value *B = GetBroadcastInstrs(IRV);
299     set(Def, B, Part);
300     return B;
301   }
302 
303   Value *ScalarValue = get(Def, {Part, 0});
304   // If we aren't vectorizing, we can just copy the scalar map values over
305   // to the vector map.
306   if (VF.isScalar()) {
307     set(Def, ScalarValue, Part);
308     return ScalarValue;
309   }
310 
311   bool IsUniform = vputils::isUniformAfterVectorization(Def);
312 
313   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
314   // Check if there is a scalar value for the selected lane.
315   if (!hasScalarValue(Def, {Part, LastLane})) {
316     // At the moment, VPWidenIntOrFpInductionRecipes, VPScalarIVStepsRecipes and
317     // VPExpandSCEVRecipes can also be uniform.
318     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDefiningRecipe()) ||
319             isa<VPScalarIVStepsRecipe>(Def->getDefiningRecipe()) ||
320             isa<VPExpandSCEVRecipe>(Def->getDefiningRecipe())) &&
321            "unexpected recipe found to be invariant");
322     IsUniform = true;
323     LastLane = 0;
324   }
325 
326   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
327   // Set the insert point after the last scalarized instruction or after the
328   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
329   // will directly follow the scalar definitions.
330   auto OldIP = Builder.saveIP();
331   auto NewIP =
332       isa<PHINode>(LastInst)
333           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
334           : std::next(BasicBlock::iterator(LastInst));
335   Builder.SetInsertPoint(&*NewIP);
336 
337   // However, if we are vectorizing, we need to construct the vector values.
338   // If the value is known to be uniform after vectorization, we can just
339   // broadcast the scalar value corresponding to lane zero for each unroll
340   // iteration. Otherwise, we construct the vector values using
341   // insertelement instructions. Since the resulting vectors are stored in
342   // State, we will only generate the insertelements once.
343   Value *VectorValue = nullptr;
344   if (IsUniform) {
345     VectorValue = GetBroadcastInstrs(ScalarValue);
346     set(Def, VectorValue, Part);
347   } else {
348     // Initialize packing with insertelements to start from undef.
349     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
350     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
351     set(Def, Undef, Part);
352     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
353       packScalarIntoVectorValue(Def, {Part, Lane});
354     VectorValue = get(Def, Part);
355   }
356   Builder.restoreIP(OldIP);
357   return VectorValue;
358 }
359 
360 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {
361   VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
362   return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
363 }
364 
365 void VPTransformState::addNewMetadata(Instruction *To,
366                                       const Instruction *Orig) {
367   // If the loop was versioned with memchecks, add the corresponding no-alias
368   // metadata.
369   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
370     LVer->annotateInstWithNoAlias(To, Orig);
371 }
372 
373 void VPTransformState::addMetadata(Value *To, Instruction *From) {
374   // No source instruction to transfer metadata from?
375   if (!From)
376     return;
377 
378   if (Instruction *ToI = dyn_cast<Instruction>(To)) {
379     propagateMetadata(ToI, From);
380     addNewMetadata(ToI, From);
381   }
382 }
383 
384 void VPTransformState::setDebugLocFrom(DebugLoc DL) {
385   const DILocation *DIL = DL;
386   // When a FSDiscriminator is enabled, we don't need to add the multiply
387   // factors to the discriminators.
388   if (DIL &&
389       Builder.GetInsertBlock()
390           ->getParent()
391           ->shouldEmitDebugInfoForProfiling() &&
392       !EnableFSDiscriminator) {
393     // FIXME: For scalable vectors, assume vscale=1.
394     auto NewDIL =
395         DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
396     if (NewDIL)
397       Builder.SetCurrentDebugLocation(*NewDIL);
398     else
399       LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "
400                         << DIL->getFilename() << " Line: " << DIL->getLine());
401   } else
402     Builder.SetCurrentDebugLocation(DIL);
403 }
404 
405 void VPTransformState::packScalarIntoVectorValue(VPValue *Def,
406                                                  const VPIteration &Instance) {
407   Value *ScalarInst = get(Def, Instance);
408   Value *VectorValue = get(Def, Instance.Part);
409   VectorValue = Builder.CreateInsertElement(
410       VectorValue, ScalarInst, Instance.Lane.getAsRuntimeExpr(Builder, VF));
411   set(Def, VectorValue, Instance.Part);
412 }
413 
414 BasicBlock *
415 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
416   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
417   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
418   BasicBlock *PrevBB = CFG.PrevBB;
419   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
420                                          PrevBB->getParent(), CFG.ExitBB);
421   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
422 
423   // Hook up the new basic block to its predecessors.
424   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
425     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
426     auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
427     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
428 
429     assert(PredBB && "Predecessor basic-block not found building successor.");
430     auto *PredBBTerminator = PredBB->getTerminator();
431     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
432 
433     auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
434     if (isa<UnreachableInst>(PredBBTerminator)) {
435       assert(PredVPSuccessors.size() == 1 &&
436              "Predecessor ending w/o branch must have single successor.");
437       DebugLoc DL = PredBBTerminator->getDebugLoc();
438       PredBBTerminator->eraseFromParent();
439       auto *Br = BranchInst::Create(NewBB, PredBB);
440       Br->setDebugLoc(DL);
441     } else if (TermBr && !TermBr->isConditional()) {
442       TermBr->setSuccessor(0, NewBB);
443     } else {
444       // Set each forward successor here when it is created, excluding
445       // backedges. A backward successor is set when the branch is created.
446       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
447       assert(!TermBr->getSuccessor(idx) &&
448              "Trying to reset an existing successor block.");
449       TermBr->setSuccessor(idx, NewBB);
450     }
451     CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, NewBB}});
452   }
453   return NewBB;
454 }
455 
456 void VPIRBasicBlock::execute(VPTransformState *State) {
457   assert(getHierarchicalSuccessors().size() <= 2 &&
458          "VPIRBasicBlock can have at most two successors at the moment!");
459   State->Builder.SetInsertPoint(getIRBasicBlock()->getTerminator());
460   executeRecipes(State, getIRBasicBlock());
461   if (getSingleSuccessor()) {
462     assert(isa<UnreachableInst>(getIRBasicBlock()->getTerminator()));
463     auto *Br = State->Builder.CreateBr(getIRBasicBlock());
464     Br->setOperand(0, nullptr);
465     getIRBasicBlock()->getTerminator()->eraseFromParent();
466   }
467 
468   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
469     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
470     BasicBlock *PredBB = State->CFG.VPBB2IRBB[PredVPBB];
471     assert(PredBB && "Predecessor basic-block not found building successor.");
472     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
473 
474     auto *PredBBTerminator = PredBB->getTerminator();
475     auto *TermBr = cast<BranchInst>(PredBBTerminator);
476     // Set each forward successor here when it is created, excluding
477     // backedges. A backward successor is set when the branch is created.
478     const auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
479     unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
480     assert(!TermBr->getSuccessor(idx) &&
481            "Trying to reset an existing successor block.");
482     TermBr->setSuccessor(idx, IRBB);
483     State->CFG.DTU.applyUpdates({{DominatorTree::Insert, PredBB, IRBB}});
484   }
485 }
486 
487 void VPBasicBlock::execute(VPTransformState *State) {
488   bool Replica = State->Instance && !State->Instance->isFirstIteration();
489   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
490   VPBlockBase *SingleHPred = nullptr;
491   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
492 
493   auto IsLoopRegion = [](VPBlockBase *BB) {
494     auto *R = dyn_cast<VPRegionBlock>(BB);
495     return R && !R->isReplicator();
496   };
497 
498   // 1. Create an IR basic block.
499   if (PrevVPBB && /* A */
500       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
501         SingleHPred->getExitingBasicBlock() == PrevVPBB &&
502         PrevVPBB->getSingleHierarchicalSuccessor() &&
503         (SingleHPred->getParent() == getEnclosingLoopRegion() &&
504          !IsLoopRegion(SingleHPred))) &&         /* B */
505       !(Replica && getPredecessors().empty())) { /* C */
506     // The last IR basic block is reused, as an optimization, in three cases:
507     // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
508     // B. when the current VPBB has a single (hierarchical) predecessor which
509     //    is PrevVPBB and the latter has a single (hierarchical) successor which
510     //    both are in the same non-replicator region; and
511     // C. when the current VPBB is an entry of a region replica - where PrevVPBB
512     //    is the exiting VPBB of this region from a previous instance, or the
513     //    predecessor of this region.
514 
515     NewBB = createEmptyBasicBlock(State->CFG);
516     State->Builder.SetInsertPoint(NewBB);
517     // Temporarily terminate with unreachable until CFG is rewired.
518     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
519     // Register NewBB in its loop. In innermost loops its the same for all
520     // BB's.
521     if (State->CurrentVectorLoop)
522       State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
523     State->Builder.SetInsertPoint(Terminator);
524     State->CFG.PrevBB = NewBB;
525   }
526 
527   // 2. Fill the IR basic block with IR instructions.
528   executeRecipes(State, NewBB);
529 }
530 
531 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
532   for (VPRecipeBase &R : Recipes) {
533     for (auto *Def : R.definedValues())
534       Def->replaceAllUsesWith(NewValue);
535 
536     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
537       R.setOperand(I, NewValue);
538   }
539 }
540 
541 void VPBasicBlock::executeRecipes(VPTransformState *State, BasicBlock *BB) {
542   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
543                     << " in BB:" << BB->getName() << '\n');
544 
545   State->CFG.VPBB2IRBB[this] = BB;
546   State->CFG.PrevVPBB = this;
547 
548   for (VPRecipeBase &Recipe : Recipes)
549     Recipe.execute(*State);
550 
551   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *BB);
552 }
553 
554 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
555   assert((SplitAt == end() || SplitAt->getParent() == this) &&
556          "can only split at a position in the same block");
557 
558   SmallVector<VPBlockBase *, 2> Succs(successors());
559   // First, disconnect the current block from its successors.
560   for (VPBlockBase *Succ : Succs)
561     VPBlockUtils::disconnectBlocks(this, Succ);
562 
563   // Create new empty block after the block to split.
564   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
565   VPBlockUtils::insertBlockAfter(SplitBlock, this);
566 
567   // Add successors for block to split to new block.
568   for (VPBlockBase *Succ : Succs)
569     VPBlockUtils::connectBlocks(SplitBlock, Succ);
570 
571   // Finally, move the recipes starting at SplitAt to new block.
572   for (VPRecipeBase &ToMove :
573        make_early_inc_range(make_range(SplitAt, this->end())))
574     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
575 
576   return SplitBlock;
577 }
578 
579 /// Return the enclosing loop region for region \p P. The templated version is
580 /// used to support both const and non-const block arguments.
581 template <typename T> static T *getEnclosingLoopRegionForRegion(T *P) {
582   if (P && P->isReplicator()) {
583     P = P->getParent();
584     assert(!cast<VPRegionBlock>(P)->isReplicator() &&
585            "unexpected nested replicate regions");
586   }
587   return P;
588 }
589 
590 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
591   return getEnclosingLoopRegionForRegion(getParent());
592 }
593 
594 const VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() const {
595   return getEnclosingLoopRegionForRegion(getParent());
596 }
597 
598 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
599   if (VPBB->empty()) {
600     assert(
601         VPBB->getNumSuccessors() < 2 &&
602         "block with multiple successors doesn't have a recipe as terminator");
603     return false;
604   }
605 
606   const VPRecipeBase *R = &VPBB->back();
607   bool IsCondBranch = isa<VPBranchOnMaskRecipe>(R) ||
608                       match(R, m_BranchOnCond(m_VPValue())) ||
609                       match(R, m_BranchOnCount(m_VPValue(), m_VPValue()));
610   (void)IsCondBranch;
611 
612   if (VPBB->getNumSuccessors() >= 2 ||
613       (VPBB->isExiting() && !VPBB->getParent()->isReplicator())) {
614     assert(IsCondBranch && "block with multiple successors not terminated by "
615                            "conditional branch recipe");
616 
617     return true;
618   }
619 
620   assert(
621       !IsCondBranch &&
622       "block with 0 or 1 successors terminated by conditional branch recipe");
623   return false;
624 }
625 
626 VPRecipeBase *VPBasicBlock::getTerminator() {
627   if (hasConditionalTerminator(this))
628     return &back();
629   return nullptr;
630 }
631 
632 const VPRecipeBase *VPBasicBlock::getTerminator() const {
633   if (hasConditionalTerminator(this))
634     return &back();
635   return nullptr;
636 }
637 
638 bool VPBasicBlock::isExiting() const {
639   return getParent() && getParent()->getExitingBasicBlock() == this;
640 }
641 
642 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
643 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
644   if (getSuccessors().empty()) {
645     O << Indent << "No successors\n";
646   } else {
647     O << Indent << "Successor(s): ";
648     ListSeparator LS;
649     for (auto *Succ : getSuccessors())
650       O << LS << Succ->getName();
651     O << '\n';
652   }
653 }
654 
655 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
656                          VPSlotTracker &SlotTracker) const {
657   O << Indent << getName() << ":\n";
658 
659   auto RecipeIndent = Indent + "  ";
660   for (const VPRecipeBase &Recipe : *this) {
661     Recipe.print(O, RecipeIndent, SlotTracker);
662     O << '\n';
663   }
664 
665   printSuccessors(O, Indent);
666 }
667 #endif
668 
669 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry);
670 
671 // Clone the CFG for all nodes reachable from \p Entry, this includes cloning
672 // the blocks and their recipes. Operands of cloned recipes will NOT be updated.
673 // Remapping of operands must be done separately. Returns a pair with the new
674 // entry and exiting blocks of the cloned region. If \p Entry isn't part of a
675 // region, return nullptr for the exiting block.
676 static std::pair<VPBlockBase *, VPBlockBase *> cloneFrom(VPBlockBase *Entry) {
677   DenseMap<VPBlockBase *, VPBlockBase *> Old2NewVPBlocks;
678   VPBlockBase *Exiting = nullptr;
679   bool InRegion = Entry->getParent();
680   // First, clone blocks reachable from Entry.
681   for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
682     VPBlockBase *NewBB = BB->clone();
683     Old2NewVPBlocks[BB] = NewBB;
684     if (InRegion && BB->getNumSuccessors() == 0) {
685       assert(!Exiting && "Multiple exiting blocks?");
686       Exiting = BB;
687     }
688   }
689   assert((!InRegion || Exiting) && "regions must have a single exiting block");
690 
691   // Second, update the predecessors & successors of the cloned blocks.
692   for (VPBlockBase *BB : vp_depth_first_shallow(Entry)) {
693     VPBlockBase *NewBB = Old2NewVPBlocks[BB];
694     SmallVector<VPBlockBase *> NewPreds;
695     for (VPBlockBase *Pred : BB->getPredecessors()) {
696       NewPreds.push_back(Old2NewVPBlocks[Pred]);
697     }
698     NewBB->setPredecessors(NewPreds);
699     SmallVector<VPBlockBase *> NewSuccs;
700     for (VPBlockBase *Succ : BB->successors()) {
701       NewSuccs.push_back(Old2NewVPBlocks[Succ]);
702     }
703     NewBB->setSuccessors(NewSuccs);
704   }
705 
706 #if !defined(NDEBUG)
707   // Verify that the order of predecessors and successors matches in the cloned
708   // version.
709   for (const auto &[OldBB, NewBB] :
710        zip(vp_depth_first_shallow(Entry),
711            vp_depth_first_shallow(Old2NewVPBlocks[Entry]))) {
712     for (const auto &[OldPred, NewPred] :
713          zip(OldBB->getPredecessors(), NewBB->getPredecessors()))
714       assert(NewPred == Old2NewVPBlocks[OldPred] && "Different predecessors");
715 
716     for (const auto &[OldSucc, NewSucc] :
717          zip(OldBB->successors(), NewBB->successors()))
718       assert(NewSucc == Old2NewVPBlocks[OldSucc] && "Different successors");
719   }
720 #endif
721 
722   return std::make_pair(Old2NewVPBlocks[Entry],
723                         Exiting ? Old2NewVPBlocks[Exiting] : nullptr);
724 }
725 
726 VPRegionBlock *VPRegionBlock::clone() {
727   const auto &[NewEntry, NewExiting] = cloneFrom(getEntry());
728   auto *NewRegion =
729       new VPRegionBlock(NewEntry, NewExiting, getName(), isReplicator());
730   for (VPBlockBase *Block : vp_depth_first_shallow(NewEntry))
731     Block->setParent(NewRegion);
732   return NewRegion;
733 }
734 
735 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
736   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
737     // Drop all references in VPBasicBlocks and replace all uses with
738     // DummyValue.
739     Block->dropAllReferences(NewValue);
740 }
741 
742 void VPRegionBlock::execute(VPTransformState *State) {
743   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
744       RPOT(Entry);
745 
746   if (!isReplicator()) {
747     // Create and register the new vector loop.
748     Loop *PrevLoop = State->CurrentVectorLoop;
749     State->CurrentVectorLoop = State->LI->AllocateLoop();
750     BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
751     Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
752 
753     // Insert the new loop into the loop nest and register the new basic blocks
754     // before calling any utilities such as SCEV that require valid LoopInfo.
755     if (ParentLoop)
756       ParentLoop->addChildLoop(State->CurrentVectorLoop);
757     else
758       State->LI->addTopLevelLoop(State->CurrentVectorLoop);
759 
760     // Visit the VPBlocks connected to "this", starting from it.
761     for (VPBlockBase *Block : RPOT) {
762       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
763       Block->execute(State);
764     }
765 
766     State->CurrentVectorLoop = PrevLoop;
767     return;
768   }
769 
770   assert(!State->Instance && "Replicating a Region with non-null instance.");
771 
772   // Enter replicating mode.
773   State->Instance = VPIteration(0, 0);
774 
775   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
776     State->Instance->Part = Part;
777     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
778     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
779          ++Lane) {
780       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
781       // Visit the VPBlocks connected to \p this, starting from it.
782       for (VPBlockBase *Block : RPOT) {
783         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
784         Block->execute(State);
785       }
786     }
787   }
788 
789   // Exit replicating mode.
790   State->Instance.reset();
791 }
792 
793 InstructionCost VPBasicBlock::cost(ElementCount VF, VPCostContext &Ctx) {
794   InstructionCost Cost = 0;
795   for (VPRecipeBase &R : Recipes)
796     Cost += R.cost(VF, Ctx);
797   return Cost;
798 }
799 
800 InstructionCost VPRegionBlock::cost(ElementCount VF, VPCostContext &Ctx) {
801   if (!isReplicator()) {
802     InstructionCost Cost = 0;
803     for (VPBlockBase *Block : vp_depth_first_shallow(getEntry()))
804       Cost += Block->cost(VF, Ctx);
805     InstructionCost BackedgeCost =
806         ForceTargetInstructionCost.getNumOccurrences()
807             ? InstructionCost(ForceTargetInstructionCost.getNumOccurrences())
808             : Ctx.TTI.getCFInstrCost(Instruction::Br, TTI::TCK_RecipThroughput);
809     LLVM_DEBUG(dbgs() << "Cost of " << BackedgeCost << " for VF " << VF
810                       << ": vector loop backedge\n");
811     Cost += BackedgeCost;
812     return Cost;
813   }
814 
815   // Compute the cost of a replicate region. Replicating isn't supported for
816   // scalable vectors, return an invalid cost for them.
817   // TODO: Discard scalable VPlans with replicate recipes earlier after
818   // construction.
819   if (VF.isScalable())
820     return InstructionCost::getInvalid();
821 
822   // First compute the cost of the conditionally executed recipes, followed by
823   // account for the branching cost, except if the mask is a header mask or
824   // uniform condition.
825   using namespace llvm::VPlanPatternMatch;
826   VPBasicBlock *Then = cast<VPBasicBlock>(getEntry()->getSuccessors()[0]);
827   InstructionCost ThenCost = Then->cost(VF, Ctx);
828 
829   // For the scalar case, we may not always execute the original predicated
830   // block, Thus, scale the block's cost by the probability of executing it.
831   if (VF.isScalar())
832     return ThenCost / getReciprocalPredBlockProb();
833 
834   return ThenCost;
835 }
836 
837 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
838 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
839                           VPSlotTracker &SlotTracker) const {
840   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
841   auto NewIndent = Indent + "  ";
842   for (auto *BlockBase : vp_depth_first_shallow(Entry)) {
843     O << '\n';
844     BlockBase->print(O, NewIndent, SlotTracker);
845   }
846   O << Indent << "}\n";
847 
848   printSuccessors(O, Indent);
849 }
850 #endif
851 
852 VPlan::~VPlan() {
853   for (auto &KV : LiveOuts)
854     delete KV.second;
855   LiveOuts.clear();
856 
857   if (Entry) {
858     VPValue DummyValue;
859     for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
860       Block->dropAllReferences(&DummyValue);
861 
862     VPBlockBase::deleteCFG(Entry);
863 
864     Preheader->dropAllReferences(&DummyValue);
865     delete Preheader;
866   }
867   for (VPValue *VPV : VPLiveInsToFree)
868     delete VPV;
869   if (BackedgeTakenCount)
870     delete BackedgeTakenCount;
871 }
872 
873 static VPIRBasicBlock *createVPIRBasicBlockFor(BasicBlock *BB) {
874   auto *VPIRBB = new VPIRBasicBlock(BB);
875   for (Instruction &I :
876        make_range(BB->begin(), BB->getTerminator()->getIterator()))
877     VPIRBB->appendRecipe(new VPIRInstruction(I));
878   return VPIRBB;
879 }
880 
881 VPlanPtr VPlan::createInitialVPlan(Type *InductionTy,
882                                    PredicatedScalarEvolution &PSE,
883                                    bool RequiresScalarEpilogueCheck,
884                                    bool TailFolded, Loop *TheLoop) {
885   VPIRBasicBlock *Entry = createVPIRBasicBlockFor(TheLoop->getLoopPreheader());
886   VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph");
887   auto Plan = std::make_unique<VPlan>(Entry, VecPreheader);
888 
889   // Create SCEV and VPValue for the trip count.
890   const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
891   assert(!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && "Invalid loop count");
892   ScalarEvolution &SE = *PSE.getSE();
893   const SCEV *TripCount =
894       SE.getTripCountFromExitCount(BackedgeTakenCount, InductionTy, TheLoop);
895   Plan->TripCount =
896       vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE);
897 
898   // Create VPRegionBlock, with empty header and latch blocks, to be filled
899   // during processing later.
900   VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");
901   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
902   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
903   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop",
904                                       false /*isReplicator*/);
905 
906   VPBlockUtils::insertBlockAfter(TopRegion, VecPreheader);
907   VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
908   VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
909 
910   VPBasicBlock *ScalarPH = new VPBasicBlock("scalar.ph");
911   if (!RequiresScalarEpilogueCheck) {
912     VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
913     return Plan;
914   }
915 
916   // If needed, add a check in the middle block to see if we have completed
917   // all of the iterations in the first vector loop.  Three cases:
918   // 1) If (N - N%VF) == N, then we *don't* need to run the remainder.
919   //    Thus if tail is to be folded, we know we don't need to run the
920   //    remainder and we can set the condition to true.
921   // 2) If we require a scalar epilogue, there is no conditional branch as
922   //    we unconditionally branch to the scalar preheader.  Do nothing.
923   // 3) Otherwise, construct a runtime check.
924   BasicBlock *IRExitBlock = TheLoop->getUniqueExitBlock();
925   auto *VPExitBlock = createVPIRBasicBlockFor(IRExitBlock);
926   // The connection order corresponds to the operands of the conditional branch.
927   VPBlockUtils::insertBlockAfter(VPExitBlock, MiddleVPBB);
928   VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
929 
930   auto *ScalarLatchTerm = TheLoop->getLoopLatch()->getTerminator();
931   // Here we use the same DebugLoc as the scalar loop latch terminator instead
932   // of the corresponding compare because they may have ended up with
933   // different line numbers and we want to avoid awkward line stepping while
934   // debugging. Eg. if the compare has got a line number inside the loop.
935   VPBuilder Builder(MiddleVPBB);
936   VPValue *Cmp =
937       TailFolded
938           ? Plan->getOrAddLiveIn(ConstantInt::getTrue(
939                 IntegerType::getInt1Ty(TripCount->getType()->getContext())))
940           : Builder.createICmp(CmpInst::ICMP_EQ, Plan->getTripCount(),
941                                &Plan->getVectorTripCount(),
942                                ScalarLatchTerm->getDebugLoc(), "cmp.n");
943   Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp},
944                        ScalarLatchTerm->getDebugLoc());
945   return Plan;
946 }
947 
948 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
949                              Value *CanonicalIVStartValue,
950                              VPTransformState &State) {
951   Type *TCTy = TripCountV->getType();
952   // Check if the backedge taken count is needed, and if so build it.
953   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
954     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
955     auto *TCMO = Builder.CreateSub(TripCountV, ConstantInt::get(TCTy, 1),
956                                    "trip.count.minus.1");
957     BackedgeTakenCount->setUnderlyingValue(TCMO);
958   }
959 
960   VectorTripCount.setUnderlyingValue(VectorTripCountV);
961 
962   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
963   // FIXME: Model VF * UF computation completely in VPlan.
964   assert(VFxUF.getNumUsers() && "VFxUF expected to always have users");
965   if (VF.getNumUsers()) {
966     Value *RuntimeVF = getRuntimeVF(Builder, TCTy, State.VF);
967     VF.setUnderlyingValue(RuntimeVF);
968     VFxUF.setUnderlyingValue(
969         State.UF > 1
970             ? Builder.CreateMul(RuntimeVF, ConstantInt::get(TCTy, State.UF))
971             : RuntimeVF);
972   } else {
973     VFxUF.setUnderlyingValue(
974         createStepForVF(Builder, TCTy, State.VF, State.UF));
975   }
976 
977   // When vectorizing the epilogue loop, the canonical induction start value
978   // needs to be changed from zero to the value after the main vector loop.
979   // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
980   if (CanonicalIVStartValue) {
981     VPValue *VPV = getOrAddLiveIn(CanonicalIVStartValue);
982     auto *IV = getCanonicalIV();
983     assert(all_of(IV->users(),
984                   [](const VPUser *U) {
985                     return isa<VPScalarIVStepsRecipe>(U) ||
986                            isa<VPScalarCastRecipe>(U) ||
987                            isa<VPDerivedIVRecipe>(U) ||
988                            cast<VPInstruction>(U)->getOpcode() ==
989                                Instruction::Add;
990                   }) &&
991            "the canonical IV should only be used by its increment or "
992            "ScalarIVSteps when resetting the start value");
993     IV->setOperand(0, VPV);
994   }
995 }
996 
997 /// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
998 /// VPBB are moved to the end of the newly created VPIRBasicBlock. VPBB must
999 /// have a single predecessor, which is rewired to the new VPIRBasicBlock. All
1000 /// successors of VPBB, if any, are rewired to the new VPIRBasicBlock.
1001 static void replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB) {
1002   VPIRBasicBlock *IRVPBB = createVPIRBasicBlockFor(IRBB);
1003   for (auto &R : make_early_inc_range(*VPBB)) {
1004     assert(!R.isPhi() && "Tried to move phi recipe to end of block");
1005     R.moveBefore(*IRVPBB, IRVPBB->end());
1006   }
1007   VPBlockBase *PredVPBB = VPBB->getSinglePredecessor();
1008   VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
1009   VPBlockUtils::connectBlocks(PredVPBB, IRVPBB);
1010   for (auto *Succ : to_vector(VPBB->getSuccessors())) {
1011     VPBlockUtils::connectBlocks(IRVPBB, Succ);
1012     VPBlockUtils::disconnectBlocks(VPBB, Succ);
1013   }
1014   delete VPBB;
1015 }
1016 
1017 /// Generate the code inside the preheader and body of the vectorized loop.
1018 /// Assumes a single pre-header basic-block was created for this. Introduce
1019 /// additional basic-blocks as needed, and fill them all.
1020 void VPlan::execute(VPTransformState *State) {
1021   // Initialize CFG state.
1022   State->CFG.PrevVPBB = nullptr;
1023   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
1024   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
1025   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
1026 
1027   // Disconnect VectorPreHeader from ExitBB in both the CFG and DT.
1028   cast<BranchInst>(VectorPreHeader->getTerminator())->setSuccessor(0, nullptr);
1029   State->CFG.DTU.applyUpdates(
1030       {{DominatorTree::Delete, VectorPreHeader, State->CFG.ExitBB}});
1031 
1032   // Replace regular VPBB's for the middle and scalar preheader blocks with
1033   // VPIRBasicBlocks wrapping their IR blocks. The IR blocks are created during
1034   // skeleton creation, so we can only create the VPIRBasicBlocks now during
1035   // VPlan execution rather than earlier during VPlan construction.
1036   BasicBlock *MiddleBB = State->CFG.ExitBB;
1037   VPBasicBlock *MiddleVPBB =
1038       cast<VPBasicBlock>(getVectorLoopRegion()->getSingleSuccessor());
1039   // Find the VPBB for the scalar preheader, relying on the current structure
1040   // when creating the middle block and its successrs: if there's a single
1041   // predecessor, it must be the scalar preheader. Otherwise, the second
1042   // successor is the scalar preheader.
1043   BasicBlock *ScalarPh = MiddleBB->getSingleSuccessor();
1044   auto &MiddleSuccs = MiddleVPBB->getSuccessors();
1045   assert((MiddleSuccs.size() == 1 || MiddleSuccs.size() == 2) &&
1046          "middle block has unexpected successors");
1047   VPBasicBlock *ScalarPhVPBB = cast<VPBasicBlock>(
1048       MiddleSuccs.size() == 1 ? MiddleSuccs[0] : MiddleSuccs[1]);
1049   assert(!isa<VPIRBasicBlock>(ScalarPhVPBB) &&
1050          "scalar preheader cannot be wrapped already");
1051   replaceVPBBWithIRVPBB(ScalarPhVPBB, ScalarPh);
1052   replaceVPBBWithIRVPBB(MiddleVPBB, MiddleBB);
1053 
1054   // Disconnect the middle block from its single successor (the scalar loop
1055   // header) in both the CFG and DT. The branch will be recreated during VPlan
1056   // execution.
1057   auto *BrInst = new UnreachableInst(MiddleBB->getContext());
1058   BrInst->insertBefore(MiddleBB->getTerminator());
1059   MiddleBB->getTerminator()->eraseFromParent();
1060   State->CFG.DTU.applyUpdates({{DominatorTree::Delete, MiddleBB, ScalarPh}});
1061 
1062   // Generate code in the loop pre-header and body.
1063   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
1064     Block->execute(State);
1065 
1066   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
1067   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
1068 
1069   // Fix the latch value of canonical, reduction and first-order recurrences
1070   // phis in the vector loop.
1071   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
1072   for (VPRecipeBase &R : Header->phis()) {
1073     // Skip phi-like recipes that generate their backedege values themselves.
1074     if (isa<VPWidenPHIRecipe>(&R))
1075       continue;
1076 
1077     if (isa<VPWidenPointerInductionRecipe>(&R) ||
1078         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1079       PHINode *Phi = nullptr;
1080       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1081         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
1082       } else {
1083         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
1084         assert(!WidenPhi->onlyScalarsGenerated(State->VF.isScalable()) &&
1085                "recipe generating only scalars should have been replaced");
1086         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
1087         Phi = cast<PHINode>(GEP->getPointerOperand());
1088       }
1089 
1090       Phi->setIncomingBlock(1, VectorLatchBB);
1091 
1092       // Move the last step to the end of the latch block. This ensures
1093       // consistent placement of all induction updates.
1094       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
1095       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
1096       continue;
1097     }
1098 
1099     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
1100     // For  canonical IV, first-order recurrences and in-order reduction phis,
1101     // only a single part is generated, which provides the last part from the
1102     // previous iteration. For non-ordered reductions all UF parts are
1103     // generated.
1104     bool SinglePartNeeded =
1105         isa<VPCanonicalIVPHIRecipe>(PhiR) ||
1106         isa<VPFirstOrderRecurrencePHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
1107         (isa<VPReductionPHIRecipe>(PhiR) &&
1108          cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
1109     bool NeedsScalar =
1110         isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
1111         (isa<VPReductionPHIRecipe>(PhiR) &&
1112          cast<VPReductionPHIRecipe>(PhiR)->isInLoop());
1113     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
1114 
1115     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1116       Value *Phi = State->get(PhiR, Part, NeedsScalar);
1117       Value *Val =
1118           State->get(PhiR->getBackedgeValue(),
1119                      SinglePartNeeded ? State->UF - 1 : Part, NeedsScalar);
1120       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
1121     }
1122   }
1123 
1124   State->CFG.DTU.flush();
1125   assert(State->CFG.DTU.getDomTree().verify(
1126              DominatorTree::VerificationLevel::Fast) &&
1127          "DT not preserved correctly");
1128 }
1129 
1130 InstructionCost VPlan::cost(ElementCount VF, VPCostContext &Ctx) {
1131   // For now only return the cost of the vector loop region, ignoring any other
1132   // blocks, like the preheader or middle blocks.
1133   return getVectorLoopRegion()->cost(VF, Ctx);
1134 }
1135 
1136 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1137 void VPlan::printLiveIns(raw_ostream &O) const {
1138   VPSlotTracker SlotTracker(this);
1139 
1140   if (VF.getNumUsers() > 0) {
1141     O << "\nLive-in ";
1142     VF.printAsOperand(O, SlotTracker);
1143     O << " = VF";
1144   }
1145 
1146   if (VFxUF.getNumUsers() > 0) {
1147     O << "\nLive-in ";
1148     VFxUF.printAsOperand(O, SlotTracker);
1149     O << " = VF * UF";
1150   }
1151 
1152   if (VectorTripCount.getNumUsers() > 0) {
1153     O << "\nLive-in ";
1154     VectorTripCount.printAsOperand(O, SlotTracker);
1155     O << " = vector-trip-count";
1156   }
1157 
1158   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
1159     O << "\nLive-in ";
1160     BackedgeTakenCount->printAsOperand(O, SlotTracker);
1161     O << " = backedge-taken count";
1162   }
1163 
1164   O << "\n";
1165   if (TripCount->isLiveIn())
1166     O << "Live-in ";
1167   TripCount->printAsOperand(O, SlotTracker);
1168   O << " = original trip-count";
1169   O << "\n";
1170 }
1171 
1172 LLVM_DUMP_METHOD
1173 void VPlan::print(raw_ostream &O) const {
1174   VPSlotTracker SlotTracker(this);
1175 
1176   O << "VPlan '" << getName() << "' {";
1177 
1178   printLiveIns(O);
1179 
1180   if (!getPreheader()->empty()) {
1181     O << "\n";
1182     getPreheader()->print(O, "", SlotTracker);
1183   }
1184 
1185   for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) {
1186     O << '\n';
1187     Block->print(O, "", SlotTracker);
1188   }
1189 
1190   if (!LiveOuts.empty())
1191     O << "\n";
1192   for (const auto &KV : LiveOuts) {
1193     KV.second->print(O, SlotTracker);
1194   }
1195 
1196   O << "}\n";
1197 }
1198 
1199 std::string VPlan::getName() const {
1200   std::string Out;
1201   raw_string_ostream RSO(Out);
1202   RSO << Name << " for ";
1203   if (!VFs.empty()) {
1204     RSO << "VF={" << VFs[0];
1205     for (ElementCount VF : drop_begin(VFs))
1206       RSO << "," << VF;
1207     RSO << "},";
1208   }
1209 
1210   if (UFs.empty()) {
1211     RSO << "UF>=1";
1212   } else {
1213     RSO << "UF={" << UFs[0];
1214     for (unsigned UF : drop_begin(UFs))
1215       RSO << "," << UF;
1216     RSO << "}";
1217   }
1218 
1219   return Out;
1220 }
1221 
1222 LLVM_DUMP_METHOD
1223 void VPlan::printDOT(raw_ostream &O) const {
1224   VPlanPrinter Printer(O, *this);
1225   Printer.dump();
1226 }
1227 
1228 LLVM_DUMP_METHOD
1229 void VPlan::dump() const { print(dbgs()); }
1230 #endif
1231 
1232 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
1233   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
1234   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
1235 }
1236 
1237 static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry,
1238                           DenseMap<VPValue *, VPValue *> &Old2NewVPValues) {
1239   // Update the operands of all cloned recipes starting at NewEntry. This
1240   // traverses all reachable blocks. This is done in two steps, to handle cycles
1241   // in PHI recipes.
1242   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>
1243       OldDeepRPOT(Entry);
1244   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>
1245       NewDeepRPOT(NewEntry);
1246   // First, collect all mappings from old to new VPValues defined by cloned
1247   // recipes.
1248   for (const auto &[OldBB, NewBB] :
1249        zip(VPBlockUtils::blocksOnly<VPBasicBlock>(OldDeepRPOT),
1250            VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT))) {
1251     assert(OldBB->getRecipeList().size() == NewBB->getRecipeList().size() &&
1252            "blocks must have the same number of recipes");
1253     for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) {
1254       assert(OldR.getNumOperands() == NewR.getNumOperands() &&
1255              "recipes must have the same number of operands");
1256       assert(OldR.getNumDefinedValues() == NewR.getNumDefinedValues() &&
1257              "recipes must define the same number of operands");
1258       for (const auto &[OldV, NewV] :
1259            zip(OldR.definedValues(), NewR.definedValues()))
1260         Old2NewVPValues[OldV] = NewV;
1261     }
1262   }
1263 
1264   // Update all operands to use cloned VPValues.
1265   for (VPBasicBlock *NewBB :
1266        VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT)) {
1267     for (VPRecipeBase &NewR : *NewBB)
1268       for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) {
1269         VPValue *NewOp = Old2NewVPValues.lookup(NewR.getOperand(I));
1270         NewR.setOperand(I, NewOp);
1271       }
1272   }
1273 }
1274 
1275 VPlan *VPlan::duplicate() {
1276   // Clone blocks.
1277   VPBasicBlock *NewPreheader = Preheader->clone();
1278   const auto &[NewEntry, __] = cloneFrom(Entry);
1279 
1280   // Create VPlan, clone live-ins and remap operands in the cloned blocks.
1281   auto *NewPlan = new VPlan(NewPreheader, cast<VPBasicBlock>(NewEntry));
1282   DenseMap<VPValue *, VPValue *> Old2NewVPValues;
1283   for (VPValue *OldLiveIn : VPLiveInsToFree) {
1284     Old2NewVPValues[OldLiveIn] =
1285         NewPlan->getOrAddLiveIn(OldLiveIn->getLiveInIRValue());
1286   }
1287   Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount;
1288   Old2NewVPValues[&VF] = &NewPlan->VF;
1289   Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF;
1290   if (BackedgeTakenCount) {
1291     NewPlan->BackedgeTakenCount = new VPValue();
1292     Old2NewVPValues[BackedgeTakenCount] = NewPlan->BackedgeTakenCount;
1293   }
1294   assert(TripCount && "trip count must be set");
1295   if (TripCount->isLiveIn())
1296     Old2NewVPValues[TripCount] =
1297         NewPlan->getOrAddLiveIn(TripCount->getLiveInIRValue());
1298   // else NewTripCount will be created and inserted into Old2NewVPValues when
1299   // TripCount is cloned. In any case NewPlan->TripCount is updated below.
1300 
1301   remapOperands(Preheader, NewPreheader, Old2NewVPValues);
1302   remapOperands(Entry, NewEntry, Old2NewVPValues);
1303 
1304   // Clone live-outs.
1305   for (const auto &[_, LO] : LiveOuts)
1306     NewPlan->addLiveOut(LO->getPhi(), Old2NewVPValues[LO->getOperand(0)]);
1307 
1308   // Initialize remaining fields of cloned VPlan.
1309   NewPlan->VFs = VFs;
1310   NewPlan->UFs = UFs;
1311   // TODO: Adjust names.
1312   NewPlan->Name = Name;
1313   assert(Old2NewVPValues.contains(TripCount) &&
1314          "TripCount must have been added to Old2NewVPValues");
1315   NewPlan->TripCount = Old2NewVPValues[TripCount];
1316   return NewPlan;
1317 }
1318 
1319 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1320 
1321 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
1322   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
1323          Twine(getOrCreateBID(Block));
1324 }
1325 
1326 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
1327   const std::string &Name = Block->getName();
1328   if (!Name.empty())
1329     return Name;
1330   return "VPB" + Twine(getOrCreateBID(Block));
1331 }
1332 
1333 void VPlanPrinter::dump() {
1334   Depth = 1;
1335   bumpIndent(0);
1336   OS << "digraph VPlan {\n";
1337   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
1338   if (!Plan.getName().empty())
1339     OS << "\\n" << DOT::EscapeString(Plan.getName());
1340 
1341   {
1342     // Print live-ins.
1343   std::string Str;
1344   raw_string_ostream SS(Str);
1345   Plan.printLiveIns(SS);
1346   SmallVector<StringRef, 0> Lines;
1347   StringRef(Str).rtrim('\n').split(Lines, "\n");
1348   for (auto Line : Lines)
1349     OS << DOT::EscapeString(Line.str()) << "\\n";
1350   }
1351 
1352   OS << "\"]\n";
1353   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
1354   OS << "edge [fontname=Courier, fontsize=30]\n";
1355   OS << "compound=true\n";
1356 
1357   dumpBlock(Plan.getPreheader());
1358 
1359   for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry()))
1360     dumpBlock(Block);
1361 
1362   OS << "}\n";
1363 }
1364 
1365 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1366   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1367     dumpBasicBlock(BasicBlock);
1368   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1369     dumpRegion(Region);
1370   else
1371     llvm_unreachable("Unsupported kind of VPBlock.");
1372 }
1373 
1374 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1375                             bool Hidden, const Twine &Label) {
1376   // Due to "dot" we print an edge between two regions as an edge between the
1377   // exiting basic block and the entry basic of the respective regions.
1378   const VPBlockBase *Tail = From->getExitingBasicBlock();
1379   const VPBlockBase *Head = To->getEntryBasicBlock();
1380   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1381   OS << " [ label=\"" << Label << '\"';
1382   if (Tail != From)
1383     OS << " ltail=" << getUID(From);
1384   if (Head != To)
1385     OS << " lhead=" << getUID(To);
1386   if (Hidden)
1387     OS << "; splines=none";
1388   OS << "]\n";
1389 }
1390 
1391 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1392   auto &Successors = Block->getSuccessors();
1393   if (Successors.size() == 1)
1394     drawEdge(Block, Successors.front(), false, "");
1395   else if (Successors.size() == 2) {
1396     drawEdge(Block, Successors.front(), false, "T");
1397     drawEdge(Block, Successors.back(), false, "F");
1398   } else {
1399     unsigned SuccessorNumber = 0;
1400     for (auto *Successor : Successors)
1401       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1402   }
1403 }
1404 
1405 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1406   // Implement dot-formatted dump by performing plain-text dump into the
1407   // temporary storage followed by some post-processing.
1408   OS << Indent << getUID(BasicBlock) << " [label =\n";
1409   bumpIndent(1);
1410   std::string Str;
1411   raw_string_ostream SS(Str);
1412   // Use no indentation as we need to wrap the lines into quotes ourselves.
1413   BasicBlock->print(SS, "", SlotTracker);
1414 
1415   // We need to process each line of the output separately, so split
1416   // single-string plain-text dump.
1417   SmallVector<StringRef, 0> Lines;
1418   StringRef(Str).rtrim('\n').split(Lines, "\n");
1419 
1420   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1421     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1422   };
1423 
1424   // Don't need the "+" after the last line.
1425   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1426     EmitLine(Line, " +\n");
1427   EmitLine(Lines.back(), "\n");
1428 
1429   bumpIndent(-1);
1430   OS << Indent << "]\n";
1431 
1432   dumpEdges(BasicBlock);
1433 }
1434 
1435 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1436   OS << Indent << "subgraph " << getUID(Region) << " {\n";
1437   bumpIndent(1);
1438   OS << Indent << "fontname=Courier\n"
1439      << Indent << "label=\""
1440      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1441      << DOT::EscapeString(Region->getName()) << "\"\n";
1442   // Dump the blocks of the region.
1443   assert(Region->getEntry() && "Region contains no inner blocks.");
1444   for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry()))
1445     dumpBlock(Block);
1446   bumpIndent(-1);
1447   OS << Indent << "}\n";
1448   dumpEdges(Region);
1449 }
1450 
1451 void VPlanIngredient::print(raw_ostream &O) const {
1452   if (auto *Inst = dyn_cast<Instruction>(V)) {
1453     if (!Inst->getType()->isVoidTy()) {
1454       Inst->printAsOperand(O, false);
1455       O << " = ";
1456     }
1457     O << Inst->getOpcodeName() << " ";
1458     unsigned E = Inst->getNumOperands();
1459     if (E > 0) {
1460       Inst->getOperand(0)->printAsOperand(O, false);
1461       for (unsigned I = 1; I < E; ++I)
1462         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1463     }
1464   } else // !Inst
1465     V->printAsOperand(O, false);
1466 }
1467 
1468 #endif
1469 
1470 bool VPValue::isDefinedOutsideLoopRegions() const {
1471   return !hasDefiningRecipe() ||
1472          !getDefiningRecipe()->getParent()->getEnclosingLoopRegion();
1473 }
1474 
1475 void VPValue::replaceAllUsesWith(VPValue *New) {
1476   replaceUsesWithIf(New, [](VPUser &, unsigned) { return true; });
1477 }
1478 
1479 void VPValue::replaceUsesWithIf(
1480     VPValue *New,
1481     llvm::function_ref<bool(VPUser &U, unsigned Idx)> ShouldReplace) {
1482   // Note that this early exit is required for correctness; the implementation
1483   // below relies on the number of users for this VPValue to decrease, which
1484   // isn't the case if this == New.
1485   if (this == New)
1486     return;
1487 
1488   for (unsigned J = 0; J < getNumUsers();) {
1489     VPUser *User = Users[J];
1490     bool RemovedUser = false;
1491     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
1492       if (User->getOperand(I) != this || !ShouldReplace(*User, I))
1493         continue;
1494 
1495       RemovedUser = true;
1496       User->setOperand(I, New);
1497     }
1498     // If a user got removed after updating the current user, the next user to
1499     // update will be moved to the current position, so we only need to
1500     // increment the index if the number of users did not change.
1501     if (!RemovedUser)
1502       J++;
1503   }
1504 }
1505 
1506 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1507 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1508   OS << Tracker.getOrCreateName(this);
1509 }
1510 
1511 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1512   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1513     Op->printAsOperand(O, SlotTracker);
1514   });
1515 }
1516 #endif
1517 
1518 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1519                                           Old2NewTy &Old2New,
1520                                           InterleavedAccessInfo &IAI) {
1521   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
1522       RPOT(Region->getEntry());
1523   for (VPBlockBase *Base : RPOT) {
1524     visitBlock(Base, Old2New, IAI);
1525   }
1526 }
1527 
1528 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1529                                          InterleavedAccessInfo &IAI) {
1530   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1531     for (VPRecipeBase &VPI : *VPBB) {
1532       if (isa<VPWidenPHIRecipe>(&VPI))
1533         continue;
1534       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1535       auto *VPInst = cast<VPInstruction>(&VPI);
1536 
1537       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
1538       if (!Inst)
1539         continue;
1540       auto *IG = IAI.getInterleaveGroup(Inst);
1541       if (!IG)
1542         continue;
1543 
1544       auto NewIGIter = Old2New.find(IG);
1545       if (NewIGIter == Old2New.end())
1546         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1547             IG->getFactor(), IG->isReverse(), IG->getAlign());
1548 
1549       if (Inst == IG->getInsertPos())
1550         Old2New[IG]->setInsertPos(VPInst);
1551 
1552       InterleaveGroupMap[VPInst] = Old2New[IG];
1553       InterleaveGroupMap[VPInst]->insertMember(
1554           VPInst, IG->getIndex(Inst),
1555           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1556                                 : IG->getFactor()));
1557     }
1558   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1559     visitRegion(Region, Old2New, IAI);
1560   else
1561     llvm_unreachable("Unsupported kind of VPBlock.");
1562 }
1563 
1564 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1565                                                  InterleavedAccessInfo &IAI) {
1566   Old2NewTy Old2New;
1567   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1568 }
1569 
1570 void VPSlotTracker::assignName(const VPValue *V) {
1571   assert(!VPValue2Name.contains(V) && "VPValue already has a name!");
1572   auto *UV = V->getUnderlyingValue();
1573   if (!UV) {
1574     VPValue2Name[V] = (Twine("vp<%") + Twine(NextSlot) + ">").str();
1575     NextSlot++;
1576     return;
1577   }
1578 
1579   // Use the name of the underlying Value, wrapped in "ir<>", and versioned by
1580   // appending ".Number" to the name if there are multiple uses.
1581   std::string Name;
1582   raw_string_ostream S(Name);
1583   UV->printAsOperand(S, false);
1584   assert(!Name.empty() && "Name cannot be empty.");
1585   std::string BaseName = (Twine("ir<") + Name + Twine(">")).str();
1586 
1587   // First assign the base name for V.
1588   const auto &[A, _] = VPValue2Name.insert({V, BaseName});
1589   // Integer or FP constants with different types will result in he same string
1590   // due to stripping types.
1591   if (V->isLiveIn() && isa<ConstantInt, ConstantFP>(UV))
1592     return;
1593 
1594   // If it is already used by C > 0 other VPValues, increase the version counter
1595   // C and use it for V.
1596   const auto &[C, UseInserted] = BaseName2Version.insert({BaseName, 0});
1597   if (!UseInserted) {
1598     C->second++;
1599     A->second = (BaseName + Twine(".") + Twine(C->second)).str();
1600   }
1601 }
1602 
1603 void VPSlotTracker::assignNames(const VPlan &Plan) {
1604   if (Plan.VF.getNumUsers() > 0)
1605     assignName(&Plan.VF);
1606   if (Plan.VFxUF.getNumUsers() > 0)
1607     assignName(&Plan.VFxUF);
1608   assignName(&Plan.VectorTripCount);
1609   if (Plan.BackedgeTakenCount)
1610     assignName(Plan.BackedgeTakenCount);
1611   for (VPValue *LI : Plan.VPLiveInsToFree)
1612     assignName(LI);
1613   assignNames(Plan.getPreheader());
1614 
1615   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>>
1616       RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
1617   for (const VPBasicBlock *VPBB :
1618        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1619     assignNames(VPBB);
1620 }
1621 
1622 void VPSlotTracker::assignNames(const VPBasicBlock *VPBB) {
1623   for (const VPRecipeBase &Recipe : *VPBB)
1624     for (VPValue *Def : Recipe.definedValues())
1625       assignName(Def);
1626 }
1627 
1628 std::string VPSlotTracker::getOrCreateName(const VPValue *V) const {
1629   std::string Name = VPValue2Name.lookup(V);
1630   if (!Name.empty())
1631     return Name;
1632 
1633   // If no name was assigned, no VPlan was provided when creating the slot
1634   // tracker or it is not reachable from the provided VPlan. This can happen,
1635   // e.g. when trying to print a recipe that has not been inserted into a VPlan
1636   // in a debugger.
1637   // TODO: Update VPSlotTracker constructor to assign names to recipes &
1638   // VPValues not associated with a VPlan, instead of constructing names ad-hoc
1639   // here.
1640   const VPRecipeBase *DefR = V->getDefiningRecipe();
1641   (void)DefR;
1642   assert((!DefR || !DefR->getParent() || !DefR->getParent()->getPlan()) &&
1643          "VPValue defined by a recipe in a VPlan?");
1644 
1645   // Use the underlying value's name, if there is one.
1646   if (auto *UV = V->getUnderlyingValue()) {
1647     std::string Name;
1648     raw_string_ostream S(Name);
1649     UV->printAsOperand(S, false);
1650     return (Twine("ir<") + Name + ">").str();
1651   }
1652 
1653   return "<badref>";
1654 }
1655 
1656 bool LoopVectorizationPlanner::getDecisionAndClampRange(
1657     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
1658   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
1659   bool PredicateAtRangeStart = Predicate(Range.Start);
1660 
1661   for (ElementCount TmpVF : VFRange(Range.Start * 2, Range.End))
1662     if (Predicate(TmpVF) != PredicateAtRangeStart) {
1663       Range.End = TmpVF;
1664       break;
1665     }
1666 
1667   return PredicateAtRangeStart;
1668 }
1669 
1670 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
1671 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
1672 /// of VF's starting at a given VF and extending it as much as possible. Each
1673 /// vectorization decision can potentially shorten this sub-range during
1674 /// buildVPlan().
1675 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
1676                                            ElementCount MaxVF) {
1677   auto MaxVFTimes2 = MaxVF * 2;
1678   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
1679     VFRange SubRange = {VF, MaxVFTimes2};
1680     auto Plan = buildVPlan(SubRange);
1681     VPlanTransforms::optimize(*Plan);
1682     VPlans.push_back(std::move(Plan));
1683     VF = SubRange.End;
1684   }
1685 }
1686 
1687 VPlan &LoopVectorizationPlanner::getPlanFor(ElementCount VF) const {
1688   assert(count_if(VPlans,
1689                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
1690              1 &&
1691          "Multiple VPlans for VF.");
1692 
1693   for (const VPlanPtr &Plan : VPlans) {
1694     if (Plan->hasVF(VF))
1695       return *Plan.get();
1696   }
1697   llvm_unreachable("No plan found!");
1698 }
1699 
1700 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1701 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
1702   if (VPlans.empty()) {
1703     O << "LV: No VPlans built.\n";
1704     return;
1705   }
1706   for (const auto &Plan : VPlans)
1707     if (PrintVPlansInDotFormat)
1708       Plan->printDOT(O);
1709     else
1710       Plan->print(O);
1711 }
1712 #endif
1713