blob: f57f4a8e28109ae451dcc936e6164844eca0cece [file] [log] [blame]
Chris Lattner21ab22e2004-07-31 10:01:27 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
Misha Brukmanedf128a2005-04-21 22:36:52 +00002//
Chris Lattner21ab22e2004-07-31 10:01:27 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanedf128a2005-04-21 22:36:52 +00007//
Chris Lattner21ab22e2004-07-31 10:01:27 +00008//===----------------------------------------------------------------------===//
9//
10// This pass forwards branches to unconditional branches to make them branch
11// directly to the target block. This pass often results in dead MBB's, which
12// it then removes.
13//
14// Note that this pass must be run after register allocation, it cannot handle
15// SSA form.
16//
17//===----------------------------------------------------------------------===//
18
Chris Lattnerf10a56a2006-11-18 21:56:39 +000019#define DEBUG_TYPE "branchfolding"
Evan Cheng030a0a02009-09-04 07:47:40 +000020#include "BranchFolding.h"
Bob Wilson2c04dae2009-10-28 22:10:20 +000021#include "llvm/Function.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000022#include "llvm/CodeGen/Passes.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000023#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000024#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000025#include "llvm/CodeGen/MachineJumpTableInfo.h"
Dale Johannesen69cb9b72007-03-20 21:35:06 +000026#include "llvm/CodeGen/RegisterScavenging.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000027#include "llvm/Target/TargetInstrInfo.h"
28#include "llvm/Target/TargetMachine.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000029#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner12143052006-10-21 00:47:49 +000030#include "llvm/Support/CommandLine.h"
Chris Lattnerf10a56a2006-11-18 21:56:39 +000031#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Bill Wendling3403bcd2009-08-22 20:03:00 +000033#include "llvm/Support/raw_ostream.h"
Evan Cheng80b09fe2008-04-10 02:32:10 +000034#include "llvm/ADT/SmallSet.h"
Dan Gohman2210c0b2009-11-11 19:48:59 +000035#include "llvm/ADT/SetVector.h"
Chris Lattner12143052006-10-21 00:47:49 +000036#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000037#include "llvm/ADT/STLExtras.h"
Jeff Cohend41b30d2006-11-05 19:31:28 +000038#include <algorithm>
Chris Lattner21ab22e2004-07-31 10:01:27 +000039using namespace llvm;
40
Chris Lattnercd3245a2006-12-19 22:41:21 +000041STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
42STATISTIC(NumBranchOpts, "Number of branches optimized");
43STATISTIC(NumTailMerge , "Number of block tails merged");
Evan Chengcbc988b2011-05-12 00:56:58 +000044STATISTIC(NumHoist , "Number of times common instructions are hoisted");
Bob Wilson7cd5d3e2009-11-18 19:29:37 +000045
Dan Gohman4e3f1252009-11-11 18:38:14 +000046static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
Dale Johannesen81da02b2007-05-22 17:14:46 +000047 cl::init(cl::BOU_UNSET), cl::Hidden);
Bob Wilson7cd5d3e2009-11-18 19:29:37 +000048
Dan Gohman844731a2008-05-13 00:00:25 +000049// Throttle for huge numbers of predecessors (compile speed problems)
50static cl::opt<unsigned>
Dan Gohman4e3f1252009-11-11 18:38:14 +000051TailMergeThreshold("tail-merge-threshold",
Dan Gohman844731a2008-05-13 00:00:25 +000052 cl::desc("Max number of predecessors to consider tail merging"),
Dale Johannesen622addb2008-10-27 02:10:21 +000053 cl::init(150), cl::Hidden);
Dale Johannesen1a90a5a2007-06-08 01:08:52 +000054
Dan Gohman2210c0b2009-11-11 19:48:59 +000055// Heuristic for tail merging (and, inversely, tail duplication).
56// TODO: This should be replaced with a target query.
57static cl::opt<unsigned>
Bob Wilson3cbc3122009-11-16 17:56:13 +000058TailMergeSize("tail-merge-size",
Dan Gohman2210c0b2009-11-11 19:48:59 +000059 cl::desc("Min number of instructions to consider tail merging"),
60 cl::init(3), cl::Hidden);
Devang Patel794fd752007-05-01 21:15:47 +000061
Dan Gohman72b29902009-11-12 01:59:26 +000062namespace {
63 /// BranchFolderPass - Wrap branch folder in a machine function pass.
Andrew Trick61f1e3d2012-02-08 21:22:48 +000064 class BranchFolderPass : public MachineFunctionPass {
Dan Gohman72b29902009-11-12 01:59:26 +000065 public:
66 static char ID;
Andrew Trick61f1e3d2012-02-08 21:22:48 +000067 explicit BranchFolderPass(): MachineFunctionPass(ID) {}
Dan Gohman72b29902009-11-12 01:59:26 +000068
69 virtual bool runOnMachineFunction(MachineFunction &MF);
Andrew Trick61f1e3d2012-02-08 21:22:48 +000070
71 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 AU.addRequired<TargetPassConfig>();
73 MachineFunctionPass::getAnalysisUsage(AU);
74 }
Dan Gohman72b29902009-11-12 01:59:26 +000075 };
76}
77
Evan Cheng030a0a02009-09-04 07:47:40 +000078char BranchFolderPass::ID = 0;
Andrew Trick61f1e3d2012-02-08 21:22:48 +000079char &llvm::BranchFolderPassID = BranchFolderPass::ID;
Chris Lattner21ab22e2004-07-31 10:01:27 +000080
Andrew Trick61f1e3d2012-02-08 21:22:48 +000081INITIALIZE_PASS(BranchFolderPass, "branch-folder",
82 "Control Flow Optimizer", false, false)
Evan Cheng030a0a02009-09-04 07:47:40 +000083
84bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
Andrew Trick61f1e3d2012-02-08 21:22:48 +000085 TargetPassConfig *PassConfig = &getAnalysis<TargetPassConfig>();
86 BranchFolder Folder(PassConfig->getEnableTailMerge(), /*CommonHoist=*/true);
87 return Folder.OptimizeFunction(MF,
88 MF.getTarget().getInstrInfo(),
89 MF.getTarget().getRegisterInfo(),
90 getAnalysisIfAvailable<MachineModuleInfo>());
Evan Cheng030a0a02009-09-04 07:47:40 +000091}
92
93
Evan Chengcbc988b2011-05-12 00:56:58 +000094BranchFolder::BranchFolder(bool defaultEnableTailMerge, bool CommonHoist) {
Evan Cheng030a0a02009-09-04 07:47:40 +000095 switch (FlagEnableTailMerge) {
96 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
97 case cl::BOU_TRUE: EnableTailMerge = true; break;
98 case cl::BOU_FALSE: EnableTailMerge = false; break;
99 }
Evan Chengcbc988b2011-05-12 00:56:58 +0000100
101 EnableHoistCommonCode = CommonHoist;
Evan Chengb3c27422009-09-03 23:54:22 +0000102}
Chris Lattner21ab22e2004-07-31 10:01:27 +0000103
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000104/// RemoveDeadBlock - Remove the specified dead machine basic block from the
105/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +0000106void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +0000107 assert(MBB->pred_empty() && "MBB must be dead!");
David Greene465e2b92009-12-24 00:34:21 +0000108 DEBUG(dbgs() << "\nRemoving MBB: " << *MBB);
Dan Gohman4e3f1252009-11-11 18:38:14 +0000109
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000110 MachineFunction *MF = MBB->getParent();
111 // drop all successors.
112 while (!MBB->succ_empty())
113 MBB->removeSuccessor(MBB->succ_end()-1);
Dan Gohman4e3f1252009-11-11 18:38:14 +0000114
Rafael Espindolaf924dea2011-06-14 15:31:54 +0000115 // Avoid matching if this pointer gets reused.
116 TriedMerging.erase(MBB);
117
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000118 // Remove the block.
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000119 MF->erase(MBB);
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000120}
121
Evan Cheng80b09fe2008-04-10 02:32:10 +0000122/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
123/// followed by terminators, and if the implicitly defined registers are not
124/// used by the terminators, remove those implicit_def's. e.g.
125/// BB1:
126/// r0 = implicit_def
127/// r1 = implicit_def
128/// br
129/// This block can be optimized away later if the implicit instructions are
130/// removed.
131bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
132 SmallSet<unsigned, 4> ImpDefRegs;
133 MachineBasicBlock::iterator I = MBB->begin();
134 while (I != MBB->end()) {
Chris Lattner518bb532010-02-09 19:54:29 +0000135 if (!I->isImplicitDef())
Evan Cheng80b09fe2008-04-10 02:32:10 +0000136 break;
137 unsigned Reg = I->getOperand(0).getReg();
138 ImpDefRegs.insert(Reg);
Craig Topper9ebfbf82012-03-05 05:37:41 +0000139 for (const uint16_t *SubRegs = TRI->getSubRegisters(Reg);
Evan Cheng80b09fe2008-04-10 02:32:10 +0000140 unsigned SubReg = *SubRegs; ++SubRegs)
141 ImpDefRegs.insert(SubReg);
142 ++I;
143 }
144 if (ImpDefRegs.empty())
145 return false;
146
147 MachineBasicBlock::iterator FirstTerm = I;
148 while (I != MBB->end()) {
149 if (!TII->isUnpredicatedTerminator(I))
150 return false;
151 // See if it uses any of the implicitly defined registers.
152 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
153 MachineOperand &MO = I->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000154 if (!MO.isReg() || !MO.isUse())
Evan Cheng80b09fe2008-04-10 02:32:10 +0000155 continue;
156 unsigned Reg = MO.getReg();
157 if (ImpDefRegs.count(Reg))
158 return false;
159 }
160 ++I;
161 }
162
163 I = MBB->begin();
164 while (I != FirstTerm) {
165 MachineInstr *ImpDefMI = &*I;
166 ++I;
167 MBB->erase(ImpDefMI);
168 }
169
170 return true;
171}
172
Evan Cheng030a0a02009-09-04 07:47:40 +0000173/// OptimizeFunction - Perhaps branch folding, tail merging and other
174/// CFG optimizations on the given function.
175bool BranchFolder::OptimizeFunction(MachineFunction &MF,
176 const TargetInstrInfo *tii,
177 const TargetRegisterInfo *tri,
178 MachineModuleInfo *mmi) {
179 if (!tii) return false;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000180
Rafael Espindolaf924dea2011-06-14 15:31:54 +0000181 TriedMerging.clear();
182
Evan Cheng030a0a02009-09-04 07:47:40 +0000183 TII = tii;
184 TRI = tri;
185 MMI = mmi;
186
Evan Cheng70017fb2012-01-07 03:35:48 +0000187 RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
Evan Cheng80b09fe2008-04-10 02:32:10 +0000188
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000189 // Fix CFG. The later algorithms expect it to be right.
Evan Cheng030a0a02009-09-04 07:47:40 +0000190 bool MadeChange = false;
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000191 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
192 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000193 SmallVector<MachineOperand, 4> Cond;
Evan Chengdc54d312009-02-09 07:14:22 +0000194 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
Evan Cheng030a0a02009-09-04 07:47:40 +0000195 MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
196 MadeChange |= OptimizeImpDefsBlock(MBB);
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000197 }
198
Chris Lattner12143052006-10-21 00:47:49 +0000199 bool MadeChangeThisIteration = true;
200 while (MadeChangeThisIteration) {
Evan Chengcbc988b2011-05-12 00:56:58 +0000201 MadeChangeThisIteration = TailMergeBlocks(MF);
202 MadeChangeThisIteration |= OptimizeBranches(MF);
203 if (EnableHoistCommonCode)
204 MadeChangeThisIteration |= HoistCommonCode(MF);
Evan Cheng030a0a02009-09-04 07:47:40 +0000205 MadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000206 }
207
Bob Wilson80d23702010-03-19 19:05:41 +0000208 // See if any jump tables have become dead as the code generator
Chris Lattner6acfe122006-10-28 18:34:47 +0000209 // did its thing.
210 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
Chris Lattner071c62f2010-01-25 23:26:13 +0000211 if (JTI == 0) {
212 delete RS;
213 return MadeChange;
214 }
Andrew Trick1df91b02012-02-08 21:22:43 +0000215
Bob Wilson80d23702010-03-19 19:05:41 +0000216 // Walk the function to find jump tables that are live.
217 BitVector JTIsLive(JTI->getJumpTables().size());
Chris Lattner071c62f2010-01-25 23:26:13 +0000218 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
219 BB != E; ++BB) {
220 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
221 I != E; ++I)
222 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
223 MachineOperand &Op = I->getOperand(op);
224 if (!Op.isJTI()) continue;
Chris Lattner6acfe122006-10-28 18:34:47 +0000225
Chris Lattner071c62f2010-01-25 23:26:13 +0000226 // Remember that this JT is live.
Bob Wilson80d23702010-03-19 19:05:41 +0000227 JTIsLive.set(Op.getIndex());
Chris Lattner6acfe122006-10-28 18:34:47 +0000228 }
229 }
Evan Cheng030a0a02009-09-04 07:47:40 +0000230
Bob Wilson80d23702010-03-19 19:05:41 +0000231 // Finally, remove dead jump tables. This happens when the
232 // indirect jump was unreachable (and thus deleted).
Chris Lattner071c62f2010-01-25 23:26:13 +0000233 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
234 if (!JTIsLive.test(i)) {
235 JTI->RemoveJumpTable(i);
236 MadeChange = true;
237 }
238
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000239 delete RS;
Evan Cheng030a0a02009-09-04 07:47:40 +0000240 return MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000241}
242
Chris Lattner12143052006-10-21 00:47:49 +0000243//===----------------------------------------------------------------------===//
244// Tail Merging of Blocks
245//===----------------------------------------------------------------------===//
246
247/// HashMachineInstr - Compute a hash value for MI and its operands.
248static unsigned HashMachineInstr(const MachineInstr *MI) {
249 unsigned Hash = MI->getOpcode();
250 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
251 const MachineOperand &Op = MI->getOperand(i);
Dan Gohman4e3f1252009-11-11 18:38:14 +0000252
Chris Lattner12143052006-10-21 00:47:49 +0000253 // Merge in bits from the operand if easy.
254 unsigned OperandHash = 0;
255 switch (Op.getType()) {
256 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
257 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
258 case MachineOperand::MO_MachineBasicBlock:
Chris Lattner8aa797a2007-12-30 23:10:15 +0000259 OperandHash = Op.getMBB()->getNumber();
Chris Lattner12143052006-10-21 00:47:49 +0000260 break;
Chris Lattner8aa797a2007-12-30 23:10:15 +0000261 case MachineOperand::MO_FrameIndex:
Chris Lattner12143052006-10-21 00:47:49 +0000262 case MachineOperand::MO_ConstantPoolIndex:
Chris Lattner12143052006-10-21 00:47:49 +0000263 case MachineOperand::MO_JumpTableIndex:
Chris Lattner8aa797a2007-12-30 23:10:15 +0000264 OperandHash = Op.getIndex();
Chris Lattner12143052006-10-21 00:47:49 +0000265 break;
266 case MachineOperand::MO_GlobalAddress:
267 case MachineOperand::MO_ExternalSymbol:
268 // Global address / external symbol are too hard, don't bother, but do
269 // pull in the offset.
270 OperandHash = Op.getOffset();
271 break;
272 default: break;
273 }
Dan Gohman4e3f1252009-11-11 18:38:14 +0000274
Chris Lattner12143052006-10-21 00:47:49 +0000275 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
276 }
277 return Hash;
278}
279
Dan Gohman30fc5bb2010-05-03 14:35:47 +0000280/// HashEndOfMBB - Hash the last instruction in the MBB.
281static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
Chris Lattner12143052006-10-21 00:47:49 +0000282 MachineBasicBlock::const_iterator I = MBB->end();
283 if (I == MBB->begin())
284 return 0; // Empty MBB.
Dan Gohman4e3f1252009-11-11 18:38:14 +0000285
Chris Lattner12143052006-10-21 00:47:49 +0000286 --I;
Dale Johannesen84839da2010-03-08 05:38:13 +0000287 // Skip debug info so it will not affect codegen.
288 while (I->isDebugValue()) {
289 if (I==MBB->begin())
290 return 0; // MBB empty except for debug info.
291 --I;
292 }
Dan Gohman4e3f1252009-11-11 18:38:14 +0000293
Dan Gohman30fc5bb2010-05-03 14:35:47 +0000294 return HashMachineInstr(I);
Chris Lattner12143052006-10-21 00:47:49 +0000295}
296
297/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
298/// of instructions they actually have in common together at their end. Return
299/// iterators for the first shared instruction in each block.
300static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
301 MachineBasicBlock *MBB2,
302 MachineBasicBlock::iterator &I1,
303 MachineBasicBlock::iterator &I2) {
304 I1 = MBB1->end();
305 I2 = MBB2->end();
Dan Gohman4e3f1252009-11-11 18:38:14 +0000306
Chris Lattner12143052006-10-21 00:47:49 +0000307 unsigned TailLen = 0;
308 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
309 --I1; --I2;
Dale Johannesen84839da2010-03-08 05:38:13 +0000310 // Skip debugging pseudos; necessary to avoid changing the code.
311 while (I1->isDebugValue()) {
Dale Johannesenc5cf2272010-03-10 05:45:47 +0000312 if (I1==MBB1->begin()) {
313 while (I2->isDebugValue()) {
314 if (I2==MBB2->begin())
315 // I1==DBG at begin; I2==DBG at begin
316 return TailLen;
317 --I2;
318 }
319 ++I2;
320 // I1==DBG at begin; I2==non-DBG, or first of DBGs not at begin
Dale Johannesen84839da2010-03-08 05:38:13 +0000321 return TailLen;
Dale Johannesenc5cf2272010-03-10 05:45:47 +0000322 }
Dale Johannesen84839da2010-03-08 05:38:13 +0000323 --I1;
324 }
Dale Johannesenc5cf2272010-03-10 05:45:47 +0000325 // I1==first (untested) non-DBG preceding known match
Dale Johannesen84839da2010-03-08 05:38:13 +0000326 while (I2->isDebugValue()) {
Dale Johannesenc5cf2272010-03-10 05:45:47 +0000327 if (I2==MBB2->begin()) {
328 ++I1;
329 // I1==non-DBG, or first of DBGs not at begin; I2==DBG at begin
Dale Johannesen84839da2010-03-08 05:38:13 +0000330 return TailLen;
Dale Johannesenc5cf2272010-03-10 05:45:47 +0000331 }
Dale Johannesen84839da2010-03-08 05:38:13 +0000332 --I2;
333 }
Dale Johannesenc5cf2272010-03-10 05:45:47 +0000334 // I1, I2==first (untested) non-DBGs preceding known match
Dale Johannesen84839da2010-03-08 05:38:13 +0000335 if (!I1->isIdenticalTo(I2) ||
Bill Wendlingda6efc52007-10-25 19:49:32 +0000336 // FIXME: This check is dubious. It's used to get around a problem where
Bill Wendling0713a222007-10-25 18:23:45 +0000337 // people incorrectly expect inline asm directives to remain in the same
338 // relative order. This is untenable because normal compiler
339 // optimizations (like this one) may reorder and/or merge these
340 // directives.
Chris Lattner518bb532010-02-09 19:54:29 +0000341 I1->isInlineAsm()) {
Chris Lattner12143052006-10-21 00:47:49 +0000342 ++I1; ++I2;
343 break;
344 }
345 ++TailLen;
346 }
Dale Johannesenc5cf2272010-03-10 05:45:47 +0000347 // Back past possible debugging pseudos at beginning of block. This matters
348 // when one block differs from the other only by whether debugging pseudos
349 // are present at the beginning. (This way, the various checks later for
350 // I1==MBB1->begin() work as expected.)
351 if (I1 == MBB1->begin() && I2 != MBB2->begin()) {
352 --I2;
353 while (I2->isDebugValue()) {
354 if (I2 == MBB2->begin()) {
355 return TailLen;
356 }
357 --I2;
358 }
359 ++I2;
360 }
361 if (I2 == MBB2->begin() && I1 != MBB1->begin()) {
362 --I1;
363 while (I1->isDebugValue()) {
364 if (I1 == MBB1->begin())
365 return TailLen;
366 --I1;
367 }
368 ++I1;
369 }
Chris Lattner12143052006-10-21 00:47:49 +0000370 return TailLen;
371}
372
Eli Friedmana38cfb22011-07-06 23:41:48 +0000373void BranchFolder::MaintainLiveIns(MachineBasicBlock *CurMBB,
374 MachineBasicBlock *NewMBB) {
Evan Cheng70017fb2012-01-07 03:35:48 +0000375 if (RS) {
376 RS->enterBasicBlock(CurMBB);
377 if (!CurMBB->empty())
378 RS->forward(prior(CurMBB->end()));
379 BitVector RegsLiveAtExit(TRI->getNumRegs());
380 RS->getRegsUsed(RegsLiveAtExit, false);
381 for (unsigned int i = 0, e = TRI->getNumRegs(); i != e; i++)
382 if (RegsLiveAtExit[i])
383 NewMBB->addLiveIn(i);
384 }
Eli Friedmana38cfb22011-07-06 23:41:48 +0000385}
386
Chris Lattner12143052006-10-21 00:47:49 +0000387/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Evan Cheng86050dc2010-06-18 23:09:54 +0000388/// after it, replacing it with an unconditional branch to NewDest.
Chris Lattner12143052006-10-21 00:47:49 +0000389void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
390 MachineBasicBlock *NewDest) {
Eli Friedmana38cfb22011-07-06 23:41:48 +0000391 MachineBasicBlock *CurMBB = OldInst->getParent();
392
Evan Cheng86050dc2010-06-18 23:09:54 +0000393 TII->ReplaceTailWithBranchTo(OldInst, NewDest);
Eli Friedmana38cfb22011-07-06 23:41:48 +0000394
395 // For targets that use the register scavenger, we must maintain LiveIns.
396 MaintainLiveIns(CurMBB, NewDest);
397
Chris Lattner12143052006-10-21 00:47:49 +0000398 ++NumTailMerge;
399}
400
Chris Lattner1d08d832006-11-01 01:16:12 +0000401/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
402/// MBB so that the part before the iterator falls into the part starting at the
403/// iterator. This returns the new MBB.
404MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
405 MachineBasicBlock::iterator BBI1) {
Evan Cheng4d54e5b2010-06-22 01:18:16 +0000406 if (!TII->isLegalToSplitMBBAt(CurMBB, BBI1))
407 return 0;
408
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000409 MachineFunction &MF = *CurMBB.getParent();
410
Chris Lattner1d08d832006-11-01 01:16:12 +0000411 // Create the fall-through block.
412 MachineFunction::iterator MBBI = &CurMBB;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000413 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
414 CurMBB.getParent()->insert(++MBBI, NewMBB);
Chris Lattner1d08d832006-11-01 01:16:12 +0000415
416 // Move all the successors of this block to the specified block.
Dan Gohman04478e52008-06-19 17:22:29 +0000417 NewMBB->transferSuccessors(&CurMBB);
Dan Gohman4e3f1252009-11-11 18:38:14 +0000418
Chris Lattner1d08d832006-11-01 01:16:12 +0000419 // Add an edge from CurMBB to NewMBB for the fall-through.
420 CurMBB.addSuccessor(NewMBB);
Dan Gohman4e3f1252009-11-11 18:38:14 +0000421
Chris Lattner1d08d832006-11-01 01:16:12 +0000422 // Splice the code over.
423 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000424
425 // For targets that use the register scavenger, we must maintain LiveIns.
Eli Friedmana38cfb22011-07-06 23:41:48 +0000426 MaintainLiveIns(&CurMBB, NewMBB);
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000427
Chris Lattner1d08d832006-11-01 01:16:12 +0000428 return NewMBB;
429}
430
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000431/// EstimateRuntime - Make a rough estimate for how long it will take to run
432/// the specified code.
433static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
Chris Lattner69244302008-01-07 01:56:04 +0000434 MachineBasicBlock::iterator E) {
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000435 unsigned Time = 0;
436 for (; I != E; ++I) {
Dale Johannesenb0812f12010-03-05 00:02:59 +0000437 if (I->isDebugValue())
438 continue;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000439 if (I->isCall())
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000440 Time += 10;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000441 else if (I->mayLoad() || I->mayStore())
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000442 Time += 2;
443 else
444 ++Time;
445 }
446 return Time;
447}
448
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000449// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
450// branches temporarily for tail merging). In the case where CurMBB ends
451// with a conditional branch to the next block, optimize by reversing the
452// test and conditionally branching to SuccMBB instead.
Bob Wilsond34f5d92009-11-16 18:08:46 +0000453static void FixTail(MachineBasicBlock *CurMBB, MachineBasicBlock *SuccBB,
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000454 const TargetInstrInfo *TII) {
455 MachineFunction *MF = CurMBB->getParent();
Chris Lattner7896c9f2009-12-03 00:50:42 +0000456 MachineFunction::iterator I = llvm::next(MachineFunction::iterator(CurMBB));
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000457 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000458 SmallVector<MachineOperand, 4> Cond;
Stuart Hastings3bf91252010-06-17 22:43:56 +0000459 DebugLoc dl; // FIXME: this is nowhere
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000460 if (I != MF->end() &&
Evan Chengdc54d312009-02-09 07:14:22 +0000461 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000462 MachineBasicBlock *NextBB = I;
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000463 if (TBB == NextBB && !Cond.empty() && !FBB) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000464 if (!TII->ReverseBranchCondition(Cond)) {
465 TII->RemoveBranch(*CurMBB);
Stuart Hastings3bf91252010-06-17 22:43:56 +0000466 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond, dl);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000467 return;
468 }
469 }
470 }
Stuart Hastings3bf91252010-06-17 22:43:56 +0000471 TII->InsertBranch(*CurMBB, SuccBB, NULL,
472 SmallVector<MachineOperand, 0>(), dl);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000473}
474
Dan Gohmanffe644e2009-11-11 21:57:02 +0000475bool
476BranchFolder::MergePotentialsElt::operator<(const MergePotentialsElt &o) const {
477 if (getHash() < o.getHash())
478 return true;
479 else if (getHash() > o.getHash())
480 return false;
481 else if (getBlock()->getNumber() < o.getBlock()->getNumber())
482 return true;
483 else if (getBlock()->getNumber() > o.getBlock()->getNumber())
484 return false;
485 else {
486 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
487 // an object with itself.
Duncan Sands97b4ac82007-07-11 08:47:55 +0000488#ifndef _GLIBCXX_DEBUG
Dan Gohmanffe644e2009-11-11 21:57:02 +0000489 llvm_unreachable("Predecessor appears twice");
David Blaikie4d6ccb52012-01-20 21:51:11 +0000490#else
Dan Gohmanffe644e2009-11-11 21:57:02 +0000491 return false;
David Blaikie4d6ccb52012-01-20 21:51:11 +0000492#endif
Dan Gohmanffe644e2009-11-11 21:57:02 +0000493 }
Dale Johannesen95ef4062007-05-29 23:47:50 +0000494}
495
Dan Gohman2210c0b2009-11-11 19:48:59 +0000496/// CountTerminators - Count the number of terminators in the given
497/// block and set I to the position of the first non-terminator, if there
498/// is one, or MBB->end() otherwise.
499static unsigned CountTerminators(MachineBasicBlock *MBB,
500 MachineBasicBlock::iterator &I) {
501 I = MBB->end();
502 unsigned NumTerms = 0;
503 for (;;) {
504 if (I == MBB->begin()) {
505 I = MBB->end();
506 break;
507 }
508 --I;
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000509 if (!I->isTerminator()) break;
Dan Gohman2210c0b2009-11-11 19:48:59 +0000510 ++NumTerms;
511 }
512 return NumTerms;
513}
514
Bob Wilson7b888b82009-10-29 18:40:06 +0000515/// ProfitableToMerge - Check if two machine basic blocks have a common tail
516/// and decide if it would be profitable to merge those tails. Return the
517/// length of the common tail and iterators to the first common instruction
518/// in each block.
519static bool ProfitableToMerge(MachineBasicBlock *MBB1,
520 MachineBasicBlock *MBB2,
521 unsigned minCommonTailLength,
522 unsigned &CommonTailLen,
523 MachineBasicBlock::iterator &I1,
Dan Gohman2210c0b2009-11-11 19:48:59 +0000524 MachineBasicBlock::iterator &I2,
525 MachineBasicBlock *SuccBB,
526 MachineBasicBlock *PredBB) {
Bob Wilson7b888b82009-10-29 18:40:06 +0000527 CommonTailLen = ComputeCommonTailLength(MBB1, MBB2, I1, I2);
Bob Wilson7b888b82009-10-29 18:40:06 +0000528 if (CommonTailLen == 0)
529 return false;
Evan Chengcf13af62011-02-21 23:39:48 +0000530 DEBUG(dbgs() << "Common tail length of BB#" << MBB1->getNumber()
531 << " and BB#" << MBB2->getNumber() << " is " << CommonTailLen
532 << '\n');
Bob Wilson7b888b82009-10-29 18:40:06 +0000533
Dan Gohman2210c0b2009-11-11 19:48:59 +0000534 // It's almost always profitable to merge any number of non-terminator
535 // instructions with the block that falls through into the common successor.
536 if (MBB1 == PredBB || MBB2 == PredBB) {
537 MachineBasicBlock::iterator I;
538 unsigned NumTerms = CountTerminators(MBB1 == PredBB ? MBB2 : MBB1, I);
539 if (CommonTailLen > NumTerms)
540 return true;
541 }
542
Dan Gohmanad6af452009-11-12 00:39:10 +0000543 // If one of the blocks can be completely merged and happens to be in
544 // a position where the other could fall through into it, merge any number
545 // of instructions, because it can be done without a branch.
546 // TODO: If the blocks are not adjacent, move one of them so that they are?
547 if (MBB1->isLayoutSuccessor(MBB2) && I2 == MBB2->begin())
548 return true;
549 if (MBB2->isLayoutSuccessor(MBB1) && I1 == MBB1->begin())
550 return true;
551
Dan Gohman2210c0b2009-11-11 19:48:59 +0000552 // If both blocks have an unconditional branch temporarily stripped out,
Dan Gohmanc4c550c2009-11-13 21:02:15 +0000553 // count that as an additional common instruction for the following
554 // heuristics.
555 unsigned EffectiveTailLen = CommonTailLen;
Bob Wilson3cbc3122009-11-16 17:56:13 +0000556 if (SuccBB && MBB1 != PredBB && MBB2 != PredBB &&
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000557 !MBB1->back().isBarrier() &&
558 !MBB2->back().isBarrier())
Dan Gohmanc4c550c2009-11-13 21:02:15 +0000559 ++EffectiveTailLen;
Dan Gohman2210c0b2009-11-11 19:48:59 +0000560
561 // Check if the common tail is long enough to be worthwhile.
Dan Gohmanc4c550c2009-11-13 21:02:15 +0000562 if (EffectiveTailLen >= minCommonTailLength)
Dan Gohman2210c0b2009-11-11 19:48:59 +0000563 return true;
564
Dan Gohmanc4c550c2009-11-13 21:02:15 +0000565 // If we are optimizing for code size, 2 instructions in common is enough if
566 // we don't have to split a block. At worst we will be introducing 1 new
567 // branch instruction, which is likely to be smaller than the 2
568 // instructions that would be deleted in the merge.
Evan Chengcf13af62011-02-21 23:39:48 +0000569 MachineFunction *MF = MBB1->getParent();
Dan Gohmanc4c550c2009-11-13 21:02:15 +0000570 if (EffectiveTailLen >= 2 &&
571 MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize) &&
Bob Wilson7b888b82009-10-29 18:40:06 +0000572 (I1 == MBB1->begin() || I2 == MBB2->begin()))
573 return true;
574
575 return false;
576}
577
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000578/// ComputeSameTails - Look through all the blocks in MergePotentials that have
Dan Gohman4e3f1252009-11-11 18:38:14 +0000579/// hash CurHash (guaranteed to match the last element). Build the vector
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000580/// SameTails of all those that have the (same) largest number of instructions
581/// in common of any pair of these blocks. SameTails entries contain an
Dan Gohman4e3f1252009-11-11 18:38:14 +0000582/// iterator into MergePotentials (from which the MachineBasicBlock can be
583/// found) and a MachineBasicBlock::iterator into that MBB indicating the
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000584/// instruction where the matching code sequence begins.
585/// Order of elements in SameTails is the reverse of the order in which
586/// those blocks appear in MergePotentials (where they are not necessarily
587/// consecutive).
Dan Gohman4e3f1252009-11-11 18:38:14 +0000588unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
Dan Gohman2210c0b2009-11-11 19:48:59 +0000589 unsigned minCommonTailLength,
590 MachineBasicBlock *SuccBB,
591 MachineBasicBlock *PredBB) {
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000592 unsigned maxCommonTailLength = 0U;
593 SameTails.clear();
594 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
595 MPIterator HighestMPIter = prior(MergePotentials.end());
596 for (MPIterator CurMPIter = prior(MergePotentials.end()),
Dan Gohman4e3f1252009-11-11 18:38:14 +0000597 B = MergePotentials.begin();
Dan Gohman8520149d2009-11-12 01:51:28 +0000598 CurMPIter != B && CurMPIter->getHash() == CurHash;
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000599 --CurMPIter) {
Dan Gohmanffe644e2009-11-11 21:57:02 +0000600 for (MPIterator I = prior(CurMPIter); I->getHash() == CurHash ; --I) {
Bob Wilson7b888b82009-10-29 18:40:06 +0000601 unsigned CommonTailLen;
Dan Gohmanffe644e2009-11-11 21:57:02 +0000602 if (ProfitableToMerge(CurMPIter->getBlock(), I->getBlock(),
603 minCommonTailLength,
Dan Gohman2210c0b2009-11-11 19:48:59 +0000604 CommonTailLen, TrialBBI1, TrialBBI2,
605 SuccBB, PredBB)) {
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000606 if (CommonTailLen > maxCommonTailLength) {
607 SameTails.clear();
608 maxCommonTailLength = CommonTailLen;
609 HighestMPIter = CurMPIter;
Dan Gohmanffe644e2009-11-11 21:57:02 +0000610 SameTails.push_back(SameTailElt(CurMPIter, TrialBBI1));
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000611 }
612 if (HighestMPIter == CurMPIter &&
613 CommonTailLen == maxCommonTailLength)
Dan Gohmanffe644e2009-11-11 21:57:02 +0000614 SameTails.push_back(SameTailElt(I, TrialBBI2));
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000615 }
Dan Gohman4e3f1252009-11-11 18:38:14 +0000616 if (I == B)
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000617 break;
618 }
619 }
620 return maxCommonTailLength;
621}
622
623/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
624/// MergePotentials, restoring branches at ends of blocks as appropriate.
Dan Gohman4e3f1252009-11-11 18:38:14 +0000625void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
Bob Wilsond34f5d92009-11-16 18:08:46 +0000626 MachineBasicBlock *SuccBB,
627 MachineBasicBlock *PredBB) {
Dale Johannesen679860e2008-05-23 17:19:02 +0000628 MPIterator CurMPIter, B;
Dan Gohman4e3f1252009-11-11 18:38:14 +0000629 for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
Dan Gohmanffe644e2009-11-11 21:57:02 +0000630 CurMPIter->getHash() == CurHash;
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000631 --CurMPIter) {
632 // Put the unconditional branch back, if we need one.
Dan Gohmanffe644e2009-11-11 21:57:02 +0000633 MachineBasicBlock *CurMBB = CurMPIter->getBlock();
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000634 if (SuccBB && CurMBB != PredBB)
635 FixTail(CurMBB, SuccBB, TII);
Dan Gohman4e3f1252009-11-11 18:38:14 +0000636 if (CurMPIter == B)
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000637 break;
638 }
Dan Gohmanffe644e2009-11-11 21:57:02 +0000639 if (CurMPIter->getHash() != CurHash)
Dale Johannesen679860e2008-05-23 17:19:02 +0000640 CurMPIter++;
641 MergePotentials.erase(CurMPIter, MergePotentials.end());
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000642}
643
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000644/// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
645/// only of the common tail. Create a block that does by splitting one.
Evan Cheng4d54e5b2010-06-22 01:18:16 +0000646bool BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
647 unsigned maxCommonTailLength,
648 unsigned &commonTailIndex) {
649 commonTailIndex = 0;
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000650 unsigned TimeEstimate = ~0U;
Dan Gohman8520149d2009-11-12 01:51:28 +0000651 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000652 // Use PredBB if possible; that doesn't require a new branch.
Dan Gohmanffe644e2009-11-11 21:57:02 +0000653 if (SameTails[i].getBlock() == PredBB) {
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000654 commonTailIndex = i;
655 break;
656 }
657 // Otherwise, make a (fairly bogus) choice based on estimate of
658 // how long it will take the various blocks to execute.
Dan Gohmanffe644e2009-11-11 21:57:02 +0000659 unsigned t = EstimateRuntime(SameTails[i].getBlock()->begin(),
660 SameTails[i].getTailStartPos());
Dan Gohman4e3f1252009-11-11 18:38:14 +0000661 if (t <= TimeEstimate) {
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000662 TimeEstimate = t;
663 commonTailIndex = i;
664 }
665 }
666
Dan Gohmanffe644e2009-11-11 21:57:02 +0000667 MachineBasicBlock::iterator BBI =
668 SameTails[commonTailIndex].getTailStartPos();
669 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000670
Dale Johannesen84839da2010-03-08 05:38:13 +0000671 // If the common tail includes any debug info we will take it pretty
672 // randomly from one of the inputs. Might be better to remove it?
David Greene465e2b92009-12-24 00:34:21 +0000673 DEBUG(dbgs() << "\nSplitting BB#" << MBB->getNumber() << ", size "
Bill Wendling3403bcd2009-08-22 20:03:00 +0000674 << maxCommonTailLength);
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000675
676 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
Evan Cheng4d54e5b2010-06-22 01:18:16 +0000677 if (!newMBB) {
678 DEBUG(dbgs() << "... failed!");
679 return false;
680 }
681
Dan Gohmanffe644e2009-11-11 21:57:02 +0000682 SameTails[commonTailIndex].setBlock(newMBB);
683 SameTails[commonTailIndex].setTailStartPos(newMBB->begin());
Dan Gohman4e3f1252009-11-11 18:38:14 +0000684
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000685 // If we split PredBB, newMBB is the new predecessor.
Dan Gohman4e3f1252009-11-11 18:38:14 +0000686 if (PredBB == MBB)
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000687 PredBB = newMBB;
688
Evan Cheng4d54e5b2010-06-22 01:18:16 +0000689 return true;
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000690}
691
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000692// See if any of the blocks in MergePotentials (which all have a common single
693// successor, or all have no successor) can be tail-merged. If there is a
694// successor, any blocks in MergePotentials that are not tail-merged and
695// are not immediately before Succ must have an unconditional branch to
Dan Gohman4e3f1252009-11-11 18:38:14 +0000696// Succ added (but the predecessor/successor lists need no adjustment).
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000697// The lone predecessor of Succ that falls through into Succ,
698// if any, is given in PredBB.
699
Dan Gohman2210c0b2009-11-11 19:48:59 +0000700bool BranchFolder::TryTailMergeBlocks(MachineBasicBlock *SuccBB,
Bob Wilsond34f5d92009-11-16 18:08:46 +0000701 MachineBasicBlock *PredBB) {
Evan Cheng030a0a02009-09-04 07:47:40 +0000702 bool MadeChange = false;
703
Dan Gohman2210c0b2009-11-11 19:48:59 +0000704 // Except for the special cases below, tail-merge if there are at least
705 // this many instructions in common.
706 unsigned minCommonTailLength = TailMergeSize;
Dan Gohman4e3f1252009-11-11 18:38:14 +0000707
David Greene465e2b92009-12-24 00:34:21 +0000708 DEBUG(dbgs() << "\nTryTailMergeBlocks: ";
Dan Gohman2210c0b2009-11-11 19:48:59 +0000709 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
David Greene465e2b92009-12-24 00:34:21 +0000710 dbgs() << "BB#" << MergePotentials[i].getBlock()->getNumber()
Dan Gohman2210c0b2009-11-11 19:48:59 +0000711 << (i == e-1 ? "" : ", ");
David Greene465e2b92009-12-24 00:34:21 +0000712 dbgs() << "\n";
Dan Gohman2210c0b2009-11-11 19:48:59 +0000713 if (SuccBB) {
David Greene465e2b92009-12-24 00:34:21 +0000714 dbgs() << " with successor BB#" << SuccBB->getNumber() << '\n';
Dan Gohman2210c0b2009-11-11 19:48:59 +0000715 if (PredBB)
David Greene465e2b92009-12-24 00:34:21 +0000716 dbgs() << " which has fall-through from BB#"
Dan Gohman2210c0b2009-11-11 19:48:59 +0000717 << PredBB->getNumber() << "\n";
718 }
David Greene465e2b92009-12-24 00:34:21 +0000719 dbgs() << "Looking for common tails of at least "
Dan Gohman2210c0b2009-11-11 19:48:59 +0000720 << minCommonTailLength << " instruction"
721 << (minCommonTailLength == 1 ? "" : "s") << '\n';
722 );
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000723
Chris Lattner12143052006-10-21 00:47:49 +0000724 // Sort by hash value so that blocks with identical end sequences sort
725 // together.
Dan Gohmanffe644e2009-11-11 21:57:02 +0000726 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
Chris Lattner12143052006-10-21 00:47:49 +0000727
728 // Walk through equivalence sets looking for actual exact matches.
729 while (MergePotentials.size() > 1) {
Dan Gohmanffe644e2009-11-11 21:57:02 +0000730 unsigned CurHash = MergePotentials.back().getHash();
Dan Gohman4e3f1252009-11-11 18:38:14 +0000731
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000732 // Build SameTails, identifying the set of blocks with this hash code
733 // and with the maximum number of instructions in common.
Dan Gohman4e3f1252009-11-11 18:38:14 +0000734 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
Dan Gohman2210c0b2009-11-11 19:48:59 +0000735 minCommonTailLength,
736 SuccBB, PredBB);
Dale Johannesen7aea8322007-05-23 21:07:20 +0000737
Dan Gohman4e3f1252009-11-11 18:38:14 +0000738 // If we didn't find any pair that has at least minCommonTailLength
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000739 // instructions in common, remove all blocks with this hash code and retry.
740 if (SameTails.empty()) {
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000741 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
Dale Johannesen7aea8322007-05-23 21:07:20 +0000742 continue;
Chris Lattner12143052006-10-21 00:47:49 +0000743 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000744
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000745 // If one of the blocks is the entire common tail (and not the entry
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000746 // block, which we can't jump to), we can treat all blocks with this same
747 // tail at once. Use PredBB if that is one of the possibilities, as that
748 // will not introduce any extra branches.
Dan Gohmanffe644e2009-11-11 21:57:02 +0000749 MachineBasicBlock *EntryBB = MergePotentials.begin()->getBlock()->
750 getParent()->begin();
751 unsigned commonTailIndex = SameTails.size();
Dan Gohmanad6af452009-11-12 00:39:10 +0000752 // If there are two blocks, check to see if one can be made to fall through
753 // into the other.
754 if (SameTails.size() == 2 &&
755 SameTails[0].getBlock()->isLayoutSuccessor(SameTails[1].getBlock()) &&
756 SameTails[1].tailIsWholeBlock())
757 commonTailIndex = 1;
758 else if (SameTails.size() == 2 &&
759 SameTails[1].getBlock()->isLayoutSuccessor(
760 SameTails[0].getBlock()) &&
761 SameTails[0].tailIsWholeBlock())
762 commonTailIndex = 0;
763 else {
764 // Otherwise just pick one, favoring the fall-through predecessor if
765 // there is one.
766 for (unsigned i = 0, e = SameTails.size(); i != e; ++i) {
767 MachineBasicBlock *MBB = SameTails[i].getBlock();
768 if (MBB == EntryBB && SameTails[i].tailIsWholeBlock())
769 continue;
770 if (MBB == PredBB) {
771 commonTailIndex = i;
772 break;
773 }
774 if (SameTails[i].tailIsWholeBlock())
775 commonTailIndex = i;
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000776 }
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000777 }
Dale Johannesena5a21172007-06-01 23:02:45 +0000778
Dan Gohman2210c0b2009-11-11 19:48:59 +0000779 if (commonTailIndex == SameTails.size() ||
Dan Gohmanffe644e2009-11-11 21:57:02 +0000780 (SameTails[commonTailIndex].getBlock() == PredBB &&
781 !SameTails[commonTailIndex].tailIsWholeBlock())) {
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000782 // None of the blocks consist entirely of the common tail.
783 // Split a block so that one does.
Evan Cheng4d54e5b2010-06-22 01:18:16 +0000784 if (!CreateCommonTailOnlyBlock(PredBB,
785 maxCommonTailLength, commonTailIndex)) {
786 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
787 continue;
788 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000789 }
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000790
Dan Gohmanffe644e2009-11-11 21:57:02 +0000791 MachineBasicBlock *MBB = SameTails[commonTailIndex].getBlock();
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000792 // MBB is common tail. Adjust all other BB's to jump to this one.
793 // Traversal must be forwards so erases work.
David Greene465e2b92009-12-24 00:34:21 +0000794 DEBUG(dbgs() << "\nUsing common tail in BB#" << MBB->getNumber()
Dan Gohman2210c0b2009-11-11 19:48:59 +0000795 << " for ");
796 for (unsigned int i=0, e = SameTails.size(); i != e; ++i) {
Dan Gohman4e3f1252009-11-11 18:38:14 +0000797 if (commonTailIndex == i)
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000798 continue;
David Greene465e2b92009-12-24 00:34:21 +0000799 DEBUG(dbgs() << "BB#" << SameTails[i].getBlock()->getNumber()
Dan Gohman2210c0b2009-11-11 19:48:59 +0000800 << (i == e-1 ? "" : ", "));
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000801 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
Dan Gohmanffe644e2009-11-11 21:57:02 +0000802 ReplaceTailWithBranchTo(SameTails[i].getTailStartPos(), MBB);
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000803 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
Dan Gohmanffe644e2009-11-11 21:57:02 +0000804 MergePotentials.erase(SameTails[i].getMPIter());
Chris Lattner12143052006-10-21 00:47:49 +0000805 }
David Greene465e2b92009-12-24 00:34:21 +0000806 DEBUG(dbgs() << "\n");
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000807 // We leave commonTailIndex in the worklist in case there are other blocks
808 // that match it with a smaller number of instructions.
Chris Lattner1d08d832006-11-01 01:16:12 +0000809 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000810 }
Chris Lattner12143052006-10-21 00:47:49 +0000811 return MadeChange;
812}
813
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000814bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000815
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000816 if (!EnableTailMerge) return false;
Dan Gohman4e3f1252009-11-11 18:38:14 +0000817
Evan Cheng030a0a02009-09-04 07:47:40 +0000818 bool MadeChange = false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000819
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000820 // First find blocks with no successors.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000821 MergePotentials.clear();
Rafael Espindolaf924dea2011-06-14 15:31:54 +0000822 for (MachineFunction::iterator I = MF.begin(), E = MF.end();
823 I != E && MergePotentials.size() < TailMergeThreshold; ++I) {
824 if (TriedMerging.count(I))
825 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000826 if (I->succ_empty())
Dan Gohman30fc5bb2010-05-03 14:35:47 +0000827 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(I), I));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000828 }
Dan Gohman4e3f1252009-11-11 18:38:14 +0000829
Rafael Espindolaf924dea2011-06-14 15:31:54 +0000830 // If this is a large problem, avoid visiting the same basic blocks
831 // multiple times.
832 if (MergePotentials.size() == TailMergeThreshold)
833 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
834 TriedMerging.insert(MergePotentials[i].getBlock());
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000835 // See if we can do any tail merging on those.
Rafael Espindolaf924dea2011-06-14 15:31:54 +0000836 if (MergePotentials.size() >= 2)
Dan Gohman2210c0b2009-11-11 19:48:59 +0000837 MadeChange |= TryTailMergeBlocks(NULL, NULL);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000838
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000839 // Look at blocks (IBB) with multiple predecessors (PBB).
840 // We change each predecessor to a canonical form, by
841 // (1) temporarily removing any unconditional branch from the predecessor
842 // to IBB, and
843 // (2) alter conditional branches so they branch to the other block
Dan Gohman4e3f1252009-11-11 18:38:14 +0000844 // not IBB; this may require adding back an unconditional branch to IBB
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000845 // later, where there wasn't one coming in. E.g.
846 // Bcc IBB
847 // fallthrough to QBB
848 // here becomes
849 // Bncc QBB
850 // with a conceptual B to IBB after that, which never actually exists.
851 // With those changes, we see whether the predecessors' tails match,
852 // and merge them if so. We change things out of canonical form and
853 // back to the way they were later in the process. (OptimizeBranches
854 // would undo some of this, but we can't use it, because we'd get into
855 // a compile-time infinite loop repeatedly doing and undoing the same
856 // transformations.)
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000857
Chris Lattner7896c9f2009-12-03 00:50:42 +0000858 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
Dan Gohman2210c0b2009-11-11 19:48:59 +0000859 I != E; ++I) {
Rafael Espindolaf924dea2011-06-14 15:31:54 +0000860 if (I->pred_size() >= 2) {
Dan Gohmanda658222009-08-18 15:18:18 +0000861 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000862 MachineBasicBlock *IBB = I;
863 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000864 MergePotentials.clear();
Dan Gohman4e3f1252009-11-11 18:38:14 +0000865 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
Dale Johannesen1a90a5a2007-06-08 01:08:52 +0000866 E2 = I->pred_end();
Rafael Espindolaf924dea2011-06-14 15:31:54 +0000867 P != E2 && MergePotentials.size() < TailMergeThreshold; ++P) {
Bob Wilsond34f5d92009-11-16 18:08:46 +0000868 MachineBasicBlock *PBB = *P;
Rafael Espindolaf924dea2011-06-14 15:31:54 +0000869 if (TriedMerging.count(PBB))
870 continue;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000871 // Skip blocks that loop to themselves, can't tail merge these.
Dan Gohman4e3f1252009-11-11 18:38:14 +0000872 if (PBB == IBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000873 continue;
Dan Gohmanda658222009-08-18 15:18:18 +0000874 // Visit each predecessor only once.
875 if (!UniquePreds.insert(PBB))
876 continue;
Bill Wendlinga823e3d2011-10-26 01:10:25 +0000877 // Skip blocks which may jump to a landing pad. Can't tail merge these.
878 if (PBB->getLandingPadSuccessor())
879 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000880 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000881 SmallVector<MachineOperand, 4> Cond;
Evan Chengdc54d312009-02-09 07:14:22 +0000882 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000883 // Failing case: IBB is the target of a cbr, and
884 // we cannot reverse the branch.
Owen Anderson44eb65c2008-08-14 22:49:33 +0000885 SmallVector<MachineOperand, 4> NewCond(Cond);
Dan Gohman4e3f1252009-11-11 18:38:14 +0000886 if (!Cond.empty() && TBB == IBB) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000887 if (TII->ReverseBranchCondition(NewCond))
888 continue;
889 // This is the QBB case described above
890 if (!FBB)
Chris Lattner7896c9f2009-12-03 00:50:42 +0000891 FBB = llvm::next(MachineFunction::iterator(PBB));
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000892 }
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000893 // Failing case: the only way IBB can be reached from PBB is via
894 // exception handling. Happens for landing pads. Would be nice
895 // to have a bit in the edge so we didn't have to do all this.
896 if (IBB->isLandingPad()) {
897 MachineFunction::iterator IP = PBB; IP++;
Bob Wilsond34f5d92009-11-16 18:08:46 +0000898 MachineBasicBlock *PredNextBB = NULL;
Dan Gohman8520149d2009-11-12 01:51:28 +0000899 if (IP != MF.end())
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000900 PredNextBB = IP;
Dan Gohman4e3f1252009-11-11 18:38:14 +0000901 if (TBB == NULL) {
Dan Gohman8520149d2009-11-12 01:51:28 +0000902 if (IBB != PredNextBB) // fallthrough
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000903 continue;
904 } else if (FBB) {
Dan Gohman8520149d2009-11-12 01:51:28 +0000905 if (TBB != IBB && FBB != IBB) // cbr then ubr
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000906 continue;
Dan Gohman30359592008-01-29 13:02:09 +0000907 } else if (Cond.empty()) {
Dan Gohman8520149d2009-11-12 01:51:28 +0000908 if (TBB != IBB) // ubr
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000909 continue;
910 } else {
Dan Gohman8520149d2009-11-12 01:51:28 +0000911 if (TBB != IBB && IBB != PredNextBB) // cbr
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000912 continue;
913 }
914 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000915 // Remove the unconditional branch at the end, if any.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000916 if (TBB && (Cond.empty() || FBB)) {
Stuart Hastings3bf91252010-06-17 22:43:56 +0000917 DebugLoc dl; // FIXME: this is nowhere
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000918 TII->RemoveBranch(*PBB);
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000919 if (!Cond.empty())
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000920 // reinsert conditional branch only, for now
Stuart Hastings3bf91252010-06-17 22:43:56 +0000921 TII->InsertBranch(*PBB, (TBB == IBB) ? FBB : TBB, 0, NewCond, dl);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000922 }
Duncan Sands51583ce2011-10-25 12:30:22 +0000923 MergePotentials.push_back(MergePotentialsElt(HashEndOfMBB(PBB), *P));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000924 }
925 }
Rafael Espindolaf924dea2011-06-14 15:31:54 +0000926 // If this is a large problem, avoid visiting the same basic blocks
927 // multiple times.
928 if (MergePotentials.size() == TailMergeThreshold)
929 for (unsigned i = 0, e = MergePotentials.size(); i != e; ++i)
930 TriedMerging.insert(MergePotentials[i].getBlock());
Dan Gohmancdc06ba2009-11-11 18:42:28 +0000931 if (MergePotentials.size() >= 2)
Dan Gohman2210c0b2009-11-11 19:48:59 +0000932 MadeChange |= TryTailMergeBlocks(IBB, PredBB);
Dan Gohmancdc06ba2009-11-11 18:42:28 +0000933 // Reinsert an unconditional branch if needed.
Evan Chengddfd1372011-12-14 02:11:42 +0000934 // The 1 below can occur as a result of removing blocks in
935 // TryTailMergeBlocks.
936 PredBB = prior(I); // this may have been changed in TryTailMergeBlocks
Dan Gohmancdc06ba2009-11-11 18:42:28 +0000937 if (MergePotentials.size() == 1 &&
Dan Gohmanffe644e2009-11-11 21:57:02 +0000938 MergePotentials.begin()->getBlock() != PredBB)
939 FixTail(MergePotentials.begin()->getBlock(), IBB, TII);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000940 }
941 }
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000942 return MadeChange;
943}
Chris Lattner12143052006-10-21 00:47:49 +0000944
945//===----------------------------------------------------------------------===//
946// Branch Optimization
947//===----------------------------------------------------------------------===//
948
949bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
Evan Cheng030a0a02009-09-04 07:47:40 +0000950 bool MadeChange = false;
Dan Gohman4e3f1252009-11-11 18:38:14 +0000951
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000952 // Make sure blocks are numbered in order
953 MF.RenumberBlocks();
954
Evan Chengcbc988b2011-05-12 00:56:58 +0000955 for (MachineFunction::iterator I = llvm::next(MF.begin()), E = MF.end();
956 I != E; ) {
Chris Lattner12143052006-10-21 00:47:49 +0000957 MachineBasicBlock *MBB = I++;
Evan Cheng030a0a02009-09-04 07:47:40 +0000958 MadeChange |= OptimizeBlock(MBB);
Dan Gohman4e3f1252009-11-11 18:38:14 +0000959
Chris Lattner12143052006-10-21 00:47:49 +0000960 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000961 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000962 RemoveDeadBlock(MBB);
963 MadeChange = true;
964 ++NumDeadBlocks;
965 }
966 }
967 return MadeChange;
968}
969
Dale Johannesenc5cf2272010-03-10 05:45:47 +0000970// Blocks should be considered empty if they contain only debug info;
971// else the debug info would affect codegen.
972static bool IsEmptyBlock(MachineBasicBlock *MBB) {
973 if (MBB->empty())
974 return true;
975 for (MachineBasicBlock::iterator MBBI = MBB->begin(), MBBE = MBB->end();
976 MBBI!=MBBE; ++MBBI) {
977 if (!MBBI->isDebugValue())
978 return false;
979 }
980 return true;
981}
Chris Lattner12143052006-10-21 00:47:49 +0000982
Dale Johannesen2cd9ffe2010-03-10 19:57:56 +0000983// Blocks with only debug info and branches should be considered the same
984// as blocks with only branches.
985static bool IsBranchOnlyBlock(MachineBasicBlock *MBB) {
986 MachineBasicBlock::iterator MBBI, MBBE;
987 for (MBBI = MBB->begin(), MBBE = MBB->end(); MBBI!=MBBE; ++MBBI) {
988 if (!MBBI->isDebugValue())
989 break;
990 }
Evan Cheng5a96b3d2011-12-07 07:15:52 +0000991 return (MBBI->isBranch());
Dale Johannesen2cd9ffe2010-03-10 19:57:56 +0000992}
993
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000994/// IsBetterFallthrough - Return true if it would be clearly better to
995/// fall-through to MBB1 than to fall through into MBB2. This has to return
996/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
997/// result in infinite loops.
Dan Gohman4e3f1252009-11-11 18:38:14 +0000998static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
Chris Lattner69244302008-01-07 01:56:04 +0000999 MachineBasicBlock *MBB2) {
Chris Lattner154e1042006-11-18 21:30:35 +00001000 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
1001 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001002 // optimize branches that branch to either a return block or an assert block
1003 // into a fallthrough to the return.
Dale Johannesen93d6a7e2010-04-02 01:38:09 +00001004 if (IsEmptyBlock(MBB1) || IsEmptyBlock(MBB2)) return false;
Dan Gohman4e3f1252009-11-11 18:38:14 +00001005
Christopher Lamb11a4f642007-12-10 07:24:06 +00001006 // If there is a clear successor ordering we make sure that one block
1007 // will fall through to the next
1008 if (MBB1->isSuccessor(MBB2)) return true;
1009 if (MBB2->isSuccessor(MBB1)) return false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001010
Dale Johannesen93d6a7e2010-04-02 01:38:09 +00001011 // Neither block consists entirely of debug info (per IsEmptyBlock check),
1012 // so we needn't test for falling off the beginning here.
1013 MachineBasicBlock::iterator MBB1I = --MBB1->end();
1014 while (MBB1I->isDebugValue())
1015 --MBB1I;
1016 MachineBasicBlock::iterator MBB2I = --MBB2->end();
1017 while (MBB2I->isDebugValue())
1018 --MBB2I;
Evan Cheng5a96b3d2011-12-07 07:15:52 +00001019 return MBB2I->isCall() && !MBB1I->isCall();
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001020}
1021
Bill Wendling5b2749a2012-03-07 08:49:42 +00001022/// getBranchDebugLoc - Find and return, if any, the DebugLoc of the branch
1023/// instructions on the block. Always use the DebugLoc of the first
1024/// branching instruction found unless its absent, in which case use the
1025/// DebugLoc of the second if present.
1026static DebugLoc getBranchDebugLoc(MachineBasicBlock &MBB) {
1027 MachineBasicBlock::iterator I = MBB.end();
1028 if (I == MBB.begin())
1029 return DebugLoc();
1030 --I;
1031 while (I->isDebugValue() && I != MBB.begin())
1032 --I;
1033 if (I->isBranch())
1034 return I->getDebugLoc();
1035 return DebugLoc();
1036}
1037
Chris Lattner7821a8a2006-10-14 00:21:48 +00001038/// OptimizeBlock - Analyze and optimize control flow related to the specified
1039/// block. This is never called on the entry block.
Evan Cheng030a0a02009-09-04 07:47:40 +00001040bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
1041 bool MadeChange = false;
Dan Gohmand1944982009-11-11 18:18:34 +00001042 MachineFunction &MF = *MBB->getParent();
Dan Gohman2210c0b2009-11-11 19:48:59 +00001043ReoptimizeBlock:
Evan Cheng030a0a02009-09-04 07:47:40 +00001044
Chris Lattner7d097842006-10-24 01:12:32 +00001045 MachineFunction::iterator FallThrough = MBB;
1046 ++FallThrough;
Dan Gohman4e3f1252009-11-11 18:38:14 +00001047
Chris Lattnereb15eee2006-10-13 20:43:10 +00001048 // If this block is empty, make everyone use its fall-through, not the block
Dale Johannesena52dd152007-05-31 21:54:00 +00001049 // explicitly. Landing pads should not do this since the landing-pad table
Dan Gohmanab918102009-10-30 02:13:27 +00001050 // points to this block. Blocks with their addresses taken shouldn't be
1051 // optimized away.
Dale Johannesenc5cf2272010-03-10 05:45:47 +00001052 if (IsEmptyBlock(MBB) && !MBB->isLandingPad() && !MBB->hasAddressTaken()) {
Chris Lattner386e2902006-10-21 05:08:28 +00001053 // Dead block? Leave for cleanup later.
Evan Cheng030a0a02009-09-04 07:47:40 +00001054 if (MBB->pred_empty()) return MadeChange;
Dan Gohman4e3f1252009-11-11 18:38:14 +00001055
Dan Gohmand1944982009-11-11 18:18:34 +00001056 if (FallThrough == MF.end()) {
Chris Lattnerc50ffcb2006-10-17 17:13:52 +00001057 // TODO: Simplify preds to not branch here if possible!
1058 } else {
1059 // Rewrite all predecessors of the old block to go to the fallthrough
1060 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +00001061 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +00001062 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
Evan Cheng0370fad2007-06-04 06:44:01 +00001063 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +00001064 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +00001065 // If MBB was the target of a jump table, update jump tables to go to the
1066 // fallthrough instead.
Chris Lattner071c62f2010-01-25 23:26:13 +00001067 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1068 MJTI->ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +00001069 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +00001070 }
Evan Cheng030a0a02009-09-04 07:47:40 +00001071 return MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +00001072 }
1073
Chris Lattner7821a8a2006-10-14 00:21:48 +00001074 // Check to see if we can simplify the terminator of the block before this
1075 // one.
Chris Lattner7d097842006-10-24 01:12:32 +00001076 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +00001077
Chris Lattner7821a8a2006-10-14 00:21:48 +00001078 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +00001079 SmallVector<MachineOperand, 4> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001080 bool PriorUnAnalyzable =
Evan Chengdc54d312009-02-09 07:14:22 +00001081 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
Chris Lattner386e2902006-10-21 05:08:28 +00001082 if (!PriorUnAnalyzable) {
1083 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001084 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
1085 !PriorCond.empty());
Dan Gohman4e3f1252009-11-11 18:38:14 +00001086
Chris Lattner7821a8a2006-10-14 00:21:48 +00001087 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +00001088 // destination, remove the branch, replacing it with an unconditional one or
1089 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +00001090 if (PriorTBB && PriorTBB == PriorFBB) {
Bill Wendling5b2749a2012-03-07 08:49:42 +00001091 DebugLoc dl = getBranchDebugLoc(PrevBB);
Chris Lattner386e2902006-10-21 05:08:28 +00001092 TII->RemoveBranch(PrevBB);
Dan Gohman4e3f1252009-11-11 18:38:14 +00001093 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +00001094 if (PriorTBB != MBB)
Stuart Hastings3bf91252010-06-17 22:43:56 +00001095 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
Chris Lattner7821a8a2006-10-14 00:21:48 +00001096 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +00001097 ++NumBranchOpts;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001098 goto ReoptimizeBlock;
Chris Lattner7821a8a2006-10-14 00:21:48 +00001099 }
Dan Gohman4e3f1252009-11-11 18:38:14 +00001100
Dan Gohman2210c0b2009-11-11 19:48:59 +00001101 // If the previous block unconditionally falls through to this block and
1102 // this block has no other predecessors, move the contents of this block
1103 // into the prior block. This doesn't usually happen when SimplifyCFG
Bob Wilson465c8252009-11-17 17:40:31 +00001104 // has been used, but it can happen if tail merging splits a fall-through
1105 // predecessor of a block.
Dan Gohman2210c0b2009-11-11 19:48:59 +00001106 // This has to check PrevBB->succ_size() because EH edges are ignored by
1107 // AnalyzeBranch.
1108 if (PriorCond.empty() && !PriorTBB && MBB->pred_size() == 1 &&
1109 PrevBB.succ_size() == 1 &&
Bill Wendlingd3dbd5f2011-04-22 01:07:09 +00001110 !MBB->hasAddressTaken() && !MBB->isLandingPad()) {
David Greene465e2b92009-12-24 00:34:21 +00001111 DEBUG(dbgs() << "\nMerging into block: " << PrevBB
Dan Gohman2210c0b2009-11-11 19:48:59 +00001112 << "From MBB: " << *MBB);
Devang Patel95ba6692011-05-26 21:49:28 +00001113 // Remove redundant DBG_VALUEs first.
Devang Patel785badb2011-05-26 21:47:59 +00001114 if (PrevBB.begin() != PrevBB.end()) {
1115 MachineBasicBlock::iterator PrevBBIter = PrevBB.end();
1116 --PrevBBIter;
1117 MachineBasicBlock::iterator MBBIter = MBB->begin();
Andrew Trick1df91b02012-02-08 21:22:43 +00001118 // Check if DBG_VALUE at the end of PrevBB is identical to the
Devang Patel95ba6692011-05-26 21:49:28 +00001119 // DBG_VALUE at the beginning of MBB.
Devang Patel785badb2011-05-26 21:47:59 +00001120 while (PrevBBIter != PrevBB.begin() && MBBIter != MBB->end()
1121 && PrevBBIter->isDebugValue() && MBBIter->isDebugValue()) {
1122 if (!MBBIter->isIdenticalTo(PrevBBIter))
1123 break;
1124 MachineInstr *DuplicateDbg = MBBIter;
1125 ++MBBIter; -- PrevBBIter;
1126 DuplicateDbg->eraseFromParent();
1127 }
1128 }
Dan Gohman2210c0b2009-11-11 19:48:59 +00001129 PrevBB.splice(PrevBB.end(), MBB, MBB->begin(), MBB->end());
Chad Rosier90f20042012-02-22 17:25:00 +00001130 PrevBB.removeSuccessor(PrevBB.succ_begin());
Dan Gohman2210c0b2009-11-11 19:48:59 +00001131 assert(PrevBB.succ_empty());
1132 PrevBB.transferSuccessors(MBB);
1133 MadeChange = true;
1134 return MadeChange;
1135 }
Bob Wilson3cbc3122009-11-16 17:56:13 +00001136
Chris Lattner7821a8a2006-10-14 00:21:48 +00001137 // If the previous branch *only* branches to *this* block (conditional or
1138 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +00001139 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +00001140 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +00001141 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +00001142 ++NumBranchOpts;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001143 goto ReoptimizeBlock;
Chris Lattner7821a8a2006-10-14 00:21:48 +00001144 }
Dan Gohman4e3f1252009-11-11 18:38:14 +00001145
Chris Lattner2d47bd92006-10-21 05:43:30 +00001146 // If the prior block branches somewhere else on the condition and here if
1147 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +00001148 if (PriorFBB == MBB) {
Bill Wendling5b2749a2012-03-07 08:49:42 +00001149 DebugLoc dl = getBranchDebugLoc(PrevBB);
Chris Lattner2d47bd92006-10-21 05:43:30 +00001150 TII->RemoveBranch(PrevBB);
Stuart Hastings3bf91252010-06-17 22:43:56 +00001151 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond, dl);
Chris Lattner2d47bd92006-10-21 05:43:30 +00001152 MadeChange = true;
1153 ++NumBranchOpts;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001154 goto ReoptimizeBlock;
Chris Lattner2d47bd92006-10-21 05:43:30 +00001155 }
Dan Gohman4e3f1252009-11-11 18:38:14 +00001156
Chris Lattnera2d79952006-10-21 05:54:00 +00001157 // If the prior block branches here on true and somewhere else on false, and
1158 // if the branch condition is reversible, reverse the branch to create a
1159 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +00001160 if (PriorTBB == MBB) {
Owen Anderson44eb65c2008-08-14 22:49:33 +00001161 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Chris Lattnera2d79952006-10-21 05:54:00 +00001162 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Bill Wendling5b2749a2012-03-07 08:49:42 +00001163 DebugLoc dl = getBranchDebugLoc(PrevBB);
Chris Lattnera2d79952006-10-21 05:54:00 +00001164 TII->RemoveBranch(PrevBB);
Stuart Hastings3bf91252010-06-17 22:43:56 +00001165 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond, dl);
Chris Lattnera2d79952006-10-21 05:54:00 +00001166 MadeChange = true;
1167 ++NumBranchOpts;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001168 goto ReoptimizeBlock;
Chris Lattnera2d79952006-10-21 05:54:00 +00001169 }
1170 }
Dan Gohman4e3f1252009-11-11 18:38:14 +00001171
Dan Gohman6d312682009-10-22 00:03:58 +00001172 // If this block has no successors (e.g. it is a return block or ends with
1173 // a call to a no-return function like abort or __cxa_throw) and if the pred
1174 // falls through into this block, and if it would otherwise fall through
1175 // into the block after this, move this block to the end of the function.
Chris Lattner154e1042006-11-18 21:30:35 +00001176 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001177 // We consider it more likely that execution will stay in the function (e.g.
1178 // due to loops) than it is to exit it. This asserts in loops etc, moving
1179 // the assert condition out of the loop body.
Dan Gohman6d312682009-10-22 00:03:58 +00001180 if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
Chris Lattner154e1042006-11-18 21:30:35 +00001181 MachineFunction::iterator(PriorTBB) == FallThrough &&
Bob Wilson15acadd2009-11-26 00:32:21 +00001182 !MBB->canFallThrough()) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +00001183 bool DoTransform = true;
Dan Gohman4e3f1252009-11-11 18:38:14 +00001184
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001185 // We have to be careful that the succs of PredBB aren't both no-successor
1186 // blocks. If neither have successors and if PredBB is the second from
1187 // last block in the function, we'd just keep swapping the two blocks for
1188 // last. Only do the swap if one is clearly better to fall through than
1189 // the other.
Dan Gohmand1944982009-11-11 18:18:34 +00001190 if (FallThrough == --MF.end() &&
Chris Lattner69244302008-01-07 01:56:04 +00001191 !IsBetterFallthrough(PriorTBB, MBB))
Chris Lattnerf10a56a2006-11-18 21:56:39 +00001192 DoTransform = false;
1193
Chris Lattnerf10a56a2006-11-18 21:56:39 +00001194 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001195 // Reverse the branch so we will fall through on the previous true cond.
Owen Anderson44eb65c2008-08-14 22:49:33 +00001196 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001197 if (!TII->ReverseBranchCondition(NewPriorCond)) {
David Greene465e2b92009-12-24 00:34:21 +00001198 DEBUG(dbgs() << "\nMoving MBB: " << *MBB
Bill Wendling3403bcd2009-08-22 20:03:00 +00001199 << "To make fallthrough to: " << *PriorTBB << "\n");
Dan Gohman4e3f1252009-11-11 18:38:14 +00001200
Bill Wendling5b2749a2012-03-07 08:49:42 +00001201 DebugLoc dl = getBranchDebugLoc(PrevBB);
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001202 TII->RemoveBranch(PrevBB);
Stuart Hastings3bf91252010-06-17 22:43:56 +00001203 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond, dl);
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001204
1205 // Move this block to the end of the function.
Dan Gohmand1944982009-11-11 18:18:34 +00001206 MBB->moveAfter(--MF.end());
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001207 MadeChange = true;
1208 ++NumBranchOpts;
Evan Cheng030a0a02009-09-04 07:47:40 +00001209 return MadeChange;
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001210 }
1211 }
1212 }
Chris Lattner7821a8a2006-10-14 00:21:48 +00001213 }
Dan Gohman4e3f1252009-11-11 18:38:14 +00001214
Chris Lattner386e2902006-10-21 05:08:28 +00001215 // Analyze the branch in the current block.
1216 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +00001217 SmallVector<MachineOperand, 4> CurCond;
Evan Chengdc54d312009-02-09 07:14:22 +00001218 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001219 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +00001220 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001221 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
Chris Lattnereb15eee2006-10-13 20:43:10 +00001222
Dan Gohman4e3f1252009-11-11 18:38:14 +00001223 // If this is a two-way branch, and the FBB branches to this block, reverse
Chris Lattner5d056952006-11-08 01:03:21 +00001224 // the condition so the single-basic-block loop is faster. Instead of:
1225 // Loop: xxx; jcc Out; jmp Loop
1226 // we want:
1227 // Loop: xxx; jncc Loop; jmp Out
1228 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
Owen Anderson44eb65c2008-08-14 22:49:33 +00001229 SmallVector<MachineOperand, 4> NewCond(CurCond);
Chris Lattner5d056952006-11-08 01:03:21 +00001230 if (!TII->ReverseBranchCondition(NewCond)) {
Bill Wendling5b2749a2012-03-07 08:49:42 +00001231 DebugLoc dl = getBranchDebugLoc(*MBB);
Chris Lattner5d056952006-11-08 01:03:21 +00001232 TII->RemoveBranch(*MBB);
Stuart Hastings3bf91252010-06-17 22:43:56 +00001233 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond, dl);
Chris Lattner5d056952006-11-08 01:03:21 +00001234 MadeChange = true;
1235 ++NumBranchOpts;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001236 goto ReoptimizeBlock;
Chris Lattner5d056952006-11-08 01:03:21 +00001237 }
1238 }
Dan Gohman4e3f1252009-11-11 18:38:14 +00001239
Chris Lattner386e2902006-10-21 05:08:28 +00001240 // If this branch is the only thing in its block, see if we can forward
1241 // other blocks across it.
Dan Gohman4e3f1252009-11-11 18:38:14 +00001242 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Dale Johannesen2cd9ffe2010-03-10 19:57:56 +00001243 IsBranchOnlyBlock(MBB) && CurTBB != MBB &&
Bob Wilson888acc32009-11-03 23:44:31 +00001244 !MBB->hasAddressTaken()) {
Bill Wendling5b2749a2012-03-07 08:49:42 +00001245 DebugLoc dl = getBranchDebugLoc(*MBB);
Chris Lattner386e2902006-10-21 05:08:28 +00001246 // This block may contain just an unconditional branch. Because there can
1247 // be 'non-branch terminators' in the block, try removing the branch and
1248 // then seeing if the block is empty.
1249 TII->RemoveBranch(*MBB);
Dale Johannesenc5cf2272010-03-10 05:45:47 +00001250 // If the only things remaining in the block are debug info, remove these
1251 // as well, so this will behave the same as an empty block in non-debug
1252 // mode.
1253 if (!MBB->empty()) {
1254 bool NonDebugInfoFound = false;
1255 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
1256 I != E; ++I) {
1257 if (!I->isDebugValue()) {
1258 NonDebugInfoFound = true;
1259 break;
1260 }
1261 }
1262 if (!NonDebugInfoFound)
1263 // Make the block empty, losing the debug info (we could probably
1264 // improve this in some cases.)
1265 MBB->erase(MBB->begin(), MBB->end());
1266 }
Chris Lattner386e2902006-10-21 05:08:28 +00001267 // If this block is just an unconditional branch to CurTBB, we can
1268 // usually completely eliminate the block. The only case we cannot
1269 // completely eliminate the block is when the block before this one
1270 // falls through into MBB and we can't understand the prior block's branch
1271 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +00001272 if (MBB->empty()) {
Dan Gohman864e2ef2009-12-05 00:44:40 +00001273 bool PredHasNoFallThrough = !PrevBB.canFallThrough();
Chris Lattnercf420cc2006-10-28 17:32:47 +00001274 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1275 !PrevBB.isSuccessor(MBB)) {
1276 // If the prior block falls through into us, turn it into an
1277 // explicit branch to us to make updates simpler.
Dan Gohman4e3f1252009-11-11 18:38:14 +00001278 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
Chris Lattnercf420cc2006-10-28 17:32:47 +00001279 PriorTBB != MBB && PriorFBB != MBB) {
1280 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +00001281 assert(PriorCond.empty() && PriorFBB == 0 &&
1282 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +00001283 PriorTBB = MBB;
1284 } else {
1285 assert(PriorFBB == 0 && "Machine CFG out of date!");
1286 PriorFBB = MBB;
1287 }
Bill Wendling5b2749a2012-03-07 08:49:42 +00001288 DebugLoc pdl = getBranchDebugLoc(PrevBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001289 TII->RemoveBranch(PrevBB);
Bill Wendling5b2749a2012-03-07 08:49:42 +00001290 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, pdl);
Chris Lattner386e2902006-10-21 05:08:28 +00001291 }
Chris Lattner386e2902006-10-21 05:08:28 +00001292
Chris Lattnercf420cc2006-10-28 17:32:47 +00001293 // Iterate through all the predecessors, revectoring each in-turn.
David Greene8a46d342007-06-29 02:45:24 +00001294 size_t PI = 0;
Chris Lattnercf420cc2006-10-28 17:32:47 +00001295 bool DidChange = false;
1296 bool HasBranchToSelf = false;
David Greene8a46d342007-06-29 02:45:24 +00001297 while(PI != MBB->pred_size()) {
1298 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1299 if (PMBB == MBB) {
Chris Lattnercf420cc2006-10-28 17:32:47 +00001300 // If this block has an uncond branch to itself, leave it.
1301 ++PI;
1302 HasBranchToSelf = true;
1303 } else {
1304 DidChange = true;
David Greene8a46d342007-06-29 02:45:24 +00001305 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
Dale Johannesenbf06f6a2009-05-11 21:54:13 +00001306 // If this change resulted in PMBB ending in a conditional
1307 // branch where both conditions go to the same destination,
1308 // change this to an unconditional branch (and fix the CFG).
1309 MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1310 SmallVector<MachineOperand, 4> NewCurCond;
1311 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1312 NewCurFBB, NewCurCond, true);
1313 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
Bill Wendling5b2749a2012-03-07 08:49:42 +00001314 DebugLoc pdl = getBranchDebugLoc(*PMBB);
Dale Johannesenbf06f6a2009-05-11 21:54:13 +00001315 TII->RemoveBranch(*PMBB);
Dan Gohman4e3f1252009-11-11 18:38:14 +00001316 NewCurCond.clear();
Bill Wendling5b2749a2012-03-07 08:49:42 +00001317 TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond, pdl);
Dale Johannesenbf06f6a2009-05-11 21:54:13 +00001318 MadeChange = true;
1319 ++NumBranchOpts;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001320 PMBB->CorrectExtraCFGEdges(NewCurTBB, 0, false);
Dale Johannesenbf06f6a2009-05-11 21:54:13 +00001321 }
Chris Lattnercf420cc2006-10-28 17:32:47 +00001322 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001323 }
Chris Lattner386e2902006-10-21 05:08:28 +00001324
Chris Lattnercf420cc2006-10-28 17:32:47 +00001325 // Change any jumptables to go to the new MBB.
Chris Lattner071c62f2010-01-25 23:26:13 +00001326 if (MachineJumpTableInfo *MJTI = MF.getJumpTableInfo())
1327 MJTI->ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001328 if (DidChange) {
1329 ++NumBranchOpts;
1330 MadeChange = true;
Evan Cheng030a0a02009-09-04 07:47:40 +00001331 if (!HasBranchToSelf) return MadeChange;
Chris Lattnercf420cc2006-10-28 17:32:47 +00001332 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001333 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001334 }
Dan Gohman4e3f1252009-11-11 18:38:14 +00001335
Chris Lattner386e2902006-10-21 05:08:28 +00001336 // Add the branch back if the block is more than just an uncond branch.
Stuart Hastings3bf91252010-06-17 22:43:56 +00001337 TII->InsertBranch(*MBB, CurTBB, 0, CurCond, dl);
Chris Lattner21ab22e2004-07-31 10:01:27 +00001338 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001339 }
1340
Bill Wendling43cf6c32009-12-15 00:39:24 +00001341 // If the prior block doesn't fall through into this block, and if this
1342 // block doesn't fall through into some other block, see if we can find a
1343 // place to move this block where a fall-through will happen.
1344 if (!PrevBB.canFallThrough()) {
1345
Bob Wilson56ea69c2009-11-17 17:06:18 +00001346 // Now we know that there was no fall-through into this block, check to
1347 // see if it has a fall-through into its successor.
Bob Wilson15acadd2009-11-26 00:32:21 +00001348 bool CurFallsThru = MBB->canFallThrough();
Bob Wilson56ea69c2009-11-17 17:06:18 +00001349
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001350 if (!MBB->isLandingPad()) {
1351 // Check all the predecessors of this block. If one of them has no fall
1352 // throughs, move this block right after it.
1353 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1354 E = MBB->pred_end(); PI != E; ++PI) {
1355 // Analyze the branch at the end of the pred.
1356 MachineBasicBlock *PredBB = *PI;
Bill Wendling43cf6c32009-12-15 00:39:24 +00001357 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
Bill Wendling408e9d12009-12-16 00:00:18 +00001358 MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001359 SmallVector<MachineOperand, 4> PredCond;
Bill Wendling43cf6c32009-12-15 00:39:24 +00001360 if (PredBB != MBB && !PredBB->canFallThrough() &&
1361 !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond, true)
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001362 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001363 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
Bill Wendling43cf6c32009-12-15 00:39:24 +00001364 // If the current block doesn't fall through, just move it.
1365 // If the current block can fall through and does not end with a
1366 // conditional branch, we need to append an unconditional jump to
1367 // the (current) next block. To avoid a possible compile-time
1368 // infinite loop, move blocks only backward in this case.
1369 // Also, if there are already 2 branches here, we cannot add a third;
1370 // this means we have the case
1371 // Bcc next
1372 // B elsewhere
1373 // next:
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001374 if (CurFallsThru) {
Bill Wendling43cf6c32009-12-15 00:39:24 +00001375 MachineBasicBlock *NextBB = llvm::next(MachineFunction::iterator(MBB));
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001376 CurCond.clear();
Bill Wendling5b2749a2012-03-07 08:49:42 +00001377 TII->InsertBranch(*MBB, NextBB, 0, CurCond, DebugLoc());
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001378 }
1379 MBB->moveAfter(PredBB);
1380 MadeChange = true;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001381 goto ReoptimizeBlock;
Chris Lattner7d097842006-10-24 01:12:32 +00001382 }
1383 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001384 }
Dan Gohman4e3f1252009-11-11 18:38:14 +00001385
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001386 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001387 // Check all successors to see if we can move this block before it.
1388 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1389 E = MBB->succ_end(); SI != E; ++SI) {
1390 // Analyze the branch at the end of the block before the succ.
1391 MachineBasicBlock *SuccBB = *SI;
1392 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Dan Gohman4e3f1252009-11-11 18:38:14 +00001393
Chris Lattner77edc4b2007-04-30 23:35:00 +00001394 // If this block doesn't already fall-through to that successor, and if
1395 // the succ doesn't already have a block that can fall through into it,
1396 // and if the successor isn't an EH destination, we can arrange for the
1397 // fallthrough to happen.
Dan Gohman2210c0b2009-11-11 19:48:59 +00001398 if (SuccBB != MBB && &*SuccPrev != MBB &&
Bob Wilson15acadd2009-11-26 00:32:21 +00001399 !SuccPrev->canFallThrough() && !CurUnAnalyzable &&
Chris Lattner77edc4b2007-04-30 23:35:00 +00001400 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001401 MBB->moveBefore(SuccBB);
1402 MadeChange = true;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001403 goto ReoptimizeBlock;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001404 }
1405 }
Dan Gohman4e3f1252009-11-11 18:38:14 +00001406
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001407 // Okay, there is no really great place to put this block. If, however,
1408 // the block before this one would be a fall-through if this block were
1409 // removed, move this block to the end of the function.
Bill Wendlingfe586b32009-12-16 00:01:27 +00001410 MachineBasicBlock *PrevTBB = 0, *PrevFBB = 0;
Dan Gohman2210c0b2009-11-11 19:48:59 +00001411 SmallVector<MachineOperand, 4> PrevCond;
Dan Gohmand1944982009-11-11 18:18:34 +00001412 if (FallThrough != MF.end() &&
Dan Gohman2210c0b2009-11-11 19:48:59 +00001413 !TII->AnalyzeBranch(PrevBB, PrevTBB, PrevFBB, PrevCond, true) &&
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001414 PrevBB.isSuccessor(FallThrough)) {
Dan Gohmand1944982009-11-11 18:18:34 +00001415 MBB->moveAfter(--MF.end());
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001416 MadeChange = true;
Evan Cheng030a0a02009-09-04 07:47:40 +00001417 return MadeChange;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001418 }
Chris Lattner7d097842006-10-24 01:12:32 +00001419 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001420 }
Evan Cheng030a0a02009-09-04 07:47:40 +00001421
1422 return MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +00001423}
Evan Chengcbc988b2011-05-12 00:56:58 +00001424
1425//===----------------------------------------------------------------------===//
1426// Hoist Common Code
1427//===----------------------------------------------------------------------===//
1428
1429/// HoistCommonCode - Hoist common instruction sequences at the start of basic
1430/// blocks to their common predecessor.
Evan Chengcbc988b2011-05-12 00:56:58 +00001431bool BranchFolder::HoistCommonCode(MachineFunction &MF) {
1432 bool MadeChange = false;
1433 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ) {
1434 MachineBasicBlock *MBB = I++;
1435 MadeChange |= HoistCommonCodeInSuccs(MBB);
1436 }
1437
1438 return MadeChange;
1439}
1440
1441/// findFalseBlock - BB has a fallthrough. Find its 'false' successor given
1442/// its 'true' successor.
1443static MachineBasicBlock *findFalseBlock(MachineBasicBlock *BB,
1444 MachineBasicBlock *TrueBB) {
1445 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
1446 E = BB->succ_end(); SI != E; ++SI) {
1447 MachineBasicBlock *SuccBB = *SI;
1448 if (SuccBB != TrueBB)
1449 return SuccBB;
1450 }
1451 return NULL;
1452}
1453
1454/// findHoistingInsertPosAndDeps - Find the location to move common instructions
1455/// in successors to. The location is ususally just before the terminator,
1456/// however if the terminator is a conditional branch and its previous
1457/// instruction is the flag setting instruction, the previous instruction is
1458/// the preferred location. This function also gathers uses and defs of the
1459/// instructions from the insertion point to the end of the block. The data is
1460/// used by HoistCommonCodeInSuccs to ensure safety.
1461static
1462MachineBasicBlock::iterator findHoistingInsertPosAndDeps(MachineBasicBlock *MBB,
1463 const TargetInstrInfo *TII,
1464 const TargetRegisterInfo *TRI,
1465 SmallSet<unsigned,4> &Uses,
1466 SmallSet<unsigned,4> &Defs) {
1467 MachineBasicBlock::iterator Loc = MBB->getFirstTerminator();
1468 if (!TII->isUnpredicatedTerminator(Loc))
1469 return MBB->end();
1470
1471 for (unsigned i = 0, e = Loc->getNumOperands(); i != e; ++i) {
1472 const MachineOperand &MO = Loc->getOperand(i);
1473 if (!MO.isReg())
1474 continue;
1475 unsigned Reg = MO.getReg();
1476 if (!Reg)
1477 continue;
1478 if (MO.isUse()) {
1479 Uses.insert(Reg);
Craig Toppere4fd9072012-03-04 10:43:23 +00001480 for (const uint16_t *AS = TRI->getAliasSet(Reg); *AS; ++AS)
Evan Chengcbc988b2011-05-12 00:56:58 +00001481 Uses.insert(*AS);
1482 } else if (!MO.isDead())
1483 // Don't try to hoist code in the rare case the terminator defines a
1484 // register that is later used.
1485 return MBB->end();
1486 }
1487
1488 if (Uses.empty())
1489 return Loc;
1490 if (Loc == MBB->begin())
1491 return MBB->end();
1492
1493 // The terminator is probably a conditional branch, try not to separate the
1494 // branch from condition setting instruction.
1495 MachineBasicBlock::iterator PI = Loc;
1496 --PI;
1497 while (PI != MBB->begin() && Loc->isDebugValue())
1498 --PI;
1499
1500 bool IsDef = false;
1501 for (unsigned i = 0, e = PI->getNumOperands(); !IsDef && i != e; ++i) {
1502 const MachineOperand &MO = PI->getOperand(i);
Jakob Stoklund Olesena2302622012-02-15 23:42:54 +00001503 // If PI has a regmask operand, it is probably a call. Separate away.
1504 if (MO.isRegMask())
1505 return Loc;
Evan Chengcbc988b2011-05-12 00:56:58 +00001506 if (!MO.isReg() || MO.isUse())
1507 continue;
1508 unsigned Reg = MO.getReg();
1509 if (!Reg)
1510 continue;
1511 if (Uses.count(Reg))
1512 IsDef = true;
1513 }
1514 if (!IsDef)
1515 // The condition setting instruction is not just before the conditional
1516 // branch.
1517 return Loc;
1518
1519 // Be conservative, don't insert instruction above something that may have
1520 // side-effects. And since it's potentially bad to separate flag setting
1521 // instruction from the conditional branch, just abort the optimization
1522 // completely.
1523 // Also avoid moving code above predicated instruction since it's hard to
1524 // reason about register liveness with predicated instruction.
1525 bool DontMoveAcrossStore = true;
1526 if (!PI->isSafeToMove(TII, 0, DontMoveAcrossStore) ||
1527 TII->isPredicated(PI))
1528 return MBB->end();
1529
1530
1531 // Find out what registers are live. Note this routine is ignoring other live
1532 // registers which are only used by instructions in successor blocks.
1533 for (unsigned i = 0, e = PI->getNumOperands(); i != e; ++i) {
1534 const MachineOperand &MO = PI->getOperand(i);
1535 if (!MO.isReg())
1536 continue;
1537 unsigned Reg = MO.getReg();
1538 if (!Reg)
1539 continue;
1540 if (MO.isUse()) {
1541 Uses.insert(Reg);
Craig Toppere4fd9072012-03-04 10:43:23 +00001542 for (const uint16_t *AS = TRI->getAliasSet(Reg); *AS; ++AS)
Evan Chengcbc988b2011-05-12 00:56:58 +00001543 Uses.insert(*AS);
1544 } else {
1545 if (Uses.count(Reg)) {
1546 Uses.erase(Reg);
Craig Topper9ebfbf82012-03-05 05:37:41 +00001547 for (const uint16_t *SR = TRI->getSubRegisters(Reg); *SR; ++SR)
Evan Chengcbc988b2011-05-12 00:56:58 +00001548 Uses.erase(*SR); // Use getSubRegisters to be conservative
Evan Chengcbc988b2011-05-12 00:56:58 +00001549 }
Evan Cheng7139d352011-05-12 20:30:01 +00001550 Defs.insert(Reg);
Craig Toppere4fd9072012-03-04 10:43:23 +00001551 for (const uint16_t *AS = TRI->getAliasSet(Reg); *AS; ++AS)
Evan Cheng7139d352011-05-12 20:30:01 +00001552 Defs.insert(*AS);
Evan Chengcbc988b2011-05-12 00:56:58 +00001553 }
1554 }
1555
1556 return PI;
1557}
1558
1559/// HoistCommonCodeInSuccs - If the successors of MBB has common instruction
1560/// sequence at the start of the function, move the instructions before MBB
1561/// terminator if it's legal.
1562bool BranchFolder::HoistCommonCodeInSuccs(MachineBasicBlock *MBB) {
1563 MachineBasicBlock *TBB = 0, *FBB = 0;
1564 SmallVector<MachineOperand, 4> Cond;
1565 if (TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true) || !TBB || Cond.empty())
1566 return false;
1567
1568 if (!FBB) FBB = findFalseBlock(MBB, TBB);
1569 if (!FBB)
1570 // Malformed bcc? True and false blocks are the same?
1571 return false;
1572
1573 // Restrict the optimization to cases where MBB is the only predecessor,
1574 // it is an obvious win.
1575 if (TBB->pred_size() > 1 || FBB->pred_size() > 1)
1576 return false;
1577
1578 // Find a suitable position to hoist the common instructions to. Also figure
1579 // out which registers are used or defined by instructions from the insertion
1580 // point to the end of the block.
1581 SmallSet<unsigned, 4> Uses, Defs;
1582 MachineBasicBlock::iterator Loc =
1583 findHoistingInsertPosAndDeps(MBB, TII, TRI, Uses, Defs);
1584 if (Loc == MBB->end())
1585 return false;
1586
1587 bool HasDups = false;
Evan Cheng7139d352011-05-12 20:30:01 +00001588 SmallVector<unsigned, 4> LocalDefs;
1589 SmallSet<unsigned, 4> LocalDefsSet;
Evan Chengcbc988b2011-05-12 00:56:58 +00001590 MachineBasicBlock::iterator TIB = TBB->begin();
1591 MachineBasicBlock::iterator FIB = FBB->begin();
1592 MachineBasicBlock::iterator TIE = TBB->end();
1593 MachineBasicBlock::iterator FIE = FBB->end();
1594 while (TIB != TIE && FIB != FIE) {
1595 // Skip dbg_value instructions. These do not count.
1596 if (TIB->isDebugValue()) {
1597 while (TIB != TIE && TIB->isDebugValue())
1598 ++TIB;
1599 if (TIB == TIE)
1600 break;
1601 }
1602 if (FIB->isDebugValue()) {
1603 while (FIB != FIE && FIB->isDebugValue())
1604 ++FIB;
1605 if (FIB == FIE)
1606 break;
1607 }
1608 if (!TIB->isIdenticalTo(FIB, MachineInstr::CheckKillDead))
1609 break;
1610
1611 if (TII->isPredicated(TIB))
1612 // Hard to reason about register liveness with predicated instruction.
1613 break;
1614
1615 bool IsSafe = true;
1616 for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1617 MachineOperand &MO = TIB->getOperand(i);
Jakob Stoklund Olesena2302622012-02-15 23:42:54 +00001618 // Don't attempt to hoist instructions with register masks.
1619 if (MO.isRegMask()) {
1620 IsSafe = false;
1621 break;
1622 }
Evan Chengcbc988b2011-05-12 00:56:58 +00001623 if (!MO.isReg())
1624 continue;
1625 unsigned Reg = MO.getReg();
1626 if (!Reg)
1627 continue;
1628 if (MO.isDef()) {
1629 if (Uses.count(Reg)) {
1630 // Avoid clobbering a register that's used by the instruction at
1631 // the point of insertion.
1632 IsSafe = false;
1633 break;
1634 }
1635
1636 if (Defs.count(Reg) && !MO.isDead()) {
1637 // Don't hoist the instruction if the def would be clobber by the
1638 // instruction at the point insertion. FIXME: This is overly
1639 // conservative. It should be possible to hoist the instructions
1640 // in BB2 in the following example:
1641 // BB1:
1642 // r1, eflag = op1 r2, r3
1643 // brcc eflag
1644 //
1645 // BB2:
1646 // r1 = op2, ...
1647 // = op3, r1<kill>
1648 IsSafe = false;
1649 break;
1650 }
Evan Cheng7139d352011-05-12 20:30:01 +00001651 } else if (!LocalDefsSet.count(Reg)) {
Evan Chengcbc988b2011-05-12 00:56:58 +00001652 if (Defs.count(Reg)) {
1653 // Use is defined by the instruction at the point of insertion.
1654 IsSafe = false;
1655 break;
1656 }
Evan Chengc16c25f2012-01-12 20:31:24 +00001657
1658 if (MO.isKill() && Uses.count(Reg))
1659 // Kills a register that's read by the instruction at the point of
1660 // insertion. Remove the kill marker.
1661 MO.setIsKill(false);
Evan Chengcbc988b2011-05-12 00:56:58 +00001662 }
1663 }
1664 if (!IsSafe)
1665 break;
1666
1667 bool DontMoveAcrossStore = true;
1668 if (!TIB->isSafeToMove(TII, 0, DontMoveAcrossStore))
1669 break;
1670
Jakob Stoklund Olesen54cfeda2011-08-05 18:47:07 +00001671 // Remove kills from LocalDefsSet, these registers had short live ranges.
1672 for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1673 MachineOperand &MO = TIB->getOperand(i);
1674 if (!MO.isReg() || !MO.isUse() || !MO.isKill())
1675 continue;
1676 unsigned Reg = MO.getReg();
1677 if (!Reg || !LocalDefsSet.count(Reg))
1678 continue;
Craig Toppere4fd9072012-03-04 10:43:23 +00001679 for (const uint16_t *OR = TRI->getOverlaps(Reg); *OR; ++OR)
Jakob Stoklund Olesen54cfeda2011-08-05 18:47:07 +00001680 LocalDefsSet.erase(*OR);
1681 }
1682
Evan Cheng7139d352011-05-12 20:30:01 +00001683 // Track local defs so we can update liveins.
1684 for (unsigned i = 0, e = TIB->getNumOperands(); i != e; ++i) {
1685 MachineOperand &MO = TIB->getOperand(i);
Jakob Stoklund Olesen54cfeda2011-08-05 18:47:07 +00001686 if (!MO.isReg() || !MO.isDef() || MO.isDead())
Evan Cheng7139d352011-05-12 20:30:01 +00001687 continue;
1688 unsigned Reg = MO.getReg();
1689 if (!Reg)
1690 continue;
Jakob Stoklund Olesen54cfeda2011-08-05 18:47:07 +00001691 LocalDefs.push_back(Reg);
Craig Toppere4fd9072012-03-04 10:43:23 +00001692 for (const uint16_t *OR = TRI->getOverlaps(Reg); *OR; ++OR)
Jakob Stoklund Olesen54cfeda2011-08-05 18:47:07 +00001693 LocalDefsSet.insert(*OR);
Evan Cheng7139d352011-05-12 20:30:01 +00001694 }
1695
Chad Rosier90f20042012-02-22 17:25:00 +00001696 HasDups = true;
Evan Chengcbc988b2011-05-12 00:56:58 +00001697 ++TIB;
1698 ++FIB;
1699 }
1700
1701 if (!HasDups)
1702 return false;
1703
1704 MBB->splice(Loc, TBB, TBB->begin(), TIB);
1705 FBB->erase(FBB->begin(), FIB);
Evan Cheng7139d352011-05-12 20:30:01 +00001706
1707 // Update livein's.
1708 for (unsigned i = 0, e = LocalDefs.size(); i != e; ++i) {
1709 unsigned Def = LocalDefs[i];
1710 if (LocalDefsSet.count(Def)) {
1711 TBB->addLiveIn(Def);
1712 FBB->addLiveIn(Def);
1713 }
1714 }
1715
Evan Chengcbc988b2011-05-12 00:56:58 +00001716 ++NumHoist;
1717 return true;
1718}