VPlanHCFGBuilder.cpp 16 KB

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