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