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