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