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