blob: c11765037cda502c49236fb0b8fc9c47e873b19d [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"
20#include "llvm/CodeGen/Passes.h"
21#include "llvm/CodeGen/MachineModuleInfo.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineJumpTableInfo.h"
24#include "llvm/CodeGen/RegisterScavenging.h"
25#include "llvm/Target/TargetInstrInfo.h"
26#include "llvm/Target/TargetMachine.h"
Dan Gohman1e57df32008-02-10 18:45:23 +000027#include "llvm/Target/TargetRegisterInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000028#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
Edwin Török675d5622009-07-11 20:10:48 +000030#include "llvm/Support/ErrorHandling.h"
Bill Wendlingef26d402009-08-22 20:03:00 +000031#include "llvm/Support/raw_ostream.h"
Evan Cheng682e4aa2008-04-10 02:32:10 +000032#include "llvm/ADT/SmallSet.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000033#include "llvm/ADT/Statistic.h"
34#include "llvm/ADT/STLExtras.h"
35#include <algorithm>
36using namespace llvm;
37
38STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
39STATISTIC(NumBranchOpts, "Number of branches optimized");
40STATISTIC(NumTailMerge , "Number of block tails merged");
41static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
42 cl::init(cl::BOU_UNSET), cl::Hidden);
Dan Gohman089efff2008-05-13 00:00:25 +000043// Throttle for huge numbers of predecessors (compile speed problems)
44static cl::opt<unsigned>
45TailMergeThreshold("tail-merge-threshold",
46 cl::desc("Max number of predecessors to consider tail merging"),
Dale Johannesen2d9dfce2008-10-27 02:10:21 +000047 cl::init(150), cl::Hidden);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048
Dan Gohman089efff2008-05-13 00:00:25 +000049namespace {
Evan Cheng45c1edb2008-02-28 00:43:03 +000050 struct VISIBILITY_HIDDEN BranchFolder : public MachineFunctionPass {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000051 static char ID;
Dan Gohman3a78bbf2007-08-02 21:21:54 +000052 explicit BranchFolder(bool defaultEnableTailMerge) :
Evan Cheng465a66e2008-09-22 20:58:04 +000053 MachineFunctionPass(&ID) {
54 switch (FlagEnableTailMerge) {
55 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
56 case cl::BOU_TRUE: EnableTailMerge = true; break;
57 case cl::BOU_FALSE: EnableTailMerge = false; break;
58 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059 }
60
61 virtual bool runOnMachineFunction(MachineFunction &MF);
62 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
63 const TargetInstrInfo *TII;
64 MachineModuleInfo *MMI;
65 bool MadeChange;
66 private:
67 // Tail Merging.
68 bool EnableTailMerge;
69 bool TailMergeBlocks(MachineFunction &MF);
70 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
71 MachineBasicBlock* PredBB);
72 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
73 MachineBasicBlock *NewDest);
74 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
75 MachineBasicBlock::iterator BBI1);
Dale Johannesen865e6252008-05-09 23:28:24 +000076 unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength);
77 void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
78 MachineBasicBlock* PredBB);
Dale Johannesena3fbac92008-05-12 20:33:57 +000079 unsigned CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
80 unsigned maxCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081
Dale Johannesen652b7ff2008-05-09 21:24:35 +000082 typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
Dale Johannesen652b7ff2008-05-09 21:24:35 +000083 typedef std::vector<MergePotentialsElt>::iterator MPIterator;
Dale Johannesen865e6252008-05-09 23:28:24 +000084 std::vector<MergePotentialsElt> MergePotentials;
Dale Johannesena3fbac92008-05-12 20:33:57 +000085
Dale Johannesen865e6252008-05-09 23:28:24 +000086 typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
87 std::vector<SameTailElt> SameTails;
Dale Johannesen652b7ff2008-05-09 21:24:35 +000088
Dan Gohman1e57df32008-02-10 18:45:23 +000089 const TargetRegisterInfo *RegInfo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090 RegScavenger *RS;
91 // Branch optzn.
92 bool OptimizeBranches(MachineFunction &MF);
93 void OptimizeBlock(MachineBasicBlock *MBB);
94 void RemoveDeadBlock(MachineBasicBlock *MBB);
Evan Cheng682e4aa2008-04-10 02:32:10 +000095 bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096
97 bool CanFallThrough(MachineBasicBlock *CurBB);
98 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
99 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
Owen Andersond131b5b2008-08-14 22:49:33 +0000100 const SmallVectorImpl<MachineOperand> &Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 };
102 char BranchFolder::ID = 0;
103}
104
105FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
106 return new BranchFolder(DefaultEnableTailMerge); }
107
108/// RemoveDeadBlock - Remove the specified dead machine basic block from the
109/// function, updating the CFG.
110void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
111 assert(MBB->pred_empty() && "MBB must be dead!");
Bill Wendlingef26d402009-08-22 20:03:00 +0000112 DEBUG(errs() << "\nRemoving MBB: " << *MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113
114 MachineFunction *MF = MBB->getParent();
115 // drop all successors.
116 while (!MBB->succ_empty())
117 MBB->removeSuccessor(MBB->succ_end()-1);
118
Duncan Sands342271d2008-07-29 20:56:02 +0000119 // If there are any labels in the basic block, unregister them from
120 // MachineModuleInfo.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121 if (MMI && !MBB->empty()) {
122 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
123 I != E; ++I) {
Duncan Sands342271d2008-07-29 20:56:02 +0000124 if (I->isLabel())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 // The label ID # is always operand #0, an immediate.
126 MMI->InvalidateLabel(I->getOperand(0).getImm());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 }
128 }
129
130 // Remove the block.
Dan Gohman221a4372008-07-07 23:14:23 +0000131 MF->erase(MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132}
133
Evan Cheng682e4aa2008-04-10 02:32:10 +0000134/// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
135/// followed by terminators, and if the implicitly defined registers are not
136/// used by the terminators, remove those implicit_def's. e.g.
137/// BB1:
138/// r0 = implicit_def
139/// r1 = implicit_def
140/// br
141/// This block can be optimized away later if the implicit instructions are
142/// removed.
143bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
144 SmallSet<unsigned, 4> ImpDefRegs;
145 MachineBasicBlock::iterator I = MBB->begin();
146 while (I != MBB->end()) {
147 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
148 break;
149 unsigned Reg = I->getOperand(0).getReg();
150 ImpDefRegs.insert(Reg);
151 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
152 unsigned SubReg = *SubRegs; ++SubRegs)
153 ImpDefRegs.insert(SubReg);
154 ++I;
155 }
156 if (ImpDefRegs.empty())
157 return false;
158
159 MachineBasicBlock::iterator FirstTerm = I;
160 while (I != MBB->end()) {
161 if (!TII->isUnpredicatedTerminator(I))
162 return false;
163 // See if it uses any of the implicitly defined registers.
164 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
165 MachineOperand &MO = I->getOperand(i);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000166 if (!MO.isReg() || !MO.isUse())
Evan Cheng682e4aa2008-04-10 02:32:10 +0000167 continue;
168 unsigned Reg = MO.getReg();
169 if (ImpDefRegs.count(Reg))
170 return false;
171 }
172 ++I;
173 }
174
175 I = MBB->begin();
176 while (I != FirstTerm) {
177 MachineInstr *ImpDefMI = &*I;
178 ++I;
179 MBB->erase(ImpDefMI);
180 }
181
182 return true;
183}
184
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
186 TII = MF.getTarget().getInstrInfo();
187 if (!TII) return false;
188
Evan Cheng682e4aa2008-04-10 02:32:10 +0000189 RegInfo = MF.getTarget().getRegisterInfo();
190
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 // Fix CFG. The later algorithms expect it to be right.
192 bool EverMadeChange = false;
193 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
194 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000195 SmallVector<MachineOperand, 4> Cond;
Evan Chengeac31642009-02-09 07:14:22 +0000196 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, true))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
Evan Cheng682e4aa2008-04-10 02:32:10 +0000198 EverMadeChange |= OptimizeImpDefsBlock(MBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199 }
200
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
202
Duncan Sands4e0d6a72009-01-28 13:14:17 +0000203 MMI = getAnalysisIfAvailable<MachineModuleInfo>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000204
205 bool MadeChangeThisIteration = true;
206 while (MadeChangeThisIteration) {
207 MadeChangeThisIteration = false;
208 MadeChangeThisIteration |= TailMergeBlocks(MF);
209 MadeChangeThisIteration |= OptimizeBranches(MF);
210 EverMadeChange |= MadeChangeThisIteration;
211 }
212
213 // See if any jump tables have become mergable or dead as the code generator
214 // did its thing.
215 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
216 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
217 if (!JTs.empty()) {
218 // Figure out how these jump tables should be merged.
219 std::vector<unsigned> JTMapping;
220 JTMapping.reserve(JTs.size());
221
222 // We always keep the 0th jump table.
223 JTMapping.push_back(0);
224
225 // Scan the jump tables, seeing if there are any duplicates. Note that this
226 // is N^2, which should be fixed someday.
227 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
228 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
229
230 // If a jump table was merge with another one, walk the function rewriting
231 // references to jump tables to reference the new JT ID's. Keep track of
232 // whether we see a jump table idx, if not, we can delete the JT.
Dale Johannesen865e6252008-05-09 23:28:24 +0000233 BitVector JTIsLive(JTs.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000234 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
235 BB != E; ++BB) {
236 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
237 I != E; ++I)
238 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
239 MachineOperand &Op = I->getOperand(op);
Dan Gohmanb9f4fa72008-10-03 15:45:36 +0000240 if (!Op.isJTI()) continue;
Chris Lattner6017d482007-12-30 23:10:15 +0000241 unsigned NewIdx = JTMapping[Op.getIndex()];
242 Op.setIndex(NewIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000243
244 // Remember that this JT is live.
Dale Johannesen865e6252008-05-09 23:28:24 +0000245 JTIsLive.set(NewIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000246 }
247 }
248
249 // Finally, remove dead jump tables. This happens either because the
250 // indirect jump was unreachable (and thus deleted) or because the jump
251 // table was merged with some other one.
252 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
Dale Johannesen865e6252008-05-09 23:28:24 +0000253 if (!JTIsLive.test(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254 JTI->RemoveJumpTable(i);
255 EverMadeChange = true;
256 }
257 }
258
259 delete RS;
260 return EverMadeChange;
261}
262
263//===----------------------------------------------------------------------===//
264// Tail Merging of Blocks
265//===----------------------------------------------------------------------===//
266
267/// HashMachineInstr - Compute a hash value for MI and its operands.
268static unsigned HashMachineInstr(const MachineInstr *MI) {
269 unsigned Hash = MI->getOpcode();
270 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
271 const MachineOperand &Op = MI->getOperand(i);
272
273 // Merge in bits from the operand if easy.
274 unsigned OperandHash = 0;
275 switch (Op.getType()) {
276 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
277 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
278 case MachineOperand::MO_MachineBasicBlock:
Chris Lattner6017d482007-12-30 23:10:15 +0000279 OperandHash = Op.getMBB()->getNumber();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000280 break;
Chris Lattner6017d482007-12-30 23:10:15 +0000281 case MachineOperand::MO_FrameIndex:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282 case MachineOperand::MO_ConstantPoolIndex:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 case MachineOperand::MO_JumpTableIndex:
Chris Lattner6017d482007-12-30 23:10:15 +0000284 OperandHash = Op.getIndex();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000285 break;
286 case MachineOperand::MO_GlobalAddress:
287 case MachineOperand::MO_ExternalSymbol:
288 // Global address / external symbol are too hard, don't bother, but do
289 // pull in the offset.
290 OperandHash = Op.getOffset();
291 break;
292 default: break;
293 }
294
295 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
296 }
297 return Hash;
298}
299
300/// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
301/// with no successors, we hash two instructions, because cross-jumping
302/// only saves code when at least two instructions are removed (since a
303/// branch must be inserted). For blocks with a successor, one of the
304/// two blocks to be tail-merged will end with a branch already, so
305/// it gains to cross-jump even for one instruction.
306
307static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
308 unsigned minCommonTailLength) {
309 MachineBasicBlock::const_iterator I = MBB->end();
310 if (I == MBB->begin())
311 return 0; // Empty MBB.
312
313 --I;
314 unsigned Hash = HashMachineInstr(I);
315
316 if (I == MBB->begin() || minCommonTailLength == 1)
317 return Hash; // Single instr MBB.
318
319 --I;
320 // Hash in the second-to-last instruction.
321 Hash ^= HashMachineInstr(I) << 2;
322 return Hash;
323}
324
325/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
326/// of instructions they actually have in common together at their end. Return
327/// iterators for the first shared instruction in each block.
328static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
329 MachineBasicBlock *MBB2,
330 MachineBasicBlock::iterator &I1,
331 MachineBasicBlock::iterator &I2) {
332 I1 = MBB1->end();
333 I2 = MBB2->end();
334
335 unsigned TailLen = 0;
336 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
337 --I1; --I2;
Bill Wendling46329b72007-10-19 21:09:55 +0000338 if (!I1->isIdenticalTo(I2) ||
Bill Wendlingf728a1c2007-10-25 19:49:32 +0000339 // FIXME: This check is dubious. It's used to get around a problem where
Bill Wendling83628182007-10-25 18:23:45 +0000340 // people incorrectly expect inline asm directives to remain in the same
341 // relative order. This is untenable because normal compiler
342 // optimizations (like this one) may reorder and/or merge these
343 // directives.
Bill Wendling46329b72007-10-19 21:09:55 +0000344 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000345 ++I1; ++I2;
346 break;
347 }
348 ++TailLen;
349 }
350 return TailLen;
351}
352
353/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
354/// after it, replacing it with an unconditional branch to NewDest. This
355/// returns true if OldInst's block is modified, false if NewDest is modified.
356void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
357 MachineBasicBlock *NewDest) {
358 MachineBasicBlock *OldBB = OldInst->getParent();
359
360 // Remove all the old successors of OldBB from the CFG.
361 while (!OldBB->succ_empty())
362 OldBB->removeSuccessor(OldBB->succ_begin());
363
364 // Remove all the dead instructions from the end of OldBB.
365 OldBB->erase(OldInst, OldBB->end());
366
367 // If OldBB isn't immediately before OldBB, insert a branch to it.
368 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
Dan Gohmane458ea82008-08-22 16:07:55 +0000369 TII->InsertBranch(*OldBB, NewDest, 0, SmallVector<MachineOperand, 0>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 OldBB->addSuccessor(NewDest);
371 ++NumTailMerge;
372}
373
374/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
375/// MBB so that the part before the iterator falls into the part starting at the
376/// iterator. This returns the new MBB.
377MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
378 MachineBasicBlock::iterator BBI1) {
Dan Gohman221a4372008-07-07 23:14:23 +0000379 MachineFunction &MF = *CurMBB.getParent();
380
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000381 // Create the fall-through block.
382 MachineFunction::iterator MBBI = &CurMBB;
Dan Gohman221a4372008-07-07 23:14:23 +0000383 MachineBasicBlock *NewMBB =MF.CreateMachineBasicBlock(CurMBB.getBasicBlock());
384 CurMBB.getParent()->insert(++MBBI, NewMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385
386 // Move all the successors of this block to the specified block.
Dan Gohmanf995c022008-06-19 17:22:29 +0000387 NewMBB->transferSuccessors(&CurMBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000388
389 // Add an edge from CurMBB to NewMBB for the fall-through.
390 CurMBB.addSuccessor(NewMBB);
391
392 // Splice the code over.
393 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
394
395 // For targets that use the register scavenger, we must maintain LiveIns.
396 if (RS) {
397 RS->enterBasicBlock(&CurMBB);
398 if (!CurMBB.empty())
399 RS->forward(prior(CurMBB.end()));
400 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
401 RS->getRegsUsed(RegsLiveAtExit, false);
402 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
403 if (RegsLiveAtExit[i])
404 NewMBB->addLiveIn(i);
405 }
406
407 return NewMBB;
408}
409
410/// EstimateRuntime - Make a rough estimate for how long it will take to run
411/// the specified code.
412static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
Chris Lattner62327602008-01-07 01:56:04 +0000413 MachineBasicBlock::iterator E) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 unsigned Time = 0;
415 for (; I != E; ++I) {
Chris Lattner5b930372008-01-07 07:27:27 +0000416 const TargetInstrDesc &TID = I->getDesc();
417 if (TID.isCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000418 Time += 10;
Dan Gohmanbc1714f2008-12-03 02:30:17 +0000419 else if (TID.mayLoad() || TID.mayStore())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 Time += 2;
421 else
422 ++Time;
423 }
424 return Time;
425}
426
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
428// branches temporarily for tail merging). In the case where CurMBB ends
429// with a conditional branch to the next block, optimize by reversing the
430// test and conditionally branching to SuccMBB instead.
431
432static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
433 const TargetInstrInfo *TII) {
434 MachineFunction *MF = CurMBB->getParent();
435 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
436 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000437 SmallVector<MachineOperand, 4> Cond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000438 if (I != MF->end() &&
Evan Chengeac31642009-02-09 07:14:22 +0000439 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond, true)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 MachineBasicBlock *NextBB = I;
Dale Johannesen865e6252008-05-09 23:28:24 +0000441 if (TBB == NextBB && !Cond.empty() && !FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 if (!TII->ReverseBranchCondition(Cond)) {
443 TII->RemoveBranch(*CurMBB);
444 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
445 return;
446 }
447 }
448 }
Dan Gohmane458ea82008-08-22 16:07:55 +0000449 TII->InsertBranch(*CurMBB, SuccBB, NULL, SmallVector<MachineOperand, 0>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450}
451
452static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
453 const std::pair<unsigned,MachineBasicBlock*> &q) {
454 if (p.first < q.first)
455 return true;
456 else if (p.first > q.first)
457 return false;
458 else if (p.second->getNumber() < q.second->getNumber())
459 return true;
460 else if (p.second->getNumber() > q.second->getNumber())
461 return false;
462 else {
463 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
464 // an object with itself.
465#ifndef _GLIBCXX_DEBUG
Edwin Törökbd448e32009-07-14 16:55:14 +0000466 llvm_unreachable("Predecessor appears twice");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000467#endif
Dan Gohmand2826ae2009-01-08 22:19:34 +0000468 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000469 }
470}
471
Dale Johannesen865e6252008-05-09 23:28:24 +0000472/// ComputeSameTails - Look through all the blocks in MergePotentials that have
473/// hash CurHash (guaranteed to match the last element). Build the vector
474/// SameTails of all those that have the (same) largest number of instructions
475/// in common of any pair of these blocks. SameTails entries contain an
476/// iterator into MergePotentials (from which the MachineBasicBlock can be
477/// found) and a MachineBasicBlock::iterator into that MBB indicating the
478/// instruction where the matching code sequence begins.
479/// Order of elements in SameTails is the reverse of the order in which
480/// those blocks appear in MergePotentials (where they are not necessarily
481/// consecutive).
482unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
483 unsigned minCommonTailLength) {
484 unsigned maxCommonTailLength = 0U;
485 SameTails.clear();
486 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
487 MPIterator HighestMPIter = prior(MergePotentials.end());
488 for (MPIterator CurMPIter = prior(MergePotentials.end()),
489 B = MergePotentials.begin();
490 CurMPIter!=B && CurMPIter->first==CurHash;
491 --CurMPIter) {
492 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
493 unsigned CommonTailLen = ComputeCommonTailLength(
494 CurMPIter->second,
495 I->second,
496 TrialBBI1, TrialBBI2);
Dale Johannesendaf6ac32008-05-12 22:53:12 +0000497 // If we will have to split a block, there should be at least
498 // minCommonTailLength instructions in common; if not, at worst
499 // we will be replacing a fallthrough into the common tail with a
500 // branch, which at worst breaks even with falling through into
501 // the duplicated common tail, so 1 instruction in common is enough.
502 // We will always pick a block we do not have to split as the common
503 // tail if there is one.
504 // (Empty blocks will get forwarded and need not be considered.)
505 if (CommonTailLen >= minCommonTailLength ||
506 (CommonTailLen > 0 &&
507 (TrialBBI1==CurMPIter->second->begin() ||
508 TrialBBI2==I->second->begin()))) {
Dale Johannesen865e6252008-05-09 23:28:24 +0000509 if (CommonTailLen > maxCommonTailLength) {
510 SameTails.clear();
511 maxCommonTailLength = CommonTailLen;
512 HighestMPIter = CurMPIter;
513 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
514 }
515 if (HighestMPIter == CurMPIter &&
516 CommonTailLen == maxCommonTailLength)
517 SameTails.push_back(std::make_pair(I, TrialBBI2));
518 }
519 if (I==B)
520 break;
521 }
522 }
523 return maxCommonTailLength;
524}
525
526/// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
527/// MergePotentials, restoring branches at ends of blocks as appropriate.
528void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
529 MachineBasicBlock* SuccBB,
530 MachineBasicBlock* PredBB) {
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000531 MPIterator CurMPIter, B;
532 for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
Dale Johannesen865e6252008-05-09 23:28:24 +0000533 CurMPIter->first==CurHash;
534 --CurMPIter) {
535 // Put the unconditional branch back, if we need one.
536 MachineBasicBlock *CurMBB = CurMPIter->second;
537 if (SuccBB && CurMBB != PredBB)
538 FixTail(CurMBB, SuccBB, TII);
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000539 if (CurMPIter==B)
Dale Johannesen865e6252008-05-09 23:28:24 +0000540 break;
541 }
Dale Johannesen3ecd4252008-05-23 17:19:02 +0000542 if (CurMPIter->first!=CurHash)
543 CurMPIter++;
544 MergePotentials.erase(CurMPIter, MergePotentials.end());
Dale Johannesen865e6252008-05-09 23:28:24 +0000545}
546
Dale Johannesena3fbac92008-05-12 20:33:57 +0000547/// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
548/// only of the common tail. Create a block that does by splitting one.
549unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
550 unsigned maxCommonTailLength) {
551 unsigned i, commonTailIndex;
552 unsigned TimeEstimate = ~0U;
553 for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
554 // Use PredBB if possible; that doesn't require a new branch.
555 if (SameTails[i].first->second==PredBB) {
556 commonTailIndex = i;
557 break;
558 }
559 // Otherwise, make a (fairly bogus) choice based on estimate of
560 // how long it will take the various blocks to execute.
561 unsigned t = EstimateRuntime(SameTails[i].first->second->begin(),
562 SameTails[i].second);
563 if (t<=TimeEstimate) {
564 TimeEstimate = t;
565 commonTailIndex = i;
566 }
567 }
568
569 MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
570 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
571
Bill Wendlingef26d402009-08-22 20:03:00 +0000572 DEBUG(errs() << "\nSplitting " << MBB->getNumber() << ", size "
573 << maxCommonTailLength);
Dale Johannesena3fbac92008-05-12 20:33:57 +0000574
575 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
576 SameTails[commonTailIndex].first->second = newMBB;
577 SameTails[commonTailIndex].second = newMBB->begin();
578 // If we split PredBB, newMBB is the new predecessor.
579 if (PredBB==MBB)
580 PredBB = newMBB;
581
582 return commonTailIndex;
583}
584
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000585// See if any of the blocks in MergePotentials (which all have a common single
586// successor, or all have no successor) can be tail-merged. If there is a
587// successor, any blocks in MergePotentials that are not tail-merged and
588// are not immediately before Succ must have an unconditional branch to
589// Succ added (but the predecessor/successor lists need no adjustment).
590// The lone predecessor of Succ that falls through into Succ,
591// if any, is given in PredBB.
592
593bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
594 MachineBasicBlock* PredBB) {
Evan Cheng55d13352008-02-19 02:09:37 +0000595 // It doesn't make sense to save a single instruction since tail merging
596 // will add a jump.
597 // FIXME: Ask the target to provide the threshold?
598 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000599 MadeChange = false;
600
Bill Wendlingef26d402009-08-22 20:03:00 +0000601 DEBUG(errs() << "\nTryMergeBlocks " << MergePotentials.size() << '\n');
Dale Johannesen865e6252008-05-09 23:28:24 +0000602
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603 // Sort by hash value so that blocks with identical end sequences sort
604 // together.
Dale Johannesen865e6252008-05-09 23:28:24 +0000605 std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606
607 // Walk through equivalence sets looking for actual exact matches.
608 while (MergePotentials.size() > 1) {
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000609 unsigned CurHash = prior(MergePotentials.end())->first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610
Dale Johannesen865e6252008-05-09 23:28:24 +0000611 // Build SameTails, identifying the set of blocks with this hash code
612 // and with the maximum number of instructions in common.
613 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
614 minCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000615
616 // If we didn't find any pair that has at least minCommonTailLength
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000617 // instructions in common, remove all blocks with this hash code and retry.
618 if (SameTails.empty()) {
Dale Johannesen865e6252008-05-09 23:28:24 +0000619 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620 continue;
621 }
622
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000623 // If one of the blocks is the entire common tail (and not the entry
Dale Johannesena3fbac92008-05-12 20:33:57 +0000624 // block, which we can't jump to), we can treat all blocks with this same
625 // tail at once. Use PredBB if that is one of the possibilities, as that
626 // will not introduce any extra branches.
627 MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
628 getParent()->begin();
629 unsigned int commonTailIndex, i;
630 for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000631 MachineBasicBlock *MBB = SameTails[i].first->second;
Dale Johannesena3fbac92008-05-12 20:33:57 +0000632 if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
633 commonTailIndex = i;
634 if (MBB==PredBB)
635 break;
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000636 }
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000637 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000638
Dale Johannesena3fbac92008-05-12 20:33:57 +0000639 if (commonTailIndex==SameTails.size()) {
640 // None of the blocks consist entirely of the common tail.
641 // Split a block so that one does.
642 commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000643 }
Dale Johannesena3fbac92008-05-12 20:33:57 +0000644
645 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
646 // MBB is common tail. Adjust all other BB's to jump to this one.
647 // Traversal must be forwards so erases work.
Bill Wendlingef26d402009-08-22 20:03:00 +0000648 DEBUG(errs() << "\nUsing common tail " << MBB->getNumber() << " for ");
Dale Johannesena3fbac92008-05-12 20:33:57 +0000649 for (unsigned int i=0; i<SameTails.size(); ++i) {
650 if (commonTailIndex==i)
651 continue;
Bill Wendlingef26d402009-08-22 20:03:00 +0000652 DEBUG(errs() << SameTails[i].first->second->getNumber() << ",");
Dale Johannesena3fbac92008-05-12 20:33:57 +0000653 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
654 ReplaceTailWithBranchTo(SameTails[i].second, MBB);
655 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
656 MergePotentials.erase(SameTails[i].first);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000657 }
Bill Wendlingef26d402009-08-22 20:03:00 +0000658 DEBUG(errs() << "\n");
Dale Johannesena3fbac92008-05-12 20:33:57 +0000659 // We leave commonTailIndex in the worklist in case there are other blocks
660 // that match it with a smaller number of instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661 MadeChange = true;
662 }
663 return MadeChange;
664}
665
666bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
667
668 if (!EnableTailMerge) return false;
669
670 MadeChange = false;
671
672 // First find blocks with no successors.
673 MergePotentials.clear();
674 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
675 if (I->succ_empty())
676 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
677 }
678 // See if we can do any tail merging on those.
Dale Johannesen652b7ff2008-05-09 21:24:35 +0000679 if (MergePotentials.size() < TailMergeThreshold &&
680 MergePotentials.size() >= 2)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681 MadeChange |= TryMergeBlocks(NULL, NULL);
682
683 // Look at blocks (IBB) with multiple predecessors (PBB).
684 // We change each predecessor to a canonical form, by
685 // (1) temporarily removing any unconditional branch from the predecessor
686 // to IBB, and
687 // (2) alter conditional branches so they branch to the other block
688 // not IBB; this may require adding back an unconditional branch to IBB
689 // later, where there wasn't one coming in. E.g.
690 // Bcc IBB
691 // fallthrough to QBB
692 // here becomes
693 // Bncc QBB
694 // with a conceptual B to IBB after that, which never actually exists.
695 // With those changes, we see whether the predecessors' tails match,
696 // and merge them if so. We change things out of canonical form and
697 // back to the way they were later in the process. (OptimizeBranches
698 // would undo some of this, but we can't use it, because we'd get into
699 // a compile-time infinite loop repeatedly doing and undoing the same
700 // transformations.)
701
702 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
Dale Johannesen92e84662008-07-01 21:50:14 +0000703 if (I->pred_size() >= 2 && I->pred_size() < TailMergeThreshold) {
Dan Gohman1a30b662009-08-18 15:18:18 +0000704 SmallPtrSet<MachineBasicBlock *, 8> UniquePreds;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 MachineBasicBlock *IBB = I;
706 MachineBasicBlock *PredBB = prior(I);
707 MergePotentials.clear();
708 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
709 E2 = I->pred_end();
710 P != E2; ++P) {
711 MachineBasicBlock* PBB = *P;
712 // Skip blocks that loop to themselves, can't tail merge these.
713 if (PBB==IBB)
714 continue;
Dan Gohman1a30b662009-08-18 15:18:18 +0000715 // Visit each predecessor only once.
716 if (!UniquePreds.insert(PBB))
717 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000719 SmallVector<MachineOperand, 4> Cond;
Evan Chengeac31642009-02-09 07:14:22 +0000720 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond, true)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 // Failing case: IBB is the target of a cbr, and
722 // we cannot reverse the branch.
Owen Andersond131b5b2008-08-14 22:49:33 +0000723 SmallVector<MachineOperand, 4> NewCond(Cond);
Dale Johannesen865e6252008-05-09 23:28:24 +0000724 if (!Cond.empty() && TBB==IBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 if (TII->ReverseBranchCondition(NewCond))
726 continue;
727 // This is the QBB case described above
728 if (!FBB)
729 FBB = next(MachineFunction::iterator(PBB));
730 }
731 // Failing case: the only way IBB can be reached from PBB is via
732 // exception handling. Happens for landing pads. Would be nice
733 // to have a bit in the edge so we didn't have to do all this.
734 if (IBB->isLandingPad()) {
735 MachineFunction::iterator IP = PBB; IP++;
736 MachineBasicBlock* PredNextBB = NULL;
737 if (IP!=MF.end())
738 PredNextBB = IP;
739 if (TBB==NULL) {
740 if (IBB!=PredNextBB) // fallthrough
741 continue;
742 } else if (FBB) {
743 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
744 continue;
Dan Gohman301f4052008-01-29 13:02:09 +0000745 } else if (Cond.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000746 if (TBB!=IBB) // ubr
747 continue;
748 } else {
749 if (TBB!=IBB && IBB!=PredNextBB) // cbr
750 continue;
751 }
752 }
753 // Remove the unconditional branch at the end, if any.
Dale Johannesen865e6252008-05-09 23:28:24 +0000754 if (TBB && (Cond.empty() || FBB)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755 TII->RemoveBranch(*PBB);
Dale Johannesen865e6252008-05-09 23:28:24 +0000756 if (!Cond.empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757 // reinsert conditional branch only, for now
758 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
759 }
760 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
761 }
762 }
763 if (MergePotentials.size() >= 2)
764 MadeChange |= TryMergeBlocks(I, PredBB);
765 // Reinsert an unconditional branch if needed.
Dale Johannesena3fbac92008-05-12 20:33:57 +0000766 // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 PredBB = prior(I); // this may have been changed in TryMergeBlocks
768 if (MergePotentials.size()==1 &&
Dale Johannesena3fbac92008-05-12 20:33:57 +0000769 MergePotentials.begin()->second != PredBB)
770 FixTail(MergePotentials.begin()->second, I, TII);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771 }
772 }
773 return MadeChange;
774}
775
776//===----------------------------------------------------------------------===//
777// Branch Optimization
778//===----------------------------------------------------------------------===//
779
780bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
781 MadeChange = false;
782
783 // Make sure blocks are numbered in order
784 MF.RenumberBlocks();
785
786 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
787 MachineBasicBlock *MBB = I++;
788 OptimizeBlock(MBB);
789
790 // If it is dead, remove it.
791 if (MBB->pred_empty()) {
792 RemoveDeadBlock(MBB);
793 MadeChange = true;
794 ++NumDeadBlocks;
795 }
796 }
797 return MadeChange;
798}
799
800
801/// CanFallThrough - Return true if the specified block (with the specified
802/// branch condition) can implicitly transfer control to the block after it by
803/// falling off the end of it. This should return false if it can reach the
804/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
805///
806/// True is a conservative answer.
807///
808bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
809 bool BranchUnAnalyzable,
Dale Johannesena3fbac92008-05-12 20:33:57 +0000810 MachineBasicBlock *TBB,
811 MachineBasicBlock *FBB,
Owen Andersond131b5b2008-08-14 22:49:33 +0000812 const SmallVectorImpl<MachineOperand> &Cond) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000813 MachineFunction::iterator Fallthrough = CurBB;
814 ++Fallthrough;
815 // If FallthroughBlock is off the end of the function, it can't fall through.
816 if (Fallthrough == CurBB->getParent()->end())
817 return false;
818
819 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
820 if (!CurBB->isSuccessor(Fallthrough))
821 return false;
822
823 // If we couldn't analyze the branch, assume it could fall through.
824 if (BranchUnAnalyzable) return true;
825
826 // If there is no branch, control always falls through.
827 if (TBB == 0) return true;
828
829 // If there is some explicit branch to the fallthrough block, it can obviously
830 // reach, even though the branch should get folded to fall through implicitly.
831 if (MachineFunction::iterator(TBB) == Fallthrough ||
832 MachineFunction::iterator(FBB) == Fallthrough)
833 return true;
834
835 // If it's an unconditional branch to some block not the fall through, it
836 // doesn't fall through.
837 if (Cond.empty()) return false;
838
839 // Otherwise, if it is conditional and has no explicit false block, it falls
840 // through.
841 return FBB == 0;
842}
843
844/// CanFallThrough - Return true if the specified can implicitly transfer
845/// control to the block after it by falling off the end of it. This should
846/// return false if it can reach the block after it, but it uses an explicit
847/// branch to do so (e.g. a table jump).
848///
849/// True is a conservative answer.
850///
851bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
852 MachineBasicBlock *TBB = 0, *FBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000853 SmallVector<MachineOperand, 4> Cond;
Evan Chengeac31642009-02-09 07:14:22 +0000854 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
856}
857
858/// IsBetterFallthrough - Return true if it would be clearly better to
859/// fall-through to MBB1 than to fall through into MBB2. This has to return
860/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
861/// result in infinite loops.
862static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
Chris Lattner62327602008-01-07 01:56:04 +0000863 MachineBasicBlock *MBB2) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
865 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
866 // optimize branches that branch to either a return block or an assert block
867 // into a fallthrough to the return.
868 if (MBB1->empty() || MBB2->empty()) return false;
Christopher Lambff904542007-12-10 07:24:06 +0000869
870 // If there is a clear successor ordering we make sure that one block
871 // will fall through to the next
872 if (MBB1->isSuccessor(MBB2)) return true;
873 if (MBB2->isSuccessor(MBB1)) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000874
875 MachineInstr *MBB1I = --MBB1->end();
876 MachineInstr *MBB2I = --MBB2->end();
Chris Lattner5b930372008-01-07 07:27:27 +0000877 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878}
879
880/// OptimizeBlock - Analyze and optimize control flow related to the specified
881/// block. This is never called on the entry block.
882void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
883 MachineFunction::iterator FallThrough = MBB;
884 ++FallThrough;
885
886 // If this block is empty, make everyone use its fall-through, not the block
887 // explicitly. Landing pads should not do this since the landing-pad table
888 // points to this block.
889 if (MBB->empty() && !MBB->isLandingPad()) {
890 // Dead block? Leave for cleanup later.
891 if (MBB->pred_empty()) return;
892
893 if (FallThrough == MBB->getParent()->end()) {
894 // TODO: Simplify preds to not branch here if possible!
895 } else {
896 // Rewrite all predecessors of the old block to go to the fallthrough
897 // instead.
898 while (!MBB->pred_empty()) {
899 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
900 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
901 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000902 // If MBB was the target of a jump table, update jump tables to go to the
903 // fallthrough instead.
904 MBB->getParent()->getJumpTableInfo()->
905 ReplaceMBBInJumpTables(MBB, FallThrough);
906 MadeChange = true;
907 }
908 return;
909 }
910
911 // Check to see if we can simplify the terminator of the block before this
912 // one.
913 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
914
915 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +0000916 SmallVector<MachineOperand, 4> PriorCond;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 bool PriorUnAnalyzable =
Evan Chengeac31642009-02-09 07:14:22 +0000918 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000919 if (!PriorUnAnalyzable) {
920 // If the CFG for the prior block has extra edges, remove them.
921 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
922 !PriorCond.empty());
923
924 // If the previous branch is conditional and both conditions go to the same
925 // destination, remove the branch, replacing it with an unconditional one or
926 // a fall-through.
927 if (PriorTBB && PriorTBB == PriorFBB) {
928 TII->RemoveBranch(PrevBB);
929 PriorCond.clear();
930 if (PriorTBB != MBB)
931 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
932 MadeChange = true;
933 ++NumBranchOpts;
934 return OptimizeBlock(MBB);
935 }
936
937 // If the previous branch *only* branches to *this* block (conditional or
938 // not) remove the branch.
939 if (PriorTBB == MBB && PriorFBB == 0) {
940 TII->RemoveBranch(PrevBB);
941 MadeChange = true;
942 ++NumBranchOpts;
943 return OptimizeBlock(MBB);
944 }
945
946 // If the prior block branches somewhere else on the condition and here if
947 // the condition is false, remove the uncond second branch.
948 if (PriorFBB == MBB) {
949 TII->RemoveBranch(PrevBB);
950 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
951 MadeChange = true;
952 ++NumBranchOpts;
953 return OptimizeBlock(MBB);
954 }
955
956 // If the prior block branches here on true and somewhere else on false, and
957 // if the branch condition is reversible, reverse the branch to create a
958 // fall-through.
959 if (PriorTBB == MBB) {
Owen Andersond131b5b2008-08-14 22:49:33 +0000960 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 if (!TII->ReverseBranchCondition(NewPriorCond)) {
962 TII->RemoveBranch(PrevBB);
963 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
964 MadeChange = true;
965 ++NumBranchOpts;
966 return OptimizeBlock(MBB);
967 }
968 }
969
970 // If this block doesn't fall through (e.g. it ends with an uncond branch or
971 // has no successors) and if the pred falls through into this block, and if
972 // it would otherwise fall through into the block after this, move this
973 // block to the end of the function.
974 //
975 // We consider it more likely that execution will stay in the function (e.g.
976 // due to loops) than it is to exit it. This asserts in loops etc, moving
977 // the assert condition out of the loop body.
978 if (!PriorCond.empty() && PriorFBB == 0 &&
979 MachineFunction::iterator(PriorTBB) == FallThrough &&
980 !CanFallThrough(MBB)) {
981 bool DoTransform = true;
982
983 // We have to be careful that the succs of PredBB aren't both no-successor
984 // blocks. If neither have successors and if PredBB is the second from
985 // last block in the function, we'd just keep swapping the two blocks for
986 // last. Only do the swap if one is clearly better to fall through than
987 // the other.
988 if (FallThrough == --MBB->getParent()->end() &&
Chris Lattner62327602008-01-07 01:56:04 +0000989 !IsBetterFallthrough(PriorTBB, MBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 DoTransform = false;
991
992 // We don't want to do this transformation if we have control flow like:
993 // br cond BB2
994 // BB1:
995 // ..
996 // jmp BBX
997 // BB2:
998 // ..
999 // ret
1000 //
1001 // In this case, we could actually be moving the return block *into* a
1002 // loop!
1003 if (DoTransform && !MBB->succ_empty() &&
1004 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
1005 DoTransform = false;
1006
1007
1008 if (DoTransform) {
1009 // Reverse the branch so we will fall through on the previous true cond.
Owen Andersond131b5b2008-08-14 22:49:33 +00001010 SmallVector<MachineOperand, 4> NewPriorCond(PriorCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011 if (!TII->ReverseBranchCondition(NewPriorCond)) {
Bill Wendlingef26d402009-08-22 20:03:00 +00001012 DEBUG(errs() << "\nMoving MBB: " << *MBB
1013 << "To make fallthrough to: " << *PriorTBB << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001014
1015 TII->RemoveBranch(PrevBB);
1016 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
1017
1018 // Move this block to the end of the function.
1019 MBB->moveAfter(--MBB->getParent()->end());
1020 MadeChange = true;
1021 ++NumBranchOpts;
1022 return;
1023 }
1024 }
1025 }
1026 }
1027
1028 // Analyze the branch in the current block.
1029 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
Owen Andersond131b5b2008-08-14 22:49:33 +00001030 SmallVector<MachineOperand, 4> CurCond;
Evan Chengeac31642009-02-09 07:14:22 +00001031 bool CurUnAnalyzable= TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 if (!CurUnAnalyzable) {
1033 // If the CFG for the prior block has extra edges, remove them.
1034 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1035
1036 // If this is a two-way branch, and the FBB branches to this block, reverse
1037 // the condition so the single-basic-block loop is faster. Instead of:
1038 // Loop: xxx; jcc Out; jmp Loop
1039 // we want:
1040 // Loop: xxx; jncc Loop; jmp Out
1041 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
Owen Andersond131b5b2008-08-14 22:49:33 +00001042 SmallVector<MachineOperand, 4> NewCond(CurCond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001043 if (!TII->ReverseBranchCondition(NewCond)) {
1044 TII->RemoveBranch(*MBB);
1045 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1046 MadeChange = true;
1047 ++NumBranchOpts;
1048 return OptimizeBlock(MBB);
1049 }
1050 }
1051
1052
1053 // If this branch is the only thing in its block, see if we can forward
1054 // other blocks across it.
1055 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
Chris Lattner5b930372008-01-07 07:27:27 +00001056 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001057 // This block may contain just an unconditional branch. Because there can
1058 // be 'non-branch terminators' in the block, try removing the branch and
1059 // then seeing if the block is empty.
1060 TII->RemoveBranch(*MBB);
1061
1062 // If this block is just an unconditional branch to CurTBB, we can
1063 // usually completely eliminate the block. The only case we cannot
1064 // completely eliminate the block is when the block before this one
1065 // falls through into MBB and we can't understand the prior block's branch
1066 // condition.
1067 if (MBB->empty()) {
1068 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1069 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1070 !PrevBB.isSuccessor(MBB)) {
1071 // If the prior block falls through into us, turn it into an
1072 // explicit branch to us to make updates simpler.
1073 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1074 PriorTBB != MBB && PriorFBB != MBB) {
1075 if (PriorTBB == 0) {
1076 assert(PriorCond.empty() && PriorFBB == 0 &&
1077 "Bad branch analysis");
1078 PriorTBB = MBB;
1079 } else {
1080 assert(PriorFBB == 0 && "Machine CFG out of date!");
1081 PriorFBB = MBB;
1082 }
1083 TII->RemoveBranch(PrevBB);
1084 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1085 }
1086
1087 // Iterate through all the predecessors, revectoring each in-turn.
1088 size_t PI = 0;
1089 bool DidChange = false;
1090 bool HasBranchToSelf = false;
1091 while(PI != MBB->pred_size()) {
1092 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1093 if (PMBB == MBB) {
1094 // If this block has an uncond branch to itself, leave it.
1095 ++PI;
1096 HasBranchToSelf = true;
1097 } else {
1098 DidChange = true;
1099 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
Dale Johannesenf8031372009-05-11 21:54:13 +00001100 // If this change resulted in PMBB ending in a conditional
1101 // branch where both conditions go to the same destination,
1102 // change this to an unconditional branch (and fix the CFG).
1103 MachineBasicBlock *NewCurTBB = 0, *NewCurFBB = 0;
1104 SmallVector<MachineOperand, 4> NewCurCond;
1105 bool NewCurUnAnalyzable = TII->AnalyzeBranch(*PMBB, NewCurTBB,
1106 NewCurFBB, NewCurCond, true);
1107 if (!NewCurUnAnalyzable && NewCurTBB && NewCurTBB == NewCurFBB) {
1108 TII->RemoveBranch(*PMBB);
1109 NewCurCond.clear();
1110 TII->InsertBranch(*PMBB, NewCurTBB, 0, NewCurCond);
1111 MadeChange = true;
1112 ++NumBranchOpts;
1113 PMBB->CorrectExtraCFGEdges(NewCurTBB, NewCurFBB, false);
1114 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001115 }
1116 }
1117
1118 // Change any jumptables to go to the new MBB.
1119 MBB->getParent()->getJumpTableInfo()->
1120 ReplaceMBBInJumpTables(MBB, CurTBB);
1121 if (DidChange) {
1122 ++NumBranchOpts;
1123 MadeChange = true;
1124 if (!HasBranchToSelf) return;
1125 }
1126 }
1127 }
1128
1129 // Add the branch back if the block is more than just an uncond branch.
1130 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1131 }
1132 }
1133
1134 // If the prior block doesn't fall through into this block, and if this
1135 // block doesn't fall through into some other block, see if we can find a
1136 // place to move this block where a fall-through will happen.
1137 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1138 PriorTBB, PriorFBB, PriorCond)) {
1139 // Now we know that there was no fall-through into this block, check to
1140 // see if it has a fall-through into its successor.
1141 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1142 CurCond);
1143
1144 if (!MBB->isLandingPad()) {
1145 // Check all the predecessors of this block. If one of them has no fall
1146 // throughs, move this block right after it.
1147 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1148 E = MBB->pred_end(); PI != E; ++PI) {
1149 // Analyze the branch at the end of the pred.
1150 MachineBasicBlock *PredBB = *PI;
1151 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1152 if (PredBB != MBB && !CanFallThrough(PredBB)
1153 && (!CurFallsThru || !CurTBB || !CurFBB)
1154 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1155 // If the current block doesn't fall through, just move it.
1156 // If the current block can fall through and does not end with a
1157 // conditional branch, we need to append an unconditional jump to
1158 // the (current) next block. To avoid a possible compile-time
1159 // infinite loop, move blocks only backward in this case.
1160 // Also, if there are already 2 branches here, we cannot add a third;
1161 // this means we have the case
1162 // Bcc next
1163 // B elsewhere
1164 // next:
1165 if (CurFallsThru) {
1166 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1167 CurCond.clear();
1168 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1169 }
1170 MBB->moveAfter(PredBB);
1171 MadeChange = true;
1172 return OptimizeBlock(MBB);
1173 }
1174 }
1175 }
1176
1177 if (!CurFallsThru) {
1178 // Check all successors to see if we can move this block before it.
1179 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1180 E = MBB->succ_end(); SI != E; ++SI) {
1181 // Analyze the branch at the end of the block before the succ.
1182 MachineBasicBlock *SuccBB = *SI;
1183 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1184 std::vector<MachineOperand> SuccPrevCond;
1185
1186 // If this block doesn't already fall-through to that successor, and if
1187 // the succ doesn't already have a block that can fall through into it,
1188 // and if the successor isn't an EH destination, we can arrange for the
1189 // fallthrough to happen.
1190 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1191 !SuccBB->isLandingPad()) {
1192 MBB->moveBefore(SuccBB);
1193 MadeChange = true;
1194 return OptimizeBlock(MBB);
1195 }
1196 }
1197
1198 // Okay, there is no really great place to put this block. If, however,
1199 // the block before this one would be a fall-through if this block were
1200 // removed, move this block to the end of the function.
1201 if (FallThrough != MBB->getParent()->end() &&
1202 PrevBB.isSuccessor(FallThrough)) {
1203 MBB->moveAfter(--MBB->getParent()->end());
1204 MadeChange = true;
1205 return;
1206 }
1207 }
1208 }
1209}