PPCBranchCoalescing.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. //===-- CoalesceBranches.cpp - Coalesce blocks with the same condition ---===//
  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. /// Coalesce basic blocks guarded by the same branch condition into a single
  11. /// basic block.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "PPC.h"
  15. #include "llvm/ADT/BitVector.h"
  16. #include "llvm/ADT/Statistic.h"
  17. #include "llvm/CodeGen/MachineDominators.h"
  18. #include "llvm/CodeGen/MachineFunctionPass.h"
  19. #include "llvm/CodeGen/MachinePostDominators.h"
  20. #include "llvm/CodeGen/MachineRegisterInfo.h"
  21. #include "llvm/CodeGen/Passes.h"
  22. #include "llvm/CodeGen/TargetFrameLowering.h"
  23. #include "llvm/CodeGen/TargetInstrInfo.h"
  24. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  25. #include "llvm/InitializePasses.h"
  26. #include "llvm/Support/Debug.h"
  27. using namespace llvm;
  28. #define DEBUG_TYPE "ppc-branch-coalescing"
  29. STATISTIC(NumBlocksCoalesced, "Number of blocks coalesced");
  30. STATISTIC(NumPHINotMoved, "Number of PHI Nodes that cannot be merged");
  31. STATISTIC(NumBlocksNotCoalesced, "Number of blocks not coalesced");
  32. //===----------------------------------------------------------------------===//
  33. // PPCBranchCoalescing
  34. //===----------------------------------------------------------------------===//
  35. ///
  36. /// Improve scheduling by coalescing branches that depend on the same condition.
  37. /// This pass looks for blocks that are guarded by the same branch condition
  38. /// and attempts to merge the blocks together. Such opportunities arise from
  39. /// the expansion of select statements in the IR.
  40. ///
  41. /// This pass does not handle implicit operands on branch statements. In order
  42. /// to run on targets that use implicit operands, changes need to be made in the
  43. /// canCoalesceBranch and canMerge methods.
  44. ///
  45. /// Example: the following LLVM IR
  46. ///
  47. /// %test = icmp eq i32 %x 0
  48. /// %tmp1 = select i1 %test, double %a, double 2.000000e-03
  49. /// %tmp2 = select i1 %test, double %b, double 5.000000e-03
  50. ///
  51. /// expands to the following machine code:
  52. ///
  53. /// %bb.0: derived from LLVM BB %entry
  54. /// liveins: %f1 %f3 %x6
  55. /// <SNIP1>
  56. /// %0 = COPY %f1; F8RC:%0
  57. /// %5 = CMPLWI killed %4, 0; CRRC:%5 GPRC:%4
  58. /// %8 = LXSDX %zero8, killed %7, implicit %rm;
  59. /// mem:LD8[ConstantPool] F8RC:%8 G8RC:%7
  60. /// BCC 76, %5, <%bb.2>; CRRC:%5
  61. /// Successors according to CFG: %bb.1(?%) %bb.2(?%)
  62. ///
  63. /// %bb.1: derived from LLVM BB %entry
  64. /// Predecessors according to CFG: %bb.0
  65. /// Successors according to CFG: %bb.2(?%)
  66. ///
  67. /// %bb.2: derived from LLVM BB %entry
  68. /// Predecessors according to CFG: %bb.0 %bb.1
  69. /// %9 = PHI %8, <%bb.1>, %0, <%bb.0>;
  70. /// F8RC:%9,%8,%0
  71. /// <SNIP2>
  72. /// BCC 76, %5, <%bb.4>; CRRC:%5
  73. /// Successors according to CFG: %bb.3(?%) %bb.4(?%)
  74. ///
  75. /// %bb.3: derived from LLVM BB %entry
  76. /// Predecessors according to CFG: %bb.2
  77. /// Successors according to CFG: %bb.4(?%)
  78. ///
  79. /// %bb.4: derived from LLVM BB %entry
  80. /// Predecessors according to CFG: %bb.2 %bb.3
  81. /// %13 = PHI %12, <%bb.3>, %2, <%bb.2>;
  82. /// F8RC:%13,%12,%2
  83. /// <SNIP3>
  84. /// BLR8 implicit %lr8, implicit %rm, implicit %f1
  85. ///
  86. /// When this pattern is detected, branch coalescing will try to collapse
  87. /// it by moving code in %bb.2 to %bb.0 and/or %bb.4 and removing %bb.3.
  88. ///
  89. /// If all conditions are meet, IR should collapse to:
  90. ///
  91. /// %bb.0: derived from LLVM BB %entry
  92. /// liveins: %f1 %f3 %x6
  93. /// <SNIP1>
  94. /// %0 = COPY %f1; F8RC:%0
  95. /// %5 = CMPLWI killed %4, 0; CRRC:%5 GPRC:%4
  96. /// %8 = LXSDX %zero8, killed %7, implicit %rm;
  97. /// mem:LD8[ConstantPool] F8RC:%8 G8RC:%7
  98. /// <SNIP2>
  99. /// BCC 76, %5, <%bb.4>; CRRC:%5
  100. /// Successors according to CFG: %bb.1(0x2aaaaaaa / 0x80000000 = 33.33%)
  101. /// %bb.4(0x55555554 / 0x80000000 = 66.67%)
  102. ///
  103. /// %bb.1: derived from LLVM BB %entry
  104. /// Predecessors according to CFG: %bb.0
  105. /// Successors according to CFG: %bb.4(0x40000000 / 0x80000000 = 50.00%)
  106. ///
  107. /// %bb.4: derived from LLVM BB %entry
  108. /// Predecessors according to CFG: %bb.0 %bb.1
  109. /// %9 = PHI %8, <%bb.1>, %0, <%bb.0>;
  110. /// F8RC:%9,%8,%0
  111. /// %13 = PHI %12, <%bb.1>, %2, <%bb.0>;
  112. /// F8RC:%13,%12,%2
  113. /// <SNIP3>
  114. /// BLR8 implicit %lr8, implicit %rm, implicit %f1
  115. ///
  116. /// Branch Coalescing does not split blocks, it moves everything in the same
  117. /// direction ensuring it does not break use/definition semantics.
  118. ///
  119. /// PHI nodes and its corresponding use instructions are moved to its successor
  120. /// block if there are no uses within the successor block PHI nodes. PHI
  121. /// node ordering cannot be assumed.
  122. ///
  123. /// Non-PHI can be moved up to the predecessor basic block or down to the
  124. /// successor basic block following any PHI instructions. Whether it moves
  125. /// up or down depends on whether the register(s) defined in the instructions
  126. /// are used in current block or in any PHI instructions at the beginning of
  127. /// the successor block.
  128. namespace {
  129. class PPCBranchCoalescing : public MachineFunctionPass {
  130. struct CoalescingCandidateInfo {
  131. MachineBasicBlock *BranchBlock; // Block containing the branch
  132. MachineBasicBlock *BranchTargetBlock; // Block branched to
  133. MachineBasicBlock *FallThroughBlock; // Fall-through if branch not taken
  134. SmallVector<MachineOperand, 4> Cond;
  135. bool MustMoveDown;
  136. bool MustMoveUp;
  137. CoalescingCandidateInfo();
  138. void clear();
  139. };
  140. MachineDominatorTree *MDT;
  141. MachinePostDominatorTree *MPDT;
  142. const TargetInstrInfo *TII;
  143. MachineRegisterInfo *MRI;
  144. void initialize(MachineFunction &F);
  145. bool canCoalesceBranch(CoalescingCandidateInfo &Cand);
  146. bool identicalOperands(ArrayRef<MachineOperand> OperandList1,
  147. ArrayRef<MachineOperand> OperandList2) const;
  148. bool validateCandidates(CoalescingCandidateInfo &SourceRegion,
  149. CoalescingCandidateInfo &TargetRegion) const;
  150. public:
  151. static char ID;
  152. PPCBranchCoalescing() : MachineFunctionPass(ID) {
  153. initializePPCBranchCoalescingPass(*PassRegistry::getPassRegistry());
  154. }
  155. void getAnalysisUsage(AnalysisUsage &AU) const override {
  156. AU.addRequired<MachineDominatorTree>();
  157. AU.addRequired<MachinePostDominatorTree>();
  158. MachineFunctionPass::getAnalysisUsage(AU);
  159. }
  160. StringRef getPassName() const override { return "Branch Coalescing"; }
  161. bool mergeCandidates(CoalescingCandidateInfo &SourceRegion,
  162. CoalescingCandidateInfo &TargetRegion);
  163. bool canMoveToBeginning(const MachineInstr &MI,
  164. const MachineBasicBlock &MBB) const;
  165. bool canMoveToEnd(const MachineInstr &MI,
  166. const MachineBasicBlock &MBB) const;
  167. bool canMerge(CoalescingCandidateInfo &SourceRegion,
  168. CoalescingCandidateInfo &TargetRegion) const;
  169. void moveAndUpdatePHIs(MachineBasicBlock *SourceRegionMBB,
  170. MachineBasicBlock *TargetRegionMBB);
  171. bool runOnMachineFunction(MachineFunction &MF) override;
  172. };
  173. } // End anonymous namespace.
  174. char PPCBranchCoalescing::ID = 0;
  175. /// createPPCBranchCoalescingPass - returns an instance of the Branch Coalescing
  176. /// Pass
  177. FunctionPass *llvm::createPPCBranchCoalescingPass() {
  178. return new PPCBranchCoalescing();
  179. }
  180. INITIALIZE_PASS_BEGIN(PPCBranchCoalescing, DEBUG_TYPE,
  181. "Branch Coalescing", false, false)
  182. INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
  183. INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
  184. INITIALIZE_PASS_END(PPCBranchCoalescing, DEBUG_TYPE, "Branch Coalescing",
  185. false, false)
  186. PPCBranchCoalescing::CoalescingCandidateInfo::CoalescingCandidateInfo()
  187. : BranchBlock(nullptr), BranchTargetBlock(nullptr),
  188. FallThroughBlock(nullptr), MustMoveDown(false), MustMoveUp(false) {}
  189. void PPCBranchCoalescing::CoalescingCandidateInfo::clear() {
  190. BranchBlock = nullptr;
  191. BranchTargetBlock = nullptr;
  192. FallThroughBlock = nullptr;
  193. Cond.clear();
  194. MustMoveDown = false;
  195. MustMoveUp = false;
  196. }
  197. void PPCBranchCoalescing::initialize(MachineFunction &MF) {
  198. MDT = &getAnalysis<MachineDominatorTree>();
  199. MPDT = &getAnalysis<MachinePostDominatorTree>();
  200. TII = MF.getSubtarget().getInstrInfo();
  201. MRI = &MF.getRegInfo();
  202. }
  203. ///
  204. /// Analyze the branch statement to determine if it can be coalesced. This
  205. /// method analyses the branch statement for the given candidate to determine
  206. /// if it can be coalesced. If the branch can be coalesced, then the
  207. /// BranchTargetBlock and the FallThroughBlock are recorded in the specified
  208. /// Candidate.
  209. ///
  210. ///\param[in,out] Cand The coalescing candidate to analyze
  211. ///\return true if and only if the branch can be coalesced, false otherwise
  212. ///
  213. bool PPCBranchCoalescing::canCoalesceBranch(CoalescingCandidateInfo &Cand) {
  214. LLVM_DEBUG(dbgs() << "Determine if branch block "
  215. << Cand.BranchBlock->getNumber() << " can be coalesced:");
  216. MachineBasicBlock *FalseMBB = nullptr;
  217. if (TII->analyzeBranch(*Cand.BranchBlock, Cand.BranchTargetBlock, FalseMBB,
  218. Cand.Cond)) {
  219. LLVM_DEBUG(dbgs() << "TII unable to Analyze Branch - skip\n");
  220. return false;
  221. }
  222. for (auto &I : Cand.BranchBlock->terminators()) {
  223. LLVM_DEBUG(dbgs() << "Looking at terminator : " << I << "\n");
  224. if (!I.isBranch())
  225. continue;
  226. // The analyzeBranch method does not include any implicit operands.
  227. // This is not an issue on PPC but must be handled on other targets.
  228. // For this pass to be made target-independent, the analyzeBranch API
  229. // need to be updated to support implicit operands and there would
  230. // need to be a way to verify that any implicit operands would not be
  231. // clobbered by merging blocks. This would include identifying the
  232. // implicit operands as well as the basic block they are defined in.
  233. // This could be done by changing the analyzeBranch API to have it also
  234. // record and return the implicit operands and the blocks where they are
  235. // defined. Alternatively, the BranchCoalescing code would need to be
  236. // extended to identify the implicit operands. The analysis in canMerge
  237. // must then be extended to prove that none of the implicit operands are
  238. // changed in the blocks that are combined during coalescing.
  239. if (I.getNumOperands() != I.getNumExplicitOperands()) {
  240. LLVM_DEBUG(dbgs() << "Terminator contains implicit operands - skip : "
  241. << I << "\n");
  242. return false;
  243. }
  244. }
  245. if (Cand.BranchBlock->isEHPad() || Cand.BranchBlock->hasEHPadSuccessor()) {
  246. LLVM_DEBUG(dbgs() << "EH Pad - skip\n");
  247. return false;
  248. }
  249. if (Cand.BranchBlock->mayHaveInlineAsmBr()) {
  250. LLVM_DEBUG(dbgs() << "Inline Asm Br - skip\n");
  251. return false;
  252. }
  253. // For now only consider triangles (i.e, BranchTargetBlock is set,
  254. // FalseMBB is null, and BranchTargetBlock is a successor to BranchBlock)
  255. if (!Cand.BranchTargetBlock || FalseMBB ||
  256. !Cand.BranchBlock->isSuccessor(Cand.BranchTargetBlock)) {
  257. LLVM_DEBUG(dbgs() << "Does not form a triangle - skip\n");
  258. return false;
  259. }
  260. // Ensure there are only two successors
  261. if (Cand.BranchBlock->succ_size() != 2) {
  262. LLVM_DEBUG(dbgs() << "Does not have 2 successors - skip\n");
  263. return false;
  264. }
  265. // The block must be able to fall through.
  266. assert(Cand.BranchBlock->canFallThrough() &&
  267. "Expecting the block to fall through!");
  268. // We have already ensured there are exactly two successors to
  269. // BranchBlock and that BranchTargetBlock is a successor to BranchBlock.
  270. // Ensure the single fall though block is empty.
  271. MachineBasicBlock *Succ =
  272. (*Cand.BranchBlock->succ_begin() == Cand.BranchTargetBlock)
  273. ? *Cand.BranchBlock->succ_rbegin()
  274. : *Cand.BranchBlock->succ_begin();
  275. assert(Succ && "Expecting a valid fall-through block\n");
  276. if (!Succ->empty()) {
  277. LLVM_DEBUG(dbgs() << "Fall-through block contains code -- skip\n");
  278. return false;
  279. }
  280. if (!Succ->isSuccessor(Cand.BranchTargetBlock)) {
  281. LLVM_DEBUG(
  282. dbgs()
  283. << "Successor of fall through block is not branch taken block\n");
  284. return false;
  285. }
  286. Cand.FallThroughBlock = Succ;
  287. LLVM_DEBUG(dbgs() << "Valid Candidate\n");
  288. return true;
  289. }
  290. ///
  291. /// Determine if the two operand lists are identical
  292. ///
  293. /// \param[in] OpList1 operand list
  294. /// \param[in] OpList2 operand list
  295. /// \return true if and only if the operands lists are identical
  296. ///
  297. bool PPCBranchCoalescing::identicalOperands(
  298. ArrayRef<MachineOperand> OpList1, ArrayRef<MachineOperand> OpList2) const {
  299. if (OpList1.size() != OpList2.size()) {
  300. LLVM_DEBUG(dbgs() << "Operand list is different size\n");
  301. return false;
  302. }
  303. for (unsigned i = 0; i < OpList1.size(); ++i) {
  304. const MachineOperand &Op1 = OpList1[i];
  305. const MachineOperand &Op2 = OpList2[i];
  306. LLVM_DEBUG(dbgs() << "Op1: " << Op1 << "\n"
  307. << "Op2: " << Op2 << "\n");
  308. if (Op1.isIdenticalTo(Op2)) {
  309. // filter out instructions with physical-register uses
  310. if (Op1.isReg() && Op1.getReg().isPhysical()
  311. // If the physical register is constant then we can assume the value
  312. // has not changed between uses.
  313. && !(Op1.isUse() && MRI->isConstantPhysReg(Op1.getReg()))) {
  314. LLVM_DEBUG(dbgs() << "The operands are not provably identical.\n");
  315. return false;
  316. }
  317. LLVM_DEBUG(dbgs() << "Op1 and Op2 are identical!\n");
  318. continue;
  319. }
  320. // If the operands are not identical, but are registers, check to see if the
  321. // definition of the register produces the same value. If they produce the
  322. // same value, consider them to be identical.
  323. if (Op1.isReg() && Op2.isReg() && Op1.getReg().isVirtual() &&
  324. Op2.getReg().isVirtual()) {
  325. MachineInstr *Op1Def = MRI->getVRegDef(Op1.getReg());
  326. MachineInstr *Op2Def = MRI->getVRegDef(Op2.getReg());
  327. if (TII->produceSameValue(*Op1Def, *Op2Def, MRI)) {
  328. LLVM_DEBUG(dbgs() << "Op1Def: " << *Op1Def << " and " << *Op2Def
  329. << " produce the same value!\n");
  330. } else {
  331. LLVM_DEBUG(dbgs() << "Operands produce different values\n");
  332. return false;
  333. }
  334. } else {
  335. LLVM_DEBUG(dbgs() << "The operands are not provably identical.\n");
  336. return false;
  337. }
  338. }
  339. return true;
  340. }
  341. ///
  342. /// Moves ALL PHI instructions in SourceMBB to beginning of TargetMBB
  343. /// and update them to refer to the new block. PHI node ordering
  344. /// cannot be assumed so it does not matter where the PHI instructions
  345. /// are moved to in TargetMBB.
  346. ///
  347. /// \param[in] SourceMBB block to move PHI instructions from
  348. /// \param[in] TargetMBB block to move PHI instructions to
  349. ///
  350. void PPCBranchCoalescing::moveAndUpdatePHIs(MachineBasicBlock *SourceMBB,
  351. MachineBasicBlock *TargetMBB) {
  352. MachineBasicBlock::iterator MI = SourceMBB->begin();
  353. MachineBasicBlock::iterator ME = SourceMBB->getFirstNonPHI();
  354. if (MI == ME) {
  355. LLVM_DEBUG(dbgs() << "SourceMBB contains no PHI instructions.\n");
  356. return;
  357. }
  358. // Update all PHI instructions in SourceMBB and move to top of TargetMBB
  359. for (MachineBasicBlock::iterator Iter = MI; Iter != ME; Iter++) {
  360. MachineInstr &PHIInst = *Iter;
  361. for (unsigned i = 2, e = PHIInst.getNumOperands() + 1; i != e; i += 2) {
  362. MachineOperand &MO = PHIInst.getOperand(i);
  363. if (MO.getMBB() == SourceMBB)
  364. MO.setMBB(TargetMBB);
  365. }
  366. }
  367. TargetMBB->splice(TargetMBB->begin(), SourceMBB, MI, ME);
  368. }
  369. ///
  370. /// This function checks if MI can be moved to the beginning of the TargetMBB
  371. /// following PHI instructions. A MI instruction can be moved to beginning of
  372. /// the TargetMBB if there are no uses of it within the TargetMBB PHI nodes.
  373. ///
  374. /// \param[in] MI the machine instruction to move.
  375. /// \param[in] TargetMBB the machine basic block to move to
  376. /// \return true if it is safe to move MI to beginning of TargetMBB,
  377. /// false otherwise.
  378. ///
  379. bool PPCBranchCoalescing::canMoveToBeginning(const MachineInstr &MI,
  380. const MachineBasicBlock &TargetMBB
  381. ) const {
  382. LLVM_DEBUG(dbgs() << "Checking if " << MI << " can move to beginning of "
  383. << TargetMBB.getNumber() << "\n");
  384. for (auto &Def : MI.defs()) { // Looking at Def
  385. for (auto &Use : MRI->use_instructions(Def.getReg())) {
  386. if (Use.isPHI() && Use.getParent() == &TargetMBB) {
  387. LLVM_DEBUG(dbgs() << " *** used in a PHI -- cannot move ***\n");
  388. return false;
  389. }
  390. }
  391. }
  392. LLVM_DEBUG(dbgs() << " Safe to move to the beginning.\n");
  393. return true;
  394. }
  395. ///
  396. /// This function checks if MI can be moved to the end of the TargetMBB,
  397. /// immediately before the first terminator. A MI instruction can be moved
  398. /// to then end of the TargetMBB if no PHI node defines what MI uses within
  399. /// it's own MBB.
  400. ///
  401. /// \param[in] MI the machine instruction to move.
  402. /// \param[in] TargetMBB the machine basic block to move to
  403. /// \return true if it is safe to move MI to end of TargetMBB,
  404. /// false otherwise.
  405. ///
  406. bool PPCBranchCoalescing::canMoveToEnd(const MachineInstr &MI,
  407. const MachineBasicBlock &TargetMBB
  408. ) const {
  409. LLVM_DEBUG(dbgs() << "Checking if " << MI << " can move to end of "
  410. << TargetMBB.getNumber() << "\n");
  411. for (auto &Use : MI.uses()) {
  412. if (Use.isReg() && Use.getReg().isVirtual()) {
  413. MachineInstr *DefInst = MRI->getVRegDef(Use.getReg());
  414. if (DefInst->isPHI() && DefInst->getParent() == MI.getParent()) {
  415. LLVM_DEBUG(dbgs() << " *** Cannot move this instruction ***\n");
  416. return false;
  417. } else {
  418. LLVM_DEBUG(
  419. dbgs() << " *** def is in another block -- safe to move!\n");
  420. }
  421. }
  422. }
  423. LLVM_DEBUG(dbgs() << " Safe to move to the end.\n");
  424. return true;
  425. }
  426. ///
  427. /// This method checks to ensure the two coalescing candidates follows the
  428. /// expected pattern required for coalescing.
  429. ///
  430. /// \param[in] SourceRegion The candidate to move statements from
  431. /// \param[in] TargetRegion The candidate to move statements to
  432. /// \return true if all instructions in SourceRegion.BranchBlock can be merged
  433. /// into a block in TargetRegion; false otherwise.
  434. ///
  435. bool PPCBranchCoalescing::validateCandidates(
  436. CoalescingCandidateInfo &SourceRegion,
  437. CoalescingCandidateInfo &TargetRegion) const {
  438. if (TargetRegion.BranchTargetBlock != SourceRegion.BranchBlock)
  439. llvm_unreachable("Expecting SourceRegion to immediately follow TargetRegion");
  440. else if (!MDT->dominates(TargetRegion.BranchBlock, SourceRegion.BranchBlock))
  441. llvm_unreachable("Expecting TargetRegion to dominate SourceRegion");
  442. else if (!MPDT->dominates(SourceRegion.BranchBlock, TargetRegion.BranchBlock))
  443. llvm_unreachable("Expecting SourceRegion to post-dominate TargetRegion");
  444. else if (!TargetRegion.FallThroughBlock->empty() ||
  445. !SourceRegion.FallThroughBlock->empty())
  446. llvm_unreachable("Expecting fall-through blocks to be empty");
  447. return true;
  448. }
  449. ///
  450. /// This method determines whether the two coalescing candidates can be merged.
  451. /// In order to be merged, all instructions must be able to
  452. /// 1. Move to the beginning of the SourceRegion.BranchTargetBlock;
  453. /// 2. Move to the end of the TargetRegion.BranchBlock.
  454. /// Merging involves moving the instructions in the
  455. /// TargetRegion.BranchTargetBlock (also SourceRegion.BranchBlock).
  456. ///
  457. /// This function first try to move instructions from the
  458. /// TargetRegion.BranchTargetBlock down, to the beginning of the
  459. /// SourceRegion.BranchTargetBlock. This is not possible if any register defined
  460. /// in TargetRegion.BranchTargetBlock is used in a PHI node in the
  461. /// SourceRegion.BranchTargetBlock. In this case, check whether the statement
  462. /// can be moved up, to the end of the TargetRegion.BranchBlock (immediately
  463. /// before the branch statement). If it cannot move, then these blocks cannot
  464. /// be merged.
  465. ///
  466. /// Note that there is no analysis for moving instructions past the fall-through
  467. /// blocks because they are confirmed to be empty. An assert is thrown if they
  468. /// are not.
  469. ///
  470. /// \param[in] SourceRegion The candidate to move statements from
  471. /// \param[in] TargetRegion The candidate to move statements to
  472. /// \return true if all instructions in SourceRegion.BranchBlock can be merged
  473. /// into a block in TargetRegion, false otherwise.
  474. ///
  475. bool PPCBranchCoalescing::canMerge(CoalescingCandidateInfo &SourceRegion,
  476. CoalescingCandidateInfo &TargetRegion) const {
  477. if (!validateCandidates(SourceRegion, TargetRegion))
  478. return false;
  479. // Walk through PHI nodes first and see if they force the merge into the
  480. // SourceRegion.BranchTargetBlock.
  481. for (MachineBasicBlock::iterator
  482. I = SourceRegion.BranchBlock->instr_begin(),
  483. E = SourceRegion.BranchBlock->getFirstNonPHI();
  484. I != E; ++I) {
  485. for (auto &Def : I->defs())
  486. for (auto &Use : MRI->use_instructions(Def.getReg())) {
  487. if (Use.isPHI() && Use.getParent() == SourceRegion.BranchTargetBlock) {
  488. LLVM_DEBUG(dbgs()
  489. << "PHI " << *I
  490. << " defines register used in another "
  491. "PHI within branch target block -- can't merge\n");
  492. NumPHINotMoved++;
  493. return false;
  494. }
  495. if (Use.getParent() == SourceRegion.BranchBlock) {
  496. LLVM_DEBUG(dbgs() << "PHI " << *I
  497. << " defines register used in this "
  498. "block -- all must move down\n");
  499. SourceRegion.MustMoveDown = true;
  500. }
  501. }
  502. }
  503. // Walk through the MI to see if they should be merged into
  504. // TargetRegion.BranchBlock (up) or SourceRegion.BranchTargetBlock (down)
  505. for (MachineBasicBlock::iterator
  506. I = SourceRegion.BranchBlock->getFirstNonPHI(),
  507. E = SourceRegion.BranchBlock->end();
  508. I != E; ++I) {
  509. if (!canMoveToBeginning(*I, *SourceRegion.BranchTargetBlock)) {
  510. LLVM_DEBUG(dbgs() << "Instruction " << *I
  511. << " cannot move down - must move up!\n");
  512. SourceRegion.MustMoveUp = true;
  513. }
  514. if (!canMoveToEnd(*I, *TargetRegion.BranchBlock)) {
  515. LLVM_DEBUG(dbgs() << "Instruction " << *I
  516. << " cannot move up - must move down!\n");
  517. SourceRegion.MustMoveDown = true;
  518. }
  519. }
  520. return (SourceRegion.MustMoveUp && SourceRegion.MustMoveDown) ? false : true;
  521. }
  522. /// Merge the instructions from SourceRegion.BranchBlock,
  523. /// SourceRegion.BranchTargetBlock, and SourceRegion.FallThroughBlock into
  524. /// TargetRegion.BranchBlock, TargetRegion.BranchTargetBlock and
  525. /// TargetRegion.FallThroughBlock respectively.
  526. ///
  527. /// The successors for blocks in TargetRegion will be updated to use the
  528. /// successors from blocks in SourceRegion. Finally, the blocks in SourceRegion
  529. /// will be removed from the function.
  530. ///
  531. /// A region consists of a BranchBlock, a FallThroughBlock, and a
  532. /// BranchTargetBlock. Branch coalesce works on patterns where the
  533. /// TargetRegion's BranchTargetBlock must also be the SourceRegions's
  534. /// BranchBlock.
  535. ///
  536. /// Before mergeCandidates:
  537. ///
  538. /// +---------------------------+
  539. /// | TargetRegion.BranchBlock |
  540. /// +---------------------------+
  541. /// / |
  542. /// / +--------------------------------+
  543. /// | | TargetRegion.FallThroughBlock |
  544. /// \ +--------------------------------+
  545. /// \ |
  546. /// +----------------------------------+
  547. /// | TargetRegion.BranchTargetBlock |
  548. /// | SourceRegion.BranchBlock |
  549. /// +----------------------------------+
  550. /// / |
  551. /// / +--------------------------------+
  552. /// | | SourceRegion.FallThroughBlock |
  553. /// \ +--------------------------------+
  554. /// \ |
  555. /// +----------------------------------+
  556. /// | SourceRegion.BranchTargetBlock |
  557. /// +----------------------------------+
  558. ///
  559. /// After mergeCandidates:
  560. ///
  561. /// +-----------------------------+
  562. /// | TargetRegion.BranchBlock |
  563. /// | SourceRegion.BranchBlock |
  564. /// +-----------------------------+
  565. /// / |
  566. /// / +---------------------------------+
  567. /// | | TargetRegion.FallThroughBlock |
  568. /// | | SourceRegion.FallThroughBlock |
  569. /// \ +---------------------------------+
  570. /// \ |
  571. /// +----------------------------------+
  572. /// | SourceRegion.BranchTargetBlock |
  573. /// +----------------------------------+
  574. ///
  575. /// \param[in] SourceRegion The candidate to move blocks from
  576. /// \param[in] TargetRegion The candidate to move blocks to
  577. ///
  578. bool PPCBranchCoalescing::mergeCandidates(CoalescingCandidateInfo &SourceRegion,
  579. CoalescingCandidateInfo &TargetRegion) {
  580. if (SourceRegion.MustMoveUp && SourceRegion.MustMoveDown) {
  581. llvm_unreachable("Cannot have both MustMoveDown and MustMoveUp set!");
  582. return false;
  583. }
  584. if (!validateCandidates(SourceRegion, TargetRegion))
  585. return false;
  586. // Start the merging process by first handling the BranchBlock.
  587. // Move any PHIs in SourceRegion.BranchBlock down to the branch-taken block
  588. moveAndUpdatePHIs(SourceRegion.BranchBlock, SourceRegion.BranchTargetBlock);
  589. // Move remaining instructions in SourceRegion.BranchBlock into
  590. // TargetRegion.BranchBlock
  591. MachineBasicBlock::iterator firstInstr =
  592. SourceRegion.BranchBlock->getFirstNonPHI();
  593. MachineBasicBlock::iterator lastInstr =
  594. SourceRegion.BranchBlock->getFirstTerminator();
  595. MachineBasicBlock *Source = SourceRegion.MustMoveDown
  596. ? SourceRegion.BranchTargetBlock
  597. : TargetRegion.BranchBlock;
  598. MachineBasicBlock::iterator Target =
  599. SourceRegion.MustMoveDown
  600. ? SourceRegion.BranchTargetBlock->getFirstNonPHI()
  601. : TargetRegion.BranchBlock->getFirstTerminator();
  602. Source->splice(Target, SourceRegion.BranchBlock, firstInstr, lastInstr);
  603. // Once PHI and instructions have been moved we need to clean up the
  604. // control flow.
  605. // Remove SourceRegion.FallThroughBlock before transferring successors of
  606. // SourceRegion.BranchBlock to TargetRegion.BranchBlock.
  607. SourceRegion.BranchBlock->removeSuccessor(SourceRegion.FallThroughBlock);
  608. TargetRegion.BranchBlock->transferSuccessorsAndUpdatePHIs(
  609. SourceRegion.BranchBlock);
  610. // Update branch in TargetRegion.BranchBlock to jump to
  611. // SourceRegion.BranchTargetBlock
  612. // In this case, TargetRegion.BranchTargetBlock == SourceRegion.BranchBlock.
  613. TargetRegion.BranchBlock->ReplaceUsesOfBlockWith(
  614. SourceRegion.BranchBlock, SourceRegion.BranchTargetBlock);
  615. // Remove the branch statement(s) in SourceRegion.BranchBlock
  616. MachineBasicBlock::iterator I =
  617. SourceRegion.BranchBlock->terminators().begin();
  618. while (I != SourceRegion.BranchBlock->terminators().end()) {
  619. MachineInstr &CurrInst = *I;
  620. ++I;
  621. if (CurrInst.isBranch())
  622. CurrInst.eraseFromParent();
  623. }
  624. // Fall-through block should be empty since this is part of the condition
  625. // to coalesce the branches.
  626. assert(TargetRegion.FallThroughBlock->empty() &&
  627. "FallThroughBlocks should be empty!");
  628. // Transfer successor information and move PHIs down to the
  629. // branch-taken block.
  630. TargetRegion.FallThroughBlock->transferSuccessorsAndUpdatePHIs(
  631. SourceRegion.FallThroughBlock);
  632. TargetRegion.FallThroughBlock->removeSuccessor(SourceRegion.BranchBlock);
  633. // Remove the blocks from the function.
  634. assert(SourceRegion.BranchBlock->empty() &&
  635. "Expecting branch block to be empty!");
  636. SourceRegion.BranchBlock->eraseFromParent();
  637. assert(SourceRegion.FallThroughBlock->empty() &&
  638. "Expecting fall-through block to be empty!\n");
  639. SourceRegion.FallThroughBlock->eraseFromParent();
  640. NumBlocksCoalesced++;
  641. return true;
  642. }
  643. bool PPCBranchCoalescing::runOnMachineFunction(MachineFunction &MF) {
  644. if (skipFunction(MF.getFunction()) || MF.empty())
  645. return false;
  646. bool didSomething = false;
  647. LLVM_DEBUG(dbgs() << "******** Branch Coalescing ********\n");
  648. initialize(MF);
  649. LLVM_DEBUG(dbgs() << "Function: "; MF.dump(); dbgs() << "\n");
  650. CoalescingCandidateInfo Cand1, Cand2;
  651. // Walk over blocks and find candidates to merge
  652. // Continue trying to merge with the first candidate found, as long as merging
  653. // is successfull.
  654. for (MachineBasicBlock &MBB : MF) {
  655. bool MergedCandidates = false;
  656. do {
  657. MergedCandidates = false;
  658. Cand1.clear();
  659. Cand2.clear();
  660. Cand1.BranchBlock = &MBB;
  661. // If unable to coalesce the branch, then continue to next block
  662. if (!canCoalesceBranch(Cand1))
  663. break;
  664. Cand2.BranchBlock = Cand1.BranchTargetBlock;
  665. if (!canCoalesceBranch(Cand2))
  666. break;
  667. // The branch-taken block of the second candidate should post-dominate the
  668. // first candidate.
  669. assert(MPDT->dominates(Cand2.BranchTargetBlock, Cand1.BranchBlock) &&
  670. "Branch-taken block should post-dominate first candidate");
  671. if (!identicalOperands(Cand1.Cond, Cand2.Cond)) {
  672. LLVM_DEBUG(dbgs() << "Blocks " << Cand1.BranchBlock->getNumber()
  673. << " and " << Cand2.BranchBlock->getNumber()
  674. << " have different branches\n");
  675. break;
  676. }
  677. if (!canMerge(Cand2, Cand1)) {
  678. LLVM_DEBUG(dbgs() << "Cannot merge blocks "
  679. << Cand1.BranchBlock->getNumber() << " and "
  680. << Cand2.BranchBlock->getNumber() << "\n");
  681. NumBlocksNotCoalesced++;
  682. continue;
  683. }
  684. LLVM_DEBUG(dbgs() << "Merging blocks " << Cand1.BranchBlock->getNumber()
  685. << " and " << Cand1.BranchTargetBlock->getNumber()
  686. << "\n");
  687. MergedCandidates = mergeCandidates(Cand2, Cand1);
  688. if (MergedCandidates)
  689. didSomething = true;
  690. LLVM_DEBUG(dbgs() << "Function after merging: "; MF.dump();
  691. dbgs() << "\n");
  692. } while (MergedCandidates);
  693. }
  694. #ifndef NDEBUG
  695. // Verify MF is still valid after branch coalescing
  696. if (didSomething)
  697. MF.verify(nullptr, "Error in code produced by branch coalescing");
  698. #endif // NDEBUG
  699. LLVM_DEBUG(dbgs() << "Finished Branch Coalescing\n");
  700. return didSomething;
  701. }