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