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