blob: 7bc25ab9e9551e21c48acf2c02c04492439e8097 [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"
Chris Lattner12143052006-10-21 00:47:49 +000035#include "llvm/ADT/Statistic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000036#include "llvm/ADT/STLExtras.h"
Jeff Cohend41b30d2006-11-05 19:31:28 +000037#include <algorithm>
Chris Lattner21ab22e2004-07-31 10:01:27 +000038using namespace llvm;
39
Chris Lattnercd3245a2006-12-19 22:41:21 +000040STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
41STATISTIC(NumBranchOpts, "Number of branches optimized");
42STATISTIC(NumTailMerge , "Number of block tails merged");
Dale Johannesen81da02b2007-05-22 17:14:46 +000043static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
44 cl::init(cl::BOU_UNSET), cl::Hidden);
Dan Gohman844731a2008-05-13 00:00:25 +000045// Throttle for huge numbers of predecessors (compile speed problems)
46static cl::opt<unsigned>
47TailMergeThreshold("tail-merge-threshold",
48 cl::desc("Max number of predecessors to consider tail merging"),
Dale Johannesen622addb2008-10-27 02:10:21 +000049 cl::init(150), cl::Hidden);
Dale Johannesen1a90a5a2007-06-08 01:08:52 +000050
Devang Patel794fd752007-05-01 21:15:47 +000051
Evan Cheng030a0a02009-09-04 07:47:40 +000052char BranchFolderPass::ID = 0;
Chris Lattner21ab22e2004-07-31 10:01:27 +000053
Bob Wilsona5971032009-10-28 20:46:46 +000054FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
55 return new BranchFolderPass(DefaultEnableTailMerge);
Evan Cheng030a0a02009-09-04 07:47:40 +000056}
57
58bool BranchFolderPass::runOnMachineFunction(MachineFunction &MF) {
59 return OptimizeFunction(MF,
60 MF.getTarget().getInstrInfo(),
61 MF.getTarget().getRegisterInfo(),
62 getAnalysisIfAvailable<MachineModuleInfo>());
63}
64
65
66
Bob Wilsona5971032009-10-28 20:46:46 +000067BranchFolder::BranchFolder(bool defaultEnableTailMerge) {
Evan Cheng030a0a02009-09-04 07:47:40 +000068 switch (FlagEnableTailMerge) {
69 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
70 case cl::BOU_TRUE: EnableTailMerge = true; break;
71 case cl::BOU_FALSE: EnableTailMerge = false; break;
72 }
Evan Chengb3c27422009-09-03 23:54:22 +000073}
Chris Lattner21ab22e2004-07-31 10:01:27 +000074
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000075/// RemoveDeadBlock - Remove the specified dead machine basic block from the
76/// function, updating the CFG.
Chris Lattner683747a2006-10-17 23:17:27 +000077void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
Jim Laskey033c9712007-02-22 16:39:03 +000078 assert(MBB->pred_empty() && "MBB must be dead!");
Bill Wendling3403bcd2009-08-22 20:03:00 +000079 DEBUG(errs() << "\nRemoving MBB: " << *MBB);
Chris Lattner683747a2006-10-17 23:17:27 +000080
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000081 MachineFunction *MF = MBB->getParent();
82 // drop all successors.
83 while (!MBB->succ_empty())
84 MBB->removeSuccessor(MBB->succ_end()-1);
Chris Lattner683747a2006-10-17 23:17:27 +000085
Duncan Sands68d4d1d2008-07-29 20:56:02 +000086 // If there are any labels in the basic block, unregister them from
87 // MachineModuleInfo.
Jim Laskey44c3b9f2007-01-26 21:22:28 +000088 if (MMI && !MBB->empty()) {
Chris Lattner683747a2006-10-17 23:17:27 +000089 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
90 I != E; ++I) {
Duncan Sands68d4d1d2008-07-29 20:56:02 +000091 if (I->isLabel())
Chris Lattner683747a2006-10-17 23:17:27 +000092 // The label ID # is always operand #0, an immediate.
Jim Laskey44c3b9f2007-01-26 21:22:28 +000093 MMI->InvalidateLabel(I->getOperand(0).getImm());
Chris Lattner683747a2006-10-17 23:17:27 +000094 }
95 }
96
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000097 // Remove the block.
Dan Gohman8e5f2c62008-07-07 23:14:23 +000098 MF->erase(MBB);
Chris Lattnerc50ffcb2006-10-17 17:13:52 +000099}
100
Evan Cheng80b09fe2008-04-10 02:32:10 +0000101/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
102/// followed by terminators, and if the implicitly defined registers are not
103/// used by the terminators, remove those implicit_def's. e.g.
104/// BB1:
105/// r0 = implicit_def
106/// r1 = implicit_def
107/// br
108/// This block can be optimized away later if the implicit instructions are
109/// removed.
110bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
111 SmallSet<unsigned, 4> ImpDefRegs;
112 MachineBasicBlock::iterator I = MBB->begin();
113 while (I != MBB->end()) {
114 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
115 break;
116 unsigned Reg = I->getOperand(0).getReg();
117 ImpDefRegs.insert(Reg);
Evan Cheng030a0a02009-09-04 07:47:40 +0000118 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
Evan Cheng80b09fe2008-04-10 02:32:10 +0000119 unsigned SubReg = *SubRegs; ++SubRegs)
120 ImpDefRegs.insert(SubReg);
121 ++I;
122 }
123 if (ImpDefRegs.empty())
124 return false;
125
126 MachineBasicBlock::iterator FirstTerm = I;
127 while (I != MBB->end()) {
128 if (!TII->isUnpredicatedTerminator(I))
129 return false;
130 // See if it uses any of the implicitly defined registers.
131 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
132 MachineOperand &MO = I->getOperand(i);
Dan Gohmand735b802008-10-03 15:45:36 +0000133 if (!MO.isReg() || !MO.isUse())
Evan Cheng80b09fe2008-04-10 02:32:10 +0000134 continue;
135 unsigned Reg = MO.getReg();
136 if (ImpDefRegs.count(Reg))
137 return false;
138 }
139 ++I;
140 }
141
142 I = MBB->begin();
143 while (I != FirstTerm) {
144 MachineInstr *ImpDefMI = &*I;
145 ++I;
146 MBB->erase(ImpDefMI);
147 }
148
149 return true;
150}
151
Evan Cheng030a0a02009-09-04 07:47:40 +0000152/// OptimizeFunction - Perhaps branch folding, tail merging and other
153/// CFG optimizations on the given function.
154bool BranchFolder::OptimizeFunction(MachineFunction &MF,
155 const TargetInstrInfo *tii,
156 const TargetRegisterInfo *tri,
157 MachineModuleInfo *mmi) {
158 if (!tii) return false;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000159
Evan Cheng030a0a02009-09-04 07:47:40 +0000160 TII = tii;
161 TRI = tri;
162 MMI = mmi;
163
164 RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
Evan Cheng80b09fe2008-04-10 02:32:10 +0000165
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000166 // Fix CFG. The later algorithms expect it to be right.
Evan Cheng030a0a02009-09-04 07:47:40 +0000167 bool MadeChange = false;
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000168 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
169 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000170 SmallVector<MachineOperand, 4> Cond;
Evan Chengdc54d312009-02-09 07:14:22 +0000171 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
Evan Cheng030a0a02009-09-04 07:47:40 +0000172 MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
173 MadeChange |= OptimizeImpDefsBlock(MBB);
Dale Johannesen14ba0cc2007-05-15 21:19:17 +0000174 }
175
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000176
Chris Lattner12143052006-10-21 00:47:49 +0000177 bool MadeChangeThisIteration = true;
178 while (MadeChangeThisIteration) {
179 MadeChangeThisIteration = false;
180 MadeChangeThisIteration |= TailMergeBlocks(MF);
181 MadeChangeThisIteration |= OptimizeBranches(MF);
Evan Cheng030a0a02009-09-04 07:47:40 +0000182 MadeChange |= MadeChangeThisIteration;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000183 }
184
Chris Lattner6acfe122006-10-28 18:34:47 +0000185 // See if any jump tables have become mergable or dead as the code generator
186 // did its thing.
187 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
188 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
189 if (!JTs.empty()) {
190 // Figure out how these jump tables should be merged.
191 std::vector<unsigned> JTMapping;
192 JTMapping.reserve(JTs.size());
193
194 // We always keep the 0th jump table.
195 JTMapping.push_back(0);
196
197 // Scan the jump tables, seeing if there are any duplicates. Note that this
198 // is N^2, which should be fixed someday.
Evan Cheng030a0a02009-09-04 07:47:40 +0000199 for (unsigned i = 1, e = JTs.size(); i != e; ++i) {
200 if (JTs[i].MBBs.empty())
201 JTMapping.push_back(i);
202 else
203 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
204 }
Chris Lattner6acfe122006-10-28 18:34:47 +0000205
206 // If a jump table was merge with another one, walk the function rewriting
207 // references to jump tables to reference the new JT ID's. Keep track of
208 // whether we see a jump table idx, if not, we can delete the JT.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000209 BitVector JTIsLive(JTs.size());
Chris Lattner6acfe122006-10-28 18:34:47 +0000210 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
211 BB != E; ++BB) {
212 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
213 I != E; ++I)
214 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
215 MachineOperand &Op = I->getOperand(op);
Dan Gohmand735b802008-10-03 15:45:36 +0000216 if (!Op.isJTI()) continue;
Chris Lattner8aa797a2007-12-30 23:10:15 +0000217 unsigned NewIdx = JTMapping[Op.getIndex()];
218 Op.setIndex(NewIdx);
Chris Lattner6acfe122006-10-28 18:34:47 +0000219
220 // Remember that this JT is live.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000221 JTIsLive.set(NewIdx);
Chris Lattner6acfe122006-10-28 18:34:47 +0000222 }
223 }
224
225 // Finally, remove dead jump tables. This happens either because the
226 // indirect jump was unreachable (and thus deleted) or because the jump
227 // table was merged with some other one.
228 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000229 if (!JTIsLive.test(i)) {
Chris Lattner6acfe122006-10-28 18:34:47 +0000230 JTI->RemoveJumpTable(i);
Evan Cheng030a0a02009-09-04 07:47:40 +0000231 MadeChange = true;
Chris Lattner6acfe122006-10-28 18:34:47 +0000232 }
233 }
Evan Cheng030a0a02009-09-04 07:47:40 +0000234
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000235 delete RS;
Evan Cheng030a0a02009-09-04 07:47:40 +0000236 return MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000237}
238
Chris Lattner12143052006-10-21 00:47:49 +0000239//===----------------------------------------------------------------------===//
240// Tail Merging of Blocks
241//===----------------------------------------------------------------------===//
242
243/// HashMachineInstr - Compute a hash value for MI and its operands.
244static unsigned HashMachineInstr(const MachineInstr *MI) {
245 unsigned Hash = MI->getOpcode();
246 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
247 const MachineOperand &Op = MI->getOperand(i);
248
249 // Merge in bits from the operand if easy.
250 unsigned OperandHash = 0;
251 switch (Op.getType()) {
252 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
253 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
254 case MachineOperand::MO_MachineBasicBlock:
Chris Lattner8aa797a2007-12-30 23:10:15 +0000255 OperandHash = Op.getMBB()->getNumber();
Chris Lattner12143052006-10-21 00:47:49 +0000256 break;
Chris Lattner8aa797a2007-12-30 23:10:15 +0000257 case MachineOperand::MO_FrameIndex:
Chris Lattner12143052006-10-21 00:47:49 +0000258 case MachineOperand::MO_ConstantPoolIndex:
Chris Lattner12143052006-10-21 00:47:49 +0000259 case MachineOperand::MO_JumpTableIndex:
Chris Lattner8aa797a2007-12-30 23:10:15 +0000260 OperandHash = Op.getIndex();
Chris Lattner12143052006-10-21 00:47:49 +0000261 break;
262 case MachineOperand::MO_GlobalAddress:
263 case MachineOperand::MO_ExternalSymbol:
264 // Global address / external symbol are too hard, don't bother, but do
265 // pull in the offset.
266 OperandHash = Op.getOffset();
267 break;
268 default: break;
269 }
270
271 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
272 }
273 return Hash;
274}
275
Dale Johannesen7aea8322007-05-23 21:07:20 +0000276/// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
277/// with no successors, we hash two instructions, because cross-jumping
278/// only saves code when at least two instructions are removed (since a
279/// branch must be inserted). For blocks with a successor, one of the
280/// two blocks to be tail-merged will end with a branch already, so
281/// it gains to cross-jump even for one instruction.
282
283static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
284 unsigned minCommonTailLength) {
Chris Lattner12143052006-10-21 00:47:49 +0000285 MachineBasicBlock::const_iterator I = MBB->end();
286 if (I == MBB->begin())
287 return 0; // Empty MBB.
288
289 --I;
290 unsigned Hash = HashMachineInstr(I);
291
Dale Johannesen7aea8322007-05-23 21:07:20 +0000292 if (I == MBB->begin() || minCommonTailLength == 1)
Chris Lattner12143052006-10-21 00:47:49 +0000293 return Hash; // Single instr MBB.
294
295 --I;
296 // Hash in the second-to-last instruction.
297 Hash ^= HashMachineInstr(I) << 2;
298 return Hash;
299}
300
301/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
302/// of instructions they actually have in common together at their end. Return
303/// iterators for the first shared instruction in each block.
304static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
305 MachineBasicBlock *MBB2,
306 MachineBasicBlock::iterator &I1,
307 MachineBasicBlock::iterator &I2) {
308 I1 = MBB1->end();
309 I2 = MBB2->end();
310
311 unsigned TailLen = 0;
312 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
313 --I1; --I2;
Bill Wendling80629c82007-10-19 21:09:55 +0000314 if (!I1->isIdenticalTo(I2) ||
Bill Wendlingda6efc52007-10-25 19:49:32 +0000315 // FIXME: This check is dubious. It's used to get around a problem where
Bill Wendling0713a222007-10-25 18:23:45 +0000316 // people incorrectly expect inline asm directives to remain in the same
317 // relative order. This is untenable because normal compiler
318 // optimizations (like this one) may reorder and/or merge these
319 // directives.
Bill Wendling80629c82007-10-19 21:09:55 +0000320 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
Chris Lattner12143052006-10-21 00:47:49 +0000321 ++I1; ++I2;
322 break;
323 }
324 ++TailLen;
325 }
326 return TailLen;
327}
328
329/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
Chris Lattner386e2902006-10-21 05:08:28 +0000330/// after it, replacing it with an unconditional branch to NewDest. This
331/// returns true if OldInst's block is modified, false if NewDest is modified.
Chris Lattner12143052006-10-21 00:47:49 +0000332void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
333 MachineBasicBlock *NewDest) {
334 MachineBasicBlock *OldBB = OldInst->getParent();
335
336 // Remove all the old successors of OldBB from the CFG.
337 while (!OldBB->succ_empty())
338 OldBB->removeSuccessor(OldBB->succ_begin());
339
340 // Remove all the dead instructions from the end of OldBB.
341 OldBB->erase(OldInst, OldBB->end());
342
Chris Lattner386e2902006-10-21 05:08:28 +0000343 // If OldBB isn't immediately before OldBB, insert a branch to it.
344 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
Dan Gohman1501cdb2008-08-22 16:07:55 +0000345 TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
Chris Lattner12143052006-10-21 00:47:49 +0000346 OldBB->addSuccessor(NewDest);
347 ++NumTailMerge;
348}
349
Chris Lattner1d08d832006-11-01 01:16:12 +0000350/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
351/// MBB so that the part before the iterator falls into the part starting at the
352/// iterator. This returns the new MBB.
353MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
354 MachineBasicBlock::iterator BBI1) {
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000355 MachineFunction &MF = *CurMBB.getParent();
356
Chris Lattner1d08d832006-11-01 01:16:12 +0000357 // Create the fall-through block.
358 MachineFunction::iterator MBBI = &CurMBB;
Dan Gohman8e5f2c62008-07-07 23:14:23 +0000359 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
360 CurMBB.getParent()->insert(++MBBI, NewMBB);
Chris Lattner1d08d832006-11-01 01:16:12 +0000361
362 // Move all the successors of this block to the specified block.
Dan Gohman04478e52008-06-19 17:22:29 +0000363 NewMBB->transferSuccessors(&CurMBB);
Chris Lattner1d08d832006-11-01 01:16:12 +0000364
365 // Add an edge from CurMBB to NewMBB for the fall-through.
366 CurMBB.addSuccessor(NewMBB);
367
368 // Splice the code over.
369 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000370
371 // For targets that use the register scavenger, we must maintain LiveIns.
372 if (RS) {
373 RS->enterBasicBlock(&CurMBB);
374 if (!CurMBB.empty())
375 RS->forward(prior(CurMBB.end()));
Evan Cheng030a0a02009-09-04 07:47:40 +0000376 BitVector RegsLiveAtExit(TRI->getNumRegs());
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000377 RS->getRegsUsed(RegsLiveAtExit, false);
Evan Cheng030a0a02009-09-04 07:47:40 +0000378 for (unsigned int i=0, e=TRI->getNumRegs(); i!=e; i++)
Dale Johannesen69cb9b72007-03-20 21:35:06 +0000379 if (RegsLiveAtExit[i])
380 NewMBB->addLiveIn(i);
381 }
382
Chris Lattner1d08d832006-11-01 01:16:12 +0000383 return NewMBB;
384}
385
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000386/// EstimateRuntime - Make a rough estimate for how long it will take to run
387/// the specified code.
388static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
Chris Lattner69244302008-01-07 01:56:04 +0000389 MachineBasicBlock::iterator E) {
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000390 unsigned Time = 0;
391 for (; I != E; ++I) {
Chris Lattner749c6f62008-01-07 07:27:27 +0000392 const TargetInstrDesc &TID = I->getDesc();
393 if (TID.isCall())
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000394 Time += 10;
Dan Gohman41474ba2008-12-03 02:30:17 +0000395 else if (TID.mayLoad() || TID.mayStore())
Chris Lattnerd4bf3c22006-11-01 19:36:29 +0000396 Time += 2;
397 else
398 ++Time;
399 }
400 return Time;
401}
402
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000403// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
404// branches temporarily for tail merging). In the case where CurMBB ends
405// with a conditional branch to the next block, optimize by reversing the
406// test and conditionally branching to SuccMBB instead.
407
408static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
409 const TargetInstrInfo *TII) {
410 MachineFunction *MF = CurMBB->getParent();
411 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
412 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000413 SmallVector<MachineOperand, 4> Cond;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000414 if (I != MF->end() &&
Evan Chengdc54d312009-02-09 07:14:22 +0000415 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000416 MachineBasicBlock *NextBB = I;
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000417 if (TBB == NextBB && !Cond.empty() && !FBB) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000418 if (!TII->ReverseBranchCondition(Cond)) {
419 TII->RemoveBranch(*CurMBB);
420 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
421 return;
422 }
423 }
424 }
Dan Gohman1501cdb2008-08-22 16:07:55 +0000425 TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000426}
427
Dale Johannesen44008c52007-05-30 00:32:01 +0000428static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
429 const std::pair<unsigned,MachineBasicBlock*> &q) {
Dale Johannesen95ef4062007-05-29 23:47:50 +0000430 if (p.first < q.first)
431 return true;
432 else if (p.first > q.first)
433 return false;
434 else if (p.second->getNumber() < q.second->getNumber())
435 return true;
436 else if (p.second->getNumber() > q.second->getNumber())
437 return false;
David Greene67fcdf72007-07-10 22:00:30 +0000438 else {
Duncan Sands97b4ac82007-07-11 08:47:55 +0000439 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
440 // an object with itself.
441#ifndef _GLIBCXX_DEBUG
Torok Edwinc23197a2009-07-14 16:55:14 +0000442 llvm_unreachable("Predecessor appears twice");
David Greene67fcdf72007-07-10 22:00:30 +0000443#endif
Dan Gohman5d5ee802009-01-08 22:19:34 +0000444 return false;
David Greene67fcdf72007-07-10 22:00:30 +0000445 }
Dale Johannesen95ef4062007-05-29 23:47:50 +0000446}
447
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000448/// ComputeSameTails - Look through all the blocks in MergePotentials that have
449/// hash CurHash (guaranteed to match the last element). Build the vector
450/// SameTails of all those that have the (same) largest number of instructions
451/// in common of any pair of these blocks. SameTails entries contain an
452/// iterator into MergePotentials (from which the MachineBasicBlock can be
453/// found) and a MachineBasicBlock::iterator into that MBB indicating the
454/// instruction where the matching code sequence begins.
455/// Order of elements in SameTails is the reverse of the order in which
456/// those blocks appear in MergePotentials (where they are not necessarily
457/// consecutive).
458unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
459 unsigned minCommonTailLength) {
460 unsigned maxCommonTailLength = 0U;
461 SameTails.clear();
462 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
463 MPIterator HighestMPIter = prior(MergePotentials.end());
464 for (MPIterator CurMPIter = prior(MergePotentials.end()),
465 B = MergePotentials.begin();
466 CurMPIter!=B && CurMPIter->first==CurHash;
467 --CurMPIter) {
468 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
Bob Wilson2c04dae2009-10-28 22:10:20 +0000469 unsigned CommonTailLen = ComputeCommonTailLength(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 Wilson2c04dae2009-10-28 22:10:20 +0000473 // minCommonTailLength instructions in common. Otherwise, if we are
474 // optimizing for code size, 1 instruction in common is enough. At
475 // worst we will be replacing a fallthrough into the common tail with a
476 // branch, which at worst breaks even with falling through into the
477 // duplicated common tail. We will always pick a block we do not have
478 // to split as the common tail if there is one. (Empty blocks will get
479 // forwarded and need not be considered.)
480 MachineFunction *MF = CurMPIter->second->getParent();
Dale Johannesen30562b72008-05-12 22:53:12 +0000481 if (CommonTailLen >= minCommonTailLength ||
Bob Wilsona5971032009-10-28 20:46:46 +0000482 (CommonTailLen > 0 &&
Bob Wilson2c04dae2009-10-28 22:10:20 +0000483 MF->getFunction()->hasFnAttr(Attribute::OptimizeForSize) &&
484 (TrialBBI1 == CurMPIter->second->begin() ||
485 TrialBBI2 == I->second->begin()))) {
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000486 if (CommonTailLen > maxCommonTailLength) {
487 SameTails.clear();
488 maxCommonTailLength = CommonTailLen;
489 HighestMPIter = CurMPIter;
490 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
491 }
492 if (HighestMPIter == CurMPIter &&
493 CommonTailLen == maxCommonTailLength)
494 SameTails.push_back(std::make_pair(I, TrialBBI2));
495 }
496 if (I==B)
497 break;
498 }
499 }
500 return maxCommonTailLength;
501}
502
503/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
504/// MergePotentials, restoring branches at ends of blocks as appropriate.
505void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
506 MachineBasicBlock* SuccBB,
507 MachineBasicBlock* PredBB) {
Dale Johannesen679860e2008-05-23 17:19:02 +0000508 MPIterator CurMPIter, B;
509 for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000510 CurMPIter->first==CurHash;
511 --CurMPIter) {
512 // Put the unconditional branch back, if we need one.
513 MachineBasicBlock *CurMBB = CurMPIter->second;
514 if (SuccBB && CurMBB != PredBB)
515 FixTail(CurMBB, SuccBB, TII);
Dale Johannesen679860e2008-05-23 17:19:02 +0000516 if (CurMPIter==B)
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000517 break;
518 }
Dale Johannesen679860e2008-05-23 17:19:02 +0000519 if (CurMPIter->first!=CurHash)
520 CurMPIter++;
521 MergePotentials.erase(CurMPIter, MergePotentials.end());
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000522}
523
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000524/// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
525/// only of the common tail. Create a block that does by splitting one.
526unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
527 unsigned maxCommonTailLength) {
528 unsigned i, commonTailIndex;
529 unsigned TimeEstimate = ~0U;
530 for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
531 // Use PredBB if possible; that doesn't require a new branch.
532 if (SameTails[i].first->second==PredBB) {
533 commonTailIndex = i;
534 break;
535 }
536 // Otherwise, make a (fairly bogus) choice based on estimate of
537 // how long it will take the various blocks to execute.
538 unsigned t = EstimateRuntime(SameTails[i].first->second->begin(),
539 SameTails[i].second);
540 if (t<=TimeEstimate) {
541 TimeEstimate = t;
542 commonTailIndex = i;
543 }
544 }
545
546 MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
547 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
548
Bill Wendling3403bcd2009-08-22 20:03:00 +0000549 DEBUG(errs() << "\nSplitting " << MBB->getNumber() << ", size "
550 << maxCommonTailLength);
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000551
552 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
553 SameTails[commonTailIndex].first->second = newMBB;
554 SameTails[commonTailIndex].second = newMBB->begin();
555 // If we split PredBB, newMBB is the new predecessor.
556 if (PredBB==MBB)
557 PredBB = newMBB;
558
559 return commonTailIndex;
560}
561
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000562// See if any of the blocks in MergePotentials (which all have a common single
563// successor, or all have no successor) can be tail-merged. If there is a
564// successor, any blocks in MergePotentials that are not tail-merged and
565// are not immediately before Succ must have an unconditional branch to
566// Succ added (but the predecessor/successor lists need no adjustment).
567// The lone predecessor of Succ that falls through into Succ,
568// if any, is given in PredBB.
569
570bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
571 MachineBasicBlock* PredBB) {
Evan Cheng030a0a02009-09-04 07:47:40 +0000572 bool MadeChange = false;
573
Evan Cheng31886db2008-02-19 02:09:37 +0000574 // It doesn't make sense to save a single instruction since tail merging
575 // will add a jump.
576 // FIXME: Ask the target to provide the threshold?
577 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
Chris Lattner12143052006-10-21 00:47:49 +0000578
Bill Wendling3403bcd2009-08-22 20:03:00 +0000579 DEBUG(errs() << "\nTryMergeBlocks " << MergePotentials.size() << '\n');
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000580
Chris Lattner12143052006-10-21 00:47:49 +0000581 // Sort by hash value so that blocks with identical end sequences sort
582 // together.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000583 std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
Chris Lattner12143052006-10-21 00:47:49 +0000584
585 // Walk through equivalence sets looking for actual exact matches.
586 while (MergePotentials.size() > 1) {
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000587 unsigned CurHash = prior(MergePotentials.end())->first;
Chris Lattner12143052006-10-21 00:47:49 +0000588
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000589 // Build SameTails, identifying the set of blocks with this hash code
590 // and with the maximum number of instructions in common.
591 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
592 minCommonTailLength);
Dale Johannesen7aea8322007-05-23 21:07:20 +0000593
Dale Johannesena5a21172007-06-01 23:02:45 +0000594 // If we didn't find any pair that has at least minCommonTailLength
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000595 // instructions in common, remove all blocks with this hash code and retry.
596 if (SameTails.empty()) {
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000597 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
Dale Johannesen7aea8322007-05-23 21:07:20 +0000598 continue;
Chris Lattner12143052006-10-21 00:47:49 +0000599 }
Chris Lattner1d08d832006-11-01 01:16:12 +0000600
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000601 // If one of the blocks is the entire common tail (and not the entry
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000602 // block, which we can't jump to), we can treat all blocks with this same
603 // tail at once. Use PredBB if that is one of the possibilities, as that
604 // will not introduce any extra branches.
605 MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
606 getParent()->begin();
607 unsigned int commonTailIndex, i;
608 for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000609 MachineBasicBlock *MBB = SameTails[i].first->second;
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000610 if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
611 commonTailIndex = i;
612 if (MBB==PredBB)
613 break;
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000614 }
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000615 }
Dale Johannesena5a21172007-06-01 23:02:45 +0000616
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000617 if (commonTailIndex==SameTails.size()) {
618 // None of the blocks consist entirely of the common tail.
619 // Split a block so that one does.
620 commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
Chris Lattner1d08d832006-11-01 01:16:12 +0000621 }
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000622
623 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
624 // MBB is common tail. Adjust all other BB's to jump to this one.
625 // Traversal must be forwards so erases work.
Bill Wendling3403bcd2009-08-22 20:03:00 +0000626 DEBUG(errs() << "\nUsing common tail " << MBB->getNumber() << " for ");
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000627 for (unsigned int i=0; i<SameTails.size(); ++i) {
628 if (commonTailIndex==i)
629 continue;
Bill Wendling3403bcd2009-08-22 20:03:00 +0000630 DEBUG(errs() << SameTails[i].first->second->getNumber() << ",");
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000631 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
632 ReplaceTailWithBranchTo(SameTails[i].second, MBB);
633 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
634 MergePotentials.erase(SameTails[i].first);
Chris Lattner12143052006-10-21 00:47:49 +0000635 }
Bill Wendling3403bcd2009-08-22 20:03:00 +0000636 DEBUG(errs() << "\n");
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000637 // We leave commonTailIndex in the worklist in case there are other blocks
638 // that match it with a smaller number of instructions.
Chris Lattner1d08d832006-11-01 01:16:12 +0000639 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000640 }
Chris Lattner12143052006-10-21 00:47:49 +0000641 return MadeChange;
642}
643
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000644bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000645
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000646 if (!EnableTailMerge) return false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000647
Evan Cheng030a0a02009-09-04 07:47:40 +0000648 bool MadeChange = false;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000649
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000650 // First find blocks with no successors.
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000651 MergePotentials.clear();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000652 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
653 if (I->succ_empty())
Dale Johannesen7aea8322007-05-23 21:07:20 +0000654 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000655 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000656 // See if we can do any tail merging on those.
Dale Johannesen6ae83fa2008-05-09 21:24:35 +0000657 if (MergePotentials.size() < TailMergeThreshold &&
658 MergePotentials.size() >= 2)
Dale Johannesen53af4c02007-06-08 00:34:27 +0000659 MadeChange |= TryMergeBlocks(NULL, NULL);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000660
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000661 // Look at blocks (IBB) with multiple predecessors (PBB).
662 // We change each predecessor to a canonical form, by
663 // (1) temporarily removing any unconditional branch from the predecessor
664 // to IBB, and
665 // (2) alter conditional branches so they branch to the other block
666 // not IBB; this may require adding back an unconditional branch to IBB
667 // later, where there wasn't one coming in. E.g.
668 // Bcc IBB
669 // fallthrough to QBB
670 // here becomes
671 // Bncc QBB
672 // with a conceptual B to IBB after that, which never actually exists.
673 // With those changes, we see whether the predecessors' tails match,
674 // and merge them if so. We change things out of canonical form and
675 // back to the way they were later in the process. (OptimizeBranches
676 // would undo some of this, but we can't use it, because we'd get into
677 // a compile-time infinite loop repeatedly doing and undoing the same
678 // transformations.)
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000679
680 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Dale Johannesen62bc8a42008-07-01 21:50:14 +0000681 if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
Dan Gohmanda658222009-08-18 15:18:18 +0000682 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000683 MachineBasicBlock *IBB = I;
684 MachineBasicBlock *PredBB = prior(I);
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000685 MergePotentials.clear();
Dale Johannesen1a90a5a2007-06-08 01:08:52 +0000686 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
687 E2 = I->pred_end();
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000688 P != E2; ++P) {
689 MachineBasicBlock* PBB = *P;
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000690 // Skip blocks that loop to themselves, can't tail merge these.
691 if (PBB==IBB)
692 continue;
Dan Gohmanda658222009-08-18 15:18:18 +0000693 // Visit each predecessor only once.
694 if (!UniquePreds.insert(PBB))
695 continue;
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000696 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000697 SmallVector<MachineOperand, 4> Cond;
Evan Chengdc54d312009-02-09 07:14:22 +0000698 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000699 // Failing case: IBB is the target of a cbr, and
700 // we cannot reverse the branch.
Owen Anderson44eb65c2008-08-14 22:49:33 +0000701 SmallVector<MachineOperand, 4> NewCond(Cond);
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000702 if (!Cond.empty() && TBB==IBB) {
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000703 if (TII->ReverseBranchCondition(NewCond))
704 continue;
705 // This is the QBB case described above
706 if (!FBB)
707 FBB = next(MachineFunction::iterator(PBB));
708 }
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000709 // Failing case: the only way IBB can be reached from PBB is via
710 // exception handling. Happens for landing pads. Would be nice
711 // to have a bit in the edge so we didn't have to do all this.
712 if (IBB->isLandingPad()) {
713 MachineFunction::iterator IP = PBB; IP++;
714 MachineBasicBlock* PredNextBB = NULL;
715 if (IP!=MF.end())
716 PredNextBB = IP;
717 if (TBB==NULL) {
718 if (IBB!=PredNextBB) // fallthrough
719 continue;
720 } else if (FBB) {
721 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
722 continue;
Dan Gohman30359592008-01-29 13:02:09 +0000723 } else if (Cond.empty()) {
Dale Johannesenfe7e3972007-06-04 23:52:54 +0000724 if (TBB!=IBB) // ubr
725 continue;
726 } else {
727 if (TBB!=IBB && IBB!=PredNextBB) // cbr
728 continue;
729 }
730 }
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000731 // Remove the unconditional branch at the end, if any.
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000732 if (TBB && (Cond.empty() || FBB)) {
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000733 TII->RemoveBranch(*PBB);
Dale Johannesen6b8583c2008-05-09 23:28:24 +0000734 if (!Cond.empty())
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000735 // reinsert conditional branch only, for now
Dale Johannesen76b38fc2007-05-10 01:01:49 +0000736 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000737 }
Dale Johannesen7aea8322007-05-23 21:07:20 +0000738 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000739 }
740 }
741 if (MergePotentials.size() >= 2)
742 MadeChange |= TryMergeBlocks(I, PredBB);
743 // Reinsert an unconditional branch if needed.
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000744 // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
Dale Johannesen1cf08c12007-05-18 01:28:58 +0000745 PredBB = prior(I); // this may have been changed in TryMergeBlocks
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000746 if (MergePotentials.size()==1 &&
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000747 MergePotentials.begin()->second != PredBB)
748 FixTail(MergePotentials.begin()->second, I, TII);
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000749 }
750 }
Dale Johannesen7d33b4c2007-05-07 20:57:21 +0000751 return MadeChange;
752}
Chris Lattner12143052006-10-21 00:47:49 +0000753
754//===----------------------------------------------------------------------===//
755// Branch Optimization
756//===----------------------------------------------------------------------===//
757
758bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
Evan Cheng030a0a02009-09-04 07:47:40 +0000759 bool MadeChange = false;
Chris Lattner12143052006-10-21 00:47:49 +0000760
Dale Johannesen6b896ce2007-02-17 00:44:34 +0000761 // Make sure blocks are numbered in order
762 MF.RenumberBlocks();
763
Chris Lattner12143052006-10-21 00:47:49 +0000764 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
765 MachineBasicBlock *MBB = I++;
Evan Cheng030a0a02009-09-04 07:47:40 +0000766 MadeChange |= OptimizeBlock(MBB);
Chris Lattner12143052006-10-21 00:47:49 +0000767
768 // If it is dead, remove it.
Jim Laskey033c9712007-02-22 16:39:03 +0000769 if (MBB->pred_empty()) {
Chris Lattner12143052006-10-21 00:47:49 +0000770 RemoveDeadBlock(MBB);
771 MadeChange = true;
772 ++NumDeadBlocks;
773 }
774 }
775 return MadeChange;
776}
777
778
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000779/// CanFallThrough - Return true if the specified block (with the specified
780/// branch condition) can implicitly transfer control to the block after it by
781/// falling off the end of it. This should return false if it can reach the
782/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
783///
784/// True is a conservative answer.
785///
786bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
787 bool BranchUnAnalyzable,
Dale Johannesen51b2b9e2008-05-12 20:33:57 +0000788 MachineBasicBlock *TBB,
789 MachineBasicBlock *FBB,
Owen Anderson44eb65c2008-08-14 22:49:33 +0000790 const SmallVectorImpl<MachineOperand> &Cond) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000791 MachineFunction::iterator Fallthrough = CurBB;
792 ++Fallthrough;
793 // If FallthroughBlock is off the end of the function, it can't fall through.
794 if (Fallthrough == CurBB->getParent()->end())
795 return false;
796
797 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
798 if (!CurBB->isSuccessor(Fallthrough))
799 return false;
800
801 // If we couldn't analyze the branch, assume it could fall through.
802 if (BranchUnAnalyzable) return true;
803
Chris Lattner7d097842006-10-24 01:12:32 +0000804 // If there is no branch, control always falls through.
805 if (TBB == 0) return true;
806
807 // If there is some explicit branch to the fallthrough block, it can obviously
808 // reach, even though the branch should get folded to fall through implicitly.
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000809 if (MachineFunction::iterator(TBB) == Fallthrough ||
810 MachineFunction::iterator(FBB) == Fallthrough)
Chris Lattner7d097842006-10-24 01:12:32 +0000811 return true;
812
813 // If it's an unconditional branch to some block not the fall through, it
814 // doesn't fall through.
815 if (Cond.empty()) return false;
816
817 // Otherwise, if it is conditional and has no explicit false block, it falls
818 // through.
Chris Lattnerc2e91e32006-10-25 22:21:37 +0000819 return FBB == 0;
Chris Lattner7d097842006-10-24 01:12:32 +0000820}
821
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000822/// CanFallThrough - Return true if the specified can implicitly transfer
823/// control to the block after it by falling off the end of it. This should
824/// return false if it can reach the block after it, but it uses an explicit
825/// branch to do so (e.g. a table jump).
826///
827/// True is a conservative answer.
828///
829bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
830 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000831 SmallVector<MachineOperand, 4> Cond;
Evan Chengdc54d312009-02-09 07:14:22 +0000832 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond, true);
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000833 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
834}
835
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000836/// IsBetterFallthrough - Return true if it would be clearly better to
837/// fall-through to MBB1 than to fall through into MBB2. This has to return
838/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
839/// result in infinite loops.
840static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
Chris Lattner69244302008-01-07 01:56:04 +0000841 MachineBasicBlock *MBB2) {
Chris Lattner154e1042006-11-18 21:30:35 +0000842 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
843 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000844 // optimize branches that branch to either a return block or an assert block
845 // into a fallthrough to the return.
846 if (MBB1->empty() || MBB2->empty()) return false;
Christopher Lamb11a4f642007-12-10 07:24:06 +0000847
848 // If there is a clear successor ordering we make sure that one block
849 // will fall through to the next
850 if (MBB1->isSuccessor(MBB2)) return true;
851 if (MBB2->isSuccessor(MBB1)) return false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000852
853 MachineInstr *MBB1I = --MBB1->end();
854 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner749c6f62008-01-07 07:27:27 +0000855 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000856}
857
Chris Lattner7821a8a2006-10-14 00:21:48 +0000858/// OptimizeBlock - Analyze and optimize control flow related to the specified
859/// block. This is never called on the entry block.
Evan Cheng030a0a02009-09-04 07:47:40 +0000860bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
861 bool MadeChange = false;
862
Chris Lattner7d097842006-10-24 01:12:32 +0000863 MachineFunction::iterator FallThrough = MBB;
864 ++FallThrough;
865
Chris Lattnereb15eee2006-10-13 20:43:10 +0000866 // If this block is empty, make everyone use its fall-through, not the block
Dale Johannesena52dd152007-05-31 21:54:00 +0000867 // explicitly. Landing pads should not do this since the landing-pad table
868 // points to this block.
869 if (MBB->empty() && !MBB->isLandingPad()) {
Chris Lattner386e2902006-10-21 05:08:28 +0000870 // Dead block? Leave for cleanup later.
Evan Cheng030a0a02009-09-04 07:47:40 +0000871 if (MBB->pred_empty()) return MadeChange;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000872
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000873 if (FallThrough == MBB->getParent()->end()) {
874 // TODO: Simplify preds to not branch here if possible!
875 } else {
876 // Rewrite all predecessors of the old block to go to the fallthrough
877 // instead.
Jim Laskey033c9712007-02-22 16:39:03 +0000878 while (!MBB->pred_empty()) {
Chris Lattner7821a8a2006-10-14 00:21:48 +0000879 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
Evan Cheng0370fad2007-06-04 06:44:01 +0000880 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000881 }
Chris Lattnerc50ffcb2006-10-17 17:13:52 +0000882 // If MBB was the target of a jump table, update jump tables to go to the
883 // fallthrough instead.
Chris Lattner6acfe122006-10-28 18:34:47 +0000884 MBB->getParent()->getJumpTableInfo()->
885 ReplaceMBBInJumpTables(MBB, FallThrough);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000886 MadeChange = true;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000887 }
Evan Cheng030a0a02009-09-04 07:47:40 +0000888 return MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +0000889 }
890
Chris Lattner7821a8a2006-10-14 00:21:48 +0000891 // Check to see if we can simplify the terminator of the block before this
892 // one.
Chris Lattner7d097842006-10-24 01:12:32 +0000893 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
Chris Lattnerffddf6b2006-10-17 18:16:40 +0000894
Chris Lattner7821a8a2006-10-14 00:21:48 +0000895 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +0000896 SmallVector<MachineOperand, 4> PriorCond;
Chris Lattner6b0e3f82006-10-29 21:05:41 +0000897 bool PriorUnAnalyzable =
Evan Chengdc54d312009-02-09 07:14:22 +0000898 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
Chris Lattner386e2902006-10-21 05:08:28 +0000899 if (!PriorUnAnalyzable) {
900 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2bdb7d02007-06-18 22:43:58 +0000901 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
902 !PriorCond.empty());
Chris Lattner386e2902006-10-21 05:08:28 +0000903
Chris Lattner7821a8a2006-10-14 00:21:48 +0000904 // If the previous branch is conditional and both conditions go to the same
Chris Lattner2d47bd92006-10-21 05:43:30 +0000905 // destination, remove the branch, replacing it with an unconditional one or
906 // a fall-through.
Chris Lattner7821a8a2006-10-14 00:21:48 +0000907 if (PriorTBB && PriorTBB == PriorFBB) {
Chris Lattner386e2902006-10-21 05:08:28 +0000908 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000909 PriorCond.clear();
Chris Lattner7d097842006-10-24 01:12:32 +0000910 if (PriorTBB != MBB)
Chris Lattner386e2902006-10-21 05:08:28 +0000911 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000912 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000913 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000914 return OptimizeBlock(MBB);
915 }
916
917 // If the previous branch *only* branches to *this* block (conditional or
918 // not) remove the branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000919 if (PriorTBB == MBB && PriorFBB == 0) {
Chris Lattner386e2902006-10-21 05:08:28 +0000920 TII->RemoveBranch(PrevBB);
Chris Lattner7821a8a2006-10-14 00:21:48 +0000921 MadeChange = true;
Chris Lattner12143052006-10-21 00:47:49 +0000922 ++NumBranchOpts;
Chris Lattner7821a8a2006-10-14 00:21:48 +0000923 return OptimizeBlock(MBB);
924 }
Chris Lattner2d47bd92006-10-21 05:43:30 +0000925
926 // If the prior block branches somewhere else on the condition and here if
927 // the condition is false, remove the uncond second branch.
Chris Lattner7d097842006-10-24 01:12:32 +0000928 if (PriorFBB == MBB) {
Chris Lattner2d47bd92006-10-21 05:43:30 +0000929 TII->RemoveBranch(PrevBB);
930 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
931 MadeChange = true;
932 ++NumBranchOpts;
933 return OptimizeBlock(MBB);
934 }
Chris Lattnera2d79952006-10-21 05:54:00 +0000935
936 // If the prior block branches here on true and somewhere else on false, and
937 // if the branch condition is reversible, reverse the branch to create a
938 // fall-through.
Chris Lattner7d097842006-10-24 01:12:32 +0000939 if (PriorTBB == MBB) {
Owen Anderson44eb65c2008-08-14 22:49:33 +0000940 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Chris Lattnera2d79952006-10-21 05:54:00 +0000941 if (!TII->ReverseBranchCondition(NewPriorCond)) {
942 TII->RemoveBranch(PrevBB);
943 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
944 MadeChange = true;
945 ++NumBranchOpts;
946 return OptimizeBlock(MBB);
947 }
948 }
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000949
Dan Gohman6d312682009-10-22 00:03:58 +0000950 // If this block has no successors (e.g. it is a return block or ends with
951 // a call to a no-return function like abort or __cxa_throw) and if the pred
952 // falls through into this block, and if it would otherwise fall through
953 // into the block after this, move this block to the end of the function.
Chris Lattner154e1042006-11-18 21:30:35 +0000954 //
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000955 // We consider it more likely that execution will stay in the function (e.g.
956 // due to loops) than it is to exit it. This asserts in loops etc, moving
957 // the assert condition out of the loop body.
Dan Gohman6d312682009-10-22 00:03:58 +0000958 if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
Chris Lattner154e1042006-11-18 21:30:35 +0000959 MachineFunction::iterator(PriorTBB) == FallThrough &&
960 !CanFallThrough(MBB)) {
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000961 bool DoTransform = true;
962
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000963 // We have to be careful that the succs of PredBB aren't both no-successor
964 // blocks. If neither have successors and if PredBB is the second from
965 // last block in the function, we'd just keep swapping the two blocks for
966 // last. Only do the swap if one is clearly better to fall through than
967 // the other.
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000968 if (FallThrough == --MBB->getParent()->end() &&
Chris Lattner69244302008-01-07 01:56:04 +0000969 !IsBetterFallthrough(PriorTBB, MBB))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000970 DoTransform = false;
971
972 // We don't want to do this transformation if we have control flow like:
973 // br cond BB2
974 // BB1:
975 // ..
976 // jmp BBX
977 // BB2:
978 // ..
979 // ret
980 //
981 // In this case, we could actually be moving the return block *into* a
982 // loop!
Chris Lattner4b105912006-11-18 22:25:39 +0000983 if (DoTransform && !MBB->succ_empty() &&
984 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000985 DoTransform = false;
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000986
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000987
988 if (DoTransform) {
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000989 // Reverse the branch so we will fall through on the previous true cond.
Owen Anderson44eb65c2008-08-14 22:49:33 +0000990 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000991 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Bill Wendling3403bcd2009-08-22 20:03:00 +0000992 DEBUG(errs() << "\nMoving MBB: " << *MBB
993 << "To make fallthrough to: " << *PriorTBB << "\n");
Chris Lattnerf10a56a2006-11-18 21:56:39 +0000994
Chris Lattnera7bef4a2006-11-18 20:47:54 +0000995 TII->RemoveBranch(PrevBB);
996 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
997
998 // Move this block to the end of the function.
999 MBB->moveAfter(--MBB->getParent()->end());
1000 MadeChange = true;
1001 ++NumBranchOpts;
Evan Cheng030a0a02009-09-04 07:47:40 +00001002 return MadeChange;
Chris Lattnera7bef4a2006-11-18 20:47:54 +00001003 }
1004 }
1005 }
Chris Lattner7821a8a2006-10-14 00:21:48 +00001006 }
Chris Lattner7821a8a2006-10-14 00:21:48 +00001007
Chris Lattner386e2902006-10-21 05:08:28 +00001008 // Analyze the branch in the current block.
1009 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
Owen Anderson44eb65c2008-08-14 22:49:33 +00001010 SmallVector<MachineOperand, 4> CurCond;
Evan Chengdc54d312009-02-09 07:14:22 +00001011 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001012 if (!CurUnAnalyzable) {
Chris Lattner386e2902006-10-21 05:08:28 +00001013 // If the CFG for the prior block has extra edges, remove them.
Evan Cheng2bdb7d02007-06-18 22:43:58 +00001014 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
Chris Lattnereb15eee2006-10-13 20:43:10 +00001015
Chris Lattner5d056952006-11-08 01:03:21 +00001016 // If this is a two-way branch, and the FBB branches to this block, reverse
1017 // the condition so the single-basic-block loop is faster. Instead of:
1018 // Loop: xxx; jcc Out; jmp Loop
1019 // we want:
1020 // Loop: xxx; jncc Loop; jmp Out
1021 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
Owen Anderson44eb65c2008-08-14 22:49:33 +00001022 SmallVector<MachineOperand, 4> NewCond(CurCond);
Chris Lattner5d056952006-11-08 01:03:21 +00001023 if (!TII->ReverseBranchCondition(NewCond)) {
1024 TII->RemoveBranch(*MBB);
1025 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1026 MadeChange = true;
1027 ++NumBranchOpts;
1028 return OptimizeBlock(MBB);
1029 }
1030 }
1031
1032
Chris Lattner386e2902006-10-21 05:08:28 +00001033 // If this branch is the only thing in its block, see if we can forward
1034 // other blocks across it.
1035 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner749c6f62008-01-07 07:27:27 +00001036 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
Chris Lattner386e2902006-10-21 05:08:28 +00001037 // This block may contain just an unconditional branch. Because there can
1038 // be 'non-branch terminators' in the block, try removing the branch and
1039 // then seeing if the block is empty.
1040 TII->RemoveBranch(*MBB);
1041
1042 // If this block is just an unconditional branch to CurTBB, we can
1043 // usually completely eliminate the block. The only case we cannot
1044 // completely eliminate the block is when the block before this one
1045 // falls through into MBB and we can't understand the prior block's branch
1046 // condition.
Chris Lattnercf420cc2006-10-28 17:32:47 +00001047 if (MBB->empty()) {
1048 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1049 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1050 !PrevBB.isSuccessor(MBB)) {
1051 // If the prior block falls through into us, turn it into an
1052 // explicit branch to us to make updates simpler.
1053 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1054 PriorTBB != MBB && PriorFBB != MBB) {
1055 if (PriorTBB == 0) {
Chris Lattner6acfe122006-10-28 18:34:47 +00001056 assert(PriorCond.empty() && PriorFBB == 0 &&
1057 "Bad branch analysis");
Chris Lattnercf420cc2006-10-28 17:32:47 +00001058 PriorTBB = MBB;
1059 } else {
1060 assert(PriorFBB == 0 && "Machine CFG out of date!");
1061 PriorFBB = MBB;
1062 }
1063 TII->RemoveBranch(PrevBB);
1064 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
Chris Lattner386e2902006-10-21 05:08:28 +00001065 }
Chris Lattner386e2902006-10-21 05:08:28 +00001066
Chris Lattnercf420cc2006-10-28 17:32:47 +00001067 // Iterate through all the predecessors, revectoring each in-turn.
David Greene8a46d342007-06-29 02:45:24 +00001068 size_t PI = 0;
Chris Lattnercf420cc2006-10-28 17:32:47 +00001069 bool DidChange = false;
1070 bool HasBranchToSelf = false;
David Greene8a46d342007-06-29 02:45:24 +00001071 while(PI != MBB->pred_size()) {
1072 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1073 if (PMBB == MBB) {
Chris Lattnercf420cc2006-10-28 17:32:47 +00001074 // If this block has an uncond branch to itself, leave it.
1075 ++PI;
1076 HasBranchToSelf = true;
1077 } else {
1078 DidChange = true;
David Greene8a46d342007-06-29 02:45:24 +00001079 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
Dale Johannesenbf06f6a2009-05-11 21:54:13 +00001080 // If this change resulted in PMBB ending in a conditional
1081 // branch where both conditions go to the same destination,
1082 // change this to an unconditional branch (and fix the CFG).
1083 MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1084 SmallVector<MachineOperand, 4> NewCurCond;
1085 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1086 NewCurFBB, NewCurCond, true);
1087 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1088 TII->RemoveBranch(*PMBB);
1089 NewCurCond.clear();
1090 TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond);
1091 MadeChange = true;
1092 ++NumBranchOpts;
1093 PMBB->CorrectExtraCFGEdges(NewCurTBB, NewCurFBB, false);
1094 }
Chris Lattnercf420cc2006-10-28 17:32:47 +00001095 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001096 }
Chris Lattner386e2902006-10-21 05:08:28 +00001097
Chris Lattnercf420cc2006-10-28 17:32:47 +00001098 // Change any jumptables to go to the new MBB.
Chris Lattner6acfe122006-10-28 18:34:47 +00001099 MBB->getParent()->getJumpTableInfo()->
1100 ReplaceMBBInJumpTables(MBB, CurTBB);
Chris Lattnercf420cc2006-10-28 17:32:47 +00001101 if (DidChange) {
1102 ++NumBranchOpts;
1103 MadeChange = true;
Evan Cheng030a0a02009-09-04 07:47:40 +00001104 if (!HasBranchToSelf) return MadeChange;
Chris Lattnercf420cc2006-10-28 17:32:47 +00001105 }
Chris Lattner4bc135e2006-10-21 06:11:43 +00001106 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001107 }
Chris Lattnereb15eee2006-10-13 20:43:10 +00001108
Chris Lattner386e2902006-10-21 05:08:28 +00001109 // Add the branch back if the block is more than just an uncond branch.
1110 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
Chris Lattner21ab22e2004-07-31 10:01:27 +00001111 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001112 }
1113
1114 // If the prior block doesn't fall through into this block, and if this
1115 // block doesn't fall through into some other block, see if we can find a
1116 // place to move this block where a fall-through will happen.
1117 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1118 PriorTBB, PriorFBB, PriorCond)) {
1119 // Now we know that there was no fall-through into this block, check to
1120 // see if it has a fall-through into its successor.
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001121 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
Chris Lattner77edc4b2007-04-30 23:35:00 +00001122 CurCond);
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001123
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001124 if (!MBB->isLandingPad()) {
1125 // Check all the predecessors of this block. If one of them has no fall
1126 // throughs, move this block right after it.
1127 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1128 E = MBB->pred_end(); PI != E; ++PI) {
1129 // Analyze the branch at the end of the pred.
1130 MachineBasicBlock *PredBB = *PI;
1131 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1132 if (PredBB != MBB && !CanFallThrough(PredBB)
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001133 && (!CurFallsThru || !CurTBB || !CurFBB)
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001134 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1135 // If the current block doesn't fall through, just move it.
1136 // If the current block can fall through and does not end with a
1137 // conditional branch, we need to append an unconditional jump to
1138 // the (current) next block. To avoid a possible compile-time
1139 // infinite loop, move blocks only backward in this case.
Dale Johannesen76b38fc2007-05-10 01:01:49 +00001140 // Also, if there are already 2 branches here, we cannot add a third;
1141 // this means we have the case
1142 // Bcc next
1143 // B elsewhere
1144 // next:
Jim Laskey02b3f5e2007-02-21 22:42:20 +00001145 if (CurFallsThru) {
1146 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1147 CurCond.clear();
1148 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1149 }
1150 MBB->moveAfter(PredBB);
1151 MadeChange = true;
1152 return OptimizeBlock(MBB);
Chris Lattner7d097842006-10-24 01:12:32 +00001153 }
1154 }
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001155 }
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001156
Dale Johannesen6b896ce2007-02-17 00:44:34 +00001157 if (!CurFallsThru) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001158 // Check all successors to see if we can move this block before it.
1159 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1160 E = MBB->succ_end(); SI != E; ++SI) {
1161 // Analyze the branch at the end of the block before the succ.
1162 MachineBasicBlock *SuccBB = *SI;
1163 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001164 std::vector<MachineOperand> SuccPrevCond;
Chris Lattner77edc4b2007-04-30 23:35:00 +00001165
1166 // If this block doesn't already fall-through to that successor, and if
1167 // the succ doesn't already have a block that can fall through into it,
1168 // and if the successor isn't an EH destination, we can arrange for the
1169 // fallthrough to happen.
1170 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1171 !SuccBB->isLandingPad()) {
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001172 MBB->moveBefore(SuccBB);
1173 MadeChange = true;
1174 return OptimizeBlock(MBB);
1175 }
1176 }
1177
1178 // Okay, there is no really great place to put this block. If, however,
1179 // the block before this one would be a fall-through if this block were
1180 // removed, move this block to the end of the function.
1181 if (FallThrough != MBB->getParent()->end() &&
1182 PrevBB.isSuccessor(FallThrough)) {
1183 MBB->moveAfter(--MBB->getParent()->end());
1184 MadeChange = true;
Evan Cheng030a0a02009-09-04 07:47:40 +00001185 return MadeChange;
Chris Lattner6b0e3f82006-10-29 21:05:41 +00001186 }
Chris Lattner7d097842006-10-24 01:12:32 +00001187 }
Chris Lattner21ab22e2004-07-31 10:01:27 +00001188 }
Evan Cheng030a0a02009-09-04 07:47:40 +00001189
1190 return MadeChange;
Chris Lattner21ab22e2004-07-31 10:01:27 +00001191}