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