http://llvm.org/bugs/show_bug.cgi?id=1237
[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/Target/TargetInstrInfo.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/STLExtras.h"
30 #include <algorithm>
31 using namespace llvm;
32
33 STATISTIC(NumDeadBlocks, "Number of dead blocks removed");
34 STATISTIC(NumBranchOpts, "Number of branches optimized");
35 STATISTIC(NumTailMerge , "Number of block tails merged");
36 static cl::opt<bool> EnableTailMerge("enable-tail-merge", cl::Hidden);
37
38 namespace {
39   struct BranchFolder : public MachineFunctionPass {
40     virtual bool runOnMachineFunction(MachineFunction &MF);
41     virtual const char *getPassName() const { return "Control Flow Optimizer"; }
42     const TargetInstrInfo *TII;
43     MachineModuleInfo *MMI;
44     bool MadeChange;
45   private:
46     // Tail Merging.
47     bool TailMergeBlocks(MachineFunction &MF);
48     void ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
49                                  MachineBasicBlock *NewDest);
50     MachineBasicBlock *SplitMBBAt(MachineBasicBlock &CurMBB,
51                                   MachineBasicBlock::iterator BBI1);
52         
53     // Branch optzn.
54     bool OptimizeBranches(MachineFunction &MF);
55     void OptimizeBlock(MachineBasicBlock *MBB);
56     void RemoveDeadBlock(MachineBasicBlock *MBB);
57     
58     bool CanFallThrough(MachineBasicBlock *CurBB);
59     bool CanFallThrough(MachineBasicBlock *CurBB, bool BranchUnAnalyzable,
60                         MachineBasicBlock *TBB, MachineBasicBlock *FBB,
61                         const std::vector<MachineOperand> &Cond);
62   };
63 }
64
65 FunctionPass *llvm::createBranchFoldingPass() { return new BranchFolder(); }
66
67 /// RemoveDeadBlock - Remove the specified dead machine basic block from the
68 /// function, updating the CFG.
69 void BranchFolder::RemoveDeadBlock(MachineBasicBlock *MBB) {
70   assert(MBB->pred_empty() && "MBB must be dead!");
71   DOUT << "\nRemoving MBB: " << *MBB;
72   
73   MachineFunction *MF = MBB->getParent();
74   // drop all successors.
75   while (!MBB->succ_empty())
76     MBB->removeSuccessor(MBB->succ_end()-1);
77   
78   // If there is DWARF info to active, check to see if there are any LABEL
79   // records in the basic block.  If so, unregister them from MachineModuleInfo.
80   if (MMI && !MBB->empty()) {
81     for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
82          I != E; ++I) {
83       if ((unsigned)I->getOpcode() == TargetInstrInfo::LABEL) {
84         // The label ID # is always operand #0, an immediate.
85         MMI->InvalidateLabel(I->getOperand(0).getImm());
86       }
87     }
88   }
89   
90   // Remove the block.
91   MF->getBasicBlockList().erase(MBB);
92 }
93
94 bool BranchFolder::runOnMachineFunction(MachineFunction &MF) {
95   TII = MF.getTarget().getInstrInfo();
96   if (!TII) return false;
97
98   MMI = getAnalysisToUpdate<MachineModuleInfo>();
99   
100   bool EverMadeChange = false;
101   bool MadeChangeThisIteration = true;
102   while (MadeChangeThisIteration) {
103     MadeChangeThisIteration = false;
104     MadeChangeThisIteration |= TailMergeBlocks(MF);
105     MadeChangeThisIteration |= OptimizeBranches(MF);
106     EverMadeChange |= MadeChangeThisIteration;
107   }
108
109   // See if any jump tables have become mergable or dead as the code generator
110   // did its thing.
111   MachineJumpTableInfo *JTI = MF.getJumpTableInfo();
112   const std::vector<MachineJumpTableEntry> &JTs = JTI->getJumpTables();
113   if (!JTs.empty()) {
114     // Figure out how these jump tables should be merged.
115     std::vector<unsigned> JTMapping;
116     JTMapping.reserve(JTs.size());
117     
118     // We always keep the 0th jump table.
119     JTMapping.push_back(0);
120
121     // Scan the jump tables, seeing if there are any duplicates.  Note that this
122     // is N^2, which should be fixed someday.
123     for (unsigned i = 1, e = JTs.size(); i != e; ++i)
124       JTMapping.push_back(JTI->getJumpTableIndex(JTs[i].MBBs));
125     
126     // If a jump table was merge with another one, walk the function rewriting
127     // references to jump tables to reference the new JT ID's.  Keep track of
128     // whether we see a jump table idx, if not, we can delete the JT.
129     std::vector<bool> JTIsLive;
130     JTIsLive.resize(JTs.size());
131     for (MachineFunction::iterator BB = MF.begin(), E = MF.end();
132          BB != E; ++BB) {
133       for (MachineBasicBlock::iterator I = BB->begin(), E = BB->end();
134            I != E; ++I)
135         for (unsigned op = 0, e = I->getNumOperands(); op != e; ++op) {
136           MachineOperand &Op = I->getOperand(op);
137           if (!Op.isJumpTableIndex()) continue;
138           unsigned NewIdx = JTMapping[Op.getJumpTableIndex()];
139           Op.setJumpTableIndex(NewIdx);
140
141           // Remember that this JT is live.
142           JTIsLive[NewIdx] = true;
143         }
144     }
145    
146     // Finally, remove dead jump tables.  This happens either because the
147     // indirect jump was unreachable (and thus deleted) or because the jump
148     // table was merged with some other one.
149     for (unsigned i = 0, e = JTIsLive.size(); i != e; ++i)
150       if (!JTIsLive[i]) {
151         JTI->RemoveJumpTable(i);
152         EverMadeChange = true;
153       }
154   }
155   
156   return EverMadeChange;
157 }
158
159 //===----------------------------------------------------------------------===//
160 //  Tail Merging of Blocks
161 //===----------------------------------------------------------------------===//
162
163 /// HashMachineInstr - Compute a hash value for MI and its operands.
164 static unsigned HashMachineInstr(const MachineInstr *MI) {
165   unsigned Hash = MI->getOpcode();
166   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
167     const MachineOperand &Op = MI->getOperand(i);
168     
169     // Merge in bits from the operand if easy.
170     unsigned OperandHash = 0;
171     switch (Op.getType()) {
172     case MachineOperand::MO_Register:          OperandHash = Op.getReg(); break;
173     case MachineOperand::MO_Immediate:         OperandHash = Op.getImm(); break;
174     case MachineOperand::MO_MachineBasicBlock:
175       OperandHash = Op.getMachineBasicBlock()->getNumber();
176       break;
177     case MachineOperand::MO_FrameIndex: OperandHash = Op.getFrameIndex(); break;
178     case MachineOperand::MO_ConstantPoolIndex:
179       OperandHash = Op.getConstantPoolIndex();
180       break;
181     case MachineOperand::MO_JumpTableIndex:
182       OperandHash = Op.getJumpTableIndex();
183       break;
184     case MachineOperand::MO_GlobalAddress:
185     case MachineOperand::MO_ExternalSymbol:
186       // Global address / external symbol are too hard, don't bother, but do
187       // pull in the offset.
188       OperandHash = Op.getOffset();
189       break;
190     default: break;
191     }
192     
193     Hash += ((OperandHash << 3) | Op.getType()) << (i&31);
194   }
195   return Hash;
196 }
197
198 /// HashEndOfMBB - Hash the last two instructions in the MBB.  We hash two
199 /// instructions, because cross-jumping only saves code when at least two
200 /// instructions are removed (since a branch must be inserted).
201 static unsigned HashEndOfMBB(const MachineBasicBlock *MBB) {
202   MachineBasicBlock::const_iterator I = MBB->end();
203   if (I == MBB->begin())
204     return 0;   // Empty MBB.
205   
206   --I;
207   unsigned Hash = HashMachineInstr(I);
208     
209   if (I == MBB->begin())
210     return Hash;   // Single instr MBB.
211   
212   --I;
213   // Hash in the second-to-last instruction.
214   Hash ^= HashMachineInstr(I) << 2;
215   return Hash;
216 }
217
218 /// ComputeCommonTailLength - Given two machine basic blocks, compute the number
219 /// of instructions they actually have in common together at their end.  Return
220 /// iterators for the first shared instruction in each block.
221 static unsigned ComputeCommonTailLength(MachineBasicBlock *MBB1,
222                                         MachineBasicBlock *MBB2,
223                                         MachineBasicBlock::iterator &I1,
224                                         MachineBasicBlock::iterator &I2) {
225   I1 = MBB1->end();
226   I2 = MBB2->end();
227   
228   unsigned TailLen = 0;
229   while (I1 != MBB1->begin() && I2 != MBB2->begin()) {
230     --I1; --I2;
231     if (!I1->isIdenticalTo(I2)) {
232       ++I1; ++I2;
233       break;
234     }
235     ++TailLen;
236   }
237   return TailLen;
238 }
239
240 /// ReplaceTailWithBranchTo - Delete the instruction OldInst and everything
241 /// after it, replacing it with an unconditional branch to NewDest.  This
242 /// returns true if OldInst's block is modified, false if NewDest is modified.
243 void BranchFolder::ReplaceTailWithBranchTo(MachineBasicBlock::iterator OldInst,
244                                            MachineBasicBlock *NewDest) {
245   MachineBasicBlock *OldBB = OldInst->getParent();
246   
247   // Remove all the old successors of OldBB from the CFG.
248   while (!OldBB->succ_empty())
249     OldBB->removeSuccessor(OldBB->succ_begin());
250   
251   // Remove all the dead instructions from the end of OldBB.
252   OldBB->erase(OldInst, OldBB->end());
253
254   // If OldBB isn't immediately before OldBB, insert a branch to it.
255   if (++MachineFunction::iterator(OldBB) != MachineFunction::iterator(NewDest))
256     TII->InsertBranch(*OldBB, NewDest, 0, std::vector<MachineOperand>());
257   OldBB->addSuccessor(NewDest);
258   ++NumTailMerge;
259 }
260
261 /// SplitMBBAt - Given a machine basic block and an iterator into it, split the
262 /// MBB so that the part before the iterator falls into the part starting at the
263 /// iterator.  This returns the new MBB.
264 MachineBasicBlock *BranchFolder::SplitMBBAt(MachineBasicBlock &CurMBB,
265                                             MachineBasicBlock::iterator BBI1) {
266   // Create the fall-through block.
267   MachineFunction::iterator MBBI = &CurMBB;
268   MachineBasicBlock *NewMBB = new MachineBasicBlock(CurMBB.getBasicBlock());
269   CurMBB.getParent()->getBasicBlockList().insert(++MBBI, NewMBB);
270
271   // Move all the successors of this block to the specified block.
272   while (!CurMBB.succ_empty()) {
273     MachineBasicBlock *S = *(CurMBB.succ_end()-1);
274     NewMBB->addSuccessor(S);
275     CurMBB.removeSuccessor(S);
276   }
277  
278   // Add an edge from CurMBB to NewMBB for the fall-through.
279   CurMBB.addSuccessor(NewMBB);
280   
281   // Splice the code over.
282   NewMBB->splice(NewMBB->end(), &CurMBB, BBI1, CurMBB.end());
283   return NewMBB;
284 }
285
286 /// EstimateRuntime - Make a rough estimate for how long it will take to run
287 /// the specified code.
288 static unsigned EstimateRuntime(MachineBasicBlock::iterator I,
289                                 MachineBasicBlock::iterator E,
290                                 const TargetInstrInfo *TII) {
291   unsigned Time = 0;
292   for (; I != E; ++I) {
293     const TargetInstrDescriptor &TID = TII->get(I->getOpcode());
294     if (TID.Flags & M_CALL_FLAG)
295       Time += 10;
296     else if (TID.Flags & (M_LOAD_FLAG|M_STORE_FLAG))
297       Time += 2;
298     else
299       ++Time;
300   }
301   return Time;
302 }
303
304 /// ShouldSplitFirstBlock - We need to either split MBB1 at MBB1I or MBB2 at
305 /// MBB2I and then insert an unconditional branch in the other block.  Determine
306 /// which is the best to split
307 static bool ShouldSplitFirstBlock(MachineBasicBlock *MBB1,
308                                   MachineBasicBlock::iterator MBB1I,
309                                   MachineBasicBlock *MBB2,
310                                   MachineBasicBlock::iterator MBB2I,
311                                   const TargetInstrInfo *TII) {
312   // TODO: if we had some notion of which block was hotter, we could split
313   // the hot block, so it is the fall-through.  Since we don't have profile info
314   // make a decision based on which will hurt most to split.
315   unsigned MBB1Time = EstimateRuntime(MBB1->begin(), MBB1I, TII);
316   unsigned MBB2Time = EstimateRuntime(MBB2->begin(), MBB2I, TII);
317   
318   // If the MBB1 prefix takes "less time" to run than the MBB2 prefix, split the
319   // MBB1 block so it falls through.  This will penalize the MBB2 path, but will
320   // have a lower overall impact on the program execution.
321   return MBB1Time < MBB2Time;
322 }
323
324 bool BranchFolder::TailMergeBlocks(MachineFunction &MF) {
325   MadeChange = false;
326   
327   if (!EnableTailMerge) return false;
328   
329   // Find blocks with no successors.
330   std::vector<std::pair<unsigned,MachineBasicBlock*> > MergePotentials;
331   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
332     if (I->succ_empty())
333       MergePotentials.push_back(std::make_pair(HashEndOfMBB(I), I));
334   }
335   
336   // Sort by hash value so that blocks with identical end sequences sort
337   // together.
338   std::stable_sort(MergePotentials.begin(), MergePotentials.end());
339
340   // Walk through equivalence sets looking for actual exact matches.
341   while (MergePotentials.size() > 1) {
342     unsigned CurHash  = (MergePotentials.end()-1)->first;
343     unsigned PrevHash = (MergePotentials.end()-2)->first;
344     MachineBasicBlock *CurMBB = (MergePotentials.end()-1)->second;
345     
346     // If there is nothing that matches the hash of the current basic block,
347     // give up.
348     if (CurHash != PrevHash) {
349       MergePotentials.pop_back();
350       continue;
351     }
352     
353     // Determine the actual length of the shared tail between these two basic
354     // blocks.  Because the hash can have collisions, it's possible that this is
355     // less than 2.
356     MachineBasicBlock::iterator BBI1, BBI2;
357     unsigned CommonTailLen = 
358       ComputeCommonTailLength(CurMBB, (MergePotentials.end()-2)->second, 
359                               BBI1, BBI2);
360     
361     // If the tails don't have at least two instructions in common, see if there
362     // is anything else in the equivalence class that does match.
363     if (CommonTailLen < 2) {
364       unsigned FoundMatch = ~0U;
365       for (int i = MergePotentials.size()-2;
366            i != -1 && MergePotentials[i].first == CurHash; --i) {
367         CommonTailLen = ComputeCommonTailLength(CurMBB, 
368                                                 MergePotentials[i].second,
369                                                 BBI1, BBI2);
370         if (CommonTailLen >= 2) {
371           FoundMatch = i;
372           break;
373         }
374       }
375       
376       // If we didn't find anything that has at least two instructions matching
377       // this one, bail out.
378       if (FoundMatch == ~0U) {
379         MergePotentials.pop_back();
380         continue;
381       }
382       
383       // Otherwise, move the matching block to the right position.
384       std::swap(MergePotentials[FoundMatch], *(MergePotentials.end()-2));
385     }
386
387     MachineBasicBlock *MBB2 = (MergePotentials.end()-2)->second;
388
389     // If neither block is the entire common tail, split the tail of one block
390     // to make it redundant with the other tail.
391     if (CurMBB->begin() != BBI1 && MBB2->begin() != BBI2) {
392       if (0) { // Enable this to disable partial tail merges.
393         MergePotentials.pop_back();
394         continue;
395       }
396       
397       // Decide whether we want to split CurMBB or MBB2.
398       if (ShouldSplitFirstBlock(CurMBB, BBI1, MBB2, BBI2, TII)) {
399         CurMBB = SplitMBBAt(*CurMBB, BBI1);
400         BBI1 = CurMBB->begin();
401         MergePotentials.back().second = CurMBB;
402       } else {
403         MBB2 = SplitMBBAt(*MBB2, BBI2);
404         BBI2 = MBB2->begin();
405         (MergePotentials.end()-2)->second = MBB2;
406       }
407     }
408     
409     if (MBB2->begin() == BBI2) {
410       // Hack the end off CurMBB, making it jump to MBBI@ instead.
411       ReplaceTailWithBranchTo(BBI1, MBB2);
412       // This modifies CurMBB, so remove it from the worklist.
413       MergePotentials.pop_back();
414     } else {
415       assert(CurMBB->begin() == BBI1 && "Didn't split block correctly?");
416       // Hack the end off MBB2, making it jump to CurMBB instead.
417       ReplaceTailWithBranchTo(BBI2, CurMBB);
418       // This modifies MBB2, so remove it from the worklist.
419       MergePotentials.erase(MergePotentials.end()-2);
420     }
421     MadeChange = true;
422   }
423   
424   return MadeChange;
425 }
426
427
428 //===----------------------------------------------------------------------===//
429 //  Branch Optimization
430 //===----------------------------------------------------------------------===//
431
432 bool BranchFolder::OptimizeBranches(MachineFunction &MF) {
433   MadeChange = false;
434   
435   // Make sure blocks are numbered in order
436   MF.RenumberBlocks();
437
438   for (MachineFunction::iterator I = ++MF.begin(), E = MF.end(); I != E; ) {
439     MachineBasicBlock *MBB = I++;
440     OptimizeBlock(MBB);
441     
442     // If it is dead, remove it.
443     if (MBB->pred_empty()) {
444       RemoveDeadBlock(MBB);
445       MadeChange = true;
446       ++NumDeadBlocks;
447     }
448   }
449   return MadeChange;
450 }
451
452
453 /// CorrectExtraCFGEdges - Various pieces of code can cause excess edges in the
454 /// CFG to be inserted.  If we have proven that MBB can only branch to DestA and
455 /// DestB, remove any other MBB successors from the CFG.  DestA and DestB can
456 /// be null.
457 static bool CorrectExtraCFGEdges(MachineBasicBlock &MBB, 
458                                  MachineBasicBlock *DestA,
459                                  MachineBasicBlock *DestB,
460                                  bool isCond, 
461                                  MachineFunction::iterator FallThru) {
462   bool MadeChange = false;
463   bool AddedFallThrough = false;
464   
465   // If this block ends with a conditional branch that falls through to its
466   // successor, set DestB as the successor.
467   if (isCond) {
468     if (DestB == 0 && FallThru != MBB.getParent()->end()) {
469       DestB = FallThru;
470       AddedFallThrough = true;
471     }
472   } else {
473     // If this is an unconditional branch with no explicit dest, it must just be
474     // a fallthrough into DestB.
475     if (DestA == 0 && FallThru != MBB.getParent()->end()) {
476       DestA = FallThru;
477       AddedFallThrough = true;
478     }
479   }
480   
481   MachineBasicBlock::pred_iterator SI = MBB.succ_begin();
482   while (SI != MBB.succ_end()) {
483     if (*SI == DestA) {
484       DestA = 0;
485       ++SI;
486     } else if (*SI == DestB) {
487       DestB = 0;
488       ++SI;
489     } else if ((*SI)->isLandingPad()) {
490       ++SI;
491     } else {
492       // Otherwise, this is a superfluous edge, remove it.
493       MBB.removeSuccessor(SI);
494       MadeChange = true;
495     }
496   }
497   if (!AddedFallThrough) {
498     assert(DestA == 0 && DestB == 0 &&
499            "MachineCFG is missing edges!");
500   } else if (isCond) {
501     assert(DestA == 0 && "MachineCFG is missing edges!");
502   }
503   return MadeChange;
504 }
505
506
507 /// ReplaceUsesOfBlockWith - Given a machine basic block 'BB' that branched to
508 /// 'Old', change the code and CFG so that it branches to 'New' instead.
509 static void ReplaceUsesOfBlockWith(MachineBasicBlock *BB,
510                                    MachineBasicBlock *Old,
511                                    MachineBasicBlock *New,
512                                    const TargetInstrInfo *TII) {
513   assert(Old != New && "Cannot replace self with self!");
514
515   MachineBasicBlock::iterator I = BB->end();
516   while (I != BB->begin()) {
517     --I;
518     if (!TII->isTerminatorInstr(I->getOpcode())) break;
519
520     // Scan the operands of this machine instruction, replacing any uses of Old
521     // with New.
522     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
523       if (I->getOperand(i).isMachineBasicBlock() &&
524           I->getOperand(i).getMachineBasicBlock() == Old)
525         I->getOperand(i).setMachineBasicBlock(New);
526   }
527
528   // Update the successor information.
529   std::vector<MachineBasicBlock*> Succs(BB->succ_begin(), BB->succ_end());
530   for (int i = Succs.size()-1; i >= 0; --i)
531     if (Succs[i] == Old) {
532       BB->removeSuccessor(Old);
533       BB->addSuccessor(New);
534     }
535 }
536
537 /// CanFallThrough - Return true if the specified block (with the specified
538 /// branch condition) can implicitly transfer control to the block after it by
539 /// falling off the end of it.  This should return false if it can reach the
540 /// block after it, but it uses an explicit branch to do so (e.g. a table jump).
541 ///
542 /// True is a conservative answer.
543 ///
544 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB,
545                                   bool BranchUnAnalyzable,
546                                   MachineBasicBlock *TBB, MachineBasicBlock *FBB,
547                                   const std::vector<MachineOperand> &Cond) {
548   MachineFunction::iterator Fallthrough = CurBB;
549   ++Fallthrough;
550   // If FallthroughBlock is off the end of the function, it can't fall through.
551   if (Fallthrough == CurBB->getParent()->end())
552     return false;
553   
554   // If FallthroughBlock isn't a successor of CurBB, no fallthrough is possible.
555   if (!CurBB->isSuccessor(Fallthrough))
556     return false;
557   
558   // If we couldn't analyze the branch, assume it could fall through.
559   if (BranchUnAnalyzable) return true;
560   
561   // If there is no branch, control always falls through.
562   if (TBB == 0) return true;
563
564   // If there is some explicit branch to the fallthrough block, it can obviously
565   // reach, even though the branch should get folded to fall through implicitly.
566   if (MachineFunction::iterator(TBB) == Fallthrough ||
567       MachineFunction::iterator(FBB) == Fallthrough)
568     return true;
569   
570   // If it's an unconditional branch to some block not the fall through, it 
571   // doesn't fall through.
572   if (Cond.empty()) return false;
573   
574   // Otherwise, if it is conditional and has no explicit false block, it falls
575   // through.
576   return FBB == 0;
577 }
578
579 /// CanFallThrough - Return true if the specified can implicitly transfer
580 /// control to the block after it by falling off the end of it.  This should
581 /// return false if it can reach the block after it, but it uses an explicit
582 /// branch to do so (e.g. a table jump).
583 ///
584 /// True is a conservative answer.
585 ///
586 bool BranchFolder::CanFallThrough(MachineBasicBlock *CurBB) {
587   MachineBasicBlock *TBB = 0, *FBB = 0;
588   std::vector<MachineOperand> Cond;
589   bool CurUnAnalyzable = TII->AnalyzeBranch(*CurBB, TBB, FBB, Cond);
590   return CanFallThrough(CurBB, CurUnAnalyzable, TBB, FBB, Cond);
591 }
592
593 /// IsBetterFallthrough - Return true if it would be clearly better to
594 /// fall-through to MBB1 than to fall through into MBB2.  This has to return
595 /// a strict ordering, returning true for both (MBB1,MBB2) and (MBB2,MBB1) will
596 /// result in infinite loops.
597 static bool IsBetterFallthrough(MachineBasicBlock *MBB1, 
598                                 MachineBasicBlock *MBB2,
599                                 const TargetInstrInfo &TII) {
600   // Right now, we use a simple heuristic.  If MBB2 ends with a call, and
601   // MBB1 doesn't, we prefer to fall through into MBB1.  This allows us to
602   // optimize branches that branch to either a return block or an assert block
603   // into a fallthrough to the return.
604   if (MBB1->empty() || MBB2->empty()) return false;
605
606   MachineInstr *MBB1I = --MBB1->end();
607   MachineInstr *MBB2I = --MBB2->end();
608   return TII.isCall(MBB2I->getOpcode()) && !TII.isCall(MBB1I->getOpcode());
609 }
610
611 /// OptimizeBlock - Analyze and optimize control flow related to the specified
612 /// block.  This is never called on the entry block.
613 void BranchFolder::OptimizeBlock(MachineBasicBlock *MBB) {
614   MachineFunction::iterator FallThrough = MBB;
615   ++FallThrough;
616   
617   // If this block is empty, make everyone use its fall-through, not the block
618   // explicitly.
619   if (MBB->empty()) {
620     // Dead block?  Leave for cleanup later.
621     if (MBB->pred_empty()) return;
622     
623     if (FallThrough == MBB->getParent()->end()) {
624       // TODO: Simplify preds to not branch here if possible!
625     } else {
626       // Rewrite all predecessors of the old block to go to the fallthrough
627       // instead.
628       while (!MBB->pred_empty()) {
629         MachineBasicBlock *Pred = *(MBB->pred_end()-1);
630         ReplaceUsesOfBlockWith(Pred, MBB, FallThrough, TII);
631       }
632       
633       // If MBB was the target of a jump table, update jump tables to go to the
634       // fallthrough instead.
635       MBB->getParent()->getJumpTableInfo()->
636         ReplaceMBBInJumpTables(MBB, FallThrough);
637       MadeChange = true;
638     }
639     return;
640   }
641
642   // Check to see if we can simplify the terminator of the block before this
643   // one.
644   MachineBasicBlock &PrevBB = *prior(MachineFunction::iterator(MBB));
645
646   MachineBasicBlock *PriorTBB = 0, *PriorFBB = 0;
647   std::vector<MachineOperand> PriorCond;
648   bool PriorUnAnalyzable =
649     TII->AnalyzeBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
650   if (!PriorUnAnalyzable) {
651     // If the CFG for the prior block has extra edges, remove them.
652     MadeChange |= CorrectExtraCFGEdges(PrevBB, PriorTBB, PriorFBB,
653                                        !PriorCond.empty(), MBB);
654     
655     // If the previous branch is conditional and both conditions go to the same
656     // destination, remove the branch, replacing it with an unconditional one or
657     // a fall-through.
658     if (PriorTBB && PriorTBB == PriorFBB) {
659       TII->RemoveBranch(PrevBB);
660       PriorCond.clear(); 
661       if (PriorTBB != MBB)
662         TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
663       MadeChange = true;
664       ++NumBranchOpts;
665       return OptimizeBlock(MBB);
666     }
667     
668     // If the previous branch *only* branches to *this* block (conditional or
669     // not) remove the branch.
670     if (PriorTBB == MBB && PriorFBB == 0) {
671       TII->RemoveBranch(PrevBB);
672       MadeChange = true;
673       ++NumBranchOpts;
674       return OptimizeBlock(MBB);
675     }
676     
677     // If the prior block branches somewhere else on the condition and here if
678     // the condition is false, remove the uncond second branch.
679     if (PriorFBB == MBB) {
680       TII->RemoveBranch(PrevBB);
681       TII->InsertBranch(PrevBB, PriorTBB, 0, PriorCond);
682       MadeChange = true;
683       ++NumBranchOpts;
684       return OptimizeBlock(MBB);
685     }
686     
687     // If the prior block branches here on true and somewhere else on false, and
688     // if the branch condition is reversible, reverse the branch to create a
689     // fall-through.
690     if (PriorTBB == MBB) {
691       std::vector<MachineOperand> NewPriorCond(PriorCond);
692       if (!TII->ReverseBranchCondition(NewPriorCond)) {
693         TII->RemoveBranch(PrevBB);
694         TII->InsertBranch(PrevBB, PriorFBB, 0, NewPriorCond);
695         MadeChange = true;
696         ++NumBranchOpts;
697         return OptimizeBlock(MBB);
698       }
699     }
700     
701     // If this block doesn't fall through (e.g. it ends with an uncond branch or
702     // has no successors) and if the pred falls through into this block, and if
703     // it would otherwise fall through into the block after this, move this
704     // block to the end of the function.
705     //
706     // We consider it more likely that execution will stay in the function (e.g.
707     // due to loops) than it is to exit it.  This asserts in loops etc, moving
708     // the assert condition out of the loop body.
709     if (!PriorCond.empty() && PriorFBB == 0 &&
710         MachineFunction::iterator(PriorTBB) == FallThrough &&
711         !CanFallThrough(MBB)) {
712       bool DoTransform = true;
713       
714       // We have to be careful that the succs of PredBB aren't both no-successor
715       // blocks.  If neither have successors and if PredBB is the second from
716       // last block in the function, we'd just keep swapping the two blocks for
717       // last.  Only do the swap if one is clearly better to fall through than
718       // the other.
719       if (FallThrough == --MBB->getParent()->end() &&
720           !IsBetterFallthrough(PriorTBB, MBB, *TII))
721         DoTransform = false;
722
723       // We don't want to do this transformation if we have control flow like:
724       //   br cond BB2
725       // BB1:
726       //   ..
727       //   jmp BBX
728       // BB2:
729       //   ..
730       //   ret
731       //
732       // In this case, we could actually be moving the return block *into* a
733       // loop!
734       if (DoTransform && !MBB->succ_empty() &&
735           (!CanFallThrough(PriorTBB) || PriorTBB->empty()))
736         DoTransform = false;
737       
738       
739       if (DoTransform) {
740         // Reverse the branch so we will fall through on the previous true cond.
741         std::vector<MachineOperand> NewPriorCond(PriorCond);
742         if (!TII->ReverseBranchCondition(NewPriorCond)) {
743           DOUT << "\nMoving MBB: " << *MBB;
744           DOUT << "To make fallthrough to: " << *PriorTBB << "\n";
745           
746           TII->RemoveBranch(PrevBB);
747           TII->InsertBranch(PrevBB, MBB, 0, NewPriorCond);
748
749           // Move this block to the end of the function.
750           MBB->moveAfter(--MBB->getParent()->end());
751           MadeChange = true;
752           ++NumBranchOpts;
753           return;
754         }
755       }
756     }
757   }
758   
759   // Analyze the branch in the current block.
760   MachineBasicBlock *CurTBB = 0, *CurFBB = 0;
761   std::vector<MachineOperand> CurCond;
762   bool CurUnAnalyzable = TII->AnalyzeBranch(*MBB, CurTBB, CurFBB, CurCond);
763   if (!CurUnAnalyzable) {
764     // If the CFG for the prior block has extra edges, remove them.
765     MadeChange |= CorrectExtraCFGEdges(*MBB, CurTBB, CurFBB,
766                                        !CurCond.empty(),
767                                        ++MachineFunction::iterator(MBB));
768
769     // If this is a two-way branch, and the FBB branches to this block, reverse 
770     // the condition so the single-basic-block loop is faster.  Instead of:
771     //    Loop: xxx; jcc Out; jmp Loop
772     // we want:
773     //    Loop: xxx; jncc Loop; jmp Out
774     if (CurTBB && CurFBB && CurFBB == MBB && CurTBB != MBB) {
775       std::vector<MachineOperand> NewCond(CurCond);
776       if (!TII->ReverseBranchCondition(NewCond)) {
777         TII->RemoveBranch(*MBB);
778         TII->InsertBranch(*MBB, CurFBB, CurTBB, NewCond);
779         MadeChange = true;
780         ++NumBranchOpts;
781         return OptimizeBlock(MBB);
782       }
783     }
784     
785     
786     // If this branch is the only thing in its block, see if we can forward
787     // other blocks across it.
788     if (CurTBB && CurCond.empty() && CurFBB == 0 && 
789         TII->isBranch(MBB->begin()->getOpcode()) && CurTBB != MBB) {
790       // This block may contain just an unconditional branch.  Because there can
791       // be 'non-branch terminators' in the block, try removing the branch and
792       // then seeing if the block is empty.
793       TII->RemoveBranch(*MBB);
794
795       // If this block is just an unconditional branch to CurTBB, we can
796       // usually completely eliminate the block.  The only case we cannot
797       // completely eliminate the block is when the block before this one
798       // falls through into MBB and we can't understand the prior block's branch
799       // condition.
800       if (MBB->empty()) {
801         bool PredHasNoFallThrough = TII->BlockHasNoFallThrough(PrevBB);
802         if (PredHasNoFallThrough || !PriorUnAnalyzable ||
803             !PrevBB.isSuccessor(MBB)) {
804           // If the prior block falls through into us, turn it into an
805           // explicit branch to us to make updates simpler.
806           if (!PredHasNoFallThrough && PrevBB.isSuccessor(MBB) && 
807               PriorTBB != MBB && PriorFBB != MBB) {
808             if (PriorTBB == 0) {
809               assert(PriorCond.empty() && PriorFBB == 0 &&
810                      "Bad branch analysis");
811               PriorTBB = MBB;
812             } else {
813               assert(PriorFBB == 0 && "Machine CFG out of date!");
814               PriorFBB = MBB;
815             }
816             TII->RemoveBranch(PrevBB);
817             TII->InsertBranch(PrevBB, PriorTBB, PriorFBB, PriorCond);
818           }
819
820           // Iterate through all the predecessors, revectoring each in-turn.
821           MachineBasicBlock::pred_iterator PI = MBB->pred_begin();
822           bool DidChange = false;
823           bool HasBranchToSelf = false;
824           while (PI != MBB->pred_end()) {
825             if (*PI == MBB) {
826               // If this block has an uncond branch to itself, leave it.
827               ++PI;
828               HasBranchToSelf = true;
829             } else {
830               DidChange = true;
831               ReplaceUsesOfBlockWith(*PI, MBB, CurTBB, TII);
832             }
833           }
834
835           // Change any jumptables to go to the new MBB.
836           MBB->getParent()->getJumpTableInfo()->
837             ReplaceMBBInJumpTables(MBB, CurTBB);
838           if (DidChange) {
839             ++NumBranchOpts;
840             MadeChange = true;
841             if (!HasBranchToSelf) return;
842           }
843         }
844       }
845       
846       // Add the branch back if the block is more than just an uncond branch.
847       TII->InsertBranch(*MBB, CurTBB, 0, CurCond);
848     }
849   }
850
851   // If the prior block doesn't fall through into this block, and if this
852   // block doesn't fall through into some other block, see if we can find a
853   // place to move this block where a fall-through will happen.
854   if (!CanFallThrough(&PrevBB, PriorUnAnalyzable,
855                       PriorTBB, PriorFBB, PriorCond)) {
856     // Now we know that there was no fall-through into this block, check to
857     // see if it has a fall-through into its successor.
858     bool CurFallsThru = CanFallThrough(MBB, CurUnAnalyzable, CurTBB, CurFBB, 
859                                             CurCond);
860
861     if (!MBB->isLandingPad()) {
862       // Check all the predecessors of this block.  If one of them has no fall
863       // throughs, move this block right after it.
864       for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
865            E = MBB->pred_end(); PI != E; ++PI) {
866         // Analyze the branch at the end of the pred.
867         MachineBasicBlock *PredBB = *PI;
868         MachineFunction::iterator PredFallthrough = PredBB; ++PredFallthrough;
869         if (PredBB != MBB && !CanFallThrough(PredBB)
870             && (!CurFallsThru || MBB->getNumber() >= PredBB->getNumber())) {
871           // If the current block doesn't fall through, just move it.
872           // If the current block can fall through and does not end with a
873           // conditional branch, we need to append an unconditional jump to 
874           // the (current) next block.  To avoid a possible compile-time
875           // infinite loop, move blocks only backward in this case.
876           if (CurFallsThru) {
877             MachineBasicBlock *NextBB = next(MachineFunction::iterator(MBB));
878             CurCond.clear();
879             TII->InsertBranch(*MBB, NextBB, 0, CurCond);
880           }
881           MBB->moveAfter(PredBB);
882           MadeChange = true;
883           return OptimizeBlock(MBB);
884         }
885       }
886     }
887         
888     if (!CurFallsThru) {
889       // Check all successors to see if we can move this block before it.
890       for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
891            E = MBB->succ_end(); SI != E; ++SI) {
892         // Analyze the branch at the end of the block before the succ.
893         MachineBasicBlock *SuccBB = *SI;
894         MachineFunction::iterator SuccPrev = SuccBB; --SuccPrev;
895         std::vector<MachineOperand> SuccPrevCond;
896         if (SuccBB != MBB && !CanFallThrough(SuccPrev)) {
897           MBB->moveBefore(SuccBB);
898           MadeChange = true;
899           return OptimizeBlock(MBB);
900         }
901       }
902       
903       // Okay, there is no really great place to put this block.  If, however,
904       // the block before this one would be a fall-through if this block were
905       // removed, move this block to the end of the function.
906       if (FallThrough != MBB->getParent()->end() &&
907           PrevBB.isSuccessor(FallThrough)) {
908         MBB->moveAfter(--MBB->getParent()->end());
909         MadeChange = true;
910         return;
911       }
912     }
913   }
914 }