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