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