xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlan.cpp (revision 525b085a65d30a5f2ae2af38c0be252fe8d4781b)
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/SmallVector.h"
24 #include "llvm/ADT/Twine.h"
25 #include "llvm/Analysis/LoopInfo.h"
26 #include "llvm/IR/BasicBlock.h"
27 #include "llvm/IR/CFG.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/IR/Value.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.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 <cassert>
42 #include <iterator>
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 raw_ostream &llvm::operator<<(raw_ostream &OS, const VPValue &V) {
52   const VPInstruction *Instr = dyn_cast<VPInstruction>(&V);
53   VPSlotTracker SlotTracker(
54       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
55   V.print(OS, SlotTracker);
56   return OS;
57 }
58 
59 void VPValue::print(raw_ostream &OS, VPSlotTracker &SlotTracker) const {
60   if (const VPInstruction *Instr = dyn_cast<VPInstruction>(this))
61     Instr->print(OS, SlotTracker);
62   else
63     printAsOperand(OS, SlotTracker);
64 }
65 
66 void VPValue::dump() const {
67   const VPInstruction *Instr = dyn_cast<VPInstruction>(this);
68   VPSlotTracker SlotTracker(
69       (Instr && Instr->getParent()) ? Instr->getParent()->getPlan() : nullptr);
70   print(dbgs(), SlotTracker);
71   dbgs() << "\n";
72 }
73 
74 void VPRecipeBase::dump() const {
75   VPSlotTracker SlotTracker(nullptr);
76   print(dbgs(), "", SlotTracker);
77   dbgs() << "\n";
78 }
79 
80 VPUser *VPRecipeBase::toVPUser() {
81   if (auto *U = dyn_cast<VPInstruction>(this))
82     return U;
83   if (auto *U = dyn_cast<VPWidenRecipe>(this))
84     return U;
85   if (auto *U = dyn_cast<VPWidenCallRecipe>(this))
86     return U;
87   if (auto *U = dyn_cast<VPWidenSelectRecipe>(this))
88     return U;
89   if (auto *U = dyn_cast<VPWidenGEPRecipe>(this))
90     return U;
91   if (auto *U = dyn_cast<VPBlendRecipe>(this))
92     return U;
93   if (auto *U = dyn_cast<VPInterleaveRecipe>(this))
94     return U;
95   if (auto *U = dyn_cast<VPReplicateRecipe>(this))
96     return U;
97   if (auto *U = dyn_cast<VPBranchOnMaskRecipe>(this))
98     return U;
99   if (auto *U = dyn_cast<VPWidenMemoryInstructionRecipe>(this))
100     return U;
101   return nullptr;
102 }
103 
104 VPValue *VPRecipeBase::toVPValue() {
105   if (auto *V = dyn_cast<VPInstruction>(this))
106     return V;
107   if (auto *V = dyn_cast<VPWidenMemoryInstructionRecipe>(this))
108     return V;
109   return nullptr;
110 }
111 
112 const VPValue *VPRecipeBase::toVPValue() const {
113   if (auto *V = dyn_cast<VPInstruction>(this))
114     return V;
115   if (auto *V = dyn_cast<VPWidenMemoryInstructionRecipe>(this))
116     return V;
117   return nullptr;
118 }
119 
120 // Get the top-most entry block of \p Start. This is the entry block of the
121 // containing VPlan. This function is templated to support both const and non-const blocks
122 template <typename T> static T *getPlanEntry(T *Start) {
123   T *Next = Start;
124   T *Current = Start;
125   while ((Next = Next->getParent()))
126     Current = Next;
127 
128   SmallSetVector<T *, 8> WorkList;
129   WorkList.insert(Current);
130 
131   for (unsigned i = 0; i < WorkList.size(); i++) {
132     T *Current = WorkList[i];
133     if (Current->getNumPredecessors() == 0)
134       return Current;
135     auto &Predecessors = Current->getPredecessors();
136     WorkList.insert(Predecessors.begin(), Predecessors.end());
137   }
138 
139   llvm_unreachable("VPlan without any entry node without predecessors");
140 }
141 
142 VPlan *VPBlockBase::getPlan() { return getPlanEntry(this)->Plan; }
143 
144 const VPlan *VPBlockBase::getPlan() const { return getPlanEntry(this)->Plan; }
145 
146 /// \return the VPBasicBlock that is the entry of Block, possibly indirectly.
147 const VPBasicBlock *VPBlockBase::getEntryBasicBlock() const {
148   const VPBlockBase *Block = this;
149   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
150     Block = Region->getEntry();
151   return cast<VPBasicBlock>(Block);
152 }
153 
154 VPBasicBlock *VPBlockBase::getEntryBasicBlock() {
155   VPBlockBase *Block = this;
156   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
157     Block = Region->getEntry();
158   return cast<VPBasicBlock>(Block);
159 }
160 
161 void VPBlockBase::setPlan(VPlan *ParentPlan) {
162   assert(ParentPlan->getEntry() == this &&
163          "Can only set plan on its entry block.");
164   Plan = ParentPlan;
165 }
166 
167 /// \return the VPBasicBlock that is the exit of Block, possibly indirectly.
168 const VPBasicBlock *VPBlockBase::getExitBasicBlock() const {
169   const VPBlockBase *Block = this;
170   while (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
171     Block = Region->getExit();
172   return cast<VPBasicBlock>(Block);
173 }
174 
175 VPBasicBlock *VPBlockBase::getExitBasicBlock() {
176   VPBlockBase *Block = this;
177   while (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
178     Block = Region->getExit();
179   return cast<VPBasicBlock>(Block);
180 }
181 
182 VPBlockBase *VPBlockBase::getEnclosingBlockWithSuccessors() {
183   if (!Successors.empty() || !Parent)
184     return this;
185   assert(Parent->getExit() == this &&
186          "Block w/o successors not the exit of its parent.");
187   return Parent->getEnclosingBlockWithSuccessors();
188 }
189 
190 VPBlockBase *VPBlockBase::getEnclosingBlockWithPredecessors() {
191   if (!Predecessors.empty() || !Parent)
192     return this;
193   assert(Parent->getEntry() == this &&
194          "Block w/o predecessors not the entry of its parent.");
195   return Parent->getEnclosingBlockWithPredecessors();
196 }
197 
198 void VPBlockBase::deleteCFG(VPBlockBase *Entry) {
199   SmallVector<VPBlockBase *, 8> Blocks;
200 
201   VPValue DummyValue;
202   for (VPBlockBase *Block : depth_first(Entry)) {
203     // Drop all references in VPBasicBlocks and replace all uses with
204     // DummyValue.
205     if (auto *VPBB = dyn_cast<VPBasicBlock>(Block))
206       VPBB->dropAllReferences(&DummyValue);
207     Blocks.push_back(Block);
208   }
209 
210   for (VPBlockBase *Block : Blocks)
211     delete Block;
212 }
213 
214 VPBasicBlock::iterator VPBasicBlock::getFirstNonPhi() {
215   iterator It = begin();
216   while (It != end() &&
217          (It->getVPRecipeID() == VPRecipeBase::VPWidenPHISC ||
218           It->getVPRecipeID() == VPRecipeBase::VPWidenIntOrFpInductionSC ||
219           It->getVPRecipeID() == VPRecipeBase::VPPredInstPHISC ||
220           It->getVPRecipeID() == VPRecipeBase::VPWidenCanonicalIVSC))
221     It++;
222   return It;
223 }
224 
225 BasicBlock *
226 VPBasicBlock::createEmptyBasicBlock(VPTransformState::CFGState &CFG) {
227   // BB stands for IR BasicBlocks. VPBB stands for VPlan VPBasicBlocks.
228   // Pred stands for Predessor. Prev stands for Previous - last visited/created.
229   BasicBlock *PrevBB = CFG.PrevBB;
230   BasicBlock *NewBB = BasicBlock::Create(PrevBB->getContext(), getName(),
231                                          PrevBB->getParent(), CFG.LastBB);
232   LLVM_DEBUG(dbgs() << "LV: created " << NewBB->getName() << '\n');
233 
234   // Hook up the new basic block to its predecessors.
235   for (VPBlockBase *PredVPBlock : getHierarchicalPredecessors()) {
236     VPBasicBlock *PredVPBB = PredVPBlock->getExitBasicBlock();
237     auto &PredVPSuccessors = PredVPBB->getSuccessors();
238     BasicBlock *PredBB = CFG.VPBB2IRBB[PredVPBB];
239 
240     // In outer loop vectorization scenario, the predecessor BBlock may not yet
241     // be visited(backedge). Mark the VPBasicBlock for fixup at the end of
242     // vectorization. We do not encounter this case in inner loop vectorization
243     // as we start out by building a loop skeleton with the vector loop header
244     // and latch blocks. As a result, we never enter this function for the
245     // header block in the non VPlan-native path.
246     if (!PredBB) {
247       assert(EnableVPlanNativePath &&
248              "Unexpected null predecessor in non VPlan-native path");
249       CFG.VPBBsToFix.push_back(PredVPBB);
250       continue;
251     }
252 
253     assert(PredBB && "Predecessor basic-block not found building successor.");
254     auto *PredBBTerminator = PredBB->getTerminator();
255     LLVM_DEBUG(dbgs() << "LV: draw edge from" << PredBB->getName() << '\n');
256     if (isa<UnreachableInst>(PredBBTerminator)) {
257       assert(PredVPSuccessors.size() == 1 &&
258              "Predecessor ending w/o branch must have single successor.");
259       PredBBTerminator->eraseFromParent();
260       BranchInst::Create(NewBB, PredBB);
261     } else {
262       assert(PredVPSuccessors.size() == 2 &&
263              "Predecessor ending with branch must have two successors.");
264       unsigned idx = PredVPSuccessors.front() == this ? 0 : 1;
265       assert(!PredBBTerminator->getSuccessor(idx) &&
266              "Trying to reset an existing successor block.");
267       PredBBTerminator->setSuccessor(idx, NewBB);
268     }
269   }
270   return NewBB;
271 }
272 
273 void VPBasicBlock::execute(VPTransformState *State) {
274   bool Replica = State->Instance &&
275                  !(State->Instance->Part == 0 && State->Instance->Lane == 0);
276   VPBasicBlock *PrevVPBB = State->CFG.PrevVPBB;
277   VPBlockBase *SingleHPred = nullptr;
278   BasicBlock *NewBB = State->CFG.PrevBB; // Reuse it if possible.
279 
280   // 1. Create an IR basic block, or reuse the last one if possible.
281   // The last IR basic block is reused, as an optimization, in three cases:
282   // A. the first VPBB reuses the loop header BB - when PrevVPBB is null;
283   // B. when the current VPBB has a single (hierarchical) predecessor which
284   //    is PrevVPBB and the latter has a single (hierarchical) successor; and
285   // C. when the current VPBB is an entry of a region replica - where PrevVPBB
286   //    is the exit of this region from a previous instance, or the predecessor
287   //    of this region.
288   if (PrevVPBB && /* A */
289       !((SingleHPred = getSingleHierarchicalPredecessor()) &&
290         SingleHPred->getExitBasicBlock() == PrevVPBB &&
291         PrevVPBB->getSingleHierarchicalSuccessor()) && /* B */
292       !(Replica && getPredecessors().empty())) {       /* C */
293     NewBB = createEmptyBasicBlock(State->CFG);
294     State->Builder.SetInsertPoint(NewBB);
295     // Temporarily terminate with unreachable until CFG is rewired.
296     UnreachableInst *Terminator = State->Builder.CreateUnreachable();
297     State->Builder.SetInsertPoint(Terminator);
298     // Register NewBB in its loop. In innermost loops its the same for all BB's.
299     Loop *L = State->LI->getLoopFor(State->CFG.LastBB);
300     L->addBasicBlockToLoop(NewBB, *State->LI);
301     State->CFG.PrevBB = NewBB;
302   }
303 
304   // 2. Fill the IR basic block with IR instructions.
305   LLVM_DEBUG(dbgs() << "LV: vectorizing VPBB:" << getName()
306                     << " in BB:" << NewBB->getName() << '\n');
307 
308   State->CFG.VPBB2IRBB[this] = NewBB;
309   State->CFG.PrevVPBB = this;
310 
311   for (VPRecipeBase &Recipe : Recipes)
312     Recipe.execute(*State);
313 
314   VPValue *CBV;
315   if (EnableVPlanNativePath && (CBV = getCondBit())) {
316     Value *IRCBV = CBV->getUnderlyingValue();
317     assert(IRCBV && "Unexpected null underlying value for condition bit");
318 
319     // Condition bit value in a VPBasicBlock is used as the branch selector. In
320     // the VPlan-native path case, since all branches are uniform we generate a
321     // branch instruction using the condition value from vector lane 0 and dummy
322     // successors. The successors are fixed later when the successor blocks are
323     // visited.
324     Value *NewCond = State->Callback.getOrCreateVectorValues(IRCBV, 0);
325     NewCond = State->Builder.CreateExtractElement(NewCond,
326                                                   State->Builder.getInt32(0));
327 
328     // Replace the temporary unreachable terminator with the new conditional
329     // branch.
330     auto *CurrentTerminator = NewBB->getTerminator();
331     assert(isa<UnreachableInst>(CurrentTerminator) &&
332            "Expected to replace unreachable terminator with conditional "
333            "branch.");
334     auto *CondBr = BranchInst::Create(NewBB, nullptr, NewCond);
335     CondBr->setSuccessor(0, nullptr);
336     ReplaceInstWithInst(CurrentTerminator, CondBr);
337   }
338 
339   LLVM_DEBUG(dbgs() << "LV: filled BB:" << *NewBB);
340 }
341 
342 void VPBasicBlock::dropAllReferences(VPValue *NewValue) {
343   for (VPRecipeBase &R : Recipes) {
344     if (auto *VPV = R.toVPValue())
345       VPV->replaceAllUsesWith(NewValue);
346 
347     if (auto *User = R.toVPUser())
348       for (unsigned I = 0, E = User->getNumOperands(); I != E; I++)
349         User->setOperand(I, NewValue);
350   }
351 }
352 
353 void VPRegionBlock::execute(VPTransformState *State) {
354   ReversePostOrderTraversal<VPBlockBase *> RPOT(Entry);
355 
356   if (!isReplicator()) {
357     // Visit the VPBlocks connected to "this", starting from it.
358     for (VPBlockBase *Block : RPOT) {
359       if (EnableVPlanNativePath) {
360         // The inner loop vectorization path does not represent loop preheader
361         // and exit blocks as part of the VPlan. In the VPlan-native path, skip
362         // vectorizing loop preheader block. In future, we may replace this
363         // check with the check for loop preheader.
364         if (Block->getNumPredecessors() == 0)
365           continue;
366 
367         // Skip vectorizing loop exit block. In future, we may replace this
368         // check with the check for loop exit.
369         if (Block->getNumSuccessors() == 0)
370           continue;
371       }
372 
373       LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
374       Block->execute(State);
375     }
376     return;
377   }
378 
379   assert(!State->Instance && "Replicating a Region with non-null instance.");
380 
381   // Enter replicating mode.
382   State->Instance = {0, 0};
383 
384   for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part) {
385     State->Instance->Part = Part;
386     assert(!State->VF.isScalable() && "VF is assumed to be non scalable.");
387     for (unsigned Lane = 0, VF = State->VF.getKnownMinValue(); Lane < VF;
388          ++Lane) {
389       State->Instance->Lane = Lane;
390       // Visit the VPBlocks connected to \p this, starting from it.
391       for (VPBlockBase *Block : RPOT) {
392         LLVM_DEBUG(dbgs() << "LV: VPBlock in RPO " << Block->getName() << '\n');
393         Block->execute(State);
394       }
395     }
396   }
397 
398   // Exit replicating mode.
399   State->Instance.reset();
400 }
401 
402 void VPRecipeBase::insertBefore(VPRecipeBase *InsertPos) {
403   assert(!Parent && "Recipe already in some VPBasicBlock");
404   assert(InsertPos->getParent() &&
405          "Insertion position not in any VPBasicBlock");
406   Parent = InsertPos->getParent();
407   Parent->getRecipeList().insert(InsertPos->getIterator(), this);
408 }
409 
410 void VPRecipeBase::insertAfter(VPRecipeBase *InsertPos) {
411   assert(!Parent && "Recipe already in some VPBasicBlock");
412   assert(InsertPos->getParent() &&
413          "Insertion position not in any VPBasicBlock");
414   Parent = InsertPos->getParent();
415   Parent->getRecipeList().insertAfter(InsertPos->getIterator(), this);
416 }
417 
418 void VPRecipeBase::removeFromParent() {
419   assert(getParent() && "Recipe not in any VPBasicBlock");
420   getParent()->getRecipeList().remove(getIterator());
421   Parent = nullptr;
422 }
423 
424 iplist<VPRecipeBase>::iterator VPRecipeBase::eraseFromParent() {
425   assert(getParent() && "Recipe not in any VPBasicBlock");
426   // If the recipe is a VPValue and has been added to the containing VPlan,
427   // remove the mapping.
428   if (Value *UV = getUnderlyingInstr())
429     if (!UV->getType()->isVoidTy())
430       if (auto *Plan = getParent()->getPlan())
431         Plan->removeVPValueFor(UV);
432 
433   return getParent()->getRecipeList().erase(getIterator());
434 }
435 
436 void VPRecipeBase::moveAfter(VPRecipeBase *InsertPos) {
437   removeFromParent();
438   insertAfter(InsertPos);
439 }
440 
441 void VPInstruction::generateInstruction(VPTransformState &State,
442                                         unsigned Part) {
443   IRBuilder<> &Builder = State.Builder;
444 
445   if (Instruction::isBinaryOp(getOpcode())) {
446     Value *A = State.get(getOperand(0), Part);
447     Value *B = State.get(getOperand(1), Part);
448     Value *V = Builder.CreateBinOp((Instruction::BinaryOps)getOpcode(), A, B);
449     State.set(this, V, Part);
450     return;
451   }
452 
453   switch (getOpcode()) {
454   case VPInstruction::Not: {
455     Value *A = State.get(getOperand(0), Part);
456     Value *V = Builder.CreateNot(A);
457     State.set(this, V, Part);
458     break;
459   }
460   case VPInstruction::ICmpULE: {
461     Value *IV = State.get(getOperand(0), Part);
462     Value *TC = State.get(getOperand(1), Part);
463     Value *V = Builder.CreateICmpULE(IV, TC);
464     State.set(this, V, Part);
465     break;
466   }
467   case Instruction::Select: {
468     Value *Cond = State.get(getOperand(0), Part);
469     Value *Op1 = State.get(getOperand(1), Part);
470     Value *Op2 = State.get(getOperand(2), Part);
471     Value *V = Builder.CreateSelect(Cond, Op1, Op2);
472     State.set(this, V, Part);
473     break;
474   }
475   case VPInstruction::ActiveLaneMask: {
476     // Get first lane of vector induction variable.
477     Value *VIVElem0 = State.get(getOperand(0), {Part, 0});
478     // Get the original loop tripcount.
479     Value *ScalarTC = State.TripCount;
480 
481     auto *Int1Ty = Type::getInt1Ty(Builder.getContext());
482     auto *PredTy = FixedVectorType::get(Int1Ty, State.VF.getKnownMinValue());
483     Instruction *Call = Builder.CreateIntrinsic(
484         Intrinsic::get_active_lane_mask, {PredTy, ScalarTC->getType()},
485         {VIVElem0, ScalarTC}, nullptr, "active.lane.mask");
486     State.set(this, Call, Part);
487     break;
488   }
489   default:
490     llvm_unreachable("Unsupported opcode for instruction");
491   }
492 }
493 
494 void VPInstruction::execute(VPTransformState &State) {
495   assert(!State.Instance && "VPInstruction executing an Instance");
496   for (unsigned Part = 0; Part < State.UF; ++Part)
497     generateInstruction(State, Part);
498 }
499 
500 void VPInstruction::print(raw_ostream &O, const Twine &Indent,
501                           VPSlotTracker &SlotTracker) const {
502   O << "\"EMIT ";
503   print(O, SlotTracker);
504 }
505 
506 void VPInstruction::print(raw_ostream &O) const {
507   VPSlotTracker SlotTracker(getParent()->getPlan());
508   print(O, SlotTracker);
509 }
510 
511 void VPInstruction::print(raw_ostream &O, VPSlotTracker &SlotTracker) const {
512   if (hasResult()) {
513     printAsOperand(O, SlotTracker);
514     O << " = ";
515   }
516 
517   switch (getOpcode()) {
518   case VPInstruction::Not:
519     O << "not";
520     break;
521   case VPInstruction::ICmpULE:
522     O << "icmp ule";
523     break;
524   case VPInstruction::SLPLoad:
525     O << "combined load";
526     break;
527   case VPInstruction::SLPStore:
528     O << "combined store";
529     break;
530   case VPInstruction::ActiveLaneMask:
531     O << "active lane mask";
532     break;
533 
534   default:
535     O << Instruction::getOpcodeName(getOpcode());
536   }
537 
538   for (const VPValue *Operand : operands()) {
539     O << " ";
540     Operand->printAsOperand(O, SlotTracker);
541   }
542 }
543 
544 /// Generate the code inside the body of the vectorized loop. Assumes a single
545 /// LoopVectorBody basic-block was created for this. Introduce additional
546 /// basic-blocks as needed, and fill them all.
547 void VPlan::execute(VPTransformState *State) {
548   // -1. Check if the backedge taken count is needed, and if so build it.
549   if (BackedgeTakenCount && BackedgeTakenCount->getNumUsers()) {
550     Value *TC = State->TripCount;
551     IRBuilder<> Builder(State->CFG.PrevBB->getTerminator());
552     auto *TCMO = Builder.CreateSub(TC, ConstantInt::get(TC->getType(), 1),
553                                    "trip.count.minus.1");
554     auto VF = State->VF;
555     Value *VTCMO =
556         VF.isScalar() ? TCMO : Builder.CreateVectorSplat(VF, TCMO, "broadcast");
557     for (unsigned Part = 0, UF = State->UF; Part < UF; ++Part)
558       State->set(BackedgeTakenCount, VTCMO, Part);
559   }
560 
561   // 0. Set the reverse mapping from VPValues to Values for code generation.
562   for (auto &Entry : Value2VPValue)
563     State->VPValue2Value[Entry.second] = Entry.first;
564 
565   BasicBlock *VectorPreHeaderBB = State->CFG.PrevBB;
566   BasicBlock *VectorHeaderBB = VectorPreHeaderBB->getSingleSuccessor();
567   assert(VectorHeaderBB && "Loop preheader does not have a single successor.");
568 
569   // 1. Make room to generate basic-blocks inside loop body if needed.
570   BasicBlock *VectorLatchBB = VectorHeaderBB->splitBasicBlock(
571       VectorHeaderBB->getFirstInsertionPt(), "vector.body.latch");
572   Loop *L = State->LI->getLoopFor(VectorHeaderBB);
573   L->addBasicBlockToLoop(VectorLatchBB, *State->LI);
574   // Remove the edge between Header and Latch to allow other connections.
575   // Temporarily terminate with unreachable until CFG is rewired.
576   // Note: this asserts the generated code's assumption that
577   // getFirstInsertionPt() can be dereferenced into an Instruction.
578   VectorHeaderBB->getTerminator()->eraseFromParent();
579   State->Builder.SetInsertPoint(VectorHeaderBB);
580   UnreachableInst *Terminator = State->Builder.CreateUnreachable();
581   State->Builder.SetInsertPoint(Terminator);
582 
583   // 2. Generate code in loop body.
584   State->CFG.PrevVPBB = nullptr;
585   State->CFG.PrevBB = VectorHeaderBB;
586   State->CFG.LastBB = VectorLatchBB;
587 
588   for (VPBlockBase *Block : depth_first(Entry))
589     Block->execute(State);
590 
591   // Setup branch terminator successors for VPBBs in VPBBsToFix based on
592   // VPBB's successors.
593   for (auto VPBB : State->CFG.VPBBsToFix) {
594     assert(EnableVPlanNativePath &&
595            "Unexpected VPBBsToFix in non VPlan-native path");
596     BasicBlock *BB = State->CFG.VPBB2IRBB[VPBB];
597     assert(BB && "Unexpected null basic block for VPBB");
598 
599     unsigned Idx = 0;
600     auto *BBTerminator = BB->getTerminator();
601 
602     for (VPBlockBase *SuccVPBlock : VPBB->getHierarchicalSuccessors()) {
603       VPBasicBlock *SuccVPBB = SuccVPBlock->getEntryBasicBlock();
604       BBTerminator->setSuccessor(Idx, State->CFG.VPBB2IRBB[SuccVPBB]);
605       ++Idx;
606     }
607   }
608 
609   // 3. Merge the temporary latch created with the last basic-block filled.
610   BasicBlock *LastBB = State->CFG.PrevBB;
611   // Connect LastBB to VectorLatchBB to facilitate their merge.
612   assert((EnableVPlanNativePath ||
613           isa<UnreachableInst>(LastBB->getTerminator())) &&
614          "Expected InnerLoop VPlan CFG to terminate with unreachable");
615   assert((!EnableVPlanNativePath || isa<BranchInst>(LastBB->getTerminator())) &&
616          "Expected VPlan CFG to terminate with branch in NativePath");
617   LastBB->getTerminator()->eraseFromParent();
618   BranchInst::Create(VectorLatchBB, LastBB);
619 
620   // Merge LastBB with Latch.
621   bool Merged = MergeBlockIntoPredecessor(VectorLatchBB, nullptr, State->LI);
622   (void)Merged;
623   assert(Merged && "Could not merge last basic block with latch.");
624   VectorLatchBB = LastBB;
625 
626   // We do not attempt to preserve DT for outer loop vectorization currently.
627   if (!EnableVPlanNativePath)
628     updateDominatorTree(State->DT, VectorPreHeaderBB, VectorLatchBB,
629                         L->getExitBlock());
630 }
631 
632 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
633 LLVM_DUMP_METHOD
634 void VPlan::dump() const { dbgs() << *this << '\n'; }
635 #endif
636 
637 void VPlan::updateDominatorTree(DominatorTree *DT, BasicBlock *LoopPreHeaderBB,
638                                 BasicBlock *LoopLatchBB,
639                                 BasicBlock *LoopExitBB) {
640   BasicBlock *LoopHeaderBB = LoopPreHeaderBB->getSingleSuccessor();
641   assert(LoopHeaderBB && "Loop preheader does not have a single successor.");
642   // The vector body may be more than a single basic-block by this point.
643   // Update the dominator tree information inside the vector body by propagating
644   // it from header to latch, expecting only triangular control-flow, if any.
645   BasicBlock *PostDomSucc = nullptr;
646   for (auto *BB = LoopHeaderBB; BB != LoopLatchBB; BB = PostDomSucc) {
647     // Get the list of successors of this block.
648     std::vector<BasicBlock *> Succs(succ_begin(BB), succ_end(BB));
649     assert(Succs.size() <= 2 &&
650            "Basic block in vector loop has more than 2 successors.");
651     PostDomSucc = Succs[0];
652     if (Succs.size() == 1) {
653       assert(PostDomSucc->getSinglePredecessor() &&
654              "PostDom successor has more than one predecessor.");
655       DT->addNewBlock(PostDomSucc, BB);
656       continue;
657     }
658     BasicBlock *InterimSucc = Succs[1];
659     if (PostDomSucc->getSingleSuccessor() == InterimSucc) {
660       PostDomSucc = Succs[1];
661       InterimSucc = Succs[0];
662     }
663     assert(InterimSucc->getSingleSuccessor() == PostDomSucc &&
664            "One successor of a basic block does not lead to the other.");
665     assert(InterimSucc->getSinglePredecessor() &&
666            "Interim successor has more than one predecessor.");
667     assert(PostDomSucc->hasNPredecessors(2) &&
668            "PostDom successor has more than two predecessors.");
669     DT->addNewBlock(InterimSucc, BB);
670     DT->addNewBlock(PostDomSucc, BB);
671   }
672   // Latch block is a new dominator for the loop exit.
673   DT->changeImmediateDominator(LoopExitBB, LoopLatchBB);
674   assert(DT->verify(DominatorTree::VerificationLevel::Fast));
675 }
676 
677 const Twine VPlanPrinter::getUID(const VPBlockBase *Block) {
678   return (isa<VPRegionBlock>(Block) ? "cluster_N" : "N") +
679          Twine(getOrCreateBID(Block));
680 }
681 
682 const Twine VPlanPrinter::getOrCreateName(const VPBlockBase *Block) {
683   const std::string &Name = Block->getName();
684   if (!Name.empty())
685     return Name;
686   return "VPB" + Twine(getOrCreateBID(Block));
687 }
688 
689 void VPlanPrinter::dump() {
690   Depth = 1;
691   bumpIndent(0);
692   OS << "digraph VPlan {\n";
693   OS << "graph [labelloc=t, fontsize=30; label=\"Vectorization Plan";
694   if (!Plan.getName().empty())
695     OS << "\\n" << DOT::EscapeString(Plan.getName());
696   if (Plan.BackedgeTakenCount) {
697     OS << ", where:\\n";
698     Plan.BackedgeTakenCount->print(OS, SlotTracker);
699     OS << " := BackedgeTakenCount";
700   }
701   OS << "\"]\n";
702   OS << "node [shape=rect, fontname=Courier, fontsize=30]\n";
703   OS << "edge [fontname=Courier, fontsize=30]\n";
704   OS << "compound=true\n";
705 
706   for (const VPBlockBase *Block : depth_first(Plan.getEntry()))
707     dumpBlock(Block);
708 
709   OS << "}\n";
710 }
711 
712 void VPlanPrinter::dumpBlock(const VPBlockBase *Block) {
713   if (const VPBasicBlock *BasicBlock = dyn_cast<VPBasicBlock>(Block))
714     dumpBasicBlock(BasicBlock);
715   else if (const VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
716     dumpRegion(Region);
717   else
718     llvm_unreachable("Unsupported kind of VPBlock.");
719 }
720 
721 void VPlanPrinter::drawEdge(const VPBlockBase *From, const VPBlockBase *To,
722                             bool Hidden, const Twine &Label) {
723   // Due to "dot" we print an edge between two regions as an edge between the
724   // exit basic block and the entry basic of the respective regions.
725   const VPBlockBase *Tail = From->getExitBasicBlock();
726   const VPBlockBase *Head = To->getEntryBasicBlock();
727   OS << Indent << getUID(Tail) << " -> " << getUID(Head);
728   OS << " [ label=\"" << Label << '\"';
729   if (Tail != From)
730     OS << " ltail=" << getUID(From);
731   if (Head != To)
732     OS << " lhead=" << getUID(To);
733   if (Hidden)
734     OS << "; splines=none";
735   OS << "]\n";
736 }
737 
738 void VPlanPrinter::dumpEdges(const VPBlockBase *Block) {
739   auto &Successors = Block->getSuccessors();
740   if (Successors.size() == 1)
741     drawEdge(Block, Successors.front(), false, "");
742   else if (Successors.size() == 2) {
743     drawEdge(Block, Successors.front(), false, "T");
744     drawEdge(Block, Successors.back(), false, "F");
745   } else {
746     unsigned SuccessorNumber = 0;
747     for (auto *Successor : Successors)
748       drawEdge(Block, Successor, false, Twine(SuccessorNumber++));
749   }
750 }
751 
752 void VPlanPrinter::dumpBasicBlock(const VPBasicBlock *BasicBlock) {
753   OS << Indent << getUID(BasicBlock) << " [label =\n";
754   bumpIndent(1);
755   OS << Indent << "\"" << DOT::EscapeString(BasicBlock->getName()) << ":\\n\"";
756   bumpIndent(1);
757 
758   // Dump the block predicate.
759   const VPValue *Pred = BasicBlock->getPredicate();
760   if (Pred) {
761     OS << " +\n" << Indent << " \"BlockPredicate: ";
762     if (const VPInstruction *PredI = dyn_cast<VPInstruction>(Pred)) {
763       PredI->printAsOperand(OS, SlotTracker);
764       OS << " (" << DOT::EscapeString(PredI->getParent()->getName())
765          << ")\\l\"";
766     } else
767       Pred->printAsOperand(OS, SlotTracker);
768   }
769 
770   for (const VPRecipeBase &Recipe : *BasicBlock) {
771     OS << " +\n" << Indent;
772     Recipe.print(OS, Indent, SlotTracker);
773     OS << "\\l\"";
774   }
775 
776   // Dump the condition bit.
777   const VPValue *CBV = BasicBlock->getCondBit();
778   if (CBV) {
779     OS << " +\n" << Indent << " \"CondBit: ";
780     if (const VPInstruction *CBI = dyn_cast<VPInstruction>(CBV)) {
781       CBI->printAsOperand(OS, SlotTracker);
782       OS << " (" << DOT::EscapeString(CBI->getParent()->getName()) << ")\\l\"";
783     } else {
784       CBV->printAsOperand(OS, SlotTracker);
785       OS << "\"";
786     }
787   }
788 
789   bumpIndent(-2);
790   OS << "\n" << Indent << "]\n";
791   dumpEdges(BasicBlock);
792 }
793 
794 void VPlanPrinter::dumpRegion(const VPRegionBlock *Region) {
795   OS << Indent << "subgraph " << getUID(Region) << " {\n";
796   bumpIndent(1);
797   OS << Indent << "fontname=Courier\n"
798      << Indent << "label=\""
799      << DOT::EscapeString(Region->isReplicator() ? "<xVFxUF> " : "<x1> ")
800      << DOT::EscapeString(Region->getName()) << "\"\n";
801   // Dump the blocks of the region.
802   assert(Region->getEntry() && "Region contains no inner blocks.");
803   for (const VPBlockBase *Block : depth_first(Region->getEntry()))
804     dumpBlock(Block);
805   bumpIndent(-1);
806   OS << Indent << "}\n";
807   dumpEdges(Region);
808 }
809 
810 void VPlanPrinter::printAsIngredient(raw_ostream &O, const Value *V) {
811   std::string IngredientString;
812   raw_string_ostream RSO(IngredientString);
813   if (auto *Inst = dyn_cast<Instruction>(V)) {
814     if (!Inst->getType()->isVoidTy()) {
815       Inst->printAsOperand(RSO, false);
816       RSO << " = ";
817     }
818     RSO << Inst->getOpcodeName() << " ";
819     unsigned E = Inst->getNumOperands();
820     if (E > 0) {
821       Inst->getOperand(0)->printAsOperand(RSO, false);
822       for (unsigned I = 1; I < E; ++I)
823         Inst->getOperand(I)->printAsOperand(RSO << ", ", false);
824     }
825   } else // !Inst
826     V->printAsOperand(RSO, false);
827   RSO.flush();
828   O << DOT::EscapeString(IngredientString);
829 }
830 
831 void VPWidenCallRecipe::print(raw_ostream &O, const Twine &Indent,
832                               VPSlotTracker &SlotTracker) const {
833   O << "\"WIDEN-CALL " << VPlanIngredient(&Ingredient);
834 }
835 
836 void VPWidenSelectRecipe::print(raw_ostream &O, const Twine &Indent,
837                                 VPSlotTracker &SlotTracker) const {
838   O << "\"WIDEN-SELECT" << VPlanIngredient(&Ingredient)
839     << (InvariantCond ? " (condition is loop invariant)" : "");
840 }
841 
842 void VPWidenRecipe::print(raw_ostream &O, const Twine &Indent,
843                           VPSlotTracker &SlotTracker) const {
844   O << "\"WIDEN\\l\"";
845   O << "\"  " << VPlanIngredient(&Ingredient);
846 }
847 
848 void VPWidenIntOrFpInductionRecipe::print(raw_ostream &O, const Twine &Indent,
849                                           VPSlotTracker &SlotTracker) const {
850   O << "\"WIDEN-INDUCTION";
851   if (Trunc) {
852     O << "\\l\"";
853     O << " +\n" << Indent << "\"  " << VPlanIngredient(IV) << "\\l\"";
854     O << " +\n" << Indent << "\"  " << VPlanIngredient(Trunc);
855   } else
856     O << " " << VPlanIngredient(IV);
857 }
858 
859 void VPWidenGEPRecipe::print(raw_ostream &O, const Twine &Indent,
860                              VPSlotTracker &SlotTracker) const {
861   O << "\"WIDEN-GEP ";
862   O << (IsPtrLoopInvariant ? "Inv" : "Var");
863   size_t IndicesNumber = IsIndexLoopInvariant.size();
864   for (size_t I = 0; I < IndicesNumber; ++I)
865     O << "[" << (IsIndexLoopInvariant[I] ? "Inv" : "Var") << "]";
866   O << "\\l\"";
867   O << " +\n" << Indent << "\"  " << VPlanIngredient(GEP);
868 }
869 
870 void VPWidenPHIRecipe::print(raw_ostream &O, const Twine &Indent,
871                              VPSlotTracker &SlotTracker) const {
872   O << "\"WIDEN-PHI " << VPlanIngredient(Phi);
873 }
874 
875 void VPBlendRecipe::print(raw_ostream &O, const Twine &Indent,
876                           VPSlotTracker &SlotTracker) const {
877   O << "\"BLEND ";
878   Phi->printAsOperand(O, false);
879   O << " =";
880   if (getNumIncomingValues() == 1) {
881     // Not a User of any mask: not really blending, this is a
882     // single-predecessor phi.
883     O << " ";
884     getIncomingValue(0)->printAsOperand(O, SlotTracker);
885   } else {
886     for (unsigned I = 0, E = getNumIncomingValues(); I < E; ++I) {
887       O << " ";
888       getIncomingValue(I)->printAsOperand(O, SlotTracker);
889       O << "/";
890       getMask(I)->printAsOperand(O, SlotTracker);
891     }
892   }
893 }
894 
895 void VPReductionRecipe::print(raw_ostream &O, const Twine &Indent,
896                               VPSlotTracker &SlotTracker) const {
897   O << "\"REDUCE of" << *I << " as ";
898   ChainOp->printAsOperand(O, SlotTracker);
899   O << " + reduce(";
900   VecOp->printAsOperand(O, SlotTracker);
901   if (CondOp) {
902     O << ", ";
903     CondOp->printAsOperand(O, SlotTracker);
904   }
905   O << ")";
906 }
907 
908 void VPReplicateRecipe::print(raw_ostream &O, const Twine &Indent,
909                               VPSlotTracker &SlotTracker) const {
910   O << "\"" << (IsUniform ? "CLONE " : "REPLICATE ")
911     << VPlanIngredient(Ingredient);
912   if (AlsoPack)
913     O << " (S->V)";
914 }
915 
916 void VPPredInstPHIRecipe::print(raw_ostream &O, const Twine &Indent,
917                                 VPSlotTracker &SlotTracker) const {
918   O << "\"PHI-PREDICATED-INSTRUCTION " << VPlanIngredient(PredInst);
919 }
920 
921 void VPWidenMemoryInstructionRecipe::print(raw_ostream &O, const Twine &Indent,
922                                            VPSlotTracker &SlotTracker) const {
923   O << "\"WIDEN "
924     << Instruction::getOpcodeName(getUnderlyingInstr()->getOpcode()) << " ";
925 
926   bool First = true;
927   for (VPValue *Op : operands()) {
928     if (!First)
929       O << ", ";
930     Op->printAsOperand(O, SlotTracker);
931     First = false;
932   }
933 }
934 
935 void VPWidenCanonicalIVRecipe::execute(VPTransformState &State) {
936   Value *CanonicalIV = State.CanonicalIV;
937   Type *STy = CanonicalIV->getType();
938   IRBuilder<> Builder(State.CFG.PrevBB->getTerminator());
939   ElementCount VF = State.VF;
940   assert(!VF.isScalable() && "the code following assumes non scalables ECs");
941   Value *VStart = VF.isScalar()
942                       ? CanonicalIV
943                       : Builder.CreateVectorSplat(VF.getKnownMinValue(),
944                                                   CanonicalIV, "broadcast");
945   for (unsigned Part = 0, UF = State.UF; Part < UF; ++Part) {
946     SmallVector<Constant *, 8> Indices;
947     for (unsigned Lane = 0; Lane < VF.getKnownMinValue(); ++Lane)
948       Indices.push_back(
949           ConstantInt::get(STy, Part * VF.getKnownMinValue() + Lane));
950     // If VF == 1, there is only one iteration in the loop above, thus the
951     // element pushed back into Indices is ConstantInt::get(STy, Part)
952     Constant *VStep =
953         VF.isScalar() ? Indices.back() : ConstantVector::get(Indices);
954     // Add the consecutive indices to the vector value.
955     Value *CanonicalVectorIV = Builder.CreateAdd(VStart, VStep, "vec.iv");
956     State.set(getVPValue(), CanonicalVectorIV, Part);
957   }
958 }
959 
960 void VPWidenCanonicalIVRecipe::print(raw_ostream &O, const Twine &Indent,
961                                      VPSlotTracker &SlotTracker) const {
962   O << "\"EMIT ";
963   getVPValue()->printAsOperand(O, SlotTracker);
964   O << " = WIDEN-CANONICAL-INDUCTION";
965 }
966 
967 template void DomTreeBuilder::Calculate<VPDominatorTree>(VPDominatorTree &DT);
968 
969 void VPValue::replaceAllUsesWith(VPValue *New) {
970   for (unsigned J = 0; J < getNumUsers();) {
971     VPUser *User = Users[J];
972     unsigned NumUsers = getNumUsers();
973     for (unsigned I = 0, E = User->getNumOperands(); I < E; ++I)
974       if (User->getOperand(I) == this)
975         User->setOperand(I, New);
976     // If a user got removed after updating the current user, the next user to
977     // update will be moved to the current position, so we only need to
978     // increment the index if the number of users did not change.
979     if (NumUsers == getNumUsers())
980       J++;
981   }
982 }
983 
984 void VPValue::printAsOperand(raw_ostream &OS, VPSlotTracker &Tracker) const {
985   if (const Value *UV = getUnderlyingValue()) {
986     OS << "ir<";
987     UV->printAsOperand(OS, false);
988     OS << ">";
989     return;
990   }
991 
992   unsigned Slot = Tracker.getSlot(this);
993   if (Slot == unsigned(-1))
994     OS << "<badref>";
995   else
996     OS << "vp<%" << Tracker.getSlot(this) << ">";
997 }
998 
999 void VPInterleavedAccessInfo::visitRegion(VPRegionBlock *Region,
1000                                           Old2NewTy &Old2New,
1001                                           InterleavedAccessInfo &IAI) {
1002   ReversePostOrderTraversal<VPBlockBase *> RPOT(Region->getEntry());
1003   for (VPBlockBase *Base : RPOT) {
1004     visitBlock(Base, Old2New, IAI);
1005   }
1006 }
1007 
1008 void VPInterleavedAccessInfo::visitBlock(VPBlockBase *Block, Old2NewTy &Old2New,
1009                                          InterleavedAccessInfo &IAI) {
1010   if (VPBasicBlock *VPBB = dyn_cast<VPBasicBlock>(Block)) {
1011     for (VPRecipeBase &VPI : *VPBB) {
1012       assert(isa<VPInstruction>(&VPI) && "Can only handle VPInstructions");
1013       auto *VPInst = cast<VPInstruction>(&VPI);
1014       auto *Inst = cast<Instruction>(VPInst->getUnderlyingValue());
1015       auto *IG = IAI.getInterleaveGroup(Inst);
1016       if (!IG)
1017         continue;
1018 
1019       auto NewIGIter = Old2New.find(IG);
1020       if (NewIGIter == Old2New.end())
1021         Old2New[IG] = new InterleaveGroup<VPInstruction>(
1022             IG->getFactor(), IG->isReverse(), IG->getAlign());
1023 
1024       if (Inst == IG->getInsertPos())
1025         Old2New[IG]->setInsertPos(VPInst);
1026 
1027       InterleaveGroupMap[VPInst] = Old2New[IG];
1028       InterleaveGroupMap[VPInst]->insertMember(
1029           VPInst, IG->getIndex(Inst),
1030           Align(IG->isReverse() ? (-1) * int(IG->getFactor())
1031                                 : IG->getFactor()));
1032     }
1033   } else if (VPRegionBlock *Region = dyn_cast<VPRegionBlock>(Block))
1034     visitRegion(Region, Old2New, IAI);
1035   else
1036     llvm_unreachable("Unsupported kind of VPBlock.");
1037 }
1038 
1039 VPInterleavedAccessInfo::VPInterleavedAccessInfo(VPlan &Plan,
1040                                                  InterleavedAccessInfo &IAI) {
1041   Old2NewTy Old2New;
1042   visitRegion(cast<VPRegionBlock>(Plan.getEntry()), Old2New, IAI);
1043 }
1044 
1045 void VPSlotTracker::assignSlot(const VPValue *V) {
1046   assert(Slots.find(V) == Slots.end() && "VPValue already has a slot!");
1047   const Value *UV = V->getUnderlyingValue();
1048   if (UV)
1049     return;
1050   const auto *VPI = dyn_cast<VPInstruction>(V);
1051   if (VPI && !VPI->hasResult())
1052     return;
1053 
1054   Slots[V] = NextSlot++;
1055 }
1056 
1057 void VPSlotTracker::assignSlots(const VPBlockBase *VPBB) {
1058   if (auto *Region = dyn_cast<VPRegionBlock>(VPBB))
1059     assignSlots(Region);
1060   else
1061     assignSlots(cast<VPBasicBlock>(VPBB));
1062 }
1063 
1064 void VPSlotTracker::assignSlots(const VPRegionBlock *Region) {
1065   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Region->getEntry());
1066   for (const VPBlockBase *Block : RPOT)
1067     assignSlots(Block);
1068 }
1069 
1070 void VPSlotTracker::assignSlots(const VPBasicBlock *VPBB) {
1071   for (const VPRecipeBase &Recipe : *VPBB) {
1072     if (const auto *VPI = dyn_cast<VPInstruction>(&Recipe))
1073       assignSlot(VPI);
1074     else if (const auto *VPIV = dyn_cast<VPWidenCanonicalIVRecipe>(&Recipe))
1075       assignSlot(VPIV->getVPValue());
1076   }
1077 }
1078 
1079 void VPSlotTracker::assignSlots(const VPlan &Plan) {
1080 
1081   for (const VPValue *V : Plan.VPExternalDefs)
1082     assignSlot(V);
1083 
1084   for (auto &E : Plan.Value2VPValue)
1085     if (!isa<VPInstruction>(E.second))
1086       assignSlot(E.second);
1087 
1088   for (const VPValue *V : Plan.VPCBVs)
1089     assignSlot(V);
1090 
1091   if (Plan.BackedgeTakenCount)
1092     assignSlot(Plan.BackedgeTakenCount);
1093 
1094   ReversePostOrderTraversal<const VPBlockBase *> RPOT(Plan.getEntry());
1095   for (const VPBlockBase *Block : RPOT)
1096     assignSlots(Block);
1097 }
1098