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