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