blob: 5e9a661f8f0b118a122683ac21628470b631b655 [file] [log] [blame]
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +00001//===-- CoalesceBranches.cpp - Coalesce blocks with the same condition ---===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +00006//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// Coalesce basic blocks guarded by the same branch condition into a single
11/// basic block.
12///
13//===----------------------------------------------------------------------===//
14
Lei Huang34e66212017-09-12 18:39:11 +000015#include "PPC.h"
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000016#include "llvm/ADT/BitVector.h"
17#include "llvm/ADT/Statistic.h"
18#include "llvm/CodeGen/MachineDominators.h"
19#include "llvm/CodeGen/MachineFunctionPass.h"
20#include "llvm/CodeGen/MachinePostDominators.h"
21#include "llvm/CodeGen/MachineRegisterInfo.h"
22#include "llvm/CodeGen/Passes.h"
David Blaikie1be62f02017-11-03 22:32:11 +000023#include "llvm/CodeGen/TargetFrameLowering.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000024#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000025#include "llvm/CodeGen/TargetSubtargetInfo.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000026#include "llvm/Support/Debug.h"
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000027
28using namespace llvm;
29
Lei Huang34e66212017-09-12 18:39:11 +000030#define DEBUG_TYPE "ppc-branch-coalescing"
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000031
32STATISTIC(NumBlocksCoalesced, "Number of blocks coalesced");
33STATISTIC(NumPHINotMoved, "Number of PHI Nodes that cannot be merged");
34STATISTIC(NumBlocksNotCoalesced, "Number of blocks not coalesced");
35
36//===----------------------------------------------------------------------===//
Lei Huang34e66212017-09-12 18:39:11 +000037// PPCBranchCoalescing
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000038//===----------------------------------------------------------------------===//
39///
40/// Improve scheduling by coalescing branches that depend on the same condition.
41/// This pass looks for blocks that are guarded by the same branch condition
42/// and attempts to merge the blocks together. Such opportunities arise from
43/// the expansion of select statements in the IR.
44///
Lei Huang34e66212017-09-12 18:39:11 +000045/// This pass does not handle implicit operands on branch statements. In order
46/// to run on targets that use implicit operands, changes need to be made in the
47/// canCoalesceBranch and canMerge methods.
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000048///
Lei Huang34e66212017-09-12 18:39:11 +000049/// Example: the following LLVM IR
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000050///
Lei Huang34e66212017-09-12 18:39:11 +000051/// %test = icmp eq i32 %x 0
52/// %tmp1 = select i1 %test, double %a, double 2.000000e-03
53/// %tmp2 = select i1 %test, double %b, double 5.000000e-03
54///
55/// expands to the following machine code:
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000056///
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +000057/// %bb.0: derived from LLVM BB %entry
Francis Visoiu Mistrihfb7b14f72018-02-09 01:14:44 +000058/// liveins: %f1 %f3 %x6
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000059/// <SNIP1>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +000060/// %0 = COPY %f1; F8RC:%0
61/// %5 = CMPLWI killed %4, 0; CRRC:%5 GPRC:%4
62/// %8 = LXSDX %zero8, killed %7, implicit %rm;
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +000063/// mem:LD8[ConstantPool] F8RC:%8 G8RC:%7
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +000064/// BCC 76, %5, <%bb.2>; CRRC:%5
65/// Successors according to CFG: %bb.1(?%) %bb.2(?%)
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000066///
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +000067/// %bb.1: derived from LLVM BB %entry
68/// Predecessors according to CFG: %bb.0
69/// Successors according to CFG: %bb.2(?%)
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000070///
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +000071/// %bb.2: derived from LLVM BB %entry
72/// Predecessors according to CFG: %bb.0 %bb.1
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +000073/// %9 = PHI %8, <%bb.1>, %0, <%bb.0>;
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +000074/// F8RC:%9,%8,%0
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000075/// <SNIP2>
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +000076/// BCC 76, %5, <%bb.4>; CRRC:%5
77/// Successors according to CFG: %bb.3(?%) %bb.4(?%)
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000078///
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +000079/// %bb.3: derived from LLVM BB %entry
80/// Predecessors according to CFG: %bb.2
81/// Successors according to CFG: %bb.4(?%)
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000082///
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +000083/// %bb.4: derived from LLVM BB %entry
84/// Predecessors according to CFG: %bb.2 %bb.3
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +000085/// %13 = PHI %12, <%bb.3>, %2, <%bb.2>;
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +000086/// F8RC:%13,%12,%2
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000087/// <SNIP3>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +000088/// BLR8 implicit %lr8, implicit %rm, implicit %f1
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000089///
90/// When this pattern is detected, branch coalescing will try to collapse
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +000091/// it by moving code in %bb.2 to %bb.0 and/or %bb.4 and removing %bb.3.
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000092///
93/// If all conditions are meet, IR should collapse to:
94///
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +000095/// %bb.0: derived from LLVM BB %entry
Francis Visoiu Mistrihfb7b14f72018-02-09 01:14:44 +000096/// liveins: %f1 %f3 %x6
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +000097/// <SNIP1>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +000098/// %0 = COPY %f1; F8RC:%0
99/// %5 = CMPLWI killed %4, 0; CRRC:%5 GPRC:%4
100/// %8 = LXSDX %zero8, killed %7, implicit %rm;
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +0000101/// mem:LD8[ConstantPool] F8RC:%8 G8RC:%7
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000102/// <SNIP2>
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000103/// BCC 76, %5, <%bb.4>; CRRC:%5
104/// Successors according to CFG: %bb.1(0x2aaaaaaa / 0x80000000 = 33.33%)
105/// %bb.4(0x55555554 / 0x80000000 = 66.67%)
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000106///
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000107/// %bb.1: derived from LLVM BB %entry
108/// Predecessors according to CFG: %bb.0
109/// Successors according to CFG: %bb.4(0x40000000 / 0x80000000 = 50.00%)
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000110///
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000111/// %bb.4: derived from LLVM BB %entry
112/// Predecessors according to CFG: %bb.0 %bb.1
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000113/// %9 = PHI %8, <%bb.1>, %0, <%bb.0>;
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +0000114/// F8RC:%9,%8,%0
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000115/// %13 = PHI %12, <%bb.1>, %2, <%bb.0>;
Francis Visoiu Mistrih93ef1452017-11-30 12:12:19 +0000116/// F8RC:%13,%12,%2
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000117/// <SNIP3>
Francis Visoiu Mistriha8a83d12017-12-07 10:40:31 +0000118/// BLR8 implicit %lr8, implicit %rm, implicit %f1
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000119///
120/// Branch Coalescing does not split blocks, it moves everything in the same
121/// direction ensuring it does not break use/definition semantics.
122///
123/// PHI nodes and its corresponding use instructions are moved to its successor
124/// block if there are no uses within the successor block PHI nodes. PHI
125/// node ordering cannot be assumed.
126///
127/// Non-PHI can be moved up to the predecessor basic block or down to the
128/// successor basic block following any PHI instructions. Whether it moves
129/// up or down depends on whether the register(s) defined in the instructions
130/// are used in current block or in any PHI instructions at the beginning of
131/// the successor block.
132
133namespace {
134
Lei Huang34e66212017-09-12 18:39:11 +0000135class PPCBranchCoalescing : public MachineFunctionPass {
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000136 struct CoalescingCandidateInfo {
Simon Pilgrimb01bb3a2017-03-03 12:09:11 +0000137 MachineBasicBlock *BranchBlock; // Block containing the branch
138 MachineBasicBlock *BranchTargetBlock; // Block branched to
139 MachineBasicBlock *FallThroughBlock; // Fall-through if branch not taken
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000140 SmallVector<MachineOperand, 4> Cond;
141 bool MustMoveDown;
142 bool MustMoveUp;
143
144 CoalescingCandidateInfo();
145 void clear();
146 };
147
148 MachineDominatorTree *MDT;
149 MachinePostDominatorTree *MPDT;
150 const TargetInstrInfo *TII;
151 MachineRegisterInfo *MRI;
152
153 void initialize(MachineFunction &F);
154 bool canCoalesceBranch(CoalescingCandidateInfo &Cand);
155 bool identicalOperands(ArrayRef<MachineOperand> OperandList1,
156 ArrayRef<MachineOperand> OperandList2) const;
157 bool validateCandidates(CoalescingCandidateInfo &SourceRegion,
158 CoalescingCandidateInfo &TargetRegion) const;
159
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000160public:
161 static char ID;
162
Lei Huang34e66212017-09-12 18:39:11 +0000163 PPCBranchCoalescing() : MachineFunctionPass(ID) {
164 initializePPCBranchCoalescingPass(*PassRegistry::getPassRegistry());
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000165 }
166
167 void getAnalysisUsage(AnalysisUsage &AU) const override {
168 AU.addRequired<MachineDominatorTree>();
169 AU.addRequired<MachinePostDominatorTree>();
170 MachineFunctionPass::getAnalysisUsage(AU);
171 }
172
173 StringRef getPassName() const override { return "Branch Coalescing"; }
174
175 bool mergeCandidates(CoalescingCandidateInfo &SourceRegion,
176 CoalescingCandidateInfo &TargetRegion);
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000177 bool canMoveToBeginning(const MachineInstr &MI,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000178 const MachineBasicBlock &MBB) const;
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000179 bool canMoveToEnd(const MachineInstr &MI,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000180 const MachineBasicBlock &MBB) const;
181 bool canMerge(CoalescingCandidateInfo &SourceRegion,
182 CoalescingCandidateInfo &TargetRegion) const;
183 void moveAndUpdatePHIs(MachineBasicBlock *SourceRegionMBB,
184 MachineBasicBlock *TargetRegionMBB);
185 bool runOnMachineFunction(MachineFunction &MF) override;
186};
187} // End anonymous namespace.
188
Lei Huang34e66212017-09-12 18:39:11 +0000189char PPCBranchCoalescing::ID = 0;
190/// createPPCBranchCoalescingPass - returns an instance of the Branch Coalescing
191/// Pass
192FunctionPass *llvm::createPPCBranchCoalescingPass() {
193 return new PPCBranchCoalescing();
194}
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000195
Lei Huang34e66212017-09-12 18:39:11 +0000196INITIALIZE_PASS_BEGIN(PPCBranchCoalescing, DEBUG_TYPE,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000197 "Branch Coalescing", false, false)
198INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
199INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTree)
Lei Huang34e66212017-09-12 18:39:11 +0000200INITIALIZE_PASS_END(PPCBranchCoalescing, DEBUG_TYPE, "Branch Coalescing",
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000201 false, false)
202
Lei Huang34e66212017-09-12 18:39:11 +0000203PPCBranchCoalescing::CoalescingCandidateInfo::CoalescingCandidateInfo()
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000204 : BranchBlock(nullptr), BranchTargetBlock(nullptr),
205 FallThroughBlock(nullptr), MustMoveDown(false), MustMoveUp(false) {}
206
Lei Huang34e66212017-09-12 18:39:11 +0000207void PPCBranchCoalescing::CoalescingCandidateInfo::clear() {
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000208 BranchBlock = nullptr;
209 BranchTargetBlock = nullptr;
210 FallThroughBlock = nullptr;
211 Cond.clear();
212 MustMoveDown = false;
213 MustMoveUp = false;
214}
215
Lei Huang34e66212017-09-12 18:39:11 +0000216void PPCBranchCoalescing::initialize(MachineFunction &MF) {
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000217 MDT = &getAnalysis<MachineDominatorTree>();
218 MPDT = &getAnalysis<MachinePostDominatorTree>();
219 TII = MF.getSubtarget().getInstrInfo();
220 MRI = &MF.getRegInfo();
221}
222
223///
224/// Analyze the branch statement to determine if it can be coalesced. This
225/// method analyses the branch statement for the given candidate to determine
226/// if it can be coalesced. If the branch can be coalesced, then the
227/// BranchTargetBlock and the FallThroughBlock are recorded in the specified
228/// Candidate.
229///
230///\param[in,out] Cand The coalescing candidate to analyze
231///\return true if and only if the branch can be coalesced, false otherwise
232///
Lei Huang34e66212017-09-12 18:39:11 +0000233bool PPCBranchCoalescing::canCoalesceBranch(CoalescingCandidateInfo &Cand) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000234 LLVM_DEBUG(dbgs() << "Determine if branch block "
235 << Cand.BranchBlock->getNumber() << " can be coalesced:");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000236 MachineBasicBlock *FalseMBB = nullptr;
237
238 if (TII->analyzeBranch(*Cand.BranchBlock, Cand.BranchTargetBlock, FalseMBB,
239 Cand.Cond)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000240 LLVM_DEBUG(dbgs() << "TII unable to Analyze Branch - skip\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000241 return false;
242 }
243
244 for (auto &I : Cand.BranchBlock->terminators()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000245 LLVM_DEBUG(dbgs() << "Looking at terminator : " << I << "\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000246 if (!I.isBranch())
247 continue;
248
Lei Huang34e66212017-09-12 18:39:11 +0000249 // The analyzeBranch method does not include any implicit operands.
250 // This is not an issue on PPC but must be handled on other targets.
251 // For this pass to be made target-independent, the analyzeBranch API
252 // need to be updated to support implicit operands and there would
253 // need to be a way to verify that any implicit operands would not be
254 // clobbered by merging blocks. This would include identifying the
255 // implicit operands as well as the basic block they are defined in.
256 // This could be done by changing the analyzeBranch API to have it also
257 // record and return the implicit operands and the blocks where they are
258 // defined. Alternatively, the BranchCoalescing code would need to be
259 // extended to identify the implicit operands. The analysis in canMerge
260 // must then be extended to prove that none of the implicit operands are
261 // changed in the blocks that are combined during coalescing.
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000262 if (I.getNumOperands() != I.getNumExplicitOperands()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000263 LLVM_DEBUG(dbgs() << "Terminator contains implicit operands - skip : "
264 << I << "\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000265 return false;
266 }
267 }
268
269 if (Cand.BranchBlock->isEHPad() || Cand.BranchBlock->hasEHPadSuccessor()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000270 LLVM_DEBUG(dbgs() << "EH Pad - skip\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000271 return false;
272 }
273
274 // For now only consider triangles (i.e, BranchTargetBlock is set,
275 // FalseMBB is null, and BranchTargetBlock is a successor to BranchBlock)
Simon Pilgrim83c37c42017-03-10 22:44:47 +0000276 if (!Cand.BranchTargetBlock || FalseMBB ||
277 !Cand.BranchBlock->isSuccessor(Cand.BranchTargetBlock)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000278 LLVM_DEBUG(dbgs() << "Does not form a triangle - skip\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000279 return false;
280 }
281
282 // Ensure there are only two successors
283 if (Cand.BranchBlock->succ_size() != 2) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000284 LLVM_DEBUG(dbgs() << "Does not have 2 successors - skip\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000285 return false;
286 }
287
288 // Sanity check - the block must be able to fall through
289 assert(Cand.BranchBlock->canFallThrough() &&
290 "Expecting the block to fall through!");
291
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000292 // We have already ensured there are exactly two successors to
293 // BranchBlock and that BranchTargetBlock is a successor to BranchBlock.
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000294 // Ensure the single fall though block is empty.
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000295 MachineBasicBlock *Succ =
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000296 (*Cand.BranchBlock->succ_begin() == Cand.BranchTargetBlock)
297 ? *Cand.BranchBlock->succ_rbegin()
298 : *Cand.BranchBlock->succ_begin();
299
300 assert(Succ && "Expecting a valid fall-through block\n");
301
302 if (!Succ->empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000303 LLVM_DEBUG(dbgs() << "Fall-through block contains code -- skip\n");
304 return false;
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000305 }
306
307 if (!Succ->isSuccessor(Cand.BranchTargetBlock)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000308 LLVM_DEBUG(
309 dbgs()
310 << "Successor of fall through block is not branch taken block\n");
311 return false;
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000312 }
313
314 Cand.FallThroughBlock = Succ;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000315 LLVM_DEBUG(dbgs() << "Valid Candidate\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000316 return true;
317}
318
319///
320/// Determine if the two operand lists are identical
321///
322/// \param[in] OpList1 operand list
323/// \param[in] OpList2 operand list
324/// \return true if and only if the operands lists are identical
325///
Lei Huang34e66212017-09-12 18:39:11 +0000326bool PPCBranchCoalescing::identicalOperands(
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000327 ArrayRef<MachineOperand> OpList1, ArrayRef<MachineOperand> OpList2) const {
328
329 if (OpList1.size() != OpList2.size()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000330 LLVM_DEBUG(dbgs() << "Operand list is different size\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000331 return false;
332 }
333
334 for (unsigned i = 0; i < OpList1.size(); ++i) {
335 const MachineOperand &Op1 = OpList1[i];
336 const MachineOperand &Op2 = OpList2[i];
337
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000338 LLVM_DEBUG(dbgs() << "Op1: " << Op1 << "\n"
339 << "Op2: " << Op2 << "\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000340
341 if (Op1.isIdenticalTo(Op2)) {
Lei Huang34e66212017-09-12 18:39:11 +0000342 // filter out instructions with physical-register uses
343 if (Op1.isReg() && TargetRegisterInfo::isPhysicalRegister(Op1.getReg())
344 // If the physical register is constant then we can assume the value
345 // has not changed between uses.
346 && !(Op1.isUse() && MRI->isConstantPhysReg(Op1.getReg()))) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000347 LLVM_DEBUG(dbgs() << "The operands are not provably identical.\n");
Lei Huang34e66212017-09-12 18:39:11 +0000348 return false;
349 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000350 LLVM_DEBUG(dbgs() << "Op1 and Op2 are identical!\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000351 continue;
352 }
353
354 // If the operands are not identical, but are registers, check to see if the
355 // definition of the register produces the same value. If they produce the
356 // same value, consider them to be identical.
357 if (Op1.isReg() && Op2.isReg() &&
358 TargetRegisterInfo::isVirtualRegister(Op1.getReg()) &&
359 TargetRegisterInfo::isVirtualRegister(Op2.getReg())) {
360 MachineInstr *Op1Def = MRI->getVRegDef(Op1.getReg());
361 MachineInstr *Op2Def = MRI->getVRegDef(Op2.getReg());
362 if (TII->produceSameValue(*Op1Def, *Op2Def, MRI)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000363 LLVM_DEBUG(dbgs() << "Op1Def: " << *Op1Def << " and " << *Op2Def
364 << " produce the same value!\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000365 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000366 LLVM_DEBUG(dbgs() << "Operands produce different values\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000367 return false;
368 }
369 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000370 LLVM_DEBUG(dbgs() << "The operands are not provably identical.\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000371 return false;
372 }
373 }
Lei Huang34e66212017-09-12 18:39:11 +0000374
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000375 return true;
376}
377
378///
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000379/// Moves ALL PHI instructions in SourceMBB to beginning of TargetMBB
380/// and update them to refer to the new block. PHI node ordering
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000381/// cannot be assumed so it does not matter where the PHI instructions
382/// are moved to in TargetMBB.
383///
384/// \param[in] SourceMBB block to move PHI instructions from
385/// \param[in] TargetMBB block to move PHI instructions to
386///
Lei Huang34e66212017-09-12 18:39:11 +0000387void PPCBranchCoalescing::moveAndUpdatePHIs(MachineBasicBlock *SourceMBB,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000388 MachineBasicBlock *TargetMBB) {
389
390 MachineBasicBlock::iterator MI = SourceMBB->begin();
391 MachineBasicBlock::iterator ME = SourceMBB->getFirstNonPHI();
392
393 if (MI == ME) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000394 LLVM_DEBUG(dbgs() << "SourceMBB contains no PHI instructions.\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000395 return;
396 }
397
398 // Update all PHI instructions in SourceMBB and move to top of TargetMBB
399 for (MachineBasicBlock::iterator Iter = MI; Iter != ME; Iter++) {
400 MachineInstr &PHIInst = *Iter;
401 for (unsigned i = 2, e = PHIInst.getNumOperands() + 1; i != e; i += 2) {
402 MachineOperand &MO = PHIInst.getOperand(i);
403 if (MO.getMBB() == SourceMBB)
404 MO.setMBB(TargetMBB);
405 }
406 }
407 TargetMBB->splice(TargetMBB->begin(), SourceMBB, MI, ME);
408}
409
410///
411/// This function checks if MI can be moved to the beginning of the TargetMBB
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000412/// following PHI instructions. A MI instruction can be moved to beginning of
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000413/// the TargetMBB if there are no uses of it within the TargetMBB PHI nodes.
414///
415/// \param[in] MI the machine instruction to move.
Simon Pilgrim7b227fe2017-03-02 18:59:07 +0000416/// \param[in] TargetMBB the machine basic block to move to
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000417/// \return true if it is safe to move MI to beginning of TargetMBB,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000418/// false otherwise.
419///
Lei Huang34e66212017-09-12 18:39:11 +0000420bool PPCBranchCoalescing::canMoveToBeginning(const MachineInstr &MI,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000421 const MachineBasicBlock &TargetMBB
422 ) const {
423
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000424 LLVM_DEBUG(dbgs() << "Checking if " << MI << " can move to beginning of "
425 << TargetMBB.getNumber() << "\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000426
427 for (auto &Def : MI.defs()) { // Looking at Def
428 for (auto &Use : MRI->use_instructions(Def.getReg())) {
429 if (Use.isPHI() && Use.getParent() == &TargetMBB) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000430 LLVM_DEBUG(dbgs() << " *** used in a PHI -- cannot move ***\n");
431 return false;
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000432 }
433 }
434 }
435
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000436 LLVM_DEBUG(dbgs() << " Safe to move to the beginning.\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000437 return true;
438}
439
440///
441/// This function checks if MI can be moved to the end of the TargetMBB,
442/// immediately before the first terminator. A MI instruction can be moved
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000443/// to then end of the TargetMBB if no PHI node defines what MI uses within
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000444/// it's own MBB.
445///
446/// \param[in] MI the machine instruction to move.
Simon Pilgrim7b227fe2017-03-02 18:59:07 +0000447/// \param[in] TargetMBB the machine basic block to move to
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000448/// \return true if it is safe to move MI to end of TargetMBB,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000449/// false otherwise.
450///
Lei Huang34e66212017-09-12 18:39:11 +0000451bool PPCBranchCoalescing::canMoveToEnd(const MachineInstr &MI,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000452 const MachineBasicBlock &TargetMBB
453 ) const {
454
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000455 LLVM_DEBUG(dbgs() << "Checking if " << MI << " can move to end of "
456 << TargetMBB.getNumber() << "\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000457
458 for (auto &Use : MI.uses()) {
459 if (Use.isReg() && TargetRegisterInfo::isVirtualRegister(Use.getReg())) {
460 MachineInstr *DefInst = MRI->getVRegDef(Use.getReg());
461 if (DefInst->isPHI() && DefInst->getParent() == MI.getParent()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000462 LLVM_DEBUG(dbgs() << " *** Cannot move this instruction ***\n");
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000463 return false;
464 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000465 LLVM_DEBUG(
466 dbgs() << " *** def is in another block -- safe to move!\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000467 }
468 }
469 }
470
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000471 LLVM_DEBUG(dbgs() << " Safe to move to the end.\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000472 return true;
473}
474
475///
476/// This method checks to ensure the two coalescing candidates follows the
477/// expected pattern required for coalescing.
478///
479/// \param[in] SourceRegion The candidate to move statements from
480/// \param[in] TargetRegion The candidate to move statements to
481/// \return true if all instructions in SourceRegion.BranchBlock can be merged
482/// into a block in TargetRegion; false otherwise.
483///
Lei Huang34e66212017-09-12 18:39:11 +0000484bool PPCBranchCoalescing::validateCandidates(
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000485 CoalescingCandidateInfo &SourceRegion,
486 CoalescingCandidateInfo &TargetRegion) const {
487
488 if (TargetRegion.BranchTargetBlock != SourceRegion.BranchBlock)
489 llvm_unreachable("Expecting SourceRegion to immediately follow TargetRegion");
490 else if (!MDT->dominates(TargetRegion.BranchBlock, SourceRegion.BranchBlock))
491 llvm_unreachable("Expecting TargetRegion to dominate SourceRegion");
492 else if (!MPDT->dominates(SourceRegion.BranchBlock, TargetRegion.BranchBlock))
493 llvm_unreachable("Expecting SourceRegion to post-dominate TargetRegion");
494 else if (!TargetRegion.FallThroughBlock->empty() ||
495 !SourceRegion.FallThroughBlock->empty())
496 llvm_unreachable("Expecting fall-through blocks to be empty");
497
498 return true;
499}
500
501///
502/// This method determines whether the two coalescing candidates can be merged.
503/// In order to be merged, all instructions must be able to
504/// 1. Move to the beginning of the SourceRegion.BranchTargetBlock;
505/// 2. Move to the end of the TargetRegion.BranchBlock.
506/// Merging involves moving the instructions in the
507/// TargetRegion.BranchTargetBlock (also SourceRegion.BranchBlock).
508///
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000509/// This function first try to move instructions from the
510/// TargetRegion.BranchTargetBlock down, to the beginning of the
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000511/// SourceRegion.BranchTargetBlock. This is not possible if any register defined
512/// in TargetRegion.BranchTargetBlock is used in a PHI node in the
513/// SourceRegion.BranchTargetBlock. In this case, check whether the statement
514/// can be moved up, to the end of the TargetRegion.BranchBlock (immediately
515/// before the branch statement). If it cannot move, then these blocks cannot
516/// be merged.
517///
518/// Note that there is no analysis for moving instructions past the fall-through
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000519/// blocks because they are confirmed to be empty. An assert is thrown if they
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000520/// are not.
521///
522/// \param[in] SourceRegion The candidate to move statements from
523/// \param[in] TargetRegion The candidate to move statements to
524/// \return true if all instructions in SourceRegion.BranchBlock can be merged
525/// into a block in TargetRegion, false otherwise.
526///
Lei Huang34e66212017-09-12 18:39:11 +0000527bool PPCBranchCoalescing::canMerge(CoalescingCandidateInfo &SourceRegion,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000528 CoalescingCandidateInfo &TargetRegion) const {
529 if (!validateCandidates(SourceRegion, TargetRegion))
530 return false;
531
532 // Walk through PHI nodes first and see if they force the merge into the
533 // SourceRegion.BranchTargetBlock.
534 for (MachineBasicBlock::iterator
535 I = SourceRegion.BranchBlock->instr_begin(),
536 E = SourceRegion.BranchBlock->getFirstNonPHI();
537 I != E; ++I) {
538 for (auto &Def : I->defs())
539 for (auto &Use : MRI->use_instructions(Def.getReg())) {
540 if (Use.isPHI() && Use.getParent() == SourceRegion.BranchTargetBlock) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000541 LLVM_DEBUG(dbgs()
542 << "PHI " << *I
543 << " defines register used in another "
544 "PHI within branch target block -- can't merge\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000545 NumPHINotMoved++;
546 return false;
547 }
548 if (Use.getParent() == SourceRegion.BranchBlock) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000549 LLVM_DEBUG(dbgs() << "PHI " << *I
550 << " defines register used in this "
551 "block -- all must move down\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000552 SourceRegion.MustMoveDown = true;
553 }
554 }
555 }
556
557 // Walk through the MI to see if they should be merged into
558 // TargetRegion.BranchBlock (up) or SourceRegion.BranchTargetBlock (down)
559 for (MachineBasicBlock::iterator
560 I = SourceRegion.BranchBlock->getFirstNonPHI(),
561 E = SourceRegion.BranchBlock->end();
562 I != E; ++I) {
563 if (!canMoveToBeginning(*I, *SourceRegion.BranchTargetBlock)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000564 LLVM_DEBUG(dbgs() << "Instruction " << *I
565 << " cannot move down - must move up!\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000566 SourceRegion.MustMoveUp = true;
567 }
568 if (!canMoveToEnd(*I, *TargetRegion.BranchBlock)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000569 LLVM_DEBUG(dbgs() << "Instruction " << *I
570 << " cannot move up - must move down!\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000571 SourceRegion.MustMoveDown = true;
572 }
573 }
574
575 return (SourceRegion.MustMoveUp && SourceRegion.MustMoveDown) ? false : true;
576}
577
578/// Merge the instructions from SourceRegion.BranchBlock,
579/// SourceRegion.BranchTargetBlock, and SourceRegion.FallThroughBlock into
580/// TargetRegion.BranchBlock, TargetRegion.BranchTargetBlock and
581/// TargetRegion.FallThroughBlock respectively.
582///
583/// The successors for blocks in TargetRegion will be updated to use the
584/// successors from blocks in SourceRegion. Finally, the blocks in SourceRegion
585/// will be removed from the function.
586///
587/// A region consists of a BranchBlock, a FallThroughBlock, and a
588/// BranchTargetBlock. Branch coalesce works on patterns where the
589/// TargetRegion's BranchTargetBlock must also be the SourceRegions's
590/// BranchBlock.
591///
592/// Before mergeCandidates:
593///
594/// +---------------------------+
595/// | TargetRegion.BranchBlock |
596/// +---------------------------+
597/// / |
598/// / +--------------------------------+
599/// | | TargetRegion.FallThroughBlock |
600/// \ +--------------------------------+
601/// \ |
602/// +----------------------------------+
603/// | TargetRegion.BranchTargetBlock |
604/// | SourceRegion.BranchBlock |
605/// +----------------------------------+
606/// / |
607/// / +--------------------------------+
608/// | | SourceRegion.FallThroughBlock |
609/// \ +--------------------------------+
610/// \ |
611/// +----------------------------------+
612/// | SourceRegion.BranchTargetBlock |
613/// +----------------------------------+
614///
615/// After mergeCandidates:
616///
617/// +-----------------------------+
618/// | TargetRegion.BranchBlock |
619/// | SourceRegion.BranchBlock |
620/// +-----------------------------+
621/// / |
622/// / +---------------------------------+
623/// | | TargetRegion.FallThroughBlock |
624/// | | SourceRegion.FallThroughBlock |
625/// \ +---------------------------------+
626/// \ |
627/// +----------------------------------+
628/// | SourceRegion.BranchTargetBlock |
629/// +----------------------------------+
630///
631/// \param[in] SourceRegion The candidate to move blocks from
632/// \param[in] TargetRegion The candidate to move blocks to
633///
Lei Huang34e66212017-09-12 18:39:11 +0000634bool PPCBranchCoalescing::mergeCandidates(CoalescingCandidateInfo &SourceRegion,
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000635 CoalescingCandidateInfo &TargetRegion) {
636
637 if (SourceRegion.MustMoveUp && SourceRegion.MustMoveDown) {
638 llvm_unreachable("Cannot have both MustMoveDown and MustMoveUp set!");
639 return false;
640 }
641
642 if (!validateCandidates(SourceRegion, TargetRegion))
643 return false;
644
645 // Start the merging process by first handling the BranchBlock.
646 // Move any PHIs in SourceRegion.BranchBlock down to the branch-taken block
647 moveAndUpdatePHIs(SourceRegion.BranchBlock, SourceRegion.BranchTargetBlock);
648
649 // Move remaining instructions in SourceRegion.BranchBlock into
650 // TargetRegion.BranchBlock
651 MachineBasicBlock::iterator firstInstr =
652 SourceRegion.BranchBlock->getFirstNonPHI();
653 MachineBasicBlock::iterator lastInstr =
654 SourceRegion.BranchBlock->getFirstTerminator();
655
656 MachineBasicBlock *Source = SourceRegion.MustMoveDown
657 ? SourceRegion.BranchTargetBlock
658 : TargetRegion.BranchBlock;
659
660 MachineBasicBlock::iterator Target =
661 SourceRegion.MustMoveDown
662 ? SourceRegion.BranchTargetBlock->getFirstNonPHI()
663 : TargetRegion.BranchBlock->getFirstTerminator();
664
665 Source->splice(Target, SourceRegion.BranchBlock, firstInstr, lastInstr);
666
667 // Once PHI and instructions have been moved we need to clean up the
668 // control flow.
669
670 // Remove SourceRegion.FallThroughBlock before transferring successors of
671 // SourceRegion.BranchBlock to TargetRegion.BranchBlock.
672 SourceRegion.BranchBlock->removeSuccessor(SourceRegion.FallThroughBlock);
673 TargetRegion.BranchBlock->transferSuccessorsAndUpdatePHIs(
674 SourceRegion.BranchBlock);
675 // Update branch in TargetRegion.BranchBlock to jump to
676 // SourceRegion.BranchTargetBlock
677 // In this case, TargetRegion.BranchTargetBlock == SourceRegion.BranchBlock.
678 TargetRegion.BranchBlock->ReplaceUsesOfBlockWith(
679 SourceRegion.BranchBlock, SourceRegion.BranchTargetBlock);
680 // Remove the branch statement(s) in SourceRegion.BranchBlock
681 MachineBasicBlock::iterator I =
682 SourceRegion.BranchBlock->terminators().begin();
683 while (I != SourceRegion.BranchBlock->terminators().end()) {
684 MachineInstr &CurrInst = *I;
685 ++I;
686 if (CurrInst.isBranch())
687 CurrInst.eraseFromParent();
688 }
689
690 // Fall-through block should be empty since this is part of the condition
691 // to coalesce the branches.
692 assert(TargetRegion.FallThroughBlock->empty() &&
693 "FallThroughBlocks should be empty!");
694
Simon Pilgrim455e2f32017-03-10 22:53:19 +0000695 // Transfer successor information and move PHIs down to the
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000696 // branch-taken block.
697 TargetRegion.FallThroughBlock->transferSuccessorsAndUpdatePHIs(
698 SourceRegion.FallThroughBlock);
699 TargetRegion.FallThroughBlock->removeSuccessor(SourceRegion.BranchBlock);
700
701 // Remove the blocks from the function.
702 assert(SourceRegion.BranchBlock->empty() &&
703 "Expecting branch block to be empty!");
704 SourceRegion.BranchBlock->eraseFromParent();
705
706 assert(SourceRegion.FallThroughBlock->empty() &&
707 "Expecting fall-through block to be empty!\n");
708 SourceRegion.FallThroughBlock->eraseFromParent();
709
710 NumBlocksCoalesced++;
711 return true;
712}
713
Lei Huang34e66212017-09-12 18:39:11 +0000714bool PPCBranchCoalescing::runOnMachineFunction(MachineFunction &MF) {
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000715
Matthias Braunf1caa282017-12-15 22:22:58 +0000716 if (skipFunction(MF.getFunction()) || MF.empty())
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000717 return false;
718
719 bool didSomething = false;
720
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000721 LLVM_DEBUG(dbgs() << "******** Branch Coalescing ********\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000722 initialize(MF);
723
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000724 LLVM_DEBUG(dbgs() << "Function: "; MF.dump(); dbgs() << "\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000725
726 CoalescingCandidateInfo Cand1, Cand2;
727 // Walk over blocks and find candidates to merge
728 // Continue trying to merge with the first candidate found, as long as merging
729 // is successfull.
730 for (MachineBasicBlock &MBB : MF) {
731 bool MergedCandidates = false;
732 do {
733 MergedCandidates = false;
734 Cand1.clear();
735 Cand2.clear();
736
737 Cand1.BranchBlock = &MBB;
738
739 // If unable to coalesce the branch, then continue to next block
740 if (!canCoalesceBranch(Cand1))
741 break;
742
743 Cand2.BranchBlock = Cand1.BranchTargetBlock;
744 if (!canCoalesceBranch(Cand2))
745 break;
746
747 // Sanity check
748 // The branch-taken block of the second candidate should post-dominate the
749 // first candidate
750 assert(MPDT->dominates(Cand2.BranchTargetBlock, Cand1.BranchBlock) &&
751 "Branch-taken block should post-dominate first candidate");
752
753 if (!identicalOperands(Cand1.Cond, Cand2.Cond)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000754 LLVM_DEBUG(dbgs() << "Blocks " << Cand1.BranchBlock->getNumber()
755 << " and " << Cand2.BranchBlock->getNumber()
756 << " have different branches\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000757 break;
758 }
759 if (!canMerge(Cand2, Cand1)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000760 LLVM_DEBUG(dbgs() << "Cannot merge blocks "
761 << Cand1.BranchBlock->getNumber() << " and "
762 << Cand2.BranchBlock->getNumber() << "\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000763 NumBlocksNotCoalesced++;
764 continue;
765 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000766 LLVM_DEBUG(dbgs() << "Merging blocks " << Cand1.BranchBlock->getNumber()
767 << " and " << Cand1.BranchTargetBlock->getNumber()
768 << "\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000769 MergedCandidates = mergeCandidates(Cand2, Cand1);
770 if (MergedCandidates)
771 didSomething = true;
772
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000773 LLVM_DEBUG(dbgs() << "Function after merging: "; MF.dump();
774 dbgs() << "\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000775 } while (MergedCandidates);
776 }
777
778#ifndef NDEBUG
779 // Verify MF is still valid after branch coalescing
780 if (didSomething)
781 MF.verify(nullptr, "Error in code produced by branch coalescing");
782#endif // NDEBUG
783
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000784 LLVM_DEBUG(dbgs() << "Finished Branch Coalescing\n");
Nemanja Ivanovicb223cfa2017-03-01 20:29:34 +0000785 return didSomething;
786}