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