xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 97687b7aea17cfc6e9c42d89b6f22ac5b9c7ddc1)
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 "VPlanCFG.h"
21 #include "VPlanDominatorTree.h"
22 #include "llvm/ADT/DepthFirstIterator.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/Twine.h"
28 #include "llvm/Analysis/LoopInfo.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CFG.h"
31 #include "llvm/IR/IRBuilder.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.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/LoopVersioning.h"
44 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
45 #include <cassert>
46 #include <string>
47 #include <vector>
48 
49 using namespace llvm;
50 
51 namespace llvm {
52 extern cl::opt<bool> EnableVPlanNativePath;
53 }
54 
55 #define DEBUG_TYPE "vplan"
56 
57 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
58 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
59   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
60   VPSlotTracker SlotTracker(
61       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
62   V.print(OS, SlotTracker);
63   return OS;
64 }
65 #endif
66 
67 Value *VPLane::getAsRuntimeExpr(IRBuilderBase &Builder,
68                                 const ElementCount &VF) const {
69   switch (LaneKind) {
70   case VPLane::Kind::ScalableLast:
71     // Lane = RuntimeVF - VF.getKnownMinValue() + Lane
72     return Builder.CreateSub(getRuntimeVF(Builder, Builder.getInt32Ty(), VF),
73                              Builder.getInt32(VF.getKnownMinValue() - Lane));
74   case VPLane::Kind::First:
75     return Builder.getInt32(Lane);
76   }
77   llvm_unreachable("Unknown lane kind");
78 }
79 
80 VPValue::VPValue(const unsigned char SC, Value *UV, VPDef *Def)
81     : SubclassID(SC), UnderlyingVal(UV), Def(Def) {
82   if (Def)
83     Def->addDefinedValue(this);
84 }
85 
86 VPValue::~VPValue() {
87   assert(Users.empty() && "trying to delete a VPValue with remaining users");
88   if (Def)
89     Def->removeDefinedValue(this);
90 }
91 
92 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
93 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
94   if (const VPRecipeBase *R = dyn_cast_or_null<VPRecipeBase>(Def))
95     R->print(OS, "", SlotTracker);
96   else
97     printAsOperand(OS, SlotTracker);
98 }
99 
100 void VPValue::dump() const {
101   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this->Def);
102   VPSlotTracker SlotTracker(
103       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
104   print(dbgs(), SlotTracker);
105   dbgs() << "\n";
106 }
107 
108 void VPDef::dump() const {
109   const VPRecipeBase *Instr = dyn_cast_or_null<VPRecipeBase>(this);
110   VPSlotTracker SlotTracker(
111       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
112   print(dbgs(), "", SlotTracker);
113   dbgs() << "\n";
114 }
115 #endif
116 
117 VPRecipeBase *VPValue::getDefiningRecipe() {
118   return cast_or_null<VPRecipeBase>(Def);
119 }
120 
121 const VPRecipeBase *VPValue::getDefiningRecipe() const {
122   return cast_or_null<VPRecipeBase>(Def);
123 }
124 
125 // Get the top-most entry block of \p Start. This is the entry block of the
126 // containing VPlan. This function is templated to support both const and non-const blocks
127 template <typename T> static T *getPlanEntry(T *Start) {
128   T *Next = Start;
129   T *Current = Start;
130   while ((Next = Next->getParent()))
131     Current = Next;
132 
133   SmallSetVector<T *, 8> WorkList;
134   WorkList.insert(Current);
135 
136   for (unsigned i = 0; i < WorkList.size(); i++) {
137     T *Current = WorkList[i];
138     if (Current->getNumPredecessors() == 0)
139       return Current;
140     auto &Predecessors = Current->getPredecessors();
141     WorkList.insert(Predecessors.begin(), Predecessors.end());
142   }
143 
144   llvm_unreachable("VPlan without any entry node without predecessors");
145 }
146 
147 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
148 
149 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
150 
151 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
152 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
153   const VPBlockBase *Block = this;
154   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
155     Block = Region->getEntry();
156   return cast<VPBasicBlock>(Block);
157 }
158 
159 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
160   VPBlockBase *Block = this;
161   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
162     Block = Region->getEntry();
163   return cast<VPBasicBlock>(Block);
164 }
165 
166 void VPBlockBase::setPlan(VPlan *ParentPlan) {
167   assert(
168       (ParentPlan->getEntry() == this || ParentPlan->getPreheader() == this) &&
169       "Can only set plan on its entry or preheader block.");
170   Plan = ParentPlan;
171 }
172 
173 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
174 const VPBasicBlock *VPBlockBase::getExitingBasicBlock() const {
175   const VPBlockBase *Block = this;
176   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
177     Block = Region->getExiting();
178   return cast<VPBasicBlock>(Block);
179 }
180 
181 VPBasicBlock *VPBlockBase::getExitingBasicBlock() {
182   VPBlockBase *Block = this;
183   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
184     Block = Region->getExiting();
185   return cast<VPBasicBlock>(Block);
186 }
187 
188 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
189   if (!Successors.empty() || !Parent)
190     return this;
191   assert(Parent->getExiting() == this &&
192          "Block w/o successors not the exiting block of its parent.");
193   return Parent->getEnclosingBlockWithSuccessors();
194 }
195 
196 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
197   if (!Predecessors.empty() || !Parent)
198     return this;
199   assert(Parent->getEntry() == this &&
200          "Block w/o predecessors not the entry of its parent.");
201   return Parent->getEnclosingBlockWithPredecessors();
202 }
203 
204 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
205   for (VPBlockBase *Block : to_vector(vp_depth_first_shallow(Entry)))
206     delete Block;
207 }
208 
209 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
210   iterator It = begin();
211   while (It != end() && It->isPhi())
212     It++;
213   return It;
214 }
215 
216 Value *VPTransformState::get(VPValue *Def, const VPIteration &Instance) {
217   if (Def->isLiveIn())
218     return Def->getLiveInIRValue();
219 
220   if (hasScalarValue(Def, Instance)) {
221     return Data
222         .PerPartScalars[Def][Instance.Part][Instance.Lane.mapToCacheIndex(VF)];
223   }
224 
225   assert(hasVectorValue(Def, Instance.Part));
226   auto *VecPart = Data.PerPartOutput[Def][Instance.Part];
227   if (!VecPart->getType()->isVectorTy()) {
228     assert(Instance.Lane.isFirstLane() && "cannot get lane > 0 for scalar");
229     return VecPart;
230   }
231   // TODO: Cache created scalar values.
232   Value *Lane = Instance.Lane.getAsRuntimeExpr(Builder, VF);
233   auto *Extract = Builder.CreateExtractElement(VecPart, Lane);
234   // set(Def, Extract, Instance);
235   return Extract;
236 }
237 
238 Value *VPTransformState::get(VPValue *Def, unsigned Part) {
239   // If Values have been set for this Def return the one relevant for \p Part.
240   if (hasVectorValue(Def, Part))
241     return Data.PerPartOutput[Def][Part];
242 
243   auto GetBroadcastInstrs = [this, Def](Value *V) {
244     bool SafeToHoist = Def->isDefinedOutsideVectorRegions();
245     if (VF.isScalar())
246       return V;
247     // Place the code for broadcasting invariant variables in the new preheader.
248     IRBuilder<>::InsertPointGuard Guard(Builder);
249     if (SafeToHoist) {
250       BasicBlock *LoopVectorPreHeader = CFG.VPBB2IRBB[cast<VPBasicBlock>(
251           Plan->getVectorLoopRegion()->getSinglePredecessor())];
252       if (LoopVectorPreHeader)
253         Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
254     }
255 
256     // Place the code for broadcasting invariant variables in the new preheader.
257     // Broadcast the scalar into all locations in the vector.
258     Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
259 
260     return Shuf;
261   };
262 
263   if (!hasScalarValue(Def, {Part, 0})) {
264     assert(Def->isLiveIn() && "expected a live-in");
265     if (Part != 0)
266       return get(Def, 0);
267     Value *IRV = Def->getLiveInIRValue();
268     Value *B = GetBroadcastInstrs(IRV);
269     set(Def, B, Part);
270     return B;
271   }
272 
273   Value *ScalarValue = get(Def, {Part, 0});
274   // If we aren't vectorizing, we can just copy the scalar map values over
275   // to the vector map.
276   if (VF.isScalar()) {
277     set(Def, ScalarValue, Part);
278     return ScalarValue;
279   }
280 
281   bool IsUniform = vputils::isUniformAfterVectorization(Def);
282 
283   unsigned LastLane = IsUniform ? 0 : VF.getKnownMinValue() - 1;
284   // Check if there is a scalar value for the selected lane.
285   if (!hasScalarValue(Def, {Part, LastLane})) {
286     // At the moment, VPWidenIntOrFpInductionRecipes, VPScalarIVStepsRecipes and
287     // VPExpandSCEVRecipes can also be uniform.
288     assert((isa<VPWidenIntOrFpInductionRecipe>(Def->getDefiningRecipe()) ||
289             isa<VPScalarIVStepsRecipe>(Def->getDefiningRecipe()) ||
290             isa<VPExpandSCEVRecipe>(Def->getDefiningRecipe())) &&
291            "unexpected recipe found to be invariant");
292     IsUniform = true;
293     LastLane = 0;
294   }
295 
296   auto *LastInst = cast<Instruction>(get(Def, {Part, LastLane}));
297   // Set the insert point after the last scalarized instruction or after the
298   // last PHI, if LastInst is a PHI. This ensures the insertelement sequence
299   // will directly follow the scalar definitions.
300   auto OldIP = Builder.saveIP();
301   auto NewIP =
302       isa<PHINode>(LastInst)
303           ? BasicBlock::iterator(LastInst->getParent()->getFirstNonPHI())
304           : std::next(BasicBlock::iterator(LastInst));
305   Builder.SetInsertPoint(&*NewIP);
306 
307   // However, if we are vectorizing, we need to construct the vector values.
308   // If the value is known to be uniform after vectorization, we can just
309   // broadcast the scalar value corresponding to lane zero for each unroll
310   // iteration. Otherwise, we construct the vector values using
311   // insertelement instructions. Since the resulting vectors are stored in
312   // State, we will only generate the insertelements once.
313   Value *VectorValue = nullptr;
314   if (IsUniform) {
315     VectorValue = GetBroadcastInstrs(ScalarValue);
316     set(Def, VectorValue, Part);
317   } else {
318     // Initialize packing with insertelements to start from undef.
319     assert(!VF.isScalable() && "VF is assumed to be non scalable.");
320     Value *Undef = PoisonValue::get(VectorType::get(LastInst->getType(), VF));
321     set(Def, Undef, Part);
322     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
323       packScalarIntoVectorValue(Def, {Part, Lane});
324     VectorValue = get(Def, Part);
325   }
326   Builder.restoreIP(OldIP);
327   return VectorValue;
328 }
329 
330 BasicBlock *VPTransformState::CFGState::getPreheaderBBFor(VPRecipeBase *R) {
331   VPRegionBlock *LoopRegion = R->getParent()->getEnclosingLoopRegion();
332   return VPBB2IRBB[LoopRegion->getPreheaderVPBB()];
333 }
334 
335 void VPTransformState::addNewMetadata(Instruction *To,
336                                       const Instruction *Orig) {
337   // If the loop was versioned with memchecks, add the corresponding no-alias
338   // metadata.
339   if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
340     LVer->annotateInstWithNoAlias(To, Orig);
341 }
342 
343 void VPTransformState::addMetadata(Instruction *To, Instruction *From) {
344   // No source instruction to transfer metadata from?
345   if (!From)
346     return;
347 
348   propagateMetadata(To, From);
349   addNewMetadata(To, From);
350 }
351 
352 void VPTransformState::addMetadata(ArrayRef<Value *> To, Instruction *From) {
353   // No source instruction to transfer metadata from?
354   if (!From)
355     return;
356 
357   for (Value *V : To) {
358     if (Instruction *I = dyn_cast<Instruction>(V))
359       addMetadata(I, From);
360   }
361 }
362 
363 void VPTransformState::setDebugLocFrom(DebugLoc DL) {
364   const DILocation *DIL = DL;
365   // When a FSDiscriminator is enabled, we don't need to add the multiply
366   // factors to the discriminators.
367   if (DIL &&
368       Builder.GetInsertBlock()
369           ->getParent()
370           ->shouldEmitDebugInfoForProfiling() &&
371       !EnableFSDiscriminator) {
372     // FIXME: For scalable vectors, assume vscale=1.
373     auto NewDIL =
374         DIL->cloneByMultiplyingDuplicationFactor(UF * VF.getKnownMinValue());
375     if (NewDIL)
376       Builder.SetCurrentDebugLocation(*NewDIL);
377     else
378       LLVM_DEBUG(dbgs() << "Failed to create new discriminator: "
379                         << DIL->getFilename() << " Line: " << DIL->getLine());
380   } else
381     Builder.SetCurrentDebugLocation(DIL);
382 }
383 
384 void VPTransformState::packScalarIntoVectorValue(VPValue *Def,
385                                                  const VPIteration &Instance) {
386   Value *ScalarInst = get(Def, Instance);
387   Value *VectorValue = get(Def, Instance.Part);
388   VectorValue = Builder.CreateInsertElement(
389       VectorValue, ScalarInst, Instance.Lane.getAsRuntimeExpr(Builder, VF));
390   set(Def, VectorValue, Instance.Part);
391 }
392 
393 BasicBlock *
394 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
395   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
396   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
397   BasicBlock *PrevBB = CFG.PrevBB;
398   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
399                                          PrevBB->getParent(), CFG.ExitBB);
400   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
401 
402   // Hook up the new basic block to its predecessors.
403   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
404     VPBasicBlock *PredVPBB = PredVPBlock->getExitingBasicBlock();
405     auto &PredVPSuccessors = PredVPBB->getHierarchicalSuccessors();
406     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
407 
408     assert(PredBB && "Predecessor basic-block not found building successor.");
409     auto *PredBBTerminator = PredBB->getTerminator();
410     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
411 
412     auto *TermBr = dyn_cast<BranchInst>(PredBBTerminator);
413     if (isa<UnreachableInst>(PredBBTerminator)) {
414       assert(PredVPSuccessors.size() == 1 &&
415              "Predecessor ending w/o branch must have single successor.");
416       DebugLoc DL = PredBBTerminator->getDebugLoc();
417       PredBBTerminator->eraseFromParent();
418       auto *Br = BranchInst::Create(NewBB, PredBB);
419       Br->setDebugLoc(DL);
420     } else if (TermBr && !TermBr->isConditional()) {
421       TermBr->setSuccessor(0, NewBB);
422     } else {
423       // Set each forward successor here when it is created, excluding
424       // backedges. A backward successor is set when the branch is created.
425       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
426       assert(!TermBr->getSuccessor(idx) &&
427              "Trying to reset an existing successor block.");
428       TermBr->setSuccessor(idx, NewBB);
429     }
430   }
431   return NewBB;
432 }
433 
434 void VPBasicBlock::execute(VPTransformState *State) {
435   bool Replica = State->Instance && !State->Instance->isFirstIteration();
436   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
437   VPBlockBase *SingleHPred = nullptr;
438   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
439 
440   auto IsLoopRegion = [](VPBlockBase *BB) {
441     auto *R = dyn_cast<VPRegionBlock>(BB);
442     return R && !R->isReplicator();
443   };
444 
445   // 1. Create an IR basic block, or reuse the last one or ExitBB if possible.
446   if (getPlan()->getVectorLoopRegion()->getSingleSuccessor() == this) {
447     // ExitBB can be re-used for the exit block of the Plan.
448     NewBB = State->CFG.ExitBB;
449     State->CFG.PrevBB = NewBB;
450 
451     // Update the branch instruction in the predecessor to branch to ExitBB.
452     VPBlockBase *PredVPB = getSingleHierarchicalPredecessor();
453     VPBasicBlock *ExitingVPBB = PredVPB->getExitingBasicBlock();
454     assert(PredVPB->getSingleSuccessor() == this &&
455            "predecessor must have the current block as only successor");
456     BasicBlock *ExitingBB = State->CFG.VPBB2IRBB[ExitingVPBB];
457     // The Exit block of a loop is always set to be successor 0 of the Exiting
458     // block.
459     cast<BranchInst>(ExitingBB->getTerminator())->setSuccessor(0, NewBB);
460   } else if (PrevVPBB && /* A */
461              !((SingleHPred = getSingleHierarchicalPredecessor()) &&
462                SingleHPred->getExitingBasicBlock() == PrevVPBB &&
463                PrevVPBB->getSingleHierarchicalSuccessor() &&
464                (SingleHPred->getParent() == getEnclosingLoopRegion() &&
465                 !IsLoopRegion(SingleHPred))) &&         /* B */
466              !(Replica && getPredecessors().empty())) { /* C */
467     // The last IR basic block is reused, as an optimization, in three cases:
468     // A. the first VPBB reuses the loop pre-header BB - when PrevVPBB is null;
469     // B. when the current VPBB has a single (hierarchical) predecessor which
470     //    is PrevVPBB and the latter has a single (hierarchical) successor which
471     //    both are in the same non-replicator region; and
472     // C. when the current VPBB is an entry of a region replica - where PrevVPBB
473     //    is the exiting VPBB of this region from a previous instance, or the
474     //    predecessor of this region.
475 
476     NewBB = createEmptyBasicBlock(State->CFG);
477     State->Builder.SetInsertPoint(NewBB);
478     // Temporarily terminate with unreachable until CFG is rewired.
479     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
480     // Register NewBB in its loop. In innermost loops its the same for all
481     // BB's.
482     if (State->CurrentVectorLoop)
483       State->CurrentVectorLoop->addBasicBlockToLoop(NewBB, *State->LI);
484     State->Builder.SetInsertPoint(Terminator);
485     State->CFG.PrevBB = NewBB;
486   }
487 
488   // 2. Fill the IR basic block with IR instructions.
489   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
490                     << " in BB:" << NewBB->getName() << '\n');
491 
492   State->CFG.VPBB2IRBB[this] = NewBB;
493   State->CFG.PrevVPBB = this;
494 
495   for (VPRecipeBase &Recipe : Recipes)
496     Recipe.execute(*State);
497 
498   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
499 }
500 
501 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
502   for (VPRecipeBase &R : Recipes) {
503     for (auto *Def : R.definedValues())
504       Def->replaceAllUsesWith(NewValue);
505 
506     for (unsigned I = 0, E = R.getNumOperands(); I != E; I++)
507       R.setOperand(I, NewValue);
508   }
509 }
510 
511 VPBasicBlock *VPBasicBlock::splitAt(iterator SplitAt) {
512   assert((SplitAt == end() || SplitAt->getParent() == this) &&
513          "can only split at a position in the same block");
514 
515   SmallVector<VPBlockBase *, 2> Succs(successors());
516   // First, disconnect the current block from its successors.
517   for (VPBlockBase *Succ : Succs)
518     VPBlockUtils::disconnectBlocks(this, Succ);
519 
520   // Create new empty block after the block to split.
521   auto *SplitBlock = new VPBasicBlock(getName() + ".split");
522   VPBlockUtils::insertBlockAfter(SplitBlock, this);
523 
524   // Add successors for block to split to new block.
525   for (VPBlockBase *Succ : Succs)
526     VPBlockUtils::connectBlocks(SplitBlock, Succ);
527 
528   // Finally, move the recipes starting at SplitAt to new block.
529   for (VPRecipeBase &ToMove :
530        make_early_inc_range(make_range(SplitAt, this->end())))
531     ToMove.moveBefore(*SplitBlock, SplitBlock->end());
532 
533   return SplitBlock;
534 }
535 
536 VPRegionBlock *VPBasicBlock::getEnclosingLoopRegion() {
537   VPRegionBlock *P = getParent();
538   if (P && P->isReplicator()) {
539     P = P->getParent();
540     assert(!cast<VPRegionBlock>(P)->isReplicator() &&
541            "unexpected nested replicate regions");
542   }
543   return P;
544 }
545 
546 static bool hasConditionalTerminator(const VPBasicBlock *VPBB) {
547   if (VPBB->empty()) {
548     assert(
549         VPBB->getNumSuccessors() < 2 &&
550         "block with multiple successors doesn't have a recipe as terminator");
551     return false;
552   }
553 
554   const VPRecipeBase *R = &VPBB->back();
555   auto *VPI = dyn_cast<VPInstruction>(R);
556   bool IsCondBranch =
557       isa<VPBranchOnMaskRecipe>(R) ||
558       (VPI && (VPI->getOpcode() == VPInstruction::BranchOnCond ||
559                VPI->getOpcode() == VPInstruction::BranchOnCount));
560   (void)IsCondBranch;
561 
562   if (VPBB->getNumSuccessors() >= 2 || VPBB->isExiting()) {
563     assert(IsCondBranch && "block with multiple successors not terminated by "
564                            "conditional branch recipe");
565 
566     return true;
567   }
568 
569   assert(
570       !IsCondBranch &&
571       "block with 0 or 1 successors terminated by conditional branch recipe");
572   return false;
573 }
574 
575 VPRecipeBase *VPBasicBlock::getTerminator() {
576   if (hasConditionalTerminator(this))
577     return &back();
578   return nullptr;
579 }
580 
581 const VPRecipeBase *VPBasicBlock::getTerminator() const {
582   if (hasConditionalTerminator(this))
583     return &back();
584   return nullptr;
585 }
586 
587 bool VPBasicBlock::isExiting() const {
588   return getParent()->getExitingBasicBlock() == this;
589 }
590 
591 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
592 void VPBlockBase::printSuccessors(raw_ostream &O, const Twine &Indent) const {
593   if (getSuccessors().empty()) {
594     O << Indent << "No successors\n";
595   } else {
596     O << Indent << "Successor(s): ";
597     ListSeparator LS;
598     for (auto *Succ : getSuccessors())
599       O << LS << Succ->getName();
600     O << '\n';
601   }
602 }
603 
604 void VPBasicBlock::print(raw_ostream &O, const Twine &Indent,
605                          VPSlotTracker &SlotTracker) const {
606   O << Indent << getName() << ":\n";
607 
608   auto RecipeIndent = Indent + "  ";
609   for (const VPRecipeBase &Recipe : *this) {
610     Recipe.print(O, RecipeIndent, SlotTracker);
611     O << '\n';
612   }
613 
614   printSuccessors(O, Indent);
615 }
616 #endif
617 
618 void VPRegionBlock::dropAllReferences(VPValue *NewValue) {
619   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
620     // Drop all references in VPBasicBlocks and replace all uses with
621     // DummyValue.
622     Block->dropAllReferences(NewValue);
623 }
624 
625 void VPRegionBlock::execute(VPTransformState *State) {
626   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
627       RPOT(Entry);
628 
629   if (!isReplicator()) {
630     // Create and register the new vector loop.
631     Loop *PrevLoop = State->CurrentVectorLoop;
632     State->CurrentVectorLoop = State->LI->AllocateLoop();
633     BasicBlock *VectorPH = State->CFG.VPBB2IRBB[getPreheaderVPBB()];
634     Loop *ParentLoop = State->LI->getLoopFor(VectorPH);
635 
636     // Insert the new loop into the loop nest and register the new basic blocks
637     // before calling any utilities such as SCEV that require valid LoopInfo.
638     if (ParentLoop)
639       ParentLoop->addChildLoop(State->CurrentVectorLoop);
640     else
641       State->LI->addTopLevelLoop(State->CurrentVectorLoop);
642 
643     // Visit the VPBlocks connected to "this", starting from it.
644     for (VPBlockBase *Block : RPOT) {
645       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
646       Block->execute(State);
647     }
648 
649     State->CurrentVectorLoop = PrevLoop;
650     return;
651   }
652 
653   assert(!State->Instance && "Replicating a Region with non-null instance.");
654 
655   // Enter replicating mode.
656   State->Instance = VPIteration(0, 0);
657 
658   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
659     State->Instance->Part = Part;
660     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
661     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
662          ++Lane) {
663       State->Instance->Lane = VPLane(Lane, VPLane::Kind::First);
664       // Visit the VPBlocks connected to \p this, starting from it.
665       for (VPBlockBase *Block : RPOT) {
666         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
667         Block->execute(State);
668       }
669     }
670   }
671 
672   // Exit replicating mode.
673   State->Instance.reset();
674 }
675 
676 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
677 void VPRegionBlock::print(raw_ostream &O, const Twine &Indent,
678                           VPSlotTracker &SlotTracker) const {
679   O << Indent << (isReplicator() ? "<xVFxUF> " : "<x1> ") << getName() << ": {";
680   auto NewIndent = Indent + "  ";
681   for (auto *BlockBase : vp_depth_first_shallow(Entry)) {
682     O << '\n';
683     BlockBase->print(O, NewIndent, SlotTracker);
684   }
685   O << Indent << "}\n";
686 
687   printSuccessors(O, Indent);
688 }
689 #endif
690 
691 VPlan::~VPlan() {
692   for (auto &KV : LiveOuts)
693     delete KV.second;
694   LiveOuts.clear();
695 
696   if (Entry) {
697     VPValue DummyValue;
698     for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
699       Block->dropAllReferences(&DummyValue);
700 
701     VPBlockBase::deleteCFG(Entry);
702 
703     Preheader->dropAllReferences(&DummyValue);
704     delete Preheader;
705   }
706   for (VPValue *VPV : VPLiveInsToFree)
707     delete VPV;
708   if (BackedgeTakenCount)
709     delete BackedgeTakenCount;
710 }
711 
712 VPlanPtr VPlan::createInitialVPlan(const SCEV *TripCount, ScalarEvolution &SE) {
713   VPBasicBlock *Preheader = new VPBasicBlock("ph");
714   VPBasicBlock *VecPreheader = new VPBasicBlock("vector.ph");
715   auto Plan = std::make_unique<VPlan>(Preheader, VecPreheader);
716   Plan->TripCount =
717       vputils::getOrCreateVPValueForSCEVExpr(*Plan, TripCount, SE);
718   return Plan;
719 }
720 
721 void VPlan::prepareToExecute(Value *TripCountV, Value *VectorTripCountV,
722                              Value *CanonicalIVStartValue,
723                              VPTransformState &State,
724                              bool IsEpilogueVectorization) {
725   // Check if the backedge taken count is needed, and if so build it.
726   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
727     IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
728     auto *TCMO = Builder.CreateSub(TripCountV,
729                                    ConstantInt::get(TripCountV->getType(), 1),
730                                    "trip.count.minus.1");
731     auto VF = State.VF;
732     Value *VTCMO =
733         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
734     for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
735       State.set(BackedgeTakenCount, VTCMO, Part);
736   }
737 
738   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part)
739     State.set(&VectorTripCount, VectorTripCountV, Part);
740 
741   // When vectorizing the epilogue loop, the canonical induction start value
742   // needs to be changed from zero to the value after the main vector loop.
743   // FIXME: Improve modeling for canonical IV start values in the epilogue loop.
744   if (CanonicalIVStartValue) {
745     VPValue *VPV = getVPValueOrAddLiveIn(CanonicalIVStartValue);
746     auto *IV = getCanonicalIV();
747     assert(all_of(IV->users(),
748                   [](const VPUser *U) {
749                     return isa<VPScalarIVStepsRecipe>(U) ||
750                            isa<VPDerivedIVRecipe>(U) ||
751                            cast<VPInstruction>(U)->getOpcode() ==
752                                VPInstruction::CanonicalIVIncrement;
753                   }) &&
754            "the canonical IV should only be used by its increment or "
755            "ScalarIVSteps when resetting the start value");
756     IV->setOperand(0, VPV);
757   }
758 }
759 
760 /// Generate the code inside the preheader and body of the vectorized loop.
761 /// Assumes a single pre-header basic-block was created for this. Introduce
762 /// additional basic-blocks as needed, and fill them all.
763 void VPlan::execute(VPTransformState *State) {
764   // Set the reverse mapping from VPValues to Values for code generation.
765   for (auto &Entry : Value2VPValue)
766     State->VPValue2Value[Entry.second] = Entry.first;
767 
768   // Initialize CFG state.
769   State->CFG.PrevVPBB = nullptr;
770   State->CFG.ExitBB = State->CFG.PrevBB->getSingleSuccessor();
771   BasicBlock *VectorPreHeader = State->CFG.PrevBB;
772   State->Builder.SetInsertPoint(VectorPreHeader->getTerminator());
773 
774   // Generate code in the loop pre-header and body.
775   for (VPBlockBase *Block : vp_depth_first_shallow(Entry))
776     Block->execute(State);
777 
778   VPBasicBlock *LatchVPBB = getVectorLoopRegion()->getExitingBasicBlock();
779   BasicBlock *VectorLatchBB = State->CFG.VPBB2IRBB[LatchVPBB];
780 
781   // Fix the latch value of canonical, reduction and first-order recurrences
782   // phis in the vector loop.
783   VPBasicBlock *Header = getVectorLoopRegion()->getEntryBasicBlock();
784   for (VPRecipeBase &R : Header->phis()) {
785     // Skip phi-like recipes that generate their backedege values themselves.
786     if (isa<VPWidenPHIRecipe>(&R))
787       continue;
788 
789     if (isa<VPWidenPointerInductionRecipe>(&R) ||
790         isa<VPWidenIntOrFpInductionRecipe>(&R)) {
791       PHINode *Phi = nullptr;
792       if (isa<VPWidenIntOrFpInductionRecipe>(&R)) {
793         Phi = cast<PHINode>(State->get(R.getVPSingleValue(), 0));
794       } else {
795         auto *WidenPhi = cast<VPWidenPointerInductionRecipe>(&R);
796         // TODO: Split off the case that all users of a pointer phi are scalar
797         // from the VPWidenPointerInductionRecipe.
798         if (WidenPhi->onlyScalarsGenerated(State->VF))
799           continue;
800 
801         auto *GEP = cast<GetElementPtrInst>(State->get(WidenPhi, 0));
802         Phi = cast<PHINode>(GEP->getPointerOperand());
803       }
804 
805       Phi->setIncomingBlock(1, VectorLatchBB);
806 
807       // Move the last step to the end of the latch block. This ensures
808       // consistent placement of all induction updates.
809       Instruction *Inc = cast<Instruction>(Phi->getIncomingValue(1));
810       Inc->moveBefore(VectorLatchBB->getTerminator()->getPrevNode());
811       continue;
812     }
813 
814     auto *PhiR = cast<VPHeaderPHIRecipe>(&R);
815     // For  canonical IV, first-order recurrences and in-order reduction phis,
816     // only a single part is generated, which provides the last part from the
817     // previous iteration. For non-ordered reductions all UF parts are
818     // generated.
819     bool SinglePartNeeded = isa<VPCanonicalIVPHIRecipe>(PhiR) ||
820                             isa<VPFirstOrderRecurrencePHIRecipe>(PhiR) ||
821                             (isa<VPReductionPHIRecipe>(PhiR) &&
822                              cast<VPReductionPHIRecipe>(PhiR)->isOrdered());
823     unsigned LastPartForNewPhi = SinglePartNeeded ? 1 : State->UF;
824 
825     for (unsigned Part = 0; Part < LastPartForNewPhi; ++Part) {
826       Value *Phi = State->get(PhiR, Part);
827       Value *Val = State->get(PhiR->getBackedgeValue(),
828                               SinglePartNeeded ? State->UF - 1 : Part);
829       cast<PHINode>(Phi)->addIncoming(Val, VectorLatchBB);
830     }
831   }
832 
833   // We do not attempt to preserve DT for outer loop vectorization currently.
834   if (!EnableVPlanNativePath) {
835     BasicBlock *VectorHeaderBB = State->CFG.VPBB2IRBB[Header];
836     State->DT->addNewBlock(VectorHeaderBB, VectorPreHeader);
837     updateDominatorTree(State->DT, VectorHeaderBB, VectorLatchBB,
838                         State->CFG.ExitBB);
839   }
840 }
841 
842 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
843 LLVM_DUMP_METHOD
844 void VPlan::print(raw_ostream &O) const {
845   VPSlotTracker SlotTracker(this);
846 
847   O << "VPlan '" << getName() << "' {";
848 
849   if (VectorTripCount.getNumUsers() > 0) {
850     O << "\nLive-in ";
851     VectorTripCount.printAsOperand(O, SlotTracker);
852     O << " = vector-trip-count";
853   }
854 
855   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
856     O << "\nLive-in ";
857     BackedgeTakenCount->printAsOperand(O, SlotTracker);
858     O << " = backedge-taken count";
859   }
860 
861   O << "\n";
862   if (TripCount->isLiveIn())
863     O << "Live-in ";
864   TripCount->printAsOperand(O, SlotTracker);
865   O << " = original trip-count";
866   O << "\n";
867 
868   if (!getPreheader()->empty()) {
869     O << "\n";
870     getPreheader()->print(O, "", SlotTracker);
871   }
872 
873   for (const VPBlockBase *Block : vp_depth_first_shallow(getEntry())) {
874     O << '\n';
875     Block->print(O, "", SlotTracker);
876   }
877 
878   if (!LiveOuts.empty())
879     O << "\n";
880   for (const auto &KV : LiveOuts) {
881     KV.second->print(O, SlotTracker);
882   }
883 
884   O << "}\n";
885 }
886 
887 std::string VPlan::getName() const {
888   std::string Out;
889   raw_string_ostream RSO(Out);
890   RSO << Name << " for ";
891   if (!VFs.empty()) {
892     RSO << "VF={" << VFs[0];
893     for (ElementCount VF : drop_begin(VFs))
894       RSO << "," << VF;
895     RSO << "},";
896   }
897 
898   if (UFs.empty()) {
899     RSO << "UF>=1";
900   } else {
901     RSO << "UF={" << UFs[0];
902     for (unsigned UF : drop_begin(UFs))
903       RSO << "," << UF;
904     RSO << "}";
905   }
906 
907   return Out;
908 }
909 
910 LLVM_DUMP_METHOD
911 void VPlan::printDOT(raw_ostream &O) const {
912   VPlanPrinter Printer(O, *this);
913   Printer.dump();
914 }
915 
916 LLVM_DUMP_METHOD
917 void VPlan::dump() const { print(dbgs()); }
918 #endif
919 
920 void VPlan::addLiveOut(PHINode *PN, VPValue *V) {
921   assert(LiveOuts.count(PN) == 0 && "an exit value for PN already exists");
922   LiveOuts.insert({PN, new VPLiveOut(PN, V)});
923 }
924 
925 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopHeaderBB,
926                                 BasicBlock *LoopLatchBB,
927                                 BasicBlock *LoopExitBB) {
928   // The vector body may be more than a single basic-block by this point.
929   // Update the dominator tree information inside the vector body by propagating
930   // it from header to latch, expecting only triangular control-flow, if any.
931   BasicBlock *PostDomSucc = nullptr;
932   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
933     // Get the list of successors of this block.
934     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
935     assert(Succs.size() <= 2 &&
936            "Basic block in vector loop has more than 2 successors.");
937     PostDomSucc = Succs[0];
938     if (Succs.size() == 1) {
939       assert(PostDomSucc->getSinglePredecessor() &&
940              "PostDom successor has more than one predecessor.");
941       DT->addNewBlock(PostDomSucc, BB);
942       continue;
943     }
944     BasicBlock *InterimSucc = Succs[1];
945     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
946       PostDomSucc = Succs[1];
947       InterimSucc = Succs[0];
948     }
949     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
950            "One successor of a basic block does not lead to the other.");
951     assert(InterimSucc->getSinglePredecessor() &&
952            "Interim successor has more than one predecessor.");
953     assert(PostDomSucc->hasNPredecessors(2) &&
954            "PostDom successor has more than two predecessors.");
955     DT->addNewBlock(InterimSucc, BB);
956     DT->addNewBlock(PostDomSucc, BB);
957   }
958   // Latch block is a new dominator for the loop exit.
959   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
960   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
961 }
962 
963 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
964 
965 Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
966   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
967          Twine(getOrCreateBID(Block));
968 }
969 
970 Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
971   const std::string &Name = Block->getName();
972   if (!Name.empty())
973     return Name;
974   return "VPB" + Twine(getOrCreateBID(Block));
975 }
976 
977 void VPlanPrinter::dump() {
978   Depth = 1;
979   bumpIndent(0);
980   OS << "digraph VPlan {\n";
981   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
982   if (!Plan.getName().empty())
983     OS << "\\n" << DOT::EscapeString(Plan.getName());
984   if (Plan.BackedgeTakenCount) {
985     OS << ", where:\\n";
986     Plan.BackedgeTakenCount->print(OS, SlotTracker);
987     OS << " := BackedgeTakenCount";
988   }
989   OS << "\"]\n";
990   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
991   OS << "edge [fontname=Courier, fontsize=30]\n";
992   OS << "compound=true\n";
993 
994   dumpBlock(Plan.getPreheader());
995 
996   for (const VPBlockBase *Block : vp_depth_first_shallow(Plan.getEntry()))
997     dumpBlock(Block);
998 
999   OS << "}\n";
1000 }
1001 
1002 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
1003   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
1004     dumpBasicBlock(BasicBlock);
1005   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1006     dumpRegion(Region);
1007   else
1008     llvm_unreachable("Unsupported kind of VPBlock.");
1009 }
1010 
1011 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
1012                             bool Hidden, const Twine &Label) {
1013   // Due to "dot" we print an edge between two regions as an edge between the
1014   // exiting basic block and the entry basic of the respective regions.
1015   const VPBlockBase *Tail = From->getExitingBasicBlock();
1016   const VPBlockBase *Head = To->getEntryBasicBlock();
1017   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
1018   OS << " [ label=\"" << Label << '\"';
1019   if (Tail != From)
1020     OS << " ltail=" << getUID(From);
1021   if (Head != To)
1022     OS << " lhead=" << getUID(To);
1023   if (Hidden)
1024     OS << "; splines=none";
1025   OS << "]\n";
1026 }
1027 
1028 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
1029   auto &Successors = Block->getSuccessors();
1030   if (Successors.size() == 1)
1031     drawEdge(Block, Successors.front(), false, "");
1032   else if (Successors.size() == 2) {
1033     drawEdge(Block, Successors.front(), false, "T");
1034     drawEdge(Block, Successors.back(), false, "F");
1035   } else {
1036     unsigned SuccessorNumber = 0;
1037     for (auto *Successor : Successors)
1038       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
1039   }
1040 }
1041 
1042 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
1043   // Implement dot-formatted dump by performing plain-text dump into the
1044   // temporary storage followed by some post-processing.
1045   OS << Indent << getUID(BasicBlock) << " [label =\n";
1046   bumpIndent(1);
1047   std::string Str;
1048   raw_string_ostream SS(Str);
1049   // Use no indentation as we need to wrap the lines into quotes ourselves.
1050   BasicBlock->print(SS, "", SlotTracker);
1051 
1052   // We need to process each line of the output separately, so split
1053   // single-string plain-text dump.
1054   SmallVector<StringRef, 0> Lines;
1055   StringRef(Str).rtrim('\n').split(Lines, "\n");
1056 
1057   auto EmitLine = [&](StringRef Line, StringRef Suffix) {
1058     OS << Indent << '"' << DOT::EscapeString(Line.str()) << "\\l\"" << Suffix;
1059   };
1060 
1061   // Don't need the "+" after the last line.
1062   for (auto Line : make_range(Lines.begin(), Lines.end() - 1))
1063     EmitLine(Line, " +\n");
1064   EmitLine(Lines.back(), "\n");
1065 
1066   bumpIndent(-1);
1067   OS << Indent << "]\n";
1068 
1069   dumpEdges(BasicBlock);
1070 }
1071 
1072 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
1073   OS << Indent << "subgraph " << getUID(Region) << " {\n";
1074   bumpIndent(1);
1075   OS << Indent << "fontname=Courier\n"
1076      << Indent << "label=\""
1077      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
1078      << DOT::EscapeString(Region->getName()) << "\"\n";
1079   // Dump the blocks of the region.
1080   assert(Region->getEntry() && "Region contains no inner blocks.");
1081   for (const VPBlockBase *Block : vp_depth_first_shallow(Region->getEntry()))
1082     dumpBlock(Block);
1083   bumpIndent(-1);
1084   OS << Indent << "}\n";
1085   dumpEdges(Region);
1086 }
1087 
1088 void VPlanIngredient::print(raw_ostream &O) const {
1089   if (auto *Inst = dyn_cast<Instruction>(V)) {
1090     if (!Inst->getType()->isVoidTy()) {
1091       Inst->printAsOperand(O, false);
1092       O << " = ";
1093     }
1094     O << Inst->getOpcodeName() << " ";
1095     unsigned E = Inst->getNumOperands();
1096     if (E > 0) {
1097       Inst->getOperand(0)->printAsOperand(O, false);
1098       for (unsigned I = 1; I < E; ++I)
1099         Inst->getOperand(I)->printAsOperand(O << ", ", false);
1100     }
1101   } else // !Inst
1102     V->printAsOperand(O, false);
1103 }
1104 
1105 #endif
1106 
1107 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
1108 
1109 void VPValue::replaceAllUsesWith(VPValue *New) {
1110   for (unsigned J = 0; J < getNumUsers();) {
1111     VPUser *User = Users[J];
1112     unsigned NumUsers = getNumUsers();
1113     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
1114       if (User->getOperand(I) == this)
1115         User->setOperand(I, New);
1116     // If a user got removed after updating the current user, the next user to
1117     // update will be moved to the current position, so we only need to
1118     // increment the index if the number of users did not change.
1119     if (NumUsers == getNumUsers())
1120       J++;
1121   }
1122 }
1123 
1124 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1125 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
1126   if (const Value *UV = getUnderlyingValue()) {
1127     OS << "ir<";
1128     UV->printAsOperand(OS, false);
1129     OS << ">";
1130     return;
1131   }
1132 
1133   unsigned Slot = Tracker.getSlot(this);
1134   if (Slot == unsigned(-1))
1135     OS << "<badref>";
1136   else
1137     OS << "vp<%" << Tracker.getSlot(this) << ">";
1138 }
1139 
1140 void VPUser::printOperands(raw_ostream &O, VPSlotTracker &SlotTracker) const {
1141   interleaveComma(operands(), O, [&O, &SlotTracker](VPValue *Op) {
1142     Op->printAsOperand(O, SlotTracker);
1143   });
1144 }
1145 #endif
1146 
1147 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1148                                           Old2NewTy &Old2New,
1149                                           InterleavedAccessInfo &IAI) {
1150   ReversePostOrderTraversal<VPBlockShallowTraversalWrapper<VPBlockBase *>>
1151       RPOT(Region->getEntry());
1152   for (VPBlockBase *Base : RPOT) {
1153     visitBlock(Base, Old2New, IAI);
1154   }
1155 }
1156 
1157 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1158                                          InterleavedAccessInfo &IAI) {
1159   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1160     for (VPRecipeBase &VPI : *VPBB) {
1161       if (isa<VPHeaderPHIRecipe>(&VPI))
1162         continue;
1163       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1164       auto *VPInst = cast<VPInstruction>(&VPI);
1165 
1166       auto *Inst = dyn_cast_or_null<Instruction>(VPInst->getUnderlyingValue());
1167       if (!Inst)
1168         continue;
1169       auto *IG = IAI.getInterleaveGroup(Inst);
1170       if (!IG)
1171         continue;
1172 
1173       auto NewIGIter = Old2New.find(IG);
1174       if (NewIGIter == Old2New.end())
1175         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1176             IG->getFactor(), IG->isReverse(), IG->getAlign());
1177 
1178       if (Inst == IG->getInsertPos())
1179         Old2New[IG]->setInsertPos(VPInst);
1180 
1181       InterleaveGroupMap[VPInst] = Old2New[IG];
1182       InterleaveGroupMap[VPInst]->insertMember(
1183           VPInst, IG->getIndex(Inst),
1184           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1185                                 : IG->getFactor()));
1186     }
1187   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1188     visitRegion(Region, Old2New, IAI);
1189   else
1190     llvm_unreachable("Unsupported kind of VPBlock.");
1191 }
1192 
1193 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1194                                                  InterleavedAccessInfo &IAI) {
1195   Old2NewTy Old2New;
1196   visitRegion(Plan.getVectorLoopRegion(), Old2New, IAI);
1197 }
1198 
1199 void VPSlotTracker::assignSlot(const VPValue *V) {
1200   assert(!Slots.contains(V) && "VPValue already has a slot!");
1201   Slots[V] = NextSlot++;
1202 }
1203 
1204 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1205   assignSlot(&Plan.VectorTripCount);
1206   if (Plan.BackedgeTakenCount)
1207     assignSlot(Plan.BackedgeTakenCount);
1208   assignSlots(Plan.getPreheader());
1209 
1210   ReversePostOrderTraversal<VPBlockDeepTraversalWrapper<const VPBlockBase *>>
1211       RPOT(VPBlockDeepTraversalWrapper<const VPBlockBase *>(Plan.getEntry()));
1212   for (const VPBasicBlock *VPBB :
1213        VPBlockUtils::blocksOnly<const VPBasicBlock>(RPOT))
1214     assignSlots(VPBB);
1215 }
1216 
1217 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
1218   for (const VPRecipeBase &Recipe : *VPBB)
1219     for (VPValue *Def : Recipe.definedValues())
1220       assignSlot(Def);
1221 }
1222 
1223 bool vputils::onlyFirstLaneUsed(VPValue *Def) {
1224   return all_of(Def->users(),
1225                 [Def](VPUser *U) { return U->onlyFirstLaneUsed(Def); });
1226 }
1227 
1228 VPValue *vputils::getOrCreateVPValueForSCEVExpr(VPlan &Plan, const SCEV *Expr,
1229                                                 ScalarEvolution &SE) {
1230   if (auto *Expanded = Plan.getSCEVExpansion(Expr))
1231     return Expanded;
1232   VPValue *Expanded = nullptr;
1233   if (auto *E = dyn_cast<SCEVConstant>(Expr))
1234     Expanded = Plan.getVPValueOrAddLiveIn(E->getValue());
1235   else if (auto *E = dyn_cast<SCEVUnknown>(Expr))
1236     Expanded = Plan.getVPValueOrAddLiveIn(E->getValue());
1237   else {
1238     Expanded = new VPExpandSCEVRecipe(Expr, SE);
1239     Plan.getPreheader()->appendRecipe(Expanded->getDefiningRecipe());
1240   }
1241   Plan.addSCEVExpansion(Expr, Expanded);
1242   return Expanded;
1243 }
1244