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