1168d04d5SDiego Caballero //===-- VPlanHCFGBuilder.cpp ----------------------------------------------===//
2168d04d5SDiego Caballero //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6168d04d5SDiego Caballero //
7168d04d5SDiego Caballero //===----------------------------------------------------------------------===//
8168d04d5SDiego Caballero ///
9168d04d5SDiego Caballero /// \file
10168d04d5SDiego Caballero /// This file implements the construction of a VPlan-based Hierarchical CFG
11168d04d5SDiego Caballero /// (H-CFG) for an incoming IR. This construction comprises the following
12168d04d5SDiego Caballero /// components and steps:
13168d04d5SDiego Caballero //
14168d04d5SDiego Caballero /// 1. PlainCFGBuilder class: builds a plain VPBasicBlock-based CFG that
15168d04d5SDiego Caballero /// faithfully represents the CFG in the incoming IR. A VPRegionBlock (Top
16168d04d5SDiego Caballero /// Region) is created to enclose and serve as parent of all the VPBasicBlocks
17168d04d5SDiego Caballero /// in the plain CFG.
18168d04d5SDiego Caballero /// NOTE: At this point, there is a direct correspondence between all the
19168d04d5SDiego Caballero /// VPBasicBlocks created for the initial plain CFG and the incoming
20168d04d5SDiego Caballero /// BasicBlocks. However, this might change in the future.
21168d04d5SDiego Caballero ///
22168d04d5SDiego Caballero //===----------------------------------------------------------------------===//
23168d04d5SDiego Caballero 
24168d04d5SDiego Caballero #include "VPlanHCFGBuilder.h"
25168d04d5SDiego Caballero #include "LoopVectorizationPlanner.h"
26168d04d5SDiego Caballero #include "llvm/Analysis/LoopIterator.h"
27168d04d5SDiego Caballero 
28168d04d5SDiego Caballero #define DEBUG_TYPE "loop-vectorize"
29168d04d5SDiego Caballero 
30168d04d5SDiego Caballero using namespace llvm;
31168d04d5SDiego Caballero 
32d34b765cSAndrei Elovikov namespace {
33168d04d5SDiego Caballero // Class that is used to build the plain CFG for the incoming IR.
34168d04d5SDiego Caballero class PlainCFGBuilder {
35168d04d5SDiego Caballero private:
36168d04d5SDiego Caballero   // The outermost loop of the input loop nest considered for vectorization.
37168d04d5SDiego Caballero   Loop *TheLoop;
38168d04d5SDiego Caballero 
39168d04d5SDiego Caballero   // Loop Info analysis.
40168d04d5SDiego Caballero   LoopInfo *LI;
41168d04d5SDiego Caballero 
42168d04d5SDiego Caballero   // Vectorization plan that we are working on.
43168d04d5SDiego Caballero   VPlan &Plan;
44168d04d5SDiego Caballero 
45168d04d5SDiego Caballero   // Builder of the VPlan instruction-level representation.
46168d04d5SDiego Caballero   VPBuilder VPIRBuilder;
47168d04d5SDiego Caballero 
48168d04d5SDiego Caballero   // NOTE: The following maps are intentionally destroyed after the plain CFG
49168d04d5SDiego Caballero   // construction because subsequent VPlan-to-VPlan transformation may
50168d04d5SDiego Caballero   // invalidate them.
51168d04d5SDiego Caballero   // Map incoming BasicBlocks to their newly-created VPBasicBlocks.
52168d04d5SDiego Caballero   DenseMap<BasicBlock *, VPBasicBlock *> BB2VPBB;
53168d04d5SDiego Caballero   // Map incoming Value definitions to their newly-created VPValues.
54168d04d5SDiego Caballero   DenseMap<Value *, VPValue *> IRDef2VPValue;
55168d04d5SDiego Caballero 
56168d04d5SDiego Caballero   // Hold phi node's that need to be fixed once the plain CFG has been built.
57168d04d5SDiego Caballero   SmallVector<PHINode *, 8> PhisToFix;
58168d04d5SDiego Caballero 
5905776122SFlorian Hahn   /// Maps loops in the original IR to their corresponding region.
6005776122SFlorian Hahn   DenseMap<Loop *, VPRegionBlock *> Loop2Region;
6105776122SFlorian Hahn 
62168d04d5SDiego Caballero   // Utility functions.
63168d04d5SDiego Caballero   void setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB);
64168d04d5SDiego Caballero   void fixPhiNodes();
65168d04d5SDiego Caballero   VPBasicBlock *getOrCreateVPBB(BasicBlock *BB);
66e071cd86SJonas Hahnfeld #ifndef NDEBUG
67168d04d5SDiego Caballero   bool isExternalDef(Value *Val);
68e071cd86SJonas Hahnfeld #endif
69168d04d5SDiego Caballero   VPValue *getOrCreateVPOperand(Value *IRVal);
70168d04d5SDiego Caballero   void createVPInstructionsForVPBB(VPBasicBlock *VPBB, BasicBlock *BB);
71168d04d5SDiego Caballero 
72168d04d5SDiego Caballero public:
PlainCFGBuilder(Loop * Lp,LoopInfo * LI,VPlan & P)73168d04d5SDiego Caballero   PlainCFGBuilder(Loop *Lp, LoopInfo *LI, VPlan &P)
74168d04d5SDiego Caballero       : TheLoop(Lp), LI(LI), Plan(P) {}
75168d04d5SDiego Caballero 
7605776122SFlorian Hahn   /// Build plain CFG for TheLoop. Return the pre-header VPBasicBlock connected
7705776122SFlorian Hahn   /// to a new VPRegionBlock (TopRegion) enclosing the plain CFG.
7805776122SFlorian Hahn   VPBasicBlock *buildPlainCFG();
79168d04d5SDiego Caballero };
80d34b765cSAndrei Elovikov } // anonymous namespace
81168d04d5SDiego Caballero 
82168d04d5SDiego Caballero // Set predecessors of \p VPBB in the same order as they are in \p BB. \p VPBB
83168d04d5SDiego Caballero // must have no predecessors.
setVPBBPredsFromBB(VPBasicBlock * VPBB,BasicBlock * BB)84168d04d5SDiego Caballero void PlainCFGBuilder::setVPBBPredsFromBB(VPBasicBlock *VPBB, BasicBlock *BB) {
85168d04d5SDiego Caballero   SmallVector<VPBlockBase *, 8> VPBBPreds;
86168d04d5SDiego Caballero   // Collect VPBB predecessors.
87168d04d5SDiego Caballero   for (BasicBlock *Pred : predecessors(BB))
88168d04d5SDiego Caballero     VPBBPreds.push_back(getOrCreateVPBB(Pred));
89168d04d5SDiego Caballero 
90168d04d5SDiego Caballero   VPBB->setPredecessors(VPBBPreds);
91168d04d5SDiego Caballero }
92168d04d5SDiego Caballero 
93168d04d5SDiego Caballero // Add operands to VPInstructions representing phi nodes from the input IR.
fixPhiNodes()94168d04d5SDiego Caballero void PlainCFGBuilder::fixPhiNodes() {
95168d04d5SDiego Caballero   for (auto *Phi : PhisToFix) {
96168d04d5SDiego Caballero     assert(IRDef2VPValue.count(Phi) && "Missing VPInstruction for PHINode.");
97168d04d5SDiego Caballero     VPValue *VPVal = IRDef2VPValue[Phi];
9815a74b64SFlorian Hahn     assert(isa<VPWidenPHIRecipe>(VPVal) &&
9915a74b64SFlorian Hahn            "Expected WidenPHIRecipe for phi node.");
10015a74b64SFlorian Hahn     auto *VPPhi = cast<VPWidenPHIRecipe>(VPVal);
101168d04d5SDiego Caballero     assert(VPPhi->getNumOperands() == 0 &&
102168d04d5SDiego Caballero            "Expected VPInstruction with no operands.");
103168d04d5SDiego Caballero 
10415a74b64SFlorian Hahn     for (unsigned I = 0; I != Phi->getNumOperands(); ++I)
10515a74b64SFlorian Hahn       VPPhi->addIncoming(getOrCreateVPOperand(Phi->getIncomingValue(I)),
10615a74b64SFlorian Hahn                          BB2VPBB[Phi->getIncomingBlock(I)]);
107168d04d5SDiego Caballero   }
108168d04d5SDiego Caballero }
109168d04d5SDiego Caballero 
11005776122SFlorian Hahn // Create a new empty VPBasicBlock for an incoming BasicBlock in the region
11105776122SFlorian Hahn // corresponding to the containing loop  or retrieve an existing one if it was
11205776122SFlorian Hahn // already created. If no region exists yet for the loop containing \p BB, a new
11305776122SFlorian Hahn // one is created.
getOrCreateVPBB(BasicBlock * BB)114168d04d5SDiego Caballero VPBasicBlock *PlainCFGBuilder::getOrCreateVPBB(BasicBlock *BB) {
115168d04d5SDiego Caballero   auto BlockIt = BB2VPBB.find(BB);
116168d04d5SDiego Caballero   if (BlockIt != BB2VPBB.end())
117168d04d5SDiego Caballero     // Retrieve existing VPBB.
118168d04d5SDiego Caballero     return BlockIt->second;
119168d04d5SDiego Caballero 
12005776122SFlorian Hahn   // Get or create a region for the loop containing BB.
12105776122SFlorian Hahn   Loop *CurrentLoop = LI->getLoopFor(BB);
12205776122SFlorian Hahn   VPRegionBlock *ParentR = nullptr;
12305776122SFlorian Hahn   if (CurrentLoop) {
12405776122SFlorian Hahn     auto Iter = Loop2Region.insert({CurrentLoop, nullptr});
12505776122SFlorian Hahn     if (Iter.second)
12605776122SFlorian Hahn       Iter.first->second = new VPRegionBlock(
12705776122SFlorian Hahn           CurrentLoop->getHeader()->getName().str(), false /*isReplicator*/);
12805776122SFlorian Hahn     ParentR = Iter.first->second;
12905776122SFlorian Hahn   }
13005776122SFlorian Hahn 
131168d04d5SDiego Caballero   // Create new VPBB.
13203d0b91fSNicola Zaghen   LLVM_DEBUG(dbgs() << "Creating VPBasicBlock for " << BB->getName() << "\n");
133168d04d5SDiego Caballero   VPBasicBlock *VPBB = new VPBasicBlock(BB->getName());
134168d04d5SDiego Caballero   BB2VPBB[BB] = VPBB;
13505776122SFlorian Hahn   VPBB->setParent(ParentR);
136168d04d5SDiego Caballero   return VPBB;
137168d04d5SDiego Caballero }
138168d04d5SDiego Caballero 
139e071cd86SJonas Hahnfeld #ifndef NDEBUG
140168d04d5SDiego Caballero // Return true if \p Val is considered an external definition. An external
141168d04d5SDiego Caballero // definition is either:
142168d04d5SDiego Caballero // 1. A Value that is not an Instruction. This will be refined in the future.
143168d04d5SDiego Caballero // 2. An Instruction that is outside of the CFG snippet represented in VPlan,
144168d04d5SDiego Caballero // i.e., is not part of: a) the loop nest, b) outermost loop PH and, c)
145168d04d5SDiego Caballero // outermost loop exits.
isExternalDef(Value * Val)146168d04d5SDiego Caballero bool PlainCFGBuilder::isExternalDef(Value *Val) {
147168d04d5SDiego Caballero   // All the Values that are not Instructions are considered external
148168d04d5SDiego Caballero   // definitions for now.
149168d04d5SDiego Caballero   Instruction *Inst = dyn_cast<Instruction>(Val);
150168d04d5SDiego Caballero   if (!Inst)
151168d04d5SDiego Caballero     return true;
152168d04d5SDiego Caballero 
153168d04d5SDiego Caballero   BasicBlock *InstParent = Inst->getParent();
154168d04d5SDiego Caballero   assert(InstParent && "Expected instruction parent.");
155168d04d5SDiego Caballero 
156168d04d5SDiego Caballero   // Check whether Instruction definition is in loop PH.
157168d04d5SDiego Caballero   BasicBlock *PH = TheLoop->getLoopPreheader();
158168d04d5SDiego Caballero   assert(PH && "Expected loop pre-header.");
159168d04d5SDiego Caballero 
160168d04d5SDiego Caballero   if (InstParent == PH)
161168d04d5SDiego Caballero     // Instruction definition is in outermost loop PH.
162168d04d5SDiego Caballero     return false;
163168d04d5SDiego Caballero 
164168d04d5SDiego Caballero   // Check whether Instruction definition is in the loop exit.
165168d04d5SDiego Caballero   BasicBlock *Exit = TheLoop->getUniqueExitBlock();
166168d04d5SDiego Caballero   assert(Exit && "Expected loop with single exit.");
167168d04d5SDiego Caballero   if (InstParent == Exit) {
168168d04d5SDiego Caballero     // Instruction definition is in outermost loop exit.
169168d04d5SDiego Caballero     return false;
170168d04d5SDiego Caballero   }
171168d04d5SDiego Caballero 
172168d04d5SDiego Caballero   // Check whether Instruction definition is in loop body.
173168d04d5SDiego Caballero   return !TheLoop->contains(Inst);
174168d04d5SDiego Caballero }
175e071cd86SJonas Hahnfeld #endif
176168d04d5SDiego Caballero 
177168d04d5SDiego Caballero // Create a new VPValue or retrieve an existing one for the Instruction's
178168d04d5SDiego Caballero // operand \p IRVal. This function must only be used to create/retrieve VPValues
179168d04d5SDiego Caballero // for *Instruction's operands* and not to create regular VPInstruction's. For
180168d04d5SDiego Caballero // the latter, please, look at 'createVPInstructionsForVPBB'.
getOrCreateVPOperand(Value * IRVal)181168d04d5SDiego Caballero VPValue *PlainCFGBuilder::getOrCreateVPOperand(Value *IRVal) {
182168d04d5SDiego Caballero   auto VPValIt = IRDef2VPValue.find(IRVal);
183168d04d5SDiego Caballero   if (VPValIt != IRDef2VPValue.end())
184168d04d5SDiego Caballero     // Operand has an associated VPInstruction or VPValue that was previously
185168d04d5SDiego Caballero     // created.
186168d04d5SDiego Caballero     return VPValIt->second;
187168d04d5SDiego Caballero 
188168d04d5SDiego Caballero   // Operand doesn't have a previously created VPInstruction/VPValue. This
189168d04d5SDiego Caballero   // means that operand is:
190168d04d5SDiego Caballero   //   A) a definition external to VPlan,
191168d04d5SDiego Caballero   //   B) any other Value without specific representation in VPlan.
192168d04d5SDiego Caballero   // For now, we use VPValue to represent A and B and classify both as external
193168d04d5SDiego Caballero   // definitions. We may introduce specific VPValue subclasses for them in the
194168d04d5SDiego Caballero   // future.
195168d04d5SDiego Caballero   assert(isExternalDef(IRVal) && "Expected external definition as operand.");
196168d04d5SDiego Caballero 
197168d04d5SDiego Caballero   // A and B: Create VPValue and add it to the pool of external definitions and
198168d04d5SDiego Caballero   // to the Value->VPValue map.
1992c14cdf8SFlorian Hahn   VPValue *NewVPVal = Plan.getOrAddExternalDef(IRVal);
200168d04d5SDiego Caballero   IRDef2VPValue[IRVal] = NewVPVal;
201168d04d5SDiego Caballero   return NewVPVal;
202168d04d5SDiego Caballero }
203168d04d5SDiego Caballero 
204168d04d5SDiego Caballero // Create new VPInstructions in a VPBasicBlock, given its BasicBlock
205168d04d5SDiego Caballero // counterpart. This function must be invoked in RPO so that the operands of a
206168d04d5SDiego Caballero // VPInstruction in \p BB have been visited before (except for Phi nodes).
createVPInstructionsForVPBB(VPBasicBlock * VPBB,BasicBlock * BB)207168d04d5SDiego Caballero void PlainCFGBuilder::createVPInstructionsForVPBB(VPBasicBlock *VPBB,
208168d04d5SDiego Caballero                                                   BasicBlock *BB) {
209168d04d5SDiego Caballero   VPIRBuilder.setInsertPoint(VPBB);
210168d04d5SDiego Caballero   for (Instruction &InstRef : *BB) {
211168d04d5SDiego Caballero     Instruction *Inst = &InstRef;
212168d04d5SDiego Caballero 
213d0953014SDiego Caballero     // There shouldn't be any VPValue for Inst at this point. Otherwise, we
214168d04d5SDiego Caballero     // visited Inst when we shouldn't, breaking the RPO traversal order.
215168d04d5SDiego Caballero     assert(!IRDef2VPValue.count(Inst) &&
216168d04d5SDiego Caballero            "Instruction shouldn't have been visited.");
217168d04d5SDiego Caballero 
218d0953014SDiego Caballero     if (auto *Br = dyn_cast<BranchInst>(Inst)) {
219a5bb4a3bSFlorian Hahn       // Conditional branch instruction are represented using BranchOnCond
220a5bb4a3bSFlorian Hahn       // recipes.
221a5bb4a3bSFlorian Hahn       if (Br->isConditional()) {
222a5bb4a3bSFlorian Hahn         VPValue *Cond = getOrCreateVPOperand(Br->getCondition());
223a5bb4a3bSFlorian Hahn         VPBB->appendRecipe(
224a5bb4a3bSFlorian Hahn             new VPInstruction(VPInstruction::BranchOnCond, {Cond}));
225a5bb4a3bSFlorian Hahn       }
226d0953014SDiego Caballero 
227d0953014SDiego Caballero       // Skip the rest of the Instruction processing for Branch instructions.
228d0953014SDiego Caballero       continue;
229d0953014SDiego Caballero     }
230d0953014SDiego Caballero 
23115a74b64SFlorian Hahn     VPValue *NewVPV;
232d0953014SDiego Caballero     if (auto *Phi = dyn_cast<PHINode>(Inst)) {
233168d04d5SDiego Caballero       // Phi node's operands may have not been visited at this point. We create
234168d04d5SDiego Caballero       // an empty VPInstruction that we will fix once the whole plain CFG has
235168d04d5SDiego Caballero       // been built.
23615a74b64SFlorian Hahn       NewVPV = new VPWidenPHIRecipe(Phi);
23715a74b64SFlorian Hahn       VPBB->appendRecipe(cast<VPWidenPHIRecipe>(NewVPV));
238168d04d5SDiego Caballero       PhisToFix.push_back(Phi);
239168d04d5SDiego Caballero     } else {
240168d04d5SDiego Caballero       // Translate LLVM-IR operands into VPValue operands and set them in the
241168d04d5SDiego Caballero       // new VPInstruction.
242168d04d5SDiego Caballero       SmallVector<VPValue *, 4> VPOperands;
243168d04d5SDiego Caballero       for (Value *Op : Inst->operands())
244168d04d5SDiego Caballero         VPOperands.push_back(getOrCreateVPOperand(Op));
245168d04d5SDiego Caballero 
246168d04d5SDiego Caballero       // Build VPInstruction for any arbitraty Instruction without specific
247168d04d5SDiego Caballero       // representation in VPlan.
24815a74b64SFlorian Hahn       NewVPV = cast<VPInstruction>(
249168d04d5SDiego Caballero           VPIRBuilder.createNaryOp(Inst->getOpcode(), VPOperands, Inst));
250168d04d5SDiego Caballero     }
251168d04d5SDiego Caballero 
25215a74b64SFlorian Hahn     IRDef2VPValue[Inst] = NewVPV;
253168d04d5SDiego Caballero   }
254168d04d5SDiego Caballero }
255168d04d5SDiego Caballero 
256168d04d5SDiego Caballero // Main interface to build the plain CFG.
buildPlainCFG()25705776122SFlorian Hahn VPBasicBlock *PlainCFGBuilder::buildPlainCFG() {
25805776122SFlorian Hahn   // 1. Scan the body of the loop in a topological order to visit each basic
259168d04d5SDiego Caballero   // block after having visited its predecessor basic blocks. Create a VPBB for
260168d04d5SDiego Caballero   // each BB and link it to its successor and predecessor VPBBs. Note that
261168d04d5SDiego Caballero   // predecessors must be set in the same order as they are in the incomming IR.
262168d04d5SDiego Caballero   // Otherwise, there might be problems with existing phi nodes and algorithm
263168d04d5SDiego Caballero   // based on predecessors traversal.
264168d04d5SDiego Caballero 
265168d04d5SDiego Caballero   // Loop PH needs to be explicitly visited since it's not taken into account by
266168d04d5SDiego Caballero   // LoopBlocksDFS.
26705776122SFlorian Hahn   BasicBlock *ThePreheaderBB = TheLoop->getLoopPreheader();
26805776122SFlorian Hahn   assert((ThePreheaderBB->getTerminator()->getNumSuccessors() == 1) &&
269168d04d5SDiego Caballero          "Unexpected loop preheader");
27005776122SFlorian Hahn   VPBasicBlock *ThePreheaderVPBB = getOrCreateVPBB(ThePreheaderBB);
27105776122SFlorian Hahn   ThePreheaderVPBB->setName("vector.ph");
27205776122SFlorian Hahn   for (auto &I : *ThePreheaderBB) {
273fd8afa41SFlorian Hahn     if (I.getType()->isVoidTy())
274fd8afa41SFlorian Hahn       continue;
2752c14cdf8SFlorian Hahn     IRDef2VPValue[&I] = Plan.getOrAddExternalDef(&I);
276fd8afa41SFlorian Hahn   }
277168d04d5SDiego Caballero   // Create empty VPBB for Loop H so that we can link PH->H.
278168d04d5SDiego Caballero   VPBlockBase *HeaderVPBB = getOrCreateVPBB(TheLoop->getHeader());
2794388c979SFlorian Hahn   HeaderVPBB->setName("vector.body");
28005776122SFlorian Hahn   ThePreheaderVPBB->setOneSuccessor(HeaderVPBB);
281168d04d5SDiego Caballero 
282168d04d5SDiego Caballero   LoopBlocksRPO RPO(TheLoop);
283168d04d5SDiego Caballero   RPO.perform(LI);
284168d04d5SDiego Caballero 
285168d04d5SDiego Caballero   for (BasicBlock *BB : RPO) {
286168d04d5SDiego Caballero     // Create or retrieve the VPBasicBlock for this BB and create its
287168d04d5SDiego Caballero     // VPInstructions.
288168d04d5SDiego Caballero     VPBasicBlock *VPBB = getOrCreateVPBB(BB);
289168d04d5SDiego Caballero     createVPInstructionsForVPBB(VPBB, BB);
290168d04d5SDiego Caballero 
291168d04d5SDiego Caballero     // Set VPBB successors. We create empty VPBBs for successors if they don't
292168d04d5SDiego Caballero     // exist already. Recipes will be created when the successor is visited
293168d04d5SDiego Caballero     // during the RPO traversal.
294edb12a83SChandler Carruth     Instruction *TI = BB->getTerminator();
295168d04d5SDiego Caballero     assert(TI && "Terminator expected.");
296168d04d5SDiego Caballero     unsigned NumSuccs = TI->getNumSuccessors();
297168d04d5SDiego Caballero 
298168d04d5SDiego Caballero     if (NumSuccs == 1) {
299168d04d5SDiego Caballero       VPBasicBlock *SuccVPBB = getOrCreateVPBB(TI->getSuccessor(0));
300168d04d5SDiego Caballero       assert(SuccVPBB && "VPBB Successor not found.");
301168d04d5SDiego Caballero       VPBB->setOneSuccessor(SuccVPBB);
302168d04d5SDiego Caballero     } else if (NumSuccs == 2) {
303168d04d5SDiego Caballero       VPBasicBlock *SuccVPBB0 = getOrCreateVPBB(TI->getSuccessor(0));
304168d04d5SDiego Caballero       assert(SuccVPBB0 && "Successor 0 not found.");
305168d04d5SDiego Caballero       VPBasicBlock *SuccVPBB1 = getOrCreateVPBB(TI->getSuccessor(1));
306168d04d5SDiego Caballero       assert(SuccVPBB1 && "Successor 1 not found.");
307d0953014SDiego Caballero 
308d0953014SDiego Caballero       // Get VPBB's condition bit.
309d0953014SDiego Caballero       assert(isa<BranchInst>(TI) && "Unsupported terminator!");
310d0953014SDiego Caballero       // Look up the branch condition to get the corresponding VPValue
311d0953014SDiego Caballero       // representing the condition bit in VPlan (which may be in another VPBB).
312*6b7c1863SBenjamin Kramer       assert(IRDef2VPValue.count(cast<BranchInst>(TI)->getCondition()) &&
313d0953014SDiego Caballero              "Missing condition bit in IRDef2VPValue!");
314d0953014SDiego Caballero 
315a5bb4a3bSFlorian Hahn       // Link successors.
316a5bb4a3bSFlorian Hahn       VPBB->setTwoSuccessors(SuccVPBB0, SuccVPBB1);
317168d04d5SDiego Caballero     } else
318168d04d5SDiego Caballero       llvm_unreachable("Number of successors not supported.");
319168d04d5SDiego Caballero 
320168d04d5SDiego Caballero     // Set VPBB predecessors in the same order as they are in the incoming BB.
321168d04d5SDiego Caballero     setVPBBPredsFromBB(VPBB, BB);
322168d04d5SDiego Caballero   }
323168d04d5SDiego Caballero 
32405776122SFlorian Hahn   // 2. Process outermost loop exit. We created an empty VPBB for the loop
325168d04d5SDiego Caballero   // single exit BB during the RPO traversal of the loop body but Instructions
326168d04d5SDiego Caballero   // weren't visited because it's not part of the the loop.
327168d04d5SDiego Caballero   BasicBlock *LoopExitBB = TheLoop->getUniqueExitBlock();
328168d04d5SDiego Caballero   assert(LoopExitBB && "Loops with multiple exits are not supported.");
329168d04d5SDiego Caballero   VPBasicBlock *LoopExitVPBB = BB2VPBB[LoopExitBB];
330168d04d5SDiego Caballero   // Loop exit was already set as successor of the loop exiting BB.
331168d04d5SDiego Caballero   // We only set its predecessor VPBB now.
332168d04d5SDiego Caballero   setVPBBPredsFromBB(LoopExitVPBB, LoopExitBB);
333168d04d5SDiego Caballero 
33405776122SFlorian Hahn   // 3. Fix up region blocks for loops. For each loop,
33505776122SFlorian Hahn   //   * use the header block as entry to the corresponding region,
33605776122SFlorian Hahn   //   * use the latch block as exit of the corresponding region,
33705776122SFlorian Hahn   //   * set the region as successor of the loop pre-header, and
33805776122SFlorian Hahn   //   * set the exit block as successor to the region.
33905776122SFlorian Hahn   SmallVector<Loop *> LoopWorkList;
34005776122SFlorian Hahn   LoopWorkList.push_back(TheLoop);
34105776122SFlorian Hahn   while (!LoopWorkList.empty()) {
34205776122SFlorian Hahn     Loop *L = LoopWorkList.pop_back_val();
34305776122SFlorian Hahn     BasicBlock *Header = L->getHeader();
34405776122SFlorian Hahn     BasicBlock *Exiting = L->getLoopLatch();
34505776122SFlorian Hahn     assert(Exiting == L->getExitingBlock() &&
34605776122SFlorian Hahn            "Latch must be the only exiting block");
34705776122SFlorian Hahn     VPRegionBlock *Region = Loop2Region[L];
34805776122SFlorian Hahn     VPBasicBlock *HeaderVPBB = getOrCreateVPBB(Header);
34905776122SFlorian Hahn     VPBasicBlock *ExitingVPBB = getOrCreateVPBB(Exiting);
35005776122SFlorian Hahn 
35105776122SFlorian Hahn     // Disconnect backedge and pre-header from header.
35205776122SFlorian Hahn     VPBasicBlock *PreheaderVPBB = getOrCreateVPBB(L->getLoopPreheader());
35305776122SFlorian Hahn     VPBlockUtils::disconnectBlocks(PreheaderVPBB, HeaderVPBB);
35405776122SFlorian Hahn     VPBlockUtils::disconnectBlocks(ExitingVPBB, HeaderVPBB);
35505776122SFlorian Hahn 
35605776122SFlorian Hahn     Region->setParent(PreheaderVPBB->getParent());
35705776122SFlorian Hahn     Region->setEntry(HeaderVPBB);
35805776122SFlorian Hahn     VPBlockUtils::connectBlocks(PreheaderVPBB, Region);
35905776122SFlorian Hahn 
36005776122SFlorian Hahn     // Disconnect exit block from exiting (=latch) block, set exiting block and
36105776122SFlorian Hahn     // connect region to exit block.
36205776122SFlorian Hahn     VPBasicBlock *ExitVPBB = getOrCreateVPBB(L->getExitBlock());
36305776122SFlorian Hahn     VPBlockUtils::disconnectBlocks(ExitingVPBB, ExitVPBB);
36405776122SFlorian Hahn     Region->setExiting(ExitingVPBB);
36505776122SFlorian Hahn     VPBlockUtils::connectBlocks(Region, ExitVPBB);
36605776122SFlorian Hahn 
36705776122SFlorian Hahn     // Queue sub-loops for processing.
36805776122SFlorian Hahn     LoopWorkList.append(L->begin(), L->end());
36905776122SFlorian Hahn   }
370168d04d5SDiego Caballero   // 4. The whole CFG has been built at this point so all the input Values must
371168d04d5SDiego Caballero   // have a VPlan couterpart. Fix VPlan phi nodes by adding their corresponding
372168d04d5SDiego Caballero   // VPlan operands.
373168d04d5SDiego Caballero   fixPhiNodes();
374168d04d5SDiego Caballero 
37505776122SFlorian Hahn   return ThePreheaderVPBB;
376168d04d5SDiego Caballero }
377168d04d5SDiego Caballero 
buildPlainCFG()37805776122SFlorian Hahn VPBasicBlock *VPlanHCFGBuilder::buildPlainCFG() {
379168d04d5SDiego Caballero   PlainCFGBuilder PCFGBuilder(TheLoop, LI, Plan);
3802a34ac86SDiego Caballero   return PCFGBuilder.buildPlainCFG();
3812a34ac86SDiego Caballero }
3822a34ac86SDiego Caballero 
3832a34ac86SDiego Caballero // Public interface to build a H-CFG.
buildHierarchicalCFG()3842a34ac86SDiego Caballero void VPlanHCFGBuilder::buildHierarchicalCFG() {
3852a34ac86SDiego Caballero   // Build Top Region enclosing the plain CFG and set it as VPlan entry.
38605776122SFlorian Hahn   VPBasicBlock *EntryVPBB = buildPlainCFG();
38705776122SFlorian Hahn   Plan.setEntry(EntryVPBB);
38803d0b91fSNicola Zaghen   LLVM_DEBUG(Plan.setName("HCFGBuilder: Plain CFG\n"); dbgs() << Plan);
389168d04d5SDiego Caballero 
39005776122SFlorian Hahn   VPRegionBlock *TopRegion = Plan.getVectorLoopRegion();
391168d04d5SDiego Caballero   Verifier.verifyHierarchicalCFG(TopRegion);
3922a34ac86SDiego Caballero 
3932a34ac86SDiego Caballero   // Compute plain CFG dom tree for VPLInfo.
3942a34ac86SDiego Caballero   VPDomTree.recalculate(*TopRegion);
3952a34ac86SDiego Caballero   LLVM_DEBUG(dbgs() << "Dominator Tree after building the plain CFG.\n";
3962a34ac86SDiego Caballero              VPDomTree.print(dbgs()));
397168d04d5SDiego Caballero }
398