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