1 //===-- PPCBranchSelector.cpp - Emit long conditional branches ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This 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 pseudo 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 "MCTargetDesc/PPCPredicates.h"
20 #include "PPCInstrBuilder.h"
21 #include "PPCInstrInfo.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Target/TargetSubtargetInfo.h"
27 using namespace llvm;
28 
29 #define DEBUG_TYPE "ppc-branch-select"
30 
31 STATISTIC(NumExpanded, "Number of branches expanded to long format");
32 
33 namespace llvm {
34   void initializePPCBSelPass(PassRegistry&);
35 }
36 
37 namespace {
38   struct PPCBSel : public MachineFunctionPass {
39     static char ID;
40     PPCBSel() : MachineFunctionPass(ID) {
41       initializePPCBSelPass(*PassRegistry::getPassRegistry());
42     }
43 
44     /// BlockSizes - The sizes of the basic blocks in the function.
45     std::vector<unsigned> BlockSizes;
46 
47     bool runOnMachineFunction(MachineFunction &Fn) override;
48 
49     MachineFunctionProperties getRequiredProperties() const override {
50       return MachineFunctionProperties().set(
51           MachineFunctionProperties::Property::AllVRegsAllocated);
52     }
53 
54     const char *getPassName() const override {
55       return "PowerPC Branch Selector";
56     }
57   };
58   char PPCBSel::ID = 0;
59 }
60 
61 INITIALIZE_PASS(PPCBSel, "ppc-branch-select", "PowerPC Branch Selector",
62                 false, false)
63 
64 /// createPPCBranchSelectionPass - returns an instance of the Branch Selection
65 /// Pass
66 ///
67 FunctionPass *llvm::createPPCBranchSelectionPass() {
68   return new PPCBSel();
69 }
70 
71 bool PPCBSel::runOnMachineFunction(MachineFunction &Fn) {
72   const PPCInstrInfo *TII =
73       static_cast<const PPCInstrInfo *>(Fn.getSubtarget().getInstrInfo());
74   // Give the blocks of the function a dense, in-order, numbering.
75   Fn.RenumberBlocks();
76   BlockSizes.resize(Fn.getNumBlockIDs());
77 
78   auto GetAlignmentAdjustment =
79     [TII](MachineBasicBlock &MBB, unsigned Offset) -> unsigned {
80     unsigned Align = MBB.getAlignment();
81     if (!Align)
82       return 0;
83 
84     unsigned AlignAmt = 1 << Align;
85     unsigned ParentAlign = MBB.getParent()->getAlignment();
86 
87     if (Align <= ParentAlign)
88       return OffsetToAlignment(Offset, AlignAmt);
89 
90     // The alignment of this MBB is larger than the function's alignment, so we
91     // can't tell whether or not it will insert nops. Assume that it will.
92     return AlignAmt + OffsetToAlignment(Offset, AlignAmt);
93   };
94 
95   // Measure each MBB and compute a size for the entire function.
96   unsigned FuncSize = 0;
97   for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
98        ++MFI) {
99     MachineBasicBlock *MBB = &*MFI;
100 
101     // The end of the previous block may have extra nops if this block has an
102     // alignment requirement.
103     if (MBB->getNumber() > 0) {
104       unsigned AlignExtra = GetAlignmentAdjustment(*MBB, FuncSize);
105       BlockSizes[MBB->getNumber()-1] += AlignExtra;
106       FuncSize += AlignExtra;
107     }
108 
109     unsigned BlockSize = 0;
110     for (MachineBasicBlock::iterator MBBI = MBB->begin(), EE = MBB->end();
111          MBBI != EE; ++MBBI)
112       BlockSize += TII->GetInstSizeInBytes(MBBI);
113 
114     BlockSizes[MBB->getNumber()] = BlockSize;
115     FuncSize += BlockSize;
116   }
117 
118   // If the entire function is smaller than the displacement of a branch field,
119   // we know we don't need to shrink any branches in this function.  This is a
120   // common case.
121   if (FuncSize < (1 << 15)) {
122     BlockSizes.clear();
123     return false;
124   }
125 
126   // For each conditional branch, if the offset to its destination is larger
127   // than the offset field allows, transform it into a long branch sequence
128   // like this:
129   //   short branch:
130   //     bCC MBB
131   //   long branch:
132   //     b!CC $PC+8
133   //     b MBB
134   //
135   bool MadeChange = true;
136   bool EverMadeChange = false;
137   while (MadeChange) {
138     // Iteratively expand branches until we reach a fixed point.
139     MadeChange = false;
140 
141     for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
142          ++MFI) {
143       MachineBasicBlock &MBB = *MFI;
144       unsigned MBBStartOffset = 0;
145       for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
146            I != E; ++I) {
147         MachineBasicBlock *Dest = nullptr;
148         if (I->getOpcode() == PPC::BCC && !I->getOperand(2).isImm())
149           Dest = I->getOperand(2).getMBB();
150         else if ((I->getOpcode() == PPC::BC || I->getOpcode() == PPC::BCn) &&
151                  !I->getOperand(1).isImm())
152           Dest = I->getOperand(1).getMBB();
153         else if ((I->getOpcode() == PPC::BDNZ8 || I->getOpcode() == PPC::BDNZ ||
154                   I->getOpcode() == PPC::BDZ8  || I->getOpcode() == PPC::BDZ) &&
155                  !I->getOperand(0).isImm())
156           Dest = I->getOperand(0).getMBB();
157 
158         if (!Dest) {
159           MBBStartOffset += TII->GetInstSizeInBytes(I);
160           continue;
161         }
162 
163         // Determine the offset from the current branch to the destination
164         // block.
165         int BranchSize;
166         if (Dest->getNumber() <= MBB.getNumber()) {
167           // If this is a backwards branch, the delta is the offset from the
168           // start of this block to this branch, plus the sizes of all blocks
169           // from this block to the dest.
170           BranchSize = MBBStartOffset;
171 
172           for (unsigned i = Dest->getNumber(), e = MBB.getNumber(); i != e; ++i)
173             BranchSize += BlockSizes[i];
174         } else {
175           // Otherwise, add the size of the blocks between this block and the
176           // dest to the number of bytes left in this block.
177           BranchSize = -MBBStartOffset;
178 
179           for (unsigned i = MBB.getNumber(), e = Dest->getNumber(); i != e; ++i)
180             BranchSize += BlockSizes[i];
181         }
182 
183         // If this branch is in range, ignore it.
184         if (isInt<16>(BranchSize)) {
185           MBBStartOffset += 4;
186           continue;
187         }
188 
189         // Otherwise, we have to expand it to a long branch.
190         MachineInstr *OldBranch = I;
191         DebugLoc dl = OldBranch->getDebugLoc();
192 
193         if (I->getOpcode() == PPC::BCC) {
194           // The BCC operands are:
195           // 0. PPC branch predicate
196           // 1. CR register
197           // 2. Target MBB
198           PPC::Predicate Pred = (PPC::Predicate)I->getOperand(0).getImm();
199           unsigned CRReg = I->getOperand(1).getReg();
200 
201           // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition.
202           BuildMI(MBB, I, dl, TII->get(PPC::BCC))
203             .addImm(PPC::InvertPredicate(Pred)).addReg(CRReg).addImm(2);
204         } else if (I->getOpcode() == PPC::BC) {
205           unsigned CRBit = I->getOperand(0).getReg();
206           BuildMI(MBB, I, dl, TII->get(PPC::BCn)).addReg(CRBit).addImm(2);
207         } else if (I->getOpcode() == PPC::BCn) {
208           unsigned CRBit = I->getOperand(0).getReg();
209           BuildMI(MBB, I, dl, TII->get(PPC::BC)).addReg(CRBit).addImm(2);
210         } else if (I->getOpcode() == PPC::BDNZ) {
211           BuildMI(MBB, I, dl, TII->get(PPC::BDZ)).addImm(2);
212         } else if (I->getOpcode() == PPC::BDNZ8) {
213           BuildMI(MBB, I, dl, TII->get(PPC::BDZ8)).addImm(2);
214         } else if (I->getOpcode() == PPC::BDZ) {
215           BuildMI(MBB, I, dl, TII->get(PPC::BDNZ)).addImm(2);
216         } else if (I->getOpcode() == PPC::BDZ8) {
217           BuildMI(MBB, I, dl, TII->get(PPC::BDNZ8)).addImm(2);
218         } else {
219            llvm_unreachable("Unhandled branch type!");
220         }
221 
222         // Uncond branch to the real destination.
223         I = BuildMI(MBB, I, dl, TII->get(PPC::B)).addMBB(Dest);
224 
225         // Remove the old branch from the function.
226         OldBranch->eraseFromParent();
227 
228         // Remember that this instruction is 8-bytes, increase the size of the
229         // block by 4, remember to iterate.
230         BlockSizes[MBB.getNumber()] += 4;
231         MBBStartOffset += 8;
232         ++NumExpanded;
233         MadeChange = true;
234       }
235     }
236     EverMadeChange |= MadeChange;
237   }
238 
239   BlockSizes.clear();
240   return true;
241 }
242