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