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