xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 52f3714dae7b23ba734a449623cb1570c6c1b700)
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 "VPlanDominatorTree.h"
21 #include "llvm/ADT/DepthFirstIterator.h"
22 #include "llvm/ADT/PostOrderIterator.h"
23 #include "llvm/ADT/SmallVector.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/GenericDomTreeConstruction.h"
38 #include "llvm/Support/GraphWriter.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
41 #include <cassert>
42 #include <iterator>
43 #include <string>
44 #include <vector>
45 
46 using namespace llvm;
47 extern cl::opt<bool> EnableVPlanNativePath;
48 
49 #define DEBUG_TYPE "vplan"
50 
51 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
52   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
53   VPSlotTracker SlotTracker(
54       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
55   V.print(OS, SlotTracker);
56   return OS;
57 }
58 
59 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
60     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
61   if (Def)
62     Def->addDefinedValue(this);
63 }
64 
65 VPValue::~VPValue() {
66   assert(Users.empty() && "trying to delete a VPValue with remaining users");
67   if (Def)
68     Def->removeDefinedValue(this);
69 }
70 
71 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
72   if (const VPInstruction *Instr = dyn_cast<VPInstruction>(this))
73     Instr->print(OS, SlotTracker);
74   else
75     printAsOperand(OS, SlotTracker);
76 }
77 
78 void VPValue::dump() const {
79   const VPInstruction *Instr = dyn_cast<VPInstruction>(this);
80   VPSlotTracker SlotTracker(
81       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
82   print(dbgs(), SlotTracker);
83   dbgs() << "\n";
84 }
85 
86 void VPRecipeBase::dump() const {
87   VPSlotTracker SlotTracker(nullptr);
88   print(dbgs(), "", SlotTracker);
89   dbgs() << "\n";
90 }
91 
92 VPUser *VPRecipeBase::toVPUser() {
93   if (auto *U = dyn_cast<VPInstruction>(this))
94     return U;
95   if (auto *U = dyn_cast<VPWidenRecipe>(this))
96     return U;
97   if (auto *U = dyn_cast<VPWidenCallRecipe>(this))
98     return U;
99   if (auto *U = dyn_cast<VPWidenSelectRecipe>(this))
100     return U;
101   if (auto *U = dyn_cast<VPWidenGEPRecipe>(this))
102     return U;
103   if (auto *U = dyn_cast<VPBlendRecipe>(this))
104     return U;
105   if (auto *U = dyn_cast<VPInterleaveRecipe>(this))
106     return U;
107   if (auto *U = dyn_cast<VPReplicateRecipe>(this))
108     return U;
109   if (auto *U = dyn_cast<VPBranchOnMaskRecipe>(this))
110     return U;
111   if (auto *U = dyn_cast<VPWidenMemoryInstructionRecipe>(this))
112     return U;
113   return nullptr;
114 }
115 
116 VPValue *VPRecipeBase::toVPValue() {
117   if (auto *V = dyn_cast<VPInstruction>(this))
118     return V;
119   if (auto *V = dyn_cast<VPWidenMemoryInstructionRecipe>(this))
120     return V;
121   if (auto *V = dyn_cast<VPWidenCallRecipe>(this))
122     return V;
123   if (auto *V = dyn_cast<VPWidenSelectRecipe>(this))
124     return V;
125   if (auto *V = dyn_cast<VPWidenGEPRecipe>(this))
126     return V;
127   return nullptr;
128 }
129 
130 const VPValue *VPRecipeBase::toVPValue() const {
131   if (auto *V = dyn_cast<VPInstruction>(this))
132     return V;
133   if (auto *V = dyn_cast<VPWidenMemoryInstructionRecipe>(this))
134     return V;
135   if (auto *V = dyn_cast<VPWidenCallRecipe>(this))
136     return V;
137   if (auto *V = dyn_cast<VPWidenSelectRecipe>(this))
138     return V;
139   if (auto *V = dyn_cast<VPWidenGEPRecipe>(this))
140     return V;
141   return nullptr;
142 }
143 
144 // Get the top-most entry block of \p Start. This is the entry block of the
145 // containing VPlan. This function is templated to support both const and non-const blocks
146 template <typename T> static T *getPlanEntry(T *Start) {
147   T *Next = Start;
148   T *Current = Start;
149   while ((Next = Next->getParent()))
150     Current = Next;
151 
152   SmallSetVector<T *, 8> WorkList;
153   WorkList.insert(Current);
154 
155   for (unsigned i = 0; i < WorkList.size(); i++) {
156     T *Current = WorkList[i];
157     if (Current->getNumPredecessors() == 0)
158       return Current;
159     auto &Predecessors = Current->getPredecessors();
160     WorkList.insert(Predecessors.begin(), Predecessors.end());
161   }
162 
163   llvm_unreachable("VPlan without any entry node without predecessors");
164 }
165 
166 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
167 
168 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
169 
170 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
171 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
172   const VPBlockBase *Block = this;
173   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
174     Block = Region->getEntry();
175   return cast<VPBasicBlock>(Block);
176 }
177 
178 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
179   VPBlockBase *Block = this;
180   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
181     Block = Region->getEntry();
182   return cast<VPBasicBlock>(Block);
183 }
184 
185 void VPBlockBase::setPlan(VPlan *ParentPlan) {
186   assert(ParentPlan->getEntry() == this &&
187          "Can only set plan on its entry block.");
188   Plan = ParentPlan;
189 }
190 
191 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
192 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
193   const VPBlockBase *Block = this;
194   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
195     Block = Region->getExit();
196   return cast<VPBasicBlock>(Block);
197 }
198 
199 VPBasicBlock *VPBlockBase::getExitBasicBlock() {
200   VPBlockBase *Block = this;
201   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
202     Block = Region->getExit();
203   return cast<VPBasicBlock>(Block);
204 }
205 
206 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
207   if (!Successors.empty() || !Parent)
208     return this;
209   assert(Parent->getExit() == this &&
210          "Block w/o successors not the exit of its parent.");
211   return Parent->getEnclosingBlockWithSuccessors();
212 }
213 
214 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
215   if (!Predecessors.empty() || !Parent)
216     return this;
217   assert(Parent->getEntry() == this &&
218          "Block w/o predecessors not the entry of its parent.");
219   return Parent->getEnclosingBlockWithPredecessors();
220 }
221 
222 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
223   SmallVector<VPBlockBase *, 8> Blocks;
224 
225   VPValue DummyValue;
226   for (VPBlockBase *Block : depth_first(Entry)) {
227     // Drop all references in VPBasicBlocks and replace all uses with
228     // DummyValue.
229     if (auto *VPBB = dyn_cast<VPBasicBlock>(Block))
230       VPBB->dropAllReferences(&DummyValue);
231     Blocks.push_back(Block);
232   }
233 
234   for (VPBlockBase *Block : Blocks)
235     delete Block;
236 }
237 
238 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
239   iterator It = begin();
240   while (It != end() && (isa<VPWidenPHIRecipe>(&*It) ||
241                          isa<VPWidenIntOrFpInductionRecipe>(&*It) ||
242                          isa<VPPredInstPHIRecipe>(&*It) ||
243                          isa<VPWidenCanonicalIVRecipe>(&*It)))
244     It++;
245   return It;
246 }
247 
248 BasicBlock *
249 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
250   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
251   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
252   BasicBlock *PrevBB = CFG.PrevBB;
253   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
254                                          PrevBB->getParent(), CFG.LastBB);
255   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
256 
257   // Hook up the new basic block to its predecessors.
258   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
259     VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
260     auto &PredVPSuccessors = PredVPBB->getSuccessors();
261     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
262 
263     // In outer loop vectorization scenario, the predecessor BBlock may not yet
264     // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
265     // vectorization. We do not encounter this case in inner loop vectorization
266     // as we start out by building a loop skeleton with the vector loop header
267     // and latch blocks. As a result, we never enter this function for the
268     // header block in the non VPlan-native path.
269     if (!PredBB) {
270       assert(EnableVPlanNativePath &&
271              "Unexpected null predecessor in non VPlan-native path");
272       CFG.VPBBsToFix.push_back(PredVPBB);
273       continue;
274     }
275 
276     assert(PredBB && "Predecessor basic-block not found building successor.");
277     auto *PredBBTerminator = PredBB->getTerminator();
278     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
279     if (isa<UnreachableInst>(PredBBTerminator)) {
280       assert(PredVPSuccessors.size() == 1 &&
281              "Predecessor ending w/o branch must have single successor.");
282       PredBBTerminator->eraseFromParent();
283       BranchInst::Create(NewBB, PredBB);
284     } else {
285       assert(PredVPSuccessors.size() == 2 &&
286              "Predecessor ending with branch must have two successors.");
287       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
288       assert(!PredBBTerminator->getSuccessor(idx) &&
289              "Trying to reset an existing successor block.");
290       PredBBTerminator->setSuccessor(idx, NewBB);
291     }
292   }
293   return NewBB;
294 }
295 
296 void VPBasicBlock::execute(VPTransformState *State) {
297   bool Replica = State->Instance &&
298                  !(State->Instance->Part == 0 && State->Instance->Lane == 0);
299   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
300   VPBlockBase *SingleHPred = nullptr;
301   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
302 
303   // 1. Create an IR basic block, or reuse the last one if possible.
304   // The last IR basic block is reused, as an optimization, in three cases:
305   // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
306   // B. when the current VPBB has a single (hierarchical) predecessor which
307   //    is PrevVPBB and the latter has a single (hierarchical) successor; and
308   // C. when the current VPBB is an entry of a region replica - where PrevVPBB
309   //    is the exit of this region from a previous instance, or the predecessor
310   //    of this region.
311   if (PrevVPBB && /* A */
312       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
313         SingleHPred->getExitBasicBlock() == PrevVPBB &&
314         PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
315       !(Replica && getPredecessors().empty())) {       /* C */
316     NewBB = createEmptyBasicBlock(State->CFG);
317     State->Builder.SetInsertPoint(NewBB);
318     // Temporarily terminate with unreachable until CFG is rewired.
319     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
320     State->Builder.SetInsertPoint(Terminator);
321     // Register NewBB in its loop. In innermost loops its the same for all BB's.
322     Loop *L = State->LI->getLoopFor(State->CFG.LastBB);
323     L->addBasicBlockToLoop(NewBB, *State->LI);
324     State->CFG.PrevBB = NewBB;
325   }
326 
327   // 2. Fill the IR basic block with IR instructions.
328   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
329                     << " in BB:" << NewBB->getName() << '\n');
330 
331   State->CFG.VPBB2IRBB[this] = NewBB;
332   State->CFG.PrevVPBB = this;
333 
334   for (VPRecipeBase &Recipe : Recipes)
335     Recipe.execute(*State);
336 
337   VPValue *CBV;
338   if (EnableVPlanNativePath && (CBV = getCondBit())) {
339     Value *IRCBV = CBV->getUnderlyingValue();
340     assert(IRCBV && "Unexpected null underlying value for condition bit");
341 
342     // Condition bit value in a VPBasicBlock is used as the branch selector. In
343     // the VPlan-native path case, since all branches are uniform we generate a
344     // branch instruction using the condition value from vector lane 0 and dummy
345     // successors. The successors are fixed later when the successor blocks are
346     // visited.
347     Value *NewCond = State->Callback.getOrCreateVectorValues(IRCBV, 0);
348     NewCond = State->Builder.CreateExtractElement(NewCond,
349                                                   State->Builder.getInt32(0));
350 
351     // Replace the temporary unreachable terminator with the new conditional
352     // branch.
353     auto *CurrentTerminator = NewBB->getTerminator();
354     assert(isa<UnreachableInst>(CurrentTerminator) &&
355            "Expected to replace unreachable terminator with conditional "
356            "branch.");
357     auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
358     CondBr->setSuccessor(0, nullptr);
359     ReplaceInstWithInst(CurrentTerminator, CondBr);
360   }
361 
362   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
363 }
364 
365 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
366   for (VPRecipeBase &R : Recipes) {
367     if (auto *VPV = R.toVPValue())
368       VPV->replaceAllUsesWith(NewValue);
369 
370     if (auto *User = R.toVPUser())
371       for (unsigned I = 0, E = User->getNumOperands(); I != E; I++)
372         User->setOperand(I, NewValue);
373   }
374 }
375 
376 void VPRegionBlock::execute(VPTransformState *State) {
377   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
378 
379   if (!isReplicator()) {
380     // Visit the VPBlocks connected to "this", starting from it.
381     for (VPBlockBase *Block : RPOT) {
382       if (EnableVPlanNativePath) {
383         // The inner loop vectorization path does not represent loop preheader
384         // and exit blocks as part of the VPlan. In the VPlan-native path, skip
385         // vectorizing loop preheader block. In future, we may replace this
386         // check with the check for loop preheader.
387         if (Block->getNumPredecessors() == 0)
388           continue;
389 
390         // Skip vectorizing loop exit block. In future, we may replace this
391         // check with the check for loop exit.
392         if (Block->getNumSuccessors() == 0)
393           continue;
394       }
395 
396       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
397       Block->execute(State);
398     }
399     return;
400   }
401 
402   assert(!State->Instance && "Replicating a Region with non-null instance.");
403 
404   // Enter replicating mode.
405   State->Instance = {0, 0};
406 
407   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
408     State->Instance->Part = Part;
409     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
410     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
411          ++Lane) {
412       State->Instance->Lane = Lane;
413       // Visit the VPBlocks connected to \p this, starting from it.
414       for (VPBlockBase *Block : RPOT) {
415         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
416         Block->execute(State);
417       }
418     }
419   }
420 
421   // Exit replicating mode.
422   State->Instance.reset();
423 }
424 
425 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
426   assert(!Parent && "Recipe already in some VPBasicBlock");
427   assert(InsertPos->getParent() &&
428          "Insertion position not in any VPBasicBlock");
429   Parent = InsertPos->getParent();
430   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
431 }
432 
433 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
434   assert(!Parent && "Recipe already in some VPBasicBlock");
435   assert(InsertPos->getParent() &&
436          "Insertion position not in any VPBasicBlock");
437   Parent = InsertPos->getParent();
438   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
439 }
440 
441 void VPRecipeBase::removeFromParent() {
442   assert(getParent() && "Recipe not in any VPBasicBlock");
443   getParent()->getRecipeList().remove(getIterator());
444   Parent = nullptr;
445 }
446 
447 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
448   assert(getParent() && "Recipe not in any VPBasicBlock");
449   return getParent()->getRecipeList().erase(getIterator());
450 }
451 
452 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
453   removeFromParent();
454   insertAfter(InsertPos);
455 }
456 
457 void VPInstruction::generateInstruction(VPTransformState &State,
458                                         unsigned Part) {
459   IRBuilder<> &Builder = State.Builder;
460 
461   if (Instruction::isBinaryOp(getOpcode())) {
462     Value *A = State.get(getOperand(0), Part);
463     Value *B = State.get(getOperand(1), Part);
464     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
465     State.set(this, V, Part);
466     return;
467   }
468 
469   switch (getOpcode()) {
470   case VPInstruction::Not: {
471     Value *A = State.get(getOperand(0), Part);
472     Value *V = Builder.CreateNot(A);
473     State.set(this, V, Part);
474     break;
475   }
476   case VPInstruction::ICmpULE: {
477     Value *IV = State.get(getOperand(0), Part);
478     Value *TC = State.get(getOperand(1), Part);
479     Value *V = Builder.CreateICmpULE(IV, TC);
480     State.set(this, V, Part);
481     break;
482   }
483   case Instruction::Select: {
484     Value *Cond = State.get(getOperand(0), Part);
485     Value *Op1 = State.get(getOperand(1), Part);
486     Value *Op2 = State.get(getOperand(2), Part);
487     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
488     State.set(this, V, Part);
489     break;
490   }
491   case VPInstruction::ActiveLaneMask: {
492     // Get first lane of vector induction variable.
493     Value *VIVElem0 = State.get(getOperand(0), {Part, 0});
494     // Get the original loop tripcount.
495     Value *ScalarTC = State.TripCount;
496 
497     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
498     auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue());
499     Instruction *Call = Builder.CreateIntrinsic(
500         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
501         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
502     State.set(this, Call, Part);
503     break;
504   }
505   default:
506     llvm_unreachable("Unsupported opcode for instruction");
507   }
508 }
509 
510 void VPInstruction::execute(VPTransformState &State) {
511   assert(!State.Instance && "VPInstruction executing an Instance");
512   for (unsigned Part = 0; Part < State.UF; ++Part)
513     generateInstruction(State, Part);
514 }
515 
516 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
517                           VPSlotTracker &SlotTracker) const {
518   O << "\"EMIT ";
519   print(O, SlotTracker);
520 }
521 
522 void VPInstruction::print(raw_ostream &O) const {
523   VPSlotTracker SlotTracker(getParent()->getPlan());
524   print(O, SlotTracker);
525 }
526 
527 void VPInstruction::print(raw_ostream &O, VPSlotTracker &SlotTracker) const {
528   if (hasResult()) {
529     printAsOperand(O, SlotTracker);
530     O << " = ";
531   }
532 
533   switch (getOpcode()) {
534   case VPInstruction::Not:
535     O << "not";
536     break;
537   case VPInstruction::ICmpULE:
538     O << "icmp ule";
539     break;
540   case VPInstruction::SLPLoad:
541     O << "combined load";
542     break;
543   case VPInstruction::SLPStore:
544     O << "combined store";
545     break;
546   case VPInstruction::ActiveLaneMask:
547     O << "active lane mask";
548     break;
549 
550   default:
551     O << Instruction::getOpcodeName(getOpcode());
552   }
553 
554   for (const VPValue *Operand : operands()) {
555     O << " ";
556     Operand->printAsOperand(O, SlotTracker);
557   }
558 }
559 
560 /// Generate the code inside the body of the vectorized loop. Assumes a single
561 /// LoopVectorBody basic-block was created for this. Introduce additional
562 /// basic-blocks as needed, and fill them all.
563 void VPlan::execute(VPTransformState *State) {
564   // -1. Check if the backedge taken count is needed, and if so build it.
565   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
566     Value *TC = State->TripCount;
567     IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
568     auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
569                                    "trip.count.minus.1");
570     auto VF = State->VF;
571     Value *VTCMO =
572         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
573     for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part)
574       State->set(BackedgeTakenCount, VTCMO, Part);
575   }
576 
577   // 0. Set the reverse mapping from VPValues to Values for code generation.
578   for (auto &Entry : Value2VPValue)
579     State->VPValue2Value[Entry.second] = Entry.first;
580 
581   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
582   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
583   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
584 
585   // 1. Make room to generate basic-blocks inside loop body if needed.
586   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
587       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
588   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
589   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
590   // Remove the edge between Header and Latch to allow other connections.
591   // Temporarily terminate with unreachable until CFG is rewired.
592   // Note: this asserts the generated code's assumption that
593   // getFirstInsertionPt() can be dereferenced into an Instruction.
594   VectorHeaderBB->getTerminator()->eraseFromParent();
595   State->Builder.SetInsertPoint(VectorHeaderBB);
596   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
597   State->Builder.SetInsertPoint(Terminator);
598 
599   // 2. Generate code in loop body.
600   State->CFG.PrevVPBB = nullptr;
601   State->CFG.PrevBB = VectorHeaderBB;
602   State->CFG.LastBB = VectorLatchBB;
603 
604   for (VPBlockBase *Block : depth_first(Entry))
605     Block->execute(State);
606 
607   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
608   // VPBB's successors.
609   for (auto VPBB : State->CFG.VPBBsToFix) {
610     assert(EnableVPlanNativePath &&
611            "Unexpected VPBBsToFix in non VPlan-native path");
612     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
613     assert(BB && "Unexpected null basic block for VPBB");
614 
615     unsigned Idx = 0;
616     auto *BBTerminator = BB->getTerminator();
617 
618     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
619       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
620       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
621       ++Idx;
622     }
623   }
624 
625   // 3. Merge the temporary latch created with the last basic-block filled.
626   BasicBlock *LastBB = State->CFG.PrevBB;
627   // Connect LastBB to VectorLatchBB to facilitate their merge.
628   assert((EnableVPlanNativePath ||
629           isa<UnreachableInst>(LastBB->getTerminator())) &&
630          "Expected InnerLoop VPlan CFG to terminate with unreachable");
631   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
632          "Expected VPlan CFG to terminate with branch in NativePath");
633   LastBB->getTerminator()->eraseFromParent();
634   BranchInst::Create(VectorLatchBB, LastBB);
635 
636   // Merge LastBB with Latch.
637   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
638   (void)Merged;
639   assert(Merged && "Could not merge last basic block with latch.");
640   VectorLatchBB = LastBB;
641 
642   // We do not attempt to preserve DT for outer loop vectorization currently.
643   if (!EnableVPlanNativePath)
644     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
645                         L->getExitBlock());
646 }
647 
648 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
649 LLVM_DUMP_METHOD
650 void VPlan::dump() const { dbgs() << *this << '\n'; }
651 #endif
652 
653 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
654                                 BasicBlock *LoopLatchBB,
655                                 BasicBlock *LoopExitBB) {
656   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
657   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
658   // The vector body may be more than a single basic-block by this point.
659   // Update the dominator tree information inside the vector body by propagating
660   // it from header to latch, expecting only triangular control-flow, if any.
661   BasicBlock *PostDomSucc = nullptr;
662   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
663     // Get the list of successors of this block.
664     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
665     assert(Succs.size() <= 2 &&
666            "Basic block in vector loop has more than 2 successors.");
667     PostDomSucc = Succs[0];
668     if (Succs.size() == 1) {
669       assert(PostDomSucc->getSinglePredecessor() &&
670              "PostDom successor has more than one predecessor.");
671       DT->addNewBlock(PostDomSucc, BB);
672       continue;
673     }
674     BasicBlock *InterimSucc = Succs[1];
675     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
676       PostDomSucc = Succs[1];
677       InterimSucc = Succs[0];
678     }
679     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
680            "One successor of a basic block does not lead to the other.");
681     assert(InterimSucc->getSinglePredecessor() &&
682            "Interim successor has more than one predecessor.");
683     assert(PostDomSucc->hasNPredecessors(2) &&
684            "PostDom successor has more than two predecessors.");
685     DT->addNewBlock(InterimSucc, BB);
686     DT->addNewBlock(PostDomSucc, BB);
687   }
688   // Latch block is a new dominator for the loop exit.
689   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
690   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
691 }
692 
693 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
694   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
695          Twine(getOrCreateBID(Block));
696 }
697 
698 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
699   const std::string &Name = Block->getName();
700   if (!Name.empty())
701     return Name;
702   return "VPB" + Twine(getOrCreateBID(Block));
703 }
704 
705 void VPlanPrinter::dump() {
706   Depth = 1;
707   bumpIndent(0);
708   OS << "digraph VPlan {\n";
709   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
710   if (!Plan.getName().empty())
711     OS << "\\n" << DOT::EscapeString(Plan.getName());
712   if (Plan.BackedgeTakenCount) {
713     OS << ", where:\\n";
714     Plan.BackedgeTakenCount->print(OS, SlotTracker);
715     OS << " := BackedgeTakenCount";
716   }
717   OS << "\"]\n";
718   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
719   OS << "edge [fontname=Courier, fontsize=30]\n";
720   OS << "compound=true\n";
721 
722   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
723     dumpBlock(Block);
724 
725   OS << "}\n";
726 }
727 
728 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
729   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
730     dumpBasicBlock(BasicBlock);
731   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
732     dumpRegion(Region);
733   else
734     llvm_unreachable("Unsupported kind of VPBlock.");
735 }
736 
737 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
738                             bool Hidden, const Twine &Label) {
739   // Due to "dot" we print an edge between two regions as an edge between the
740   // exit basic block and the entry basic of the respective regions.
741   const VPBlockBase *Tail = From->getExitBasicBlock();
742   const VPBlockBase *Head = To->getEntryBasicBlock();
743   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
744   OS << " [ label=\"" << Label << '\"';
745   if (Tail != From)
746     OS << " ltail=" << getUID(From);
747   if (Head != To)
748     OS << " lhead=" << getUID(To);
749   if (Hidden)
750     OS << "; splines=none";
751   OS << "]\n";
752 }
753 
754 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
755   auto &Successors = Block->getSuccessors();
756   if (Successors.size() == 1)
757     drawEdge(Block, Successors.front(), false, "");
758   else if (Successors.size() == 2) {
759     drawEdge(Block, Successors.front(), false, "T");
760     drawEdge(Block, Successors.back(), false, "F");
761   } else {
762     unsigned SuccessorNumber = 0;
763     for (auto *Successor : Successors)
764       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
765   }
766 }
767 
768 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
769   OS << Indent << getUID(BasicBlock) << " [label =\n";
770   bumpIndent(1);
771   OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
772   bumpIndent(1);
773 
774   // Dump the block predicate.
775   const VPValue *Pred = BasicBlock->getPredicate();
776   if (Pred) {
777     OS << " +\n" << Indent << " \"BlockPredicate: ";
778     if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) {
779       PredI->printAsOperand(OS, SlotTracker);
780       OS << " (" << DOT::EscapeString(PredI->getParent()->getName())
781          << ")\\l\"";
782     } else
783       Pred->printAsOperand(OS, SlotTracker);
784   }
785 
786   for (const VPRecipeBase &Recipe : *BasicBlock) {
787     OS << " +\n" << Indent;
788     Recipe.print(OS, Indent, SlotTracker);
789     OS << "\\l\"";
790   }
791 
792   // Dump the condition bit.
793   const VPValue *CBV = BasicBlock->getCondBit();
794   if (CBV) {
795     OS << " +\n" << Indent << " \"CondBit: ";
796     if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
797       CBI->printAsOperand(OS, SlotTracker);
798       OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
799     } else {
800       CBV->printAsOperand(OS, SlotTracker);
801       OS << "\"";
802     }
803   }
804 
805   bumpIndent(-2);
806   OS << "\n" << Indent << "]\n";
807   dumpEdges(BasicBlock);
808 }
809 
810 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
811   OS << Indent << "subgraph " << getUID(Region) << " {\n";
812   bumpIndent(1);
813   OS << Indent << "fontname=Courier\n"
814      << Indent << "label=\""
815      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
816      << DOT::EscapeString(Region->getName()) << "\"\n";
817   // Dump the blocks of the region.
818   assert(Region->getEntry() && "Region contains no inner blocks.");
819   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
820     dumpBlock(Block);
821   bumpIndent(-1);
822   OS << Indent << "}\n";
823   dumpEdges(Region);
824 }
825 
826 void VPlanPrinter::printAsIngredient(raw_ostream &O, const Value *V) {
827   std::string IngredientString;
828   raw_string_ostream RSO(IngredientString);
829   if (auto *Inst = dyn_cast<Instruction>(V)) {
830     if (!Inst->getType()->isVoidTy()) {
831       Inst->printAsOperand(RSO, false);
832       RSO << " = ";
833     }
834     RSO << Inst->getOpcodeName() << " ";
835     unsigned E = Inst->getNumOperands();
836     if (E > 0) {
837       Inst->getOperand(0)->printAsOperand(RSO, false);
838       for (unsigned I = 1; I < E; ++I)
839         Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
840     }
841   } else // !Inst
842     V->printAsOperand(RSO, false);
843   RSO.flush();
844   O << DOT::EscapeString(IngredientString);
845 }
846 
847 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
848                               VPSlotTracker &SlotTracker) const {
849   O << "\"WIDEN-CALL ";
850 
851   auto *CI = cast<CallInst>(getUnderlyingInstr());
852   if (CI->getType()->isVoidTy())
853     O << "void ";
854   else {
855     printAsOperand(O, SlotTracker);
856     O << " = ";
857   }
858 
859   O << "call @" << CI->getCalledFunction()->getName() << "(";
860   printOperands(O, SlotTracker);
861   O << ")";
862 }
863 
864 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
865                                 VPSlotTracker &SlotTracker) const {
866   O << "\"WIDEN-SELECT ";
867   printAsOperand(O, SlotTracker);
868   O << " = select ";
869   getOperand(0)->printAsOperand(O, SlotTracker);
870   O << ", ";
871   getOperand(1)->printAsOperand(O, SlotTracker);
872   O << ", ";
873   getOperand(2)->printAsOperand(O, SlotTracker);
874   O << (InvariantCond ? " (condition is loop invariant)" : "");
875 }
876 
877 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
878                           VPSlotTracker &SlotTracker) const {
879   O << "\"WIDEN\\l\"";
880   O << "\"  " << VPlanIngredient(&Ingredient);
881 }
882 
883 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
884                                           VPSlotTracker &SlotTracker) const {
885   O << "\"WIDEN-INDUCTION";
886   if (Trunc) {
887     O << "\\l\"";
888     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
889     O << " +\n" << Indent << "\"  " << VPlanIngredient(Trunc);
890   } else
891     O << " " << VPlanIngredient(IV);
892 }
893 
894 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
895                              VPSlotTracker &SlotTracker) const {
896   O << "\"WIDEN-GEP ";
897   O << (IsPtrLoopInvariant ? "Inv" : "Var");
898   size_t IndicesNumber = IsIndexLoopInvariant.size();
899   for (size_t I = 0; I < IndicesNumber; ++I)
900     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
901 
902   O << " ";
903   printAsOperand(O, SlotTracker);
904   O << " = getelementptr ";
905   printOperands(O, SlotTracker);
906 }
907 
908 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
909                              VPSlotTracker &SlotTracker) const {
910   O << "\"WIDEN-PHI " << VPlanIngredient(Phi);
911 }
912 
913 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
914                           VPSlotTracker &SlotTracker) const {
915   O << "\"BLEND ";
916   Phi->printAsOperand(O, false);
917   O << " =";
918   if (getNumIncomingValues() == 1) {
919     // Not a User of any mask: not really blending, this is a
920     // single-predecessor phi.
921     O << " ";
922     getIncomingValue(0)->printAsOperand(O, SlotTracker);
923   } else {
924     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
925       O << " ";
926       getIncomingValue(I)->printAsOperand(O, SlotTracker);
927       O << "/";
928       getMask(I)->printAsOperand(O, SlotTracker);
929     }
930   }
931 }
932 
933 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
934                               VPSlotTracker &SlotTracker) const {
935   O << "\"REDUCE of" << *I << " as ";
936   ChainOp->printAsOperand(O, SlotTracker);
937   O << " + reduce(";
938   VecOp->printAsOperand(O, SlotTracker);
939   if (CondOp) {
940     O << ", ";
941     CondOp->printAsOperand(O, SlotTracker);
942   }
943   O << ")";
944 }
945 
946 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
947                               VPSlotTracker &SlotTracker) const {
948   O << "\"" << (IsUniform ? "CLONE " : "REPLICATE ")
949     << VPlanIngredient(Ingredient);
950   if (AlsoPack)
951     O << " (S->V)";
952 }
953 
954 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
955                                 VPSlotTracker &SlotTracker) const {
956   O << "\"PHI-PREDICATED-INSTRUCTION " << VPlanIngredient(PredInst);
957 }
958 
959 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
960                                            VPSlotTracker &SlotTracker) const {
961   O << "\"WIDEN ";
962 
963   if (!isStore()) {
964     printAsOperand(O, SlotTracker);
965     O << " = ";
966   }
967   O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
968 
969   printOperands(O, SlotTracker);
970 }
971 
972 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
973   Value *CanonicalIV = State.CanonicalIV;
974   Type *STy = CanonicalIV->getType();
975   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
976   ElementCount VF = State.VF;
977   assert(!VF.isScalable() && "the code following assumes non scalables ECs");
978   Value *VStart = VF.isScalar()
979                       ? CanonicalIV
980                       : Builder.CreateVectorSplat(VF.getKnownMinValue(),
981                                                   CanonicalIV, "broadcast");
982   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
983     SmallVector<Constant *, 8> Indices;
984     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
985       Indices.push_back(
986           ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane));
987     // If VF == 1, there is only one iteration in the loop above, thus the
988     // element pushed back into Indices is ConstantInt::get(STy, Part)
989     Constant *VStep =
990         VF.isScalar() ? Indices.back() : ConstantVector::get(Indices);
991     // Add the consecutive indices to the vector value.
992     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
993     State.set(getVPValue(), CanonicalVectorIV, Part);
994   }
995 }
996 
997 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
998                                      VPSlotTracker &SlotTracker) const {
999   O << "\"EMIT ";
1000   getVPValue()->printAsOperand(O, SlotTracker);
1001   O << " = WIDEN-CANONICAL-INDUCTION";
1002 }
1003 
1004 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1005 
1006 void VPValue::replaceAllUsesWith(VPValue *New) {
1007   for (unsigned J = 0; J < getNumUsers();) {
1008     VPUser *User = Users[J];
1009     unsigned NumUsers = getNumUsers();
1010     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1011       if (User->getOperand(I) == this)
1012         User->setOperand(I, New);
1013     // If a user got removed after updating the current user, the next user to
1014     // update will be moved to the current position, so we only need to
1015     // increment the index if the number of users did not change.
1016     if (NumUsers == getNumUsers())
1017       J++;
1018   }
1019 }
1020 
1021 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1022   if (const Value *UV = getUnderlyingValue()) {
1023     OS << "ir<";
1024     UV->printAsOperand(OS, false);
1025     OS << ">";
1026     return;
1027   }
1028 
1029   unsigned Slot = Tracker.getSlot(this);
1030   if (Slot == unsigned(-1))
1031     OS << "<badref>";
1032   else
1033     OS << "vp<%" << Tracker.getSlot(this) << ">";
1034 }
1035 
1036 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1037   bool First = true;
1038   for (VPValue *Op : operands()) {
1039     if (!First)
1040       O << ", ";
1041     Op->printAsOperand(O, SlotTracker);
1042     First = false;
1043   }
1044 }
1045 
1046 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1047                                           Old2NewTy &Old2New,
1048                                           InterleavedAccessInfo &IAI) {
1049   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1050   for (VPBlockBase *Base : RPOT) {
1051     visitBlock(Base, Old2New, IAI);
1052   }
1053 }
1054 
1055 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1056                                          InterleavedAccessInfo &IAI) {
1057   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1058     for (VPRecipeBase &VPI : *VPBB) {
1059       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1060       auto *VPInst = cast<VPInstruction>(&VPI);
1061       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
1062       auto *IG = IAI.getInterleaveGroup(Inst);
1063       if (!IG)
1064         continue;
1065 
1066       auto NewIGIter = Old2New.find(IG);
1067       if (NewIGIter == Old2New.end())
1068         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1069             IG->getFactor(), IG->isReverse(), IG->getAlign());
1070 
1071       if (Inst == IG->getInsertPos())
1072         Old2New[IG]->setInsertPos(VPInst);
1073 
1074       InterleaveGroupMap[VPInst] = Old2New[IG];
1075       InterleaveGroupMap[VPInst]->insertMember(
1076           VPInst, IG->getIndex(Inst),
1077           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1078                                 : IG->getFactor()));
1079     }
1080   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1081     visitRegion(Region, Old2New, IAI);
1082   else
1083     llvm_unreachable("Unsupported kind of VPBlock.");
1084 }
1085 
1086 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1087                                                  InterleavedAccessInfo &IAI) {
1088   Old2NewTy Old2New;
1089   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
1090 }
1091 
1092 void VPSlotTracker::assignSlot(const VPValue *V) {
1093   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1094   const Value *UV = V->getUnderlyingValue();
1095   if (UV)
1096     return;
1097   const auto *VPI = dyn_cast<VPInstruction>(V);
1098   if (VPI && !VPI->hasResult())
1099     return;
1100 
1101   Slots[V] = NextSlot++;
1102 }
1103 
1104 void VPSlotTracker::assignSlots(const VPBlockBase *VPBB) {
1105   if (auto *Region = dyn_cast<VPRegionBlock>(VPBB))
1106     assignSlots(Region);
1107   else
1108     assignSlots(cast<VPBasicBlock>(VPBB));
1109 }
1110 
1111 void VPSlotTracker::assignSlots(const VPRegionBlock *Region) {
1112   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Region->getEntry());
1113   for (const VPBlockBase *Block : RPOT)
1114     assignSlots(Block);
1115 }
1116 
1117 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
1118   for (const VPRecipeBase &Recipe : *VPBB) {
1119     if (const auto *VPI = dyn_cast<VPInstruction>(&Recipe))
1120       assignSlot(VPI);
1121     else if (const auto *VPIV = dyn_cast<VPWidenCanonicalIVRecipe>(&Recipe))
1122       assignSlot(VPIV->getVPValue());
1123   }
1124 }
1125 
1126 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1127 
1128   for (const VPValue *V : Plan.VPExternalDefs)
1129     assignSlot(V);
1130 
1131   for (auto &E : Plan.Value2VPValue)
1132     if (!isa<VPInstruction>(E.second))
1133       assignSlot(E.second);
1134 
1135   for (const VPValue *V : Plan.VPCBVs)
1136     assignSlot(V);
1137 
1138   if (Plan.BackedgeTakenCount)
1139     assignSlot(Plan.BackedgeTakenCount);
1140 
1141   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Plan.getEntry());
1142   for (const VPBlockBase *Block : RPOT)
1143     assignSlots(Block);
1144 }
1145