1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 // Note that this pass must be run after register allocation, it cannot handle
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "branchfolding"
20 #include "BranchFolding.h"
21 #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"
28 #include "llvm/Target/TargetRegisterInfo.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/ADT/STLExtras.h"
39 STATISTIC(NumDeadBlocks
, "Number of dead blocks removed");
40 STATISTIC(NumBranchOpts
, "Number of branches optimized");
41 STATISTIC(NumTailMerge
, "Number of block tails merged");
42 static cl::opt
<cl::boolOrDefault
> FlagEnableTailMerge("enable-tail-merge",
43 cl::init(cl::BOU_UNSET
), cl::Hidden
);
44 // Throttle for huge numbers of predecessors (compile speed problems)
45 static cl::opt
<unsigned>
46 TailMergeThreshold("tail-merge-threshold",
47 cl::desc("Max number of predecessors to consider tail merging"),
48 cl::init(150), cl::Hidden
);
51 char BranchFolderPass::ID
= 0;
53 FunctionPass
*llvm::createBranchFoldingPass(bool DefaultEnableTailMerge
) {
54 return new BranchFolderPass(DefaultEnableTailMerge
);
57 bool BranchFolderPass::runOnMachineFunction(MachineFunction
&MF
) {
58 return OptimizeFunction(MF
,
59 MF
.getTarget().getInstrInfo(),
60 MF
.getTarget().getRegisterInfo(),
61 getAnalysisIfAvailable
<MachineModuleInfo
>());
66 BranchFolder::BranchFolder(bool defaultEnableTailMerge
) {
67 switch (FlagEnableTailMerge
) {
68 case cl::BOU_UNSET
: EnableTailMerge
= defaultEnableTailMerge
; break;
69 case cl::BOU_TRUE
: EnableTailMerge
= true; break;
70 case cl::BOU_FALSE
: EnableTailMerge
= false; break;
74 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
75 /// function, updating the CFG.
76 void BranchFolder::RemoveDeadBlock(MachineBasicBlock
*MBB
) {
77 assert(MBB
->pred_empty() && "MBB must be dead!");
78 DEBUG(errs() << "\nRemoving MBB: " << *MBB
);
80 MachineFunction
*MF
= MBB
->getParent();
81 // drop all successors.
82 while (!MBB
->succ_empty())
83 MBB
->removeSuccessor(MBB
->succ_end()-1);
85 // If there are any labels in the basic block, unregister them from
87 if (MMI
&& !MBB
->empty()) {
88 for (MachineBasicBlock::iterator I
= MBB
->begin(), E
= MBB
->end();
91 // The label ID # is always operand #0, an immediate.
92 MMI
->InvalidateLabel(I
->getOperand(0).getImm());
100 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
101 /// followed by terminators, and if the implicitly defined registers are not
102 /// used by the terminators, remove those implicit_def's. e.g.
104 /// r0 = implicit_def
105 /// r1 = implicit_def
107 /// This block can be optimized away later if the implicit instructions are
109 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock
*MBB
) {
110 SmallSet
<unsigned, 4> ImpDefRegs
;
111 MachineBasicBlock::iterator I
= MBB
->begin();
112 while (I
!= MBB
->end()) {
113 if (I
->getOpcode() != TargetInstrInfo::IMPLICIT_DEF
)
115 unsigned Reg
= I
->getOperand(0).getReg();
116 ImpDefRegs
.insert(Reg
);
117 for (const unsigned *SubRegs
= TRI
->getSubRegisters(Reg
);
118 unsigned SubReg
= *SubRegs
; ++SubRegs
)
119 ImpDefRegs
.insert(SubReg
);
122 if (ImpDefRegs
.empty())
125 MachineBasicBlock::iterator FirstTerm
= I
;
126 while (I
!= MBB
->end()) {
127 if (!TII
->isUnpredicatedTerminator(I
))
129 // See if it uses any of the implicitly defined registers.
130 for (unsigned i
= 0, e
= I
->getNumOperands(); i
!= e
; ++i
) {
131 MachineOperand
&MO
= I
->getOperand(i
);
132 if (!MO
.isReg() || !MO
.isUse())
134 unsigned Reg
= MO
.getReg();
135 if (ImpDefRegs
.count(Reg
))
142 while (I
!= FirstTerm
) {
143 MachineInstr
*ImpDefMI
= &*I
;
145 MBB
->erase(ImpDefMI
);
151 /// OptimizeFunction - Perhaps branch folding, tail merging and other
152 /// CFG optimizations on the given function.
153 bool BranchFolder::OptimizeFunction(MachineFunction
&MF
,
154 const TargetInstrInfo
*tii
,
155 const TargetRegisterInfo
*tri
,
156 MachineModuleInfo
*mmi
) {
157 if (!tii
) return false;
163 RS
= TRI
->requiresRegisterScavenging(MF
) ? new RegScavenger() : NULL
;
165 // Fix CFG. The later algorithms expect it to be right.
166 bool MadeChange
= false;
167 for (MachineFunction::iterator I
= MF
.begin(), E
= MF
.end(); I
!= E
; I
++) {
168 MachineBasicBlock
*MBB
= I
, *TBB
= 0, *FBB
= 0;
169 SmallVector
<MachineOperand
, 4> Cond
;
170 if (!TII
->AnalyzeBranch(*MBB
, TBB
, FBB
, Cond
, true))
171 MadeChange
|= MBB
->CorrectExtraCFGEdges(TBB
, FBB
, !Cond
.empty());
172 MadeChange
|= OptimizeImpDefsBlock(MBB
);
176 bool MadeChangeThisIteration
= true;
177 while (MadeChangeThisIteration
) {
178 MadeChangeThisIteration
= false;
179 MadeChangeThisIteration
|= TailMergeBlocks(MF
);
180 MadeChangeThisIteration
|= OptimizeBranches(MF
);
181 MadeChange
|= MadeChangeThisIteration
;
184 // See if any jump tables have become mergable or dead as the code generator
186 MachineJumpTableInfo
*JTI
= MF
.getJumpTableInfo();
187 const std::vector
<MachineJumpTableEntry
> &JTs
= JTI
->getJumpTables();
189 // Figure out how these jump tables should be merged.
190 std::vector
<unsigned> JTMapping
;
191 JTMapping
.reserve(JTs
.size());
193 // We always keep the 0th jump table.
194 JTMapping
.push_back(0);
196 // Scan the jump tables, seeing if there are any duplicates. Note that this
197 // is N^2, which should be fixed someday.
198 for (unsigned i
= 1, e
= JTs
.size(); i
!= e
; ++i
) {
199 if (JTs
[i
].MBBs
.empty())
200 JTMapping
.push_back(i
);
202 JTMapping
.push_back(JTI
->getJumpTableIndex(JTs
[i
].MBBs
));
205 // If a jump table was merge with another one, walk the function rewriting
206 // references to jump tables to reference the new JT ID's. Keep track of
207 // whether we see a jump table idx, if not, we can delete the JT.
208 BitVector
JTIsLive(JTs
.size());
209 for (MachineFunction::iterator BB
= MF
.begin(), E
= MF
.end();
211 for (MachineBasicBlock::iterator I
= BB
->begin(), E
= BB
->end();
213 for (unsigned op
= 0, e
= I
->getNumOperands(); op
!= e
; ++op
) {
214 MachineOperand
&Op
= I
->getOperand(op
);
215 if (!Op
.isJTI()) continue;
216 unsigned NewIdx
= JTMapping
[Op
.getIndex()];
219 // Remember that this JT is live.
220 JTIsLive
.set(NewIdx
);
224 // Finally, remove dead jump tables. This happens either because the
225 // indirect jump was unreachable (and thus deleted) or because the jump
226 // table was merged with some other one.
227 for (unsigned i
= 0, e
= JTIsLive
.size(); i
!= e
; ++i
)
228 if (!JTIsLive
.test(i
)) {
229 JTI
->RemoveJumpTable(i
);
238 //===----------------------------------------------------------------------===//
239 // Tail Merging of Blocks
240 //===----------------------------------------------------------------------===//
242 /// HashMachineInstr - Compute a hash value for MI and its operands.
243 static unsigned HashMachineInstr(const MachineInstr
*MI
) {
244 unsigned Hash
= MI
->getOpcode();
245 for (unsigned i
= 0, e
= MI
->getNumOperands(); i
!= e
; ++i
) {
246 const MachineOperand
&Op
= MI
->getOperand(i
);
248 // Merge in bits from the operand if easy.
249 unsigned OperandHash
= 0;
250 switch (Op
.getType()) {
251 case MachineOperand::MO_Register
: OperandHash
= Op
.getReg(); break;
252 case MachineOperand::MO_Immediate
: OperandHash
= Op
.getImm(); break;
253 case MachineOperand::MO_MachineBasicBlock
:
254 OperandHash
= Op
.getMBB()->getNumber();
256 case MachineOperand::MO_FrameIndex
:
257 case MachineOperand::MO_ConstantPoolIndex
:
258 case MachineOperand::MO_JumpTableIndex
:
259 OperandHash
= Op
.getIndex();
261 case MachineOperand::MO_GlobalAddress
:
262 case MachineOperand::MO_ExternalSymbol
:
263 // Global address / external symbol are too hard, don't bother, but do
264 // pull in the offset.
265 OperandHash
= Op
.getOffset();
270 Hash
+= ((OperandHash
<< 3) | Op
.getType()) << (i
&31);
275 /// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
276 /// with no successors, we hash two instructions, because cross-jumping
277 /// only saves code when at least two instructions are removed (since a
278 /// branch must be inserted). For blocks with a successor, one of the
279 /// two blocks to be tail-merged will end with a branch already, so
280 /// it gains to cross-jump even for one instruction.
282 static unsigned HashEndOfMBB(const MachineBasicBlock
*MBB
,
283 unsigned minCommonTailLength
) {
284 MachineBasicBlock::const_iterator I
= MBB
->end();
285 if (I
== MBB
->begin())
286 return 0; // Empty MBB.
289 unsigned Hash
= HashMachineInstr(I
);
291 if (I
== MBB
->begin() || minCommonTailLength
== 1)
292 return Hash
; // Single instr MBB.
295 // Hash in the second-to-last instruction.
296 Hash
^= HashMachineInstr(I
) << 2;
300 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
301 /// of instructions they actually have in common together at their end. Return
302 /// iterators for the first shared instruction in each block.
303 static unsigned ComputeCommonTailLength(MachineBasicBlock
*MBB1
,
304 MachineBasicBlock
*MBB2
,
305 MachineBasicBlock::iterator
&I1
,
306 MachineBasicBlock::iterator
&I2
) {
310 unsigned TailLen
= 0;
311 while (I1
!= MBB1
->begin() && I2
!= MBB2
->begin()) {
313 if (!I1
->isIdenticalTo(I2
) ||
314 // FIXME: This check is dubious. It's used to get around a problem where
315 // people incorrectly expect inline asm directives to remain in the same
316 // relative order. This is untenable because normal compiler
317 // optimizations (like this one) may reorder and/or merge these
319 I1
->getOpcode() == TargetInstrInfo::INLINEASM
) {
328 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
329 /// after it, replacing it with an unconditional branch to NewDest. This
330 /// returns true if OldInst's block is modified, false if NewDest is modified.
331 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst
,
332 MachineBasicBlock
*NewDest
) {
333 MachineBasicBlock
*OldBB
= OldInst
->getParent();
335 // Remove all the old successors of OldBB from the CFG.
336 while (!OldBB
->succ_empty())
337 OldBB
->removeSuccessor(OldBB
->succ_begin());
339 // Remove all the dead instructions from the end of OldBB.
340 OldBB
->erase(OldInst
, OldBB
->end());
342 // If OldBB isn't immediately before OldBB, insert a branch to it.
343 if (++MachineFunction::iterator(OldBB
) != MachineFunction::iterator(NewDest
))
344 TII
->InsertBranch(*OldBB
, NewDest
, 0, SmallVector
<MachineOperand
, 0>());
345 OldBB
->addSuccessor(NewDest
);
349 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
350 /// MBB so that the part before the iterator falls into the part starting at the
351 /// iterator. This returns the new MBB.
352 MachineBasicBlock
*BranchFolder::SplitMBBAt(MachineBasicBlock
&CurMBB
,
353 MachineBasicBlock::iterator BBI1
) {
354 MachineFunction
&MF
= *CurMBB
.getParent();
356 // Create the fall-through block.
357 MachineFunction::iterator MBBI
= &CurMBB
;
358 MachineBasicBlock
*NewMBB
=MF
.CreateMachineBasicBlock(CurMBB
.getBasicBlock());
359 CurMBB
.getParent()->insert(++MBBI
, NewMBB
);
361 // Move all the successors of this block to the specified block.
362 NewMBB
->transferSuccessors(&CurMBB
);
364 // Add an edge from CurMBB to NewMBB for the fall-through.
365 CurMBB
.addSuccessor(NewMBB
);
367 // Splice the code over.
368 NewMBB
->splice(NewMBB
->end(), &CurMBB
, BBI1
, CurMBB
.end());
370 // For targets that use the register scavenger, we must maintain LiveIns.
372 RS
->enterBasicBlock(&CurMBB
);
374 RS
->forward(prior(CurMBB
.end()));
375 BitVector
RegsLiveAtExit(TRI
->getNumRegs());
376 RS
->getRegsUsed(RegsLiveAtExit
, false);
377 for (unsigned int i
=0, e
=TRI
->getNumRegs(); i
!=e
; i
++)
378 if (RegsLiveAtExit
[i
])
379 NewMBB
->addLiveIn(i
);
385 /// EstimateRuntime - Make a rough estimate for how long it will take to run
386 /// the specified code.
387 static unsigned EstimateRuntime(MachineBasicBlock::iterator I
,
388 MachineBasicBlock::iterator E
) {
390 for (; I
!= E
; ++I
) {
391 const TargetInstrDesc
&TID
= I
->getDesc();
394 else if (TID
.mayLoad() || TID
.mayStore())
402 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
403 // branches temporarily for tail merging). In the case where CurMBB ends
404 // with a conditional branch to the next block, optimize by reversing the
405 // test and conditionally branching to SuccMBB instead.
407 static void FixTail(MachineBasicBlock
* CurMBB
, MachineBasicBlock
*SuccBB
,
408 const TargetInstrInfo
*TII
) {
409 MachineFunction
*MF
= CurMBB
->getParent();
410 MachineFunction::iterator I
= next(MachineFunction::iterator(CurMBB
));
411 MachineBasicBlock
*TBB
= 0, *FBB
= 0;
412 SmallVector
<MachineOperand
, 4> Cond
;
413 if (I
!= MF
->end() &&
414 !TII
->AnalyzeBranch(*CurMBB
, TBB
, FBB
, Cond
, true)) {
415 MachineBasicBlock
*NextBB
= I
;
416 if (TBB
== NextBB
&& !Cond
.empty() && !FBB
) {
417 if (!TII
->ReverseBranchCondition(Cond
)) {
418 TII
->RemoveBranch(*CurMBB
);
419 TII
->InsertBranch(*CurMBB
, SuccBB
, NULL
, Cond
);
424 TII
->InsertBranch(*CurMBB
, SuccBB
, NULL
, SmallVector
<MachineOperand
, 0>());
427 static bool MergeCompare(const std::pair
<unsigned,MachineBasicBlock
*> &p
,
428 const std::pair
<unsigned,MachineBasicBlock
*> &q
) {
429 if (p
.first
< q
.first
)
431 else if (p
.first
> q
.first
)
433 else if (p
.second
->getNumber() < q
.second
->getNumber())
435 else if (p
.second
->getNumber() > q
.second
->getNumber())
438 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
439 // an object with itself.
440 #ifndef _GLIBCXX_DEBUG
441 llvm_unreachable("Predecessor appears twice");
447 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
448 /// hash CurHash (guaranteed to match the last element). Build the vector
449 /// SameTails of all those that have the (same) largest number of instructions
450 /// in common of any pair of these blocks. SameTails entries contain an
451 /// iterator into MergePotentials (from which the MachineBasicBlock can be
452 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
453 /// instruction where the matching code sequence begins.
454 /// Order of elements in SameTails is the reverse of the order in which
455 /// those blocks appear in MergePotentials (where they are not necessarily
457 unsigned BranchFolder::ComputeSameTails(unsigned CurHash
,
458 unsigned minCommonTailLength
) {
459 unsigned maxCommonTailLength
= 0U;
461 MachineBasicBlock::iterator TrialBBI1
, TrialBBI2
;
462 MPIterator HighestMPIter
= prior(MergePotentials
.end());
463 for (MPIterator CurMPIter
= prior(MergePotentials
.end()),
464 B
= MergePotentials
.begin();
465 CurMPIter
!=B
&& CurMPIter
->first
==CurHash
;
467 for (MPIterator I
= prior(CurMPIter
); I
->first
==CurHash
; --I
) {
468 unsigned CommonTailLen
= ComputeCommonTailLength(
471 TrialBBI1
, TrialBBI2
);
472 // If we will have to split a block, there should be at least
473 // minCommonTailLength instructions in common; if not, at worst
474 // we will be replacing a fallthrough into the common tail with a
475 // branch, which at worst breaks even with falling through into
476 // the duplicated common tail, so 1 instruction in common is enough.
477 // We will always pick a block we do not have to split as the common
478 // tail if there is one.
479 // (Empty blocks will get forwarded and need not be considered.)
480 if (CommonTailLen
>= minCommonTailLength
||
481 (CommonTailLen
> 0 &&
482 (TrialBBI1
==CurMPIter
->second
->begin() ||
483 TrialBBI2
==I
->second
->begin()))) {
484 if (CommonTailLen
> maxCommonTailLength
) {
486 maxCommonTailLength
= CommonTailLen
;
487 HighestMPIter
= CurMPIter
;
488 SameTails
.push_back(std::make_pair(CurMPIter
, TrialBBI1
));
490 if (HighestMPIter
== CurMPIter
&&
491 CommonTailLen
== maxCommonTailLength
)
492 SameTails
.push_back(std::make_pair(I
, TrialBBI2
));
498 return maxCommonTailLength
;
501 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
502 /// MergePotentials, restoring branches at ends of blocks as appropriate.
503 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash
,
504 MachineBasicBlock
* SuccBB
,
505 MachineBasicBlock
* PredBB
) {
506 MPIterator CurMPIter
, B
;
507 for (CurMPIter
= prior(MergePotentials
.end()), B
= MergePotentials
.begin();
508 CurMPIter
->first
==CurHash
;
510 // Put the unconditional branch back, if we need one.
511 MachineBasicBlock
*CurMBB
= CurMPIter
->second
;
512 if (SuccBB
&& CurMBB
!= PredBB
)
513 FixTail(CurMBB
, SuccBB
, TII
);
517 if (CurMPIter
->first
!=CurHash
)
519 MergePotentials
.erase(CurMPIter
, MergePotentials
.end());
522 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
523 /// only of the common tail. Create a block that does by splitting one.
524 unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock
*&PredBB
,
525 unsigned maxCommonTailLength
) {
526 unsigned i
, commonTailIndex
;
527 unsigned TimeEstimate
= ~0U;
528 for (i
=0, commonTailIndex
=0; i
<SameTails
.size(); i
++) {
529 // Use PredBB if possible; that doesn't require a new branch.
530 if (SameTails
[i
].first
->second
==PredBB
) {
534 // Otherwise, make a (fairly bogus) choice based on estimate of
535 // how long it will take the various blocks to execute.
536 unsigned t
= EstimateRuntime(SameTails
[i
].first
->second
->begin(),
537 SameTails
[i
].second
);
538 if (t
<=TimeEstimate
) {
544 MachineBasicBlock::iterator BBI
= SameTails
[commonTailIndex
].second
;
545 MachineBasicBlock
*MBB
= SameTails
[commonTailIndex
].first
->second
;
547 DEBUG(errs() << "\nSplitting " << MBB
->getNumber() << ", size "
548 << maxCommonTailLength
);
550 MachineBasicBlock
*newMBB
= SplitMBBAt(*MBB
, BBI
);
551 SameTails
[commonTailIndex
].first
->second
= newMBB
;
552 SameTails
[commonTailIndex
].second
= newMBB
->begin();
553 // If we split PredBB, newMBB is the new predecessor.
557 return commonTailIndex
;
560 // See if any of the blocks in MergePotentials (which all have a common single
561 // successor, or all have no successor) can be tail-merged. If there is a
562 // successor, any blocks in MergePotentials that are not tail-merged and
563 // are not immediately before Succ must have an unconditional branch to
564 // Succ added (but the predecessor/successor lists need no adjustment).
565 // The lone predecessor of Succ that falls through into Succ,
566 // if any, is given in PredBB.
568 bool BranchFolder::TryMergeBlocks(MachineBasicBlock
*SuccBB
,
569 MachineBasicBlock
* PredBB
) {
570 bool MadeChange
= false;
572 // It doesn't make sense to save a single instruction since tail merging
574 // FIXME: Ask the target to provide the threshold?
575 unsigned minCommonTailLength
= (SuccBB
? 1 : 2) + 1;
577 DEBUG(errs() << "\nTryMergeBlocks " << MergePotentials
.size() << '\n');
579 // Sort by hash value so that blocks with identical end sequences sort
581 std::stable_sort(MergePotentials
.begin(), MergePotentials
.end(),MergeCompare
);
583 // Walk through equivalence sets looking for actual exact matches.
584 while (MergePotentials
.size() > 1) {
585 unsigned CurHash
= prior(MergePotentials
.end())->first
;
587 // Build SameTails, identifying the set of blocks with this hash code
588 // and with the maximum number of instructions in common.
589 unsigned maxCommonTailLength
= ComputeSameTails(CurHash
,
590 minCommonTailLength
);
592 // If we didn't find any pair that has at least minCommonTailLength
593 // instructions in common, remove all blocks with this hash code and retry.
594 if (SameTails
.empty()) {
595 RemoveBlocksWithHash(CurHash
, SuccBB
, PredBB
);
599 // If one of the blocks is the entire common tail (and not the entry
600 // block, which we can't jump to), we can treat all blocks with this same
601 // tail at once. Use PredBB if that is one of the possibilities, as that
602 // will not introduce any extra branches.
603 MachineBasicBlock
*EntryBB
= MergePotentials
.begin()->second
->
604 getParent()->begin();
605 unsigned int commonTailIndex
, i
;
606 for (commonTailIndex
=SameTails
.size(), i
=0; i
<SameTails
.size(); i
++) {
607 MachineBasicBlock
*MBB
= SameTails
[i
].first
->second
;
608 if (MBB
->begin() == SameTails
[i
].second
&& MBB
!= EntryBB
) {
615 if (commonTailIndex
==SameTails
.size()) {
616 // None of the blocks consist entirely of the common tail.
617 // Split a block so that one does.
618 commonTailIndex
= CreateCommonTailOnlyBlock(PredBB
, maxCommonTailLength
);
621 MachineBasicBlock
*MBB
= SameTails
[commonTailIndex
].first
->second
;
622 // MBB is common tail. Adjust all other BB's to jump to this one.
623 // Traversal must be forwards so erases work.
624 DEBUG(errs() << "\nUsing common tail " << MBB
->getNumber() << " for ");
625 for (unsigned int i
=0; i
<SameTails
.size(); ++i
) {
626 if (commonTailIndex
==i
)
628 DEBUG(errs() << SameTails
[i
].first
->second
->getNumber() << ",");
629 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
630 ReplaceTailWithBranchTo(SameTails
[i
].second
, MBB
);
631 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
632 MergePotentials
.erase(SameTails
[i
].first
);
634 DEBUG(errs() << "\n");
635 // We leave commonTailIndex in the worklist in case there are other blocks
636 // that match it with a smaller number of instructions.
642 bool BranchFolder::TailMergeBlocks(MachineFunction
&MF
) {
644 if (!EnableTailMerge
) return false;
646 bool MadeChange
= false;
648 // First find blocks with no successors.
649 MergePotentials
.clear();
650 for (MachineFunction::iterator I
= MF
.begin(), E
= MF
.end(); I
!= E
; ++I
) {
652 MergePotentials
.push_back(std::make_pair(HashEndOfMBB(I
, 2U), I
));
654 // See if we can do any tail merging on those.
655 if (MergePotentials
.size() < TailMergeThreshold
&&
656 MergePotentials
.size() >= 2)
657 MadeChange
|= TryMergeBlocks(NULL
, NULL
);
659 // Look at blocks (IBB) with multiple predecessors (PBB).
660 // We change each predecessor to a canonical form, by
661 // (1) temporarily removing any unconditional branch from the predecessor
663 // (2) alter conditional branches so they branch to the other block
664 // not IBB; this may require adding back an unconditional branch to IBB
665 // later, where there wasn't one coming in. E.g.
667 // fallthrough to QBB
670 // with a conceptual B to IBB after that, which never actually exists.
671 // With those changes, we see whether the predecessors' tails match,
672 // and merge them if so. We change things out of canonical form and
673 // back to the way they were later in the process. (OptimizeBranches
674 // would undo some of this, but we can't use it, because we'd get into
675 // a compile-time infinite loop repeatedly doing and undoing the same
678 for (MachineFunction::iterator I
= MF
.begin(), E
= MF
.end(); I
!= E
; ++I
) {
679 if (I
->pred_size() >= 2 && I
->pred_size() < TailMergeThreshold
) {
680 SmallPtrSet
<MachineBasicBlock
*, 8> UniquePreds
;
681 MachineBasicBlock
*IBB
= I
;
682 MachineBasicBlock
*PredBB
= prior(I
);
683 MergePotentials
.clear();
684 for (MachineBasicBlock::pred_iterator P
= I
->pred_begin(),
687 MachineBasicBlock
* PBB
= *P
;
688 // Skip blocks that loop to themselves, can't tail merge these.
691 // Visit each predecessor only once.
692 if (!UniquePreds
.insert(PBB
))
694 MachineBasicBlock
*TBB
= 0, *FBB
= 0;
695 SmallVector
<MachineOperand
, 4> Cond
;
696 if (!TII
->AnalyzeBranch(*PBB
, TBB
, FBB
, Cond
, true)) {
697 // Failing case: IBB is the target of a cbr, and
698 // we cannot reverse the branch.
699 SmallVector
<MachineOperand
, 4> NewCond(Cond
);
700 if (!Cond
.empty() && TBB
==IBB
) {
701 if (TII
->ReverseBranchCondition(NewCond
))
703 // This is the QBB case described above
705 FBB
= next(MachineFunction::iterator(PBB
));
707 // Failing case: the only way IBB can be reached from PBB is via
708 // exception handling. Happens for landing pads. Would be nice
709 // to have a bit in the edge so we didn't have to do all this.
710 if (IBB
->isLandingPad()) {
711 MachineFunction::iterator IP
= PBB
; IP
++;
712 MachineBasicBlock
* PredNextBB
= NULL
;
716 if (IBB
!=PredNextBB
) // fallthrough
719 if (TBB
!=IBB
&& FBB
!=IBB
) // cbr then ubr
721 } else if (Cond
.empty()) {
725 if (TBB
!=IBB
&& IBB
!=PredNextBB
) // cbr
729 // Remove the unconditional branch at the end, if any.
730 if (TBB
&& (Cond
.empty() || FBB
)) {
731 TII
->RemoveBranch(*PBB
);
733 // reinsert conditional branch only, for now
734 TII
->InsertBranch(*PBB
, (TBB
==IBB
) ? FBB
: TBB
, 0, NewCond
);
736 MergePotentials
.push_back(std::make_pair(HashEndOfMBB(PBB
, 1U), *P
));
739 if (MergePotentials
.size() >= 2)
740 MadeChange
|= TryMergeBlocks(I
, PredBB
);
741 // Reinsert an unconditional branch if needed.
742 // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
743 PredBB
= prior(I
); // this may have been changed in TryMergeBlocks
744 if (MergePotentials
.size()==1 &&
745 MergePotentials
.begin()->second
!= PredBB
)
746 FixTail(MergePotentials
.begin()->second
, I
, TII
);
752 //===----------------------------------------------------------------------===//
753 // Branch Optimization
754 //===----------------------------------------------------------------------===//
756 bool BranchFolder::OptimizeBranches(MachineFunction
&MF
) {
757 bool MadeChange
= false;
759 // Make sure blocks are numbered in order
762 for (MachineFunction::iterator I
= ++MF
.begin(), E
= MF
.end(); I
!= E
; ) {
763 MachineBasicBlock
*MBB
= I
++;
764 MadeChange
|= OptimizeBlock(MBB
);
766 // If it is dead, remove it.
767 if (MBB
->pred_empty()) {
768 RemoveDeadBlock(MBB
);
777 /// CanFallThrough - Return true if the specified block (with the specified
778 /// branch condition) can implicitly transfer control to the block after it by
779 /// falling off the end of it. This should return false if it can reach the
780 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
782 /// True is a conservative answer.
784 bool BranchFolder::CanFallThrough(MachineBasicBlock
*CurBB
,
785 bool BranchUnAnalyzable
,
786 MachineBasicBlock
*TBB
,
787 MachineBasicBlock
*FBB
,
788 const SmallVectorImpl
<MachineOperand
> &Cond
) {
789 MachineFunction::iterator Fallthrough
= CurBB
;
791 // If FallthroughBlock is off the end of the function, it can't fall through.
792 if (Fallthrough
== CurBB
->getParent()->end())
795 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
796 if (!CurBB
->isSuccessor(Fallthrough
))
799 // If we couldn't analyze the branch, assume it could fall through.
800 if (BranchUnAnalyzable
) return true;
802 // If there is no branch, control always falls through.
803 if (TBB
== 0) return true;
805 // If there is some explicit branch to the fallthrough block, it can obviously
806 // reach, even though the branch should get folded to fall through implicitly.
807 if (MachineFunction::iterator(TBB
) == Fallthrough
||
808 MachineFunction::iterator(FBB
) == Fallthrough
)
811 // If it's an unconditional branch to some block not the fall through, it
812 // doesn't fall through.
813 if (Cond
.empty()) return false;
815 // Otherwise, if it is conditional and has no explicit false block, it falls
820 /// CanFallThrough - Return true if the specified can implicitly transfer
821 /// control to the block after it by falling off the end of it. This should
822 /// return false if it can reach the block after it, but it uses an explicit
823 /// branch to do so (e.g. a table jump).
825 /// True is a conservative answer.
827 bool BranchFolder::CanFallThrough(MachineBasicBlock
*CurBB
) {
828 MachineBasicBlock
*TBB
= 0, *FBB
= 0;
829 SmallVector
<MachineOperand
, 4> Cond
;
830 bool CurUnAnalyzable
= TII
->AnalyzeBranch(*CurBB
, TBB
, FBB
, Cond
, true);
831 return CanFallThrough(CurBB
, CurUnAnalyzable
, TBB
, FBB
, Cond
);
834 /// IsBetterFallthrough - Return true if it would be clearly better to
835 /// fall-through to MBB1 than to fall through into MBB2. This has to return
836 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
837 /// result in infinite loops.
838 static bool IsBetterFallthrough(MachineBasicBlock
*MBB1
,
839 MachineBasicBlock
*MBB2
) {
840 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
841 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
842 // optimize branches that branch to either a return block or an assert block
843 // into a fallthrough to the return.
844 if (MBB1
->empty() || MBB2
->empty()) return false;
846 // If there is a clear successor ordering we make sure that one block
847 // will fall through to the next
848 if (MBB1
->isSuccessor(MBB2
)) return true;
849 if (MBB2
->isSuccessor(MBB1
)) return false;
851 MachineInstr
*MBB1I
= --MBB1
->end();
852 MachineInstr
*MBB2I
= --MBB2
->end();
853 return MBB2I
->getDesc().isCall() && !MBB1I
->getDesc().isCall();
856 /// OptimizeBlock - Analyze and optimize control flow related to the specified
857 /// block. This is never called on the entry block.
858 bool BranchFolder::OptimizeBlock(MachineBasicBlock
*MBB
) {
859 bool MadeChange
= false;
861 MachineFunction::iterator FallThrough
= MBB
;
864 // If this block is empty, make everyone use its fall-through, not the block
865 // explicitly. Landing pads should not do this since the landing-pad table
866 // points to this block.
867 if (MBB
->empty() && !MBB
->isLandingPad()) {
868 // Dead block? Leave for cleanup later.
869 if (MBB
->pred_empty()) return MadeChange
;
871 if (FallThrough
== MBB
->getParent()->end()) {
872 // TODO: Simplify preds to not branch here if possible!
874 // Rewrite all predecessors of the old block to go to the fallthrough
876 while (!MBB
->pred_empty()) {
877 MachineBasicBlock
*Pred
= *(MBB
->pred_end()-1);
878 Pred
->ReplaceUsesOfBlockWith(MBB
, FallThrough
);
880 // If MBB was the target of a jump table, update jump tables to go to the
881 // fallthrough instead.
882 MBB
->getParent()->getJumpTableInfo()->
883 ReplaceMBBInJumpTables(MBB
, FallThrough
);
889 // Check to see if we can simplify the terminator of the block before this
891 MachineBasicBlock
&PrevBB
= *prior(MachineFunction::iterator(MBB
));
893 MachineBasicBlock
*PriorTBB
= 0, *PriorFBB
= 0;
894 SmallVector
<MachineOperand
, 4> PriorCond
;
895 bool PriorUnAnalyzable
=
896 TII
->AnalyzeBranch(PrevBB
, PriorTBB
, PriorFBB
, PriorCond
, true);
897 if (!PriorUnAnalyzable
) {
898 // If the CFG for the prior block has extra edges, remove them.
899 MadeChange
|= PrevBB
.CorrectExtraCFGEdges(PriorTBB
, PriorFBB
,
902 // If the previous branch is conditional and both conditions go to the same
903 // destination, remove the branch, replacing it with an unconditional one or
905 if (PriorTBB
&& PriorTBB
== PriorFBB
) {
906 TII
->RemoveBranch(PrevBB
);
909 TII
->InsertBranch(PrevBB
, PriorTBB
, 0, PriorCond
);
912 return OptimizeBlock(MBB
);
915 // If the previous branch *only* branches to *this* block (conditional or
916 // not) remove the branch.
917 if (PriorTBB
== MBB
&& PriorFBB
== 0) {
918 TII
->RemoveBranch(PrevBB
);
921 return OptimizeBlock(MBB
);
924 // If the prior block branches somewhere else on the condition and here if
925 // the condition is false, remove the uncond second branch.
926 if (PriorFBB
== MBB
) {
927 TII
->RemoveBranch(PrevBB
);
928 TII
->InsertBranch(PrevBB
, PriorTBB
, 0, PriorCond
);
931 return OptimizeBlock(MBB
);
934 // If the prior block branches here on true and somewhere else on false, and
935 // if the branch condition is reversible, reverse the branch to create a
937 if (PriorTBB
== MBB
) {
938 SmallVector
<MachineOperand
, 4> NewPriorCond(PriorCond
);
939 if (!TII
->ReverseBranchCondition(NewPriorCond
)) {
940 TII
->RemoveBranch(PrevBB
);
941 TII
->InsertBranch(PrevBB
, PriorFBB
, 0, NewPriorCond
);
944 return OptimizeBlock(MBB
);
948 // If this block doesn't fall through (e.g. it ends with an uncond branch or
949 // has no successors) and if the pred falls through into this block, and if
950 // it would otherwise fall through into the block after this, move this
951 // block to the end of the function.
953 // We consider it more likely that execution will stay in the function (e.g.
954 // due to loops) than it is to exit it. This asserts in loops etc, moving
955 // the assert condition out of the loop body.
956 if (!PriorCond
.empty() && PriorFBB
== 0 &&
957 MachineFunction::iterator(PriorTBB
) == FallThrough
&&
958 !CanFallThrough(MBB
)) {
959 bool DoTransform
= true;
961 // We have to be careful that the succs of PredBB aren't both no-successor
962 // blocks. If neither have successors and if PredBB is the second from
963 // last block in the function, we'd just keep swapping the two blocks for
964 // last. Only do the swap if one is clearly better to fall through than
966 if (FallThrough
== --MBB
->getParent()->end() &&
967 !IsBetterFallthrough(PriorTBB
, MBB
))
970 // We don't want to do this transformation if we have control flow like:
979 // In this case, we could actually be moving the return block *into* a
981 if (DoTransform
&& !MBB
->succ_empty() &&
982 (!CanFallThrough(PriorTBB
) || PriorTBB
->empty()))
987 // Reverse the branch so we will fall through on the previous true cond.
988 SmallVector
<MachineOperand
, 4> NewPriorCond(PriorCond
);
989 if (!TII
->ReverseBranchCondition(NewPriorCond
)) {
990 DEBUG(errs() << "\nMoving MBB: " << *MBB
991 << "To make fallthrough to: " << *PriorTBB
<< "\n");
993 TII
->RemoveBranch(PrevBB
);
994 TII
->InsertBranch(PrevBB
, MBB
, 0, NewPriorCond
);
996 // Move this block to the end of the function.
997 MBB
->moveAfter(--MBB
->getParent()->end());
1006 // Analyze the branch in the current block.
1007 MachineBasicBlock
*CurTBB
= 0, *CurFBB
= 0;
1008 SmallVector
<MachineOperand
, 4> CurCond
;
1009 bool CurUnAnalyzable
= TII
->AnalyzeBranch(*MBB
, CurTBB
, CurFBB
, CurCond
, true);
1010 if (!CurUnAnalyzable
) {
1011 // If the CFG for the prior block has extra edges, remove them.
1012 MadeChange
|= MBB
->CorrectExtraCFGEdges(CurTBB
, CurFBB
, !CurCond
.empty());
1014 // If this is a two-way branch, and the FBB branches to this block, reverse
1015 // the condition so the single-basic-block loop is faster. Instead of:
1016 // Loop: xxx; jcc Out; jmp Loop
1018 // Loop: xxx; jncc Loop; jmp Out
1019 if (CurTBB
&& CurFBB
&& CurFBB
== MBB
&& CurTBB
!= MBB
) {
1020 SmallVector
<MachineOperand
, 4> NewCond(CurCond
);
1021 if (!TII
->ReverseBranchCondition(NewCond
)) {
1022 TII
->RemoveBranch(*MBB
);
1023 TII
->InsertBranch(*MBB
, CurFBB
, CurTBB
, NewCond
);
1026 return OptimizeBlock(MBB
);
1031 // If this branch is the only thing in its block, see if we can forward
1032 // other blocks across it.
1033 if (CurTBB
&& CurCond
.empty() && CurFBB
== 0 &&
1034 MBB
->begin()->getDesc().isBranch() && CurTBB
!= MBB
) {
1035 // This block may contain just an unconditional branch. Because there can
1036 // be 'non-branch terminators' in the block, try removing the branch and
1037 // then seeing if the block is empty.
1038 TII
->RemoveBranch(*MBB
);
1040 // If this block is just an unconditional branch to CurTBB, we can
1041 // usually completely eliminate the block. The only case we cannot
1042 // completely eliminate the block is when the block before this one
1043 // falls through into MBB and we can't understand the prior block's branch
1046 bool PredHasNoFallThrough
= TII
->BlockHasNoFallThrough(PrevBB
);
1047 if (PredHasNoFallThrough
|| !PriorUnAnalyzable
||
1048 !PrevBB
.isSuccessor(MBB
)) {
1049 // If the prior block falls through into us, turn it into an
1050 // explicit branch to us to make updates simpler.
1051 if (!PredHasNoFallThrough
&& PrevBB
.isSuccessor(MBB
) &&
1052 PriorTBB
!= MBB
&& PriorFBB
!= MBB
) {
1053 if (PriorTBB
== 0) {
1054 assert(PriorCond
.empty() && PriorFBB
== 0 &&
1055 "Bad branch analysis");
1058 assert(PriorFBB
== 0 && "Machine CFG out of date!");
1061 TII
->RemoveBranch(PrevBB
);
1062 TII
->InsertBranch(PrevBB
, PriorTBB
, PriorFBB
, PriorCond
);
1065 // Iterate through all the predecessors, revectoring each in-turn.
1067 bool DidChange
= false;
1068 bool HasBranchToSelf
= false;
1069 while(PI
!= MBB
->pred_size()) {
1070 MachineBasicBlock
*PMBB
= *(MBB
->pred_begin() + PI
);
1072 // If this block has an uncond branch to itself, leave it.
1074 HasBranchToSelf
= true;
1077 PMBB
->ReplaceUsesOfBlockWith(MBB
, CurTBB
);
1078 // If this change resulted in PMBB ending in a conditional
1079 // branch where both conditions go to the same destination,
1080 // change this to an unconditional branch (and fix the CFG).
1081 MachineBasicBlock
*NewCurTBB
= 0, *NewCurFBB
= 0;
1082 SmallVector
<MachineOperand
, 4> NewCurCond
;
1083 bool NewCurUnAnalyzable
= TII
->AnalyzeBranch(*PMBB
, NewCurTBB
,
1084 NewCurFBB
, NewCurCond
, true);
1085 if (!NewCurUnAnalyzable
&& NewCurTBB
&& NewCurTBB
== NewCurFBB
) {
1086 TII
->RemoveBranch(*PMBB
);
1088 TII
->InsertBranch(*PMBB
, NewCurTBB
, 0, NewCurCond
);
1091 PMBB
->CorrectExtraCFGEdges(NewCurTBB
, NewCurFBB
, false);
1096 // Change any jumptables to go to the new MBB.
1097 MBB
->getParent()->getJumpTableInfo()->
1098 ReplaceMBBInJumpTables(MBB
, CurTBB
);
1102 if (!HasBranchToSelf
) return MadeChange
;
1107 // Add the branch back if the block is more than just an uncond branch.
1108 TII
->InsertBranch(*MBB
, CurTBB
, 0, CurCond
);
1112 // If the prior block doesn't fall through into this block, and if this
1113 // block doesn't fall through into some other block, see if we can find a
1114 // place to move this block where a fall-through will happen.
1115 if (!CanFallThrough(&PrevBB
, PriorUnAnalyzable
,
1116 PriorTBB
, PriorFBB
, PriorCond
)) {
1117 // Now we know that there was no fall-through into this block, check to
1118 // see if it has a fall-through into its successor.
1119 bool CurFallsThru
= CanFallThrough(MBB
, CurUnAnalyzable
, CurTBB
, CurFBB
,
1122 if (!MBB
->isLandingPad()) {
1123 // Check all the predecessors of this block. If one of them has no fall
1124 // throughs, move this block right after it.
1125 for (MachineBasicBlock::pred_iterator PI
= MBB
->pred_begin(),
1126 E
= MBB
->pred_end(); PI
!= E
; ++PI
) {
1127 // Analyze the branch at the end of the pred.
1128 MachineBasicBlock
*PredBB
= *PI
;
1129 MachineFunction::iterator PredFallthrough
= PredBB
; ++PredFallthrough
;
1130 if (PredBB
!= MBB
&& !CanFallThrough(PredBB
)
1131 && (!CurFallsThru
|| !CurTBB
|| !CurFBB
)
1132 && (!CurFallsThru
|| MBB
->getNumber() >= PredBB
->getNumber())) {
1133 // If the current block doesn't fall through, just move it.
1134 // If the current block can fall through and does not end with a
1135 // conditional branch, we need to append an unconditional jump to
1136 // the (current) next block. To avoid a possible compile-time
1137 // infinite loop, move blocks only backward in this case.
1138 // Also, if there are already 2 branches here, we cannot add a third;
1139 // this means we have the case
1144 MachineBasicBlock
*NextBB
= next(MachineFunction::iterator(MBB
));
1146 TII
->InsertBranch(*MBB
, NextBB
, 0, CurCond
);
1148 MBB
->moveAfter(PredBB
);
1150 return OptimizeBlock(MBB
);
1155 if (!CurFallsThru
) {
1156 // Check all successors to see if we can move this block before it.
1157 for (MachineBasicBlock::succ_iterator SI
= MBB
->succ_begin(),
1158 E
= MBB
->succ_end(); SI
!= E
; ++SI
) {
1159 // Analyze the branch at the end of the block before the succ.
1160 MachineBasicBlock
*SuccBB
= *SI
;
1161 MachineFunction::iterator SuccPrev
= SuccBB
; --SuccPrev
;
1162 std::vector
<MachineOperand
> SuccPrevCond
;
1164 // If this block doesn't already fall-through to that successor, and if
1165 // the succ doesn't already have a block that can fall through into it,
1166 // and if the successor isn't an EH destination, we can arrange for the
1167 // fallthrough to happen.
1168 if (SuccBB
!= MBB
&& !CanFallThrough(SuccPrev
) &&
1169 !SuccBB
->isLandingPad()) {
1170 MBB
->moveBefore(SuccBB
);
1172 return OptimizeBlock(MBB
);
1176 // Okay, there is no really great place to put this block. If, however,
1177 // the block before this one would be a fall-through if this block were
1178 // removed, move this block to the end of the function.
1179 if (FallThrough
!= MBB
->getParent()->end() &&
1180 PrevBB
.isSuccessor(FallThrough
)) {
1181 MBB
->moveAfter(--MBB
->getParent()->end());