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 #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/MRegisterInfo.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/STLExtras.h"
35 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
36 STATISTIC(NumBranchOpts, "Number of branches optimized");
37 STATISTIC(NumTailMerge , "Number of block tails merged");
38 static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
41 struct BranchFolder : public MachineFunctionPass {
43 BranchFolder() : MachineFunctionPass((intptr_t)&ID) {}
45 virtual bool runOnMachineFunction(MachineFunction &MF);
46 virtual const char *getPassName() const { return "Control Flow Optimizer"; }
47 const TargetInstrInfo *TII;
48 MachineModuleInfo *MMI;
52 bool TailMergeBlocks(MachineFunction &MF);
53 bool TryMergeBlocks(MachineBasicBlock* SuccBB,
54 MachineBasicBlock* PredBB);
55 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
56 MachineBasicBlock *NewDest);
57 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
58 MachineBasicBlock::iterator BBI1);
60 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
61 const MRegisterInfo *RegInfo;
64 bool OptimizeBranches(MachineFunction &MF);
65 void OptimizeBlock(MachineBasicBlock *MBB);
66 void RemoveDeadBlock(MachineBasicBlock *MBB);
68 bool CanFallThrough(MachineBasicBlock *CurBB);
69 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
70 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
71 const std::vector<MachineOperand> &Cond);
73 char BranchFolder::ID = 0;
76 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
77 MachineBasicBlock *DestA,
78 MachineBasicBlock *DestB,
80 MachineFunction::iterator FallThru);
82 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
84 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
85 /// function, updating the CFG.
86 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
87 assert(MBB->pred_empty() && "MBB must be dead!");
88 DOUT << "\nRemoving MBB: " << *MBB;
90 MachineFunction *MF = MBB->getParent();
91 // drop all successors.
92 while (!MBB->succ_empty())
93 MBB->removeSuccessor(MBB->succ_end()-1);
95 // If there is DWARF info to active, check to see if there are any LABEL
96 // records in the basic block. If so, unregister them from MachineModuleInfo.
97 if (MMI && !MBB->empty()) {
98 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
100 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
101 // The label ID # is always operand #0, an immediate.
102 MMI->InvalidateLabel(I->getOperand(0).getImm());
108 MF->getBasicBlockList().erase(MBB);
111 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
112 TII = MF.getTarget().getInstrInfo();
113 if (!TII) return false;
115 // Fix CFG. The later algorithms expect it to be right.
116 bool EverMadeChange = false;
117 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
118 MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
119 std::vector<MachineOperand> Cond;
120 if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
121 EverMadeChange |= CorrectExtraCFGEdges(*MBB, TBB, FBB,
122 !Cond.empty(), next(I));
125 RegInfo = MF.getTarget().getRegisterInfo();
126 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
128 MMI = getAnalysisToUpdate<MachineModuleInfo>();
130 bool MadeChangeThisIteration = true;
131 while (MadeChangeThisIteration) {
132 MadeChangeThisIteration = false;
133 MadeChangeThisIteration |= TailMergeBlocks(MF);
134 MadeChangeThisIteration |= OptimizeBranches(MF);
135 EverMadeChange |= MadeChangeThisIteration;
138 // See if any jump tables have become mergable or dead as the code generator
140 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
141 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
143 // Figure out how these jump tables should be merged.
144 std::vector<unsigned> JTMapping;
145 JTMapping.reserve(JTs.size());
147 // We always keep the 0th jump table.
148 JTMapping.push_back(0);
150 // Scan the jump tables, seeing if there are any duplicates. Note that this
151 // is N^2, which should be fixed someday.
152 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
153 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
155 // If a jump table was merge with another one, walk the function rewriting
156 // references to jump tables to reference the new JT ID's. Keep track of
157 // whether we see a jump table idx, if not, we can delete the JT.
158 std::vector<bool> JTIsLive;
159 JTIsLive.resize(JTs.size());
160 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
162 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
164 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
165 MachineOperand &Op = I->getOperand(op);
166 if (!Op.isJumpTableIndex()) continue;
167 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
168 Op.setJumpTableIndex(NewIdx);
170 // Remember that this JT is live.
171 JTIsLive[NewIdx] = true;
175 // Finally, remove dead jump tables. This happens either because the
176 // indirect jump was unreachable (and thus deleted) or because the jump
177 // table was merged with some other one.
178 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
180 JTI->RemoveJumpTable(i);
181 EverMadeChange = true;
186 return EverMadeChange;
189 //===----------------------------------------------------------------------===//
190 // Tail Merging of Blocks
191 //===----------------------------------------------------------------------===//
193 /// HashMachineInstr - Compute a hash value for MI and its operands.
194 static unsigned HashMachineInstr(const MachineInstr *MI) {
195 unsigned Hash = MI->getOpcode();
196 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
197 const MachineOperand &Op = MI->getOperand(i);
199 // Merge in bits from the operand if easy.
200 unsigned OperandHash = 0;
201 switch (Op.getType()) {
202 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
203 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
204 case MachineOperand::MO_MachineBasicBlock:
205 OperandHash = Op.getMachineBasicBlock()->getNumber();
207 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
208 case MachineOperand::MO_ConstantPoolIndex:
209 OperandHash = Op.getConstantPoolIndex();
211 case MachineOperand::MO_JumpTableIndex:
212 OperandHash = Op.getJumpTableIndex();
214 case MachineOperand::MO_GlobalAddress:
215 case MachineOperand::MO_ExternalSymbol:
216 // Global address / external symbol are too hard, don't bother, but do
217 // pull in the offset.
218 OperandHash = Op.getOffset();
223 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
228 /// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
229 /// instructions, because cross-jumping only saves code when at least two
230 /// instructions are removed (since a branch must be inserted).
231 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
232 MachineBasicBlock::const_iterator I = MBB->end();
233 if (I == MBB->begin())
234 return 0; // Empty MBB.
237 unsigned Hash = HashMachineInstr(I);
239 if (I == MBB->begin())
240 return Hash; // Single instr MBB.
243 // Hash in the second-to-last instruction.
244 Hash ^= HashMachineInstr(I) << 2;
248 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
249 /// of instructions they actually have in common together at their end. Return
250 /// iterators for the first shared instruction in each block.
251 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
252 MachineBasicBlock *MBB2,
253 MachineBasicBlock::iterator &I1,
254 MachineBasicBlock::iterator &I2) {
258 unsigned TailLen = 0;
259 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
261 if (!I1->isIdenticalTo(I2)) {
270 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
271 /// after it, replacing it with an unconditional branch to NewDest. This
272 /// returns true if OldInst's block is modified, false if NewDest is modified.
273 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
274 MachineBasicBlock *NewDest) {
275 MachineBasicBlock *OldBB = OldInst->getParent();
277 // Remove all the old successors of OldBB from the CFG.
278 while (!OldBB->succ_empty())
279 OldBB->removeSuccessor(OldBB->succ_begin());
281 // Remove all the dead instructions from the end of OldBB.
282 OldBB->erase(OldInst, OldBB->end());
284 // If OldBB isn't immediately before OldBB, insert a branch to it.
285 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
286 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
287 OldBB->addSuccessor(NewDest);
291 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
292 /// MBB so that the part before the iterator falls into the part starting at the
293 /// iterator. This returns the new MBB.
294 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
295 MachineBasicBlock::iterator BBI1) {
296 // Create the fall-through block.
297 MachineFunction::iterator MBBI = &CurMBB;
298 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
299 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
301 // Move all the successors of this block to the specified block.
302 while (!CurMBB.succ_empty()) {
303 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
304 NewMBB->addSuccessor(S);
305 CurMBB.removeSuccessor(S);
308 // Add an edge from CurMBB to NewMBB for the fall-through.
309 CurMBB.addSuccessor(NewMBB);
311 // Splice the code over.
312 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
314 // For targets that use the register scavenger, we must maintain LiveIns.
316 RS->enterBasicBlock(&CurMBB);
318 RS->forward(prior(CurMBB.end()));
319 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
320 RS->getRegsUsed(RegsLiveAtExit, false);
321 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
322 if (RegsLiveAtExit[i])
323 NewMBB->addLiveIn(i);
329 /// EstimateRuntime - Make a rough estimate for how long it will take to run
330 /// the specified code.
331 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
332 MachineBasicBlock::iterator E,
333 const TargetInstrInfo *TII) {
335 for (; I != E; ++I) {
336 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
337 if (TID.Flags & M_CALL_FLAG)
339 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
347 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
348 /// MBB2I and then insert an unconditional branch in the other block. Determine
349 /// which is the best to split
350 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
351 MachineBasicBlock::iterator MBB1I,
352 MachineBasicBlock *MBB2,
353 MachineBasicBlock::iterator MBB2I,
354 const TargetInstrInfo *TII,
355 MachineBasicBlock *PredBB) {
356 // If one block is the entry block, split the other one; we can't generate
357 // a branch to the entry block, as its label is not emitted.
358 MachineBasicBlock *Entry = MBB1->getParent()->begin();
364 // If one block falls through into the common successor, choose that
365 // one to split; it is one instruction less to do that.
369 else if (MBB2 == PredBB)
372 // TODO: if we had some notion of which block was hotter, we could split
373 // the hot block, so it is the fall-through. Since we don't have profile info
374 // make a decision based on which will hurt most to split.
375 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
376 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
378 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
379 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
380 // have a lower overall impact on the program execution.
381 return MBB1Time < MBB2Time;
384 // CurMBB needs to add an unconditional branch to SuccMBB (we removed these
385 // branches temporarily for tail merging). In the case where CurMBB ends
386 // with a conditional branch to the next block, optimize by reversing the
387 // test and conditionally branching to SuccMBB instead.
389 static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
390 const TargetInstrInfo *TII) {
391 MachineFunction *MF = CurMBB->getParent();
392 MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
393 MachineBasicBlock *TBB = 0, *FBB = 0;
394 std::vector<MachineOperand> Cond;
395 if (I != MF->end() &&
396 !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
397 MachineBasicBlock *NextBB = I;
398 if (TBB == NextBB && Cond.size() && !FBB) {
399 if (!TII->ReverseBranchCondition(Cond)) {
400 TII->RemoveBranch(*CurMBB);
401 TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
406 TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
409 // See if any of the blocks in MergePotentials (which all have a common single
410 // successor, or all have no successor) can be tail-merged. If there is a
411 // successor, any blocks in MergePotentials that are not tail-merged and
412 // are not immediately before Succ must have an unconditional branch to
413 // Succ added (but the predecessor/successor lists need no adjustment).
414 // The lone predecessor of Succ that falls through into Succ,
415 // if any, is given in PredBB.
417 bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
418 MachineBasicBlock* PredBB) {
421 // Sort by hash value so that blocks with identical end sequences sort
423 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
425 // Walk through equivalence sets looking for actual exact matches.
426 while (MergePotentials.size() > 1) {
427 unsigned CurHash = (MergePotentials.end()-1)->first;
428 unsigned PrevHash = (MergePotentials.end()-2)->first;
429 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
431 // If there is nothing that matches the hash of the current basic block,
433 if (CurHash != PrevHash) {
434 if (SuccBB && CurMBB != PredBB)
435 FixTail(CurMBB, SuccBB, TII);
436 MergePotentials.pop_back();
440 // Determine the actual length of the shared tail between these two basic
441 // blocks. Because the hash can have collisions, it's possible that this is
443 MachineBasicBlock::iterator BBI1, BBI2;
444 unsigned CommonTailLen =
445 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
448 // If the tails don't have at least two instructions in common, see if there
449 // is anything else in the equivalence class that does match.
450 // Since instructions may get combined later (e.g. single stores into
451 // store multiple) this measure is not particularly accurate.
452 if (CommonTailLen < 2) {
453 unsigned FoundMatch = ~0U;
454 for (int i = MergePotentials.size()-2;
455 i != -1 && MergePotentials[i].first == CurHash; --i) {
456 CommonTailLen = ComputeCommonTailLength(CurMBB,
457 MergePotentials[i].second,
459 if (CommonTailLen >= 2) {
465 // If we didn't find anything that has at least two instructions matching
466 // this one, bail out.
467 if (FoundMatch == ~0U) {
468 // Put the unconditional branch back, if we need one.
469 if (SuccBB && CurMBB != PredBB)
470 FixTail(CurMBB, SuccBB, TII);
471 MergePotentials.pop_back();
475 // Otherwise, move the matching block to the right position.
476 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
479 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
481 // If neither block is the entire common tail, split the tail of one block
482 // to make it redundant with the other tail. Also, we cannot jump to the
483 // entry block, so if one block is the entry block, split the other one.
484 MachineBasicBlock *Entry = CurMBB->getParent()->begin();
485 if (CurMBB->begin() == BBI1 && CurMBB != Entry)
486 ; // CurMBB is common tail
487 else if (MBB2->begin() == BBI2 && MBB2 != Entry)
488 ; // MBB2 is common tail
490 if (0) { // Enable this to disable partial tail merges.
491 MergePotentials.pop_back();
495 // Decide whether we want to split CurMBB or MBB2.
496 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII, PredBB)) {
497 CurMBB = SplitMBBAt(*CurMBB, BBI1);
498 BBI1 = CurMBB->begin();
499 MergePotentials.back().second = CurMBB;
501 MBB2 = SplitMBBAt(*MBB2, BBI2);
502 BBI2 = MBB2->begin();
503 (MergePotentials.end()-2)->second = MBB2;
507 if (MBB2->begin() == BBI2 && MBB2 != Entry) {
508 // Hack the end off CurMBB, making it jump to MBBI@ instead.
509 ReplaceTailWithBranchTo(BBI1, MBB2);
510 // This modifies CurMBB, so remove it from the worklist.
511 MergePotentials.pop_back();
513 assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
514 "Didn't split block correctly?");
515 // Hack the end off MBB2, making it jump to CurMBB instead.
516 ReplaceTailWithBranchTo(BBI2, CurMBB);
517 // This modifies MBB2, so remove it from the worklist.
518 MergePotentials.erase(MergePotentials.end()-2);
525 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
527 if (!EnableTailMerge) return false;
531 // First find blocks with no successors.
532 MergePotentials.clear();
533 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
535 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
537 // See if we can do any tail merging on those.
538 MadeChange |= TryMergeBlocks(NULL, NULL);
540 // Look at blocks (IBB) with multiple predecessors (PBB).
541 // We change each predecessor to a canonical form, by
542 // (1) temporarily removing any unconditional branch from the predecessor
544 // (2) alter conditional branches so they branch to the other block
545 // not IBB; this may require adding back an unconditional branch to IBB
546 // later, where there wasn't one coming in. E.g.
548 // fallthrough to QBB
551 // with a conceptual B to IBB after that, which never actually exists.
552 // With those changes, we see whether the predecessors' tails match,
553 // and merge them if so. We change things out of canonical form and
554 // back to the way they were later in the process. (OptimizeBranches
555 // would undo some of this, but we can't use it, because we'd get into
556 // a compile-time infinite loop repeatedly doing and undoing the same
559 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
560 if (!I->succ_empty() && I->pred_size() >= 2) {
561 MachineBasicBlock *IBB = I;
562 MachineBasicBlock *PredBB = prior(I);
563 MergePotentials.clear();
564 for (MachineBasicBlock::pred_iterator P = I->pred_begin(), E2 = I->pred_end();
566 MachineBasicBlock* PBB = *P;
567 // Skip blocks that loop to themselves, can't tail merge these.
570 MachineBasicBlock *TBB = 0, *FBB = 0;
571 std::vector<MachineOperand> Cond;
572 if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
573 // Failing case: IBB is the target of a cbr, and
574 // we cannot reverse the branch.
575 std::vector<MachineOperand> NewCond(Cond);
576 if (Cond.size() && TBB==IBB) {
577 if (TII->ReverseBranchCondition(NewCond))
579 // This is the QBB case described above
581 FBB = next(MachineFunction::iterator(PBB));
583 // Remove the unconditional branch at the end, if any.
584 if (TBB && (Cond.size()==0 || FBB)) {
585 TII->RemoveBranch(*PBB);
587 // reinsert conditional branch only, for now
588 TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
590 MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB), *P));
593 if (MergePotentials.size() >= 2)
594 MadeChange |= TryMergeBlocks(I, PredBB);
595 // Reinsert an unconditional branch if needed.
596 // The 1 below can be either an original single predecessor, or a result
597 // of removing blocks in TryMergeBlocks.
598 PredBB = prior(I); // this may have been changed in TryMergeBlocks
599 if (MergePotentials.size()==1 &&
600 (MergePotentials.begin())->second != PredBB)
601 FixTail((MergePotentials.begin())->second, I, TII);
607 //===----------------------------------------------------------------------===//
608 // Branch Optimization
609 //===----------------------------------------------------------------------===//
611 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
614 // Make sure blocks are numbered in order
617 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
618 MachineBasicBlock *MBB = I++;
621 // If it is dead, remove it.
622 if (MBB->pred_empty()) {
623 RemoveDeadBlock(MBB);
632 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
633 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
634 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
636 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
637 MachineBasicBlock *DestA,
638 MachineBasicBlock *DestB,
640 MachineFunction::iterator FallThru) {
641 bool MadeChange = false;
642 bool AddedFallThrough = false;
644 // If this block ends with a conditional branch that falls through to its
645 // successor, set DestB as the successor.
647 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
649 AddedFallThrough = true;
652 // If this is an unconditional branch with no explicit dest, it must just be
653 // a fallthrough into DestB.
654 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
656 AddedFallThrough = true;
660 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
661 while (SI != MBB.succ_end()) {
665 } else if (*SI == DestB) {
668 } else if ((*SI)->isLandingPad()) {
671 // Otherwise, this is a superfluous edge, remove it.
672 MBB.removeSuccessor(SI);
676 if (!AddedFallThrough) {
677 assert(DestA == 0 && DestB == 0 &&
678 "MachineCFG is missing edges!");
680 assert(DestA == 0 && "MachineCFG is missing edges!");
686 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
687 /// 'Old', change the code and CFG so that it branches to 'New' instead.
688 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
689 MachineBasicBlock *Old,
690 MachineBasicBlock *New,
691 const TargetInstrInfo *TII) {
692 assert(Old != New && "Cannot replace self with self!");
694 MachineBasicBlock::iterator I = BB->end();
695 while (I != BB->begin()) {
697 if (!TII->isTerminatorInstr(I->getOpcode())) break;
699 // Scan the operands of this machine instruction, replacing any uses of Old
701 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
702 if (I->getOperand(i).isMachineBasicBlock() &&
703 I->getOperand(i).getMachineBasicBlock() == Old)
704 I->getOperand(i).setMachineBasicBlock(New);
707 // Update the successor information.
708 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
709 for (int i = Succs.size()-1; i >= 0; --i)
710 if (Succs[i] == Old) {
711 BB->removeSuccessor(Old);
712 BB->addSuccessor(New);
716 /// CanFallThrough - Return true if the specified block (with the specified
717 /// branch condition) can implicitly transfer control to the block after it by
718 /// falling off the end of it. This should return false if it can reach the
719 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
721 /// True is a conservative answer.
723 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
724 bool BranchUnAnalyzable,
725 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
726 const std::vector<MachineOperand> &Cond) {
727 MachineFunction::iterator Fallthrough = CurBB;
729 // If FallthroughBlock is off the end of the function, it can't fall through.
730 if (Fallthrough == CurBB->getParent()->end())
733 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
734 if (!CurBB->isSuccessor(Fallthrough))
737 // If we couldn't analyze the branch, assume it could fall through.
738 if (BranchUnAnalyzable) return true;
740 // If there is no branch, control always falls through.
741 if (TBB == 0) return true;
743 // If there is some explicit branch to the fallthrough block, it can obviously
744 // reach, even though the branch should get folded to fall through implicitly.
745 if (MachineFunction::iterator(TBB) == Fallthrough ||
746 MachineFunction::iterator(FBB) == Fallthrough)
749 // If it's an unconditional branch to some block not the fall through, it
750 // doesn't fall through.
751 if (Cond.empty()) return false;
753 // Otherwise, if it is conditional and has no explicit false block, it falls
758 /// CanFallThrough - Return true if the specified can implicitly transfer
759 /// control to the block after it by falling off the end of it. This should
760 /// return false if it can reach the block after it, but it uses an explicit
761 /// branch to do so (e.g. a table jump).
763 /// True is a conservative answer.
765 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
766 MachineBasicBlock *TBB = 0, *FBB = 0;
767 std::vector<MachineOperand> Cond;
768 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
769 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
772 /// IsBetterFallthrough - Return true if it would be clearly better to
773 /// fall-through to MBB1 than to fall through into MBB2. This has to return
774 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
775 /// result in infinite loops.
776 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
777 MachineBasicBlock *MBB2,
778 const TargetInstrInfo &TII) {
779 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
780 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
781 // optimize branches that branch to either a return block or an assert block
782 // into a fallthrough to the return.
783 if (MBB1->empty() || MBB2->empty()) return false;
785 MachineInstr *MBB1I = --MBB1->end();
786 MachineInstr *MBB2I = --MBB2->end();
787 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
790 /// OptimizeBlock - Analyze and optimize control flow related to the specified
791 /// block. This is never called on the entry block.
792 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
793 MachineFunction::iterator FallThrough = MBB;
796 // If this block is empty, make everyone use its fall-through, not the block
799 // Dead block? Leave for cleanup later.
800 if (MBB->pred_empty()) return;
802 if (FallThrough == MBB->getParent()->end()) {
803 // TODO: Simplify preds to not branch here if possible!
805 // Rewrite all predecessors of the old block to go to the fallthrough
807 while (!MBB->pred_empty()) {
808 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
809 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
812 // If MBB was the target of a jump table, update jump tables to go to the
813 // fallthrough instead.
814 MBB->getParent()->getJumpTableInfo()->
815 ReplaceMBBInJumpTables(MBB, FallThrough);
821 // Check to see if we can simplify the terminator of the block before this
823 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
825 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
826 std::vector<MachineOperand> PriorCond;
827 bool PriorUnAnalyzable =
828 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
829 if (!PriorUnAnalyzable) {
830 // If the CFG for the prior block has extra edges, remove them.
831 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
832 !PriorCond.empty(), MBB);
834 // If the previous branch is conditional and both conditions go to the same
835 // destination, remove the branch, replacing it with an unconditional one or
837 if (PriorTBB && PriorTBB == PriorFBB) {
838 TII->RemoveBranch(PrevBB);
841 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
844 return OptimizeBlock(MBB);
847 // If the previous branch *only* branches to *this* block (conditional or
848 // not) remove the branch.
849 if (PriorTBB == MBB && PriorFBB == 0) {
850 TII->RemoveBranch(PrevBB);
853 return OptimizeBlock(MBB);
856 // If the prior block branches somewhere else on the condition and here if
857 // the condition is false, remove the uncond second branch.
858 if (PriorFBB == MBB) {
859 TII->RemoveBranch(PrevBB);
860 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
863 return OptimizeBlock(MBB);
866 // If the prior block branches here on true and somewhere else on false, and
867 // if the branch condition is reversible, reverse the branch to create a
869 if (PriorTBB == MBB) {
870 std::vector<MachineOperand> NewPriorCond(PriorCond);
871 if (!TII->ReverseBranchCondition(NewPriorCond)) {
872 TII->RemoveBranch(PrevBB);
873 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
876 return OptimizeBlock(MBB);
880 // If this block doesn't fall through (e.g. it ends with an uncond branch or
881 // has no successors) and if the pred falls through into this block, and if
882 // it would otherwise fall through into the block after this, move this
883 // block to the end of the function.
885 // We consider it more likely that execution will stay in the function (e.g.
886 // due to loops) than it is to exit it. This asserts in loops etc, moving
887 // the assert condition out of the loop body.
888 if (!PriorCond.empty() && PriorFBB == 0 &&
889 MachineFunction::iterator(PriorTBB) == FallThrough &&
890 !CanFallThrough(MBB)) {
891 bool DoTransform = true;
893 // We have to be careful that the succs of PredBB aren't both no-successor
894 // blocks. If neither have successors and if PredBB is the second from
895 // last block in the function, we'd just keep swapping the two blocks for
896 // last. Only do the swap if one is clearly better to fall through than
898 if (FallThrough == --MBB->getParent()->end() &&
899 !IsBetterFallthrough(PriorTBB, MBB, *TII))
902 // We don't want to do this transformation if we have control flow like:
911 // In this case, we could actually be moving the return block *into* a
913 if (DoTransform && !MBB->succ_empty() &&
914 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
919 // Reverse the branch so we will fall through on the previous true cond.
920 std::vector<MachineOperand> NewPriorCond(PriorCond);
921 if (!TII->ReverseBranchCondition(NewPriorCond)) {
922 DOUT << "\nMoving MBB: " << *MBB;
923 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
925 TII->RemoveBranch(PrevBB);
926 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
928 // Move this block to the end of the function.
929 MBB->moveAfter(--MBB->getParent()->end());
938 // Analyze the branch in the current block.
939 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
940 std::vector<MachineOperand> CurCond;
941 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
942 if (!CurUnAnalyzable) {
943 // If the CFG for the prior block has extra edges, remove them.
944 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
946 ++MachineFunction::iterator(MBB));
948 // If this is a two-way branch, and the FBB branches to this block, reverse
949 // the condition so the single-basic-block loop is faster. Instead of:
950 // Loop: xxx; jcc Out; jmp Loop
952 // Loop: xxx; jncc Loop; jmp Out
953 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
954 std::vector<MachineOperand> NewCond(CurCond);
955 if (!TII->ReverseBranchCondition(NewCond)) {
956 TII->RemoveBranch(*MBB);
957 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
960 return OptimizeBlock(MBB);
965 // If this branch is the only thing in its block, see if we can forward
966 // other blocks across it.
967 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
968 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
969 // This block may contain just an unconditional branch. Because there can
970 // be 'non-branch terminators' in the block, try removing the branch and
971 // then seeing if the block is empty.
972 TII->RemoveBranch(*MBB);
974 // If this block is just an unconditional branch to CurTBB, we can
975 // usually completely eliminate the block. The only case we cannot
976 // completely eliminate the block is when the block before this one
977 // falls through into MBB and we can't understand the prior block's branch
980 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
981 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
982 !PrevBB.isSuccessor(MBB)) {
983 // If the prior block falls through into us, turn it into an
984 // explicit branch to us to make updates simpler.
985 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
986 PriorTBB != MBB && PriorFBB != MBB) {
988 assert(PriorCond.empty() && PriorFBB == 0 &&
989 "Bad branch analysis");
992 assert(PriorFBB == 0 && "Machine CFG out of date!");
995 TII->RemoveBranch(PrevBB);
996 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
999 // Iterate through all the predecessors, revectoring each in-turn.
1000 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
1001 bool DidChange = false;
1002 bool HasBranchToSelf = false;
1003 while (PI != MBB->pred_end()) {
1005 // If this block has an uncond branch to itself, leave it.
1007 HasBranchToSelf = true;
1010 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
1014 // Change any jumptables to go to the new MBB.
1015 MBB->getParent()->getJumpTableInfo()->
1016 ReplaceMBBInJumpTables(MBB, CurTBB);
1020 if (!HasBranchToSelf) return;
1025 // Add the branch back if the block is more than just an uncond branch.
1026 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1030 // If the prior block doesn't fall through into this block, and if this
1031 // block doesn't fall through into some other block, see if we can find a
1032 // place to move this block where a fall-through will happen.
1033 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1034 PriorTBB, PriorFBB, PriorCond)) {
1035 // Now we know that there was no fall-through into this block, check to
1036 // see if it has a fall-through into its successor.
1037 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1040 if (!MBB->isLandingPad()) {
1041 // Check all the predecessors of this block. If one of them has no fall
1042 // throughs, move this block right after it.
1043 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1044 E = MBB->pred_end(); PI != E; ++PI) {
1045 // Analyze the branch at the end of the pred.
1046 MachineBasicBlock *PredBB = *PI;
1047 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1048 if (PredBB != MBB && !CanFallThrough(PredBB)
1049 && (!CurFallsThru || !CurTBB || !CurFBB)
1050 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1051 // If the current block doesn't fall through, just move it.
1052 // If the current block can fall through and does not end with a
1053 // conditional branch, we need to append an unconditional jump to
1054 // the (current) next block. To avoid a possible compile-time
1055 // infinite loop, move blocks only backward in this case.
1056 // Also, if there are already 2 branches here, we cannot add a third;
1057 // this means we have the case
1062 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1064 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1066 MBB->moveAfter(PredBB);
1068 return OptimizeBlock(MBB);
1073 if (!CurFallsThru) {
1074 // Check all successors to see if we can move this block before it.
1075 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1076 E = MBB->succ_end(); SI != E; ++SI) {
1077 // Analyze the branch at the end of the block before the succ.
1078 MachineBasicBlock *SuccBB = *SI;
1079 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1080 std::vector<MachineOperand> SuccPrevCond;
1082 // If this block doesn't already fall-through to that successor, and if
1083 // the succ doesn't already have a block that can fall through into it,
1084 // and if the successor isn't an EH destination, we can arrange for the
1085 // fallthrough to happen.
1086 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1087 !SuccBB->isLandingPad()) {
1088 MBB->moveBefore(SuccBB);
1090 return OptimizeBlock(MBB);
1094 // Okay, there is no really great place to put this block. If, however,
1095 // the block before this one would be a fall-through if this block were
1096 // removed, move this block to the end of the function.
1097 if (FallThrough != MBB->getParent()->end() &&
1098 PrevBB.isSuccessor(FallThrough)) {
1099 MBB->moveAfter(--MBB->getParent()->end());