xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 14e3650f01d158f7e4117c353927a07ceebdd504)
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/IRBuilder.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 "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
44 #include <cassert>
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(IRBuilderBase &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 VPValue *VPBlockBase::getCondBit() {
192   return CondBitUser.getSingleOperandOrNull();
193 }
194 
195 const VPValue *VPBlockBase::getCondBit() const {
196   return CondBitUser.getSingleOperandOrNull();
197 }
198 
199 void VPBlockBase::setCondBit(VPValue *CV) { CondBitUser.resetSingleOpUser(CV); }
200 
201 VPValue *VPBlockBase::getPredicate() {
202   return PredicateUser.getSingleOperandOrNull();
203 }
204 
205 const VPValue *VPBlockBase::getPredicate() const {
206   return PredicateUser.getSingleOperandOrNull();
207 }
208 
209 void VPBlockBase::setPredicate(VPValue *CV) {
210   PredicateUser.resetSingleOpUser(CV);
211 }
212 
213 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
214   SmallVector<VPBlockBase *, 8> Blocks(depth_first(Entry));
215 
216   for (VPBlockBase *Block : Blocks)
217     delete Block;
218 }
219 
220 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
221   iterator It = begin();
222   while (It != end() && It->isPhi())
223     It++;
224   return It;
225 }
226 
227 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
228   if (!Def->getDef())
229     return Def->getLiveInIRValue();
230 
231   if (hasScalarValue(Def, Instance)) {
232     return Data
233         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
234   }
235 
236   assert(hasVectorValue(Def, Instance.Part));
237   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
238   if (!VecPart->getType()->isVectorTy()) {
239     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
240     return VecPart;
241   }
242   // TODO: Cache created scalar values.
243   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
244   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
245   // set(Def, Extract, Instance);
246   return Extract;
247 }
248 
249 BasicBlock *
250 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
251   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
252   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
253   BasicBlock *PrevBB = CFG.PrevBB;
254   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
255                                          PrevBB->getParent(), CFG.ExitBB);
256   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
257 
258   // Hook up the new basic block to its predecessors.
259   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
260     VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
261     auto &PredVPSuccessors = PredVPBB->getSuccessors();
262     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
263 
264     // In outer loop vectorization scenario, the predecessor BBlock may not yet
265     // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
266     // vectorization. We do not encounter this case in inner loop vectorization
267     // as we start out by building a loop skeleton with the vector loop header
268     // and latch blocks. As a result, we never enter this function for the
269     // header block in the non VPlan-native path.
270     if (!PredBB) {
271       assert(EnableVPlanNativePath &&
272              "Unexpected null predecessor in non VPlan-native path");
273       CFG.VPBBsToFix.push_back(PredVPBB);
274       continue;
275     }
276 
277     assert(PredBB && "Predecessor basic-block not found building successor.");
278     auto *PredBBTerminator = PredBB->getTerminator();
279     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
280     if (isa<UnreachableInst>(PredBBTerminator)) {
281       assert(PredVPSuccessors.size() == 1 &&
282              "Predecessor ending w/o branch must have single successor.");
283       PredBBTerminator->eraseFromParent();
284       BranchInst::Create(NewBB, PredBB);
285     } else {
286       assert(PredVPSuccessors.size() == 2 &&
287              "Predecessor ending with branch must have two successors.");
288       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
289       assert(!PredBBTerminator->getSuccessor(idx) &&
290              "Trying to reset an existing successor block.");
291       PredBBTerminator->setSuccessor(idx, NewBB);
292     }
293   }
294   return NewBB;
295 }
296 
297 void VPBasicBlock::execute(VPTransformState *State) {
298   bool Replica = State->Instance && !State->Instance->isFirstIteration();
299   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
300   VPBlockBase *SingleHPred = nullptr;
301   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
302 
303   // 1. Create an IR basic block, or reuse the last one if possible.
304   // The last IR basic block is reused, as an optimization, in three cases:
305   // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
306   // B. when the current VPBB has a single (hierarchical) predecessor which
307   //    is PrevVPBB and the latter has a single (hierarchical) successor; and
308   // C. when the current VPBB is an entry of a region replica - where PrevVPBB
309   //    is the exit of this region from a previous instance, or the predecessor
310   //    of this region.
311   if (PrevVPBB && /* A */
312       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
313         SingleHPred->getExitBasicBlock() == PrevVPBB &&
314         PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
315       !(Replica && getPredecessors().empty())) {       /* C */
316     NewBB = createEmptyBasicBlock(State->CFG);
317     State->Builder.SetInsertPoint(NewBB);
318     // Temporarily terminate with unreachable until CFG is rewired.
319     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
320     State->Builder.SetInsertPoint(Terminator);
321     // Register NewBB in its loop. In innermost loops its the same for all BB's.
322     State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
323     State->CFG.PrevBB = NewBB;
324   }
325 
326   // 2. Fill the IR basic block with IR instructions.
327   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
328                     << " in BB:" << NewBB->getName() << '\n');
329 
330   State->CFG.VPBB2IRBB[this] = NewBB;
331   State->CFG.PrevVPBB = this;
332 
333   for (VPRecipeBase &Recipe : Recipes)
334     Recipe.execute(*State);
335 
336   VPValue *CBV;
337   if (EnableVPlanNativePath && (CBV = getCondBit())) {
338     assert(CBV->getUnderlyingValue() &&
339            "Unexpected null underlying value for condition bit");
340 
341     // Condition bit value in a VPBasicBlock is used as the branch selector. In
342     // the VPlan-native path case, since all branches are uniform we generate a
343     // branch instruction using the condition value from vector lane 0 and dummy
344     // successors. The successors are fixed later when the successor blocks are
345     // visited.
346     Value *NewCond = State->get(CBV, {0, 0});
347 
348     // Replace the temporary unreachable terminator with the new conditional
349     // branch.
350     auto *CurrentTerminator = NewBB->getTerminator();
351     assert(isa<UnreachableInst>(CurrentTerminator) &&
352            "Expected to replace unreachable terminator with conditional "
353            "branch.");
354     auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
355     CondBr->setSuccessor(0, nullptr);
356     ReplaceInstWithInst(CurrentTerminator, CondBr);
357   }
358 
359   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
360 }
361 
362 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
363   for (VPRecipeBase &R : Recipes) {
364     for (auto *Def : R.definedValues())
365       Def->replaceAllUsesWith(NewValue);
366 
367     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
368       R.setOperand(I, NewValue);
369   }
370 }
371 
372 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
373   assert((SplitAt == end() || SplitAt->getParent() == this) &&
374          "can only split at a position in the same block");
375 
376   SmallVector<VPBlockBase *, 2> Succs(successors());
377   // First, disconnect the current block from its successors.
378   for (VPBlockBase *Succ : Succs)
379     VPBlockUtils::disconnectBlocks(this, Succ);
380 
381   // Create new empty block after the block to split.
382   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
383   VPBlockUtils::insertBlockAfter(SplitBlock, this);
384 
385   // Add successors for block to split to new block.
386   for (VPBlockBase *Succ : Succs)
387     VPBlockUtils::connectBlocks(SplitBlock, Succ);
388 
389   // Finally, move the recipes starting at SplitAt to new block.
390   for (VPRecipeBase &ToMove :
391        make_early_inc_range(make_range(SplitAt, this->end())))
392     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
393 
394   return SplitBlock;
395 }
396 
397 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
398 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
399   if (getSuccessors().empty()) {
400     O << Indent << "No successors\n";
401   } else {
402     O << Indent << "Successor(s): ";
403     ListSeparator LS;
404     for (auto *Succ : getSuccessors())
405       O << LS << Succ->getName();
406     O << '\n';
407   }
408 }
409 
410 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
411                          VPSlotTracker &SlotTracker) const {
412   O << Indent << getName() << ":\n";
413   if (const VPValue *Pred = getPredicate()) {
414     O << Indent << "BlockPredicate:";
415     Pred->printAsOperand(O, SlotTracker);
416     if (const auto *PredInst = dyn_cast<VPInstruction>(Pred))
417       O << " (" << PredInst->getParent()->getName() << ")";
418     O << '\n';
419   }
420 
421   auto RecipeIndent = Indent + "  ";
422   for (const VPRecipeBase &Recipe : *this) {
423     Recipe.print(O, RecipeIndent, SlotTracker);
424     O << '\n';
425   }
426 
427   printSuccessors(O, Indent);
428 
429   if (const VPValue *CBV = getCondBit()) {
430     O << Indent << "CondBit: ";
431     CBV->printAsOperand(O, SlotTracker);
432     if (const auto *CBI = dyn_cast<VPInstruction>(CBV))
433       O << " (" << CBI->getParent()->getName() << ")";
434     O << '\n';
435   }
436 }
437 #endif
438 
439 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
440   for (VPBlockBase *Block : depth_first(Entry))
441     // Drop all references in VPBasicBlocks and replace all uses with
442     // DummyValue.
443     Block->dropAllReferences(NewValue);
444 }
445 
446 void VPRegionBlock::execute(VPTransformState *State) {
447   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
448 
449   if (!isReplicator()) {
450     // Visit the VPBlocks connected to "this", starting from it.
451     for (VPBlockBase *Block : RPOT) {
452       if (EnableVPlanNativePath) {
453         // The inner loop vectorization path does not represent loop preheader
454         // and exit blocks as part of the VPlan. In the VPlan-native path, skip
455         // vectorizing loop preheader block. In future, we may replace this
456         // check with the check for loop preheader.
457         if (Block->getNumPredecessors() == 0)
458           continue;
459 
460         // Skip vectorizing loop exit block. In future, we may replace this
461         // check with the check for loop exit.
462         if (Block->getNumSuccessors() == 0)
463           continue;
464       }
465 
466       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
467       Block->execute(State);
468     }
469     return;
470   }
471 
472   assert(!State->Instance && "Replicating a Region with non-null instance.");
473 
474   // Enter replicating mode.
475   State->Instance = VPIteration(0, 0);
476 
477   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
478     State->Instance->Part = Part;
479     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
480     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
481          ++Lane) {
482       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
483       // Visit the VPBlocks connected to \p this, starting from it.
484       for (VPBlockBase *Block : RPOT) {
485         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
486         Block->execute(State);
487       }
488     }
489   }
490 
491   // Exit replicating mode.
492   State->Instance.reset();
493 }
494 
495 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
496 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
497                           VPSlotTracker &SlotTracker) const {
498   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
499   auto NewIndent = Indent + "  ";
500   for (auto *BlockBase : depth_first(Entry)) {
501     O << '\n';
502     BlockBase->print(O, NewIndent, SlotTracker);
503   }
504   O << Indent << "}\n";
505 
506   printSuccessors(O, Indent);
507 }
508 #endif
509 
510 bool VPRecipeBase::mayWriteToMemory() const {
511   switch (getVPDefID()) {
512   case VPWidenMemoryInstructionSC: {
513     return cast<VPWidenMemoryInstructionRecipe>(this)->isStore();
514   }
515   case VPReplicateSC:
516   case VPWidenCallSC:
517     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
518         ->mayWriteToMemory();
519   case VPBranchOnMaskSC:
520     return false;
521   case VPWidenIntOrFpInductionSC:
522   case VPWidenCanonicalIVSC:
523   case VPWidenPHISC:
524   case VPBlendSC:
525   case VPWidenSC:
526   case VPWidenGEPSC:
527   case VPReductionSC:
528   case VPWidenSelectSC: {
529     const Instruction *I =
530         dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
531     (void)I;
532     assert((!I || !I->mayWriteToMemory()) &&
533            "underlying instruction may write to memory");
534     return false;
535   }
536   default:
537     return true;
538   }
539 }
540 
541 bool VPRecipeBase::mayReadFromMemory() const {
542   switch (getVPDefID()) {
543   case VPWidenMemoryInstructionSC: {
544     return !cast<VPWidenMemoryInstructionRecipe>(this)->isStore();
545   }
546   case VPReplicateSC:
547   case VPWidenCallSC:
548     return cast<Instruction>(getVPSingleValue()->getUnderlyingValue())
549         ->mayReadFromMemory();
550   case VPBranchOnMaskSC:
551     return false;
552   case VPWidenIntOrFpInductionSC:
553   case VPWidenCanonicalIVSC:
554   case VPWidenPHISC:
555   case VPBlendSC:
556   case VPWidenSC:
557   case VPWidenGEPSC:
558   case VPReductionSC:
559   case VPWidenSelectSC: {
560     const Instruction *I =
561         dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
562     (void)I;
563     assert((!I || !I->mayReadFromMemory()) &&
564            "underlying instruction may read from memory");
565     return false;
566   }
567   default:
568     return true;
569   }
570 }
571 
572 bool VPRecipeBase::mayHaveSideEffects() const {
573   switch (getVPDefID()) {
574   case VPBranchOnMaskSC:
575     return false;
576   case VPWidenIntOrFpInductionSC:
577   case VPWidenPointerInductionSC:
578   case VPWidenCanonicalIVSC:
579   case VPWidenPHISC:
580   case VPBlendSC:
581   case VPWidenSC:
582   case VPWidenGEPSC:
583   case VPReductionSC:
584   case VPWidenSelectSC:
585   case VPScalarIVStepsSC: {
586     const Instruction *I =
587         dyn_cast_or_null<Instruction>(getVPSingleValue()->getUnderlyingValue());
588     (void)I;
589     assert((!I || !I->mayHaveSideEffects()) &&
590            "underlying instruction has side-effects");
591     return false;
592   }
593   case VPReplicateSC: {
594     auto *R = cast<VPReplicateRecipe>(this);
595     return R->getUnderlyingInstr()->mayHaveSideEffects();
596   }
597   default:
598     return true;
599   }
600 }
601 
602 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
603   assert(!Parent && "Recipe already in some VPBasicBlock");
604   assert(InsertPos->getParent() &&
605          "Insertion position not in any VPBasicBlock");
606   Parent = InsertPos->getParent();
607   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
608 }
609 
610 void VPRecipeBase::insertBefore(VPBasicBlock &BB,
611                                 iplist<VPRecipeBase>::iterator I) {
612   assert(!Parent && "Recipe already in some VPBasicBlock");
613   assert(I == BB.end() || I->getParent() == &BB);
614   Parent = &BB;
615   BB.getRecipeList().insert(I, this);
616 }
617 
618 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
619   assert(!Parent && "Recipe already in some VPBasicBlock");
620   assert(InsertPos->getParent() &&
621          "Insertion position not in any VPBasicBlock");
622   Parent = InsertPos->getParent();
623   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
624 }
625 
626 void VPRecipeBase::removeFromParent() {
627   assert(getParent() && "Recipe not in any VPBasicBlock");
628   getParent()->getRecipeList().remove(getIterator());
629   Parent = nullptr;
630 }
631 
632 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
633   assert(getParent() && "Recipe not in any VPBasicBlock");
634   return getParent()->getRecipeList().erase(getIterator());
635 }
636 
637 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
638   removeFromParent();
639   insertAfter(InsertPos);
640 }
641 
642 void VPRecipeBase::moveBefore(VPBasicBlock &BB,
643                               iplist<VPRecipeBase>::iterator I) {
644   removeFromParent();
645   insertBefore(BB, I);
646 }
647 
648 void VPInstruction::generateInstruction(VPTransformState &State,
649                                         unsigned Part) {
650   IRBuilderBase &Builder = State.Builder;
651   Builder.SetCurrentDebugLocation(DL);
652 
653   if (Instruction::isBinaryOp(getOpcode())) {
654     Value *A = State.get(getOperand(0), Part);
655     Value *B = State.get(getOperand(1), Part);
656     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
657     State.set(this, V, Part);
658     return;
659   }
660 
661   switch (getOpcode()) {
662   case VPInstruction::Not: {
663     Value *A = State.get(getOperand(0), Part);
664     Value *V = Builder.CreateNot(A);
665     State.set(this, V, Part);
666     break;
667   }
668   case VPInstruction::ICmpULE: {
669     Value *IV = State.get(getOperand(0), Part);
670     Value *TC = State.get(getOperand(1), Part);
671     Value *V = Builder.CreateICmpULE(IV, TC);
672     State.set(this, V, Part);
673     break;
674   }
675   case Instruction::Select: {
676     Value *Cond = State.get(getOperand(0), Part);
677     Value *Op1 = State.get(getOperand(1), Part);
678     Value *Op2 = State.get(getOperand(2), Part);
679     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
680     State.set(this, V, Part);
681     break;
682   }
683   case VPInstruction::ActiveLaneMask: {
684     // Get first lane of vector induction variable.
685     Value *VIVElem0 = State.get(getOperand(0), VPIteration(Part, 0));
686     // Get the original loop tripcount.
687     Value *ScalarTC = State.get(getOperand(1), Part);
688 
689     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
690     auto *PredTy = VectorType::get(Int1Ty, State.VF);
691     Instruction *Call = Builder.CreateIntrinsic(
692         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
693         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
694     State.set(this, Call, Part);
695     break;
696   }
697   case VPInstruction::FirstOrderRecurrenceSplice: {
698     // Generate code to combine the previous and current values in vector v3.
699     //
700     //   vector.ph:
701     //     v_init = vector(..., ..., ..., a[-1])
702     //     br vector.body
703     //
704     //   vector.body
705     //     i = phi [0, vector.ph], [i+4, vector.body]
706     //     v1 = phi [v_init, vector.ph], [v2, vector.body]
707     //     v2 = a[i, i+1, i+2, i+3];
708     //     v3 = vector(v1(3), v2(0, 1, 2))
709 
710     // For the first part, use the recurrence phi (v1), otherwise v2.
711     auto *V1 = State.get(getOperand(0), 0);
712     Value *PartMinus1 = Part == 0 ? V1 : State.get(getOperand(1), Part - 1);
713     if (!PartMinus1->getType()->isVectorTy()) {
714       State.set(this, PartMinus1, Part);
715     } else {
716       Value *V2 = State.get(getOperand(1), Part);
717       State.set(this, Builder.CreateVectorSplice(PartMinus1, V2, -1), Part);
718     }
719     break;
720   }
721 
722   case VPInstruction::CanonicalIVIncrement:
723   case VPInstruction::CanonicalIVIncrementNUW: {
724     Value *Next = nullptr;
725     if (Part == 0) {
726       bool IsNUW = getOpcode() == VPInstruction::CanonicalIVIncrementNUW;
727       auto *Phi = State.get(getOperand(0), 0);
728       // The loop step is equal to the vectorization factor (num of SIMD
729       // elements) times the unroll factor (num of SIMD instructions).
730       Value *Step =
731           createStepForVF(Builder, Phi->getType(), State.VF, State.UF);
732       Next = Builder.CreateAdd(Phi, Step, "index.next", IsNUW, false);
733     } else {
734       Next = State.get(this, 0);
735     }
736 
737     State.set(this, Next, Part);
738     break;
739   }
740   case VPInstruction::BranchOnCount: {
741     if (Part != 0)
742       break;
743     // First create the compare.
744     Value *IV = State.get(getOperand(0), Part);
745     Value *TC = State.get(getOperand(1), Part);
746     Value *Cond = Builder.CreateICmpEQ(IV, TC);
747 
748     // Now create the branch.
749     auto *Plan = getParent()->getPlan();
750     VPRegionBlock *TopRegion = Plan->getVectorLoopRegion();
751     VPBasicBlock *Header = TopRegion->getEntry()->getEntryBasicBlock();
752     if (Header->empty()) {
753       assert(EnableVPlanNativePath &&
754              "empty entry block only expected in VPlanNativePath");
755       Header = cast<VPBasicBlock>(Header->getSingleSuccessor());
756     }
757     // TODO: Once the exit block is modeled in VPlan, use it instead of going
758     // through State.CFG.ExitBB.
759     BasicBlock *Exit = State.CFG.ExitBB;
760 
761     Builder.CreateCondBr(Cond, Exit, State.CFG.VPBB2IRBB[Header]);
762     Builder.GetInsertBlock()->getTerminator()->eraseFromParent();
763     break;
764   }
765   default:
766     llvm_unreachable("Unsupported opcode for instruction");
767   }
768 }
769 
770 void VPInstruction::execute(VPTransformState &State) {
771   assert(!State.Instance && "VPInstruction executing an Instance");
772   IRBuilderBase::FastMathFlagGuard FMFGuard(State.Builder);
773   State.Builder.setFastMathFlags(FMF);
774   for (unsigned Part = 0; Part < State.UF; ++Part)
775     generateInstruction(State, Part);
776 }
777 
778 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
779 void VPInstruction::dump() const {
780   VPSlotTracker SlotTracker(getParent()->getPlan());
781   print(dbgs(), "", SlotTracker);
782 }
783 
784 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
785                           VPSlotTracker &SlotTracker) const {
786   O << Indent << "EMIT ";
787 
788   if (hasResult()) {
789     printAsOperand(O, SlotTracker);
790     O << " = ";
791   }
792 
793   switch (getOpcode()) {
794   case VPInstruction::Not:
795     O << "not";
796     break;
797   case VPInstruction::ICmpULE:
798     O << "icmp ule";
799     break;
800   case VPInstruction::SLPLoad:
801     O << "combined load";
802     break;
803   case VPInstruction::SLPStore:
804     O << "combined store";
805     break;
806   case VPInstruction::ActiveLaneMask:
807     O << "active lane mask";
808     break;
809   case VPInstruction::FirstOrderRecurrenceSplice:
810     O << "first-order splice";
811     break;
812   case VPInstruction::CanonicalIVIncrement:
813     O << "VF * UF + ";
814     break;
815   case VPInstruction::CanonicalIVIncrementNUW:
816     O << "VF * UF +(nuw) ";
817     break;
818   case VPInstruction::BranchOnCount:
819     O << "branch-on-count ";
820     break;
821   default:
822     O << Instruction::getOpcodeName(getOpcode());
823   }
824 
825   O << FMF;
826 
827   for (const VPValue *Operand : operands()) {
828     O << " ";
829     Operand->printAsOperand(O, SlotTracker);
830   }
831 
832   if (DL) {
833     O << ", !dbg ";
834     DL.print(O);
835   }
836 }
837 #endif
838 
839 void VPInstruction::setFastMathFlags(FastMathFlags FMFNew) {
840   // Make sure the VPInstruction is a floating-point operation.
841   assert((Opcode == Instruction::FAdd || Opcode == Instruction::FMul ||
842           Opcode == Instruction::FNeg || Opcode == Instruction::FSub ||
843           Opcode == Instruction::FDiv || Opcode == Instruction::FRem ||
844           Opcode == Instruction::FCmp) &&
845          "this op can't take fast-math flags");
846   FMF = FMFNew;
847 }
848 
849 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
850                              Value *CanonicalIVStartValue,
851                              VPTransformState &State) {
852   // Check if the trip count is needed, and if so build it.
853   if (TripCount && TripCount->getNumUsers()) {
854     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
855       State.set(TripCount, TripCountV, Part);
856   }
857 
858   // Check if the backedge taken count is needed, and if so build it.
859   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
860     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
861     auto *TCMO = Builder.CreateSub(TripCountV,
862                                    ConstantInt::get(TripCountV->getType(), 1),
863                                    "trip.count.minus.1");
864     auto VF = State.VF;
865     Value *VTCMO =
866         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
867     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
868       State.set(BackedgeTakenCount, VTCMO, Part);
869   }
870 
871   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
872     State.set(&VectorTripCount, VectorTripCountV, Part);
873 
874   // When vectorizing the epilogue loop, the canonical induction start value
875   // needs to be changed from zero to the value after the main vector loop.
876   if (CanonicalIVStartValue) {
877     VPValue *VPV = new VPValue(CanonicalIVStartValue);
878     addExternalDef(VPV);
879     auto *IV = getCanonicalIV();
880     assert(all_of(IV->users(),
881                   [](const VPUser *U) {
882                     if (isa<VPScalarIVStepsRecipe>(U))
883                       return true;
884                     auto *VPI = cast<VPInstruction>(U);
885                     return VPI->getOpcode() ==
886                                VPInstruction::CanonicalIVIncrement ||
887                            VPI->getOpcode() ==
888                                VPInstruction::CanonicalIVIncrementNUW;
889                   }) &&
890            "the canonical IV should only be used by its increments or "
891            "ScalarIVSteps when "
892            "resetting the start value");
893     IV->setOperand(0, VPV);
894   }
895 }
896 
897 /// Generate the code inside the body of the vectorized loop. Assumes a single
898 /// LoopVectorBody basic-block was created for this. Introduce additional
899 /// basic-blocks as needed, and fill them all.
900 void VPlan::execute(VPTransformState *State) {
901   // 0. Set the reverse mapping from VPValues to Values for code generation.
902   for (auto &Entry : Value2VPValue)
903     State->VPValue2Value[Entry.second] = Entry.first;
904 
905   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
906   State->CFG.VectorPreHeader = VectorPreHeaderBB;
907   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
908   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
909 
910   State->CurrentVectorLoop = State->LI->getLoopFor(VectorHeaderBB);
911   State->CFG.ExitBB = State->CurrentVectorLoop->getExitBlock();
912 
913   // Remove the edge between Header and Latch to allow other connections.
914   // Temporarily terminate with unreachable until CFG is rewired.
915   // Note: this asserts the generated code's assumption that
916   // getFirstInsertionPt() can be dereferenced into an Instruction.
917   VectorHeaderBB->getTerminator()->eraseFromParent();
918   State->Builder.SetInsertPoint(VectorHeaderBB);
919   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
920   State->Builder.SetInsertPoint(Terminator);
921 
922   // Generate code in loop body.
923   State->CFG.PrevVPBB = nullptr;
924   State->CFG.PrevBB = VectorHeaderBB;
925 
926   for (VPBlockBase *Block : depth_first(Entry))
927     Block->execute(State);
928 
929   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
930   // VPBB's successors.
931   for (auto VPBB : State->CFG.VPBBsToFix) {
932     assert(EnableVPlanNativePath &&
933            "Unexpected VPBBsToFix in non VPlan-native path");
934     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
935     assert(BB && "Unexpected null basic block for VPBB");
936 
937     unsigned Idx = 0;
938     auto *BBTerminator = BB->getTerminator();
939 
940     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
941       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
942       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
943       ++Idx;
944     }
945   }
946 
947   BasicBlock *VectorLatchBB = State->CFG.PrevBB;
948 
949   // Fix the latch value of canonical, reduction and first-order recurrences
950   // phis in the vector loop.
951   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
952   if (Header->empty()) {
953     assert(EnableVPlanNativePath);
954     Header = cast<VPBasicBlock>(Header->getSingleSuccessor());
955   }
956   for (VPRecipeBase &R : Header->phis()) {
957     // Skip phi-like recipes that generate their backedege values themselves.
958     if (isa<VPWidenPHIRecipe>(&R))
959       continue;
960 
961     if (isa<VPWidenPointerInductionRecipe>(&R) ||
962         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
963       PHINode *Phi = nullptr;
964       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
965         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
966       } else {
967         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
968         // TODO: Split off the case that all users of a pointer phi are scalar
969         // from the VPWidenPointerInductionRecipe.
970         if (all_of(WidenPhi->users(), [WidenPhi](const VPUser *U) {
971               return cast<VPRecipeBase>(U)->usesScalars(WidenPhi);
972             }))
973           continue;
974 
975         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
976         Phi = cast<PHINode>(GEP->getPointerOperand());
977       }
978 
979       Phi->setIncomingBlock(1, VectorLatchBB);
980 
981       // Move the last step to the end of the latch block. This ensures
982       // consistent placement of all induction updates.
983       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
984       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
985       continue;
986     }
987 
988     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
989     // For  canonical IV, first-order recurrences and in-order reduction phis,
990     // only a single part is generated, which provides the last part from the
991     // previous iteration. For non-ordered reductions all UF parts are
992     // generated.
993     bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
994                             isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
995                             cast<VPReductionPHIRecipe>(PhiR)->isOrdered();
996     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
997 
998     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
999       Value *Phi = State->get(PhiR, Part);
1000       Value *Val = State->get(PhiR->getBackedgeValue(),
1001                               SinglePartNeeded ? State->UF - 1 : Part);
1002       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
1003     }
1004   }
1005 
1006   // We do not attempt to preserve DT for outer loop vectorization currently.
1007   if (!EnableVPlanNativePath)
1008     updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB,
1009                         State->CFG.ExitBB);
1010 }
1011 
1012 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1013 LLVM_DUMP_METHOD
1014 void VPlan::print(raw_ostream &O) const {
1015   VPSlotTracker SlotTracker(this);
1016 
1017   O << "VPlan '" << Name << "' {";
1018 
1019   if (VectorTripCount.getNumUsers() > 0) {
1020     O << "\nLive-in ";
1021     VectorTripCount.printAsOperand(O, SlotTracker);
1022     O << " = vector-trip-count\n";
1023   }
1024 
1025   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
1026     O << "\nLive-in ";
1027     BackedgeTakenCount->printAsOperand(O, SlotTracker);
1028     O << " = backedge-taken count\n";
1029   }
1030 
1031   for (const VPBlockBase *Block : depth_first(getEntry())) {
1032     O << '\n';
1033     Block->print(O, "", SlotTracker);
1034   }
1035   O << "}\n";
1036 }
1037 
1038 LLVM_DUMP_METHOD
1039 void VPlan::printDOT(raw_ostream &O) const {
1040   VPlanPrinter Printer(O, *this);
1041   Printer.dump();
1042 }
1043 
1044 LLVM_DUMP_METHOD
1045 void VPlan::dump() const { print(dbgs()); }
1046 #endif
1047 
1048 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
1049                                 BasicBlock *LoopLatchBB,
1050                                 BasicBlock *LoopExitBB) {
1051   // The vector body may be more than a single basic-block by this point.
1052   // Update the dominator tree information inside the vector body by propagating
1053   // it from header to latch, expecting only triangular control-flow, if any.
1054   BasicBlock *PostDomSucc = nullptr;
1055   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
1056     // Get the list of successors of this block.
1057     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
1058     assert(Succs.size() <= 2 &&
1059            "Basic block in vector loop has more than 2 successors.");
1060     PostDomSucc = Succs[0];
1061     if (Succs.size() == 1) {
1062       assert(PostDomSucc->getSinglePredecessor() &&
1063              "PostDom successor has more than one predecessor.");
1064       DT->addNewBlock(PostDomSucc, BB);
1065       continue;
1066     }
1067     BasicBlock *InterimSucc = Succs[1];
1068     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
1069       PostDomSucc = Succs[1];
1070       InterimSucc = Succs[0];
1071     }
1072     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
1073            "One successor of a basic block does not lead to the other.");
1074     assert(InterimSucc->getSinglePredecessor() &&
1075            "Interim successor has more than one predecessor.");
1076     assert(PostDomSucc->hasNPredecessors(2) &&
1077            "PostDom successor has more than two predecessors.");
1078     DT->addNewBlock(InterimSucc, BB);
1079     DT->addNewBlock(PostDomSucc, BB);
1080   }
1081   // Latch block is a new dominator for the loop exit.
1082   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
1083   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
1084 }
1085 
1086 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1087 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
1088   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
1089          Twine(getOrCreateBID(Block));
1090 }
1091 
1092 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
1093   const std::string &Name = Block->getName();
1094   if (!Name.empty())
1095     return Name;
1096   return "VPB" + Twine(getOrCreateBID(Block));
1097 }
1098 
1099 void VPlanPrinter::dump() {
1100   Depth = 1;
1101   bumpIndent(0);
1102   OS << "digraph VPlan {\n";
1103   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
1104   if (!Plan.getName().empty())
1105     OS << "\\n" << DOT::EscapeString(Plan.getName());
1106   if (Plan.BackedgeTakenCount) {
1107     OS << ", where:\\n";
1108     Plan.BackedgeTakenCount->print(OS, SlotTracker);
1109     OS << " := BackedgeTakenCount";
1110   }
1111   OS << "\"]\n";
1112   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
1113   OS << "edge [fontname=Courier, fontsize=30]\n";
1114   OS << "compound=true\n";
1115 
1116   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
1117     dumpBlock(Block);
1118 
1119   OS << "}\n";
1120 }
1121 
1122 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1123   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1124     dumpBasicBlock(BasicBlock);
1125   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1126     dumpRegion(Region);
1127   else
1128     llvm_unreachable("Unsupported kind of VPBlock.");
1129 }
1130 
1131 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1132                             bool Hidden, const Twine &Label) {
1133   // Due to "dot" we print an edge between two regions as an edge between the
1134   // exit basic block and the entry basic of the respective regions.
1135   const VPBlockBase *Tail = From->getExitBasicBlock();
1136   const VPBlockBase *Head = To->getEntryBasicBlock();
1137   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1138   OS << " [ label=\"" << Label << '\"';
1139   if (Tail != From)
1140     OS << " ltail=" << getUID(From);
1141   if (Head != To)
1142     OS << " lhead=" << getUID(To);
1143   if (Hidden)
1144     OS << "; splines=none";
1145   OS << "]\n";
1146 }
1147 
1148 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1149   auto &Successors = Block->getSuccessors();
1150   if (Successors.size() == 1)
1151     drawEdge(Block, Successors.front(), false, "");
1152   else if (Successors.size() == 2) {
1153     drawEdge(Block, Successors.front(), false, "T");
1154     drawEdge(Block, Successors.back(), false, "F");
1155   } else {
1156     unsigned SuccessorNumber = 0;
1157     for (auto *Successor : Successors)
1158       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1159   }
1160 }
1161 
1162 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1163   // Implement dot-formatted dump by performing plain-text dump into the
1164   // temporary storage followed by some post-processing.
1165   OS << Indent << getUID(BasicBlock) << " [label =\n";
1166   bumpIndent(1);
1167   std::string Str;
1168   raw_string_ostream SS(Str);
1169   // Use no indentation as we need to wrap the lines into quotes ourselves.
1170   BasicBlock->print(SS, "", SlotTracker);
1171 
1172   // We need to process each line of the output separately, so split
1173   // single-string plain-text dump.
1174   SmallVector<StringRef, 0> Lines;
1175   StringRef(Str).rtrim('\n').split(Lines, "\n");
1176 
1177   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1178     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1179   };
1180 
1181   // Don't need the "+" after the last line.
1182   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1183     EmitLine(Line, " +\n");
1184   EmitLine(Lines.back(), "\n");
1185 
1186   bumpIndent(-1);
1187   OS << Indent << "]\n";
1188 
1189   dumpEdges(BasicBlock);
1190 }
1191 
1192 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1193   OS << Indent << "subgraph " << getUID(Region) << " {\n";
1194   bumpIndent(1);
1195   OS << Indent << "fontname=Courier\n"
1196      << Indent << "label=\""
1197      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1198      << DOT::EscapeString(Region->getName()) << "\"\n";
1199   // Dump the blocks of the region.
1200   assert(Region->getEntry() && "Region contains no inner blocks.");
1201   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
1202     dumpBlock(Block);
1203   bumpIndent(-1);
1204   OS << Indent << "}\n";
1205   dumpEdges(Region);
1206 }
1207 
1208 void VPlanIngredient::print(raw_ostream &O) const {
1209   if (auto *Inst = dyn_cast<Instruction>(V)) {
1210     if (!Inst->getType()->isVoidTy()) {
1211       Inst->printAsOperand(O, false);
1212       O << " = ";
1213     }
1214     O << Inst->getOpcodeName() << " ";
1215     unsigned E = Inst->getNumOperands();
1216     if (E > 0) {
1217       Inst->getOperand(0)->printAsOperand(O, false);
1218       for (unsigned I = 1; I < E; ++I)
1219         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1220     }
1221   } else // !Inst
1222     V->printAsOperand(O, false);
1223 }
1224 
1225 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
1226                               VPSlotTracker &SlotTracker) const {
1227   O << Indent << "WIDEN-CALL ";
1228 
1229   auto *CI = cast<CallInst>(getUnderlyingInstr());
1230   if (CI->getType()->isVoidTy())
1231     O << "void ";
1232   else {
1233     printAsOperand(O, SlotTracker);
1234     O << " = ";
1235   }
1236 
1237   O << "call @" << CI->getCalledFunction()->getName() << "(";
1238   printOperands(O, SlotTracker);
1239   O << ")";
1240 }
1241 
1242 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
1243                                 VPSlotTracker &SlotTracker) const {
1244   O << Indent << "WIDEN-SELECT ";
1245   printAsOperand(O, SlotTracker);
1246   O << " = select ";
1247   getOperand(0)->printAsOperand(O, SlotTracker);
1248   O << ", ";
1249   getOperand(1)->printAsOperand(O, SlotTracker);
1250   O << ", ";
1251   getOperand(2)->printAsOperand(O, SlotTracker);
1252   O << (InvariantCond ? " (condition is loop invariant)" : "");
1253 }
1254 
1255 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
1256                           VPSlotTracker &SlotTracker) const {
1257   O << Indent << "WIDEN ";
1258   printAsOperand(O, SlotTracker);
1259   O << " = " << getUnderlyingInstr()->getOpcodeName() << " ";
1260   printOperands(O, SlotTracker);
1261 }
1262 
1263 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
1264                                           VPSlotTracker &SlotTracker) const {
1265   O << Indent << "WIDEN-INDUCTION";
1266   if (getTruncInst()) {
1267     O << "\\l\"";
1268     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
1269     O << " +\n" << Indent << "\"  ";
1270     getVPValue(0)->printAsOperand(O, SlotTracker);
1271   } else
1272     O << " " << VPlanIngredient(IV);
1273 }
1274 
1275 void VPWidenPointerInductionRecipe::print(raw_ostream &O, const Twine &Indent,
1276                                           VPSlotTracker &SlotTracker) const {
1277   O << Indent << "EMIT ";
1278   printAsOperand(O, SlotTracker);
1279   O << " = WIDEN-POINTER-INDUCTION ";
1280   getStartValue()->printAsOperand(O, SlotTracker);
1281   O << ", " << *IndDesc.getStep();
1282 }
1283 
1284 #endif
1285 
1286 bool VPWidenIntOrFpInductionRecipe::isCanonical() const {
1287   auto *StartC = dyn_cast<ConstantInt>(getStartValue()->getLiveInIRValue());
1288   auto *StepC = dyn_cast<SCEVConstant>(getInductionDescriptor().getStep());
1289   return StartC && StartC->isZero() && StepC && StepC->isOne();
1290 }
1291 
1292 VPCanonicalIVPHIRecipe *VPScalarIVStepsRecipe::getCanonicalIV() const {
1293   return cast<VPCanonicalIVPHIRecipe>(getOperand(0));
1294 }
1295 
1296 bool VPScalarIVStepsRecipe::isCanonical() const {
1297   auto *CanIV = getCanonicalIV();
1298   // The start value of the steps-recipe must match the start value of the
1299   // canonical induction and it must step by 1.
1300   if (CanIV->getStartValue() != getStartValue())
1301     return false;
1302   auto *StepVPV = getStepValue();
1303   if (StepVPV->getDef())
1304     return false;
1305   auto *StepC = dyn_cast_or_null<ConstantInt>(StepVPV->getLiveInIRValue());
1306   return StepC && StepC->isOne();
1307 }
1308 
1309 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1310 void VPScalarIVStepsRecipe::print(raw_ostream &O, const Twine &Indent,
1311                                   VPSlotTracker &SlotTracker) const {
1312   O << Indent;
1313   printAsOperand(O, SlotTracker);
1314   O << Indent << "= SCALAR-STEPS ";
1315   printOperands(O, SlotTracker);
1316 }
1317 
1318 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
1319                              VPSlotTracker &SlotTracker) const {
1320   O << Indent << "WIDEN-GEP ";
1321   O << (IsPtrLoopInvariant ? "Inv" : "Var");
1322   size_t IndicesNumber = IsIndexLoopInvariant.size();
1323   for (size_t I = 0; I < IndicesNumber; ++I)
1324     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
1325 
1326   O << " ";
1327   printAsOperand(O, SlotTracker);
1328   O << " = getelementptr ";
1329   printOperands(O, SlotTracker);
1330 }
1331 
1332 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1333                              VPSlotTracker &SlotTracker) const {
1334   O << Indent << "WIDEN-PHI ";
1335 
1336   auto *OriginalPhi = cast<PHINode>(getUnderlyingValue());
1337   // Unless all incoming values are modeled in VPlan  print the original PHI
1338   // directly.
1339   // TODO: Remove once all VPWidenPHIRecipe instances keep all relevant incoming
1340   // values as VPValues.
1341   if (getNumOperands() != OriginalPhi->getNumOperands()) {
1342     O << VPlanIngredient(OriginalPhi);
1343     return;
1344   }
1345 
1346   printAsOperand(O, SlotTracker);
1347   O << " = phi ";
1348   printOperands(O, SlotTracker);
1349 }
1350 
1351 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
1352                           VPSlotTracker &SlotTracker) const {
1353   O << Indent << "BLEND ";
1354   Phi->printAsOperand(O, false);
1355   O << " =";
1356   if (getNumIncomingValues() == 1) {
1357     // Not a User of any mask: not really blending, this is a
1358     // single-predecessor phi.
1359     O << " ";
1360     getIncomingValue(0)->printAsOperand(O, SlotTracker);
1361   } else {
1362     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
1363       O << " ";
1364       getIncomingValue(I)->printAsOperand(O, SlotTracker);
1365       O << "/";
1366       getMask(I)->printAsOperand(O, SlotTracker);
1367     }
1368   }
1369 }
1370 
1371 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
1372                               VPSlotTracker &SlotTracker) const {
1373   O << Indent << "REDUCE ";
1374   printAsOperand(O, SlotTracker);
1375   O << " = ";
1376   getChainOp()->printAsOperand(O, SlotTracker);
1377   O << " +";
1378   if (isa<FPMathOperator>(getUnderlyingInstr()))
1379     O << getUnderlyingInstr()->getFastMathFlags();
1380   O << " reduce." << Instruction::getOpcodeName(RdxDesc->getOpcode()) << " (";
1381   getVecOp()->printAsOperand(O, SlotTracker);
1382   if (getCondOp()) {
1383     O << ", ";
1384     getCondOp()->printAsOperand(O, SlotTracker);
1385   }
1386   O << ")";
1387 }
1388 
1389 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
1390                               VPSlotTracker &SlotTracker) const {
1391   O << Indent << (IsUniform ? "CLONE " : "REPLICATE ");
1392 
1393   if (!getUnderlyingInstr()->getType()->isVoidTy()) {
1394     printAsOperand(O, SlotTracker);
1395     O << " = ";
1396   }
1397   O << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
1398   printOperands(O, SlotTracker);
1399 
1400   if (AlsoPack)
1401     O << " (S->V)";
1402 }
1403 
1404 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1405                                 VPSlotTracker &SlotTracker) const {
1406   O << Indent << "PHI-PREDICATED-INSTRUCTION ";
1407   printAsOperand(O, SlotTracker);
1408   O << " = ";
1409   printOperands(O, SlotTracker);
1410 }
1411 
1412 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
1413                                            VPSlotTracker &SlotTracker) const {
1414   O << Indent << "WIDEN ";
1415 
1416   if (!isStore()) {
1417     printAsOperand(O, SlotTracker);
1418     O << " = ";
1419   }
1420   O << Instruction::getOpcodeName(Ingredient.getOpcode()) << " ";
1421 
1422   printOperands(O, SlotTracker);
1423 }
1424 #endif
1425 
1426 void VPCanonicalIVPHIRecipe::execute(VPTransformState &State) {
1427   Value *Start = getStartValue()->getLiveInIRValue();
1428   PHINode *EntryPart = PHINode::Create(
1429       Start->getType(), 2, "index", &*State.CFG.PrevBB->getFirstInsertionPt());
1430   EntryPart->addIncoming(Start, State.CFG.VectorPreHeader);
1431   EntryPart->setDebugLoc(DL);
1432   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
1433     State.set(this, EntryPart, Part);
1434 }
1435 
1436 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1437 void VPCanonicalIVPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1438                                    VPSlotTracker &SlotTracker) const {
1439   O << Indent << "EMIT ";
1440   printAsOperand(O, SlotTracker);
1441   O << " = CANONICAL-INDUCTION";
1442 }
1443 #endif
1444 
1445 void VPExpandSCEVRecipe::execute(VPTransformState &State) {
1446   assert(!State.Instance && "cannot be used in per-lane");
1447   const DataLayout &DL =
1448       State.CFG.VectorPreHeader->getModule()->getDataLayout();
1449   SCEVExpander Exp(SE, DL, "induction");
1450   Value *Res = Exp.expandCodeFor(Expr, Expr->getType(),
1451                                  State.CFG.VectorPreHeader->getTerminator());
1452 
1453   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
1454     State.set(this, Res, Part);
1455 }
1456 
1457 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1458 void VPExpandSCEVRecipe::print(raw_ostream &O, const Twine &Indent,
1459                                VPSlotTracker &SlotTracker) const {
1460   O << Indent << "EMIT ";
1461   getVPSingleValue()->printAsOperand(O, SlotTracker);
1462   O << " = EXPAND SCEV " << *Expr;
1463 }
1464 #endif
1465 
1466 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
1467   Value *CanonicalIV = State.get(getOperand(0), 0);
1468   Type *STy = CanonicalIV->getType();
1469   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
1470   ElementCount VF = State.VF;
1471   Value *VStart = VF.isScalar()
1472                       ? CanonicalIV
1473                       : Builder.CreateVectorSplat(VF, CanonicalIV, "broadcast");
1474   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
1475     Value *VStep = createStepForVF(Builder, STy, VF, Part);
1476     if (VF.isVector()) {
1477       VStep = Builder.CreateVectorSplat(VF, VStep);
1478       VStep = Builder.CreateAdd(VStep, Builder.CreateStepVector(VStep->getType()));
1479     }
1480     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
1481     State.set(this, CanonicalVectorIV, Part);
1482   }
1483 }
1484 
1485 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1486 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
1487                                      VPSlotTracker &SlotTracker) const {
1488   O << Indent << "EMIT ";
1489   printAsOperand(O, SlotTracker);
1490   O << " = WIDEN-CANONICAL-INDUCTION ";
1491   printOperands(O, SlotTracker);
1492 }
1493 #endif
1494 
1495 void VPFirstOrderRecurrencePHIRecipe::execute(VPTransformState &State) {
1496   auto &Builder = State.Builder;
1497   // Create a vector from the initial value.
1498   auto *VectorInit = getStartValue()->getLiveInIRValue();
1499 
1500   Type *VecTy = State.VF.isScalar()
1501                     ? VectorInit->getType()
1502                     : VectorType::get(VectorInit->getType(), State.VF);
1503 
1504   if (State.VF.isVector()) {
1505     auto *IdxTy = Builder.getInt32Ty();
1506     auto *One = ConstantInt::get(IdxTy, 1);
1507     IRBuilder<>::InsertPointGuard Guard(Builder);
1508     Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator());
1509     auto *RuntimeVF = getRuntimeVF(Builder, IdxTy, State.VF);
1510     auto *LastIdx = Builder.CreateSub(RuntimeVF, One);
1511     VectorInit = Builder.CreateInsertElement(
1512         PoisonValue::get(VecTy), VectorInit, LastIdx, "vector.recur.init");
1513   }
1514 
1515   // Create a phi node for the new recurrence.
1516   PHINode *EntryPart = PHINode::Create(
1517       VecTy, 2, "vector.recur", &*State.CFG.PrevBB->getFirstInsertionPt());
1518   EntryPart->addIncoming(VectorInit, State.CFG.VectorPreHeader);
1519   State.set(this, EntryPart, 0);
1520 }
1521 
1522 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1523 void VPFirstOrderRecurrencePHIRecipe::print(raw_ostream &O, const Twine &Indent,
1524                                             VPSlotTracker &SlotTracker) const {
1525   O << Indent << "FIRST-ORDER-RECURRENCE-PHI ";
1526   printAsOperand(O, SlotTracker);
1527   O << " = phi ";
1528   printOperands(O, SlotTracker);
1529 }
1530 #endif
1531 
1532 void VPReductionPHIRecipe::execute(VPTransformState &State) {
1533   PHINode *PN = cast<PHINode>(getUnderlyingValue());
1534   auto &Builder = State.Builder;
1535 
1536   // In order to support recurrences we need to be able to vectorize Phi nodes.
1537   // Phi nodes have cycles, so we need to vectorize them in two stages. This is
1538   // stage #1: We create a new vector PHI node with no incoming edges. We'll use
1539   // this value when we vectorize all of the instructions that use the PHI.
1540   bool ScalarPHI = State.VF.isScalar() || IsInLoop;
1541   Type *VecTy =
1542       ScalarPHI ? PN->getType() : VectorType::get(PN->getType(), State.VF);
1543 
1544   BasicBlock *HeaderBB = State.CFG.PrevBB;
1545   assert(State.CurrentVectorLoop->getHeader() == HeaderBB &&
1546          "recipe must be in the vector loop header");
1547   unsigned LastPartForNewPhi = isOrdered() ? 1 : State.UF;
1548   for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1549     Value *EntryPart =
1550         PHINode::Create(VecTy, 2, "vec.phi", &*HeaderBB->getFirstInsertionPt());
1551     State.set(this, EntryPart, Part);
1552   }
1553 
1554   // Reductions do not have to start at zero. They can start with
1555   // any loop invariant values.
1556   VPValue *StartVPV = getStartValue();
1557   Value *StartV = StartVPV->getLiveInIRValue();
1558 
1559   Value *Iden = nullptr;
1560   RecurKind RK = RdxDesc.getRecurrenceKind();
1561   if (RecurrenceDescriptor::isMinMaxRecurrenceKind(RK) ||
1562       RecurrenceDescriptor::isSelectCmpRecurrenceKind(RK)) {
1563     // MinMax reduction have the start value as their identify.
1564     if (ScalarPHI) {
1565       Iden = StartV;
1566     } else {
1567       IRBuilderBase::InsertPointGuard IPBuilder(Builder);
1568       Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator());
1569       StartV = Iden =
1570           Builder.CreateVectorSplat(State.VF, StartV, "minmax.ident");
1571     }
1572   } else {
1573     Iden = RdxDesc.getRecurrenceIdentity(RK, VecTy->getScalarType(),
1574                                          RdxDesc.getFastMathFlags());
1575 
1576     if (!ScalarPHI) {
1577       Iden = Builder.CreateVectorSplat(State.VF, Iden);
1578       IRBuilderBase::InsertPointGuard IPBuilder(Builder);
1579       Builder.SetInsertPoint(State.CFG.VectorPreHeader->getTerminator());
1580       Constant *Zero = Builder.getInt32(0);
1581       StartV = Builder.CreateInsertElement(Iden, StartV, Zero);
1582     }
1583   }
1584 
1585   for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
1586     Value *EntryPart = State.get(this, Part);
1587     // Make sure to add the reduction start value only to the
1588     // first unroll part.
1589     Value *StartVal = (Part == 0) ? StartV : Iden;
1590     cast<PHINode>(EntryPart)->addIncoming(StartVal, State.CFG.VectorPreHeader);
1591   }
1592 }
1593 
1594 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1595 void VPReductionPHIRecipe::print(raw_ostream &O, const Twine &Indent,
1596                                  VPSlotTracker &SlotTracker) const {
1597   O << Indent << "WIDEN-REDUCTION-PHI ";
1598 
1599   printAsOperand(O, SlotTracker);
1600   O << " = phi ";
1601   printOperands(O, SlotTracker);
1602 }
1603 #endif
1604 
1605 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1606 
1607 void VPValue::replaceAllUsesWith(VPValue *New) {
1608   for (unsigned J = 0; J < getNumUsers();) {
1609     VPUser *User = Users[J];
1610     unsigned NumUsers = getNumUsers();
1611     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1612       if (User->getOperand(I) == this)
1613         User->setOperand(I, New);
1614     // If a user got removed after updating the current user, the next user to
1615     // update will be moved to the current position, so we only need to
1616     // increment the index if the number of users did not change.
1617     if (NumUsers == getNumUsers())
1618       J++;
1619   }
1620 }
1621 
1622 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1623 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1624   if (const Value *UV = getUnderlyingValue()) {
1625     OS << "ir<";
1626     UV->printAsOperand(OS, false);
1627     OS << ">";
1628     return;
1629   }
1630 
1631   unsigned Slot = Tracker.getSlot(this);
1632   if (Slot == unsigned(-1))
1633     OS << "<badref>";
1634   else
1635     OS << "vp<%" << Tracker.getSlot(this) << ">";
1636 }
1637 
1638 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1639   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1640     Op->printAsOperand(O, SlotTracker);
1641   });
1642 }
1643 #endif
1644 
1645 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1646                                           Old2NewTy &Old2New,
1647                                           InterleavedAccessInfo &IAI) {
1648   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1649   for (VPBlockBase *Base : RPOT) {
1650     visitBlock(Base, Old2New, IAI);
1651   }
1652 }
1653 
1654 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1655                                          InterleavedAccessInfo &IAI) {
1656   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1657     for (VPRecipeBase &VPI : *VPBB) {
1658       if (isa<VPHeaderPHIRecipe>(&VPI))
1659         continue;
1660       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1661       auto *VPInst = cast<VPInstruction>(&VPI);
1662       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
1663       auto *IG = IAI.getInterleaveGroup(Inst);
1664       if (!IG)
1665         continue;
1666 
1667       auto NewIGIter = Old2New.find(IG);
1668       if (NewIGIter == Old2New.end())
1669         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1670             IG->getFactor(), IG->isReverse(), IG->getAlign());
1671 
1672       if (Inst == IG->getInsertPos())
1673         Old2New[IG]->setInsertPos(VPInst);
1674 
1675       InterleaveGroupMap[VPInst] = Old2New[IG];
1676       InterleaveGroupMap[VPInst]->insertMember(
1677           VPInst, IG->getIndex(Inst),
1678           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1679                                 : IG->getFactor()));
1680     }
1681   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1682     visitRegion(Region, Old2New, IAI);
1683   else
1684     llvm_unreachable("Unsupported kind of VPBlock.");
1685 }
1686 
1687 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1688                                                  InterleavedAccessInfo &IAI) {
1689   Old2NewTy Old2New;
1690   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
1691 }
1692 
1693 void VPSlotTracker::assignSlot(const VPValue *V) {
1694   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1695   Slots[V] = NextSlot++;
1696 }
1697 
1698 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1699 
1700   for (const VPValue *V : Plan.VPExternalDefs)
1701     assignSlot(V);
1702 
1703   assignSlot(&Plan.VectorTripCount);
1704   if (Plan.BackedgeTakenCount)
1705     assignSlot(Plan.BackedgeTakenCount);
1706 
1707   ReversePostOrderTraversal<
1708       VPBlockRecursiveTraversalWrapper<const VPBlockBase *>>
1709       RPOT(VPBlockRecursiveTraversalWrapper<const VPBlockBase *>(
1710           Plan.getEntry()));
1711   for (const VPBasicBlock *VPBB :
1712        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1713     for (const VPRecipeBase &Recipe : *VPBB)
1714       for (VPValue *Def : Recipe.definedValues())
1715         assignSlot(Def);
1716 }
1717 
1718 bool vputils::onlyFirstLaneUsed(VPValue *Def) {
1719   return all_of(Def->users(), [Def](VPUser *U) {
1720     return cast<VPRecipeBase>(U)->onlyFirstLaneUsed(Def);
1721   });
1722 }
1723