xref: /llvm-project/llvm/lib/Transforms/Vectorize/VPlanHCFGBuilder.cpp (revision d34b765cb22cbec73d23335f0e4a7a64a264828a)
1 //===-- VPlanHCFGBuilder.cpp ----------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// This file implements the construction of a VPlan-based Hierarchical CFG
12 /// (H-CFG) for an incoming IR. This construction comprises the following
13 /// components and steps:
14 //
15 /// 1. PlainCFGBuilder class: builds a plain VPBasicBlock-based CFG that
16 /// faithfully represents the CFG in the incoming IR. A VPRegionBlock (Top
17 /// Region) is created to enclose and serve as parent of all the VPBasicBlocks
18 /// in the plain CFG.
19 /// NOTE: At this point, there is a direct correspondence between all the
20 /// VPBasicBlocks created for the initial plain CFG and the incoming
21 /// BasicBlocks. However, this might change in the future.
22 ///
23 //===----------------------------------------------------------------------===//
24 
25 #include "VPlanHCFGBuilder.h"
26 #include "LoopVectorizationPlanner.h"
27 #include "llvm/Analysis/LoopIterator.h"
28 
29 #define DEBUG_TYPE "loop-vectorize"
30 
31 using namespace llvm;
32 
33 namespace {
34 // Class that is used to build the plain CFG for the incoming IR.
35 class PlainCFGBuilder {
36 private:
37   // The outermost loop of the input loop nest considered for vectorization.
38   Loop *TheLoop;
39 
40   // Loop Info analysis.
41   LoopInfo *LI;
42 
43   // Vectorization plan that we are working on.
44   VPlan &Plan;
45 
46   // Output Top Region.
47   VPRegionBlock *TopRegion = nullptr;
48 
49   // Builder of the VPlan instruction-level representation.
50   VPBuilder VPIRBuilder;
51 
52   // NOTE: The following maps are intentionally destroyed after the plain CFG
53   // construction because subsequent VPlan-to-VPlan transformation may
54   // invalidate them.
55   // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
56   DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB;
57   // Map incoming Value definitions to their newly-created VPValues.
58   DenseMap<Value *, VPValue *> IRDef2VPValue;
59 
60   // Hold phi node's that need to be fixed once the plain CFG has been built.
61   SmallVector<PHINode *, 8> PhisToFix;
62 
63   // Utility functions.
64   void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
65   void fixPhiNodes();
66   VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
67   bool isExternalDef(Value *Val);
68   VPValue *getOrCreateVPOperand(Value *IRVal);
69   void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);
70 
71 public:
72   PlainCFGBuilder(Loop *Lp, LoopInfo *LI, VPlan &P)
73       : TheLoop(Lp), LI(LI), Plan(P) {}
74 
75   // Build the plain CFG and return its Top Region.
76   VPRegionBlock *buildPlainCFG();
77 };
78 } // anonymous namespace
79 
80 // Return true if \p Inst is an incoming Instruction to be ignored in the VPlan
81 // representation.
82 static bool isInstructionToIgnore(Instruction *Inst) {
83   return isa<BranchInst>(Inst);
84 }
85 
86 // Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
87 // must have no predecessors.
88 void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
89   SmallVector<VPBlockBase *, 8> VPBBPreds;
90   // Collect VPBB predecessors.
91   for (BasicBlock *Pred : predecessors(BB))
92     VPBBPreds.push_back(getOrCreateVPBB(Pred));
93 
94   VPBB->setPredecessors(VPBBPreds);
95 }
96 
97 // Add operands to VPInstructions representing phi nodes from the input IR.
98 void PlainCFGBuilder::fixPhiNodes() {
99   for (auto *Phi : PhisToFix) {
100     assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
101     VPValue *VPVal = IRDef2VPValue[Phi];
102     assert(isa<VPInstruction>(VPVal) && "Expected VPInstruction for phi node.");
103     auto *VPPhi = cast<VPInstruction>(VPVal);
104     assert(VPPhi->getNumOperands() == 0 &&
105            "Expected VPInstruction with no operands.");
106 
107     for (Value *Op : Phi->operands())
108       VPPhi->addOperand(getOrCreateVPOperand(Op));
109   }
110 }
111 
112 // Create a new empty VPBasicBlock for an incoming BasicBlock or retrieve an
113 // existing one if it was already created.
114 VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
115   auto BlockIt = BB2VPBB.find(BB);
116   if (BlockIt != BB2VPBB.end())
117     // Retrieve existing VPBB.
118     return BlockIt->second;
119 
120   // Create new VPBB.
121   LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << BB->getName() << "\n");
122   VPBasicBlock *VPBB = new VPBasicBlock(BB->getName());
123   BB2VPBB[BB] = VPBB;
124   VPBB->setParent(TopRegion);
125   return VPBB;
126 }
127 
128 // Return true if \p Val is considered an external definition. An external
129 // definition is either:
130 // 1. A Value that is not an Instruction. This will be refined in the future.
131 // 2. An Instruction that is outside of the CFG snippet represented in VPlan,
132 // i.e., is not part of: a) the loop nest, b) outermost loop PH and, c)
133 // outermost loop exits.
134 bool PlainCFGBuilder::isExternalDef(Value *Val) {
135   // All the Values that are not Instructions are considered external
136   // definitions for now.
137   Instruction *Inst = dyn_cast<Instruction>(Val);
138   if (!Inst)
139     return true;
140 
141   BasicBlock *InstParent = Inst->getParent();
142   assert(InstParent && "Expected instruction parent.");
143 
144   // Check whether Instruction definition is in loop PH.
145   BasicBlock *PH = TheLoop->getLoopPreheader();
146   assert(PH && "Expected loop pre-header.");
147 
148   if (InstParent == PH)
149     // Instruction definition is in outermost loop PH.
150     return false;
151 
152   // Check whether Instruction definition is in the loop exit.
153   BasicBlock *Exit = TheLoop->getUniqueExitBlock();
154   assert(Exit && "Expected loop with single exit.");
155   if (InstParent == Exit) {
156     // Instruction definition is in outermost loop exit.
157     return false;
158   }
159 
160   // Check whether Instruction definition is in loop body.
161   return !TheLoop->contains(Inst);
162 }
163 
164 // Create a new VPValue or retrieve an existing one for the Instruction's
165 // operand \p IRVal. This function must only be used to create/retrieve VPValues
166 // for *Instruction's operands* and not to create regular VPInstruction's. For
167 // the latter, please, look at 'createVPInstructionsForVPBB'.
168 VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
169   auto VPValIt = IRDef2VPValue.find(IRVal);
170   if (VPValIt != IRDef2VPValue.end())
171     // Operand has an associated VPInstruction or VPValue that was previously
172     // created.
173     return VPValIt->second;
174 
175   // Operand doesn't have a previously created VPInstruction/VPValue. This
176   // means that operand is:
177   //   A) a definition external to VPlan,
178   //   B) any other Value without specific representation in VPlan.
179   // For now, we use VPValue to represent A and B and classify both as external
180   // definitions. We may introduce specific VPValue subclasses for them in the
181   // future.
182   assert(isExternalDef(IRVal) && "Expected external definition as operand.");
183 
184   // A and B: Create VPValue and add it to the pool of external definitions and
185   // to the Value->VPValue map.
186   VPValue *NewVPVal = new VPValue(IRVal);
187   Plan.addExternalDef(NewVPVal);
188   IRDef2VPValue[IRVal] = NewVPVal;
189   return NewVPVal;
190 }
191 
192 // Create new VPInstructions in a VPBasicBlock, given its BasicBlock
193 // counterpart. This function must be invoked in RPO so that the operands of a
194 // VPInstruction in \p BB have been visited before (except for Phi nodes).
195 void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
196                                                   BasicBlock *BB) {
197   VPIRBuilder.setInsertPoint(VPBB);
198   for (Instruction &InstRef : *BB) {
199     Instruction *Inst = &InstRef;
200     if (isInstructionToIgnore(Inst))
201       continue;
202 
203     // There should't be any VPValue for Inst at this point. Otherwise, we
204     // visited Inst when we shouldn't, breaking the RPO traversal order.
205     assert(!IRDef2VPValue.count(Inst) &&
206            "Instruction shouldn't have been visited.");
207 
208     VPInstruction *NewVPInst;
209     if (PHINode *Phi = dyn_cast<PHINode>(Inst)) {
210       // Phi node's operands may have not been visited at this point. We create
211       // an empty VPInstruction that we will fix once the whole plain CFG has
212       // been built.
213       NewVPInst = cast<VPInstruction>(VPIRBuilder.createNaryOp(
214           Inst->getOpcode(), {} /*No operands*/, Inst));
215       PhisToFix.push_back(Phi);
216     } else {
217       // Translate LLVM-IR operands into VPValue operands and set them in the
218       // new VPInstruction.
219       SmallVector<VPValue *, 4> VPOperands;
220       for (Value *Op : Inst->operands())
221         VPOperands.push_back(getOrCreateVPOperand(Op));
222 
223       // Build VPInstruction for any arbitraty Instruction without specific
224       // representation in VPlan.
225       NewVPInst = cast<VPInstruction>(
226           VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst));
227     }
228 
229     IRDef2VPValue[Inst] = NewVPInst;
230   }
231 }
232 
233 // Main interface to build the plain CFG.
234 VPRegionBlock *PlainCFGBuilder::buildPlainCFG() {
235   // 1. Create the Top Region. It will be the parent of all VPBBs.
236   TopRegion = new VPRegionBlock("TopRegion", false /*isReplicator*/);
237 
238   // 2. Scan the body of the loop in a topological order to visit each basic
239   // block after having visited its predecessor basic blocks. Create a VPBB for
240   // each BB and link it to its successor and predecessor VPBBs. Note that
241   // predecessors must be set in the same order as they are in the incomming IR.
242   // Otherwise, there might be problems with existing phi nodes and algorithm
243   // based on predecessors traversal.
244 
245   // Loop PH needs to be explicitly visited since it's not taken into account by
246   // LoopBlocksDFS.
247   BasicBlock *PreheaderBB = TheLoop->getLoopPreheader();
248   assert((PreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
249          "Unexpected loop preheader");
250   VPBasicBlock *PreheaderVPBB = getOrCreateVPBB(PreheaderBB);
251   createVPInstructionsForVPBB(PreheaderVPBB, PreheaderBB);
252   // Create empty VPBB for Loop H so that we can link PH->H.
253   VPBlockBase *HeaderVPBB = getOrCreateVPBB(TheLoop->getHeader());
254   // Preheader's predecessors will be set during the loop RPO traversal below.
255   PreheaderVPBB->setOneSuccessor(HeaderVPBB);
256 
257   LoopBlocksRPO RPO(TheLoop);
258   RPO.perform(LI);
259 
260   for (BasicBlock *BB : RPO) {
261     // Create or retrieve the VPBasicBlock for this BB and create its
262     // VPInstructions.
263     VPBasicBlock *VPBB = getOrCreateVPBB(BB);
264     createVPInstructionsForVPBB(VPBB, BB);
265 
266     // Set VPBB successors. We create empty VPBBs for successors if they don't
267     // exist already. Recipes will be created when the successor is visited
268     // during the RPO traversal.
269     TerminatorInst *TI = BB->getTerminator();
270     assert(TI && "Terminator expected.");
271     unsigned NumSuccs = TI->getNumSuccessors();
272 
273     if (NumSuccs == 1) {
274       VPBasicBlock *SuccVPBB = getOrCreateVPBB(TI->getSuccessor(0));
275       assert(SuccVPBB && "VPBB Successor not found.");
276       VPBB->setOneSuccessor(SuccVPBB);
277     } else if (NumSuccs == 2) {
278       VPBasicBlock *SuccVPBB0 = getOrCreateVPBB(TI->getSuccessor(0));
279       assert(SuccVPBB0 && "Successor 0 not found.");
280       VPBasicBlock *SuccVPBB1 = getOrCreateVPBB(TI->getSuccessor(1));
281       assert(SuccVPBB1 && "Successor 1 not found.");
282       VPBB->setTwoSuccessors(SuccVPBB0, SuccVPBB1);
283     } else
284       llvm_unreachable("Number of successors not supported.");
285 
286     // Set VPBB predecessors in the same order as they are in the incoming BB.
287     setVPBBPredsFromBB(VPBB, BB);
288   }
289 
290   // 3. Process outermost loop exit. We created an empty VPBB for the loop
291   // single exit BB during the RPO traversal of the loop body but Instructions
292   // weren't visited because it's not part of the the loop.
293   BasicBlock *LoopExitBB = TheLoop->getUniqueExitBlock();
294   assert(LoopExitBB && "Loops with multiple exits are not supported.");
295   VPBasicBlock *LoopExitVPBB = BB2VPBB[LoopExitBB];
296   createVPInstructionsForVPBB(LoopExitVPBB, LoopExitBB);
297   // Loop exit was already set as successor of the loop exiting BB.
298   // We only set its predecessor VPBB now.
299   setVPBBPredsFromBB(LoopExitVPBB, LoopExitBB);
300 
301   // 4. The whole CFG has been built at this point so all the input Values must
302   // have a VPlan couterpart. Fix VPlan phi nodes by adding their corresponding
303   // VPlan operands.
304   fixPhiNodes();
305 
306   // 5. Final Top Region setup. Set outermost loop pre-header and single exit as
307   // Top Region entry and exit.
308   TopRegion->setEntry(PreheaderVPBB);
309   TopRegion->setExit(LoopExitVPBB);
310   return TopRegion;
311 }
312 
313 // Public interface to build a H-CFG.
314 void VPlanHCFGBuilder::buildHierarchicalCFG(VPlan &Plan) {
315   // Build Top Region enclosing the plain CFG and set it as VPlan entry.
316   PlainCFGBuilder PCFGBuilder(TheLoop, LI, Plan);
317   VPRegionBlock *TopRegion = PCFGBuilder.buildPlainCFG();
318   Plan.setEntry(TopRegion);
319   LLVM_DEBUG(Plan.setName("HCFGBuilder: Plain CFG\n"); dbgs() << Plan);
320 
321   Verifier.verifyHierarchicalCFG(TopRegion);
322 }
323