blob: 11777d5ea14e37ea88a02737f083ec53e8e80682 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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
19#define DEBUG_TYPE "branchfolding"
Evan Cheng9dcb7602009-09-04 07:47:40 +000020#include "BranchFolding.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/CodeGen/Passes.h"
22#include "llvm/CodeGen/MachineModuleInfo.h"
23#include "llvm/CodeGen/MachineFunctionPass.h"
24#include "llvm/CodeGen/MachineJumpTableInfo.h"
25#include "llvm/CodeGen/RegisterScavenging.h"
26#include "llvm/Target/TargetInstrInfo.h"
27#include "llvm/Target/TargetMachine.h"
Dan Gohman1e57df32008-02-10 18:45:23 +000028#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000031#include "llvm/Support/ErrorHandling.h"
Bill Wendlingef26d402009-08-22 20:03:00 +000032#include "llvm/Support/raw_ostream.h"
Evan Cheng682e4aa2008-04-10 02:32:10 +000033#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034#include "llvm/ADT/Statistic.h"
35#include "llvm/ADT/STLExtras.h"
36#include <algorithm>
37using namespace llvm;
38
39STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
40STATISTIC(NumBranchOpts, "Number of branches optimized");
41STATISTIC(NumTailMerge , "Number of block tails merged");
42static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
43 cl::init(cl::BOU_UNSET), cl::Hidden);
Dan Gohman089efff2008-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 Johannesen2d9dfce2008-10-27 02:10:21 +000048 cl::init(150), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050
Evan Cheng9dcb7602009-09-04 07:47:40 +000051char BranchFolderPass::ID = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052
Bob Wilsonafe63292009-10-27 23:49:38 +000053FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge,
54 CodeGenOpt::Level OptLevel) {
55 return new BranchFolderPass(DefaultEnableTailMerge, OptLevel);
Evan Cheng9dcb7602009-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 Wilsonafe63292009-10-27 23:49:38 +000067BranchFolder::BranchFolder(bool defaultEnableTailMerge, CodeGenOpt::Level OL) {
68 OptLevel = OL;
Evan Cheng9dcb7602009-09-04 07:47:40 +000069 switch (FlagEnableTailMerge) {
70 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
71 case cl::BOU_TRUE: EnableTailMerge = true; break;
72 case cl::BOU_FALSE: EnableTailMerge = false; break;
73 }
Evan Chengfe0a2792009-09-03 23:54:22 +000074}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000075
76/// RemoveDeadBlock - Remove the specified dead machine basic block from the
77/// function, updating the CFG.
78void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
79 assert(MBB->pred_empty() && "MBB must be dead!");
Bill Wendlingef26d402009-08-22 20:03:00 +000080 DEBUG(errs() << "\nRemoving MBB: " << *MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081
82 MachineFunction *MF = MBB->getParent();
83 // drop all successors.
84 while (!MBB->succ_empty())
85 MBB->removeSuccessor(MBB->succ_end()-1);
86
Duncan Sands342271d2008-07-29 20:56:02 +000087 // If there are any labels in the basic block, unregister them from
88 // MachineModuleInfo.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 if (MMI && !MBB->empty()) {
90 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
91 I != E; ++I) {
Duncan Sands342271d2008-07-29 20:56:02 +000092 if (I->isLabel())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093 // The label ID # is always operand #0, an immediate.
94 MMI->InvalidateLabel(I->getOperand(0).getImm());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 }
96 }
97
98 // Remove the block.
Dan Gohman221a4372008-07-07 23:14:23 +000099 MF->erase(MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000100}
101
Evan Cheng682e4aa2008-04-10 02:32:10 +0000102/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
103/// followed by terminators, and if the implicitly defined registers are not
104/// used by the terminators, remove those implicit_def's. e.g.
105/// BB1:
106/// r0 = implicit_def
107/// r1 = implicit_def
108/// br
109/// This block can be optimized away later if the implicit instructions are
110/// removed.
111bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
112 SmallSet<unsigned, 4> ImpDefRegs;
113 MachineBasicBlock::iterator I = MBB->begin();
114 while (I != MBB->end()) {
115 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
116 break;
117 unsigned Reg = I->getOperand(0).getReg();
118 ImpDefRegs.insert(Reg);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000119 for (const unsigned *SubRegs = TRI->getSubRegisters(Reg);
Evan Cheng682e4aa2008-04-10 02:32:10 +0000120 unsigned SubReg = *SubRegs; ++SubRegs)
121 ImpDefRegs.insert(SubReg);
122 ++I;
123 }
124 if (ImpDefRegs.empty())
125 return false;
126
127 MachineBasicBlock::iterator FirstTerm = I;
128 while (I != MBB->end()) {
129 if (!TII->isUnpredicatedTerminator(I))
130 return false;
131 // See if it uses any of the implicitly defined registers.
132 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
133 MachineOperand &MO = I->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000134 if (!MO.isReg() || !MO.isUse())
Evan Cheng682e4aa2008-04-10 02:32:10 +0000135 continue;
136 unsigned Reg = MO.getReg();
137 if (ImpDefRegs.count(Reg))
138 return false;
139 }
140 ++I;
141 }
142
143 I = MBB->begin();
144 while (I != FirstTerm) {
145 MachineInstr *ImpDefMI = &*I;
146 ++I;
147 MBB->erase(ImpDefMI);
148 }
149
150 return true;
151}
152
Evan Cheng9dcb7602009-09-04 07:47:40 +0000153/// OptimizeFunction - Perhaps branch folding, tail merging and other
154/// CFG optimizations on the given function.
155bool BranchFolder::OptimizeFunction(MachineFunction &MF,
156 const TargetInstrInfo *tii,
157 const TargetRegisterInfo *tri,
158 MachineModuleInfo *mmi) {
159 if (!tii) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000160
Evan Cheng9dcb7602009-09-04 07:47:40 +0000161 TII = tii;
162 TRI = tri;
163 MMI = mmi;
164
165 RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
Evan Cheng682e4aa2008-04-10 02:32:10 +0000166
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 // Fix CFG. The later algorithms expect it to be right.
Evan Cheng9dcb7602009-09-04 07:47:40 +0000168 bool MadeChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000169 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
170 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000171 SmallVector<MachineOperand, 4> Cond;
Evan Chengeac31642009-02-09 07:14:22 +0000172 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
Evan Cheng9dcb7602009-09-04 07:47:40 +0000173 MadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
174 MadeChange |= OptimizeImpDefsBlock(MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 }
176
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177
178 bool MadeChangeThisIteration = true;
179 while (MadeChangeThisIteration) {
180 MadeChangeThisIteration = false;
181 MadeChangeThisIteration |= TailMergeBlocks(MF);
182 MadeChangeThisIteration |= OptimizeBranches(MF);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000183 MadeChange |= MadeChangeThisIteration;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 }
185
186 // See if any jump tables have become mergable or dead as the code generator
187 // did its thing.
188 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
189 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
190 if (!JTs.empty()) {
191 // Figure out how these jump tables should be merged.
192 std::vector<unsigned> JTMapping;
193 JTMapping.reserve(JTs.size());
194
195 // We always keep the 0th jump table.
196 JTMapping.push_back(0);
197
198 // Scan the jump tables, seeing if there are any duplicates. Note that this
199 // is N^2, which should be fixed someday.
Evan Cheng9dcb7602009-09-04 07:47:40 +0000200 for (unsigned i = 1, e = JTs.size(); i != e; ++i) {
201 if (JTs[i].MBBs.empty())
202 JTMapping.push_back(i);
203 else
204 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
205 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206
207 // If a jump table was merge with another one, walk the function rewriting
208 // references to jump tables to reference the new JT ID's. Keep track of
209 // whether we see a jump table idx, if not, we can delete the JT.
Dale Johannesen865e6252008-05-09 23:28:24 +0000210 BitVector JTIsLive(JTs.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
212 BB != E; ++BB) {
213 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
214 I != E; ++I)
215 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
216 MachineOperand &Op = I->getOperand(op);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000217 if (!Op.isJTI()) continue;
Chris Lattner6017d482007-12-30 23:10:15 +0000218 unsigned NewIdx = JTMapping[Op.getIndex()];
219 Op.setIndex(NewIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220
221 // Remember that this JT is live.
Dale Johannesen865e6252008-05-09 23:28:24 +0000222 JTIsLive.set(NewIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 }
224 }
225
226 // Finally, remove dead jump tables. This happens either because the
227 // indirect jump was unreachable (and thus deleted) or because the jump
228 // table was merged with some other one.
229 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
Dale Johannesen865e6252008-05-09 23:28:24 +0000230 if (!JTIsLive.test(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000231 JTI->RemoveJumpTable(i);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000232 MadeChange = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233 }
234 }
Evan Cheng9dcb7602009-09-04 07:47:40 +0000235
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 delete RS;
Evan Cheng9dcb7602009-09-04 07:47:40 +0000237 return MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000238}
239
240//===----------------------------------------------------------------------===//
241// Tail Merging of Blocks
242//===----------------------------------------------------------------------===//
243
244/// HashMachineInstr - Compute a hash value for MI and its operands.
245static unsigned HashMachineInstr(const MachineInstr *MI) {
246 unsigned Hash = MI->getOpcode();
247 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
248 const MachineOperand &Op = MI->getOperand(i);
249
250 // Merge in bits from the operand if easy.
251 unsigned OperandHash = 0;
252 switch (Op.getType()) {
253 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
254 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
255 case MachineOperand::MO_MachineBasicBlock:
Chris Lattner6017d482007-12-30 23:10:15 +0000256 OperandHash = Op.getMBB()->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257 break;
Chris Lattner6017d482007-12-30 23:10:15 +0000258 case MachineOperand::MO_FrameIndex:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 case MachineOperand::MO_ConstantPoolIndex:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000260 case MachineOperand::MO_JumpTableIndex:
Chris Lattner6017d482007-12-30 23:10:15 +0000261 OperandHash = Op.getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262 break;
263 case MachineOperand::MO_GlobalAddress:
264 case MachineOperand::MO_ExternalSymbol:
265 // Global address / external symbol are too hard, don't bother, but do
266 // pull in the offset.
267 OperandHash = Op.getOffset();
268 break;
269 default: break;
270 }
271
272 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
273 }
274 return Hash;
275}
276
277/// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
278/// with no successors, we hash two instructions, because cross-jumping
279/// only saves code when at least two instructions are removed (since a
280/// branch must be inserted). For blocks with a successor, one of the
281/// two blocks to be tail-merged will end with a branch already, so
282/// it gains to cross-jump even for one instruction.
283
284static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
285 unsigned minCommonTailLength) {
286 MachineBasicBlock::const_iterator I = MBB->end();
287 if (I == MBB->begin())
288 return 0; // Empty MBB.
289
290 --I;
291 unsigned Hash = HashMachineInstr(I);
292
293 if (I == MBB->begin() || minCommonTailLength == 1)
294 return Hash; // Single instr MBB.
295
296 --I;
297 // Hash in the second-to-last instruction.
298 Hash ^= HashMachineInstr(I) << 2;
299 return Hash;
300}
301
302/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
303/// of instructions they actually have in common together at their end. Return
304/// iterators for the first shared instruction in each block.
305static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
306 MachineBasicBlock *MBB2,
307 MachineBasicBlock::iterator &I1,
308 MachineBasicBlock::iterator &I2) {
309 I1 = MBB1->end();
310 I2 = MBB2->end();
311
312 unsigned TailLen = 0;
313 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
314 --I1; --I2;
Bill Wendling46329b72007-10-19 21:09:55 +0000315 if (!I1->isIdenticalTo(I2) ||
Bill Wendlingf728a1c2007-10-25 19:49:32 +0000316 // FIXME: This check is dubious. It's used to get around a problem where
Bill Wendling83628182007-10-25 18:23:45 +0000317 // people incorrectly expect inline asm directives to remain in the same
318 // relative order. This is untenable because normal compiler
319 // optimizations (like this one) may reorder and/or merge these
320 // directives.
Bill Wendling46329b72007-10-19 21:09:55 +0000321 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000322 ++I1; ++I2;
323 break;
324 }
325 ++TailLen;
326 }
327 return TailLen;
328}
329
330/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
331/// after it, replacing it with an unconditional branch to NewDest. This
332/// returns true if OldInst's block is modified, false if NewDest is modified.
333void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
334 MachineBasicBlock *NewDest) {
335 MachineBasicBlock *OldBB = OldInst->getParent();
336
337 // Remove all the old successors of OldBB from the CFG.
338 while (!OldBB->succ_empty())
339 OldBB->removeSuccessor(OldBB->succ_begin());
340
341 // Remove all the dead instructions from the end of OldBB.
342 OldBB->erase(OldInst, OldBB->end());
343
344 // If OldBB isn't immediately before OldBB, insert a branch to it.
345 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
Dan Gohmane458ea82008-08-22 16:07:55 +0000346 TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347 OldBB->addSuccessor(NewDest);
348 ++NumTailMerge;
349}
350
351/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
352/// MBB so that the part before the iterator falls into the part starting at the
353/// iterator. This returns the new MBB.
354MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
355 MachineBasicBlock::iterator BBI1) {
Dan Gohman221a4372008-07-07 23:14:23 +0000356 MachineFunction &MF = *CurMBB.getParent();
357
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358 // Create the fall-through block.
359 MachineFunction::iterator MBBI = &CurMBB;
Dan Gohman221a4372008-07-07 23:14:23 +0000360 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
361 CurMBB.getParent()->insert(++MBBI, NewMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000362
363 // Move all the successors of this block to the specified block.
Dan Gohmanf995c022008-06-19 17:22:29 +0000364 NewMBB->transferSuccessors(&CurMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365
366 // Add an edge from CurMBB to NewMBB for the fall-through.
367 CurMBB.addSuccessor(NewMBB);
368
369 // Splice the code over.
370 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
371
372 // For targets that use the register scavenger, we must maintain LiveIns.
373 if (RS) {
374 RS->enterBasicBlock(&CurMBB);
375 if (!CurMBB.empty())
376 RS->forward(prior(CurMBB.end()));
Evan Cheng9dcb7602009-09-04 07:47:40 +0000377 BitVector RegsLiveAtExit(TRI->getNumRegs());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 RS->getRegsUsed(RegsLiveAtExit, false);
Evan Cheng9dcb7602009-09-04 07:47:40 +0000379 for (unsigned int i=0, e=TRI->getNumRegs(); i!=e; i++)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380 if (RegsLiveAtExit[i])
381 NewMBB->addLiveIn(i);
382 }
383
384 return NewMBB;
385}
386
387/// EstimateRuntime - Make a rough estimate for how long it will take to run
388/// the specified code.
389static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
Chris Lattner62327602008-01-07 01:56:04 +0000390 MachineBasicBlock::iterator E) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000391 unsigned Time = 0;
392 for (; I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +0000393 const TargetInstrDesc &TID = I->getDesc();
394 if (TID.isCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 Time += 10;
Dan Gohmanbc1714f2008-12-03 02:30:17 +0000396 else if (TID.mayLoad() || TID.mayStore())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397 Time += 2;
398 else
399 ++Time;
400 }
401 return Time;
402}
403
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000404// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
405// branches temporarily for tail merging). In the case where CurMBB ends
406// with a conditional branch to the next block, optimize by reversing the
407// test and conditionally branching to SuccMBB instead.
408
409static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
410 const TargetInstrInfo *TII) {
411 MachineFunction *MF = CurMBB->getParent();
412 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
413 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000414 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 if (I != MF->end() &&
Evan Chengeac31642009-02-09 07:14:22 +0000416 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000417 MachineBasicBlock *NextBB = I;
Dale Johannesen865e6252008-05-09 23:28:24 +0000418 if (TBB == NextBB && !Cond.empty() && !FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419 if (!TII->ReverseBranchCondition(Cond)) {
420 TII->RemoveBranch(*CurMBB);
421 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
422 return;
423 }
424 }
425 }
Dan Gohmane458ea82008-08-22 16:07:55 +0000426 TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427}
428
429static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
430 const std::pair<unsigned,MachineBasicBlock*> &q) {
431 if (p.first < q.first)
432 return true;
433 else if (p.first > q.first)
434 return false;
435 else if (p.second->getNumber() < q.second->getNumber())
436 return true;
437 else if (p.second->getNumber() > q.second->getNumber())
438 return false;
439 else {
440 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
441 // an object with itself.
442#ifndef _GLIBCXX_DEBUG
Edwin Törökbd448e32009-07-14 16:55:14 +0000443 llvm_unreachable("Predecessor appears twice");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444#endif
Dan Gohmand2826ae2009-01-08 22:19:34 +0000445 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446 }
447}
448
Dale Johannesen865e6252008-05-09 23:28:24 +0000449/// ComputeSameTails - Look through all the blocks in MergePotentials that have
450/// hash CurHash (guaranteed to match the last element). Build the vector
451/// SameTails of all those that have the (same) largest number of instructions
452/// in common of any pair of these blocks. SameTails entries contain an
453/// iterator into MergePotentials (from which the MachineBasicBlock can be
454/// found) and a MachineBasicBlock::iterator into that MBB indicating the
455/// instruction where the matching code sequence begins.
456/// Order of elements in SameTails is the reverse of the order in which
457/// those blocks appear in MergePotentials (where they are not necessarily
458/// consecutive).
459unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
460 unsigned minCommonTailLength) {
461 unsigned maxCommonTailLength = 0U;
462 SameTails.clear();
463 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
464 MPIterator HighestMPIter = prior(MergePotentials.end());
465 for (MPIterator CurMPIter = prior(MergePotentials.end()),
466 B = MergePotentials.begin();
467 CurMPIter!=B && CurMPIter->first==CurHash;
468 --CurMPIter) {
469 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
470 unsigned CommonTailLen = ComputeCommonTailLength(
471 CurMPIter->second,
472 I->second,
473 TrialBBI1, TrialBBI2);
Dale Johannesendaf6ac32008-05-12 22:53:12 +0000474 // If we will have to split a block, there should be at least
Bob Wilsonafe63292009-10-27 23:49:38 +0000475 // minCommonTailLength instructions in common; if not, and if we are not
476 // optimizing for performance at the expense of code size, at worst
Dale Johannesendaf6ac32008-05-12 22:53:12 +0000477 // we will be replacing a fallthrough into the common tail with a
478 // branch, which at worst breaks even with falling through into
479 // the duplicated common tail, so 1 instruction in common is enough.
480 // We will always pick a block we do not have to split as the common
481 // tail if there is one.
482 // (Empty blocks will get forwarded and need not be considered.)
483 if (CommonTailLen >= minCommonTailLength ||
Bob Wilsonafe63292009-10-27 23:49:38 +0000484 (OptLevel != CodeGenOpt::Aggressive &&
485 CommonTailLen > 0 &&
Dale Johannesendaf6ac32008-05-12 22:53:12 +0000486 (TrialBBI1==CurMPIter->second->begin() ||
487 TrialBBI2==I->second->begin()))) {
Dale Johannesen865e6252008-05-09 23:28:24 +0000488 if (CommonTailLen > maxCommonTailLength) {
489 SameTails.clear();
490 maxCommonTailLength = CommonTailLen;
491 HighestMPIter = CurMPIter;
492 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
493 }
494 if (HighestMPIter == CurMPIter &&
495 CommonTailLen == maxCommonTailLength)
496 SameTails.push_back(std::make_pair(I, TrialBBI2));
497 }
498 if (I==B)
499 break;
500 }
501 }
502 return maxCommonTailLength;
503}
504
505/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
506/// MergePotentials, restoring branches at ends of blocks as appropriate.
507void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
508 MachineBasicBlock* SuccBB,
509 MachineBasicBlock* PredBB) {
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000510 MPIterator CurMPIter, B;
511 for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
Dale Johannesen865e6252008-05-09 23:28:24 +0000512 CurMPIter->first==CurHash;
513 --CurMPIter) {
514 // Put the unconditional branch back, if we need one.
515 MachineBasicBlock *CurMBB = CurMPIter->second;
516 if (SuccBB && CurMBB != PredBB)
517 FixTail(CurMBB, SuccBB, TII);
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000518 if (CurMPIter==B)
Dale Johannesen865e6252008-05-09 23:28:24 +0000519 break;
520 }
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000521 if (CurMPIter->first!=CurHash)
522 CurMPIter++;
523 MergePotentials.erase(CurMPIter, MergePotentials.end());
Dale Johannesen865e6252008-05-09 23:28:24 +0000524}
525
Dale Johannesena3fbac92008-05-12 20:33:57 +0000526/// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
527/// only of the common tail. Create a block that does by splitting one.
528unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
529 unsigned maxCommonTailLength) {
530 unsigned i, commonTailIndex;
531 unsigned TimeEstimate = ~0U;
532 for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
533 // Use PredBB if possible; that doesn't require a new branch.
534 if (SameTails[i].first->second==PredBB) {
535 commonTailIndex = i;
536 break;
537 }
538 // Otherwise, make a (fairly bogus) choice based on estimate of
539 // how long it will take the various blocks to execute.
540 unsigned t = EstimateRuntime(SameTails[i].first->second->begin(),
541 SameTails[i].second);
542 if (t<=TimeEstimate) {
543 TimeEstimate = t;
544 commonTailIndex = i;
545 }
546 }
547
548 MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
549 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
550
Bill Wendlingef26d402009-08-22 20:03:00 +0000551 DEBUG(errs() << "\nSplitting " << MBB->getNumber() << ", size "
552 << maxCommonTailLength);
Dale Johannesena3fbac92008-05-12 20:33:57 +0000553
554 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
555 SameTails[commonTailIndex].first->second = newMBB;
556 SameTails[commonTailIndex].second = newMBB->begin();
557 // If we split PredBB, newMBB is the new predecessor.
558 if (PredBB==MBB)
559 PredBB = newMBB;
560
561 return commonTailIndex;
562}
563
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564// See if any of the blocks in MergePotentials (which all have a common single
565// successor, or all have no successor) can be tail-merged. If there is a
566// successor, any blocks in MergePotentials that are not tail-merged and
567// are not immediately before Succ must have an unconditional branch to
568// Succ added (but the predecessor/successor lists need no adjustment).
569// The lone predecessor of Succ that falls through into Succ,
570// if any, is given in PredBB.
571
572bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
573 MachineBasicBlock* PredBB) {
Evan Cheng9dcb7602009-09-04 07:47:40 +0000574 bool MadeChange = false;
575
Evan Cheng55d13352008-02-19 02:09:37 +0000576 // It doesn't make sense to save a single instruction since tail merging
577 // will add a jump.
578 // FIXME: Ask the target to provide the threshold?
579 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000580
Bill Wendlingef26d402009-08-22 20:03:00 +0000581 DEBUG(errs() << "\nTryMergeBlocks " << MergePotentials.size() << '\n');
Dale Johannesen865e6252008-05-09 23:28:24 +0000582
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583 // Sort by hash value so that blocks with identical end sequences sort
584 // together.
Dale Johannesen865e6252008-05-09 23:28:24 +0000585 std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586
587 // Walk through equivalence sets looking for actual exact matches.
588 while (MergePotentials.size() > 1) {
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000589 unsigned CurHash = prior(MergePotentials.end())->first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590
Dale Johannesen865e6252008-05-09 23:28:24 +0000591 // Build SameTails, identifying the set of blocks with this hash code
592 // and with the maximum number of instructions in common.
593 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
594 minCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595
596 // If we didn't find any pair that has at least minCommonTailLength
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000597 // instructions in common, remove all blocks with this hash code and retry.
598 if (SameTails.empty()) {
Dale Johannesen865e6252008-05-09 23:28:24 +0000599 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000600 continue;
601 }
602
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000603 // If one of the blocks is the entire common tail (and not the entry
Dale Johannesena3fbac92008-05-12 20:33:57 +0000604 // block, which we can't jump to), we can treat all blocks with this same
605 // tail at once. Use PredBB if that is one of the possibilities, as that
606 // will not introduce any extra branches.
607 MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
608 getParent()->begin();
609 unsigned int commonTailIndex, i;
610 for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000611 MachineBasicBlock *MBB = SameTails[i].first->second;
Dale Johannesena3fbac92008-05-12 20:33:57 +0000612 if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
613 commonTailIndex = i;
614 if (MBB==PredBB)
615 break;
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000616 }
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000617 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618
Dale Johannesena3fbac92008-05-12 20:33:57 +0000619 if (commonTailIndex==SameTails.size()) {
620 // None of the blocks consist entirely of the common tail.
621 // Split a block so that one does.
622 commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623 }
Dale Johannesena3fbac92008-05-12 20:33:57 +0000624
625 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
626 // MBB is common tail. Adjust all other BB's to jump to this one.
627 // Traversal must be forwards so erases work.
Bill Wendlingef26d402009-08-22 20:03:00 +0000628 DEBUG(errs() << "\nUsing common tail " << MBB->getNumber() << " for ");
Dale Johannesena3fbac92008-05-12 20:33:57 +0000629 for (unsigned int i=0; i<SameTails.size(); ++i) {
630 if (commonTailIndex==i)
631 continue;
Bill Wendlingef26d402009-08-22 20:03:00 +0000632 DEBUG(errs() << SameTails[i].first->second->getNumber() << ",");
Dale Johannesena3fbac92008-05-12 20:33:57 +0000633 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
634 ReplaceTailWithBranchTo(SameTails[i].second, MBB);
635 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
636 MergePotentials.erase(SameTails[i].first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637 }
Bill Wendlingef26d402009-08-22 20:03:00 +0000638 DEBUG(errs() << "\n");
Dale Johannesena3fbac92008-05-12 20:33:57 +0000639 // We leave commonTailIndex in the worklist in case there are other blocks
640 // that match it with a smaller number of instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 MadeChange = true;
642 }
643 return MadeChange;
644}
645
646bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
647
648 if (!EnableTailMerge) return false;
649
Evan Cheng9dcb7602009-09-04 07:47:40 +0000650 bool MadeChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651
652 // First find blocks with no successors.
653 MergePotentials.clear();
654 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
655 if (I->succ_empty())
656 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
657 }
658 // See if we can do any tail merging on those.
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000659 if (MergePotentials.size() < TailMergeThreshold &&
660 MergePotentials.size() >= 2)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 MadeChange |= TryMergeBlocks(NULL, NULL);
662
663 // Look at blocks (IBB) with multiple predecessors (PBB).
664 // We change each predecessor to a canonical form, by
665 // (1) temporarily removing any unconditional branch from the predecessor
666 // to IBB, and
667 // (2) alter conditional branches so they branch to the other block
668 // not IBB; this may require adding back an unconditional branch to IBB
669 // later, where there wasn't one coming in. E.g.
670 // Bcc IBB
671 // fallthrough to QBB
672 // here becomes
673 // Bncc QBB
674 // with a conceptual B to IBB after that, which never actually exists.
675 // With those changes, we see whether the predecessors' tails match,
676 // and merge them if so. We change things out of canonical form and
677 // back to the way they were later in the process. (OptimizeBranches
678 // would undo some of this, but we can't use it, because we'd get into
679 // a compile-time infinite loop repeatedly doing and undoing the same
680 // transformations.)
681
682 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Dale Johannesen92e84662008-07-01 21:50:14 +0000683 if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
Dan Gohman1a30b662009-08-18 15:18:18 +0000684 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685 MachineBasicBlock *IBB = I;
686 MachineBasicBlock *PredBB = prior(I);
687 MergePotentials.clear();
688 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
689 E2 = I->pred_end();
690 P != E2; ++P) {
691 MachineBasicBlock* PBB = *P;
692 // Skip blocks that loop to themselves, can't tail merge these.
693 if (PBB==IBB)
694 continue;
Dan Gohman1a30b662009-08-18 15:18:18 +0000695 // Visit each predecessor only once.
696 if (!UniquePreds.insert(PBB))
697 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000698 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000699 SmallVector<MachineOperand, 4> Cond;
Evan Chengeac31642009-02-09 07:14:22 +0000700 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000701 // Failing case: IBB is the target of a cbr, and
702 // we cannot reverse the branch.
Owen Andersond131b5b2008-08-14 22:49:33 +0000703 SmallVector<MachineOperand, 4> NewCond(Cond);
Dale Johannesen865e6252008-05-09 23:28:24 +0000704 if (!Cond.empty() && TBB==IBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 if (TII->ReverseBranchCondition(NewCond))
706 continue;
707 // This is the QBB case described above
708 if (!FBB)
709 FBB = next(MachineFunction::iterator(PBB));
710 }
711 // Failing case: the only way IBB can be reached from PBB is via
712 // exception handling. Happens for landing pads. Would be nice
713 // to have a bit in the edge so we didn't have to do all this.
714 if (IBB->isLandingPad()) {
715 MachineFunction::iterator IP = PBB; IP++;
716 MachineBasicBlock* PredNextBB = NULL;
717 if (IP!=MF.end())
718 PredNextBB = IP;
719 if (TBB==NULL) {
720 if (IBB!=PredNextBB) // fallthrough
721 continue;
722 } else if (FBB) {
723 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
724 continue;
Dan Gohman301f4052008-01-29 13:02:09 +0000725 } else if (Cond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000726 if (TBB!=IBB) // ubr
727 continue;
728 } else {
729 if (TBB!=IBB && IBB!=PredNextBB) // cbr
730 continue;
731 }
732 }
733 // Remove the unconditional branch at the end, if any.
Dale Johannesen865e6252008-05-09 23:28:24 +0000734 if (TBB && (Cond.empty() || FBB)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735 TII->RemoveBranch(*PBB);
Dale Johannesen865e6252008-05-09 23:28:24 +0000736 if (!Cond.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000737 // reinsert conditional branch only, for now
738 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
739 }
740 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
741 }
742 }
743 if (MergePotentials.size() >= 2)
744 MadeChange |= TryMergeBlocks(I, PredBB);
745 // Reinsert an unconditional branch if needed.
Dale Johannesena3fbac92008-05-12 20:33:57 +0000746 // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 PredBB = prior(I); // this may have been changed in TryMergeBlocks
748 if (MergePotentials.size()==1 &&
Dale Johannesena3fbac92008-05-12 20:33:57 +0000749 MergePotentials.begin()->second != PredBB)
750 FixTail(MergePotentials.begin()->second, I, TII);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000751 }
752 }
753 return MadeChange;
754}
755
756//===----------------------------------------------------------------------===//
757// Branch Optimization
758//===----------------------------------------------------------------------===//
759
760bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
Evan Cheng9dcb7602009-09-04 07:47:40 +0000761 bool MadeChange = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762
763 // Make sure blocks are numbered in order
764 MF.RenumberBlocks();
765
766 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
767 MachineBasicBlock *MBB = I++;
Evan Cheng9dcb7602009-09-04 07:47:40 +0000768 MadeChange |= OptimizeBlock(MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000769
770 // If it is dead, remove it.
771 if (MBB->pred_empty()) {
772 RemoveDeadBlock(MBB);
773 MadeChange = true;
774 ++NumDeadBlocks;
775 }
776 }
777 return MadeChange;
778}
779
780
781/// CanFallThrough - Return true if the specified block (with the specified
782/// branch condition) can implicitly transfer control to the block after it by
783/// falling off the end of it. This should return false if it can reach the
784/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
785///
786/// True is a conservative answer.
787///
788bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
789 bool BranchUnAnalyzable,
Dale Johannesena3fbac92008-05-12 20:33:57 +0000790 MachineBasicBlock *TBB,
791 MachineBasicBlock *FBB,
Owen Andersond131b5b2008-08-14 22:49:33 +0000792 const SmallVectorImpl<MachineOperand> &Cond) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793 MachineFunction::iterator Fallthrough = CurBB;
794 ++Fallthrough;
795 // If FallthroughBlock is off the end of the function, it can't fall through.
796 if (Fallthrough == CurBB->getParent()->end())
797 return false;
798
799 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
800 if (!CurBB->isSuccessor(Fallthrough))
801 return false;
802
803 // If we couldn't analyze the branch, assume it could fall through.
804 if (BranchUnAnalyzable) return true;
805
806 // If there is no branch, control always falls through.
807 if (TBB == 0) return true;
808
809 // If there is some explicit branch to the fallthrough block, it can obviously
810 // reach, even though the branch should get folded to fall through implicitly.
811 if (MachineFunction::iterator(TBB) == Fallthrough ||
812 MachineFunction::iterator(FBB) == Fallthrough)
813 return true;
814
815 // If it's an unconditional branch to some block not the fall through, it
816 // doesn't fall through.
817 if (Cond.empty()) return false;
818
819 // Otherwise, if it is conditional and has no explicit false block, it falls
820 // through.
821 return FBB == 0;
822}
823
824/// CanFallThrough - Return true if the specified can implicitly transfer
825/// control to the block after it by falling off the end of it. This should
826/// return false if it can reach the block after it, but it uses an explicit
827/// branch to do so (e.g. a table jump).
828///
829/// True is a conservative answer.
830///
831bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
832 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000833 SmallVector<MachineOperand, 4> Cond;
Evan Chengeac31642009-02-09 07:14:22 +0000834 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
836}
837
838/// IsBetterFallthrough - Return true if it would be clearly better to
839/// fall-through to MBB1 than to fall through into MBB2. This has to return
840/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
841/// result in infinite loops.
842static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
Chris Lattner62327602008-01-07 01:56:04 +0000843 MachineBasicBlock *MBB2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
845 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
846 // optimize branches that branch to either a return block or an assert block
847 // into a fallthrough to the return.
848 if (MBB1->empty() || MBB2->empty()) return false;
Christopher Lambff904542007-12-10 07:24:06 +0000849
850 // If there is a clear successor ordering we make sure that one block
851 // will fall through to the next
852 if (MBB1->isSuccessor(MBB2)) return true;
853 if (MBB2->isSuccessor(MBB1)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000854
855 MachineInstr *MBB1I = --MBB1->end();
856 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner5b930372008-01-07 07:27:27 +0000857 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858}
859
860/// OptimizeBlock - Analyze and optimize control flow related to the specified
861/// block. This is never called on the entry block.
Evan Cheng9dcb7602009-09-04 07:47:40 +0000862bool BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
863 bool MadeChange = false;
864
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 MachineFunction::iterator FallThrough = MBB;
866 ++FallThrough;
867
868 // If this block is empty, make everyone use its fall-through, not the block
869 // explicitly. Landing pads should not do this since the landing-pad table
870 // points to this block.
871 if (MBB->empty() && !MBB->isLandingPad()) {
872 // Dead block? Leave for cleanup later.
Evan Cheng9dcb7602009-09-04 07:47:40 +0000873 if (MBB->pred_empty()) return MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874
875 if (FallThrough == MBB->getParent()->end()) {
876 // TODO: Simplify preds to not branch here if possible!
877 } else {
878 // Rewrite all predecessors of the old block to go to the fallthrough
879 // instead.
880 while (!MBB->pred_empty()) {
881 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
882 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
883 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 // If MBB was the target of a jump table, update jump tables to go to the
885 // fallthrough instead.
886 MBB->getParent()->getJumpTableInfo()->
887 ReplaceMBBInJumpTables(MBB, FallThrough);
888 MadeChange = true;
889 }
Evan Cheng9dcb7602009-09-04 07:47:40 +0000890 return MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 }
892
893 // Check to see if we can simplify the terminator of the block before this
894 // one.
895 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
896
897 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000898 SmallVector<MachineOperand, 4> PriorCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000899 bool PriorUnAnalyzable =
Evan Chengeac31642009-02-09 07:14:22 +0000900 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000901 if (!PriorUnAnalyzable) {
902 // If the CFG for the prior block has extra edges, remove them.
903 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
904 !PriorCond.empty());
905
906 // If the previous branch is conditional and both conditions go to the same
907 // destination, remove the branch, replacing it with an unconditional one or
908 // a fall-through.
909 if (PriorTBB && PriorTBB == PriorFBB) {
910 TII->RemoveBranch(PrevBB);
911 PriorCond.clear();
912 if (PriorTBB != MBB)
913 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
914 MadeChange = true;
915 ++NumBranchOpts;
916 return OptimizeBlock(MBB);
917 }
918
919 // If the previous branch *only* branches to *this* block (conditional or
920 // not) remove the branch.
921 if (PriorTBB == MBB && PriorFBB == 0) {
922 TII->RemoveBranch(PrevBB);
923 MadeChange = true;
924 ++NumBranchOpts;
925 return OptimizeBlock(MBB);
926 }
927
928 // If the prior block branches somewhere else on the condition and here if
929 // the condition is false, remove the uncond second branch.
930 if (PriorFBB == MBB) {
931 TII->RemoveBranch(PrevBB);
932 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
933 MadeChange = true;
934 ++NumBranchOpts;
935 return OptimizeBlock(MBB);
936 }
937
938 // If the prior block branches here on true and somewhere else on false, and
939 // if the branch condition is reversible, reverse the branch to create a
940 // fall-through.
941 if (PriorTBB == MBB) {
Owen Andersond131b5b2008-08-14 22:49:33 +0000942 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943 if (!TII->ReverseBranchCondition(NewPriorCond)) {
944 TII->RemoveBranch(PrevBB);
945 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
946 MadeChange = true;
947 ++NumBranchOpts;
948 return OptimizeBlock(MBB);
949 }
950 }
951
Dan Gohman52a73622009-10-22 00:03:58 +0000952 // If this block has no successors (e.g. it is a return block or ends with
953 // a call to a no-return function like abort or __cxa_throw) and if the pred
954 // falls through into this block, and if it would otherwise fall through
955 // into the block after this, move this block to the end of the function.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956 //
957 // We consider it more likely that execution will stay in the function (e.g.
958 // due to loops) than it is to exit it. This asserts in loops etc, moving
959 // the assert condition out of the loop body.
Dan Gohman52a73622009-10-22 00:03:58 +0000960 if (MBB->succ_empty() && !PriorCond.empty() && PriorFBB == 0 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 MachineFunction::iterator(PriorTBB) == FallThrough &&
962 !CanFallThrough(MBB)) {
963 bool DoTransform = true;
964
965 // We have to be careful that the succs of PredBB aren't both no-successor
966 // blocks. If neither have successors and if PredBB is the second from
967 // last block in the function, we'd just keep swapping the two blocks for
968 // last. Only do the swap if one is clearly better to fall through than
969 // the other.
970 if (FallThrough == --MBB->getParent()->end() &&
Chris Lattner62327602008-01-07 01:56:04 +0000971 !IsBetterFallthrough(PriorTBB, MBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000972 DoTransform = false;
973
974 // We don't want to do this transformation if we have control flow like:
975 // br cond BB2
976 // BB1:
977 // ..
978 // jmp BBX
979 // BB2:
980 // ..
981 // ret
982 //
983 // In this case, we could actually be moving the return block *into* a
984 // loop!
985 if (DoTransform && !MBB->succ_empty() &&
986 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
987 DoTransform = false;
988
989
990 if (DoTransform) {
991 // Reverse the branch so we will fall through on the previous true cond.
Owen Andersond131b5b2008-08-14 22:49:33 +0000992 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000993 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Bill Wendlingef26d402009-08-22 20:03:00 +0000994 DEBUG(errs() << "\nMoving MBB: " << *MBB
995 << "To make fallthrough to: " << *PriorTBB << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996
997 TII->RemoveBranch(PrevBB);
998 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
999
1000 // Move this block to the end of the function.
1001 MBB->moveAfter(--MBB->getParent()->end());
1002 MadeChange = true;
1003 ++NumBranchOpts;
Evan Cheng9dcb7602009-09-04 07:47:40 +00001004 return MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001005 }
1006 }
1007 }
1008 }
1009
1010 // Analyze the branch in the current block.
1011 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +00001012 SmallVector<MachineOperand, 4> CurCond;
Evan Chengeac31642009-02-09 07:14:22 +00001013 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014 if (!CurUnAnalyzable) {
1015 // If the CFG for the prior block has extra edges, remove them.
1016 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1017
1018 // If this is a two-way branch, and the FBB branches to this block, reverse
1019 // the condition so the single-basic-block loop is faster. Instead of:
1020 // Loop: xxx; jcc Out; jmp Loop
1021 // we want:
1022 // Loop: xxx; jncc Loop; jmp Out
1023 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
Owen Andersond131b5b2008-08-14 22:49:33 +00001024 SmallVector<MachineOperand, 4> NewCond(CurCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001025 if (!TII->ReverseBranchCondition(NewCond)) {
1026 TII->RemoveBranch(*MBB);
1027 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1028 MadeChange = true;
1029 ++NumBranchOpts;
1030 return OptimizeBlock(MBB);
1031 }
1032 }
1033
1034
1035 // If this branch is the only thing in its block, see if we can forward
1036 // other blocks across it.
1037 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner5b930372008-01-07 07:27:27 +00001038 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001039 // This block may contain just an unconditional branch. Because there can
1040 // be 'non-branch terminators' in the block, try removing the branch and
1041 // then seeing if the block is empty.
1042 TII->RemoveBranch(*MBB);
1043
1044 // If this block is just an unconditional branch to CurTBB, we can
1045 // usually completely eliminate the block. The only case we cannot
1046 // completely eliminate the block is when the block before this one
1047 // falls through into MBB and we can't understand the prior block's branch
1048 // condition.
1049 if (MBB->empty()) {
1050 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1051 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1052 !PrevBB.isSuccessor(MBB)) {
1053 // If the prior block falls through into us, turn it into an
1054 // explicit branch to us to make updates simpler.
1055 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1056 PriorTBB != MBB && PriorFBB != MBB) {
1057 if (PriorTBB == 0) {
1058 assert(PriorCond.empty() && PriorFBB == 0 &&
1059 "Bad branch analysis");
1060 PriorTBB = MBB;
1061 } else {
1062 assert(PriorFBB == 0 && "Machine CFG out of date!");
1063 PriorFBB = MBB;
1064 }
1065 TII->RemoveBranch(PrevBB);
1066 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1067 }
1068
1069 // Iterate through all the predecessors, revectoring each in-turn.
1070 size_t PI = 0;
1071 bool DidChange = false;
1072 bool HasBranchToSelf = false;
1073 while(PI != MBB->pred_size()) {
1074 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1075 if (PMBB == MBB) {
1076 // If this block has an uncond branch to itself, leave it.
1077 ++PI;
1078 HasBranchToSelf = true;
1079 } else {
1080 DidChange = true;
1081 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
Dale Johannesenf8031372009-05-11 21:54:13 +00001082 // If this change resulted in PMBB ending in a conditional
1083 // branch where both conditions go to the same destination,
1084 // change this to an unconditional branch (and fix the CFG).
1085 MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1086 SmallVector<MachineOperand, 4> NewCurCond;
1087 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1088 NewCurFBB, NewCurCond, true);
1089 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1090 TII->RemoveBranch(*PMBB);
1091 NewCurCond.clear();
1092 TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond);
1093 MadeChange = true;
1094 ++NumBranchOpts;
1095 PMBB->CorrectExtraCFGEdges(NewCurTBB, NewCurFBB, false);
1096 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 }
1098 }
1099
1100 // Change any jumptables to go to the new MBB.
1101 MBB->getParent()->getJumpTableInfo()->
1102 ReplaceMBBInJumpTables(MBB, CurTBB);
1103 if (DidChange) {
1104 ++NumBranchOpts;
1105 MadeChange = true;
Evan Cheng9dcb7602009-09-04 07:47:40 +00001106 if (!HasBranchToSelf) return MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107 }
1108 }
1109 }
1110
1111 // Add the branch back if the block is more than just an uncond branch.
1112 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1113 }
1114 }
1115
1116 // If the prior block doesn't fall through into this block, and if this
1117 // block doesn't fall through into some other block, see if we can find a
1118 // place to move this block where a fall-through will happen.
1119 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1120 PriorTBB, PriorFBB, PriorCond)) {
1121 // Now we know that there was no fall-through into this block, check to
1122 // see if it has a fall-through into its successor.
1123 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1124 CurCond);
1125
1126 if (!MBB->isLandingPad()) {
1127 // Check all the predecessors of this block. If one of them has no fall
1128 // throughs, move this block right after it.
1129 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1130 E = MBB->pred_end(); PI != E; ++PI) {
1131 // Analyze the branch at the end of the pred.
1132 MachineBasicBlock *PredBB = *PI;
1133 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1134 if (PredBB != MBB && !CanFallThrough(PredBB)
1135 && (!CurFallsThru || !CurTBB || !CurFBB)
1136 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1137 // If the current block doesn't fall through, just move it.
1138 // If the current block can fall through and does not end with a
1139 // conditional branch, we need to append an unconditional jump to
1140 // the (current) next block. To avoid a possible compile-time
1141 // infinite loop, move blocks only backward in this case.
1142 // Also, if there are already 2 branches here, we cannot add a third;
1143 // this means we have the case
1144 // Bcc next
1145 // B elsewhere
1146 // next:
1147 if (CurFallsThru) {
1148 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1149 CurCond.clear();
1150 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1151 }
1152 MBB->moveAfter(PredBB);
1153 MadeChange = true;
1154 return OptimizeBlock(MBB);
1155 }
1156 }
1157 }
1158
1159 if (!CurFallsThru) {
1160 // Check all successors to see if we can move this block before it.
1161 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1162 E = MBB->succ_end(); SI != E; ++SI) {
1163 // Analyze the branch at the end of the block before the succ.
1164 MachineBasicBlock *SuccBB = *SI;
1165 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1166 std::vector<MachineOperand> SuccPrevCond;
1167
1168 // If this block doesn't already fall-through to that successor, and if
1169 // the succ doesn't already have a block that can fall through into it,
1170 // and if the successor isn't an EH destination, we can arrange for the
1171 // fallthrough to happen.
1172 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1173 !SuccBB->isLandingPad()) {
1174 MBB->moveBefore(SuccBB);
1175 MadeChange = true;
1176 return OptimizeBlock(MBB);
1177 }
1178 }
1179
1180 // Okay, there is no really great place to put this block. If, however,
1181 // the block before this one would be a fall-through if this block were
1182 // removed, move this block to the end of the function.
1183 if (FallThrough != MBB->getParent()->end() &&
1184 PrevBB.isSuccessor(FallThrough)) {
1185 MBB->moveAfter(--MBB->getParent()->end());
1186 MadeChange = true;
Evan Cheng9dcb7602009-09-04 07:47:40 +00001187 return MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001188 }
1189 }
1190 }
Evan Cheng9dcb7602009-09-04 07:47:40 +00001191
1192 return MadeChange;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193}