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