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 void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
54 MachineBasicBlock *NewDest);
55 MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
56 MachineBasicBlock::iterator BBI1);
58 const MRegisterInfo *RegInfo;
61 bool OptimizeBranches(MachineFunction &MF);
62 void OptimizeBlock(MachineBasicBlock *MBB);
63 void RemoveDeadBlock(MachineBasicBlock *MBB);
65 bool CanFallThrough(MachineBasicBlock *CurBB);
66 bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
67 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
68 const std::vector<MachineOperand> &Cond);
70 const char BranchFolder::ID = 0;
73 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
75 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
76 /// function, updating the CFG.
77 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
78 assert(MBB->pred_empty() && "MBB must be dead!");
79 DOUT << "\nRemoving MBB: " << *MBB;
81 MachineFunction *MF = MBB->getParent();
82 // drop all successors.
83 while (!MBB->succ_empty())
84 MBB->removeSuccessor(MBB->succ_end()-1);
86 // If there is DWARF info to active, check to see if there are any LABEL
87 // records in the basic block. If so, unregister them from MachineModuleInfo.
88 if (MMI && !MBB->empty()) {
89 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
91 if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
92 // The label ID # is always operand #0, an immediate.
93 MMI->InvalidateLabel(I->getOperand(0).getImm());
99 MF->getBasicBlockList().erase(MBB);
102 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
103 TII = MF.getTarget().getInstrInfo();
104 if (!TII) return false;
106 RegInfo = MF.getTarget().getRegisterInfo();
107 RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
109 MMI = getAnalysisToUpdate<MachineModuleInfo>();
111 bool EverMadeChange = false;
112 bool MadeChangeThisIteration = true;
113 while (MadeChangeThisIteration) {
114 MadeChangeThisIteration = false;
115 MadeChangeThisIteration |= TailMergeBlocks(MF);
116 MadeChangeThisIteration |= OptimizeBranches(MF);
117 EverMadeChange |= MadeChangeThisIteration;
120 // See if any jump tables have become mergable or dead as the code generator
122 MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
123 const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
125 // Figure out how these jump tables should be merged.
126 std::vector<unsigned> JTMapping;
127 JTMapping.reserve(JTs.size());
129 // We always keep the 0th jump table.
130 JTMapping.push_back(0);
132 // Scan the jump tables, seeing if there are any duplicates. Note that this
133 // is N^2, which should be fixed someday.
134 for (unsigned i = 1, e = JTs.size(); i != e; ++i)
135 JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
137 // If a jump table was merge with another one, walk the function rewriting
138 // references to jump tables to reference the new JT ID's. Keep track of
139 // whether we see a jump table idx, if not, we can delete the JT.
140 std::vector<bool> JTIsLive;
141 JTIsLive.resize(JTs.size());
142 for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
144 for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
146 for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
147 MachineOperand &Op = I->getOperand(op);
148 if (!Op.isJumpTableIndex()) continue;
149 unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
150 Op.setJumpTableIndex(NewIdx);
152 // Remember that this JT is live.
153 JTIsLive[NewIdx] = true;
157 // Finally, remove dead jump tables. This happens either because the
158 // indirect jump was unreachable (and thus deleted) or because the jump
159 // table was merged with some other one.
160 for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
162 JTI->RemoveJumpTable(i);
163 EverMadeChange = true;
168 return EverMadeChange;
171 //===----------------------------------------------------------------------===//
172 // Tail Merging of Blocks
173 //===----------------------------------------------------------------------===//
175 /// HashMachineInstr - Compute a hash value for MI and its operands.
176 static unsigned HashMachineInstr(const MachineInstr *MI) {
177 unsigned Hash = MI->getOpcode();
178 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
179 const MachineOperand &Op = MI->getOperand(i);
181 // Merge in bits from the operand if easy.
182 unsigned OperandHash = 0;
183 switch (Op.getType()) {
184 case MachineOperand::MO_Register: OperandHash = Op.getReg(); break;
185 case MachineOperand::MO_Immediate: OperandHash = Op.getImm(); break;
186 case MachineOperand::MO_MachineBasicBlock:
187 OperandHash = Op.getMachineBasicBlock()->getNumber();
189 case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
190 case MachineOperand::MO_ConstantPoolIndex:
191 OperandHash = Op.getConstantPoolIndex();
193 case MachineOperand::MO_JumpTableIndex:
194 OperandHash = Op.getJumpTableIndex();
196 case MachineOperand::MO_GlobalAddress:
197 case MachineOperand::MO_ExternalSymbol:
198 // Global address / external symbol are too hard, don't bother, but do
199 // pull in the offset.
200 OperandHash = Op.getOffset();
205 Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
210 /// HashEndOfMBB - Hash the last two instructions in the MBB. We hash two
211 /// instructions, because cross-jumping only saves code when at least two
212 /// instructions are removed (since a branch must be inserted).
213 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
214 MachineBasicBlock::const_iterator I = MBB->end();
215 if (I == MBB->begin())
216 return 0; // Empty MBB.
219 unsigned Hash = HashMachineInstr(I);
221 if (I == MBB->begin())
222 return Hash; // Single instr MBB.
225 // Hash in the second-to-last instruction.
226 Hash ^= HashMachineInstr(I) << 2;
230 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
231 /// of instructions they actually have in common together at their end. Return
232 /// iterators for the first shared instruction in each block.
233 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
234 MachineBasicBlock *MBB2,
235 MachineBasicBlock::iterator &I1,
236 MachineBasicBlock::iterator &I2) {
240 unsigned TailLen = 0;
241 while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
243 if (!I1->isIdenticalTo(I2)) {
252 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
253 /// after it, replacing it with an unconditional branch to NewDest. This
254 /// returns true if OldInst's block is modified, false if NewDest is modified.
255 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
256 MachineBasicBlock *NewDest) {
257 MachineBasicBlock *OldBB = OldInst->getParent();
259 // Remove all the old successors of OldBB from the CFG.
260 while (!OldBB->succ_empty())
261 OldBB->removeSuccessor(OldBB->succ_begin());
263 // Remove all the dead instructions from the end of OldBB.
264 OldBB->erase(OldInst, OldBB->end());
266 // If OldBB isn't immediately before OldBB, insert a branch to it.
267 if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
268 TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
269 OldBB->addSuccessor(NewDest);
273 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
274 /// MBB so that the part before the iterator falls into the part starting at the
275 /// iterator. This returns the new MBB.
276 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
277 MachineBasicBlock::iterator BBI1) {
278 // Create the fall-through block.
279 MachineFunction::iterator MBBI = &CurMBB;
280 MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
281 CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
283 // Move all the successors of this block to the specified block.
284 while (!CurMBB.succ_empty()) {
285 MachineBasicBlock *S = *(CurMBB.succ_end()-1);
286 NewMBB->addSuccessor(S);
287 CurMBB.removeSuccessor(S);
290 // Add an edge from CurMBB to NewMBB for the fall-through.
291 CurMBB.addSuccessor(NewMBB);
293 // Splice the code over.
294 NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
296 // For targets that use the register scavenger, we must maintain LiveIns.
298 RS->enterBasicBlock(&CurMBB);
300 RS->forward(prior(CurMBB.end()));
301 BitVector RegsLiveAtExit(RegInfo->getNumRegs());
302 RS->getRegsUsed(RegsLiveAtExit, false);
303 for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
304 if (RegsLiveAtExit[i])
305 NewMBB->addLiveIn(i);
311 /// EstimateRuntime - Make a rough estimate for how long it will take to run
312 /// the specified code.
313 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
314 MachineBasicBlock::iterator E,
315 const TargetInstrInfo *TII) {
317 for (; I != E; ++I) {
318 const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
319 if (TID.Flags & M_CALL_FLAG)
321 else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
329 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
330 /// MBB2I and then insert an unconditional branch in the other block. Determine
331 /// which is the best to split
332 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
333 MachineBasicBlock::iterator MBB1I,
334 MachineBasicBlock *MBB2,
335 MachineBasicBlock::iterator MBB2I,
336 const TargetInstrInfo *TII) {
337 // TODO: if we had some notion of which block was hotter, we could split
338 // the hot block, so it is the fall-through. Since we don't have profile info
339 // make a decision based on which will hurt most to split.
340 unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
341 unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
343 // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
344 // MBB1 block so it falls through. This will penalize the MBB2 path, but will
345 // have a lower overall impact on the program execution.
346 return MBB1Time < MBB2Time;
349 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
352 if (!EnableTailMerge) return false;
354 // Find blocks with no successors.
355 std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
356 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
358 MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
361 // Sort by hash value so that blocks with identical end sequences sort
363 std::stable_sort(MergePotentials.begin(), MergePotentials.end());
365 // Walk through equivalence sets looking for actual exact matches.
366 while (MergePotentials.size() > 1) {
367 unsigned CurHash = (MergePotentials.end()-1)->first;
368 unsigned PrevHash = (MergePotentials.end()-2)->first;
369 MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
371 // If there is nothing that matches the hash of the current basic block,
373 if (CurHash != PrevHash) {
374 MergePotentials.pop_back();
378 // Determine the actual length of the shared tail between these two basic
379 // blocks. Because the hash can have collisions, it's possible that this is
381 MachineBasicBlock::iterator BBI1, BBI2;
382 unsigned CommonTailLen =
383 ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second,
386 // If the tails don't have at least two instructions in common, see if there
387 // is anything else in the equivalence class that does match.
388 if (CommonTailLen < 2) {
389 unsigned FoundMatch = ~0U;
390 for (int i = MergePotentials.size()-2;
391 i != -1 && MergePotentials[i].first == CurHash; --i) {
392 CommonTailLen = ComputeCommonTailLength(CurMBB,
393 MergePotentials[i].second,
395 if (CommonTailLen >= 2) {
401 // If we didn't find anything that has at least two instructions matching
402 // this one, bail out.
403 if (FoundMatch == ~0U) {
404 MergePotentials.pop_back();
408 // Otherwise, move the matching block to the right position.
409 std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
412 MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
414 // If neither block is the entire common tail, split the tail of one block
415 // to make it redundant with the other tail.
416 if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
417 if (0) { // Enable this to disable partial tail merges.
418 MergePotentials.pop_back();
422 // Decide whether we want to split CurMBB or MBB2.
423 if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
424 CurMBB = SplitMBBAt(*CurMBB, BBI1);
425 BBI1 = CurMBB->begin();
426 MergePotentials.back().second = CurMBB;
428 MBB2 = SplitMBBAt(*MBB2, BBI2);
429 BBI2 = MBB2->begin();
430 (MergePotentials.end()-2)->second = MBB2;
434 if (MBB2->begin() == BBI2) {
435 // Hack the end off CurMBB, making it jump to MBBI@ instead.
436 ReplaceTailWithBranchTo(BBI1, MBB2);
437 // This modifies CurMBB, so remove it from the worklist.
438 MergePotentials.pop_back();
440 assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
441 // Hack the end off MBB2, making it jump to CurMBB instead.
442 ReplaceTailWithBranchTo(BBI2, CurMBB);
443 // This modifies MBB2, so remove it from the worklist.
444 MergePotentials.erase(MergePotentials.end()-2);
453 //===----------------------------------------------------------------------===//
454 // Branch Optimization
455 //===----------------------------------------------------------------------===//
457 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
460 // Make sure blocks are numbered in order
463 for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
464 MachineBasicBlock *MBB = I++;
467 // If it is dead, remove it.
468 if (MBB->pred_empty()) {
469 RemoveDeadBlock(MBB);
478 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
479 /// CFG to be inserted. If we have proven that MBB can only branch to DestA and
480 /// DestB, remove any other MBB successors from the CFG. DestA and DestB can
482 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB,
483 MachineBasicBlock *DestA,
484 MachineBasicBlock *DestB,
486 MachineFunction::iterator FallThru) {
487 bool MadeChange = false;
488 bool AddedFallThrough = false;
490 // If this block ends with a conditional branch that falls through to its
491 // successor, set DestB as the successor.
493 if (DestB == 0 && FallThru != MBB.getParent()->end()) {
495 AddedFallThrough = true;
498 // If this is an unconditional branch with no explicit dest, it must just be
499 // a fallthrough into DestB.
500 if (DestA == 0 && FallThru != MBB.getParent()->end()) {
502 AddedFallThrough = true;
506 MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
507 while (SI != MBB.succ_end()) {
511 } else if (*SI == DestB) {
514 } else if ((*SI)->isLandingPad()) {
517 // Otherwise, this is a superfluous edge, remove it.
518 MBB.removeSuccessor(SI);
522 if (!AddedFallThrough) {
523 assert(DestA == 0 && DestB == 0 &&
524 "MachineCFG is missing edges!");
526 assert(DestA == 0 && "MachineCFG is missing edges!");
532 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
533 /// 'Old', change the code and CFG so that it branches to 'New' instead.
534 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
535 MachineBasicBlock *Old,
536 MachineBasicBlock *New,
537 const TargetInstrInfo *TII) {
538 assert(Old != New && "Cannot replace self with self!");
540 MachineBasicBlock::iterator I = BB->end();
541 while (I != BB->begin()) {
543 if (!TII->isTerminatorInstr(I->getOpcode())) break;
545 // Scan the operands of this machine instruction, replacing any uses of Old
547 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
548 if (I->getOperand(i).isMachineBasicBlock() &&
549 I->getOperand(i).getMachineBasicBlock() == Old)
550 I->getOperand(i).setMachineBasicBlock(New);
553 // Update the successor information.
554 std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
555 for (int i = Succs.size()-1; i >= 0; --i)
556 if (Succs[i] == Old) {
557 BB->removeSuccessor(Old);
558 BB->addSuccessor(New);
562 /// CanFallThrough - Return true if the specified block (with the specified
563 /// branch condition) can implicitly transfer control to the block after it by
564 /// falling off the end of it. This should return false if it can reach the
565 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
567 /// True is a conservative answer.
569 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
570 bool BranchUnAnalyzable,
571 MachineBasicBlock *TBB, MachineBasicBlock *FBB,
572 const std::vector<MachineOperand> &Cond) {
573 MachineFunction::iterator Fallthrough = CurBB;
575 // If FallthroughBlock is off the end of the function, it can't fall through.
576 if (Fallthrough == CurBB->getParent()->end())
579 // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
580 if (!CurBB->isSuccessor(Fallthrough))
583 // If we couldn't analyze the branch, assume it could fall through.
584 if (BranchUnAnalyzable) return true;
586 // If there is no branch, control always falls through.
587 if (TBB == 0) return true;
589 // If there is some explicit branch to the fallthrough block, it can obviously
590 // reach, even though the branch should get folded to fall through implicitly.
591 if (MachineFunction::iterator(TBB) == Fallthrough ||
592 MachineFunction::iterator(FBB) == Fallthrough)
595 // If it's an unconditional branch to some block not the fall through, it
596 // doesn't fall through.
597 if (Cond.empty()) return false;
599 // Otherwise, if it is conditional and has no explicit false block, it falls
604 /// CanFallThrough - Return true if the specified can implicitly transfer
605 /// control to the block after it by falling off the end of it. This should
606 /// return false if it can reach the block after it, but it uses an explicit
607 /// branch to do so (e.g. a table jump).
609 /// True is a conservative answer.
611 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
612 MachineBasicBlock *TBB = 0, *FBB = 0;
613 std::vector<MachineOperand> Cond;
614 bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
615 return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
618 /// IsBetterFallthrough - Return true if it would be clearly better to
619 /// fall-through to MBB1 than to fall through into MBB2. This has to return
620 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
621 /// result in infinite loops.
622 static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
623 MachineBasicBlock *MBB2,
624 const TargetInstrInfo &TII) {
625 // Right now, we use a simple heuristic. If MBB2 ends with a call, and
626 // MBB1 doesn't, we prefer to fall through into MBB1. This allows us to
627 // optimize branches that branch to either a return block or an assert block
628 // into a fallthrough to the return.
629 if (MBB1->empty() || MBB2->empty()) return false;
631 MachineInstr *MBB1I = --MBB1->end();
632 MachineInstr *MBB2I = --MBB2->end();
633 return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
636 /// OptimizeBlock - Analyze and optimize control flow related to the specified
637 /// block. This is never called on the entry block.
638 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
639 MachineFunction::iterator FallThrough = MBB;
642 // If this block is empty, make everyone use its fall-through, not the block
645 // Dead block? Leave for cleanup later.
646 if (MBB->pred_empty()) return;
648 if (FallThrough == MBB->getParent()->end()) {
649 // TODO: Simplify preds to not branch here if possible!
651 // Rewrite all predecessors of the old block to go to the fallthrough
653 while (!MBB->pred_empty()) {
654 MachineBasicBlock *Pred = *(MBB->pred_end()-1);
655 ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
658 // If MBB was the target of a jump table, update jump tables to go to the
659 // fallthrough instead.
660 MBB->getParent()->getJumpTableInfo()->
661 ReplaceMBBInJumpTables(MBB, FallThrough);
667 // Check to see if we can simplify the terminator of the block before this
669 MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
671 MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
672 std::vector<MachineOperand> PriorCond;
673 bool PriorUnAnalyzable =
674 TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
675 if (!PriorUnAnalyzable) {
676 // If the CFG for the prior block has extra edges, remove them.
677 MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
678 !PriorCond.empty(), MBB);
680 // If the previous branch is conditional and both conditions go to the same
681 // destination, remove the branch, replacing it with an unconditional one or
683 if (PriorTBB && PriorTBB == PriorFBB) {
684 TII->RemoveBranch(PrevBB);
687 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
690 return OptimizeBlock(MBB);
693 // If the previous branch *only* branches to *this* block (conditional or
694 // not) remove the branch.
695 if (PriorTBB == MBB && PriorFBB == 0) {
696 TII->RemoveBranch(PrevBB);
699 return OptimizeBlock(MBB);
702 // If the prior block branches somewhere else on the condition and here if
703 // the condition is false, remove the uncond second branch.
704 if (PriorFBB == MBB) {
705 TII->RemoveBranch(PrevBB);
706 TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
709 return OptimizeBlock(MBB);
712 // If the prior block branches here on true and somewhere else on false, and
713 // if the branch condition is reversible, reverse the branch to create a
715 if (PriorTBB == MBB) {
716 std::vector<MachineOperand> NewPriorCond(PriorCond);
717 if (!TII->ReverseBranchCondition(NewPriorCond)) {
718 TII->RemoveBranch(PrevBB);
719 TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
722 return OptimizeBlock(MBB);
726 // If this block doesn't fall through (e.g. it ends with an uncond branch or
727 // has no successors) and if the pred falls through into this block, and if
728 // it would otherwise fall through into the block after this, move this
729 // block to the end of the function.
731 // We consider it more likely that execution will stay in the function (e.g.
732 // due to loops) than it is to exit it. This asserts in loops etc, moving
733 // the assert condition out of the loop body.
734 if (!PriorCond.empty() && PriorFBB == 0 &&
735 MachineFunction::iterator(PriorTBB) == FallThrough &&
736 !CanFallThrough(MBB)) {
737 bool DoTransform = true;
739 // We have to be careful that the succs of PredBB aren't both no-successor
740 // blocks. If neither have successors and if PredBB is the second from
741 // last block in the function, we'd just keep swapping the two blocks for
742 // last. Only do the swap if one is clearly better to fall through than
744 if (FallThrough == --MBB->getParent()->end() &&
745 !IsBetterFallthrough(PriorTBB, MBB, *TII))
748 // We don't want to do this transformation if we have control flow like:
757 // In this case, we could actually be moving the return block *into* a
759 if (DoTransform && !MBB->succ_empty() &&
760 (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
765 // Reverse the branch so we will fall through on the previous true cond.
766 std::vector<MachineOperand> NewPriorCond(PriorCond);
767 if (!TII->ReverseBranchCondition(NewPriorCond)) {
768 DOUT << "\nMoving MBB: " << *MBB;
769 DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
771 TII->RemoveBranch(PrevBB);
772 TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
774 // Move this block to the end of the function.
775 MBB->moveAfter(--MBB->getParent()->end());
784 // Analyze the branch in the current block.
785 MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
786 std::vector<MachineOperand> CurCond;
787 bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
788 if (!CurUnAnalyzable) {
789 // If the CFG for the prior block has extra edges, remove them.
790 MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
792 ++MachineFunction::iterator(MBB));
794 // If this is a two-way branch, and the FBB branches to this block, reverse
795 // the condition so the single-basic-block loop is faster. Instead of:
796 // Loop: xxx; jcc Out; jmp Loop
798 // Loop: xxx; jncc Loop; jmp Out
799 if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
800 std::vector<MachineOperand> NewCond(CurCond);
801 if (!TII->ReverseBranchCondition(NewCond)) {
802 TII->RemoveBranch(*MBB);
803 TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
806 return OptimizeBlock(MBB);
811 // If this branch is the only thing in its block, see if we can forward
812 // other blocks across it.
813 if (CurTBB && CurCond.empty() && CurFBB == 0 &&
814 TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
815 // This block may contain just an unconditional branch. Because there can
816 // be 'non-branch terminators' in the block, try removing the branch and
817 // then seeing if the block is empty.
818 TII->RemoveBranch(*MBB);
820 // If this block is just an unconditional branch to CurTBB, we can
821 // usually completely eliminate the block. The only case we cannot
822 // completely eliminate the block is when the block before this one
823 // falls through into MBB and we can't understand the prior block's branch
826 bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
827 if (PredHasNoFallThrough || !PriorUnAnalyzable ||
828 !PrevBB.isSuccessor(MBB)) {
829 // If the prior block falls through into us, turn it into an
830 // explicit branch to us to make updates simpler.
831 if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
832 PriorTBB != MBB && PriorFBB != MBB) {
834 assert(PriorCond.empty() && PriorFBB == 0 &&
835 "Bad branch analysis");
838 assert(PriorFBB == 0 && "Machine CFG out of date!");
841 TII->RemoveBranch(PrevBB);
842 TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
845 // Iterate through all the predecessors, revectoring each in-turn.
846 MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
847 bool DidChange = false;
848 bool HasBranchToSelf = false;
849 while (PI != MBB->pred_end()) {
851 // If this block has an uncond branch to itself, leave it.
853 HasBranchToSelf = true;
856 ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
860 // Change any jumptables to go to the new MBB.
861 MBB->getParent()->getJumpTableInfo()->
862 ReplaceMBBInJumpTables(MBB, CurTBB);
866 if (!HasBranchToSelf) return;
871 // Add the branch back if the block is more than just an uncond branch.
872 TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
876 // If the prior block doesn't fall through into this block, and if this
877 // block doesn't fall through into some other block, see if we can find a
878 // place to move this block where a fall-through will happen.
879 if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
880 PriorTBB, PriorFBB, PriorCond)) {
881 // Now we know that there was no fall-through into this block, check to
882 // see if it has a fall-through into its successor.
883 bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
886 if (!MBB->isLandingPad()) {
887 // Check all the predecessors of this block. If one of them has no fall
888 // throughs, move this block right after it.
889 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
890 E = MBB->pred_end(); PI != E; ++PI) {
891 // Analyze the branch at the end of the pred.
892 MachineBasicBlock *PredBB = *PI;
893 MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
894 if (PredBB != MBB && !CanFallThrough(PredBB)
895 && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
896 // If the current block doesn't fall through, just move it.
897 // If the current block can fall through and does not end with a
898 // conditional branch, we need to append an unconditional jump to
899 // the (current) next block. To avoid a possible compile-time
900 // infinite loop, move blocks only backward in this case.
902 MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
904 TII->InsertBranch(*MBB, NextBB, 0, CurCond);
906 MBB->moveAfter(PredBB);
908 return OptimizeBlock(MBB);
914 // Check all successors to see if we can move this block before it.
915 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
916 E = MBB->succ_end(); SI != E; ++SI) {
917 // Analyze the branch at the end of the block before the succ.
918 MachineBasicBlock *SuccBB = *SI;
919 MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
920 std::vector<MachineOperand> SuccPrevCond;
922 // If this block doesn't already fall-through to that successor, and if
923 // the succ doesn't already have a block that can fall through into it,
924 // and if the successor isn't an EH destination, we can arrange for the
925 // fallthrough to happen.
926 if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
927 !SuccBB->isLandingPad()) {
928 MBB->moveBefore(SuccBB);
930 return OptimizeBlock(MBB);
934 // Okay, there is no really great place to put this block. If, however,
935 // the block before this one would be a fall-through if this block were
936 // removed, move this block to the end of the function.
937 if (FallThrough != MBB->getParent()->end() &&
938 PrevBB.isSuccessor(FallThrough)) {
939 MBB->moveAfter(--MBB->getParent()->end());