blob: 66c5aa5ff784e84b6a2648276ac9d63b52dd9ec3 [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"
Chris Lattner21ab22e2004-07-31 10:01:27 +000021#include "llvm/CodeGen/Passes.h"
Jim Laskey44c3b9f2007-01-26 21:22:28 +000022#include "llvm/CodeGen/MachineModuleInfo.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000024#include "llvm/CodeGen/MachineJumpTableInfo.h"
Dale Johannesen69cb9b72007-03-20 21:35:06 +000025#include "llvm/CodeGen/RegisterScavenging.h"
Chris Lattner21ab22e2004-07-31 10:01:27 +000026#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
Dan Gohman6f0d0242008-02-10 18:45:23 +000028#include "llvm/Target/TargetRegisterInfo.h"
Chris Lattner12143052006-10-21 00:47:49 +000029#include "llvm/Support/CommandLine.h"
Chris Lattnerf10a56a2006-11-18 21:56:39 +000030#include "llvm/Support/Debug.h"
Torok Edwinc25e7582009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Bill Wendling3403bcd2009-08-22 20:03:00 +000032#include "llvm/Support/raw_ostream.h"
Evan Cheng80b09fe2008-04-10 02:32:10 +000033#include "llvm/ADT/SmallSet.h"
Chris Lattner12143052006-10-21 00:47:49 +000034#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000035#include "llvm/ADT/STLExtras.h"
Jeff Cohend41b30d2006-11-05 19:31:28 +000036#include <algorithm>
Chris Lattner21ab22e2004-07-31 10:01:27 +000037using namespace llvm;
38
Chris Lattnercd3245a2006-12-19 22:41:21 +000039STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
40STATISTIC(NumBranchOpts, "Number of branches optimized");
41STATISTIC(NumTailMerge , "Number of block tails merged");
Dale Johannesen81da02b2007-05-22 17:14:46 +000042static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
43 cl::init(cl::BOU_UNSET), cl::Hidden);
Dan Gohman844731a2008-05-13 00:00:25 +000044// Throttle for huge numbers of predecessors (compile speed problems)
45static cl::opt<unsigned>
46TailMergeThreshold("tail-merge-threshold",
47 cl::desc("Max number of predecessors to consider tail merging"),
Dale Johannesen622addb2008-10-27 02:10:21 +000048 cl::init(150), cl::Hidden);
Dale Johannesen1a90a5a2007-06-08 01:08:52 +000049
Devang Patel794fd752007-05-01 21:15:47 +000050
Evan Cheng030a0a02009-09-04 07:47:40 +000051char BranchFolderPass::ID = 0;
Chris Lattner21ab22e2004-07-31 10:01:27 +000052
Bob Wilsona5971032009-10-28 20:46:46 +000053FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
54 return new BranchFolderPass(DefaultEnableTailMerge);
Evan Cheng030a0a02009-09-04 07:47:40 +000055}
56
57bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
58 return OptimizeFunction(MF,
59 MF.getTarget().getInstrInfo(),
60 MF.getTarget().getRegisterInfo(),
61 getAnalysisIfAvailable<MachineModuleInfo>());
62}
63
64
65
Bob Wilsona5971032009-10-28 20:46:46 +000066BranchFolder::BranchFolder(bool defaultEnableTailMerge) {
Evan Cheng030a0a02009-09-04 07:47:40 +000067 switch (FlagEnableTailMerge) {
68 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
69 case cl::BOU_TRUE: EnableTailMerge = true; break;
70 case cl::BOU_FALSE: EnableTailMerge = false; break;
71 }
Evan Chengb3c27422009-09-03 23:54:22 +000072}
Chris Lattner21ab22e2004-07-31 10:01:27 +000073
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000074/// RemoveDeadBlock - Remove the specified dead machine basic block from the
75/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000076void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +000077 assert(MBB->pred_empty() && "MBB must be dead!");
Bill Wendling3403bcd2009-08-22 20:03:00 +000078 DEBUG(errs() << "\nRemoving MBB: " << *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000079
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000080 MachineFunction *MF = MBB->getParent();
81 // drop all successors.
82 while (!MBB->succ_empty())
83 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000084
Duncan Sands68d4d1d2008-07-29 20:56:02 +000085 // If there are any labels in the basic block, unregister them from
86 // MachineModuleInfo.
Jim Laskey44c3b9f2007-01-26 21:22:28 +000087 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +000088 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
89 I != E; ++I) {
Duncan Sands68d4d1d2008-07-29 20:56:02 +000090 if (I->isLabel())
Chris Lattner683747a2006-10-17 23:17:27 +000091 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +000092 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000093 }
94 }
95
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000096 // Remove the block.
Dan Gohman8e5f2c62008-07-07 23:14:23 +000097 MF->erase(MBB);
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000098}
99
Evan Cheng80b09fe2008-04-10 02:32:10 +0000100/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
101/// followed by terminators, and if the implicitly defined registers are not
102/// used by the terminators, remove those implicit_def's. e.g.
103/// BB1:
104/// r0 = implicit_def
105/// r1 = implicit_def
106/// br
107/// This block can be optimized away later if the implicit instructions are
108/// removed.
109bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
110 SmallSet<unsigned, 4> ImpDefRegs;
111 MachineBasicBlock::iterator I = MBB->begin();
112 while (I != MBB->end()) {
113 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
114 break;
115 unsigned Reg = I->getOperand(0).getReg();
116 ImpDefRegs.insert(Reg);
Evan Cheng030a0a02009-09-04 07:47:40 +0000117 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
Evan Cheng80b09fe2008-04-10 02:32:10 +0000118 unsigned SubReg = *SubRegs; ++SubRegs)
119 ImpDefRegs.insert(SubReg);
120 ++I;
121 }
122 if (ImpDefRegs.empty())
123 return false;
124
125 MachineBasicBlock::iterator FirstTerm = I;
126 while (I != MBB->end()) {
127 if (!TII->isUnpredicatedTerminator(I))
128 return false;
129 // See if it uses any of the implicitly defined registers.
130 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
131 MachineOperand &MO = I->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000132 if (!MO.isReg() || !MO.isUse())
Evan Cheng80b09fe2008-04-10 02:32:10 +0000133 continue;
134 unsigned Reg = MO.getReg();
135 if (ImpDefRegs.count(Reg))
136 return false;
137 }
138 ++I;
139 }
140
141 I = MBB->begin();
142 while (I != FirstTerm) {
143 MachineInstr *ImpDefMI = &*I;
144 ++I;
145 MBB->erase(ImpDefMI);
146 }
147
148 return true;
149}
150
Evan Cheng030a0a02009-09-04 07:47:40 +0000151/// OptimizeFunction - Perhaps branch folding, tail merging and other
152/// CFG optimizations on the given function.
153bool BranchFolder::OptimizeFunction(MachineFunction &MF,
154 const TargetInstrInfo *tii,
155 const TargetRegisterInfo *tri,
156 MachineModuleInfo *mmi) {
157 if (!tii) return false;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000158
Evan Cheng030a0a02009-09-04 07:47:40 +0000159 TII = tii;
160 TRI = tri;
161 MMI = mmi;
162
163 RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
Evan Cheng80b09fe2008-04-10 02:32:10 +0000164
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000165 // Fix CFG. The later algorithms expect it to be right.
Evan Cheng030a0a02009-09-04 07:47:40 +0000166 bool MadeChange = false;
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000167 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
168 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000169 SmallVector<MachineOperand, 4> Cond;
Evan Chengdc54d312009-02-09 07:14:22 +0000170 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
Evan Cheng030a0a02009-09-04 07:47:40 +0000171 MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
172 MadeChange |= OptimizeImpDefsBlock(MBB);
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000173 }
174
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000175
Chris Lattner12143052006-10-21 00:47:49 +0000176 bool MadeChangeThisIteration = true;
177 while (MadeChangeThisIteration) {
178 MadeChangeThisIteration = false;
179 MadeChangeThisIteration |= TailMergeBlocks(MF);
180 MadeChangeThisIteration |= OptimizeBranches(MF);
Evan Cheng030a0a02009-09-04 07:47:40 +0000181 MadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000182 }
183
Chris Lattner6acfe122006-10-28 18:34:47 +0000184 // See if any jump tables have become mergable or dead as the code generator
185 // did its thing.
186 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
187 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
188 if (!JTs.empty()) {
189 // Figure out how these jump tables should be merged.
190 std::vector<unsigned> JTMapping;
191 JTMapping.reserve(JTs.size());
192
193 // We always keep the 0th jump table.
194 JTMapping.push_back(0);
195
196 // Scan the jump tables, seeing if there are any duplicates. Note that this
197 // is N^2, which should be fixed someday.
Evan Cheng030a0a02009-09-04 07:47:40 +0000198 for (unsigned i = 1, e = JTs.size(); i != e; ++i) {
199 if (JTs[i].MBBs.empty())
200 JTMapping.push_back(i);
201 else
202 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
203 }
Chris Lattner6acfe122006-10-28 18:34:47 +0000204
205 // If a jump table was merge with another one, walk the function rewriting
206 // references to jump tables to reference the new JT ID's. Keep track of
207 // whether we see a jump table idx, if not, we can delete the JT.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000208 BitVector JTIsLive(JTs.size());
Chris Lattner6acfe122006-10-28 18:34:47 +0000209 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
210 BB != E; ++BB) {
211 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
212 I != E; ++I)
213 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
214 MachineOperand &Op = I->getOperand(op);
Dan Gohmand735b802008-10-03 15:45:36 +0000215 if (!Op.isJTI()) continue;
Chris Lattner8aa797a2007-12-30 23:10:15 +0000216 unsigned NewIdx = JTMapping[Op.getIndex()];
217 Op.setIndex(NewIdx);
Chris Lattner6acfe122006-10-28 18:34:47 +0000218
219 // Remember that this JT is live.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000220 JTIsLive.set(NewIdx);
Chris Lattner6acfe122006-10-28 18:34:47 +0000221 }
222 }
223
224 // Finally, remove dead jump tables. This happens either because the
225 // indirect jump was unreachable (and thus deleted) or because the jump
226 // table was merged with some other one.
227 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000228 if (!JTIsLive.test(i)) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000229 JTI->RemoveJumpTable(i);
Evan Cheng030a0a02009-09-04 07:47:40 +0000230 MadeChange = true;
Chris Lattner6acfe122006-10-28 18:34:47 +0000231 }
232 }
Evan Cheng030a0a02009-09-04 07:47:40 +0000233
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000234 delete RS;
Evan Cheng030a0a02009-09-04 07:47:40 +0000235 return MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000236}
237
Chris Lattner12143052006-10-21 00:47:49 +0000238//===----------------------------------------------------------------------===//
239// Tail Merging of Blocks
240//===----------------------------------------------------------------------===//
241
242/// HashMachineInstr - Compute a hash value for MI and its operands.
243static unsigned HashMachineInstr(const MachineInstr *MI) {
244 unsigned Hash = MI->getOpcode();
245 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
246 const MachineOperand &Op = MI->getOperand(i);
247
248 // Merge in bits from the operand if easy.
249 unsigned OperandHash = 0;
250 switch (Op.getType()) {
251 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
252 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
253 case MachineOperand::MO_MachineBasicBlock:
Chris Lattner8aa797a2007-12-30 23:10:15 +0000254 OperandHash = Op.getMBB()->getNumber();
Chris Lattner12143052006-10-21 00:47:49 +0000255 break;
Chris Lattner8aa797a2007-12-30 23:10:15 +0000256 case MachineOperand::MO_FrameIndex:
Chris Lattner12143052006-10-21 00:47:49 +0000257 case MachineOperand::MO_ConstantPoolIndex:
Chris Lattner12143052006-10-21 00:47:49 +0000258 case MachineOperand::MO_JumpTableIndex:
Chris Lattner8aa797a2007-12-30 23:10:15 +0000259 OperandHash = Op.getIndex();
Chris Lattner12143052006-10-21 00:47:49 +0000260 break;
261 case MachineOperand::MO_GlobalAddress:
262 case MachineOperand::MO_ExternalSymbol:
263 // Global address / external symbol are too hard, don't bother, but do
264 // pull in the offset.
265 OperandHash = Op.getOffset();
266 break;
267 default: break;
268 }
269
270 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
271 }
272 return Hash;
273}
274
Dale Johannesen7aea8322007-05-23 21:07:20 +0000275/// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
276/// with no successors, we hash two instructions, because cross-jumping
277/// only saves code when at least two instructions are removed (since a
278/// branch must be inserted). For blocks with a successor, one of the
279/// two blocks to be tail-merged will end with a branch already, so
280/// it gains to cross-jump even for one instruction.
281
282static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
283 unsigned minCommonTailLength) {
Chris Lattner12143052006-10-21 00:47:49 +0000284 MachineBasicBlock::const_iterator I = MBB->end();
285 if (I == MBB->begin())
286 return 0; // Empty MBB.
287
288 --I;
289 unsigned Hash = HashMachineInstr(I);
290
Dale Johannesen7aea8322007-05-23 21:07:20 +0000291 if (I == MBB->begin() || minCommonTailLength == 1)
Chris Lattner12143052006-10-21 00:47:49 +0000292 return Hash; // Single instr MBB.
293
294 --I;
295 // Hash in the second-to-last instruction.
296 Hash ^= HashMachineInstr(I) << 2;
297 return Hash;
298}
299
300/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
301/// of instructions they actually have in common together at their end. Return
302/// iterators for the first shared instruction in each block.
303static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
304 MachineBasicBlock *MBB2,
305 MachineBasicBlock::iterator &I1,
306 MachineBasicBlock::iterator &I2) {
307 I1 = MBB1->end();
308 I2 = MBB2->end();
309
310 unsigned TailLen = 0;
311 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
312 --I1; --I2;
Bill Wendling80629c82007-10-19 21:09:55 +0000313 if (!I1->isIdenticalTo(I2) ||
Bill Wendlingda6efc52007-10-25 19:49:32 +0000314 // FIXME: This check is dubious. It's used to get around a problem where
Bill Wendling0713a222007-10-25 18:23:45 +0000315 // people incorrectly expect inline asm directives to remain in the same
316 // relative order. This is untenable because normal compiler
317 // optimizations (like this one) may reorder and/or merge these
318 // directives.
Bill Wendling80629c82007-10-19 21:09:55 +0000319 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
Chris Lattner12143052006-10-21 00:47:49 +0000320 ++I1; ++I2;
321 break;
322 }
323 ++TailLen;
324 }
325 return TailLen;
326}
327
328/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000329/// after it, replacing it with an unconditional branch to NewDest. This
330/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000331void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
332 MachineBasicBlock *NewDest) {
333 MachineBasicBlock *OldBB = OldInst->getParent();
334
335 // Remove all the old successors of OldBB from the CFG.
336 while (!OldBB->succ_empty())
337 OldBB->removeSuccessor(OldBB->succ_begin());
338
339 // Remove all the dead instructions from the end of OldBB.
340 OldBB->erase(OldInst, OldBB->end());
341
Chris Lattner386e2902006-10-21 05:08:28 +0000342 // If OldBB isn't immediately before OldBB, insert a branch to it.
343 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
Dan Gohman1501cdb2008-08-22 16:07:55 +0000344 TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
Chris Lattner12143052006-10-21 00:47:49 +0000345 OldBB->addSuccessor(NewDest);
346 ++NumTailMerge;
347}
348
Chris Lattner1d08d832006-11-01 01:16:12 +0000349/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
350/// MBB so that the part before the iterator falls into the part starting at the
351/// iterator. This returns the new MBB.
352MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
353 MachineBasicBlock::iterator BBI1) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000354 MachineFunction &MF = *CurMBB.getParent();
355
Chris Lattner1d08d832006-11-01 01:16:12 +0000356 // Create the fall-through block.
357 MachineFunction::iterator MBBI = &CurMBB;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000358 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
359 CurMBB.getParent()->insert(++MBBI, NewMBB);
Chris Lattner1d08d832006-11-01 01:16:12 +0000360
361 // Move all the successors of this block to the specified block.
Dan Gohman04478e52008-06-19 17:22:29 +0000362 NewMBB->transferSuccessors(&CurMBB);
Chris Lattner1d08d832006-11-01 01:16:12 +0000363
364 // Add an edge from CurMBB to NewMBB for the fall-through.
365 CurMBB.addSuccessor(NewMBB);
366
367 // Splice the code over.
368 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000369
370 // For targets that use the register scavenger, we must maintain LiveIns.
371 if (RS) {
372 RS->enterBasicBlock(&CurMBB);
373 if (!CurMBB.empty())
374 RS->forward(prior(CurMBB.end()));
Evan Cheng030a0a02009-09-04 07:47:40 +0000375 BitVector RegsLiveAtExit(TRI->getNumRegs());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000376 RS->getRegsUsed(RegsLiveAtExit, false);
Evan Cheng030a0a02009-09-04 07:47:40 +0000377 for (unsigned int i=0, e=TRI->getNumRegs(); i!=e; i++)
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000378 if (RegsLiveAtExit[i])
379 NewMBB->addLiveIn(i);
380 }
381
Chris Lattner1d08d832006-11-01 01:16:12 +0000382 return NewMBB;
383}
384
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000385/// EstimateRuntime - Make a rough estimate for how long it will take to run
386/// the specified code.
387static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
Chris Lattner69244302008-01-07 01:56:04 +0000388 MachineBasicBlock::iterator E) {
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000389 unsigned Time = 0;
390 for (; I != E; ++I) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000391 const TargetInstrDesc &TID = I->getDesc();
392 if (TID.isCall())
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000393 Time += 10;
Dan Gohman41474ba2008-12-03 02:30:17 +0000394 else if (TID.mayLoad() || TID.mayStore())
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000395 Time += 2;
396 else
397 ++Time;
398 }
399 return Time;
400}
401
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000402// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
403// branches temporarily for tail merging). In the case where CurMBB ends
404// with a conditional branch to the next block, optimize by reversing the
405// test and conditionally branching to SuccMBB instead.
406
407static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
408 const TargetInstrInfo *TII) {
409 MachineFunction *MF = CurMBB->getParent();
410 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
411 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000412 SmallVector<MachineOperand, 4> Cond;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000413 if (I != MF->end() &&
Evan Chengdc54d312009-02-09 07:14:22 +0000414 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000415 MachineBasicBlock *NextBB = I;
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000416 if (TBB == NextBB && !Cond.empty() && !FBB) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000417 if (!TII->ReverseBranchCondition(Cond)) {
418 TII->RemoveBranch(*CurMBB);
419 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
420 return;
421 }
422 }
423 }
Dan Gohman1501cdb2008-08-22 16:07:55 +0000424 TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000425}
426
Dale Johannesen44008c52007-05-30 00:32:01 +0000427static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
428 const std::pair<unsigned,MachineBasicBlock*> &q) {
Dale Johannesen95ef4062007-05-29 23:47:50 +0000429 if (p.first < q.first)
430 return true;
431 else if (p.first > q.first)
432 return false;
433 else if (p.second->getNumber() < q.second->getNumber())
434 return true;
435 else if (p.second->getNumber() > q.second->getNumber())
436 return false;
David Greene67fcdf72007-07-10 22:00:30 +0000437 else {
Duncan Sands97b4ac82007-07-11 08:47:55 +0000438 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
439 // an object with itself.
440#ifndef _GLIBCXX_DEBUG
Torok Edwinc23197a2009-07-14 16:55:14 +0000441 llvm_unreachable("Predecessor appears twice");
David Greene67fcdf72007-07-10 22:00:30 +0000442#endif
Dan Gohman5d5ee802009-01-08 22:19:34 +0000443 return false;
David Greene67fcdf72007-07-10 22:00:30 +0000444 }
Dale Johannesen95ef4062007-05-29 23:47:50 +0000445}
446
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000447/// ComputeSameTails - Look through all the blocks in MergePotentials that have
448/// hash CurHash (guaranteed to match the last element). Build the vector
449/// SameTails of all those that have the (same) largest number of instructions
450/// in common of any pair of these blocks. SameTails entries contain an
451/// iterator into MergePotentials (from which the MachineBasicBlock can be
452/// found) and a MachineBasicBlock::iterator into that MBB indicating the
453/// instruction where the matching code sequence begins.
454/// Order of elements in SameTails is the reverse of the order in which
455/// those blocks appear in MergePotentials (where they are not necessarily
456/// consecutive).
457unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
458 unsigned minCommonTailLength) {
459 unsigned maxCommonTailLength = 0U;
460 SameTails.clear();
461 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
462 MPIterator HighestMPIter = prior(MergePotentials.end());
463 for (MPIterator CurMPIter = prior(MergePotentials.end()),
464 B = MergePotentials.begin();
465 CurMPIter!=B && CurMPIter->first==CurHash;
466 --CurMPIter) {
467 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
468 unsigned CommonTailLen = ComputeCommonTailLength(
469 CurMPIter->second,
470 I->second,
471 TrialBBI1, TrialBBI2);
Dale Johannesen30562b72008-05-12 22:53:12 +0000472 // If we will have to split a block, there should be at least
Bob Wilsona5971032009-10-28 20:46:46 +0000473 // minCommonTailLength instructions in common; if not, at worst
Dale Johannesen30562b72008-05-12 22:53:12 +0000474 // we will be replacing a fallthrough into the common tail with a
475 // branch, which at worst breaks even with falling through into
476 // the duplicated common tail, so 1 instruction in common is enough.
477 // We will always pick a block we do not have to split as the common
478 // tail if there is one.
479 // (Empty blocks will get forwarded and need not be considered.)
480 if (CommonTailLen >= minCommonTailLength ||
Bob Wilsona5971032009-10-28 20:46:46 +0000481 (CommonTailLen > 0 &&
Dale Johannesen30562b72008-05-12 22:53:12 +0000482 (TrialBBI1==CurMPIter->second->begin() ||
483 TrialBBI2==I->second->begin()))) {
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000484 if (CommonTailLen > maxCommonTailLength) {
485 SameTails.clear();
486 maxCommonTailLength = CommonTailLen;
487 HighestMPIter = CurMPIter;
488 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
489 }
490 if (HighestMPIter == CurMPIter &&
491 CommonTailLen == maxCommonTailLength)
492 SameTails.push_back(std::make_pair(I, TrialBBI2));
493 }
494 if (I==B)
495 break;
496 }
497 }
498 return maxCommonTailLength;
499}
500
501/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
502/// MergePotentials, restoring branches at ends of blocks as appropriate.
503void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
504 MachineBasicBlock* SuccBB,
505 MachineBasicBlock* PredBB) {
Dale Johannesen679860e2008-05-23 17:19:02 +0000506 MPIterator CurMPIter, B;
507 for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000508 CurMPIter->first==CurHash;
509 --CurMPIter) {
510 // Put the unconditional branch back, if we need one.
511 MachineBasicBlock *CurMBB = CurMPIter->second;
512 if (SuccBB && CurMBB != PredBB)
513 FixTail(CurMBB, SuccBB, TII);
Dale Johannesen679860e2008-05-23 17:19:02 +0000514 if (CurMPIter==B)
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000515 break;
516 }
Dale Johannesen679860e2008-05-23 17:19:02 +0000517 if (CurMPIter->first!=CurHash)
518 CurMPIter++;
519 MergePotentials.erase(CurMPIter, MergePotentials.end());
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000520}
521
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000522/// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
523/// only of the common tail. Create a block that does by splitting one.
524unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
525 unsigned maxCommonTailLength) {
526 unsigned i, commonTailIndex;
527 unsigned TimeEstimate = ~0U;
528 for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
529 // Use PredBB if possible; that doesn't require a new branch.
530 if (SameTails[i].first->second==PredBB) {
531 commonTailIndex = i;
532 break;
533 }
534 // Otherwise, make a (fairly bogus) choice based on estimate of
535 // how long it will take the various blocks to execute.
536 unsigned t = EstimateRuntime(SameTails[i].first->second->begin(),
537 SameTails[i].second);
538 if (t<=TimeEstimate) {
539 TimeEstimate = t;
540 commonTailIndex = i;
541 }
542 }
543
544 MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
545 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
546
Bill Wendling3403bcd2009-08-22 20:03:00 +0000547 DEBUG(errs() << "\nSplitting " << MBB->getNumber() << ", size "
548 << maxCommonTailLength);
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000549
550 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
551 SameTails[commonTailIndex].first->second = newMBB;
552 SameTails[commonTailIndex].second = newMBB->begin();
553 // If we split PredBB, newMBB is the new predecessor.
554 if (PredBB==MBB)
555 PredBB = newMBB;
556
557 return commonTailIndex;
558}
559
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000560// See if any of the blocks in MergePotentials (which all have a common single
561// successor, or all have no successor) can be tail-merged. If there is a
562// successor, any blocks in MergePotentials that are not tail-merged and
563// are not immediately before Succ must have an unconditional branch to
564// Succ added (but the predecessor/successor lists need no adjustment).
565// The lone predecessor of Succ that falls through into Succ,
566// if any, is given in PredBB.
567
568bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
569 MachineBasicBlock* PredBB) {
Evan Cheng030a0a02009-09-04 07:47:40 +0000570 bool MadeChange = false;
571
Evan Cheng31886db2008-02-19 02:09:37 +0000572 // It doesn't make sense to save a single instruction since tail merging
573 // will add a jump.
574 // FIXME: Ask the target to provide the threshold?
575 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
Chris Lattner12143052006-10-21 00:47:49 +0000576
Bill Wendling3403bcd2009-08-22 20:03:00 +0000577 DEBUG(errs() << "\nTryMergeBlocks " << MergePotentials.size() << '\n');
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000578
Chris Lattner12143052006-10-21 00:47:49 +0000579 // Sort by hash value so that blocks with identical end sequences sort
580 // together.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000581 std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
Chris Lattner12143052006-10-21 00:47:49 +0000582
583 // Walk through equivalence sets looking for actual exact matches.
584 while (MergePotentials.size() > 1) {
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000585 unsigned CurHash = prior(MergePotentials.end())->first;
Chris Lattner12143052006-10-21 00:47:49 +0000586
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000587 // Build SameTails, identifying the set of blocks with this hash code
588 // and with the maximum number of instructions in common.
589 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
590 minCommonTailLength);
Dale Johannesen7aea8322007-05-23 21:07:20 +0000591
Dale Johannesena5a21172007-06-01 23:02:45 +0000592 // If we didn't find any pair that has at least minCommonTailLength
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000593 // instructions in common, remove all blocks with this hash code and retry.
594 if (SameTails.empty()) {
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000595 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
Dale Johannesen7aea8322007-05-23 21:07:20 +0000596 continue;
Chris Lattner12143052006-10-21 00:47:49 +0000597 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000598
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000599 // If one of the blocks is the entire common tail (and not the entry
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000600 // block, which we can't jump to), we can treat all blocks with this same
601 // tail at once. Use PredBB if that is one of the possibilities, as that
602 // will not introduce any extra branches.
603 MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
604 getParent()->begin();
605 unsigned int commonTailIndex, i;
606 for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000607 MachineBasicBlock *MBB = SameTails[i].first->second;
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000608 if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
609 commonTailIndex = i;
610 if (MBB==PredBB)
611 break;
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000612 }
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000613 }
Dale Johannesena5a21172007-06-01 23:02:45 +0000614
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000615 if (commonTailIndex==SameTails.size()) {
616 // None of the blocks consist entirely of the common tail.
617 // Split a block so that one does.
618 commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
Chris Lattner1d08d832006-11-01 01:16:12 +0000619 }
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000620
621 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
622 // MBB is common tail. Adjust all other BB's to jump to this one.
623 // Traversal must be forwards so erases work.
Bill Wendling3403bcd2009-08-22 20:03:00 +0000624 DEBUG(errs() << "\nUsing common tail " << MBB->getNumber() << " for ");
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000625 for (unsigned int i=0; i<SameTails.size(); ++i) {
626 if (commonTailIndex==i)
627 continue;
Bill Wendling3403bcd2009-08-22 20:03:00 +0000628 DEBUG(errs() << SameTails[i].first->second->getNumber() << ",");
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000629 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
630 ReplaceTailWithBranchTo(SameTails[i].second, MBB);
631 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
632 MergePotentials.erase(SameTails[i].first);
Chris Lattner12143052006-10-21 00:47:49 +0000633 }
Bill Wendling3403bcd2009-08-22 20:03:00 +0000634 DEBUG(errs() << "\n");
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000635 // We leave commonTailIndex in the worklist in case there are other blocks
636 // that match it with a smaller number of instructions.
Chris Lattner1d08d832006-11-01 01:16:12 +0000637 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000638 }
Chris Lattner12143052006-10-21 00:47:49 +0000639 return MadeChange;
640}
641
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000642bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000643
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000644 if (!EnableTailMerge) return false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000645
Evan Cheng030a0a02009-09-04 07:47:40 +0000646 bool MadeChange = false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000647
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000648 // First find blocks with no successors.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000649 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000650 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
651 if (I->succ_empty())
Dale Johannesen7aea8322007-05-23 21:07:20 +0000652 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000653 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000654 // See if we can do any tail merging on those.
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000655 if (MergePotentials.size() < TailMergeThreshold &&
656 MergePotentials.size() >= 2)
Dale Johannesen53af4c02007-06-08 00:34:27 +0000657 MadeChange |= TryMergeBlocks(NULL, NULL);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000658
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000659 // Look at blocks (IBB) with multiple predecessors (PBB).
660 // We change each predecessor to a canonical form, by
661 // (1) temporarily removing any unconditional branch from the predecessor
662 // to IBB, and
663 // (2) alter conditional branches so they branch to the other block
664 // not IBB; this may require adding back an unconditional branch to IBB
665 // later, where there wasn't one coming in. E.g.
666 // Bcc IBB
667 // fallthrough to QBB
668 // here becomes
669 // Bncc QBB
670 // with a conceptual B to IBB after that, which never actually exists.
671 // With those changes, we see whether the predecessors' tails match,
672 // and merge them if so. We change things out of canonical form and
673 // back to the way they were later in the process. (OptimizeBranches
674 // would undo some of this, but we can't use it, because we'd get into
675 // a compile-time infinite loop repeatedly doing and undoing the same
676 // transformations.)
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000677
678 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Dale Johannesen62bc8a42008-07-01 21:50:14 +0000679 if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
Dan Gohmanda658222009-08-18 15:18:18 +0000680 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000681 MachineBasicBlock *IBB = I;
682 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000683 MergePotentials.clear();
Dale Johannesen1a90a5a2007-06-08 01:08:52 +0000684 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
685 E2 = I->pred_end();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000686 P != E2; ++P) {
687 MachineBasicBlock* PBB = *P;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000688 // Skip blocks that loop to themselves, can't tail merge these.
689 if (PBB==IBB)
690 continue;
Dan Gohmanda658222009-08-18 15:18:18 +0000691 // Visit each predecessor only once.
692 if (!UniquePreds.insert(PBB))
693 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000694 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000695 SmallVector<MachineOperand, 4> Cond;
Evan Chengdc54d312009-02-09 07:14:22 +0000696 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000697 // Failing case: IBB is the target of a cbr, and
698 // we cannot reverse the branch.
Owen Anderson44eb65c2008-08-14 22:49:33 +0000699 SmallVector<MachineOperand, 4> NewCond(Cond);
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000700 if (!Cond.empty() && TBB==IBB) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000701 if (TII->ReverseBranchCondition(NewCond))
702 continue;
703 // This is the QBB case described above
704 if (!FBB)
705 FBB = next(MachineFunction::iterator(PBB));
706 }
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000707 // Failing case: the only way IBB can be reached from PBB is via
708 // exception handling. Happens for landing pads. Would be nice
709 // to have a bit in the edge so we didn't have to do all this.
710 if (IBB->isLandingPad()) {
711 MachineFunction::iterator IP = PBB; IP++;
712 MachineBasicBlock* PredNextBB = NULL;
713 if (IP!=MF.end())
714 PredNextBB = IP;
715 if (TBB==NULL) {
716 if (IBB!=PredNextBB) // fallthrough
717 continue;
718 } else if (FBB) {
719 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
720 continue;
Dan Gohman30359592008-01-29 13:02:09 +0000721 } else if (Cond.empty()) {
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000722 if (TBB!=IBB) // ubr
723 continue;
724 } else {
725 if (TBB!=IBB && IBB!=PredNextBB) // cbr
726 continue;
727 }
728 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000729 // Remove the unconditional branch at the end, if any.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000730 if (TBB && (Cond.empty() || FBB)) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000731 TII->RemoveBranch(*PBB);
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000732 if (!Cond.empty())
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000733 // reinsert conditional branch only, for now
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000734 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000735 }
Dale Johannesen7aea8322007-05-23 21:07:20 +0000736 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000737 }
738 }
739 if (MergePotentials.size() >= 2)
740 MadeChange |= TryMergeBlocks(I, PredBB);
741 // Reinsert an unconditional branch if needed.
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000742 // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
Dale Johannesen1cf08c12007-05-18 01:28:58 +0000743 PredBB = prior(I); // this may have been changed in TryMergeBlocks
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000744 if (MergePotentials.size()==1 &&
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000745 MergePotentials.begin()->second != PredBB)
746 FixTail(MergePotentials.begin()->second, I, TII);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000747 }
748 }
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000749 return MadeChange;
750}
Chris Lattner12143052006-10-21 00:47:49 +0000751
752//===----------------------------------------------------------------------===//
753// Branch Optimization
754//===----------------------------------------------------------------------===//
755
756bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
Evan Cheng030a0a02009-09-04 07:47:40 +0000757 bool MadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +0000758
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000759 // Make sure blocks are numbered in order
760 MF.RenumberBlocks();
761
Chris Lattner12143052006-10-21 00:47:49 +0000762 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
763 MachineBasicBlock *MBB = I++;
Evan Cheng030a0a02009-09-04 07:47:40 +0000764 MadeChange |= OptimizeBlock(MBB);
Chris Lattner12143052006-10-21 00:47:49 +0000765
766 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000767 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000768 RemoveDeadBlock(MBB);
769 MadeChange = true;
770 ++NumDeadBlocks;
771 }
772 }
773 return MadeChange;
774}
775
776
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000777/// CanFallThrough - Return true if the specified block (with the specified
778/// branch condition) can implicitly transfer control to the block after it by
779/// falling off the end of it. This should return false if it can reach the
780/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
781///
782/// True is a conservative answer.
783///
784bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
785 bool BranchUnAnalyzable,
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000786 MachineBasicBlock *TBB,
787 MachineBasicBlock *FBB,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000788 const SmallVectorImpl<MachineOperand> &Cond) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000789 MachineFunction::iterator Fallthrough = CurBB;
790 ++Fallthrough;
791 // If FallthroughBlock is off the end of the function, it can't fall through.
792 if (Fallthrough == CurBB->getParent()->end())
793 return false;
794
795 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
796 if (!CurBB->isSuccessor(Fallthrough))
797 return false;
798
799 // If we couldn't analyze the branch, assume it could fall through.
800 if (BranchUnAnalyzable) return true;
801
Chris Lattner7d097842006-10-24 01:12:32 +0000802 // If there is no branch, control always falls through.
803 if (TBB == 0) return true;
804
805 // If there is some explicit branch to the fallthrough block, it can obviously
806 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000807 if (MachineFunction::iterator(TBB) == Fallthrough ||
808 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000809 return true;
810
811 // If it's an unconditional branch to some block not the fall through, it
812 // doesn't fall through.
813 if (Cond.empty()) return false;
814
815 // Otherwise, if it is conditional and has no explicit false block, it falls
816 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000817 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000818}
819
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000820/// CanFallThrough - Return true if the specified can implicitly transfer
821/// control to the block after it by falling off the end of it. This should
822/// return false if it can reach the block after it, but it uses an explicit
823/// branch to do so (e.g. a table jump).
824///
825/// True is a conservative answer.
826///
827bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
828 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000829 SmallVector<MachineOperand, 4> Cond;
Evan Chengdc54d312009-02-09 07:14:22 +0000830 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond, true);
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000831 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
832}
833
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000834/// IsBetterFallthrough - Return true if it would be clearly better to
835/// fall-through to MBB1 than to fall through into MBB2. This has to return
836/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
837/// result in infinite loops.
838static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
Chris Lattner69244302008-01-07 01:56:04 +0000839 MachineBasicBlock *MBB2) {
Chris Lattner154e1042006-11-18 21:30:35 +0000840 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
841 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000842 // optimize branches that branch to either a return block or an assert block
843 // into a fallthrough to the return.
844 if (MBB1->empty() || MBB2->empty()) return false;
Christopher Lamb11a4f642007-12-10 07:24:06 +0000845
846 // If there is a clear successor ordering we make sure that one block
847 // will fall through to the next
848 if (MBB1->isSuccessor(MBB2)) return true;
849 if (MBB2->isSuccessor(MBB1)) return false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000850
851 MachineInstr *MBB1I = --MBB1->end();
852 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner749c6f62008-01-07 07:27:27 +0000853 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000854}
855
Chris Lattner7821a8a2006-10-14 00:21:48 +0000856/// OptimizeBlock - Analyze and optimize control flow related to the specified
857/// block. This is never called on the entry block.
Evan Cheng030a0a02009-09-04 07:47:40 +0000858bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
859 bool MadeChange = false;
860
Chris Lattner7d097842006-10-24 01:12:32 +0000861 MachineFunction::iterator FallThrough = MBB;
862 ++FallThrough;
863
Chris Lattnereb15eee2006-10-13 20:43:10 +0000864 // If this block is empty, make everyone use its fall-through, not the block
Dale Johannesena52dd152007-05-31 21:54:00 +0000865 // explicitly. Landing pads should not do this since the landing-pad table
866 // points to this block.
867 if (MBB->empty() && !MBB->isLandingPad()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000868 // Dead block? Leave for cleanup later.
Evan Cheng030a0a02009-09-04 07:47:40 +0000869 if (MBB->pred_empty()) return MadeChange;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000870
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000871 if (FallThrough == MBB->getParent()->end()) {
872 // TODO: Simplify preds to not branch here if possible!
873 } else {
874 // Rewrite all predecessors of the old block to go to the fallthrough
875 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000876 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000877 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
Evan Cheng0370fad2007-06-04 06:44:01 +0000878 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000879 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000880 // If MBB was the target of a jump table, update jump tables to go to the
881 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000882 MBB->getParent()->getJumpTableInfo()->
883 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000884 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000885 }
Evan Cheng030a0a02009-09-04 07:47:40 +0000886 return MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000887 }
888
Chris Lattner7821a8a2006-10-14 00:21:48 +0000889 // Check to see if we can simplify the terminator of the block before this
890 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000891 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000892
Chris Lattner7821a8a2006-10-14 00:21:48 +0000893 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000894 SmallVector<MachineOperand, 4> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000895 bool PriorUnAnalyzable =
Evan Chengdc54d312009-02-09 07:14:22 +0000896 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
Chris Lattner386e2902006-10-21 05:08:28 +0000897 if (!PriorUnAnalyzable) {
898 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2bdb7d02007-06-18 22:43:58 +0000899 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
900 !PriorCond.empty());
Chris Lattner386e2902006-10-21 05:08:28 +0000901
Chris Lattner7821a8a2006-10-14 00:21:48 +0000902 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000903 // destination, remove the branch, replacing it with an unconditional one or
904 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000905 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000906 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000907 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000908 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000909 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000910 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000911 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000912 return OptimizeBlock(MBB);
913 }
914
915 // If the previous branch *only* branches to *this* block (conditional or
916 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000917 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000918 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000919 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000920 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000921 return OptimizeBlock(MBB);
922 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000923
924 // If the prior block branches somewhere else on the condition and here if
925 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000926 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000927 TII->RemoveBranch(PrevBB);
928 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
929 MadeChange = true;
930 ++NumBranchOpts;
931 return OptimizeBlock(MBB);
932 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000933
934 // If the prior block branches here on true and somewhere else on false, and
935 // if the branch condition is reversible, reverse the branch to create a
936 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000937 if (PriorTBB == MBB) {
Owen Anderson44eb65c2008-08-14 22:49:33 +0000938 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Chris Lattnera2d79952006-10-21 05:54:00 +0000939 if (!TII->ReverseBranchCondition(NewPriorCond)) {
940 TII->RemoveBranch(PrevBB);
941 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
942 MadeChange = true;
943 ++NumBranchOpts;
944 return OptimizeBlock(MBB);
945 }
946 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000947
Dan Gohman6d312682009-10-22 00:03:58 +0000948 // If this block has no successors (e.g. it is a return block or ends with
949 // a call to a no-return function like abort or __cxa_throw) and if the pred
950 // falls through into this block, and if it would otherwise fall through
951 // into the block after this, move this block to the end of the function.
Chris Lattner154e1042006-11-18 21:30:35 +0000952 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000953 // We consider it more likely that execution will stay in the function (e.g.
954 // due to loops) than it is to exit it. This asserts in loops etc, moving
955 // the assert condition out of the loop body.
Dan Gohman6d312682009-10-22 00:03:58 +0000956 if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
Chris Lattner154e1042006-11-18 21:30:35 +0000957 MachineFunction::iterator(PriorTBB) == FallThrough &&
958 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000959 bool DoTransform = true;
960
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000961 // We have to be careful that the succs of PredBB aren't both no-successor
962 // blocks. If neither have successors and if PredBB is the second from
963 // last block in the function, we'd just keep swapping the two blocks for
964 // last. Only do the swap if one is clearly better to fall through than
965 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000966 if (FallThrough == --MBB->getParent()->end() &&
Chris Lattner69244302008-01-07 01:56:04 +0000967 !IsBetterFallthrough(PriorTBB, MBB))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000968 DoTransform = false;
969
970 // We don't want to do this transformation if we have control flow like:
971 // br cond BB2
972 // BB1:
973 // ..
974 // jmp BBX
975 // BB2:
976 // ..
977 // ret
978 //
979 // In this case, we could actually be moving the return block *into* a
980 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000981 if (DoTransform && !MBB->succ_empty() &&
982 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000983 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000984
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000985
986 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000987 // Reverse the branch so we will fall through on the previous true cond.
Owen Anderson44eb65c2008-08-14 22:49:33 +0000988 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000989 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Bill Wendling3403bcd2009-08-22 20:03:00 +0000990 DEBUG(errs() << "\nMoving MBB: " << *MBB
991 << "To make fallthrough to: " << *PriorTBB << "\n");
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000992
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000993 TII->RemoveBranch(PrevBB);
994 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
995
996 // Move this block to the end of the function.
997 MBB->moveAfter(--MBB->getParent()->end());
998 MadeChange = true;
999 ++NumBranchOpts;
Evan Cheng030a0a02009-09-04 07:47:40 +00001000 return MadeChange;
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001001 }
1002 }
1003 }
Chris Lattner7821a8a2006-10-14 00:21:48 +00001004 }
Chris Lattner7821a8a2006-10-14 00:21:48 +00001005
Chris Lattner386e2902006-10-21 05:08:28 +00001006 // Analyze the branch in the current block.
1007 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +00001008 SmallVector<MachineOperand, 4> CurCond;
Evan Chengdc54d312009-02-09 07:14:22 +00001009 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001010 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +00001011 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001012 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
Chris Lattnereb15eee2006-10-13 20:43:10 +00001013
Chris Lattner5d056952006-11-08 01:03:21 +00001014 // If this is a two-way branch, and the FBB branches to this block, reverse
1015 // the condition so the single-basic-block loop is faster. Instead of:
1016 // Loop: xxx; jcc Out; jmp Loop
1017 // we want:
1018 // Loop: xxx; jncc Loop; jmp Out
1019 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
Owen Anderson44eb65c2008-08-14 22:49:33 +00001020 SmallVector<MachineOperand, 4> NewCond(CurCond);
Chris Lattner5d056952006-11-08 01:03:21 +00001021 if (!TII->ReverseBranchCondition(NewCond)) {
1022 TII->RemoveBranch(*MBB);
1023 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1024 MadeChange = true;
1025 ++NumBranchOpts;
1026 return OptimizeBlock(MBB);
1027 }
1028 }
1029
1030
Chris Lattner386e2902006-10-21 05:08:28 +00001031 // If this branch is the only thing in its block, see if we can forward
1032 // other blocks across it.
1033 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner749c6f62008-01-07 07:27:27 +00001034 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +00001035 // This block may contain just an unconditional branch. Because there can
1036 // be 'non-branch terminators' in the block, try removing the branch and
1037 // then seeing if the block is empty.
1038 TII->RemoveBranch(*MBB);
1039
1040 // If this block is just an unconditional branch to CurTBB, we can
1041 // usually completely eliminate the block. The only case we cannot
1042 // completely eliminate the block is when the block before this one
1043 // falls through into MBB and we can't understand the prior block's branch
1044 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +00001045 if (MBB->empty()) {
1046 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1047 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1048 !PrevBB.isSuccessor(MBB)) {
1049 // If the prior block falls through into us, turn it into an
1050 // explicit branch to us to make updates simpler.
1051 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1052 PriorTBB != MBB && PriorFBB != MBB) {
1053 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +00001054 assert(PriorCond.empty() && PriorFBB == 0 &&
1055 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +00001056 PriorTBB = MBB;
1057 } else {
1058 assert(PriorFBB == 0 && "Machine CFG out of date!");
1059 PriorFBB = MBB;
1060 }
1061 TII->RemoveBranch(PrevBB);
1062 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +00001063 }
Chris Lattner386e2902006-10-21 05:08:28 +00001064
Chris Lattnercf420cc2006-10-28 17:32:47 +00001065 // Iterate through all the predecessors, revectoring each in-turn.
David Greene8a46d342007-06-29 02:45:24 +00001066 size_t PI = 0;
Chris Lattnercf420cc2006-10-28 17:32:47 +00001067 bool DidChange = false;
1068 bool HasBranchToSelf = false;
David Greene8a46d342007-06-29 02:45:24 +00001069 while(PI != MBB->pred_size()) {
1070 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1071 if (PMBB == MBB) {
Chris Lattnercf420cc2006-10-28 17:32:47 +00001072 // If this block has an uncond branch to itself, leave it.
1073 ++PI;
1074 HasBranchToSelf = true;
1075 } else {
1076 DidChange = true;
David Greene8a46d342007-06-29 02:45:24 +00001077 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
Dale Johannesenbf06f6a2009-05-11 21:54:13 +00001078 // If this change resulted in PMBB ending in a conditional
1079 // branch where both conditions go to the same destination,
1080 // change this to an unconditional branch (and fix the CFG).
1081 MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1082 SmallVector<MachineOperand, 4> NewCurCond;
1083 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1084 NewCurFBB, NewCurCond, true);
1085 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1086 TII->RemoveBranch(*PMBB);
1087 NewCurCond.clear();
1088 TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond);
1089 MadeChange = true;
1090 ++NumBranchOpts;
1091 PMBB->CorrectExtraCFGEdges(NewCurTBB, NewCurFBB, false);
1092 }
Chris Lattnercf420cc2006-10-28 17:32:47 +00001093 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001094 }
Chris Lattner386e2902006-10-21 05:08:28 +00001095
Chris Lattnercf420cc2006-10-28 17:32:47 +00001096 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +00001097 MBB->getParent()->getJumpTableInfo()->
1098 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001099 if (DidChange) {
1100 ++NumBranchOpts;
1101 MadeChange = true;
Evan Cheng030a0a02009-09-04 07:47:40 +00001102 if (!HasBranchToSelf) return MadeChange;
Chris Lattnercf420cc2006-10-28 17:32:47 +00001103 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001104 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001105 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001106
Chris Lattner386e2902006-10-21 05:08:28 +00001107 // Add the branch back if the block is more than just an uncond branch.
1108 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +00001109 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001110 }
1111
1112 // If the prior block doesn't fall through into this block, and if this
1113 // block doesn't fall through into some other block, see if we can find a
1114 // place to move this block where a fall-through will happen.
1115 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1116 PriorTBB, PriorFBB, PriorCond)) {
1117 // Now we know that there was no fall-through into this block, check to
1118 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001119 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +00001120 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001121
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001122 if (!MBB->isLandingPad()) {
1123 // Check all the predecessors of this block. If one of them has no fall
1124 // throughs, move this block right after it.
1125 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1126 E = MBB->pred_end(); PI != E; ++PI) {
1127 // Analyze the branch at the end of the pred.
1128 MachineBasicBlock *PredBB = *PI;
1129 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1130 if (PredBB != MBB && !CanFallThrough(PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001131 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001132 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1133 // If the current block doesn't fall through, just move it.
1134 // If the current block can fall through and does not end with a
1135 // conditional branch, we need to append an unconditional jump to
1136 // the (current) next block. To avoid a possible compile-time
1137 // infinite loop, move blocks only backward in this case.
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001138 // Also, if there are already 2 branches here, we cannot add a third;
1139 // this means we have the case
1140 // Bcc next
1141 // B elsewhere
1142 // next:
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001143 if (CurFallsThru) {
1144 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1145 CurCond.clear();
1146 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1147 }
1148 MBB->moveAfter(PredBB);
1149 MadeChange = true;
1150 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +00001151 }
1152 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001153 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001154
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001155 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001156 // Check all successors to see if we can move this block before it.
1157 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1158 E = MBB->succ_end(); SI != E; ++SI) {
1159 // Analyze the branch at the end of the block before the succ.
1160 MachineBasicBlock *SuccBB = *SI;
1161 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001162 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +00001163
1164 // If this block doesn't already fall-through to that successor, and if
1165 // the succ doesn't already have a block that can fall through into it,
1166 // and if the successor isn't an EH destination, we can arrange for the
1167 // fallthrough to happen.
1168 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1169 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001170 MBB->moveBefore(SuccBB);
1171 MadeChange = true;
1172 return OptimizeBlock(MBB);
1173 }
1174 }
1175
1176 // Okay, there is no really great place to put this block. If, however,
1177 // the block before this one would be a fall-through if this block were
1178 // removed, move this block to the end of the function.
1179 if (FallThrough != MBB->getParent()->end() &&
1180 PrevBB.isSuccessor(FallThrough)) {
1181 MBB->moveAfter(--MBB->getParent()->end());
1182 MadeChange = true;
Evan Cheng030a0a02009-09-04 07:47:40 +00001183 return MadeChange;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001184 }
Chris Lattner7d097842006-10-24 01:12:32 +00001185 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001186 }
Evan Cheng030a0a02009-09-04 07:47:40 +00001187
1188 return MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +00001189}