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 "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"
27 #include "llvm/Target/TargetRegisterInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/STLExtras.h"
36 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
37 STATISTIC(NumBranchOpts, "Number of branches optimized");
38 STATISTIC(NumTailMerge , "Number of block tails merged");
39 static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
40 cl::init(cl::BOU_UNSET), cl::Hidden);
41 // Throttle for huge numbers of predecessors (compile speed problems)
42 static cl::opt<unsigned>
43 TailMergeThreshold("tail-merge-threshold",
44 cl::desc("Max number of predecessors to consider tail merging"),
45 cl::init(100), cl::Hidden);
48 struct VISIBILITY_HIDDEN BranchFolder : public MachineFunctionPass {
50 explicit BranchFolder(bool defaultEnableTailMerge) :
51 MachineFunctionPass((intptr_t)&ID) {
52 switch (FlagEnableTailMerge) {
53 case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
54 case cl::BOU_TRUE: EnableTailMerge = true; break;
55 case cl::BOU_FALSE: EnableTailMerge = false; break;
59 virtual bool runOnMachineFunction(MachineFunction &MF);
60 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
61 const TargetInstrInfo *TII;
62 MachineModuleInfo *MMI;
67 bool TailMergeBlocks(MachineFunction &MF);
68 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
69 MachineBasicBlock* PredBB);
70 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
71 MachineBasicBlock *NewDest);
72 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
73 MachineBasicBlock::iterator BBI1);
74 unsigned ComputeSameTails(unsigned CurHash, unsigned minCommonTailLength);
75 void RemoveBlocksWithHash(unsigned CurHash, MachineBasicBlock* SuccBB,
76 MachineBasicBlock* PredBB);
77 unsigned CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
78 unsigned maxCommonTailLength);
80 typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
81 typedef std::vector<MergePotentialsElt>::iterator MPIterator;
82 std::vector<MergePotentialsElt> MergePotentials;
84 typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
85 std::vector<SameTailElt> SameTails;
87 const TargetRegisterInfo *RegInfo;
90 bool OptimizeBranches(MachineFunction &MF);
91 void OptimizeBlock(MachineBasicBlock *MBB);
92 void RemoveDeadBlock(MachineBasicBlock *MBB);
93 bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
95 bool CanFallThrough(MachineBasicBlock *CurBB);
96 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
97 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
98 const std::vector<MachineOperand> &Cond);
100 char BranchFolder::ID = 0;
103 FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
104 return new BranchFolder(DefaultEnableTailMerge); }
106 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
107 /// function, updating the CFG.
108 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
109 assert(MBB->pred_empty() && "MBB must be dead!");
110 DOUT << "\nRemoving MBB: " << *MBB;
112 MachineFunction *MF = MBB->getParent();
113 // drop all successors.
114 while (!MBB->succ_empty())
115 MBB->removeSuccessor(MBB->succ_end()-1);
117 // If there is DWARF info to active, check to see if there are any LABEL
118 // records in the basic block. If so, unregister them from MachineModuleInfo.
119 if (MMI && !MBB->empty()) {
120 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
122 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
123 // The label ID # is always operand #0, an immediate.
124 MMI->InvalidateLabel(I->getOperand(0).getImm());
130 MF->getBasicBlockList().erase(MBB);
133 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
134 /// followed by terminators, and if the implicitly defined registers are not
135 /// used by the terminators, remove those implicit_def's. e.g.
137 /// r0 = implicit_def
138 /// r1 = implicit_def
140 /// This block can be optimized away later if the implicit instructions are
142 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
143 SmallSet<unsigned, 4> ImpDefRegs;
144 MachineBasicBlock::iterator I = MBB->begin();
145 while (I != MBB->end()) {
146 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
148 unsigned Reg = I->getOperand(0).getReg();
149 ImpDefRegs.insert(Reg);
150 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
151 unsigned SubReg = *SubRegs; ++SubRegs)
152 ImpDefRegs.insert(SubReg);
155 if (ImpDefRegs.empty())
158 MachineBasicBlock::iterator FirstTerm = I;
159 while (I != MBB->end()) {
160 if (!TII->isUnpredicatedTerminator(I))
162 // See if it uses any of the implicitly defined registers.
163 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
164 MachineOperand &MO = I->getOperand(i);
165 if (!MO.isReg() || !MO.isUse())
167 unsigned Reg = MO.getReg();
168 if (ImpDefRegs.count(Reg))
175 while (I != FirstTerm) {
176 MachineInstr *ImpDefMI = &*I;
178 MBB->erase(ImpDefMI);
184 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
185 TII = MF.getTarget().getInstrInfo();
186 if (!TII) return false;
188 RegInfo = MF.getTarget().getRegisterInfo();
190 // Fix CFG. The later algorithms expect it to be right.
191 bool EverMadeChange = false;
192 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
193 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
194 std::vector<MachineOperand> Cond;
195 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
196 EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
197 EverMadeChange |= OptimizeImpDefsBlock(MBB);
200 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
202 MMI = getAnalysisToUpdate<MachineModuleInfo>();
204 bool MadeChangeThisIteration = true;
205 while (MadeChangeThisIteration) {
206 MadeChangeThisIteration = false;
207 MadeChangeThisIteration |= TailMergeBlocks(MF);
208 MadeChangeThisIteration |= OptimizeBranches(MF);
209 EverMadeChange |= MadeChangeThisIteration;
212 // See if any jump tables have become mergable or dead as the code generator
214 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
215 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
217 // Figure out how these jump tables should be merged.
218 std::vector<unsigned> JTMapping;
219 JTMapping.reserve(JTs.size());
221 // We always keep the 0th jump table.
222 JTMapping.push_back(0);
224 // Scan the jump tables, seeing if there are any duplicates. Note that this
225 // is N^2, which should be fixed someday.
226 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
227 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
229 // If a jump table was merge with another one, walk the function rewriting
230 // references to jump tables to reference the new JT ID's. Keep track of
231 // whether we see a jump table idx, if not, we can delete the JT.
232 BitVector JTIsLive(JTs.size());
233 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
235 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
237 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
238 MachineOperand &Op = I->getOperand(op);
239 if (!Op.isJumpTableIndex()) continue;
240 unsigned NewIdx = JTMapping[Op.getIndex()];
243 // Remember that this JT is live.
244 JTIsLive.set(NewIdx);
248 // Finally, remove dead jump tables. This happens either because the
249 // indirect jump was unreachable (and thus deleted) or because the jump
250 // table was merged with some other one.
251 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
252 if (!JTIsLive.test(i)) {
253 JTI->RemoveJumpTable(i);
254 EverMadeChange = true;
259 return EverMadeChange;
262 //===----------------------------------------------------------------------===//
263 // Tail Merging of Blocks
264 //===----------------------------------------------------------------------===//
266 /// HashMachineInstr - Compute a hash value for MI and its operands.
267 static unsigned HashMachineInstr(const MachineInstr *MI) {
268 unsigned Hash = MI->getOpcode();
269 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
270 const MachineOperand &Op = MI->getOperand(i);
272 // Merge in bits from the operand if easy.
273 unsigned OperandHash = 0;
274 switch (Op.getType()) {
275 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
276 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
277 case MachineOperand::MO_MachineBasicBlock:
278 OperandHash = Op.getMBB()->getNumber();
280 case MachineOperand::MO_FrameIndex:
281 case MachineOperand::MO_ConstantPoolIndex:
282 case MachineOperand::MO_JumpTableIndex:
283 OperandHash = Op.getIndex();
285 case MachineOperand::MO_GlobalAddress:
286 case MachineOperand::MO_ExternalSymbol:
287 // Global address / external symbol are too hard, don't bother, but do
288 // pull in the offset.
289 OperandHash = Op.getOffset();
294 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
299 /// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
300 /// with no successors, we hash two instructions, because cross-jumping
301 /// only saves code when at least two instructions are removed (since a
302 /// branch must be inserted). For blocks with a successor, one of the
303 /// two blocks to be tail-merged will end with a branch already, so
304 /// it gains to cross-jump even for one instruction.
306 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
307 unsigned minCommonTailLength) {
308 MachineBasicBlock::const_iterator I = MBB->end();
309 if (I == MBB->begin())
310 return 0; // Empty MBB.
313 unsigned Hash = HashMachineInstr(I);
315 if (I == MBB->begin() || minCommonTailLength == 1)
316 return Hash; // Single instr MBB.
319 // Hash in the second-to-last instruction.
320 Hash ^= HashMachineInstr(I) << 2;
324 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
325 /// of instructions they actually have in common together at their end. Return
326 /// iterators for the first shared instruction in each block.
327 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
328 MachineBasicBlock *MBB2,
329 MachineBasicBlock::iterator &I1,
330 MachineBasicBlock::iterator &I2) {
334 unsigned TailLen = 0;
335 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
337 if (!I1->isIdenticalTo(I2) ||
338 // FIXME: This check is dubious. It's used to get around a problem where
339 // people incorrectly expect inline asm directives to remain in the same
340 // relative order. This is untenable because normal compiler
341 // optimizations (like this one) may reorder and/or merge these
343 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
352 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
353 /// after it, replacing it with an unconditional branch to NewDest. This
354 /// returns true if OldInst's block is modified, false if NewDest is modified.
355 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
356 MachineBasicBlock *NewDest) {
357 MachineBasicBlock *OldBB = OldInst->getParent();
359 // Remove all the old successors of OldBB from the CFG.
360 while (!OldBB->succ_empty())
361 OldBB->removeSuccessor(OldBB->succ_begin());
363 // Remove all the dead instructions from the end of OldBB.
364 OldBB->erase(OldInst, OldBB->end());
366 // If OldBB isn't immediately before OldBB, insert a branch to it.
367 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
368 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
369 OldBB->addSuccessor(NewDest);
373 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
374 /// MBB so that the part before the iterator falls into the part starting at the
375 /// iterator. This returns the new MBB.
376 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
377 MachineBasicBlock::iterator BBI1) {
378 // Create the fall-through block.
379 MachineFunction::iterator MBBI = &CurMBB;
380 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
381 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
383 // Move all the successors of this block to the specified block.
384 while (!CurMBB.succ_empty()) {
385 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
386 NewMBB->addSuccessor(S);
387 CurMBB.removeSuccessor(S);
390 // Add an edge from CurMBB to NewMBB for the fall-through.
391 CurMBB.addSuccessor(NewMBB);
393 // Splice the code over.
394 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
396 // For targets that use the register scavenger, we must maintain LiveIns.
398 RS->enterBasicBlock(&CurMBB);
400 RS->forward(prior(CurMBB.end()));
401 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
402 RS->getRegsUsed(RegsLiveAtExit, false);
403 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
404 if (RegsLiveAtExit[i])
405 NewMBB->addLiveIn(i);
411 /// EstimateRuntime - Make a rough estimate for how long it will take to run
412 /// the specified code.
413 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
414 MachineBasicBlock::iterator E) {
416 for (; I != E; ++I) {
417 const TargetInstrDesc &TID = I->getDesc();
420 else if (TID.isSimpleLoad() || TID.mayStore())
428 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
429 // branches temporarily for tail merging). In the case where CurMBB ends
430 // with a conditional branch to the next block, optimize by reversing the
431 // test and conditionally branching to SuccMBB instead.
433 static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
434 const TargetInstrInfo *TII) {
435 MachineFunction *MF = CurMBB->getParent();
436 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
437 MachineBasicBlock *TBB = 0, *FBB = 0;
438 std::vector<MachineOperand> Cond;
439 if (I != MF->end() &&
440 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
441 MachineBasicBlock *NextBB = I;
442 if (TBB == NextBB && !Cond.empty() && !FBB) {
443 if (!TII->ReverseBranchCondition(Cond)) {
444 TII->RemoveBranch(*CurMBB);
445 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
450 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
453 static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
454 const std::pair<unsigned,MachineBasicBlock*> &q) {
455 if (p.first < q.first)
457 else if (p.first > q.first)
459 else if (p.second->getNumber() < q.second->getNumber())
461 else if (p.second->getNumber() > q.second->getNumber())
464 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
465 // an object with itself.
466 #ifndef _GLIBCXX_DEBUG
467 assert(0 && "Predecessor appears twice");
473 /// ComputeSameTails - Look through all the blocks in MergePotentials that have
474 /// hash CurHash (guaranteed to match the last element). Build the vector
475 /// SameTails of all those that have the (same) largest number of instructions
476 /// in common of any pair of these blocks. SameTails entries contain an
477 /// iterator into MergePotentials (from which the MachineBasicBlock can be
478 /// found) and a MachineBasicBlock::iterator into that MBB indicating the
479 /// instruction where the matching code sequence begins.
480 /// Order of elements in SameTails is the reverse of the order in which
481 /// those blocks appear in MergePotentials (where they are not necessarily
483 unsigned BranchFolder::ComputeSameTails(unsigned CurHash,
484 unsigned minCommonTailLength) {
485 unsigned maxCommonTailLength = 0U;
487 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
488 MPIterator HighestMPIter = prior(MergePotentials.end());
489 for (MPIterator CurMPIter = prior(MergePotentials.end()),
490 B = MergePotentials.begin();
491 CurMPIter!=B && CurMPIter->first==CurHash;
493 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
494 unsigned CommonTailLen = ComputeCommonTailLength(
497 TrialBBI1, TrialBBI2);
498 // If we will have to split a block, there should be at least
499 // minCommonTailLength instructions in common; if not, at worst
500 // we will be replacing a fallthrough into the common tail with a
501 // branch, which at worst breaks even with falling through into
502 // the duplicated common tail, so 1 instruction in common is enough.
503 // We will always pick a block we do not have to split as the common
504 // tail if there is one.
505 // (Empty blocks will get forwarded and need not be considered.)
506 if (CommonTailLen >= minCommonTailLength ||
507 (CommonTailLen > 0 &&
508 (TrialBBI1==CurMPIter->second->begin() ||
509 TrialBBI2==I->second->begin()))) {
510 if (CommonTailLen > maxCommonTailLength) {
512 maxCommonTailLength = CommonTailLen;
513 HighestMPIter = CurMPIter;
514 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
516 if (HighestMPIter == CurMPIter &&
517 CommonTailLen == maxCommonTailLength)
518 SameTails.push_back(std::make_pair(I, TrialBBI2));
524 return maxCommonTailLength;
527 /// RemoveBlocksWithHash - Remove all blocks with hash CurHash from
528 /// MergePotentials, restoring branches at ends of blocks as appropriate.
529 void BranchFolder::RemoveBlocksWithHash(unsigned CurHash,
530 MachineBasicBlock* SuccBB,
531 MachineBasicBlock* PredBB) {
532 MPIterator CurMPIter, B;
533 for (CurMPIter = prior(MergePotentials.end()), B = MergePotentials.begin();
534 CurMPIter->first==CurHash;
536 // Put the unconditional branch back, if we need one.
537 MachineBasicBlock *CurMBB = CurMPIter->second;
538 if (SuccBB && CurMBB != PredBB)
539 FixTail(CurMBB, SuccBB, TII);
543 if (CurMPIter->first!=CurHash)
545 MergePotentials.erase(CurMPIter, MergePotentials.end());
548 /// CreateCommonTailOnlyBlock - None of the blocks to be tail-merged consist
549 /// only of the common tail. Create a block that does by splitting one.
550 unsigned BranchFolder::CreateCommonTailOnlyBlock(MachineBasicBlock *&PredBB,
551 unsigned maxCommonTailLength) {
552 unsigned i, commonTailIndex;
553 unsigned TimeEstimate = ~0U;
554 for (i=0, commonTailIndex=0; i<SameTails.size(); i++) {
555 // Use PredBB if possible; that doesn't require a new branch.
556 if (SameTails[i].first->second==PredBB) {
560 // Otherwise, make a (fairly bogus) choice based on estimate of
561 // how long it will take the various blocks to execute.
562 unsigned t = EstimateRuntime(SameTails[i].first->second->begin(),
563 SameTails[i].second);
564 if (t<=TimeEstimate) {
570 MachineBasicBlock::iterator BBI = SameTails[commonTailIndex].second;
571 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
573 DOUT << "\nSplitting " << MBB->getNumber() << ", size " <<
576 MachineBasicBlock *newMBB = SplitMBBAt(*MBB, BBI);
577 SameTails[commonTailIndex].first->second = newMBB;
578 SameTails[commonTailIndex].second = newMBB->begin();
579 // If we split PredBB, newMBB is the new predecessor.
583 return commonTailIndex;
586 // See if any of the blocks in MergePotentials (which all have a common single
587 // successor, or all have no successor) can be tail-merged. If there is a
588 // successor, any blocks in MergePotentials that are not tail-merged and
589 // are not immediately before Succ must have an unconditional branch to
590 // Succ added (but the predecessor/successor lists need no adjustment).
591 // The lone predecessor of Succ that falls through into Succ,
592 // if any, is given in PredBB.
594 bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
595 MachineBasicBlock* PredBB) {
596 // It doesn't make sense to save a single instruction since tail merging
598 // FIXME: Ask the target to provide the threshold?
599 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
602 DOUT << "\nTryMergeBlocks " << MergePotentials.size();
604 // Sort by hash value so that blocks with identical end sequences sort
606 std::stable_sort(MergePotentials.begin(), MergePotentials.end(),MergeCompare);
608 // Walk through equivalence sets looking for actual exact matches.
609 while (MergePotentials.size() > 1) {
610 unsigned CurHash = prior(MergePotentials.end())->first;
612 // Build SameTails, identifying the set of blocks with this hash code
613 // and with the maximum number of instructions in common.
614 unsigned maxCommonTailLength = ComputeSameTails(CurHash,
615 minCommonTailLength);
617 // If we didn't find any pair that has at least minCommonTailLength
618 // instructions in common, remove all blocks with this hash code and retry.
619 if (SameTails.empty()) {
620 RemoveBlocksWithHash(CurHash, SuccBB, PredBB);
624 // If one of the blocks is the entire common tail (and not the entry
625 // block, which we can't jump to), we can treat all blocks with this same
626 // tail at once. Use PredBB if that is one of the possibilities, as that
627 // will not introduce any extra branches.
628 MachineBasicBlock *EntryBB = MergePotentials.begin()->second->
629 getParent()->begin();
630 unsigned int commonTailIndex, i;
631 for (commonTailIndex=SameTails.size(), i=0; i<SameTails.size(); i++) {
632 MachineBasicBlock *MBB = SameTails[i].first->second;
633 if (MBB->begin() == SameTails[i].second && MBB != EntryBB) {
640 if (commonTailIndex==SameTails.size()) {
641 // None of the blocks consist entirely of the common tail.
642 // Split a block so that one does.
643 commonTailIndex = CreateCommonTailOnlyBlock(PredBB, maxCommonTailLength);
646 MachineBasicBlock *MBB = SameTails[commonTailIndex].first->second;
647 // MBB is common tail. Adjust all other BB's to jump to this one.
648 // Traversal must be forwards so erases work.
649 DOUT << "\nUsing common tail " << MBB->getNumber() << " for ";
650 for (unsigned int i=0; i<SameTails.size(); ++i) {
651 if (commonTailIndex==i)
653 DOUT << SameTails[i].first->second->getNumber() << ",";
654 // Hack the end off BB i, making it jump to BB commonTailIndex instead.
655 ReplaceTailWithBranchTo(SameTails[i].second, MBB);
656 // BB i is no longer a predecessor of SuccBB; remove it from the worklist.
657 MergePotentials.erase(SameTails[i].first);
660 // We leave commonTailIndex in the worklist in case there are other blocks
661 // that match it with a smaller number of instructions.
667 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
669 if (!EnableTailMerge) return false;
673 // First find blocks with no successors.
674 MergePotentials.clear();
675 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
677 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
679 // See if we can do any tail merging on those.
680 if (MergePotentials.size() < TailMergeThreshold &&
681 MergePotentials.size() >= 2)
682 MadeChange |= TryMergeBlocks(NULL, NULL);
684 // Look at blocks (IBB) with multiple predecessors (PBB).
685 // We change each predecessor to a canonical form, by
686 // (1) temporarily removing any unconditional branch from the predecessor
688 // (2) alter conditional branches so they branch to the other block
689 // not IBB; this may require adding back an unconditional branch to IBB
690 // later, where there wasn't one coming in. E.g.
692 // fallthrough to QBB
695 // with a conceptual B to IBB after that, which never actually exists.
696 // With those changes, we see whether the predecessors' tails match,
697 // and merge them if so. We change things out of canonical form and
698 // back to the way they were later in the process. (OptimizeBranches
699 // would undo some of this, but we can't use it, because we'd get into
700 // a compile-time infinite loop repeatedly doing and undoing the same
703 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
704 if (!I->succ_empty() && I->pred_size() >= 2 &&
705 I->pred_size() < TailMergeThreshold) {
706 MachineBasicBlock *IBB = I;
707 MachineBasicBlock *PredBB = prior(I);
708 MergePotentials.clear();
709 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
712 MachineBasicBlock* PBB = *P;
713 // Skip blocks that loop to themselves, can't tail merge these.
716 MachineBasicBlock *TBB = 0, *FBB = 0;
717 std::vector<MachineOperand> Cond;
718 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
719 // Failing case: IBB is the target of a cbr, and
720 // we cannot reverse the branch.
721 std::vector<MachineOperand> NewCond(Cond);
722 if (!Cond.empty() && TBB==IBB) {
723 if (TII->ReverseBranchCondition(NewCond))
725 // This is the QBB case described above
727 FBB = next(MachineFunction::iterator(PBB));
729 // Failing case: the only way IBB can be reached from PBB is via
730 // exception handling. Happens for landing pads. Would be nice
731 // to have a bit in the edge so we didn't have to do all this.
732 if (IBB->isLandingPad()) {
733 MachineFunction::iterator IP = PBB; IP++;
734 MachineBasicBlock* PredNextBB = NULL;
738 if (IBB!=PredNextBB) // fallthrough
741 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
743 } else if (Cond.empty()) {
747 if (TBB!=IBB && IBB!=PredNextBB) // cbr
751 // Remove the unconditional branch at the end, if any.
752 if (TBB && (Cond.empty() || FBB)) {
753 TII->RemoveBranch(*PBB);
755 // reinsert conditional branch only, for now
756 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
758 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
761 if (MergePotentials.size() >= 2)
762 MadeChange |= TryMergeBlocks(I, PredBB);
763 // Reinsert an unconditional branch if needed.
764 // The 1 below can occur as a result of removing blocks in TryMergeBlocks.
765 PredBB = prior(I); // this may have been changed in TryMergeBlocks
766 if (MergePotentials.size()==1 &&
767 MergePotentials.begin()->second != PredBB)
768 FixTail(MergePotentials.begin()->second, I, TII);
774 //===----------------------------------------------------------------------===//
775 // Branch Optimization
776 //===----------------------------------------------------------------------===//
778 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
781 // Make sure blocks are numbered in order
784 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
785 MachineBasicBlock *MBB = I++;
788 // If it is dead, remove it.
789 if (MBB->pred_empty()) {
790 RemoveDeadBlock(MBB);
799 /// CanFallThrough - Return true if the specified block (with the specified
800 /// branch condition) can implicitly transfer control to the block after it by
801 /// falling off the end of it. This should return false if it can reach the
802 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
804 /// True is a conservative answer.
806 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
807 bool BranchUnAnalyzable,
808 MachineBasicBlock *TBB,
809 MachineBasicBlock *FBB,
810 const std::vector<MachineOperand> &Cond) {
811 MachineFunction::iterator Fallthrough = CurBB;
813 // If FallthroughBlock is off the end of the function, it can't fall through.
814 if (Fallthrough == CurBB->getParent()->end())
817 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
818 if (!CurBB->isSuccessor(Fallthrough))
821 // If we couldn't analyze the branch, assume it could fall through.
822 if (BranchUnAnalyzable) return true;
824 // If there is no branch, control always falls through.
825 if (TBB == 0) return true;
827 // If there is some explicit branch to the fallthrough block, it can obviously
828 // reach, even though the branch should get folded to fall through implicitly.
829 if (MachineFunction::iterator(TBB) == Fallthrough ||
830 MachineFunction::iterator(FBB) == Fallthrough)
833 // If it's an unconditional branch to some block not the fall through, it
834 // doesn't fall through.
835 if (Cond.empty()) return false;
837 // Otherwise, if it is conditional and has no explicit false block, it falls
842 /// CanFallThrough - Return true if the specified can implicitly transfer
843 /// control to the block after it by falling off the end of it. This should
844 /// return false if it can reach the block after it, but it uses an explicit
845 /// branch to do so (e.g. a table jump).
847 /// True is a conservative answer.
849 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
850 MachineBasicBlock *TBB = 0, *FBB = 0;
851 std::vector<MachineOperand> Cond;
852 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
853 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
856 /// IsBetterFallthrough - Return true if it would be clearly better to
857 /// fall-through to MBB1 than to fall through into MBB2. This has to return
858 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
859 /// result in infinite loops.
860 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
861 MachineBasicBlock *MBB2) {
862 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
863 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
864 // optimize branches that branch to either a return block or an assert block
865 // into a fallthrough to the return.
866 if (MBB1->empty() || MBB2->empty()) return false;
868 // If there is a clear successor ordering we make sure that one block
869 // will fall through to the next
870 if (MBB1->isSuccessor(MBB2)) return true;
871 if (MBB2->isSuccessor(MBB1)) return false;
873 MachineInstr *MBB1I = --MBB1->end();
874 MachineInstr *MBB2I = --MBB2->end();
875 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
878 /// OptimizeBlock - Analyze and optimize control flow related to the specified
879 /// block. This is never called on the entry block.
880 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
881 MachineFunction::iterator FallThrough = MBB;
884 // If this block is empty, make everyone use its fall-through, not the block
885 // explicitly. Landing pads should not do this since the landing-pad table
886 // points to this block.
887 if (MBB->empty() && !MBB->isLandingPad()) {
888 // Dead block? Leave for cleanup later.
889 if (MBB->pred_empty()) return;
891 if (FallThrough == MBB->getParent()->end()) {
892 // TODO: Simplify preds to not branch here if possible!
894 // Rewrite all predecessors of the old block to go to the fallthrough
896 while (!MBB->pred_empty()) {
897 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
898 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
901 // If MBB was the target of a jump table, update jump tables to go to the
902 // fallthrough instead.
903 MBB->getParent()->getJumpTableInfo()->
904 ReplaceMBBInJumpTables(MBB, FallThrough);
910 // Check to see if we can simplify the terminator of the block before this
912 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
914 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
915 std::vector<MachineOperand> PriorCond;
916 bool PriorUnAnalyzable =
917 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
918 if (!PriorUnAnalyzable) {
919 // If the CFG for the prior block has extra edges, remove them.
920 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
923 // If the previous branch is conditional and both conditions go to the same
924 // destination, remove the branch, replacing it with an unconditional one or
926 if (PriorTBB && PriorTBB == PriorFBB) {
927 TII->RemoveBranch(PrevBB);
930 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
933 return OptimizeBlock(MBB);
936 // If the previous branch *only* branches to *this* block (conditional or
937 // not) remove the branch.
938 if (PriorTBB == MBB && PriorFBB == 0) {
939 TII->RemoveBranch(PrevBB);
942 return OptimizeBlock(MBB);
945 // If the prior block branches somewhere else on the condition and here if
946 // the condition is false, remove the uncond second branch.
947 if (PriorFBB == MBB) {
948 TII->RemoveBranch(PrevBB);
949 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
952 return OptimizeBlock(MBB);
955 // If the prior block branches here on true and somewhere else on false, and
956 // if the branch condition is reversible, reverse the branch to create a
958 if (PriorTBB == MBB) {
959 std::vector<MachineOperand> NewPriorCond(PriorCond);
960 if (!TII->ReverseBranchCondition(NewPriorCond)) {
961 TII->RemoveBranch(PrevBB);
962 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
965 return OptimizeBlock(MBB);
969 // If this block doesn't fall through (e.g. it ends with an uncond branch or
970 // has no successors) and if the pred falls through into this block, and if
971 // it would otherwise fall through into the block after this, move this
972 // block to the end of the function.
974 // We consider it more likely that execution will stay in the function (e.g.
975 // due to loops) than it is to exit it. This asserts in loops etc, moving
976 // the assert condition out of the loop body.
977 if (!PriorCond.empty() && PriorFBB == 0 &&
978 MachineFunction::iterator(PriorTBB) == FallThrough &&
979 !CanFallThrough(MBB)) {
980 bool DoTransform = true;
982 // We have to be careful that the succs of PredBB aren't both no-successor
983 // blocks. If neither have successors and if PredBB is the second from
984 // last block in the function, we'd just keep swapping the two blocks for
985 // last. Only do the swap if one is clearly better to fall through than
987 if (FallThrough == --MBB->getParent()->end() &&
988 !IsBetterFallthrough(PriorTBB, MBB))
991 // We don't want to do this transformation if we have control flow like:
1000 // In this case, we could actually be moving the return block *into* a
1002 if (DoTransform && !MBB->succ_empty() &&
1003 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
1004 DoTransform = false;
1008 // Reverse the branch so we will fall through on the previous true cond.
1009 std::vector<MachineOperand> NewPriorCond(PriorCond);
1010 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1011 DOUT << "\nMoving MBB: " << *MBB;
1012 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
1014 TII->RemoveBranch(PrevBB);
1015 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
1017 // Move this block to the end of the function.
1018 MBB->moveAfter(--MBB->getParent()->end());
1027 // Analyze the branch in the current block.
1028 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
1029 std::vector<MachineOperand> CurCond;
1030 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
1031 if (!CurUnAnalyzable) {
1032 // If the CFG for the prior block has extra edges, remove them.
1033 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1035 // If this is a two-way branch, and the FBB branches to this block, reverse
1036 // the condition so the single-basic-block loop is faster. Instead of:
1037 // Loop: xxx; jcc Out; jmp Loop
1039 // Loop: xxx; jncc Loop; jmp Out
1040 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1041 std::vector<MachineOperand> NewCond(CurCond);
1042 if (!TII->ReverseBranchCondition(NewCond)) {
1043 TII->RemoveBranch(*MBB);
1044 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1047 return OptimizeBlock(MBB);
1052 // If this branch is the only thing in its block, see if we can forward
1053 // other blocks across it.
1054 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
1055 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
1056 // This block may contain just an unconditional branch. Because there can
1057 // be 'non-branch terminators' in the block, try removing the branch and
1058 // then seeing if the block is empty.
1059 TII->RemoveBranch(*MBB);
1061 // If this block is just an unconditional branch to CurTBB, we can
1062 // usually completely eliminate the block. The only case we cannot
1063 // completely eliminate the block is when the block before this one
1064 // falls through into MBB and we can't understand the prior block's branch
1067 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1068 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1069 !PrevBB.isSuccessor(MBB)) {
1070 // If the prior block falls through into us, turn it into an
1071 // explicit branch to us to make updates simpler.
1072 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1073 PriorTBB != MBB && PriorFBB != MBB) {
1074 if (PriorTBB == 0) {
1075 assert(PriorCond.empty() && PriorFBB == 0 &&
1076 "Bad branch analysis");
1079 assert(PriorFBB == 0 && "Machine CFG out of date!");
1082 TII->RemoveBranch(PrevBB);
1083 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1086 // Iterate through all the predecessors, revectoring each in-turn.
1088 bool DidChange = false;
1089 bool HasBranchToSelf = false;
1090 while(PI != MBB->pred_size()) {
1091 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1093 // If this block has an uncond branch to itself, leave it.
1095 HasBranchToSelf = true;
1098 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1102 // Change any jumptables to go to the new MBB.
1103 MBB->getParent()->getJumpTableInfo()->
1104 ReplaceMBBInJumpTables(MBB, CurTBB);
1108 if (!HasBranchToSelf) return;
1113 // Add the branch back if the block is more than just an uncond branch.
1114 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1118 // If the prior block doesn't fall through into this block, and if this
1119 // block doesn't fall through into some other block, see if we can find a
1120 // place to move this block where a fall-through will happen.
1121 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1122 PriorTBB, PriorFBB, PriorCond)) {
1123 // Now we know that there was no fall-through into this block, check to
1124 // see if it has a fall-through into its successor.
1125 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1128 if (!MBB->isLandingPad()) {
1129 // Check all the predecessors of this block. If one of them has no fall
1130 // throughs, move this block right after it.
1131 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1132 E = MBB->pred_end(); PI != E; ++PI) {
1133 // Analyze the branch at the end of the pred.
1134 MachineBasicBlock *PredBB = *PI;
1135 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1136 if (PredBB != MBB && !CanFallThrough(PredBB)
1137 && (!CurFallsThru || !CurTBB || !CurFBB)
1138 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1139 // If the current block doesn't fall through, just move it.
1140 // If the current block can fall through and does not end with a
1141 // conditional branch, we need to append an unconditional jump to
1142 // the (current) next block. To avoid a possible compile-time
1143 // infinite loop, move blocks only backward in this case.
1144 // Also, if there are already 2 branches here, we cannot add a third;
1145 // this means we have the case
1150 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1152 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1154 MBB->moveAfter(PredBB);
1156 return OptimizeBlock(MBB);
1161 if (!CurFallsThru) {
1162 // Check all successors to see if we can move this block before it.
1163 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1164 E = MBB->succ_end(); SI != E; ++SI) {
1165 // Analyze the branch at the end of the block before the succ.
1166 MachineBasicBlock *SuccBB = *SI;
1167 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1168 std::vector<MachineOperand> SuccPrevCond;
1170 // If this block doesn't already fall-through to that successor, and if
1171 // the succ doesn't already have a block that can fall through into it,
1172 // and if the successor isn't an EH destination, we can arrange for the
1173 // fallthrough to happen.
1174 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1175 !SuccBB->isLandingPad()) {
1176 MBB->moveBefore(SuccBB);
1178 return OptimizeBlock(MBB);
1182 // Okay, there is no really great place to put this block. If, however,
1183 // the block before this one would be a fall-through if this block were
1184 // removed, move this block to the end of the function.
1185 if (FallThrough != MBB->getParent()->end() &&
1186 PrevBB.isSuccessor(FallThrough)) {
1187 MBB->moveAfter(--MBB->getParent()->end());