Rewrite the branch selector to be correct in the face of large functions.
[oota-llvm.git] / lib / Target / PowerPC / PPCBranchSelector.cpp
1 //===-- PPCBranchSelector.cpp - Emit long conditional branches-----*- C++ -*-=//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Nate Baegeman and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a pass that scans a machine function to determine which
11 // conditional branches need more than 16 bits of displacement to reach their
12 // target basic block.  It does this in two passes; a calculation of basic block
13 // positions pass, and a branch psuedo op to machine branch opcode pass.  This
14 // pass should be run last, just before the assembly printer.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "PPC.h"
19 #include "PPCInstrBuilder.h"
20 #include "PPCInstrInfo.h"
21 #include "PPCPredicates.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Support/Compiler.h"
27 #include "llvm/Support/MathExtras.h"
28 using namespace llvm;
29
30 static Statistic<> NumExpanded("ppc-branch-select",
31                                "Num branches expanded to long format");
32
33 namespace {
34   struct VISIBILITY_HIDDEN PPCBSel : public MachineFunctionPass {
35     /// BlockSizes - The sizes of the basic blocks in the function.
36     std::vector<unsigned> BlockSizes;
37
38     virtual bool runOnMachineFunction(MachineFunction &Fn);
39
40     virtual const char *getPassName() const {
41       return "PowerPC Branch Selector";
42     }
43   };
44 }
45
46 /// createPPCBranchSelectionPass - returns an instance of the Branch Selection
47 /// Pass
48 ///
49 FunctionPass *llvm::createPPCBranchSelectionPass() {
50   return new PPCBSel();
51 }
52
53 /// getNumBytesForInstruction - Return the number of bytes of code the specified
54 /// instruction may be.  This returns the maximum number of bytes.
55 ///
56 static unsigned getNumBytesForInstruction(MachineInstr *MI) {
57   switch (MI->getOpcode()) {
58   case PPC::IMPLICIT_DEF_GPRC: // no asm emitted
59   case PPC::IMPLICIT_DEF_G8RC: // no asm emitted
60   case PPC::IMPLICIT_DEF_F4:   // no asm emitted
61   case PPC::IMPLICIT_DEF_F8:   // no asm emitted
62   case PPC::IMPLICIT_DEF_VRRC: // no asm emitted
63     return 0;
64   case PPC::INLINEASM: {       // Inline Asm: Variable size.
65     MachineFunction *MF = MI->getParent()->getParent();
66     const char *AsmStr = MI->getOperand(0).getSymbolName();
67     return MF->getTarget().getTargetAsmInfo()->getInlineAsmLength(AsmStr);
68   }
69   default:
70     return 4; // PowerPC instructions are all 4 bytes
71   }
72 }
73
74
75 bool PPCBSel::runOnMachineFunction(MachineFunction &Fn) {
76   // Give the blocks of the function a dense, in-order, numbering.
77   Fn.RenumberBlocks();
78   BlockSizes.resize(Fn.getNumBlockIDs());
79
80   // Measure each MBB and compute a size for the entire function.
81   unsigned FuncSize = 0;
82   for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
83        ++MFI) {
84     MachineBasicBlock *MBB = MFI;
85
86     unsigned BlockSize = 0;
87     for (MachineBasicBlock::iterator MBBI = MBB->begin(), EE = MBB->end();
88          MBBI != EE; ++MBBI)
89       BlockSize += getNumBytesForInstruction(MBBI);
90     
91     BlockSizes[MBB->getNumber()] = BlockSize;
92     FuncSize += BlockSize;
93   }
94   
95   // If the entire function is smaller than the displacement of a branch field,
96   // we know we don't need to shrink any branches in this function.  This is a
97   // common case.
98   if (FuncSize < (1 << 15)) {
99     BlockSizes.clear();
100     return false;
101   }
102   
103   // For each conditional branch, if the offset to its destination is larger
104   // than the offset field allows, transform it into a long branch sequence
105   // like this:
106   //   short branch:
107   //     bCC MBB
108   //   long branch:
109   //     b!CC $PC+8
110   //     b MBB
111   //
112   bool MadeChange = true;
113   bool EverMadeChange = false;
114   while (MadeChange) {
115     // Iteratively expand branches until we reach a fixed point.
116     MadeChange = false;
117   
118     for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
119          ++MFI) {
120       MachineBasicBlock &MBB = *MFI;
121       unsigned MBBStartOffset = 0;
122       for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
123            I != E; ++I) {
124         if (I->getOpcode() != PPC::BCC || I->getOperand(2).isImm()) {
125           MBBStartOffset += getNumBytesForInstruction(I);
126           continue;
127         }
128         
129         // Determine the offset from the current branch to the destination
130         // block.
131         MachineBasicBlock *Dest = I->getOperand(2).getMachineBasicBlock();
132         
133         int BranchSize;
134         if (Dest->getNumber() <= MBB.getNumber()) {
135           // If this is a backwards branch, the delta is the offset from the
136           // start of this block to this branch, plus the sizes of all blocks
137           // from this block to the dest.
138           BranchSize = MBBStartOffset;
139           
140           for (unsigned i = Dest->getNumber(), e = MBB.getNumber(); i != e; ++i)
141             BranchSize += BlockSizes[i];
142         } else {
143           // Otherwise, add the size of the blocks between this block and the
144           // dest to the number of bytes left in this block.
145           BranchSize = -MBBStartOffset;
146
147           for (unsigned i = MBB.getNumber(), e = Dest->getNumber(); i != e; ++i)
148             BranchSize += BlockSizes[i];
149         }
150
151         // If this branch is in range, ignore it.
152         if (isInt16(BranchSize)) {
153           MBBStartOffset += 4;
154           continue;
155         }
156         
157         // Otherwise, we have to expand it to a long branch.
158         // The BCC operands are:
159         // 0. PPC branch predicate
160         // 1. CR register
161         // 2. Target MBB
162         PPC::Predicate Pred = (PPC::Predicate)I->getOperand(0).getImm();
163         unsigned CRReg = I->getOperand(1).getReg();
164         
165         MachineInstr *OldBranch = I;
166         
167         // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition.
168         BuildMI(MBB, I, PPC::BCC, 3)
169           .addImm(PPC::InvertPredicate(Pred)).addReg(CRReg).addImm(2);
170         
171         // Uncond branch to the real destination.
172         I = BuildMI(MBB, I, PPC::B, 1).addMBB(Dest);
173
174         // Remove the old branch from the function.
175         OldBranch->eraseFromParent();
176         
177         // Remember that this instruction is 8-bytes, increase the size of the
178         // block by 4, remember to iterate.
179         BlockSizes[MBB.getNumber()] += 4;
180         MBBStartOffset += 8;
181         ++NumExpanded;
182         MadeChange = true;
183       }
184     }
185     EverMadeChange |= MadeChange;
186   }
187   
188   BlockSizes.clear();
189   return true;
190 }
191