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