1 //===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/MachineDebugInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineJumpTableInfo.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/STLExtras.h"
30 static Statistic<> NumDeadBlocks("branchfold", "Number of dead blocks removed");
31 static Statistic<> NumBranchOpts("branchfold", "Number of branches optimized");
32 static Statistic<> NumTailMerge ("branchfold", "Number of block tails merged");
35 struct BranchFolder : public MachineFunctionPass {
36 virtual bool runOnMachineFunction(MachineFunction &MF);
37 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
38 const TargetInstrInfo *TII;
39 MachineDebugInfo *MDI;
43 bool TailMergeBlocks(MachineFunction &MF);
44 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
45 MachineBasicBlock *NewDest);
48 bool OptimizeBranches(MachineFunction &MF);
49 void OptimizeBlock(MachineBasicBlock *MBB);
50 void RemoveDeadBlock(MachineBasicBlock *MBB);
54 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
56 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
57 /// function, updating the CFG.
58 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
59 assert(MBB->pred_empty() && "MBB must be dead!");
61 MachineFunction *MF = MBB->getParent();
62 // drop all successors.
63 while (!MBB->succ_empty())
64 MBB->removeSuccessor(MBB->succ_end()-1);
66 // If there is DWARF info to active, check to see if there are any DWARF_LABEL
67 // records in the basic block. If so, unregister them from MachineDebugInfo.
68 if (MDI && !MBB->empty()) {
69 unsigned DWARF_LABELOpc = TII->getDWARF_LABELOpcode();
70 assert(DWARF_LABELOpc &&
71 "Target supports dwarf but didn't implement getDWARF_LABELOpcode!");
73 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
75 if ((unsigned)I->getOpcode() == DWARF_LABELOpc) {
76 // The label ID # is always operand #0, an immediate.
77 MDI->InvalidateLabel(I->getOperand(0).getImm());
83 MF->getBasicBlockList().erase(MBB);
86 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
87 TII = MF.getTarget().getInstrInfo();
88 if (!TII) return false;
90 MDI = getAnalysisToUpdate<MachineDebugInfo>();
92 bool EverMadeChange = false;
93 bool MadeChangeThisIteration = true;
94 while (MadeChangeThisIteration) {
95 MadeChangeThisIteration = false;
96 MadeChangeThisIteration |= TailMergeBlocks(MF);
97 MadeChangeThisIteration |= OptimizeBranches(MF);
98 EverMadeChange |= MadeChangeThisIteration;
101 // See if any jump tables have become mergable or dead as the code generator
103 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
104 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
106 // Figure out how these jump tables should be merged.
107 std::vector<unsigned> JTMapping;
108 JTMapping.reserve(JTs.size());
110 // We always keep the 0th jump table.
111 JTMapping.push_back(0);
113 // Scan the jump tables, seeing if there are any duplicates. Note that this
114 // is N^2, which should be fixed someday.
115 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
116 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
118 // If a jump table was merge with another one, walk the function rewriting
119 // references to jump tables to reference the new JT ID's. Keep track of
120 // whether we see a jump table idx, if not, we can delete the JT.
121 std::vector<bool> JTIsLive;
122 JTIsLive.resize(JTs.size());
123 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
125 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
127 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
128 MachineOperand &Op = I->getOperand(op);
129 if (!Op.isJumpTableIndex()) continue;
130 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
131 Op.setJumpTableIndex(NewIdx);
133 // Remember that this JT is live.
134 JTIsLive[NewIdx] = true;
138 // Finally, remove dead jump tables. This happens either because the
139 // indirect jump was unreachable (and thus deleted) or because the jump
140 // table was merged with some other one.
141 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
143 JTI->RemoveJumpTable(i);
144 EverMadeChange = true;
148 return EverMadeChange;
151 //===----------------------------------------------------------------------===//
152 // Tail Merging of Blocks
153 //===----------------------------------------------------------------------===//
155 /// HashMachineInstr - Compute a hash value for MI and its operands.
156 static unsigned HashMachineInstr(const MachineInstr *MI) {
157 unsigned Hash = MI->getOpcode();
158 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
159 const MachineOperand &Op = MI->getOperand(i);
161 // Merge in bits from the operand if easy.
162 unsigned OperandHash = 0;
163 switch (Op.getType()) {
164 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
165 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
166 case MachineOperand::MO_MachineBasicBlock:
167 OperandHash = Op.getMachineBasicBlock()->getNumber();
169 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
170 case MachineOperand::MO_ConstantPoolIndex:
171 OperandHash = Op.getConstantPoolIndex();
173 case MachineOperand::MO_JumpTableIndex:
174 OperandHash = Op.getJumpTableIndex();
176 case MachineOperand::MO_GlobalAddress:
177 case MachineOperand::MO_ExternalSymbol:
178 // Global address / external symbol are too hard, don't bother, but do
179 // pull in the offset.
180 OperandHash = Op.getOffset();
185 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
190 /// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
191 /// instructions, because cross-jumping only saves code when at least two
192 /// instructions are removed (since a branch must be inserted).
193 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
194 MachineBasicBlock::const_iterator I = MBB->end();
195 if (I == MBB->begin())
196 return 0; // Empty MBB.
199 unsigned Hash = HashMachineInstr(I);
201 if (I == MBB->begin())
202 return Hash; // Single instr MBB.
205 // Hash in the second-to-last instruction.
206 Hash ^= HashMachineInstr(I) << 2;
210 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
211 /// of instructions they actually have in common together at their end. Return
212 /// iterators for the first shared instruction in each block.
213 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
214 MachineBasicBlock *MBB2,
215 MachineBasicBlock::iterator &I1,
216 MachineBasicBlock::iterator &I2) {
220 unsigned TailLen = 0;
221 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
223 if (!I1->isIdenticalTo(I2)) {
232 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
233 /// after it, replacing it with an unconditional branch to NewDest. This
234 /// returns true if OldInst's block is modified, false if NewDest is modified.
235 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
236 MachineBasicBlock *NewDest) {
237 MachineBasicBlock *OldBB = OldInst->getParent();
239 // Remove all the old successors of OldBB from the CFG.
240 while (!OldBB->succ_empty())
241 OldBB->removeSuccessor(OldBB->succ_begin());
243 // Remove all the dead instructions from the end of OldBB.
244 OldBB->erase(OldInst, OldBB->end());
246 // If OldBB isn't immediately before OldBB, insert a branch to it.
247 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
248 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
249 OldBB->addSuccessor(NewDest);
253 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
258 // Find blocks with no successors.
259 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
260 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
262 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
265 // Sort by hash value so that blocks with identical end sequences sort
267 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
269 // Walk through equivalence sets looking for actual exact matches.
270 while (MergePotentials.size() > 1) {
271 unsigned CurHash = (MergePotentials.end()-1)->first;
272 unsigned PrevHash = (MergePotentials.end()-2)->first;
273 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
275 // If there is nothing that matches the hash of the current basic block,
277 if (CurHash != PrevHash) {
278 MergePotentials.pop_back();
282 // Determine the actual length of the shared tail between these two basic
283 // blocks. Because the hash can have collisions, it's possible that this is
285 MachineBasicBlock::iterator BBI1, BBI2;
286 unsigned CommonTailLen =
287 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
290 // If the tails don't have at least two instructions in common, see if there
291 // is anything else in the equivalence class that does match.
292 if (CommonTailLen < 2) {
293 unsigned FoundMatch = ~0U;
294 for (int i = MergePotentials.size()-2;
295 i != -1 && MergePotentials[i].first == CurHash; --i) {
296 CommonTailLen = ComputeCommonTailLength(CurMBB,
297 MergePotentials[i].second,
299 if (CommonTailLen >= 2) {
305 // If we didn't find anything that has at least two instructions matching
306 // this one, bail out.
307 if (FoundMatch == ~0U) {
308 MergePotentials.pop_back();
312 // Otherwise, move the matching block to the right position.
313 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
316 // If either block is the entire common tail, make the longer one branch to
318 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
319 if (CurMBB->begin() == BBI1) {
320 // Hack the end off MBB2, making it jump to CurMBB instead.
321 ReplaceTailWithBranchTo(BBI2, CurMBB);
322 // This modifies MBB2, so remove it from the worklist.
323 MergePotentials.erase(MergePotentials.end()-2);
326 } else if (MBB2->begin() == BBI2) {
327 // Hack the end off CurMBB, making it jump to MBBI@ instead.
328 ReplaceTailWithBranchTo(BBI1, MBB2);
329 // This modifies CurMBB, so remove it from the worklist.
330 MergePotentials.pop_back();
335 MergePotentials.pop_back();
342 //===----------------------------------------------------------------------===//
343 // Branch Optimization
344 //===----------------------------------------------------------------------===//
346 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
349 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
350 MachineBasicBlock *MBB = I++;
353 // If it is dead, remove it.
354 if (MBB->pred_empty()) {
355 RemoveDeadBlock(MBB);
364 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
365 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
366 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
368 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
369 MachineBasicBlock *DestA,
370 MachineBasicBlock *DestB,
372 MachineFunction::iterator FallThru) {
373 bool MadeChange = false;
374 bool AddedFallThrough = false;
376 // If this block ends with a conditional branch that falls through to its
377 // successor, set DestB as the successor.
379 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
381 AddedFallThrough = true;
384 // If this is an unconditional branch with no explicit dest, it must just be
385 // a fallthrough into DestB.
386 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
388 AddedFallThrough = true;
392 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
393 while (SI != MBB.succ_end()) {
397 } else if (*SI == DestB) {
401 // Otherwise, this is a superfluous edge, remove it.
402 MBB.removeSuccessor(SI);
406 if (!AddedFallThrough) {
407 assert(DestA == 0 && DestB == 0 &&
408 "MachineCFG is missing edges!");
410 assert(DestA == 0 && "MachineCFG is missing edges!");
416 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
417 /// 'Old', change the code and CFG so that it branches to 'New' instead.
418 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
419 MachineBasicBlock *Old,
420 MachineBasicBlock *New,
421 const TargetInstrInfo *TII) {
422 assert(Old != New && "Cannot replace self with self!");
424 MachineBasicBlock::iterator I = BB->end();
425 while (I != BB->begin()) {
427 if (!TII->isTerminatorInstr(I->getOpcode())) break;
429 // Scan the operands of this machine instruction, replacing any uses of Old
431 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
432 if (I->getOperand(i).isMachineBasicBlock() &&
433 I->getOperand(i).getMachineBasicBlock() == Old)
434 I->getOperand(i).setMachineBasicBlock(New);
437 // Update the successor information.
438 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
439 for (int i = Succs.size()-1; i >= 0; --i)
440 if (Succs[i] == Old) {
441 BB->removeSuccessor(Old);
442 BB->addSuccessor(New);
446 /// CanFallThrough - Return true of the specified branch condition can transfer
447 /// control to FallthroughBlock, the block immediately after the branch.
448 static bool CanFallThrough(MachineBasicBlock *TBB,
449 MachineBasicBlock *FBB,
450 const std::vector<MachineOperand> &Cond,
451 MachineFunction::iterator FallthroughBlock) {
452 // If there is no branch, control always falls through.
453 if (TBB == 0) return true;
455 // If there is some explicit branch to the fallthrough block, it can obviously
456 // reach, even though the branch should get folded to fall through implicitly.
457 if (MachineFunction::iterator(TBB) == FallthroughBlock ||
458 MachineFunction::iterator(FBB) == FallthroughBlock)
461 // If it's an unconditional branch to some block not the fall through, it
462 // doesn't fall through.
463 if (Cond.empty()) return false;
465 // Otherwise, if it is conditional and has no explicit false block, it falls
470 /// OptimizeBlock - Analyze and optimize control flow related to the specified
471 /// block. This is never called on the entry block.
472 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
473 MachineFunction::iterator FallThrough = MBB;
476 // If this block is empty, make everyone use its fall-through, not the block
479 // Dead block? Leave for cleanup later.
480 if (MBB->pred_empty()) return;
482 if (FallThrough == MBB->getParent()->end()) {
483 // TODO: Simplify preds to not branch here if possible!
485 // Rewrite all predecessors of the old block to go to the fallthrough
487 while (!MBB->pred_empty()) {
488 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
489 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
492 // If MBB was the target of a jump table, update jump tables to go to the
493 // fallthrough instead.
494 MBB->getParent()->getJumpTableInfo()->
495 ReplaceMBBInJumpTables(MBB, FallThrough);
501 // Check to see if we can simplify the terminator of the block before this
503 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
505 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
506 std::vector<MachineOperand> PriorCond;
507 bool PriorUnAnalyzable = false;
508 PriorUnAnalyzable = TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
509 if (!PriorUnAnalyzable) {
510 // If the CFG for the prior block has extra edges, remove them.
511 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
512 !PriorCond.empty(), MBB);
514 // If the previous branch is conditional and both conditions go to the same
515 // destination, remove the branch, replacing it with an unconditional one or
517 if (PriorTBB && PriorTBB == PriorFBB) {
518 TII->RemoveBranch(PrevBB);
521 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
524 return OptimizeBlock(MBB);
527 // If the previous branch *only* branches to *this* block (conditional or
528 // not) remove the branch.
529 if (PriorTBB == MBB && PriorFBB == 0) {
530 TII->RemoveBranch(PrevBB);
533 return OptimizeBlock(MBB);
536 // If the prior block branches somewhere else on the condition and here if
537 // the condition is false, remove the uncond second branch.
538 if (PriorFBB == MBB) {
539 TII->RemoveBranch(PrevBB);
540 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
543 return OptimizeBlock(MBB);
546 // If the prior block branches here on true and somewhere else on false, and
547 // if the branch condition is reversible, reverse the branch to create a
549 if (PriorTBB == MBB) {
550 std::vector<MachineOperand> NewPriorCond(PriorCond);
551 if (!TII->ReverseBranchCondition(NewPriorCond)) {
552 TII->RemoveBranch(PrevBB);
553 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
556 return OptimizeBlock(MBB);
561 // Analyze the branch in the current block.
562 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
563 std::vector<MachineOperand> CurCond;
564 if (!TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond)) {
565 // If the CFG for the prior block has extra edges, remove them.
566 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
568 ++MachineFunction::iterator(MBB));
570 // If this branch is the only thing in its block, see if we can forward
571 // other blocks across it.
572 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
573 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
574 // This block may contain just an unconditional branch. Because there can
575 // be 'non-branch terminators' in the block, try removing the branch and
576 // then seeing if the block is empty.
577 TII->RemoveBranch(*MBB);
579 // If this block is just an unconditional branch to CurTBB, we can
580 // usually completely eliminate the block. The only case we cannot
581 // completely eliminate the block is when the block before this one
582 // falls through into MBB and we can't understand the prior block's branch
585 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
586 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
587 !PrevBB.isSuccessor(MBB)) {
588 // If the prior block falls through into us, turn it into an
589 // explicit branch to us to make updates simpler.
590 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
591 PriorTBB != MBB && PriorFBB != MBB) {
593 assert(PriorCond.empty() && PriorFBB == 0 &&
594 "Bad branch analysis");
597 assert(PriorFBB == 0 && "Machine CFG out of date!");
600 TII->RemoveBranch(PrevBB);
601 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
604 // Iterate through all the predecessors, revectoring each in-turn.
605 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
606 bool DidChange = false;
607 bool HasBranchToSelf = false;
608 while (PI != MBB->pred_end()) {
610 // If this block has an uncond branch to itself, leave it.
612 HasBranchToSelf = true;
615 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
619 // Change any jumptables to go to the new MBB.
620 MBB->getParent()->getJumpTableInfo()->
621 ReplaceMBBInJumpTables(MBB, CurTBB);
625 if (!HasBranchToSelf) return;
630 // Add the branch back if the block is more than just an uncond branch.
631 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
634 // If the prior block doesn't fall through into this block, and if this
635 // block doesn't fall through into some other block, see if we can find a
636 // place to move this block where a fall-through will happen.
637 if (!PriorUnAnalyzable && !CanFallThrough(PriorTBB, PriorFBB,
639 // Now we know that there was no fall-through into this block, check to
640 // see if it has fall-throughs.
641 if (!CanFallThrough(CurTBB, CurFBB, CurCond, FallThrough)) {
643 // Check all the predecessors of this block. If one of them has no fall
644 // throughs, move this block right after it.
645 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
646 E = MBB->pred_end(); PI != E; ++PI) {
647 // Analyze the branch at the end of the pred.
648 MachineBasicBlock *PredBB = *PI;
649 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
650 MachineBasicBlock *PredTBB = 0, *PredFBB = 0;
651 std::vector<MachineOperand> PredCond;
653 !TII->AnalyzeBranch(*PredBB, PredTBB, PredFBB, PredCond) &&
654 !CanFallThrough(PredTBB, PredFBB, PredCond, PredFallthrough)) {
655 MBB->moveAfter(PredBB);
657 return OptimizeBlock(MBB);
661 // Check all successors to see if we can move this block before it.
662 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
663 E = MBB->succ_end(); SI != E; ++SI) {
664 // Analyze the branch at the end of the block before the succ.
665 MachineBasicBlock *SuccBB = *SI;
666 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
667 MachineBasicBlock *SuccPrevTBB = 0, *SuccPrevFBB = 0;
668 std::vector<MachineOperand> SuccPrevCond;
670 !TII->AnalyzeBranch(*SuccPrev, SuccPrevTBB, SuccPrevFBB,
672 !CanFallThrough(SuccPrevTBB, SuccPrevFBB, SuccPrevCond, SuccBB)) {
673 MBB->moveBefore(SuccBB);
675 return OptimizeBlock(MBB);
679 // Okay, there is no really great place to put this block. If, however,
680 // the block before this one would be a fall-through if this block were
681 // removed, move this block to the end of the function.
682 if (FallThrough != MBB->getParent()->end() &&
683 CanFallThrough(PriorTBB, PriorFBB, PriorCond, FallThrough)) {
684 MBB->moveAfter(--MBB->getParent()->end());