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