xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision f0c5caa8144307ec59fbafeed1ba37bb3603b00f)
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 static VPIRBasicBlock *createVPIRBasicBlockFor(BasicBlock *BB) {
864   auto *VPIRBB = new VPIRBasicBlock(BB);
865   for (Instruction &I :
866        make_range(BB->begin(), BB->getTerminator()->getIterator()))
867     VPIRBB->appendRecipe(new VPIRInstruction(I));
868   return VPIRBB;
869 }
870 
871 VPlanPtr VPlan::createInitialVPlan(const SCEV *TripCount, ScalarEvolution &SE,
872                                    bool RequiresScalarEpilogueCheck,
873                                    bool TailFolded, Loop *TheLoop) {
874   VPIRBasicBlock *Entry = createVPIRBasicBlockFor(TheLoop->getLoopPreheader());
875   VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph");
876   auto Plan = std::make_unique<VPlan>(Entry, VecPreheader);
877   Plan->TripCount =
878       vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE);
879   // Create VPRegionBlock, with empty header and latch blocks, to be filled
880   // during processing later.
881   VPBasicBlock *HeaderVPBB = new VPBasicBlock("vector.body");
882   VPBasicBlock *LatchVPBB = new VPBasicBlock("vector.latch");
883   VPBlockUtils::insertBlockAfter(LatchVPBB, HeaderVPBB);
884   auto *TopRegion = new VPRegionBlock(HeaderVPBB, LatchVPBB, "vector loop",
885                                       false /*isReplicator*/);
886 
887   VPBlockUtils::insertBlockAfter(TopRegion, VecPreheader);
888   VPBasicBlock *MiddleVPBB = new VPBasicBlock("middle.block");
889   VPBlockUtils::insertBlockAfter(MiddleVPBB, TopRegion);
890 
891   VPBasicBlock *ScalarPH = new VPBasicBlock("scalar.ph");
892   if (!RequiresScalarEpilogueCheck) {
893     VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
894     return Plan;
895   }
896 
897   // If needed, add a check in the middle block to see if we have completed
898   // all of the iterations in the first vector loop.  Three cases:
899   // 1) If (N - N%VF) == N, then we *don't* need to run the remainder.
900   //    Thus if tail is to be folded, we know we don't need to run the
901   //    remainder and we can set the condition to true.
902   // 2) If we require a scalar epilogue, there is no conditional branch as
903   //    we unconditionally branch to the scalar preheader.  Do nothing.
904   // 3) Otherwise, construct a runtime check.
905   BasicBlock *IRExitBlock = TheLoop->getUniqueExitBlock();
906   auto *VPExitBlock = createVPIRBasicBlockFor(IRExitBlock);
907   // The connection order corresponds to the operands of the conditional branch.
908   VPBlockUtils::insertBlockAfter(VPExitBlock, MiddleVPBB);
909   VPBlockUtils::connectBlocks(MiddleVPBB, ScalarPH);
910 
911   auto *ScalarLatchTerm = TheLoop->getLoopLatch()->getTerminator();
912   // Here we use the same DebugLoc as the scalar loop latch terminator instead
913   // of the corresponding compare because they may have ended up with
914   // different line numbers and we want to avoid awkward line stepping while
915   // debugging. Eg. if the compare has got a line number inside the loop.
916   VPBuilder Builder(MiddleVPBB);
917   VPValue *Cmp =
918       TailFolded
919           ? Plan->getOrAddLiveIn(ConstantInt::getTrue(
920                 IntegerType::getInt1Ty(TripCount->getType()->getContext())))
921           : Builder.createICmp(CmpInst::ICMP_EQ, Plan->getTripCount(),
922                                &Plan->getVectorTripCount(),
923                                ScalarLatchTerm->getDebugLoc(), "cmp.n");
924   Builder.createNaryOp(VPInstruction::BranchOnCond, {Cmp},
925                        ScalarLatchTerm->getDebugLoc());
926   return Plan;
927 }
928 
929 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
930                              Value *CanonicalIVStartValue,
931                              VPTransformState &State) {
932   Type *TCTy = TripCountV->getType();
933   // Check if the backedge taken count is needed, and if so build it.
934   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
935     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
936     auto *TCMO = Builder.CreateSub(TripCountV, ConstantInt::get(TCTy, 1),
937                                    "trip.count.minus.1");
938     BackedgeTakenCount->setUnderlyingValue(TCMO);
939   }
940 
941   VectorTripCount.setUnderlyingValue(VectorTripCountV);
942 
943   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
944   // FIXME: Model VF * UF computation completely in VPlan.
945   assert(VFxUF.getNumUsers() && "VFxUF expected to always have users");
946   if (VF.getNumUsers()) {
947     Value *RuntimeVF = getRuntimeVF(Builder, TCTy, State.VF);
948     VF.setUnderlyingValue(RuntimeVF);
949     VFxUF.setUnderlyingValue(
950         State.UF > 1
951             ? Builder.CreateMul(RuntimeVF, ConstantInt::get(TCTy, State.UF))
952             : RuntimeVF);
953   } else {
954     VFxUF.setUnderlyingValue(
955         createStepForVF(Builder, TCTy, State.VF, State.UF));
956   }
957 
958   // When vectorizing the epilogue loop, the canonical induction start value
959   // needs to be changed from zero to the value after the main vector loop.
960   // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
961   if (CanonicalIVStartValue) {
962     VPValue *VPV = getOrAddLiveIn(CanonicalIVStartValue);
963     auto *IV = getCanonicalIV();
964     assert(all_of(IV->users(),
965                   [](const VPUser *U) {
966                     return isa<VPScalarIVStepsRecipe>(U) ||
967                            isa<VPScalarCastRecipe>(U) ||
968                            isa<VPDerivedIVRecipe>(U) ||
969                            cast<VPInstruction>(U)->getOpcode() ==
970                                Instruction::Add;
971                   }) &&
972            "the canonical IV should only be used by its increment or "
973            "ScalarIVSteps when resetting the start value");
974     IV->setOperand(0, VPV);
975   }
976 }
977 
978 /// Replace \p VPBB with a VPIRBasicBlock wrapping \p IRBB. All recipes from \p
979 /// VPBB are moved to the newly created VPIRBasicBlock.  VPBB must have a single
980 /// predecessor, which is rewired to the new VPIRBasicBlock. All successors of
981 /// VPBB, if any, are rewired to the new VPIRBasicBlock.
982 static void replaceVPBBWithIRVPBB(VPBasicBlock *VPBB, BasicBlock *IRBB) {
983   VPIRBasicBlock *IRMiddleVPBB = createVPIRBasicBlockFor(IRBB);
984   for (auto &R : make_early_inc_range(*VPBB))
985     R.moveBefore(*IRMiddleVPBB, IRMiddleVPBB->end());
986   VPBlockBase *PredVPBB = VPBB->getSinglePredecessor();
987   VPBlockUtils::disconnectBlocks(PredVPBB, VPBB);
988   VPBlockUtils::connectBlocks(PredVPBB, IRMiddleVPBB);
989   for (auto *Succ : to_vector(VPBB->getSuccessors())) {
990     VPBlockUtils::connectBlocks(IRMiddleVPBB, Succ);
991     VPBlockUtils::disconnectBlocks(VPBB, Succ);
992   }
993   delete VPBB;
994 }
995 
996 /// Generate the code inside the preheader and body of the vectorized loop.
997 /// Assumes a single pre-header basic-block was created for this. Introduce
998 /// additional basic-blocks as needed, and fill them all.
999 void VPlan::execute(VPTransformState *State) {
1000   // Initialize CFG state.
1001   State->CFG.PrevVPBB = nullptr;
1002   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
1003   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
1004   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
1005 
1006   // Disconnect VectorPreHeader from ExitBB in both the CFG and DT.
1007   cast<BranchInst>(VectorPreHeader->getTerminator())->setSuccessor(0, nullptr);
1008   State->CFG.DTU.applyUpdates(
1009       {{DominatorTree::Delete, VectorPreHeader, State->CFG.ExitBB}});
1010 
1011   // Replace regular VPBB's for the middle and scalar preheader blocks with
1012   // VPIRBasicBlocks wrapping their IR blocks. The IR blocks are created during
1013   // skeleton creation, so we can only create the VPIRBasicBlocks now during
1014   // VPlan execution rather than earlier during VPlan construction.
1015   BasicBlock *MiddleBB = State->CFG.ExitBB;
1016   VPBasicBlock *MiddleVPBB =
1017       cast<VPBasicBlock>(getVectorLoopRegion()->getSingleSuccessor());
1018   // Find the VPBB for the scalar preheader, relying on the current structure
1019   // when creating the middle block and its successrs: if there's a single
1020   // predecessor, it must be the scalar preheader. Otherwise, the second
1021   // successor is the scalar preheader.
1022   BasicBlock *ScalarPh = MiddleBB->getSingleSuccessor();
1023   auto &MiddleSuccs = MiddleVPBB->getSuccessors();
1024   assert((MiddleSuccs.size() == 1 || MiddleSuccs.size() == 2) &&
1025          "middle block has unexpected successors");
1026   VPBasicBlock *ScalarPhVPBB = cast<VPBasicBlock>(
1027       MiddleSuccs.size() == 1 ? MiddleSuccs[0] : MiddleSuccs[1]);
1028   assert(!isa<VPIRBasicBlock>(ScalarPhVPBB) &&
1029          "scalar preheader cannot be wrapped already");
1030   replaceVPBBWithIRVPBB(ScalarPhVPBB, ScalarPh);
1031   replaceVPBBWithIRVPBB(MiddleVPBB, MiddleBB);
1032 
1033   // Disconnect the middle block from its single successor (the scalar loop
1034   // header) in both the CFG and DT. The branch will be recreated during VPlan
1035   // execution.
1036   auto *BrInst = new UnreachableInst(MiddleBB->getContext());
1037   BrInst->insertBefore(MiddleBB->getTerminator());
1038   MiddleBB->getTerminator()->eraseFromParent();
1039   State->CFG.DTU.applyUpdates({{DominatorTree::Delete, MiddleBB, ScalarPh}});
1040 
1041   // Generate code in the loop pre-header and body.
1042   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
1043     Block->execute(State);
1044 
1045   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
1046   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
1047 
1048   // Fix the latch value of canonical, reduction and first-order recurrences
1049   // phis in the vector loop.
1050   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
1051   for (VPRecipeBase &R : Header->phis()) {
1052     // Skip phi-like recipes that generate their backedege values themselves.
1053     if (isa<VPWidenPHIRecipe>(&R))
1054       continue;
1055 
1056     if (isa<VPWidenPointerInductionRecipe>(&R) ||
1057         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1058       PHINode *Phi = nullptr;
1059       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
1060         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
1061       } else {
1062         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
1063         assert(!WidenPhi->onlyScalarsGenerated(State->VF.isScalable()) &&
1064                "recipe generating only scalars should have been replaced");
1065         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
1066         Phi = cast<PHINode>(GEP->getPointerOperand());
1067       }
1068 
1069       Phi->setIncomingBlock(1, VectorLatchBB);
1070 
1071       // Move the last step to the end of the latch block. This ensures
1072       // consistent placement of all induction updates.
1073       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
1074       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
1075       continue;
1076     }
1077 
1078     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
1079     // For  canonical IV, first-order recurrences and in-order reduction phis,
1080     // only a single part is generated, which provides the last part from the
1081     // previous iteration. For non-ordered reductions all UF parts are
1082     // generated.
1083     bool SinglePartNeeded =
1084         isa<VPCanonicalIVPHIRecipe>(PhiR) ||
1085         isa<VPFirstOrderRecurrencePHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
1086         (isa<VPReductionPHIRecipe>(PhiR) &&
1087          cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
1088     bool NeedsScalar =
1089         isa<VPCanonicalIVPHIRecipe, VPEVLBasedIVPHIRecipe>(PhiR) ||
1090         (isa<VPReductionPHIRecipe>(PhiR) &&
1091          cast<VPReductionPHIRecipe>(PhiR)->isInLoop());
1092     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
1093 
1094     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1095       Value *Phi = State->get(PhiR, Part, NeedsScalar);
1096       Value *Val =
1097           State->get(PhiR->getBackedgeValue(),
1098                      SinglePartNeeded ? State->UF - 1 : Part, NeedsScalar);
1099       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
1100     }
1101   }
1102 
1103   State->CFG.DTU.flush();
1104   assert(State->CFG.DTU.getDomTree().verify(
1105              DominatorTree::VerificationLevel::Fast) &&
1106          "DT not preserved correctly");
1107 }
1108 
1109 InstructionCost VPlan::cost(ElementCount VF, VPCostContext &Ctx) {
1110   // For now only return the cost of the vector loop region, ignoring any other
1111   // blocks, like the preheader or middle blocks.
1112   return getVectorLoopRegion()->cost(VF, Ctx);
1113 }
1114 
1115 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1116 void VPlan::printLiveIns(raw_ostream &O) const {
1117   VPSlotTracker SlotTracker(this);
1118 
1119   if (VF.getNumUsers() > 0) {
1120     O << "\nLive-in ";
1121     VF.printAsOperand(O, SlotTracker);
1122     O << " = VF";
1123   }
1124 
1125   if (VFxUF.getNumUsers() > 0) {
1126     O << "\nLive-in ";
1127     VFxUF.printAsOperand(O, SlotTracker);
1128     O << " = VF * UF";
1129   }
1130 
1131   if (VectorTripCount.getNumUsers() > 0) {
1132     O << "\nLive-in ";
1133     VectorTripCount.printAsOperand(O, SlotTracker);
1134     O << " = vector-trip-count";
1135   }
1136 
1137   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
1138     O << "\nLive-in ";
1139     BackedgeTakenCount->printAsOperand(O, SlotTracker);
1140     O << " = backedge-taken count";
1141   }
1142 
1143   O << "\n";
1144   if (TripCount->isLiveIn())
1145     O << "Live-in ";
1146   TripCount->printAsOperand(O, SlotTracker);
1147   O << " = original trip-count";
1148   O << "\n";
1149 }
1150 
1151 LLVM_DUMP_METHOD
1152 void VPlan::print(raw_ostream &O) const {
1153   VPSlotTracker SlotTracker(this);
1154 
1155   O << "VPlan '" << getName() << "' {";
1156 
1157   printLiveIns(O);
1158 
1159   if (!getPreheader()->empty()) {
1160     O << "\n";
1161     getPreheader()->print(O, "", SlotTracker);
1162   }
1163 
1164   for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) {
1165     O << '\n';
1166     Block->print(O, "", SlotTracker);
1167   }
1168 
1169   if (!LiveOuts.empty())
1170     O << "\n";
1171   for (const auto &KV : LiveOuts) {
1172     KV.second->print(O, SlotTracker);
1173   }
1174 
1175   O << "}\n";
1176 }
1177 
1178 std::string VPlan::getName() const {
1179   std::string Out;
1180   raw_string_ostream RSO(Out);
1181   RSO << Name << " for ";
1182   if (!VFs.empty()) {
1183     RSO << "VF={" << VFs[0];
1184     for (ElementCount VF : drop_begin(VFs))
1185       RSO << "," << VF;
1186     RSO << "},";
1187   }
1188 
1189   if (UFs.empty()) {
1190     RSO << "UF>=1";
1191   } else {
1192     RSO << "UF={" << UFs[0];
1193     for (unsigned UF : drop_begin(UFs))
1194       RSO << "," << UF;
1195     RSO << "}";
1196   }
1197 
1198   return Out;
1199 }
1200 
1201 LLVM_DUMP_METHOD
1202 void VPlan::printDOT(raw_ostream &O) const {
1203   VPlanPrinter Printer(O, *this);
1204   Printer.dump();
1205 }
1206 
1207 LLVM_DUMP_METHOD
1208 void VPlan::dump() const { print(dbgs()); }
1209 #endif
1210 
1211 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
1212   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
1213   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
1214 }
1215 
1216 static void remapOperands(VPBlockBase *Entry, VPBlockBase *NewEntry,
1217                           DenseMap<VPValue *, VPValue *> &Old2NewVPValues) {
1218   // Update the operands of all cloned recipes starting at NewEntry. This
1219   // traverses all reachable blocks. This is done in two steps, to handle cycles
1220   // in PHI recipes.
1221   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>
1222       OldDeepRPOT(Entry);
1223   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<VPBlockBase *>>
1224       NewDeepRPOT(NewEntry);
1225   // First, collect all mappings from old to new VPValues defined by cloned
1226   // recipes.
1227   for (const auto &[OldBB, NewBB] :
1228        zip(VPBlockUtils::blocksOnly<VPBasicBlock>(OldDeepRPOT),
1229            VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT))) {
1230     assert(OldBB->getRecipeList().size() == NewBB->getRecipeList().size() &&
1231            "blocks must have the same number of recipes");
1232     for (const auto &[OldR, NewR] : zip(*OldBB, *NewBB)) {
1233       assert(OldR.getNumOperands() == NewR.getNumOperands() &&
1234              "recipes must have the same number of operands");
1235       assert(OldR.getNumDefinedValues() == NewR.getNumDefinedValues() &&
1236              "recipes must define the same number of operands");
1237       for (const auto &[OldV, NewV] :
1238            zip(OldR.definedValues(), NewR.definedValues()))
1239         Old2NewVPValues[OldV] = NewV;
1240     }
1241   }
1242 
1243   // Update all operands to use cloned VPValues.
1244   for (VPBasicBlock *NewBB :
1245        VPBlockUtils::blocksOnly<VPBasicBlock>(NewDeepRPOT)) {
1246     for (VPRecipeBase &NewR : *NewBB)
1247       for (unsigned I = 0, E = NewR.getNumOperands(); I != E; ++I) {
1248         VPValue *NewOp = Old2NewVPValues.lookup(NewR.getOperand(I));
1249         NewR.setOperand(I, NewOp);
1250       }
1251   }
1252 }
1253 
1254 VPlan *VPlan::duplicate() {
1255   // Clone blocks.
1256   VPBasicBlock *NewPreheader = Preheader->clone();
1257   const auto &[NewEntry, __] = cloneFrom(Entry);
1258 
1259   // Create VPlan, clone live-ins and remap operands in the cloned blocks.
1260   auto *NewPlan = new VPlan(NewPreheader, cast<VPBasicBlock>(NewEntry));
1261   DenseMap<VPValue *, VPValue *> Old2NewVPValues;
1262   for (VPValue *OldLiveIn : VPLiveInsToFree) {
1263     Old2NewVPValues[OldLiveIn] =
1264         NewPlan->getOrAddLiveIn(OldLiveIn->getLiveInIRValue());
1265   }
1266   Old2NewVPValues[&VectorTripCount] = &NewPlan->VectorTripCount;
1267   Old2NewVPValues[&VF] = &NewPlan->VF;
1268   Old2NewVPValues[&VFxUF] = &NewPlan->VFxUF;
1269   if (BackedgeTakenCount) {
1270     NewPlan->BackedgeTakenCount = new VPValue();
1271     Old2NewVPValues[BackedgeTakenCount] = NewPlan->BackedgeTakenCount;
1272   }
1273   assert(TripCount && "trip count must be set");
1274   if (TripCount->isLiveIn())
1275     Old2NewVPValues[TripCount] =
1276         NewPlan->getOrAddLiveIn(TripCount->getLiveInIRValue());
1277   // else NewTripCount will be created and inserted into Old2NewVPValues when
1278   // TripCount is cloned. In any case NewPlan->TripCount is updated below.
1279 
1280   remapOperands(Preheader, NewPreheader, Old2NewVPValues);
1281   remapOperands(Entry, NewEntry, Old2NewVPValues);
1282 
1283   // Clone live-outs.
1284   for (const auto &[_, LO] : LiveOuts)
1285     NewPlan->addLiveOut(LO->getPhi(), Old2NewVPValues[LO->getOperand(0)]);
1286 
1287   // Initialize remaining fields of cloned VPlan.
1288   NewPlan->VFs = VFs;
1289   NewPlan->UFs = UFs;
1290   // TODO: Adjust names.
1291   NewPlan->Name = Name;
1292   assert(Old2NewVPValues.contains(TripCount) &&
1293          "TripCount must have been added to Old2NewVPValues");
1294   NewPlan->TripCount = Old2NewVPValues[TripCount];
1295   return NewPlan;
1296 }
1297 
1298 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1299 
1300 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
1301   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
1302          Twine(getOrCreateBID(Block));
1303 }
1304 
1305 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
1306   const std::string &Name = Block->getName();
1307   if (!Name.empty())
1308     return Name;
1309   return "VPB" + Twine(getOrCreateBID(Block));
1310 }
1311 
1312 void VPlanPrinter::dump() {
1313   Depth = 1;
1314   bumpIndent(0);
1315   OS << "digraph VPlan {\n";
1316   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
1317   if (!Plan.getName().empty())
1318     OS << "\\n" << DOT::EscapeString(Plan.getName());
1319 
1320   {
1321     // Print live-ins.
1322   std::string Str;
1323   raw_string_ostream SS(Str);
1324   Plan.printLiveIns(SS);
1325   SmallVector<StringRef, 0> Lines;
1326   StringRef(Str).rtrim('\n').split(Lines, "\n");
1327   for (auto Line : Lines)
1328     OS << DOT::EscapeString(Line.str()) << "\\n";
1329   }
1330 
1331   OS << "\"]\n";
1332   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
1333   OS << "edge [fontname=Courier, fontsize=30]\n";
1334   OS << "compound=true\n";
1335 
1336   dumpBlock(Plan.getPreheader());
1337 
1338   for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry()))
1339     dumpBlock(Block);
1340 
1341   OS << "}\n";
1342 }
1343 
1344 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1345   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1346     dumpBasicBlock(BasicBlock);
1347   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1348     dumpRegion(Region);
1349   else
1350     llvm_unreachable("Unsupported kind of VPBlock.");
1351 }
1352 
1353 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1354                             bool Hidden, const Twine &Label) {
1355   // Due to "dot" we print an edge between two regions as an edge between the
1356   // exiting basic block and the entry basic of the respective regions.
1357   const VPBlockBase *Tail = From->getExitingBasicBlock();
1358   const VPBlockBase *Head = To->getEntryBasicBlock();
1359   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1360   OS << " [ label=\"" << Label << '\"';
1361   if (Tail != From)
1362     OS << " ltail=" << getUID(From);
1363   if (Head != To)
1364     OS << " lhead=" << getUID(To);
1365   if (Hidden)
1366     OS << "; splines=none";
1367   OS << "]\n";
1368 }
1369 
1370 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1371   auto &Successors = Block->getSuccessors();
1372   if (Successors.size() == 1)
1373     drawEdge(Block, Successors.front(), false, "");
1374   else if (Successors.size() == 2) {
1375     drawEdge(Block, Successors.front(), false, "T");
1376     drawEdge(Block, Successors.back(), false, "F");
1377   } else {
1378     unsigned SuccessorNumber = 0;
1379     for (auto *Successor : Successors)
1380       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1381   }
1382 }
1383 
1384 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1385   // Implement dot-formatted dump by performing plain-text dump into the
1386   // temporary storage followed by some post-processing.
1387   OS << Indent << getUID(BasicBlock) << " [label =\n";
1388   bumpIndent(1);
1389   std::string Str;
1390   raw_string_ostream SS(Str);
1391   // Use no indentation as we need to wrap the lines into quotes ourselves.
1392   BasicBlock->print(SS, "", SlotTracker);
1393 
1394   // We need to process each line of the output separately, so split
1395   // single-string plain-text dump.
1396   SmallVector<StringRef, 0> Lines;
1397   StringRef(Str).rtrim('\n').split(Lines, "\n");
1398 
1399   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1400     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1401   };
1402 
1403   // Don't need the "+" after the last line.
1404   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1405     EmitLine(Line, " +\n");
1406   EmitLine(Lines.back(), "\n");
1407 
1408   bumpIndent(-1);
1409   OS << Indent << "]\n";
1410 
1411   dumpEdges(BasicBlock);
1412 }
1413 
1414 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1415   OS << Indent << "subgraph " << getUID(Region) << " {\n";
1416   bumpIndent(1);
1417   OS << Indent << "fontname=Courier\n"
1418      << Indent << "label=\""
1419      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1420      << DOT::EscapeString(Region->getName()) << "\"\n";
1421   // Dump the blocks of the region.
1422   assert(Region->getEntry() && "Region contains no inner blocks.");
1423   for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry()))
1424     dumpBlock(Block);
1425   bumpIndent(-1);
1426   OS << Indent << "}\n";
1427   dumpEdges(Region);
1428 }
1429 
1430 void VPlanIngredient::print(raw_ostream &O) const {
1431   if (auto *Inst = dyn_cast<Instruction>(V)) {
1432     if (!Inst->getType()->isVoidTy()) {
1433       Inst->printAsOperand(O, false);
1434       O << " = ";
1435     }
1436     O << Inst->getOpcodeName() << " ";
1437     unsigned E = Inst->getNumOperands();
1438     if (E > 0) {
1439       Inst->getOperand(0)->printAsOperand(O, false);
1440       for (unsigned I = 1; I < E; ++I)
1441         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1442     }
1443   } else // !Inst
1444     V->printAsOperand(O, false);
1445 }
1446 
1447 #endif
1448 
1449 void VPValue::replaceAllUsesWith(VPValue *New) {
1450   replaceUsesWithIf(New, [](VPUser &, unsigned) { return true; });
1451 }
1452 
1453 void VPValue::replaceUsesWithIf(
1454     VPValue *New,
1455     llvm::function_ref<bool(VPUser &U, unsigned Idx)> ShouldReplace) {
1456   // Note that this early exit is required for correctness; the implementation
1457   // below relies on the number of users for this VPValue to decrease, which
1458   // isn't the case if this == New.
1459   if (this == New)
1460     return;
1461 
1462   for (unsigned J = 0; J < getNumUsers();) {
1463     VPUser *User = Users[J];
1464     bool RemovedUser = false;
1465     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I) {
1466       if (User->getOperand(I) != this || !ShouldReplace(*User, I))
1467         continue;
1468 
1469       RemovedUser = true;
1470       User->setOperand(I, New);
1471     }
1472     // If a user got removed after updating the current user, the next user to
1473     // update will be moved to the current position, so we only need to
1474     // increment the index if the number of users did not change.
1475     if (!RemovedUser)
1476       J++;
1477   }
1478 }
1479 
1480 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1481 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1482   OS << Tracker.getOrCreateName(this);
1483 }
1484 
1485 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1486   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1487     Op->printAsOperand(O, SlotTracker);
1488   });
1489 }
1490 #endif
1491 
1492 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1493                                           Old2NewTy &Old2New,
1494                                           InterleavedAccessInfo &IAI) {
1495   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
1496       RPOT(Region->getEntry());
1497   for (VPBlockBase *Base : RPOT) {
1498     visitBlock(Base, Old2New, IAI);
1499   }
1500 }
1501 
1502 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1503                                          InterleavedAccessInfo &IAI) {
1504   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1505     for (VPRecipeBase &VPI : *VPBB) {
1506       if (isa<VPWidenPHIRecipe>(&VPI))
1507         continue;
1508       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1509       auto *VPInst = cast<VPInstruction>(&VPI);
1510 
1511       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
1512       if (!Inst)
1513         continue;
1514       auto *IG = IAI.getInterleaveGroup(Inst);
1515       if (!IG)
1516         continue;
1517 
1518       auto NewIGIter = Old2New.find(IG);
1519       if (NewIGIter == Old2New.end())
1520         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1521             IG->getFactor(), IG->isReverse(), IG->getAlign());
1522 
1523       if (Inst == IG->getInsertPos())
1524         Old2New[IG]->setInsertPos(VPInst);
1525 
1526       InterleaveGroupMap[VPInst] = Old2New[IG];
1527       InterleaveGroupMap[VPInst]->insertMember(
1528           VPInst, IG->getIndex(Inst),
1529           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1530                                 : IG->getFactor()));
1531     }
1532   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1533     visitRegion(Region, Old2New, IAI);
1534   else
1535     llvm_unreachable("Unsupported kind of VPBlock.");
1536 }
1537 
1538 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1539                                                  InterleavedAccessInfo &IAI) {
1540   Old2NewTy Old2New;
1541   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1542 }
1543 
1544 void VPSlotTracker::assignName(const VPValue *V) {
1545   assert(!VPValue2Name.contains(V) && "VPValue already has a name!");
1546   auto *UV = V->getUnderlyingValue();
1547   if (!UV) {
1548     VPValue2Name[V] = (Twine("vp<%") + Twine(NextSlot) + ">").str();
1549     NextSlot++;
1550     return;
1551   }
1552 
1553   // Use the name of the underlying Value, wrapped in "ir<>", and versioned by
1554   // appending ".Number" to the name if there are multiple uses.
1555   std::string Name;
1556   raw_string_ostream S(Name);
1557   UV->printAsOperand(S, false);
1558   assert(!Name.empty() && "Name cannot be empty.");
1559   std::string BaseName = (Twine("ir<") + Name + Twine(">")).str();
1560 
1561   // First assign the base name for V.
1562   const auto &[A, _] = VPValue2Name.insert({V, BaseName});
1563   // Integer or FP constants with different types will result in he same string
1564   // due to stripping types.
1565   if (V->isLiveIn() && isa<ConstantInt, ConstantFP>(UV))
1566     return;
1567 
1568   // If it is already used by C > 0 other VPValues, increase the version counter
1569   // C and use it for V.
1570   const auto &[C, UseInserted] = BaseName2Version.insert({BaseName, 0});
1571   if (!UseInserted) {
1572     C->second++;
1573     A->second = (BaseName + Twine(".") + Twine(C->second)).str();
1574   }
1575 }
1576 
1577 void VPSlotTracker::assignNames(const VPlan &Plan) {
1578   if (Plan.VF.getNumUsers() > 0)
1579     assignName(&Plan.VF);
1580   if (Plan.VFxUF.getNumUsers() > 0)
1581     assignName(&Plan.VFxUF);
1582   assignName(&Plan.VectorTripCount);
1583   if (Plan.BackedgeTakenCount)
1584     assignName(Plan.BackedgeTakenCount);
1585   for (VPValue *LI : Plan.VPLiveInsToFree)
1586     assignName(LI);
1587   assignNames(Plan.getPreheader());
1588 
1589   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>>
1590       RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
1591   for (const VPBasicBlock *VPBB :
1592        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1593     assignNames(VPBB);
1594 }
1595 
1596 void VPSlotTracker::assignNames(const VPBasicBlock *VPBB) {
1597   for (const VPRecipeBase &Recipe : *VPBB)
1598     for (VPValue *Def : Recipe.definedValues())
1599       assignName(Def);
1600 }
1601 
1602 std::string VPSlotTracker::getOrCreateName(const VPValue *V) const {
1603   std::string Name = VPValue2Name.lookup(V);
1604   if (!Name.empty())
1605     return Name;
1606 
1607   // If no name was assigned, no VPlan was provided when creating the slot
1608   // tracker or it is not reachable from the provided VPlan. This can happen,
1609   // e.g. when trying to print a recipe that has not been inserted into a VPlan
1610   // in a debugger.
1611   // TODO: Update VPSlotTracker constructor to assign names to recipes &
1612   // VPValues not associated with a VPlan, instead of constructing names ad-hoc
1613   // here.
1614   const VPRecipeBase *DefR = V->getDefiningRecipe();
1615   (void)DefR;
1616   assert((!DefR || !DefR->getParent() || !DefR->getParent()->getPlan()) &&
1617          "VPValue defined by a recipe in a VPlan?");
1618 
1619   // Use the underlying value's name, if there is one.
1620   if (auto *UV = V->getUnderlyingValue()) {
1621     std::string Name;
1622     raw_string_ostream S(Name);
1623     UV->printAsOperand(S, false);
1624     return (Twine("ir<") + Name + ">").str();
1625   }
1626 
1627   return "<badref>";
1628 }
1629 
1630 bool LoopVectorizationPlanner::getDecisionAndClampRange(
1631     const std::function<bool(ElementCount)> &Predicate, VFRange &Range) {
1632   assert(!Range.isEmpty() && "Trying to test an empty VF range.");
1633   bool PredicateAtRangeStart = Predicate(Range.Start);
1634 
1635   for (ElementCount TmpVF : VFRange(Range.Start * 2, Range.End))
1636     if (Predicate(TmpVF) != PredicateAtRangeStart) {
1637       Range.End = TmpVF;
1638       break;
1639     }
1640 
1641   return PredicateAtRangeStart;
1642 }
1643 
1644 /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
1645 /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
1646 /// of VF's starting at a given VF and extending it as much as possible. Each
1647 /// vectorization decision can potentially shorten this sub-range during
1648 /// buildVPlan().
1649 void LoopVectorizationPlanner::buildVPlans(ElementCount MinVF,
1650                                            ElementCount MaxVF) {
1651   auto MaxVFTimes2 = MaxVF * 2;
1652   for (ElementCount VF = MinVF; ElementCount::isKnownLT(VF, MaxVFTimes2);) {
1653     VFRange SubRange = {VF, MaxVFTimes2};
1654     auto Plan = buildVPlan(SubRange);
1655     VPlanTransforms::optimize(*Plan);
1656     VPlans.push_back(std::move(Plan));
1657     VF = SubRange.End;
1658   }
1659 }
1660 
1661 VPlan &LoopVectorizationPlanner::getPlanFor(ElementCount VF) const {
1662   assert(count_if(VPlans,
1663                   [VF](const VPlanPtr &Plan) { return Plan->hasVF(VF); }) ==
1664              1 &&
1665          "Multiple VPlans for VF.");
1666 
1667   for (const VPlanPtr &Plan : VPlans) {
1668     if (Plan->hasVF(VF))
1669       return *Plan.get();
1670   }
1671   llvm_unreachable("No plan found!");
1672 }
1673 
1674 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1675 void LoopVectorizationPlanner::printPlans(raw_ostream &O) {
1676   if (VPlans.empty()) {
1677     O << "LV: No VPlans built.\n";
1678     return;
1679   }
1680   for (const auto &Plan : VPlans)
1681     if (PrintVPlansInDotFormat)
1682       Plan->printDOT(O);
1683     else
1684       Plan->print(O);
1685 }
1686 #endif
1687