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);
42 // Throttle for huge numbers of predecessors (compile speed problems)
43 static cl::opt<unsigned>
44 TailMergeThreshold("tail-merge-threshold",
45 cl::desc("Max number of predecessors to consider tail merging"),
46 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);
75 typedef std::pair<unsigned,MachineBasicBlock*> MergePotentialsElt;
76 std::vector<MergePotentialsElt> MergePotentials;
77 typedef std::vector<MergePotentialsElt>::iterator MPIterator;
79 const TargetRegisterInfo *RegInfo;
82 bool OptimizeBranches(MachineFunction &MF);
83 void OptimizeBlock(MachineBasicBlock *MBB);
84 void RemoveDeadBlock(MachineBasicBlock *MBB);
85 bool OptimizeImpDefsBlock(MachineBasicBlock *MBB);
87 bool CanFallThrough(MachineBasicBlock *CurBB);
88 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
89 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
90 const std::vector<MachineOperand> &Cond);
92 char BranchFolder::ID = 0;
95 FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
96 return new BranchFolder(DefaultEnableTailMerge); }
98 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
99 /// function, updating the CFG.
100 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
101 assert(MBB->pred_empty() && "MBB must be dead!");
102 DOUT << "\nRemoving MBB: " << *MBB;
104 MachineFunction *MF = MBB->getParent();
105 // drop all successors.
106 while (!MBB->succ_empty())
107 MBB->removeSuccessor(MBB->succ_end()-1);
109 // If there is DWARF info to active, check to see if there are any LABEL
110 // records in the basic block. If so, unregister them from MachineModuleInfo.
111 if (MMI && !MBB->empty()) {
112 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
114 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
115 // The label ID # is always operand #0, an immediate.
116 MMI->InvalidateLabel(I->getOperand(0).getImm());
122 MF->getBasicBlockList().erase(MBB);
125 /// OptimizeImpDefsBlock - If a basic block is just a bunch of implicit_def
126 /// followed by terminators, and if the implicitly defined registers are not
127 /// used by the terminators, remove those implicit_def's. e.g.
129 /// r0 = implicit_def
130 /// r1 = implicit_def
132 /// This block can be optimized away later if the implicit instructions are
134 bool BranchFolder::OptimizeImpDefsBlock(MachineBasicBlock *MBB) {
135 SmallSet<unsigned, 4> ImpDefRegs;
136 MachineBasicBlock::iterator I = MBB->begin();
137 while (I != MBB->end()) {
138 if (I->getOpcode() != TargetInstrInfo::IMPLICIT_DEF)
140 unsigned Reg = I->getOperand(0).getReg();
141 ImpDefRegs.insert(Reg);
142 for (const unsigned *SubRegs = RegInfo->getSubRegisters(Reg);
143 unsigned SubReg = *SubRegs; ++SubRegs)
144 ImpDefRegs.insert(SubReg);
147 if (ImpDefRegs.empty())
150 MachineBasicBlock::iterator FirstTerm = I;
151 while (I != MBB->end()) {
152 if (!TII->isUnpredicatedTerminator(I))
154 // See if it uses any of the implicitly defined registers.
155 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
156 MachineOperand &MO = I->getOperand(i);
157 if (!MO.isReg() || !MO.isUse())
159 unsigned Reg = MO.getReg();
160 if (ImpDefRegs.count(Reg))
167 while (I != FirstTerm) {
168 MachineInstr *ImpDefMI = &*I;
170 MBB->erase(ImpDefMI);
176 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
177 TII = MF.getTarget().getInstrInfo();
178 if (!TII) return false;
180 RegInfo = MF.getTarget().getRegisterInfo();
182 // Fix CFG. The later algorithms expect it to be right.
183 bool EverMadeChange = false;
184 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
185 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
186 std::vector<MachineOperand> Cond;
187 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
188 EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
189 EverMadeChange |= OptimizeImpDefsBlock(MBB);
192 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
194 MMI = getAnalysisToUpdate<MachineModuleInfo>();
196 bool MadeChangeThisIteration = true;
197 while (MadeChangeThisIteration) {
198 MadeChangeThisIteration = false;
199 MadeChangeThisIteration |= TailMergeBlocks(MF);
200 MadeChangeThisIteration |= OptimizeBranches(MF);
201 EverMadeChange |= MadeChangeThisIteration;
204 // See if any jump tables have become mergable or dead as the code generator
206 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
207 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
209 // Figure out how these jump tables should be merged.
210 std::vector<unsigned> JTMapping;
211 JTMapping.reserve(JTs.size());
213 // We always keep the 0th jump table.
214 JTMapping.push_back(0);
216 // Scan the jump tables, seeing if there are any duplicates. Note that this
217 // is N^2, which should be fixed someday.
218 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
219 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
221 // If a jump table was merge with another one, walk the function rewriting
222 // references to jump tables to reference the new JT ID's. Keep track of
223 // whether we see a jump table idx, if not, we can delete the JT.
224 std::vector<bool> JTIsLive;
225 JTIsLive.resize(JTs.size());
226 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
228 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
230 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
231 MachineOperand &Op = I->getOperand(op);
232 if (!Op.isJumpTableIndex()) continue;
233 unsigned NewIdx = JTMapping[Op.getIndex()];
236 // Remember that this JT is live.
237 JTIsLive[NewIdx] = true;
241 // Finally, remove dead jump tables. This happens either because the
242 // indirect jump was unreachable (and thus deleted) or because the jump
243 // table was merged with some other one.
244 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
246 JTI->RemoveJumpTable(i);
247 EverMadeChange = true;
252 return EverMadeChange;
255 //===----------------------------------------------------------------------===//
256 // Tail Merging of Blocks
257 //===----------------------------------------------------------------------===//
259 /// HashMachineInstr - Compute a hash value for MI and its operands.
260 static unsigned HashMachineInstr(const MachineInstr *MI) {
261 unsigned Hash = MI->getOpcode();
262 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
263 const MachineOperand &Op = MI->getOperand(i);
265 // Merge in bits from the operand if easy.
266 unsigned OperandHash = 0;
267 switch (Op.getType()) {
268 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
269 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
270 case MachineOperand::MO_MachineBasicBlock:
271 OperandHash = Op.getMBB()->getNumber();
273 case MachineOperand::MO_FrameIndex:
274 case MachineOperand::MO_ConstantPoolIndex:
275 case MachineOperand::MO_JumpTableIndex:
276 OperandHash = Op.getIndex();
278 case MachineOperand::MO_GlobalAddress:
279 case MachineOperand::MO_ExternalSymbol:
280 // Global address / external symbol are too hard, don't bother, but do
281 // pull in the offset.
282 OperandHash = Op.getOffset();
287 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
292 /// HashEndOfMBB - Hash the last few instructions in the MBB. For blocks
293 /// with no successors, we hash two instructions, because cross-jumping
294 /// only saves code when at least two instructions are removed (since a
295 /// branch must be inserted). For blocks with a successor, one of the
296 /// two blocks to be tail-merged will end with a branch already, so
297 /// it gains to cross-jump even for one instruction.
299 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
300 unsigned minCommonTailLength) {
301 MachineBasicBlock::const_iterator I = MBB->end();
302 if (I == MBB->begin())
303 return 0; // Empty MBB.
306 unsigned Hash = HashMachineInstr(I);
308 if (I == MBB->begin() || minCommonTailLength == 1)
309 return Hash; // Single instr MBB.
312 // Hash in the second-to-last instruction.
313 Hash ^= HashMachineInstr(I) << 2;
317 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
318 /// of instructions they actually have in common together at their end. Return
319 /// iterators for the first shared instruction in each block.
320 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
321 MachineBasicBlock *MBB2,
322 MachineBasicBlock::iterator &I1,
323 MachineBasicBlock::iterator &I2) {
327 unsigned TailLen = 0;
328 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
330 if (!I1->isIdenticalTo(I2) ||
331 // FIXME: This check is dubious. It's used to get around a problem where
332 // people incorrectly expect inline asm directives to remain in the same
333 // relative order. This is untenable because normal compiler
334 // optimizations (like this one) may reorder and/or merge these
336 I1->getOpcode() == TargetInstrInfo::INLINEASM) {
345 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
346 /// after it, replacing it with an unconditional branch to NewDest. This
347 /// returns true if OldInst's block is modified, false if NewDest is modified.
348 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
349 MachineBasicBlock *NewDest) {
350 MachineBasicBlock *OldBB = OldInst->getParent();
352 // Remove all the old successors of OldBB from the CFG.
353 while (!OldBB->succ_empty())
354 OldBB->removeSuccessor(OldBB->succ_begin());
356 // Remove all the dead instructions from the end of OldBB.
357 OldBB->erase(OldInst, OldBB->end());
359 // If OldBB isn't immediately before OldBB, insert a branch to it.
360 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
361 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
362 OldBB->addSuccessor(NewDest);
366 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
367 /// MBB so that the part before the iterator falls into the part starting at the
368 /// iterator. This returns the new MBB.
369 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
370 MachineBasicBlock::iterator BBI1) {
371 // Create the fall-through block.
372 MachineFunction::iterator MBBI = &CurMBB;
373 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
374 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
376 // Move all the successors of this block to the specified block.
377 while (!CurMBB.succ_empty()) {
378 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
379 NewMBB->addSuccessor(S);
380 CurMBB.removeSuccessor(S);
383 // Add an edge from CurMBB to NewMBB for the fall-through.
384 CurMBB.addSuccessor(NewMBB);
386 // Splice the code over.
387 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
389 // For targets that use the register scavenger, we must maintain LiveIns.
391 RS->enterBasicBlock(&CurMBB);
393 RS->forward(prior(CurMBB.end()));
394 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
395 RS->getRegsUsed(RegsLiveAtExit, false);
396 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
397 if (RegsLiveAtExit[i])
398 NewMBB->addLiveIn(i);
404 /// EstimateRuntime - Make a rough estimate for how long it will take to run
405 /// the specified code.
406 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
407 MachineBasicBlock::iterator E) {
409 for (; I != E; ++I) {
410 const TargetInstrDesc &TID = I->getDesc();
413 else if (TID.isSimpleLoad() || TID.mayStore())
421 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
422 /// MBB2I and then insert an unconditional branch in the other block. Determine
423 /// which is the best to split
424 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
425 MachineBasicBlock::iterator MBB1I,
426 MachineBasicBlock *MBB2,
427 MachineBasicBlock::iterator MBB2I,
428 MachineBasicBlock *PredBB) {
429 // If one block is the entry block, split the other one; we can't generate
430 // a branch to the entry block, as its label is not emitted.
431 MachineBasicBlock *Entry = MBB1->getParent()->begin();
437 // If one block falls through into the common successor, choose that
438 // one to split; it is one instruction less to do that.
442 else if (MBB2 == PredBB)
445 // TODO: if we had some notion of which block was hotter, we could split
446 // the hot block, so it is the fall-through. Since we don't have profile info
447 // make a decision based on which will hurt most to split.
448 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I);
449 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I);
451 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
452 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
453 // have a lower overall impact on the program execution.
454 return MBB1Time < MBB2Time;
457 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
458 // branches temporarily for tail merging). In the case where CurMBB ends
459 // with a conditional branch to the next block, optimize by reversing the
460 // test and conditionally branching to SuccMBB instead.
462 static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
463 const TargetInstrInfo *TII) {
464 MachineFunction *MF = CurMBB->getParent();
465 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
466 MachineBasicBlock *TBB = 0, *FBB = 0;
467 std::vector<MachineOperand> Cond;
468 if (I != MF->end() &&
469 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
470 MachineBasicBlock *NextBB = I;
471 if (TBB == NextBB && Cond.size() && !FBB) {
472 if (!TII->ReverseBranchCondition(Cond)) {
473 TII->RemoveBranch(*CurMBB);
474 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
479 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
482 static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
483 const std::pair<unsigned,MachineBasicBlock*> &q) {
484 if (p.first < q.first)
486 else if (p.first > q.first)
488 else if (p.second->getNumber() < q.second->getNumber())
490 else if (p.second->getNumber() > q.second->getNumber())
493 // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
494 // an object with itself.
495 #ifndef _GLIBCXX_DEBUG
496 assert(0 && "Predecessor appears twice");
502 // See if any of the blocks in MergePotentials (which all have a common single
503 // successor, or all have no successor) can be tail-merged. If there is a
504 // successor, any blocks in MergePotentials that are not tail-merged and
505 // are not immediately before Succ must have an unconditional branch to
506 // Succ added (but the predecessor/successor lists need no adjustment).
507 // The lone predecessor of Succ that falls through into Succ,
508 // if any, is given in PredBB.
510 bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
511 MachineBasicBlock* PredBB) {
512 // We cannot jump to the entry block, which affects various choices below.
513 MachineBasicBlock *Entry = MergePotentials.begin()->second->
514 getParent()->begin();
516 // It doesn't make sense to save a single instruction since tail merging
518 // FIXME: Ask the target to provide the threshold?
519 unsigned minCommonTailLength = (SuccBB ? 1 : 2) + 1;
522 DOUT << "\nTryMergeBlocks " << MergePotentials.size();
523 // Sort by hash value so that blocks with identical end sequences sort
525 std::stable_sort(MergePotentials.begin(), MergePotentials.end(), MergeCompare);
527 // Walk through equivalence sets looking for actual exact matches.
528 while (MergePotentials.size() > 1) {
529 unsigned CurHash = prior(MergePotentials.end())->first;
531 // Look through all the other blocks that have the same hash as this
532 // one, and build a vector of all those that have the (same) largest number
533 // of instructions in common.
534 // Order of elements in SameTails is the reverse of the order in which
535 // those blocks appear in MergePotentials (where they are not necessarily
537 typedef std::pair<MPIterator, MachineBasicBlock::iterator> SameTailElt;
538 std::vector<SameTailElt> SameTails;
540 unsigned maxCommonTailLength = 0U;
542 MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
543 MPIterator HighestMPIter = prior(MergePotentials.end());
544 for (MPIterator CurMPIter = prior(MergePotentials.end()),
545 B = MergePotentials.begin();
546 CurMPIter!=B && CurMPIter->first==CurHash;
548 for (MPIterator I = prior(CurMPIter); I->first==CurHash ; --I) {
549 unsigned CommonTailLen = ComputeCommonTailLength(
552 TrialBBI1, TrialBBI2);
553 if (CommonTailLen >= minCommonTailLength) {
554 if (CommonTailLen > maxCommonTailLength) {
556 maxCommonTailLength = CommonTailLen;
557 HighestMPIter = CurMPIter;
558 SameTails.push_back(std::make_pair(CurMPIter, TrialBBI1));
560 if (HighestMPIter == CurMPIter &&
561 CommonTailLen == maxCommonTailLength)
562 SameTails.push_back(std::make_pair(I, TrialBBI2));
569 // If we didn't find any pair that has at least minCommonTailLength
570 // instructions in common, remove all blocks with this hash code and retry.
571 if (SameTails.empty()) {
572 for (MPIterator CurMPIter = prior(MergePotentials.end()),
573 B = MergePotentials.begin();
574 CurMPIter->first==CurHash;
576 // Put the unconditional branch back, if we need one.
577 MachineBasicBlock *CurMBB = CurMPIter->second;
578 if (SuccBB && CurMBB != PredBB)
579 FixTail(CurMBB, SuccBB, TII);
580 MergePotentials.erase(CurMPIter);
587 // If one of the blocks is the entire common tail (and not the entry
588 // block, which we can't jump to), treat all blocks with this same
591 for (i=0; i<SameTails.size(); i++) {
592 MachineBasicBlock *MBB = SameTails[i].first->second;
593 if (MBB->begin() == SameTails[i].second && MBB != Entry)
596 if (i!=SameTails.size()) {
597 MachineBasicBlock *MBB = SameTails[i].first->second;
598 // MBB is common tail. Adjust all other BB's to jump to this one.
599 // Traversal must be forwards so erases work.
600 DOUT << "\nUsing common tail " << MBB->getNumber() << " for ";
601 for (unsigned int j=0; j<SameTails.size(); ++j) {
604 DOUT << SameTails[j].first->second->getNumber() << ",";
605 // Hack the end off BB j, making it jump to BB i instead.
606 ReplaceTailWithBranchTo(SameTails[j].second, MBB);
607 // This modifies BB j, so remove it from the worklist.
608 MergePotentials.erase(SameTails[j].first);
611 // We leave i in the worklist in case there are other blocks that
612 // match it with a smaller number of instructions.
617 // Otherwise, merge the 2 blocks in SameTails that are latest in
618 // MergePotentials; these are at indices 0 and 1 in SameTails.
619 MachineBasicBlock::iterator BBI1 = (SameTails[0]).second;
620 MachineBasicBlock::iterator BBI2 = (SameTails[1]).second;
621 MachineBasicBlock *MBB1 = (SameTails[0]).first->second;
622 MachineBasicBlock *MBB2 = (SameTails[1]).first->second;
624 DOUT << "\nMerging " << MBB1->getNumber() << "," <<
625 MBB2->getNumber() << ", size " << maxCommonTailLength;
627 // Neither block is the entire common tail; split the tail of one block
628 // to make it redundant with the other tail. We cannot jump to the
629 // entry block, so if one block is the entry block, split the other one.
631 // The second half of the split block will remain in SameTails, and will
632 // consist entirely of common code. Thus in the case where there are multiple
633 // blocks that would all need to be split, the next iteration of the
634 // outer loop will handle all the rest of them.
636 // Decide whether we want to split MBB1 or MBB2.
637 if (ShouldSplitFirstBlock(MBB1, BBI1, MBB2, BBI2, PredBB)) {
638 MBB1 = SplitMBBAt(*MBB1, BBI1);
639 BBI1 = MBB1->begin();
640 SameTails[0].first->second = MBB1;
642 MBB2 = SplitMBBAt(*MBB2, BBI2);
643 BBI2 = MBB2->begin();
644 SameTails[1].first->second = MBB2;
647 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
648 // Hack the end off MBB1, making it jump to MBB2 instead.
649 ReplaceTailWithBranchTo(BBI1, MBB2);
650 // This modifies MBB1, so remove it from the worklist.
651 MergePotentials.erase(SameTails[0].first);
653 assert(MBB1->begin() == BBI1 && MBB1 != Entry &&
654 "Didn't split block correctly?");
655 // Hack the end off MBB2, making it jump to MBB1 instead.
656 ReplaceTailWithBranchTo(BBI2, MBB1);
657 // This modifies MBB2, so remove it from the worklist.
658 MergePotentials.erase(SameTails[1].first);
665 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
667 if (!EnableTailMerge) return false;
671 // First find blocks with no successors.
672 MergePotentials.clear();
673 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
675 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
677 // See if we can do any tail merging on those.
678 if (MergePotentials.size() < TailMergeThreshold &&
679 MergePotentials.size() >= 2)
680 MadeChange |= TryMergeBlocks(NULL, NULL);
682 // Look at blocks (IBB) with multiple predecessors (PBB).
683 // We change each predecessor to a canonical form, by
684 // (1) temporarily removing any unconditional branch from the predecessor
686 // (2) alter conditional branches so they branch to the other block
687 // not IBB; this may require adding back an unconditional branch to IBB
688 // later, where there wasn't one coming in. E.g.
690 // fallthrough to QBB
693 // with a conceptual B to IBB after that, which never actually exists.
694 // With those changes, we see whether the predecessors' tails match,
695 // and merge them if so. We change things out of canonical form and
696 // back to the way they were later in the process. (OptimizeBranches
697 // would undo some of this, but we can't use it, because we'd get into
698 // a compile-time infinite loop repeatedly doing and undoing the same
701 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
702 if (!I->succ_empty() && I->pred_size() >= 2 &&
703 I->pred_size() < TailMergeThreshold) {
704 MachineBasicBlock *IBB = I;
705 MachineBasicBlock *PredBB = prior(I);
706 MergePotentials.clear();
707 for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
710 MachineBasicBlock* PBB = *P;
711 // Skip blocks that loop to themselves, can't tail merge these.
714 MachineBasicBlock *TBB = 0, *FBB = 0;
715 std::vector<MachineOperand> Cond;
716 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
717 // Failing case: IBB is the target of a cbr, and
718 // we cannot reverse the branch.
719 std::vector<MachineOperand> NewCond(Cond);
720 if (Cond.size() && TBB==IBB) {
721 if (TII->ReverseBranchCondition(NewCond))
723 // This is the QBB case described above
725 FBB = next(MachineFunction::iterator(PBB));
727 // Failing case: the only way IBB can be reached from PBB is via
728 // exception handling. Happens for landing pads. Would be nice
729 // to have a bit in the edge so we didn't have to do all this.
730 if (IBB->isLandingPad()) {
731 MachineFunction::iterator IP = PBB; IP++;
732 MachineBasicBlock* PredNextBB = NULL;
736 if (IBB!=PredNextBB) // fallthrough
739 if (TBB!=IBB && FBB!=IBB) // cbr then ubr
741 } else if (Cond.empty()) {
745 if (TBB!=IBB && IBB!=PredNextBB) // cbr
749 // Remove the unconditional branch at the end, if any.
750 if (TBB && (Cond.size()==0 || FBB)) {
751 TII->RemoveBranch(*PBB);
753 // reinsert conditional branch only, for now
754 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
756 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
759 if (MergePotentials.size() >= 2)
760 MadeChange |= TryMergeBlocks(I, PredBB);
761 // Reinsert an unconditional branch if needed.
762 // The 1 below can be either an original single predecessor, or a result
763 // of removing blocks in TryMergeBlocks.
764 PredBB = prior(I); // this may have been changed in TryMergeBlocks
765 if (MergePotentials.size()==1 &&
766 (MergePotentials.begin())->second != PredBB)
767 FixTail((MergePotentials.begin())->second, I, TII);
773 //===----------------------------------------------------------------------===//
774 // Branch Optimization
775 //===----------------------------------------------------------------------===//
777 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
780 // Make sure blocks are numbered in order
783 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
784 MachineBasicBlock *MBB = I++;
787 // If it is dead, remove it.
788 if (MBB->pred_empty()) {
789 RemoveDeadBlock(MBB);
798 /// CanFallThrough - Return true if the specified block (with the specified
799 /// branch condition) can implicitly transfer control to the block after it by
800 /// falling off the end of it. This should return false if it can reach the
801 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
803 /// True is a conservative answer.
805 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
806 bool BranchUnAnalyzable,
807 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
808 const std::vector<MachineOperand> &Cond) {
809 MachineFunction::iterator Fallthrough = CurBB;
811 // If FallthroughBlock is off the end of the function, it can't fall through.
812 if (Fallthrough == CurBB->getParent()->end())
815 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
816 if (!CurBB->isSuccessor(Fallthrough))
819 // If we couldn't analyze the branch, assume it could fall through.
820 if (BranchUnAnalyzable) return true;
822 // If there is no branch, control always falls through.
823 if (TBB == 0) return true;
825 // If there is some explicit branch to the fallthrough block, it can obviously
826 // reach, even though the branch should get folded to fall through implicitly.
827 if (MachineFunction::iterator(TBB) == Fallthrough ||
828 MachineFunction::iterator(FBB) == Fallthrough)
831 // If it's an unconditional branch to some block not the fall through, it
832 // doesn't fall through.
833 if (Cond.empty()) return false;
835 // Otherwise, if it is conditional and has no explicit false block, it falls
840 /// CanFallThrough - Return true if the specified can implicitly transfer
841 /// control to the block after it by falling off the end of it. This should
842 /// return false if it can reach the block after it, but it uses an explicit
843 /// branch to do so (e.g. a table jump).
845 /// True is a conservative answer.
847 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
848 MachineBasicBlock *TBB = 0, *FBB = 0;
849 std::vector<MachineOperand> Cond;
850 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
851 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
854 /// IsBetterFallthrough - Return true if it would be clearly better to
855 /// fall-through to MBB1 than to fall through into MBB2. This has to return
856 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
857 /// result in infinite loops.
858 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
859 MachineBasicBlock *MBB2) {
860 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
861 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
862 // optimize branches that branch to either a return block or an assert block
863 // into a fallthrough to the return.
864 if (MBB1->empty() || MBB2->empty()) return false;
866 // If there is a clear successor ordering we make sure that one block
867 // will fall through to the next
868 if (MBB1->isSuccessor(MBB2)) return true;
869 if (MBB2->isSuccessor(MBB1)) return false;
871 MachineInstr *MBB1I = --MBB1->end();
872 MachineInstr *MBB2I = --MBB2->end();
873 return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
876 /// OptimizeBlock - Analyze and optimize control flow related to the specified
877 /// block. This is never called on the entry block.
878 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
879 MachineFunction::iterator FallThrough = MBB;
882 // If this block is empty, make everyone use its fall-through, not the block
883 // explicitly. Landing pads should not do this since the landing-pad table
884 // points to this block.
885 if (MBB->empty() && !MBB->isLandingPad()) {
886 // Dead block? Leave for cleanup later.
887 if (MBB->pred_empty()) return;
889 if (FallThrough == MBB->getParent()->end()) {
890 // TODO: Simplify preds to not branch here if possible!
892 // Rewrite all predecessors of the old block to go to the fallthrough
894 while (!MBB->pred_empty()) {
895 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
896 Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
899 // If MBB was the target of a jump table, update jump tables to go to the
900 // fallthrough instead.
901 MBB->getParent()->getJumpTableInfo()->
902 ReplaceMBBInJumpTables(MBB, FallThrough);
908 // Check to see if we can simplify the terminator of the block before this
910 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
912 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
913 std::vector<MachineOperand> PriorCond;
914 bool PriorUnAnalyzable =
915 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
916 if (!PriorUnAnalyzable) {
917 // If the CFG for the prior block has extra edges, remove them.
918 MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
921 // If the previous branch is conditional and both conditions go to the same
922 // destination, remove the branch, replacing it with an unconditional one or
924 if (PriorTBB && PriorTBB == PriorFBB) {
925 TII->RemoveBranch(PrevBB);
928 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
931 return OptimizeBlock(MBB);
934 // If the previous branch *only* branches to *this* block (conditional or
935 // not) remove the branch.
936 if (PriorTBB == MBB && PriorFBB == 0) {
937 TII->RemoveBranch(PrevBB);
940 return OptimizeBlock(MBB);
943 // If the prior block branches somewhere else on the condition and here if
944 // the condition is false, remove the uncond second branch.
945 if (PriorFBB == MBB) {
946 TII->RemoveBranch(PrevBB);
947 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
950 return OptimizeBlock(MBB);
953 // If the prior block branches here on true and somewhere else on false, and
954 // if the branch condition is reversible, reverse the branch to create a
956 if (PriorTBB == MBB) {
957 std::vector<MachineOperand> NewPriorCond(PriorCond);
958 if (!TII->ReverseBranchCondition(NewPriorCond)) {
959 TII->RemoveBranch(PrevBB);
960 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
963 return OptimizeBlock(MBB);
967 // If this block doesn't fall through (e.g. it ends with an uncond branch or
968 // has no successors) and if the pred falls through into this block, and if
969 // it would otherwise fall through into the block after this, move this
970 // block to the end of the function.
972 // We consider it more likely that execution will stay in the function (e.g.
973 // due to loops) than it is to exit it. This asserts in loops etc, moving
974 // the assert condition out of the loop body.
975 if (!PriorCond.empty() && PriorFBB == 0 &&
976 MachineFunction::iterator(PriorTBB) == FallThrough &&
977 !CanFallThrough(MBB)) {
978 bool DoTransform = true;
980 // We have to be careful that the succs of PredBB aren't both no-successor
981 // blocks. If neither have successors and if PredBB is the second from
982 // last block in the function, we'd just keep swapping the two blocks for
983 // last. Only do the swap if one is clearly better to fall through than
985 if (FallThrough == --MBB->getParent()->end() &&
986 !IsBetterFallthrough(PriorTBB, MBB))
989 // We don't want to do this transformation if we have control flow like:
998 // In this case, we could actually be moving the return block *into* a
1000 if (DoTransform && !MBB->succ_empty() &&
1001 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
1002 DoTransform = false;
1006 // Reverse the branch so we will fall through on the previous true cond.
1007 std::vector<MachineOperand> NewPriorCond(PriorCond);
1008 if (!TII->ReverseBranchCondition(NewPriorCond)) {
1009 DOUT << "\nMoving MBB: " << *MBB;
1010 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
1012 TII->RemoveBranch(PrevBB);
1013 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
1015 // Move this block to the end of the function.
1016 MBB->moveAfter(--MBB->getParent()->end());
1025 // Analyze the branch in the current block.
1026 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
1027 std::vector<MachineOperand> CurCond;
1028 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
1029 if (!CurUnAnalyzable) {
1030 // If the CFG for the prior block has extra edges, remove them.
1031 MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
1033 // If this is a two-way branch, and the FBB branches to this block, reverse
1034 // the condition so the single-basic-block loop is faster. Instead of:
1035 // Loop: xxx; jcc Out; jmp Loop
1037 // Loop: xxx; jncc Loop; jmp Out
1038 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
1039 std::vector<MachineOperand> NewCond(CurCond);
1040 if (!TII->ReverseBranchCondition(NewCond)) {
1041 TII->RemoveBranch(*MBB);
1042 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
1045 return OptimizeBlock(MBB);
1050 // If this branch is the only thing in its block, see if we can forward
1051 // other blocks across it.
1052 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
1053 MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
1054 // This block may contain just an unconditional branch. Because there can
1055 // be 'non-branch terminators' in the block, try removing the branch and
1056 // then seeing if the block is empty.
1057 TII->RemoveBranch(*MBB);
1059 // If this block is just an unconditional branch to CurTBB, we can
1060 // usually completely eliminate the block. The only case we cannot
1061 // completely eliminate the block is when the block before this one
1062 // falls through into MBB and we can't understand the prior block's branch
1065 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
1066 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
1067 !PrevBB.isSuccessor(MBB)) {
1068 // If the prior block falls through into us, turn it into an
1069 // explicit branch to us to make updates simpler.
1070 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
1071 PriorTBB != MBB && PriorFBB != MBB) {
1072 if (PriorTBB == 0) {
1073 assert(PriorCond.empty() && PriorFBB == 0 &&
1074 "Bad branch analysis");
1077 assert(PriorFBB == 0 && "Machine CFG out of date!");
1080 TII->RemoveBranch(PrevBB);
1081 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
1084 // Iterate through all the predecessors, revectoring each in-turn.
1086 bool DidChange = false;
1087 bool HasBranchToSelf = false;
1088 while(PI != MBB->pred_size()) {
1089 MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
1091 // If this block has an uncond branch to itself, leave it.
1093 HasBranchToSelf = true;
1096 PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1100 // Change any jumptables to go to the new MBB.
1101 MBB->getParent()->getJumpTableInfo()->
1102 ReplaceMBBInJumpTables(MBB, CurTBB);
1106 if (!HasBranchToSelf) return;
1111 // Add the branch back if the block is more than just an uncond branch.
1112 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1116 // If the prior block doesn't fall through into this block, and if this
1117 // block doesn't fall through into some other block, see if we can find a
1118 // place to move this block where a fall-through will happen.
1119 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1120 PriorTBB, PriorFBB, PriorCond)) {
1121 // Now we know that there was no fall-through into this block, check to
1122 // see if it has a fall-through into its successor.
1123 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1126 if (!MBB->isLandingPad()) {
1127 // Check all the predecessors of this block. If one of them has no fall
1128 // throughs, move this block right after it.
1129 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1130 E = MBB->pred_end(); PI != E; ++PI) {
1131 // Analyze the branch at the end of the pred.
1132 MachineBasicBlock *PredBB = *PI;
1133 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1134 if (PredBB != MBB && !CanFallThrough(PredBB)
1135 && (!CurFallsThru || !CurTBB || !CurFBB)
1136 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1137 // If the current block doesn't fall through, just move it.
1138 // If the current block can fall through and does not end with a
1139 // conditional branch, we need to append an unconditional jump to
1140 // the (current) next block. To avoid a possible compile-time
1141 // infinite loop, move blocks only backward in this case.
1142 // Also, if there are already 2 branches here, we cannot add a third;
1143 // this means we have the case
1148 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1150 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1152 MBB->moveAfter(PredBB);
1154 return OptimizeBlock(MBB);
1159 if (!CurFallsThru) {
1160 // Check all successors to see if we can move this block before it.
1161 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1162 E = MBB->succ_end(); SI != E; ++SI) {
1163 // Analyze the branch at the end of the block before the succ.
1164 MachineBasicBlock *SuccBB = *SI;
1165 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1166 std::vector<MachineOperand> SuccPrevCond;
1168 // If this block doesn't already fall-through to that successor, and if
1169 // the succ doesn't already have a block that can fall through into it,
1170 // and if the successor isn't an EH destination, we can arrange for the
1171 // fallthrough to happen.
1172 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1173 !SuccBB->isLandingPad()) {
1174 MBB->moveBefore(SuccBB);
1176 return OptimizeBlock(MBB);
1180 // Okay, there is no really great place to put this block. If, however,
1181 // the block before this one would be a fall-through if this block were
1182 // removed, move this block to the end of the function.
1183 if (FallThrough != MBB->getParent()->end() &&
1184 PrevBB.isSuccessor(FallThrough)) {
1185 MBB->moveAfter(--MBB->getParent()->end());