134e66217SLei Huang //===-- CoalesceBranches.cpp - Coalesce blocks with the same condition ---===//
234e66217SLei Huang //
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
634e66217SLei Huang //
734e66217SLei Huang //===----------------------------------------------------------------------===//
834e66217SLei Huang ///
934e66217SLei Huang /// \file
1034e66217SLei Huang /// Coalesce basic blocks guarded by the same branch condition into a single
1134e66217SLei Huang /// basic block.
1234e66217SLei Huang ///
1334e66217SLei Huang //===----------------------------------------------------------------------===//
1434e66217SLei Huang 
1534e66217SLei Huang #include "PPC.h"
1634e66217SLei Huang #include "llvm/ADT/BitVector.h"
1734e66217SLei Huang #include "llvm/ADT/Statistic.h"
1834e66217SLei Huang #include "llvm/CodeGen/MachineDominators.h"
1934e66217SLei Huang #include "llvm/CodeGen/MachineFunctionPass.h"
2034e66217SLei Huang #include "llvm/CodeGen/MachinePostDominators.h"
2134e66217SLei Huang #include "llvm/CodeGen/MachineRegisterInfo.h"
2234e66217SLei Huang #include "llvm/CodeGen/Passes.h"
231be62f03SDavid Blaikie #include "llvm/CodeGen/TargetFrameLowering.h"
243f833edcSDavid Blaikie #include "llvm/CodeGen/TargetInstrInfo.h"
25b3bde2eaSDavid Blaikie #include "llvm/CodeGen/TargetSubtargetInfo.h"
2605da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
273f833edcSDavid Blaikie #include "llvm/Support/Debug.h"
2834e66217SLei Huang 
2934e66217SLei Huang using namespace llvm;
3034e66217SLei Huang 
3134e66217SLei Huang #define DEBUG_TYPE "ppc-branch-coalescing"
3234e66217SLei Huang 
3334e66217SLei Huang STATISTIC(NumBlocksCoalesced, "Number of blocks coalesced");
3434e66217SLei Huang STATISTIC(NumPHINotMoved, "Number of PHI Nodes that cannot be merged");
3534e66217SLei Huang STATISTIC(NumBlocksNotCoalesced, "Number of blocks not coalesced");
3634e66217SLei Huang 
3734e66217SLei Huang //===----------------------------------------------------------------------===//
3834e66217SLei Huang //                               PPCBranchCoalescing
3934e66217SLei Huang //===----------------------------------------------------------------------===//
4034e66217SLei Huang ///
4134e66217SLei Huang /// Improve scheduling by coalescing branches that depend on the same condition.
4234e66217SLei Huang /// This pass looks for blocks that are guarded by the same branch condition
4334e66217SLei Huang /// and attempts to merge the blocks together. Such opportunities arise from
4434e66217SLei Huang /// the expansion of select statements in the IR.
4534e66217SLei Huang ///
4634e66217SLei Huang /// This pass does not handle implicit operands on branch statements. In order
4734e66217SLei Huang /// to run on targets that use implicit operands, changes need to be made in the
4834e66217SLei Huang /// canCoalesceBranch and canMerge methods.
4934e66217SLei Huang ///
5034e66217SLei Huang /// Example: the following LLVM IR
5134e66217SLei Huang ///
5234e66217SLei Huang ///     %test = icmp eq i32 %x 0
5334e66217SLei Huang ///     %tmp1 = select i1 %test, double %a, double 2.000000e-03
5434e66217SLei Huang ///     %tmp2 = select i1 %test, double %b, double 5.000000e-03
5534e66217SLei Huang ///
5634e66217SLei Huang /// expands to the following machine code:
5734e66217SLei Huang ///
5825528d6dSFrancis Visoiu Mistrih /// %bb.0: derived from LLVM BB %entry
59fb7b14f7SFrancis Visoiu Mistrih ///    liveins: %f1 %f3 %x6
6034e66217SLei Huang ///        <SNIP1>
61a8a83d15SFrancis Visoiu Mistrih ///        %0 = COPY %f1; F8RC:%0
62a8a83d15SFrancis Visoiu Mistrih ///        %5 = CMPLWI killed %4, 0; CRRC:%5 GPRC:%4
63a8a83d15SFrancis Visoiu Mistrih ///        %8 = LXSDX %zero8, killed %7, implicit %rm;
6493ef1458SFrancis Visoiu Mistrih ///                    mem:LD8[ConstantPool] F8RC:%8 G8RC:%7
6525528d6dSFrancis Visoiu Mistrih ///        BCC 76, %5, <%bb.2>; CRRC:%5
6625528d6dSFrancis Visoiu Mistrih ///    Successors according to CFG: %bb.1(?%) %bb.2(?%)
6734e66217SLei Huang ///
6825528d6dSFrancis Visoiu Mistrih /// %bb.1: derived from LLVM BB %entry
6925528d6dSFrancis Visoiu Mistrih ///    Predecessors according to CFG: %bb.0
7025528d6dSFrancis Visoiu Mistrih ///    Successors according to CFG: %bb.2(?%)
7134e66217SLei Huang ///
7225528d6dSFrancis Visoiu Mistrih /// %bb.2: derived from LLVM BB %entry
7325528d6dSFrancis Visoiu Mistrih ///    Predecessors according to CFG: %bb.0 %bb.1
74a8a83d15SFrancis Visoiu Mistrih ///        %9 = PHI %8, <%bb.1>, %0, <%bb.0>;
7593ef1458SFrancis Visoiu Mistrih ///                    F8RC:%9,%8,%0
7634e66217SLei Huang ///        <SNIP2>
7725528d6dSFrancis Visoiu Mistrih ///        BCC 76, %5, <%bb.4>; CRRC:%5
7825528d6dSFrancis Visoiu Mistrih ///    Successors according to CFG: %bb.3(?%) %bb.4(?%)
7934e66217SLei Huang ///
8025528d6dSFrancis Visoiu Mistrih /// %bb.3: derived from LLVM BB %entry
8125528d6dSFrancis Visoiu Mistrih ///    Predecessors according to CFG: %bb.2
8225528d6dSFrancis Visoiu Mistrih ///    Successors according to CFG: %bb.4(?%)
8334e66217SLei Huang ///
8425528d6dSFrancis Visoiu Mistrih /// %bb.4: derived from LLVM BB %entry
8525528d6dSFrancis Visoiu Mistrih ///    Predecessors according to CFG: %bb.2 %bb.3
86a8a83d15SFrancis Visoiu Mistrih ///        %13 = PHI %12, <%bb.3>, %2, <%bb.2>;
8793ef1458SFrancis Visoiu Mistrih ///                     F8RC:%13,%12,%2
8834e66217SLei Huang ///        <SNIP3>
89a8a83d15SFrancis Visoiu Mistrih ///        BLR8 implicit %lr8, implicit %rm, implicit %f1
9034e66217SLei Huang ///
9134e66217SLei Huang /// When this pattern is detected, branch coalescing will try to collapse
9225528d6dSFrancis Visoiu Mistrih /// it by moving code in %bb.2 to %bb.0 and/or %bb.4 and removing %bb.3.
9334e66217SLei Huang ///
9434e66217SLei Huang /// If all conditions are meet, IR should collapse to:
9534e66217SLei Huang ///
9625528d6dSFrancis Visoiu Mistrih /// %bb.0: derived from LLVM BB %entry
97fb7b14f7SFrancis Visoiu Mistrih ///    liveins: %f1 %f3 %x6
9834e66217SLei Huang ///        <SNIP1>
99a8a83d15SFrancis Visoiu Mistrih ///        %0 = COPY %f1; F8RC:%0
100a8a83d15SFrancis Visoiu Mistrih ///        %5 = CMPLWI killed %4, 0; CRRC:%5 GPRC:%4
101a8a83d15SFrancis Visoiu Mistrih ///        %8 = LXSDX %zero8, killed %7, implicit %rm;
10293ef1458SFrancis Visoiu Mistrih ///                     mem:LD8[ConstantPool] F8RC:%8 G8RC:%7
10334e66217SLei Huang ///        <SNIP2>
10425528d6dSFrancis Visoiu Mistrih ///        BCC 76, %5, <%bb.4>; CRRC:%5
10525528d6dSFrancis Visoiu Mistrih ///    Successors according to CFG: %bb.1(0x2aaaaaaa / 0x80000000 = 33.33%)
10625528d6dSFrancis Visoiu Mistrih ///      %bb.4(0x55555554 / 0x80000000 = 66.67%)
10734e66217SLei Huang ///
10825528d6dSFrancis Visoiu Mistrih /// %bb.1: derived from LLVM BB %entry
10925528d6dSFrancis Visoiu Mistrih ///    Predecessors according to CFG: %bb.0
11025528d6dSFrancis Visoiu Mistrih ///    Successors according to CFG: %bb.4(0x40000000 / 0x80000000 = 50.00%)
11134e66217SLei Huang ///
11225528d6dSFrancis Visoiu Mistrih /// %bb.4: derived from LLVM BB %entry
11325528d6dSFrancis Visoiu Mistrih ///    Predecessors according to CFG: %bb.0 %bb.1
114a8a83d15SFrancis Visoiu Mistrih ///        %9 = PHI %8, <%bb.1>, %0, <%bb.0>;
11593ef1458SFrancis Visoiu Mistrih ///                    F8RC:%9,%8,%0
116a8a83d15SFrancis Visoiu Mistrih ///        %13 = PHI %12, <%bb.1>, %2, <%bb.0>;
11793ef1458SFrancis Visoiu Mistrih ///                     F8RC:%13,%12,%2
11834e66217SLei Huang ///        <SNIP3>
119a8a83d15SFrancis Visoiu Mistrih ///        BLR8 implicit %lr8, implicit %rm, implicit %f1
12034e66217SLei Huang ///
12134e66217SLei Huang /// Branch Coalescing does not split blocks, it moves everything in the same
12234e66217SLei Huang /// direction ensuring it does not break use/definition semantics.
12334e66217SLei Huang ///
12434e66217SLei Huang /// PHI nodes and its corresponding use instructions are moved to its successor
12534e66217SLei Huang /// block if there are no uses within the successor block PHI nodes.  PHI
12634e66217SLei Huang /// node ordering cannot be assumed.
12734e66217SLei Huang ///
12834e66217SLei Huang /// Non-PHI can be moved up to the predecessor basic block or down to the
12934e66217SLei Huang /// successor basic block following any PHI instructions. Whether it moves
13034e66217SLei Huang /// up or down depends on whether the register(s) defined in the instructions
13134e66217SLei Huang /// are used in current block or in any PHI instructions at the beginning of
13234e66217SLei Huang /// the successor block.
13334e66217SLei Huang 
13434e66217SLei Huang namespace {
13534e66217SLei Huang 
13634e66217SLei Huang class PPCBranchCoalescing : public MachineFunctionPass {
13734e66217SLei Huang   struct CoalescingCandidateInfo {
13834e66217SLei Huang     MachineBasicBlock *BranchBlock;       // Block containing the branch
13934e66217SLei Huang     MachineBasicBlock *BranchTargetBlock; // Block branched to
14034e66217SLei Huang     MachineBasicBlock *FallThroughBlock;  // Fall-through if branch not taken
14134e66217SLei Huang     SmallVector<MachineOperand, 4> Cond;
14234e66217SLei Huang     bool MustMoveDown;
14334e66217SLei Huang     bool MustMoveUp;
14434e66217SLei Huang 
14534e66217SLei Huang     CoalescingCandidateInfo();
14634e66217SLei Huang     void clear();
14734e66217SLei Huang   };
14834e66217SLei Huang 
14934e66217SLei Huang   MachineDominatorTree *MDT;
15034e66217SLei Huang   MachinePostDominatorTree *MPDT;
15134e66217SLei Huang   const TargetInstrInfo *TII;
15234e66217SLei Huang   MachineRegisterInfo *MRI;
15334e66217SLei Huang 
15434e66217SLei Huang   void initialize(MachineFunction &F);
15534e66217SLei Huang   bool canCoalesceBranch(CoalescingCandidateInfo &Cand);
15634e66217SLei Huang   bool identicalOperands(ArrayRef<MachineOperand> OperandList1,
15734e66217SLei Huang                          ArrayRef<MachineOperand> OperandList2) const;
15834e66217SLei Huang   bool validateCandidates(CoalescingCandidateInfo &SourceRegion,
15934e66217SLei Huang                           CoalescingCandidateInfo &TargetRegion) const;
16034e66217SLei Huang 
16134e66217SLei Huang public:
16234e66217SLei Huang   static char ID;
16334e66217SLei Huang 
PPCBranchCoalescing()16434e66217SLei Huang   PPCBranchCoalescing() : MachineFunctionPass(ID) {
16534e66217SLei Huang     initializePPCBranchCoalescingPass(*PassRegistry::getPassRegistry());
16634e66217SLei Huang   }
16734e66217SLei Huang 
getAnalysisUsage(AnalysisUsage & AU) const16834e66217SLei Huang   void getAnalysisUsage(AnalysisUsage &AU) const override {
16934e66217SLei Huang     AU.addRequired<MachineDominatorTree>();
17034e66217SLei Huang     AU.addRequired<MachinePostDominatorTree>();
17134e66217SLei Huang     MachineFunctionPass::getAnalysisUsage(AU);
17234e66217SLei Huang   }
17334e66217SLei Huang 
getPassName() const17434e66217SLei Huang   StringRef getPassName() const override { return "Branch Coalescing"; }
17534e66217SLei Huang 
17634e66217SLei Huang   bool mergeCandidates(CoalescingCandidateInfo &SourceRegion,
17734e66217SLei Huang                        CoalescingCandidateInfo &TargetRegion);
17834e66217SLei Huang   bool canMoveToBeginning(const MachineInstr &MI,
17934e66217SLei Huang                           const MachineBasicBlock &MBB) const;
18034e66217SLei Huang   bool canMoveToEnd(const MachineInstr &MI,
18134e66217SLei Huang                     const MachineBasicBlock &MBB) const;
18234e66217SLei Huang   bool canMerge(CoalescingCandidateInfo &SourceRegion,
18334e66217SLei Huang                 CoalescingCandidateInfo &TargetRegion) const;
18434e66217SLei Huang   void moveAndUpdatePHIs(MachineBasicBlock *SourceRegionMBB,
18534e66217SLei Huang                          MachineBasicBlock *TargetRegionMBB);
18634e66217SLei Huang   bool runOnMachineFunction(MachineFunction &MF) override;
18734e66217SLei Huang };
18834e66217SLei Huang } // End anonymous namespace.
18934e66217SLei Huang 
19034e66217SLei Huang char PPCBranchCoalescing::ID = 0;
19134e66217SLei Huang /// createPPCBranchCoalescingPass - returns an instance of the Branch Coalescing
19234e66217SLei Huang /// Pass
createPPCBranchCoalescingPass()19334e66217SLei Huang FunctionPass *llvm::createPPCBranchCoalescingPass() {
19434e66217SLei Huang   return new PPCBranchCoalescing();
19534e66217SLei Huang }
19634e66217SLei Huang 
19734e66217SLei Huang INITIALIZE_PASS_BEGIN(PPCBranchCoalescing, DEBUG_TYPE,
19834e66217SLei Huang                       "Branch Coalescing", false, false)
INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)19934e66217SLei Huang INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
20034e66217SLei Huang INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
20134e66217SLei Huang INITIALIZE_PASS_END(PPCBranchCoalescing, DEBUG_TYPE, "Branch Coalescing",
20234e66217SLei Huang                     false, false)
20334e66217SLei Huang 
20434e66217SLei Huang PPCBranchCoalescing::CoalescingCandidateInfo::CoalescingCandidateInfo()
20534e66217SLei Huang     : BranchBlock(nullptr), BranchTargetBlock(nullptr),
20634e66217SLei Huang       FallThroughBlock(nullptr), MustMoveDown(false), MustMoveUp(false) {}
20734e66217SLei Huang 
clear()20834e66217SLei Huang void PPCBranchCoalescing::CoalescingCandidateInfo::clear() {
20934e66217SLei Huang   BranchBlock = nullptr;
21034e66217SLei Huang   BranchTargetBlock = nullptr;
21134e66217SLei Huang   FallThroughBlock = nullptr;
21234e66217SLei Huang   Cond.clear();
21334e66217SLei Huang   MustMoveDown = false;
21434e66217SLei Huang   MustMoveUp = false;
21534e66217SLei Huang }
21634e66217SLei Huang 
initialize(MachineFunction & MF)21734e66217SLei Huang void PPCBranchCoalescing::initialize(MachineFunction &MF) {
21834e66217SLei Huang   MDT = &getAnalysis<MachineDominatorTree>();
21934e66217SLei Huang   MPDT = &getAnalysis<MachinePostDominatorTree>();
22034e66217SLei Huang   TII = MF.getSubtarget().getInstrInfo();
22134e66217SLei Huang   MRI = &MF.getRegInfo();
22234e66217SLei Huang }
22334e66217SLei Huang 
22434e66217SLei Huang ///
22534e66217SLei Huang /// Analyze the branch statement to determine if it can be coalesced. This
22634e66217SLei Huang /// method analyses the branch statement for the given candidate to determine
22734e66217SLei Huang /// if it can be coalesced. If the branch can be coalesced, then the
22834e66217SLei Huang /// BranchTargetBlock and the FallThroughBlock are recorded in the specified
22934e66217SLei Huang /// Candidate.
23034e66217SLei Huang ///
23134e66217SLei Huang ///\param[in,out] Cand The coalescing candidate to analyze
23234e66217SLei Huang ///\return true if and only if the branch can be coalesced, false otherwise
23334e66217SLei Huang ///
canCoalesceBranch(CoalescingCandidateInfo & Cand)23434e66217SLei Huang bool PPCBranchCoalescing::canCoalesceBranch(CoalescingCandidateInfo &Cand) {
235d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Determine if branch block "
236d34e60caSNicola Zaghen                     << Cand.BranchBlock->getNumber() << " can be coalesced:");
23734e66217SLei Huang   MachineBasicBlock *FalseMBB = nullptr;
23834e66217SLei Huang 
23934e66217SLei Huang   if (TII->analyzeBranch(*Cand.BranchBlock, Cand.BranchTargetBlock, FalseMBB,
24034e66217SLei Huang                          Cand.Cond)) {
241d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "TII unable to Analyze Branch - skip\n");
24234e66217SLei Huang     return false;
24334e66217SLei Huang   }
24434e66217SLei Huang 
24534e66217SLei Huang   for (auto &I : Cand.BranchBlock->terminators()) {
246d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Looking at terminator : " << I << "\n");
24734e66217SLei Huang     if (!I.isBranch())
24834e66217SLei Huang       continue;
24934e66217SLei Huang 
25034e66217SLei Huang     // The analyzeBranch method does not include any implicit operands.
25134e66217SLei Huang     // This is not an issue on PPC but must be handled on other targets.
25234e66217SLei Huang     // For this pass to be made target-independent, the analyzeBranch API
25334e66217SLei Huang     // need to be updated to support implicit operands and there would
25434e66217SLei Huang     // need to be a way to verify that any implicit operands would not be
25534e66217SLei Huang     // clobbered by merging blocks.  This would include identifying the
25634e66217SLei Huang     // implicit operands as well as the basic block they are defined in.
25734e66217SLei Huang     // This could be done by changing the analyzeBranch API to have it also
25834e66217SLei Huang     // record and return the implicit operands and the blocks where they are
25934e66217SLei Huang     // defined. Alternatively, the BranchCoalescing code would need to be
26034e66217SLei Huang     // extended to identify the implicit operands.  The analysis in canMerge
26134e66217SLei Huang     // must then be extended to prove that none of the implicit operands are
26234e66217SLei Huang     // changed in the blocks that are combined during coalescing.
26334e66217SLei Huang     if (I.getNumOperands() != I.getNumExplicitOperands()) {
264d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Terminator contains implicit operands - skip : "
265d34e60caSNicola Zaghen                         << I << "\n");
26634e66217SLei Huang       return false;
26734e66217SLei Huang     }
26834e66217SLei Huang   }
26934e66217SLei Huang 
27034e66217SLei Huang   if (Cand.BranchBlock->isEHPad() || Cand.BranchBlock->hasEHPadSuccessor()) {
271d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "EH Pad - skip\n");
27234e66217SLei Huang     return false;
27334e66217SLei Huang   }
27434e66217SLei Huang 
2754b0aa572SJames Y Knight   if (Cand.BranchBlock->mayHaveInlineAsmBr()) {
2764b0aa572SJames Y Knight     LLVM_DEBUG(dbgs() << "Inline Asm Br - skip\n");
2774b0aa572SJames Y Knight     return false;
2784b0aa572SJames Y Knight   }
2794b0aa572SJames Y Knight 
28034e66217SLei Huang   // For now only consider triangles (i.e, BranchTargetBlock is set,
28134e66217SLei Huang   // FalseMBB is null, and BranchTargetBlock is a successor to BranchBlock)
28234e66217SLei Huang   if (!Cand.BranchTargetBlock || FalseMBB ||
28334e66217SLei Huang       !Cand.BranchBlock->isSuccessor(Cand.BranchTargetBlock)) {
284d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Does not form a triangle - skip\n");
28534e66217SLei Huang     return false;
28634e66217SLei Huang   }
28734e66217SLei Huang 
28834e66217SLei Huang   // Ensure there are only two successors
28934e66217SLei Huang   if (Cand.BranchBlock->succ_size() != 2) {
290d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Does not have 2 successors - skip\n");
29134e66217SLei Huang     return false;
29234e66217SLei Huang   }
29334e66217SLei Huang 
294*e9163660SZarko Todorovski   // The block must be able to fall through.
29534e66217SLei Huang   assert(Cand.BranchBlock->canFallThrough() &&
29634e66217SLei Huang          "Expecting the block to fall through!");
29734e66217SLei Huang 
29834e66217SLei Huang   // We have already ensured there are exactly two successors to
29934e66217SLei Huang   // BranchBlock and that BranchTargetBlock is a successor to BranchBlock.
30034e66217SLei Huang   // Ensure the single fall though block is empty.
30134e66217SLei Huang   MachineBasicBlock *Succ =
30234e66217SLei Huang     (*Cand.BranchBlock->succ_begin() == Cand.BranchTargetBlock)
30334e66217SLei Huang     ? *Cand.BranchBlock->succ_rbegin()
30434e66217SLei Huang     : *Cand.BranchBlock->succ_begin();
30534e66217SLei Huang 
30634e66217SLei Huang   assert(Succ && "Expecting a valid fall-through block\n");
30734e66217SLei Huang 
30834e66217SLei Huang   if (!Succ->empty()) {
309d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Fall-through block contains code -- skip\n");
31034e66217SLei Huang     return false;
31134e66217SLei Huang   }
31234e66217SLei Huang 
31334e66217SLei Huang   if (!Succ->isSuccessor(Cand.BranchTargetBlock)) {
314d34e60caSNicola Zaghen     LLVM_DEBUG(
315d34e60caSNicola Zaghen         dbgs()
31634e66217SLei Huang         << "Successor of fall through block is not branch taken block\n");
31734e66217SLei Huang     return false;
31834e66217SLei Huang   }
31934e66217SLei Huang 
32034e66217SLei Huang   Cand.FallThroughBlock = Succ;
321d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Valid Candidate\n");
32234e66217SLei Huang   return true;
32334e66217SLei Huang }
32434e66217SLei Huang 
32534e66217SLei Huang ///
32634e66217SLei Huang /// Determine if the two operand lists are identical
32734e66217SLei Huang ///
32834e66217SLei Huang /// \param[in] OpList1 operand list
32934e66217SLei Huang /// \param[in] OpList2 operand list
33034e66217SLei Huang /// \return true if and only if the operands lists are identical
33134e66217SLei Huang ///
identicalOperands(ArrayRef<MachineOperand> OpList1,ArrayRef<MachineOperand> OpList2) const33234e66217SLei Huang bool PPCBranchCoalescing::identicalOperands(
33334e66217SLei Huang     ArrayRef<MachineOperand> OpList1, ArrayRef<MachineOperand> OpList2) const {
33434e66217SLei Huang 
33534e66217SLei Huang   if (OpList1.size() != OpList2.size()) {
336d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Operand list is different size\n");
33734e66217SLei Huang     return false;
33834e66217SLei Huang   }
33934e66217SLei Huang 
34034e66217SLei Huang   for (unsigned i = 0; i < OpList1.size(); ++i) {
34134e66217SLei Huang     const MachineOperand &Op1 = OpList1[i];
34234e66217SLei Huang     const MachineOperand &Op2 = OpList2[i];
34334e66217SLei Huang 
344d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Op1: " << Op1 << "\n"
34534e66217SLei Huang                       << "Op2: " << Op2 << "\n");
34634e66217SLei Huang 
34734e66217SLei Huang     if (Op1.isIdenticalTo(Op2)) {
34834e66217SLei Huang       // filter out instructions with physical-register uses
3492bea69bfSDaniel Sanders       if (Op1.isReg() &&
3502bea69bfSDaniel Sanders           Register::isPhysicalRegister(Op1.getReg())
35134e66217SLei Huang           // If the physical register is constant then we can assume the value
35234e66217SLei Huang           // has not changed between uses.
35334e66217SLei Huang           && !(Op1.isUse() && MRI->isConstantPhysReg(Op1.getReg()))) {
354d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "The operands are not provably identical.\n");
35534e66217SLei Huang         return false;
35634e66217SLei Huang       }
357d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Op1 and Op2 are identical!\n");
35834e66217SLei Huang       continue;
35934e66217SLei Huang     }
36034e66217SLei Huang 
36134e66217SLei Huang     // If the operands are not identical, but are registers, check to see if the
36234e66217SLei Huang     // definition of the register produces the same value. If they produce the
36334e66217SLei Huang     // same value, consider them to be identical.
36434e66217SLei Huang     if (Op1.isReg() && Op2.isReg() &&
3652bea69bfSDaniel Sanders         Register::isVirtualRegister(Op1.getReg()) &&
3662bea69bfSDaniel Sanders         Register::isVirtualRegister(Op2.getReg())) {
36734e66217SLei Huang       MachineInstr *Op1Def = MRI->getVRegDef(Op1.getReg());
36834e66217SLei Huang       MachineInstr *Op2Def = MRI->getVRegDef(Op2.getReg());
36934e66217SLei Huang       if (TII->produceSameValue(*Op1Def, *Op2Def, MRI)) {
370d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Op1Def: " << *Op1Def << " and " << *Op2Def
37134e66217SLei Huang                           << " produce the same value!\n");
37234e66217SLei Huang       } else {
373d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Operands produce different values\n");
37434e66217SLei Huang         return false;
37534e66217SLei Huang       }
37634e66217SLei Huang     } else {
377d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "The operands are not provably identical.\n");
37834e66217SLei Huang       return false;
37934e66217SLei Huang     }
38034e66217SLei Huang   }
38134e66217SLei Huang 
38234e66217SLei Huang   return true;
38334e66217SLei Huang }
38434e66217SLei Huang 
38534e66217SLei Huang ///
38634e66217SLei Huang /// Moves ALL PHI instructions in SourceMBB to beginning of TargetMBB
38734e66217SLei Huang /// and update them to refer to the new block.  PHI node ordering
38834e66217SLei Huang /// cannot be assumed so it does not matter where the PHI instructions
38934e66217SLei Huang /// are moved to in TargetMBB.
39034e66217SLei Huang ///
39134e66217SLei Huang /// \param[in] SourceMBB block to move PHI instructions from
39234e66217SLei Huang /// \param[in] TargetMBB block to move PHI instructions to
39334e66217SLei Huang ///
moveAndUpdatePHIs(MachineBasicBlock * SourceMBB,MachineBasicBlock * TargetMBB)39434e66217SLei Huang void PPCBranchCoalescing::moveAndUpdatePHIs(MachineBasicBlock *SourceMBB,
39534e66217SLei Huang                                          MachineBasicBlock *TargetMBB) {
39634e66217SLei Huang 
39734e66217SLei Huang   MachineBasicBlock::iterator MI = SourceMBB->begin();
39834e66217SLei Huang   MachineBasicBlock::iterator ME = SourceMBB->getFirstNonPHI();
39934e66217SLei Huang 
40034e66217SLei Huang   if (MI == ME) {
401d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "SourceMBB contains no PHI instructions.\n");
40234e66217SLei Huang     return;
40334e66217SLei Huang   }
40434e66217SLei Huang 
40534e66217SLei Huang   // Update all PHI instructions in SourceMBB and move to top of TargetMBB
40634e66217SLei Huang   for (MachineBasicBlock::iterator Iter = MI; Iter != ME; Iter++) {
40734e66217SLei Huang     MachineInstr &PHIInst = *Iter;
40834e66217SLei Huang     for (unsigned i = 2, e = PHIInst.getNumOperands() + 1; i != e; i += 2) {
40934e66217SLei Huang       MachineOperand &MO = PHIInst.getOperand(i);
41034e66217SLei Huang       if (MO.getMBB() == SourceMBB)
41134e66217SLei Huang         MO.setMBB(TargetMBB);
41234e66217SLei Huang     }
41334e66217SLei Huang   }
41434e66217SLei Huang   TargetMBB->splice(TargetMBB->begin(), SourceMBB, MI, ME);
41534e66217SLei Huang }
41634e66217SLei Huang 
41734e66217SLei Huang ///
41834e66217SLei Huang /// This function checks if MI can be moved to the beginning of the TargetMBB
41934e66217SLei Huang /// following PHI instructions. A MI instruction can be moved to beginning of
42034e66217SLei Huang /// the TargetMBB if there are no uses of it within the TargetMBB PHI nodes.
42134e66217SLei Huang ///
42234e66217SLei Huang /// \param[in] MI the machine instruction to move.
42334e66217SLei Huang /// \param[in] TargetMBB the machine basic block to move to
42434e66217SLei Huang /// \return true if it is safe to move MI to beginning of TargetMBB,
42534e66217SLei Huang ///         false otherwise.
42634e66217SLei Huang ///
canMoveToBeginning(const MachineInstr & MI,const MachineBasicBlock & TargetMBB) const42734e66217SLei Huang bool PPCBranchCoalescing::canMoveToBeginning(const MachineInstr &MI,
42834e66217SLei Huang                                           const MachineBasicBlock &TargetMBB
42934e66217SLei Huang                                           ) const {
43034e66217SLei Huang 
431d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Checking if " << MI << " can move to beginning of "
43234e66217SLei Huang                     << TargetMBB.getNumber() << "\n");
43334e66217SLei Huang 
43434e66217SLei Huang   for (auto &Def : MI.defs()) { // Looking at Def
43534e66217SLei Huang     for (auto &Use : MRI->use_instructions(Def.getReg())) {
43634e66217SLei Huang       if (Use.isPHI() && Use.getParent() == &TargetMBB) {
437d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "    *** used in a PHI -- cannot move ***\n");
43834e66217SLei Huang         return false;
43934e66217SLei Huang       }
44034e66217SLei Huang     }
44134e66217SLei Huang   }
44234e66217SLei Huang 
443d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Safe to move to the beginning.\n");
44434e66217SLei Huang   return true;
44534e66217SLei Huang }
44634e66217SLei Huang 
44734e66217SLei Huang ///
44834e66217SLei Huang /// This function checks if MI can be moved to the end of the TargetMBB,
44934e66217SLei Huang /// immediately before the first terminator.  A MI instruction can be moved
45034e66217SLei Huang /// to then end of the TargetMBB if no PHI node defines what MI uses within
45134e66217SLei Huang /// it's own MBB.
45234e66217SLei Huang ///
45334e66217SLei Huang /// \param[in] MI the machine instruction to move.
45434e66217SLei Huang /// \param[in] TargetMBB the machine basic block to move to
45534e66217SLei Huang /// \return true if it is safe to move MI to end of TargetMBB,
45634e66217SLei Huang ///         false otherwise.
45734e66217SLei Huang ///
canMoveToEnd(const MachineInstr & MI,const MachineBasicBlock & TargetMBB) const45834e66217SLei Huang bool PPCBranchCoalescing::canMoveToEnd(const MachineInstr &MI,
45934e66217SLei Huang                                     const MachineBasicBlock &TargetMBB
46034e66217SLei Huang                                     ) const {
46134e66217SLei Huang 
462d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Checking if " << MI << " can move to end of "
46334e66217SLei Huang                     << TargetMBB.getNumber() << "\n");
46434e66217SLei Huang 
46534e66217SLei Huang   for (auto &Use : MI.uses()) {
4662bea69bfSDaniel Sanders     if (Use.isReg() && Register::isVirtualRegister(Use.getReg())) {
46734e66217SLei Huang       MachineInstr *DefInst = MRI->getVRegDef(Use.getReg());
46834e66217SLei Huang       if (DefInst->isPHI() && DefInst->getParent() == MI.getParent()) {
469d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "    *** Cannot move this instruction ***\n");
47034e66217SLei Huang         return false;
47134e66217SLei Huang       } else {
472d34e60caSNicola Zaghen         LLVM_DEBUG(
473d34e60caSNicola Zaghen             dbgs() << "    *** def is in another block -- safe to move!\n");
47434e66217SLei Huang       }
47534e66217SLei Huang     }
47634e66217SLei Huang   }
47734e66217SLei Huang 
478d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "  Safe to move to the end.\n");
47934e66217SLei Huang   return true;
48034e66217SLei Huang }
48134e66217SLei Huang 
48234e66217SLei Huang ///
48334e66217SLei Huang /// This method checks to ensure the two coalescing candidates follows the
48434e66217SLei Huang /// expected pattern required for coalescing.
48534e66217SLei Huang ///
48634e66217SLei Huang /// \param[in] SourceRegion The candidate to move statements from
48734e66217SLei Huang /// \param[in] TargetRegion The candidate to move statements to
48834e66217SLei Huang /// \return true if all instructions in SourceRegion.BranchBlock can be merged
48934e66217SLei Huang /// into a block in TargetRegion; false otherwise.
49034e66217SLei Huang ///
validateCandidates(CoalescingCandidateInfo & SourceRegion,CoalescingCandidateInfo & TargetRegion) const49134e66217SLei Huang bool PPCBranchCoalescing::validateCandidates(
49234e66217SLei Huang     CoalescingCandidateInfo &SourceRegion,
49334e66217SLei Huang     CoalescingCandidateInfo &TargetRegion) const {
49434e66217SLei Huang 
49534e66217SLei Huang   if (TargetRegion.BranchTargetBlock != SourceRegion.BranchBlock)
49634e66217SLei Huang     llvm_unreachable("Expecting SourceRegion to immediately follow TargetRegion");
49734e66217SLei Huang   else if (!MDT->dominates(TargetRegion.BranchBlock, SourceRegion.BranchBlock))
49834e66217SLei Huang     llvm_unreachable("Expecting TargetRegion to dominate SourceRegion");
49934e66217SLei Huang   else if (!MPDT->dominates(SourceRegion.BranchBlock, TargetRegion.BranchBlock))
50034e66217SLei Huang     llvm_unreachable("Expecting SourceRegion to post-dominate TargetRegion");
50134e66217SLei Huang   else if (!TargetRegion.FallThroughBlock->empty() ||
50234e66217SLei Huang            !SourceRegion.FallThroughBlock->empty())
50334e66217SLei Huang     llvm_unreachable("Expecting fall-through blocks to be empty");
50434e66217SLei Huang 
50534e66217SLei Huang   return true;
50634e66217SLei Huang }
50734e66217SLei Huang 
50834e66217SLei Huang ///
50934e66217SLei Huang /// This method determines whether the two coalescing candidates can be merged.
51034e66217SLei Huang /// In order to be merged, all instructions must be able to
51134e66217SLei Huang ///   1. Move to the beginning of the SourceRegion.BranchTargetBlock;
51234e66217SLei Huang ///   2. Move to the end of the TargetRegion.BranchBlock.
51334e66217SLei Huang /// Merging involves moving the instructions in the
51434e66217SLei Huang /// TargetRegion.BranchTargetBlock (also SourceRegion.BranchBlock).
51534e66217SLei Huang ///
51634e66217SLei Huang /// This function first try to move instructions from the
51734e66217SLei Huang /// TargetRegion.BranchTargetBlock down, to the beginning of the
51834e66217SLei Huang /// SourceRegion.BranchTargetBlock. This is not possible if any register defined
51934e66217SLei Huang /// in TargetRegion.BranchTargetBlock is used in a PHI node in the
52034e66217SLei Huang /// SourceRegion.BranchTargetBlock. In this case, check whether the statement
52134e66217SLei Huang /// can be moved up, to the end of the TargetRegion.BranchBlock (immediately
52234e66217SLei Huang /// before the branch statement). If it cannot move, then these blocks cannot
52334e66217SLei Huang /// be merged.
52434e66217SLei Huang ///
52534e66217SLei Huang /// Note that there is no analysis for moving instructions past the fall-through
52634e66217SLei Huang /// blocks because they are confirmed to be empty. An assert is thrown if they
52734e66217SLei Huang /// are not.
52834e66217SLei Huang ///
52934e66217SLei Huang /// \param[in] SourceRegion The candidate to move statements from
53034e66217SLei Huang /// \param[in] TargetRegion The candidate to move statements to
53134e66217SLei Huang /// \return true if all instructions in SourceRegion.BranchBlock can be merged
53234e66217SLei Huang ///         into a block in TargetRegion, false otherwise.
53334e66217SLei Huang ///
canMerge(CoalescingCandidateInfo & SourceRegion,CoalescingCandidateInfo & TargetRegion) const53434e66217SLei Huang bool PPCBranchCoalescing::canMerge(CoalescingCandidateInfo &SourceRegion,
53534e66217SLei Huang                                 CoalescingCandidateInfo &TargetRegion) const {
53634e66217SLei Huang   if (!validateCandidates(SourceRegion, TargetRegion))
53734e66217SLei Huang     return false;
53834e66217SLei Huang 
53934e66217SLei Huang   // Walk through PHI nodes first and see if they force the merge into the
54034e66217SLei Huang   // SourceRegion.BranchTargetBlock.
54134e66217SLei Huang   for (MachineBasicBlock::iterator
54234e66217SLei Huang            I = SourceRegion.BranchBlock->instr_begin(),
54334e66217SLei Huang            E = SourceRegion.BranchBlock->getFirstNonPHI();
54434e66217SLei Huang        I != E; ++I) {
54534e66217SLei Huang     for (auto &Def : I->defs())
54634e66217SLei Huang       for (auto &Use : MRI->use_instructions(Def.getReg())) {
54734e66217SLei Huang         if (Use.isPHI() && Use.getParent() == SourceRegion.BranchTargetBlock) {
548d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs()
549d34e60caSNicola Zaghen                      << "PHI " << *I
550d34e60caSNicola Zaghen                      << " defines register used in another "
55134e66217SLei Huang                         "PHI within branch target block -- can't merge\n");
55234e66217SLei Huang           NumPHINotMoved++;
55334e66217SLei Huang           return false;
55434e66217SLei Huang         }
55534e66217SLei Huang         if (Use.getParent() == SourceRegion.BranchBlock) {
556d34e60caSNicola Zaghen           LLVM_DEBUG(dbgs() << "PHI " << *I
55734e66217SLei Huang                             << " defines register used in this "
55834e66217SLei Huang                                "block -- all must move down\n");
55934e66217SLei Huang           SourceRegion.MustMoveDown = true;
56034e66217SLei Huang         }
56134e66217SLei Huang       }
56234e66217SLei Huang   }
56334e66217SLei Huang 
56434e66217SLei Huang   // Walk through the MI to see if they should be merged into
56534e66217SLei Huang   // TargetRegion.BranchBlock (up) or SourceRegion.BranchTargetBlock (down)
56634e66217SLei Huang   for (MachineBasicBlock::iterator
56734e66217SLei Huang            I = SourceRegion.BranchBlock->getFirstNonPHI(),
56834e66217SLei Huang            E = SourceRegion.BranchBlock->end();
56934e66217SLei Huang        I != E; ++I) {
57034e66217SLei Huang     if (!canMoveToBeginning(*I, *SourceRegion.BranchTargetBlock)) {
571d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Instruction " << *I
57234e66217SLei Huang                         << " cannot move down - must move up!\n");
57334e66217SLei Huang       SourceRegion.MustMoveUp = true;
57434e66217SLei Huang     }
57534e66217SLei Huang     if (!canMoveToEnd(*I, *TargetRegion.BranchBlock)) {
576d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Instruction " << *I
57734e66217SLei Huang                         << " cannot move up - must move down!\n");
57834e66217SLei Huang       SourceRegion.MustMoveDown = true;
57934e66217SLei Huang     }
58034e66217SLei Huang   }
58134e66217SLei Huang 
58234e66217SLei Huang   return (SourceRegion.MustMoveUp && SourceRegion.MustMoveDown) ? false : true;
58334e66217SLei Huang }
58434e66217SLei Huang 
58534e66217SLei Huang /// Merge the instructions from SourceRegion.BranchBlock,
58634e66217SLei Huang /// SourceRegion.BranchTargetBlock, and SourceRegion.FallThroughBlock into
58734e66217SLei Huang /// TargetRegion.BranchBlock, TargetRegion.BranchTargetBlock and
58834e66217SLei Huang /// TargetRegion.FallThroughBlock respectively.
58934e66217SLei Huang ///
59034e66217SLei Huang /// The successors for blocks in TargetRegion will be updated to use the
59134e66217SLei Huang /// successors from blocks in SourceRegion. Finally, the blocks in SourceRegion
59234e66217SLei Huang /// will be removed from the function.
59334e66217SLei Huang ///
59434e66217SLei Huang /// A region consists of a BranchBlock, a FallThroughBlock, and a
59534e66217SLei Huang /// BranchTargetBlock. Branch coalesce works on patterns where the
59634e66217SLei Huang /// TargetRegion's BranchTargetBlock must also be the SourceRegions's
59734e66217SLei Huang /// BranchBlock.
59834e66217SLei Huang ///
59934e66217SLei Huang ///  Before mergeCandidates:
60034e66217SLei Huang ///
60134e66217SLei Huang ///  +---------------------------+
60234e66217SLei Huang ///  |  TargetRegion.BranchBlock |
60334e66217SLei Huang ///  +---------------------------+
60434e66217SLei Huang ///     /        |
60534e66217SLei Huang ///    /   +--------------------------------+
60634e66217SLei Huang ///   |    |  TargetRegion.FallThroughBlock |
60734e66217SLei Huang ///    \   +--------------------------------+
60834e66217SLei Huang ///     \        |
60934e66217SLei Huang ///  +----------------------------------+
61034e66217SLei Huang ///  |  TargetRegion.BranchTargetBlock  |
61134e66217SLei Huang ///  |  SourceRegion.BranchBlock        |
61234e66217SLei Huang ///  +----------------------------------+
61334e66217SLei Huang ///     /        |
61434e66217SLei Huang ///    /   +--------------------------------+
61534e66217SLei Huang ///   |    |  SourceRegion.FallThroughBlock |
61634e66217SLei Huang ///    \   +--------------------------------+
61734e66217SLei Huang ///     \        |
61834e66217SLei Huang ///  +----------------------------------+
61934e66217SLei Huang ///  |  SourceRegion.BranchTargetBlock  |
62034e66217SLei Huang ///  +----------------------------------+
62134e66217SLei Huang ///
62234e66217SLei Huang ///  After mergeCandidates:
62334e66217SLei Huang ///
62434e66217SLei Huang ///  +-----------------------------+
62534e66217SLei Huang ///  |  TargetRegion.BranchBlock   |
62634e66217SLei Huang ///  |  SourceRegion.BranchBlock   |
62734e66217SLei Huang ///  +-----------------------------+
62834e66217SLei Huang ///     /        |
62934e66217SLei Huang ///    /   +---------------------------------+
63034e66217SLei Huang ///   |    |  TargetRegion.FallThroughBlock  |
63134e66217SLei Huang ///   |    |  SourceRegion.FallThroughBlock  |
63234e66217SLei Huang ///    \   +---------------------------------+
63334e66217SLei Huang ///     \        |
63434e66217SLei Huang ///  +----------------------------------+
63534e66217SLei Huang ///  |  SourceRegion.BranchTargetBlock  |
63634e66217SLei Huang ///  +----------------------------------+
63734e66217SLei Huang ///
63834e66217SLei Huang /// \param[in] SourceRegion The candidate to move blocks from
63934e66217SLei Huang /// \param[in] TargetRegion The candidate to move blocks to
64034e66217SLei Huang ///
mergeCandidates(CoalescingCandidateInfo & SourceRegion,CoalescingCandidateInfo & TargetRegion)64134e66217SLei Huang bool PPCBranchCoalescing::mergeCandidates(CoalescingCandidateInfo &SourceRegion,
64234e66217SLei Huang                                        CoalescingCandidateInfo &TargetRegion) {
64334e66217SLei Huang 
64434e66217SLei Huang   if (SourceRegion.MustMoveUp && SourceRegion.MustMoveDown) {
64534e66217SLei Huang     llvm_unreachable("Cannot have both MustMoveDown and MustMoveUp set!");
64634e66217SLei Huang     return false;
64734e66217SLei Huang   }
64834e66217SLei Huang 
64934e66217SLei Huang   if (!validateCandidates(SourceRegion, TargetRegion))
65034e66217SLei Huang     return false;
65134e66217SLei Huang 
65234e66217SLei Huang   // Start the merging process by first handling the BranchBlock.
65334e66217SLei Huang   // Move any PHIs in SourceRegion.BranchBlock down to the branch-taken block
65434e66217SLei Huang   moveAndUpdatePHIs(SourceRegion.BranchBlock, SourceRegion.BranchTargetBlock);
65534e66217SLei Huang 
65634e66217SLei Huang   // Move remaining instructions in SourceRegion.BranchBlock into
65734e66217SLei Huang   // TargetRegion.BranchBlock
65834e66217SLei Huang   MachineBasicBlock::iterator firstInstr =
65934e66217SLei Huang       SourceRegion.BranchBlock->getFirstNonPHI();
66034e66217SLei Huang   MachineBasicBlock::iterator lastInstr =
66134e66217SLei Huang       SourceRegion.BranchBlock->getFirstTerminator();
66234e66217SLei Huang 
66334e66217SLei Huang   MachineBasicBlock *Source = SourceRegion.MustMoveDown
66434e66217SLei Huang                                   ? SourceRegion.BranchTargetBlock
66534e66217SLei Huang                                   : TargetRegion.BranchBlock;
66634e66217SLei Huang 
66734e66217SLei Huang   MachineBasicBlock::iterator Target =
66834e66217SLei Huang       SourceRegion.MustMoveDown
66934e66217SLei Huang           ? SourceRegion.BranchTargetBlock->getFirstNonPHI()
67034e66217SLei Huang           : TargetRegion.BranchBlock->getFirstTerminator();
67134e66217SLei Huang 
67234e66217SLei Huang   Source->splice(Target, SourceRegion.BranchBlock, firstInstr, lastInstr);
67334e66217SLei Huang 
67434e66217SLei Huang   // Once PHI and instructions have been moved we need to clean up the
67534e66217SLei Huang   // control flow.
67634e66217SLei Huang 
67734e66217SLei Huang   // Remove SourceRegion.FallThroughBlock before transferring successors of
67834e66217SLei Huang   // SourceRegion.BranchBlock to TargetRegion.BranchBlock.
67934e66217SLei Huang   SourceRegion.BranchBlock->removeSuccessor(SourceRegion.FallThroughBlock);
68034e66217SLei Huang   TargetRegion.BranchBlock->transferSuccessorsAndUpdatePHIs(
68134e66217SLei Huang       SourceRegion.BranchBlock);
68234e66217SLei Huang   // Update branch in TargetRegion.BranchBlock to jump to
68334e66217SLei Huang   // SourceRegion.BranchTargetBlock
68434e66217SLei Huang   // In this case, TargetRegion.BranchTargetBlock == SourceRegion.BranchBlock.
68534e66217SLei Huang   TargetRegion.BranchBlock->ReplaceUsesOfBlockWith(
68634e66217SLei Huang       SourceRegion.BranchBlock, SourceRegion.BranchTargetBlock);
68734e66217SLei Huang   // Remove the branch statement(s) in SourceRegion.BranchBlock
68834e66217SLei Huang   MachineBasicBlock::iterator I =
68934e66217SLei Huang       SourceRegion.BranchBlock->terminators().begin();
69034e66217SLei Huang   while (I != SourceRegion.BranchBlock->terminators().end()) {
69134e66217SLei Huang     MachineInstr &CurrInst = *I;
69234e66217SLei Huang     ++I;
69334e66217SLei Huang     if (CurrInst.isBranch())
69434e66217SLei Huang       CurrInst.eraseFromParent();
69534e66217SLei Huang   }
69634e66217SLei Huang 
69734e66217SLei Huang   // Fall-through block should be empty since this is part of the condition
69834e66217SLei Huang   // to coalesce the branches.
69934e66217SLei Huang   assert(TargetRegion.FallThroughBlock->empty() &&
70034e66217SLei Huang          "FallThroughBlocks should be empty!");
70134e66217SLei Huang 
70234e66217SLei Huang   // Transfer successor information and move PHIs down to the
70334e66217SLei Huang   // branch-taken block.
70434e66217SLei Huang   TargetRegion.FallThroughBlock->transferSuccessorsAndUpdatePHIs(
70534e66217SLei Huang       SourceRegion.FallThroughBlock);
70634e66217SLei Huang   TargetRegion.FallThroughBlock->removeSuccessor(SourceRegion.BranchBlock);
70734e66217SLei Huang 
70834e66217SLei Huang   // Remove the blocks from the function.
70934e66217SLei Huang   assert(SourceRegion.BranchBlock->empty() &&
71034e66217SLei Huang          "Expecting branch block to be empty!");
71134e66217SLei Huang   SourceRegion.BranchBlock->eraseFromParent();
71234e66217SLei Huang 
71334e66217SLei Huang   assert(SourceRegion.FallThroughBlock->empty() &&
71434e66217SLei Huang          "Expecting fall-through block to be empty!\n");
71534e66217SLei Huang   SourceRegion.FallThroughBlock->eraseFromParent();
71634e66217SLei Huang 
71734e66217SLei Huang   NumBlocksCoalesced++;
71834e66217SLei Huang   return true;
71934e66217SLei Huang }
72034e66217SLei Huang 
runOnMachineFunction(MachineFunction & MF)72134e66217SLei Huang bool PPCBranchCoalescing::runOnMachineFunction(MachineFunction &MF) {
72234e66217SLei Huang 
723f1caa283SMatthias Braun   if (skipFunction(MF.getFunction()) || MF.empty())
72434e66217SLei Huang     return false;
72534e66217SLei Huang 
72634e66217SLei Huang   bool didSomething = false;
72734e66217SLei Huang 
728d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "******** Branch Coalescing ********\n");
72934e66217SLei Huang   initialize(MF);
73034e66217SLei Huang 
731d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Function: "; MF.dump(); dbgs() << "\n");
73234e66217SLei Huang 
73334e66217SLei Huang   CoalescingCandidateInfo Cand1, Cand2;
73434e66217SLei Huang   // Walk over blocks and find candidates to merge
73534e66217SLei Huang   // Continue trying to merge with the first candidate found, as long as merging
73634e66217SLei Huang   // is successfull.
73734e66217SLei Huang   for (MachineBasicBlock &MBB : MF) {
73834e66217SLei Huang     bool MergedCandidates = false;
73934e66217SLei Huang     do {
74034e66217SLei Huang       MergedCandidates = false;
74134e66217SLei Huang       Cand1.clear();
74234e66217SLei Huang       Cand2.clear();
74334e66217SLei Huang 
74434e66217SLei Huang       Cand1.BranchBlock = &MBB;
74534e66217SLei Huang 
74634e66217SLei Huang       // If unable to coalesce the branch, then continue to next block
74734e66217SLei Huang       if (!canCoalesceBranch(Cand1))
74834e66217SLei Huang         break;
74934e66217SLei Huang 
75034e66217SLei Huang       Cand2.BranchBlock = Cand1.BranchTargetBlock;
75134e66217SLei Huang       if (!canCoalesceBranch(Cand2))
75234e66217SLei Huang         break;
75334e66217SLei Huang 
75434e66217SLei Huang       // The branch-taken block of the second candidate should post-dominate the
755*e9163660SZarko Todorovski       // first candidate.
75634e66217SLei Huang       assert(MPDT->dominates(Cand2.BranchTargetBlock, Cand1.BranchBlock) &&
75734e66217SLei Huang              "Branch-taken block should post-dominate first candidate");
75834e66217SLei Huang 
75934e66217SLei Huang       if (!identicalOperands(Cand1.Cond, Cand2.Cond)) {
760d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Blocks " << Cand1.BranchBlock->getNumber()
761d34e60caSNicola Zaghen                           << " and " << Cand2.BranchBlock->getNumber()
76234e66217SLei Huang                           << " have different branches\n");
76334e66217SLei Huang         break;
76434e66217SLei Huang       }
76534e66217SLei Huang       if (!canMerge(Cand2, Cand1)) {
766d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Cannot merge blocks "
767d34e60caSNicola Zaghen                           << Cand1.BranchBlock->getNumber() << " and "
768d34e60caSNicola Zaghen                           << Cand2.BranchBlock->getNumber() << "\n");
76934e66217SLei Huang         NumBlocksNotCoalesced++;
77034e66217SLei Huang         continue;
77134e66217SLei Huang       }
772d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Merging blocks " << Cand1.BranchBlock->getNumber()
773d34e60caSNicola Zaghen                         << " and " << Cand1.BranchTargetBlock->getNumber()
774d34e60caSNicola Zaghen                         << "\n");
77534e66217SLei Huang       MergedCandidates = mergeCandidates(Cand2, Cand1);
77634e66217SLei Huang       if (MergedCandidates)
77734e66217SLei Huang         didSomething = true;
77834e66217SLei Huang 
779d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "Function after merging: "; MF.dump();
780d34e60caSNicola Zaghen                  dbgs() << "\n");
78134e66217SLei Huang     } while (MergedCandidates);
78234e66217SLei Huang   }
78334e66217SLei Huang 
78434e66217SLei Huang #ifndef NDEBUG
78534e66217SLei Huang   // Verify MF is still valid after branch coalescing
78634e66217SLei Huang   if (didSomething)
78734e66217SLei Huang     MF.verify(nullptr, "Error in code produced by branch coalescing");
78834e66217SLei Huang #endif // NDEBUG
78934e66217SLei Huang 
790d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Finished Branch Coalescing\n");
79134e66217SLei Huang   return didSomething;
79234e66217SLei Huang }
793