BranchFolding.cpp revision 1e57df3b4fd69b2a316d8931dee1b9e033ae3a9a
1//===-- BranchFolding.cpp - Fold machine code branch instructions ---------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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
12// it then removes.
13//
14// Note that this pass must be run after register allocation, it cannot handle
15// SSA form.
16//
17//===----------------------------------------------------------------------===//
18
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/Statistic.h"
31#include "llvm/ADT/STLExtras.h"
32#include <algorithm>
33using namespace llvm;
34
35STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
36STATISTIC(NumBranchOpts, "Number of branches optimized");
37STATISTIC(NumTailMerge , "Number of block tails merged");
38static cl::opt<cl::boolOrDefault> FlagEnableTailMerge("enable-tail-merge",
39                              cl::init(cl::BOU_UNSET), cl::Hidden);
40namespace {
41  // Throttle for huge numbers of predecessors (compile speed problems)
42  cl::opt<unsigned>
43  TailMergeThreshold("tail-merge-threshold",
44            cl::desc("Max number of predecessors to consider tail merging"),
45            cl::init(100), cl::Hidden);
46
47  struct BranchFolder : public MachineFunctionPass {
48    static char ID;
49    explicit BranchFolder(bool defaultEnableTailMerge) :
50        MachineFunctionPass((intptr_t)&ID) {
51          switch (FlagEnableTailMerge) {
52          case cl::BOU_UNSET: EnableTailMerge = defaultEnableTailMerge; break;
53          case cl::BOU_TRUE: EnableTailMerge = true; break;
54          case cl::BOU_FALSE: EnableTailMerge = false; break;
55          }
56    }
57
58    virtual bool runOnMachineFunction(MachineFunction &MF);
59    virtual const char *getPassName() const { return "Control Flow Optimizer"; }
60    const TargetInstrInfo *TII;
61    MachineModuleInfo *MMI;
62    bool MadeChange;
63  private:
64    // Tail Merging.
65    bool EnableTailMerge;
66    bool TailMergeBlocks(MachineFunction &MF);
67    bool TryMergeBlocks(MachineBasicBlock* SuccBB,
68                        MachineBasicBlock* PredBB);
69    void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
70                                 MachineBasicBlock *NewDest);
71    MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
72                                  MachineBasicBlock::iterator BBI1);
73
74    std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
75    const TargetRegisterInfo *RegInfo;
76    RegScavenger *RS;
77    // Branch optzn.
78    bool OptimizeBranches(MachineFunction &MF);
79    void OptimizeBlock(MachineBasicBlock *MBB);
80    void RemoveDeadBlock(MachineBasicBlock *MBB);
81
82    bool CanFallThrough(MachineBasicBlock *CurBB);
83    bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
84                        MachineBasicBlock *TBB, MachineBasicBlock *FBB,
85                        const std::vector<MachineOperand> &Cond);
86  };
87  char BranchFolder::ID = 0;
88}
89
90FunctionPass *llvm::createBranchFoldingPass(bool DefaultEnableTailMerge) {
91      return new BranchFolder(DefaultEnableTailMerge); }
92
93/// RemoveDeadBlock - Remove the specified dead machine basic block from the
94/// function, updating the CFG.
95void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
96  assert(MBB->pred_empty() && "MBB must be dead!");
97  DOUT << "\nRemoving MBB: " << *MBB;
98
99  MachineFunction *MF = MBB->getParent();
100  // drop all successors.
101  while (!MBB->succ_empty())
102    MBB->removeSuccessor(MBB->succ_end()-1);
103
104  // If there is DWARF info to active, check to see if there are any LABEL
105  // records in the basic block.  If so, unregister them from MachineModuleInfo.
106  if (MMI && !MBB->empty()) {
107    for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
108         I != E; ++I) {
109      if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
110        // The label ID # is always operand #0, an immediate.
111        MMI->InvalidateLabel(I->getOperand(0).getImm());
112      }
113    }
114  }
115
116  // Remove the block.
117  MF->getBasicBlockList().erase(MBB);
118}
119
120bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
121  TII = MF.getTarget().getInstrInfo();
122  if (!TII) return false;
123
124  // Fix CFG.  The later algorithms expect it to be right.
125  bool EverMadeChange = false;
126  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; I++) {
127    MachineBasicBlock *MBB = I, *TBB = 0, *FBB = 0;
128    std::vector<MachineOperand> Cond;
129    if (!TII->AnalyzeBranch(*MBB, TBB, FBB, Cond))
130      EverMadeChange |= MBB->CorrectExtraCFGEdges(TBB, FBB, !Cond.empty());
131  }
132
133  RegInfo = MF.getTarget().getRegisterInfo();
134  RS = RegInfo->requiresRegisterScavenging(MF) ? new RegScavenger() : NULL;
135
136  MMI = getAnalysisToUpdate<MachineModuleInfo>();
137
138  bool MadeChangeThisIteration = true;
139  while (MadeChangeThisIteration) {
140    MadeChangeThisIteration = false;
141    MadeChangeThisIteration |= TailMergeBlocks(MF);
142    MadeChangeThisIteration |= OptimizeBranches(MF);
143    EverMadeChange |= MadeChangeThisIteration;
144  }
145
146  // See if any jump tables have become mergable or dead as the code generator
147  // did its thing.
148  MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
149  const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
150  if (!JTs.empty()) {
151    // Figure out how these jump tables should be merged.
152    std::vector<unsigned> JTMapping;
153    JTMapping.reserve(JTs.size());
154
155    // We always keep the 0th jump table.
156    JTMapping.push_back(0);
157
158    // Scan the jump tables, seeing if there are any duplicates.  Note that this
159    // is N^2, which should be fixed someday.
160    for (unsigned i = 1, e = JTs.size(); i != e; ++i)
161      JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
162
163    // If a jump table was merge with another one, walk the function rewriting
164    // references to jump tables to reference the new JT ID's.  Keep track of
165    // whether we see a jump table idx, if not, we can delete the JT.
166    std::vector<bool> JTIsLive;
167    JTIsLive.resize(JTs.size());
168    for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
169         BB != E; ++BB) {
170      for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
171           I != E; ++I)
172        for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
173          MachineOperand &Op = I->getOperand(op);
174          if (!Op.isJumpTableIndex()) continue;
175          unsigned NewIdx = JTMapping[Op.getIndex()];
176          Op.setIndex(NewIdx);
177
178          // Remember that this JT is live.
179          JTIsLive[NewIdx] = true;
180        }
181    }
182
183    // Finally, remove dead jump tables.  This happens either because the
184    // indirect jump was unreachable (and thus deleted) or because the jump
185    // table was merged with some other one.
186    for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
187      if (!JTIsLive[i]) {
188        JTI->RemoveJumpTable(i);
189        EverMadeChange = true;
190      }
191  }
192
193  delete RS;
194  return EverMadeChange;
195}
196
197//===----------------------------------------------------------------------===//
198//  Tail Merging of Blocks
199//===----------------------------------------------------------------------===//
200
201/// HashMachineInstr - Compute a hash value for MI and its operands.
202static unsigned HashMachineInstr(const MachineInstr *MI) {
203  unsigned Hash = MI->getOpcode();
204  for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
205    const MachineOperand &Op = MI->getOperand(i);
206
207    // Merge in bits from the operand if easy.
208    unsigned OperandHash = 0;
209    switch (Op.getType()) {
210    case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
211    case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
212    case MachineOperand::MO_MachineBasicBlock:
213      OperandHash = Op.getMBB()->getNumber();
214      break;
215    case MachineOperand::MO_FrameIndex:
216    case MachineOperand::MO_ConstantPoolIndex:
217    case MachineOperand::MO_JumpTableIndex:
218      OperandHash = Op.getIndex();
219      break;
220    case MachineOperand::MO_GlobalAddress:
221    case MachineOperand::MO_ExternalSymbol:
222      // Global address / external symbol are too hard, don't bother, but do
223      // pull in the offset.
224      OperandHash = Op.getOffset();
225      break;
226    default: break;
227    }
228
229    Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
230  }
231  return Hash;
232}
233
234/// HashEndOfMBB - Hash the last few instructions in the MBB.  For blocks
235/// with no successors, we hash two instructions, because cross-jumping
236/// only saves code when at least two instructions are removed (since a
237/// branch must be inserted).  For blocks with a successor, one of the
238/// two blocks to be tail-merged will end with a branch already, so
239/// it gains to cross-jump even for one instruction.
240
241static unsigned HashEndOfMBB(const MachineBasicBlock *MBB,
242                             unsigned minCommonTailLength) {
243  MachineBasicBlock::const_iterator I = MBB->end();
244  if (I == MBB->begin())
245    return 0;   // Empty MBB.
246
247  --I;
248  unsigned Hash = HashMachineInstr(I);
249
250  if (I == MBB->begin() || minCommonTailLength == 1)
251    return Hash;   // Single instr MBB.
252
253  --I;
254  // Hash in the second-to-last instruction.
255  Hash ^= HashMachineInstr(I) << 2;
256  return Hash;
257}
258
259/// ComputeCommonTailLength - Given two machine basic blocks, compute the number
260/// of instructions they actually have in common together at their end.  Return
261/// iterators for the first shared instruction in each block.
262static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
263                                        MachineBasicBlock *MBB2,
264                                        MachineBasicBlock::iterator &I1,
265                                        MachineBasicBlock::iterator &I2) {
266  I1 = MBB1->end();
267  I2 = MBB2->end();
268
269  unsigned TailLen = 0;
270  while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
271    --I1; --I2;
272    if (!I1->isIdenticalTo(I2) ||
273        // FIXME: This check is dubious. It's used to get around a problem where
274        // people incorrectly expect inline asm directives to remain in the same
275        // relative order. This is untenable because normal compiler
276        // optimizations (like this one) may reorder and/or merge these
277        // directives.
278        I1->getOpcode() == TargetInstrInfo::INLINEASM) {
279      ++I1; ++I2;
280      break;
281    }
282    ++TailLen;
283  }
284  return TailLen;
285}
286
287/// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
288/// after it, replacing it with an unconditional branch to NewDest.  This
289/// returns true if OldInst's block is modified, false if NewDest is modified.
290void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
291                                           MachineBasicBlock *NewDest) {
292  MachineBasicBlock *OldBB = OldInst->getParent();
293
294  // Remove all the old successors of OldBB from the CFG.
295  while (!OldBB->succ_empty())
296    OldBB->removeSuccessor(OldBB->succ_begin());
297
298  // Remove all the dead instructions from the end of OldBB.
299  OldBB->erase(OldInst, OldBB->end());
300
301  // If OldBB isn't immediately before OldBB, insert a branch to it.
302  if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
303    TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
304  OldBB->addSuccessor(NewDest);
305  ++NumTailMerge;
306}
307
308/// SplitMBBAt - Given a machine basic block and an iterator into it, split the
309/// MBB so that the part before the iterator falls into the part starting at the
310/// iterator.  This returns the new MBB.
311MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
312                                            MachineBasicBlock::iterator BBI1) {
313  // Create the fall-through block.
314  MachineFunction::iterator MBBI = &CurMBB;
315  MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
316  CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
317
318  // Move all the successors of this block to the specified block.
319  while (!CurMBB.succ_empty()) {
320    MachineBasicBlock *S = *(CurMBB.succ_end()-1);
321    NewMBB->addSuccessor(S);
322    CurMBB.removeSuccessor(S);
323  }
324
325  // Add an edge from CurMBB to NewMBB for the fall-through.
326  CurMBB.addSuccessor(NewMBB);
327
328  // Splice the code over.
329  NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
330
331  // For targets that use the register scavenger, we must maintain LiveIns.
332  if (RS) {
333    RS->enterBasicBlock(&CurMBB);
334    if (!CurMBB.empty())
335      RS->forward(prior(CurMBB.end()));
336    BitVector RegsLiveAtExit(RegInfo->getNumRegs());
337    RS->getRegsUsed(RegsLiveAtExit, false);
338    for (unsigned int i=0, e=RegInfo->getNumRegs(); i!=e; i++)
339      if (RegsLiveAtExit[i])
340        NewMBB->addLiveIn(i);
341  }
342
343  return NewMBB;
344}
345
346/// EstimateRuntime - Make a rough estimate for how long it will take to run
347/// the specified code.
348static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
349                                MachineBasicBlock::iterator E) {
350  unsigned Time = 0;
351  for (; I != E; ++I) {
352    const TargetInstrDesc &TID = I->getDesc();
353    if (TID.isCall())
354      Time += 10;
355    else if (TID.isSimpleLoad() || TID.mayStore())
356      Time += 2;
357    else
358      ++Time;
359  }
360  return Time;
361}
362
363/// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
364/// MBB2I and then insert an unconditional branch in the other block.  Determine
365/// which is the best to split
366static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
367                                  MachineBasicBlock::iterator MBB1I,
368                                  MachineBasicBlock *MBB2,
369                                  MachineBasicBlock::iterator MBB2I,
370                                  MachineBasicBlock *PredBB) {
371  // If one block is the entry block, split the other one; we can't generate
372  // a branch to the entry block, as its label is not emitted.
373  MachineBasicBlock *Entry = MBB1->getParent()->begin();
374  if (MBB1 == Entry)
375    return false;
376  if (MBB2 == Entry)
377    return true;
378
379  // If one block falls through into the common successor, choose that
380  // one to split; it is one instruction less to do that.
381  if (PredBB) {
382    if (MBB1 == PredBB)
383      return true;
384    else if (MBB2 == PredBB)
385      return false;
386  }
387  // TODO: if we had some notion of which block was hotter, we could split
388  // the hot block, so it is the fall-through.  Since we don't have profile info
389  // make a decision based on which will hurt most to split.
390  unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I);
391  unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I);
392
393  // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
394  // MBB1 block so it falls through.  This will penalize the MBB2 path, but will
395  // have a lower overall impact on the program execution.
396  return MBB1Time < MBB2Time;
397}
398
399// CurMBB needs to add an unconditional branch to SuccMBB (we removed these
400// branches temporarily for tail merging).  In the case where CurMBB ends
401// with a conditional branch to the next block, optimize by reversing the
402// test and conditionally branching to SuccMBB instead.
403
404static void FixTail(MachineBasicBlock* CurMBB, MachineBasicBlock *SuccBB,
405                    const TargetInstrInfo *TII) {
406  MachineFunction *MF = CurMBB->getParent();
407  MachineFunction::iterator I = next(MachineFunction::iterator(CurMBB));
408  MachineBasicBlock *TBB = 0, *FBB = 0;
409  std::vector<MachineOperand> Cond;
410  if (I != MF->end() &&
411      !TII->AnalyzeBranch(*CurMBB, TBB, FBB, Cond)) {
412    MachineBasicBlock *NextBB = I;
413    if (TBB == NextBB && Cond.size() && !FBB) {
414      if (!TII->ReverseBranchCondition(Cond)) {
415        TII->RemoveBranch(*CurMBB);
416        TII->InsertBranch(*CurMBB, SuccBB, NULL, Cond);
417        return;
418      }
419    }
420  }
421  TII->InsertBranch(*CurMBB, SuccBB, NULL, std::vector<MachineOperand>());
422}
423
424static bool MergeCompare(const std::pair<unsigned,MachineBasicBlock*> &p,
425                         const std::pair<unsigned,MachineBasicBlock*> &q) {
426    if (p.first < q.first)
427      return true;
428     else if (p.first > q.first)
429      return false;
430    else if (p.second->getNumber() < q.second->getNumber())
431      return true;
432    else if (p.second->getNumber() > q.second->getNumber())
433      return false;
434    else {
435      // _GLIBCXX_DEBUG checks strict weak ordering, which involves comparing
436      // an object with itself.
437#ifndef _GLIBCXX_DEBUG
438      assert(0 && "Predecessor appears twice");
439#endif
440      return(false);
441    }
442}
443
444// See if any of the blocks in MergePotentials (which all have a common single
445// successor, or all have no successor) can be tail-merged.  If there is a
446// successor, any blocks in MergePotentials that are not tail-merged and
447// are not immediately before Succ must have an unconditional branch to
448// Succ added (but the predecessor/successor lists need no adjustment).
449// The lone predecessor of Succ that falls through into Succ,
450// if any, is given in PredBB.
451
452bool BranchFolder::TryMergeBlocks(MachineBasicBlock *SuccBB,
453                                  MachineBasicBlock* PredBB) {
454  unsigned minCommonTailLength = (SuccBB ? 1 : 2);
455  MadeChange = false;
456
457  // Sort by hash value so that blocks with identical end sequences sort
458  // together.
459  std::stable_sort(MergePotentials.begin(), MergePotentials.end(), MergeCompare);
460
461  // Walk through equivalence sets looking for actual exact matches.
462  while (MergePotentials.size() > 1) {
463    unsigned CurHash  = (MergePotentials.end()-1)->first;
464    unsigned PrevHash = (MergePotentials.end()-2)->first;
465    MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
466
467    // If there is nothing that matches the hash of the current basic block,
468    // give up.
469    if (CurHash != PrevHash) {
470      if (SuccBB && CurMBB != PredBB)
471        FixTail(CurMBB, SuccBB, TII);
472      MergePotentials.pop_back();
473      continue;
474    }
475
476    // Look through all the pairs of blocks that have the same hash as this
477    // one, and find the pair that has the largest number of instructions in
478    // common.
479     // Since instructions may get combined later (e.g. single stores into
480    // store multiple) this measure is not particularly accurate.
481   MachineBasicBlock::iterator BBI1, BBI2;
482
483    unsigned FoundI = ~0U, FoundJ = ~0U;
484    unsigned maxCommonTailLength = 0U;
485    for (int i = MergePotentials.size()-1;
486         i != -1 && MergePotentials[i].first == CurHash; --i) {
487      for (int j = i-1;
488           j != -1 && MergePotentials[j].first == CurHash; --j) {
489        MachineBasicBlock::iterator TrialBBI1, TrialBBI2;
490        unsigned CommonTailLen = ComputeCommonTailLength(
491                                                MergePotentials[i].second,
492                                                MergePotentials[j].second,
493                                                TrialBBI1, TrialBBI2);
494        if (CommonTailLen >= minCommonTailLength &&
495            CommonTailLen > maxCommonTailLength) {
496          FoundI = i;
497          FoundJ = j;
498          maxCommonTailLength = CommonTailLen;
499          BBI1 = TrialBBI1;
500          BBI2 = TrialBBI2;
501        }
502      }
503    }
504
505    // If we didn't find any pair that has at least minCommonTailLength
506    // instructions in common, bail out.  All entries with this
507    // hash code can go away now.
508    if (FoundI == ~0U) {
509      for (int i = MergePotentials.size()-1;
510           i != -1 && MergePotentials[i].first == CurHash; --i) {
511        // Put the unconditional branch back, if we need one.
512        CurMBB = MergePotentials[i].second;
513        if (SuccBB && CurMBB != PredBB)
514          FixTail(CurMBB, SuccBB, TII);
515        MergePotentials.pop_back();
516      }
517      continue;
518    }
519
520    // Otherwise, move the block(s) to the right position(s).  So that
521    // BBI1/2 will be valid, the last must be I and the next-to-last J.
522    if (FoundI != MergePotentials.size()-1)
523      std::swap(MergePotentials[FoundI], *(MergePotentials.end()-1));
524    if (FoundJ != MergePotentials.size()-2)
525      std::swap(MergePotentials[FoundJ], *(MergePotentials.end()-2));
526
527    CurMBB = (MergePotentials.end()-1)->second;
528    MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
529
530    // If neither block is the entire common tail, split the tail of one block
531    // to make it redundant with the other tail.  Also, we cannot jump to the
532    // entry block, so if one block is the entry block, split the other one.
533    MachineBasicBlock *Entry = CurMBB->getParent()->begin();
534    if (CurMBB->begin() == BBI1 && CurMBB != Entry)
535      ;   // CurMBB is common tail
536    else if (MBB2->begin() == BBI2 && MBB2 != Entry)
537      ;   // MBB2 is common tail
538    else {
539      if (0) { // Enable this to disable partial tail merges.
540        MergePotentials.pop_back();
541        continue;
542      }
543
544      // Decide whether we want to split CurMBB or MBB2.
545      if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, PredBB)) {
546        CurMBB = SplitMBBAt(*CurMBB, BBI1);
547        BBI1 = CurMBB->begin();
548        MergePotentials.back().second = CurMBB;
549      } else {
550        MBB2 = SplitMBBAt(*MBB2, BBI2);
551        BBI2 = MBB2->begin();
552        (MergePotentials.end()-2)->second = MBB2;
553      }
554    }
555
556    if (MBB2->begin() == BBI2 && MBB2 != Entry) {
557      // Hack the end off CurMBB, making it jump to MBBI@ instead.
558      ReplaceTailWithBranchTo(BBI1, MBB2);
559      // This modifies CurMBB, so remove it from the worklist.
560      MergePotentials.pop_back();
561    } else {
562      assert(CurMBB->begin() == BBI1 && CurMBB != Entry &&
563             "Didn't split block correctly?");
564      // Hack the end off MBB2, making it jump to CurMBB instead.
565      ReplaceTailWithBranchTo(BBI2, CurMBB);
566      // This modifies MBB2, so remove it from the worklist.
567      MergePotentials.erase(MergePotentials.end()-2);
568    }
569    MadeChange = true;
570  }
571  return MadeChange;
572}
573
574bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
575
576  if (!EnableTailMerge) return false;
577
578  MadeChange = false;
579
580  // First find blocks with no successors.
581  MergePotentials.clear();
582  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
583    if (I->succ_empty())
584      MergePotentials.push_back(std::make_pair(HashEndOfMBB(I, 2U), I));
585  }
586  // See if we can do any tail merging on those.
587  if (MergePotentials.size() < TailMergeThreshold)
588    MadeChange |= TryMergeBlocks(NULL, NULL);
589
590  // Look at blocks (IBB) with multiple predecessors (PBB).
591  // We change each predecessor to a canonical form, by
592  // (1) temporarily removing any unconditional branch from the predecessor
593  // to IBB, and
594  // (2) alter conditional branches so they branch to the other block
595  // not IBB; this may require adding back an unconditional branch to IBB
596  // later, where there wasn't one coming in.  E.g.
597  //   Bcc IBB
598  //   fallthrough to QBB
599  // here becomes
600  //   Bncc QBB
601  // with a conceptual B to IBB after that, which never actually exists.
602  // With those changes, we see whether the predecessors' tails match,
603  // and merge them if so.  We change things out of canonical form and
604  // back to the way they were later in the process.  (OptimizeBranches
605  // would undo some of this, but we can't use it, because we'd get into
606  // a compile-time infinite loop repeatedly doing and undoing the same
607  // transformations.)
608
609  for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
610    if (!I->succ_empty() && I->pred_size() >= 2 &&
611         I->pred_size() < TailMergeThreshold) {
612      MachineBasicBlock *IBB = I;
613      MachineBasicBlock *PredBB = prior(I);
614      MergePotentials.clear();
615      for (MachineBasicBlock::pred_iterator P = I->pred_begin(),
616                                            E2 = I->pred_end();
617           P != E2; ++P) {
618        MachineBasicBlock* PBB = *P;
619        // Skip blocks that loop to themselves, can't tail merge these.
620        if (PBB==IBB)
621          continue;
622        MachineBasicBlock *TBB = 0, *FBB = 0;
623        std::vector<MachineOperand> Cond;
624        if (!TII->AnalyzeBranch(*PBB, TBB, FBB, Cond)) {
625          // Failing case:  IBB is the target of a cbr, and
626          // we cannot reverse the branch.
627          std::vector<MachineOperand> NewCond(Cond);
628          if (Cond.size() && TBB==IBB) {
629            if (TII->ReverseBranchCondition(NewCond))
630              continue;
631            // This is the QBB case described above
632            if (!FBB)
633              FBB = next(MachineFunction::iterator(PBB));
634          }
635          // Failing case:  the only way IBB can be reached from PBB is via
636          // exception handling.  Happens for landing pads.  Would be nice
637          // to have a bit in the edge so we didn't have to do all this.
638          if (IBB->isLandingPad()) {
639            MachineFunction::iterator IP = PBB;  IP++;
640            MachineBasicBlock* PredNextBB = NULL;
641            if (IP!=MF.end())
642              PredNextBB = IP;
643            if (TBB==NULL) {
644              if (IBB!=PredNextBB)      // fallthrough
645                continue;
646            } else if (FBB) {
647              if (TBB!=IBB && FBB!=IBB)   // cbr then ubr
648                continue;
649            } else if (Cond.empty()) {
650              if (TBB!=IBB)               // ubr
651                continue;
652            } else {
653              if (TBB!=IBB && IBB!=PredNextBB)  // cbr
654                continue;
655            }
656          }
657          // Remove the unconditional branch at the end, if any.
658          if (TBB && (Cond.size()==0 || FBB)) {
659            TII->RemoveBranch(*PBB);
660            if (Cond.size())
661              // reinsert conditional branch only, for now
662              TII->InsertBranch(*PBB, (TBB==IBB) ? FBB : TBB, 0, NewCond);
663          }
664          MergePotentials.push_back(std::make_pair(HashEndOfMBB(PBB, 1U), *P));
665        }
666      }
667    if (MergePotentials.size() >= 2)
668      MadeChange |= TryMergeBlocks(I, PredBB);
669    // Reinsert an unconditional branch if needed.
670    // The 1 below can be either an original single predecessor, or a result
671    // of removing blocks in TryMergeBlocks.
672    PredBB = prior(I);      // this may have been changed in TryMergeBlocks
673    if (MergePotentials.size()==1 &&
674        (MergePotentials.begin())->second != PredBB)
675      FixTail((MergePotentials.begin())->second, I, TII);
676    }
677  }
678  return MadeChange;
679}
680
681//===----------------------------------------------------------------------===//
682//  Branch Optimization
683//===----------------------------------------------------------------------===//
684
685bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
686  MadeChange = false;
687
688  // Make sure blocks are numbered in order
689  MF.RenumberBlocks();
690
691  for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
692    MachineBasicBlock *MBB = I++;
693    OptimizeBlock(MBB);
694
695    // If it is dead, remove it.
696    if (MBB->pred_empty()) {
697      RemoveDeadBlock(MBB);
698      MadeChange = true;
699      ++NumDeadBlocks;
700    }
701  }
702  return MadeChange;
703}
704
705
706/// CanFallThrough - Return true if the specified block (with the specified
707/// branch condition) can implicitly transfer control to the block after it by
708/// falling off the end of it.  This should return false if it can reach the
709/// block after it, but it uses an explicit branch to do so (e.g. a table jump).
710///
711/// True is a conservative answer.
712///
713bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
714                                  bool BranchUnAnalyzable,
715                                  MachineBasicBlock *TBB, MachineBasicBlock *FBB,
716                                  const std::vector<MachineOperand> &Cond) {
717  MachineFunction::iterator Fallthrough = CurBB;
718  ++Fallthrough;
719  // If FallthroughBlock is off the end of the function, it can't fall through.
720  if (Fallthrough == CurBB->getParent()->end())
721    return false;
722
723  // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
724  if (!CurBB->isSuccessor(Fallthrough))
725    return false;
726
727  // If we couldn't analyze the branch, assume it could fall through.
728  if (BranchUnAnalyzable) return true;
729
730  // If there is no branch, control always falls through.
731  if (TBB == 0) return true;
732
733  // If there is some explicit branch to the fallthrough block, it can obviously
734  // reach, even though the branch should get folded to fall through implicitly.
735  if (MachineFunction::iterator(TBB) == Fallthrough ||
736      MachineFunction::iterator(FBB) == Fallthrough)
737    return true;
738
739  // If it's an unconditional branch to some block not the fall through, it
740  // doesn't fall through.
741  if (Cond.empty()) return false;
742
743  // Otherwise, if it is conditional and has no explicit false block, it falls
744  // through.
745  return FBB == 0;
746}
747
748/// CanFallThrough - Return true if the specified can implicitly transfer
749/// control to the block after it by falling off the end of it.  This should
750/// return false if it can reach the block after it, but it uses an explicit
751/// branch to do so (e.g. a table jump).
752///
753/// True is a conservative answer.
754///
755bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
756  MachineBasicBlock *TBB = 0, *FBB = 0;
757  std::vector<MachineOperand> Cond;
758  bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
759  return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
760}
761
762/// IsBetterFallthrough - Return true if it would be clearly better to
763/// fall-through to MBB1 than to fall through into MBB2.  This has to return
764/// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
765/// result in infinite loops.
766static bool IsBetterFallthrough(MachineBasicBlock *MBB1,
767                                MachineBasicBlock *MBB2) {
768  // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
769  // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
770  // optimize branches that branch to either a return block or an assert block
771  // into a fallthrough to the return.
772  if (MBB1->empty() || MBB2->empty()) return false;
773
774  // If there is a clear successor ordering we make sure that one block
775  // will fall through to the next
776  if (MBB1->isSuccessor(MBB2)) return true;
777  if (MBB2->isSuccessor(MBB1)) return false;
778
779  MachineInstr *MBB1I = --MBB1->end();
780  MachineInstr *MBB2I = --MBB2->end();
781  return MBB2I->getDesc().isCall() && !MBB1I->getDesc().isCall();
782}
783
784/// OptimizeBlock - Analyze and optimize control flow related to the specified
785/// block.  This is never called on the entry block.
786void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
787  MachineFunction::iterator FallThrough = MBB;
788  ++FallThrough;
789
790  // If this block is empty, make everyone use its fall-through, not the block
791  // explicitly.  Landing pads should not do this since the landing-pad table
792  // points to this block.
793  if (MBB->empty() && !MBB->isLandingPad()) {
794    // Dead block?  Leave for cleanup later.
795    if (MBB->pred_empty()) return;
796
797    if (FallThrough == MBB->getParent()->end()) {
798      // TODO: Simplify preds to not branch here if possible!
799    } else {
800      // Rewrite all predecessors of the old block to go to the fallthrough
801      // instead.
802      while (!MBB->pred_empty()) {
803        MachineBasicBlock *Pred = *(MBB->pred_end()-1);
804        Pred->ReplaceUsesOfBlockWith(MBB, FallThrough);
805      }
806
807      // If MBB was the target of a jump table, update jump tables to go to the
808      // fallthrough instead.
809      MBB->getParent()->getJumpTableInfo()->
810        ReplaceMBBInJumpTables(MBB, FallThrough);
811      MadeChange = true;
812    }
813    return;
814  }
815
816  // Check to see if we can simplify the terminator of the block before this
817  // one.
818  MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
819
820  MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
821  std::vector<MachineOperand> PriorCond;
822  bool PriorUnAnalyzable =
823    TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
824  if (!PriorUnAnalyzable) {
825    // If the CFG for the prior block has extra edges, remove them.
826    MadeChange |= PrevBB.CorrectExtraCFGEdges(PriorTBB, PriorFBB,
827                                              !PriorCond.empty());
828
829    // If the previous branch is conditional and both conditions go to the same
830    // destination, remove the branch, replacing it with an unconditional one or
831    // a fall-through.
832    if (PriorTBB && PriorTBB == PriorFBB) {
833      TII->RemoveBranch(PrevBB);
834      PriorCond.clear();
835      if (PriorTBB != MBB)
836        TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
837      MadeChange = true;
838      ++NumBranchOpts;
839      return OptimizeBlock(MBB);
840    }
841
842    // If the previous branch *only* branches to *this* block (conditional or
843    // not) remove the branch.
844    if (PriorTBB == MBB && PriorFBB == 0) {
845      TII->RemoveBranch(PrevBB);
846      MadeChange = true;
847      ++NumBranchOpts;
848      return OptimizeBlock(MBB);
849    }
850
851    // If the prior block branches somewhere else on the condition and here if
852    // the condition is false, remove the uncond second branch.
853    if (PriorFBB == MBB) {
854      TII->RemoveBranch(PrevBB);
855      TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
856      MadeChange = true;
857      ++NumBranchOpts;
858      return OptimizeBlock(MBB);
859    }
860
861    // If the prior block branches here on true and somewhere else on false, and
862    // if the branch condition is reversible, reverse the branch to create a
863    // fall-through.
864    if (PriorTBB == MBB) {
865      std::vector<MachineOperand> NewPriorCond(PriorCond);
866      if (!TII->ReverseBranchCondition(NewPriorCond)) {
867        TII->RemoveBranch(PrevBB);
868        TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
869        MadeChange = true;
870        ++NumBranchOpts;
871        return OptimizeBlock(MBB);
872      }
873    }
874
875    // If this block doesn't fall through (e.g. it ends with an uncond branch or
876    // has no successors) and if the pred falls through into this block, and if
877    // it would otherwise fall through into the block after this, move this
878    // block to the end of the function.
879    //
880    // We consider it more likely that execution will stay in the function (e.g.
881    // due to loops) than it is to exit it.  This asserts in loops etc, moving
882    // the assert condition out of the loop body.
883    if (!PriorCond.empty() && PriorFBB == 0 &&
884        MachineFunction::iterator(PriorTBB) == FallThrough &&
885        !CanFallThrough(MBB)) {
886      bool DoTransform = true;
887
888      // We have to be careful that the succs of PredBB aren't both no-successor
889      // blocks.  If neither have successors and if PredBB is the second from
890      // last block in the function, we'd just keep swapping the two blocks for
891      // last.  Only do the swap if one is clearly better to fall through than
892      // the other.
893      if (FallThrough == --MBB->getParent()->end() &&
894          !IsBetterFallthrough(PriorTBB, MBB))
895        DoTransform = false;
896
897      // We don't want to do this transformation if we have control flow like:
898      //   br cond BB2
899      // BB1:
900      //   ..
901      //   jmp BBX
902      // BB2:
903      //   ..
904      //   ret
905      //
906      // In this case, we could actually be moving the return block *into* a
907      // loop!
908      if (DoTransform && !MBB->succ_empty() &&
909          (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
910        DoTransform = false;
911
912
913      if (DoTransform) {
914        // Reverse the branch so we will fall through on the previous true cond.
915        std::vector<MachineOperand> NewPriorCond(PriorCond);
916        if (!TII->ReverseBranchCondition(NewPriorCond)) {
917          DOUT << "\nMoving MBB: " << *MBB;
918          DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
919
920          TII->RemoveBranch(PrevBB);
921          TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
922
923          // Move this block to the end of the function.
924          MBB->moveAfter(--MBB->getParent()->end());
925          MadeChange = true;
926          ++NumBranchOpts;
927          return;
928        }
929      }
930    }
931  }
932
933  // Analyze the branch in the current block.
934  MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
935  std::vector<MachineOperand> CurCond;
936  bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
937  if (!CurUnAnalyzable) {
938    // If the CFG for the prior block has extra edges, remove them.
939    MadeChange |= MBB->CorrectExtraCFGEdges(CurTBB, CurFBB, !CurCond.empty());
940
941    // If this is a two-way branch, and the FBB branches to this block, reverse
942    // the condition so the single-basic-block loop is faster.  Instead of:
943    //    Loop: xxx; jcc Out; jmp Loop
944    // we want:
945    //    Loop: xxx; jncc Loop; jmp Out
946    if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
947      std::vector<MachineOperand> NewCond(CurCond);
948      if (!TII->ReverseBranchCondition(NewCond)) {
949        TII->RemoveBranch(*MBB);
950        TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
951        MadeChange = true;
952        ++NumBranchOpts;
953        return OptimizeBlock(MBB);
954      }
955    }
956
957
958    // If this branch is the only thing in its block, see if we can forward
959    // other blocks across it.
960    if (CurTBB && CurCond.empty() && CurFBB == 0 &&
961        MBB->begin()->getDesc().isBranch() && CurTBB != MBB) {
962      // This block may contain just an unconditional branch.  Because there can
963      // be 'non-branch terminators' in the block, try removing the branch and
964      // then seeing if the block is empty.
965      TII->RemoveBranch(*MBB);
966
967      // If this block is just an unconditional branch to CurTBB, we can
968      // usually completely eliminate the block.  The only case we cannot
969      // completely eliminate the block is when the block before this one
970      // falls through into MBB and we can't understand the prior block's branch
971      // condition.
972      if (MBB->empty()) {
973        bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
974        if (PredHasNoFallThrough || !PriorUnAnalyzable ||
975            !PrevBB.isSuccessor(MBB)) {
976          // If the prior block falls through into us, turn it into an
977          // explicit branch to us to make updates simpler.
978          if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) &&
979              PriorTBB != MBB && PriorFBB != MBB) {
980            if (PriorTBB == 0) {
981              assert(PriorCond.empty() && PriorFBB == 0 &&
982                     "Bad branch analysis");
983              PriorTBB = MBB;
984            } else {
985              assert(PriorFBB == 0 && "Machine CFG out of date!");
986              PriorFBB = MBB;
987            }
988            TII->RemoveBranch(PrevBB);
989            TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
990          }
991
992          // Iterate through all the predecessors, revectoring each in-turn.
993          size_t PI = 0;
994          bool DidChange = false;
995          bool HasBranchToSelf = false;
996          while(PI != MBB->pred_size()) {
997            MachineBasicBlock *PMBB = *(MBB->pred_begin() + PI);
998            if (PMBB == MBB) {
999              // If this block has an uncond branch to itself, leave it.
1000              ++PI;
1001              HasBranchToSelf = true;
1002            } else {
1003              DidChange = true;
1004              PMBB->ReplaceUsesOfBlockWith(MBB, CurTBB);
1005            }
1006          }
1007
1008          // Change any jumptables to go to the new MBB.
1009          MBB->getParent()->getJumpTableInfo()->
1010            ReplaceMBBInJumpTables(MBB, CurTBB);
1011          if (DidChange) {
1012            ++NumBranchOpts;
1013            MadeChange = true;
1014            if (!HasBranchToSelf) return;
1015          }
1016        }
1017      }
1018
1019      // Add the branch back if the block is more than just an uncond branch.
1020      TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
1021    }
1022  }
1023
1024  // If the prior block doesn't fall through into this block, and if this
1025  // block doesn't fall through into some other block, see if we can find a
1026  // place to move this block where a fall-through will happen.
1027  if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
1028                      PriorTBB, PriorFBB, PriorCond)) {
1029    // Now we know that there was no fall-through into this block, check to
1030    // see if it has a fall-through into its successor.
1031    bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB,
1032                                       CurCond);
1033
1034    if (!MBB->isLandingPad()) {
1035      // Check all the predecessors of this block.  If one of them has no fall
1036      // throughs, move this block right after it.
1037      for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
1038           E = MBB->pred_end(); PI != E; ++PI) {
1039        // Analyze the branch at the end of the pred.
1040        MachineBasicBlock *PredBB = *PI;
1041        MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
1042        if (PredBB != MBB && !CanFallThrough(PredBB)
1043            && (!CurFallsThru || !CurTBB || !CurFBB)
1044            && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
1045          // If the current block doesn't fall through, just move it.
1046          // If the current block can fall through and does not end with a
1047          // conditional branch, we need to append an unconditional jump to
1048          // the (current) next block.  To avoid a possible compile-time
1049          // infinite loop, move blocks only backward in this case.
1050          // Also, if there are already 2 branches here, we cannot add a third;
1051          // this means we have the case
1052          // Bcc next
1053          // B elsewhere
1054          // next:
1055          if (CurFallsThru) {
1056            MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
1057            CurCond.clear();
1058            TII->InsertBranch(*MBB, NextBB, 0, CurCond);
1059          }
1060          MBB->moveAfter(PredBB);
1061          MadeChange = true;
1062          return OptimizeBlock(MBB);
1063        }
1064      }
1065    }
1066
1067    if (!CurFallsThru) {
1068      // Check all successors to see if we can move this block before it.
1069      for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
1070           E = MBB->succ_end(); SI != E; ++SI) {
1071        // Analyze the branch at the end of the block before the succ.
1072        MachineBasicBlock *SuccBB = *SI;
1073        MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
1074        std::vector<MachineOperand> SuccPrevCond;
1075
1076        // If this block doesn't already fall-through to that successor, and if
1077        // the succ doesn't already have a block that can fall through into it,
1078        // and if the successor isn't an EH destination, we can arrange for the
1079        // fallthrough to happen.
1080        if (SuccBB != MBB && !CanFallThrough(SuccPrev) &&
1081            !SuccBB->isLandingPad()) {
1082          MBB->moveBefore(SuccBB);
1083          MadeChange = true;
1084          return OptimizeBlock(MBB);
1085        }
1086      }
1087
1088      // Okay, there is no really great place to put this block.  If, however,
1089      // the block before this one would be a fall-through if this block were
1090      // removed, move this block to the end of the function.
1091      if (FallThrough != MBB->getParent()->end() &&
1092          PrevBB.isSuccessor(FallThrough)) {
1093        MBB->moveAfter(--MBB->getParent()->end());
1094        MadeChange = true;
1095        return;
1096      }
1097    }
1098  }
1099}
1100