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