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     // The sizes of the basic blocks in the function (the first
45     // element of the pair); the second element of the pair is the amount of the
46     // size that is due to potential padding.
47     std::vector<std::pair<unsigned, unsigned>> BlockSizes;
48 
49     bool runOnMachineFunction(MachineFunction &Fn) override;
50 
51     MachineFunctionProperties getRequiredProperties() const override {
52       return MachineFunctionProperties().set(
53           MachineFunctionProperties::Property::NoVRegs);
54     }
55 
56     const char *getPassName() const override {
57       return "PowerPC Branch Selector";
58     }
59   };
60   char PPCBSel::ID = 0;
61 }
62 
63 INITIALIZE_PASS(PPCBSel, "ppc-branch-select", "PowerPC Branch Selector",
64                 false, false)
65 
66 /// createPPCBranchSelectionPass - returns an instance of the Branch Selection
67 /// Pass
68 ///
69 FunctionPass *llvm::createPPCBranchSelectionPass() {
70   return new PPCBSel();
71 }
72 
73 bool PPCBSel::runOnMachineFunction(MachineFunction &Fn) {
74   const PPCInstrInfo *TII =
75       static_cast<const PPCInstrInfo *>(Fn.getSubtarget().getInstrInfo());
76   // Give the blocks of the function a dense, in-order, numbering.
77   Fn.RenumberBlocks();
78   BlockSizes.resize(Fn.getNumBlockIDs());
79 
80   auto GetAlignmentAdjustment =
81     [TII](MachineBasicBlock &MBB, unsigned Offset) -> unsigned {
82     unsigned Align = MBB.getAlignment();
83     if (!Align)
84       return 0;
85 
86     unsigned AlignAmt = 1 << Align;
87     unsigned ParentAlign = MBB.getParent()->getAlignment();
88 
89     if (Align <= ParentAlign)
90       return OffsetToAlignment(Offset, AlignAmt);
91 
92     // The alignment of this MBB is larger than the function's alignment, so we
93     // can't tell whether or not it will insert nops. Assume that it will.
94     return AlignAmt + OffsetToAlignment(Offset, AlignAmt);
95   };
96 
97   // Measure each MBB and compute a size for the entire function.
98   unsigned FuncSize = 0;
99   for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
100        ++MFI) {
101     MachineBasicBlock *MBB = &*MFI;
102 
103     // The end of the previous block may have extra nops if this block has an
104     // alignment requirement.
105     if (MBB->getNumber() > 0) {
106       unsigned AlignExtra = GetAlignmentAdjustment(*MBB, FuncSize);
107 
108       auto &BS = BlockSizes[MBB->getNumber()-1];
109       BS.first += AlignExtra;
110       BS.second = AlignExtra;
111 
112       FuncSize += AlignExtra;
113     }
114 
115     unsigned BlockSize = 0;
116     for (MachineInstr &MI : *MBB)
117       BlockSize += TII->getInstSizeInBytes(MI);
118 
119     BlockSizes[MBB->getNumber()].first = BlockSize;
120     FuncSize += BlockSize;
121   }
122 
123   // If the entire function is smaller than the displacement of a branch field,
124   // we know we don't need to shrink any branches in this function.  This is a
125   // common case.
126   if (FuncSize < (1 << 15)) {
127     BlockSizes.clear();
128     return false;
129   }
130 
131   // For each conditional branch, if the offset to its destination is larger
132   // than the offset field allows, transform it into a long branch sequence
133   // like this:
134   //   short branch:
135   //     bCC MBB
136   //   long branch:
137   //     b!CC $PC+8
138   //     b MBB
139   //
140   bool MadeChange = true;
141   bool EverMadeChange = false;
142   while (MadeChange) {
143     // Iteratively expand branches until we reach a fixed point.
144     MadeChange = false;
145 
146     for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
147          ++MFI) {
148       MachineBasicBlock &MBB = *MFI;
149       unsigned MBBStartOffset = 0;
150       for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
151            I != E; ++I) {
152         MachineBasicBlock *Dest = nullptr;
153         if (I->getOpcode() == PPC::BCC && !I->getOperand(2).isImm())
154           Dest = I->getOperand(2).getMBB();
155         else if ((I->getOpcode() == PPC::BC || I->getOpcode() == PPC::BCn) &&
156                  !I->getOperand(1).isImm())
157           Dest = I->getOperand(1).getMBB();
158         else if ((I->getOpcode() == PPC::BDNZ8 || I->getOpcode() == PPC::BDNZ ||
159                   I->getOpcode() == PPC::BDZ8  || I->getOpcode() == PPC::BDZ) &&
160                  !I->getOperand(0).isImm())
161           Dest = I->getOperand(0).getMBB();
162 
163         if (!Dest) {
164           MBBStartOffset += TII->getInstSizeInBytes(*I);
165           continue;
166         }
167 
168         // Determine the offset from the current branch to the destination
169         // block.
170         int BranchSize;
171         if (Dest->getNumber() <= MBB.getNumber()) {
172           // If this is a backwards branch, the delta is the offset from the
173           // start of this block to this branch, plus the sizes of all blocks
174           // from this block to the dest.
175           BranchSize = MBBStartOffset;
176 
177           for (unsigned i = Dest->getNumber(), e = MBB.getNumber(); i != e; ++i)
178             BranchSize += BlockSizes[i].first;
179         } else {
180           // Otherwise, add the size of the blocks between this block and the
181           // dest to the number of bytes left in this block.
182           BranchSize = -MBBStartOffset;
183 
184           for (unsigned i = MBB.getNumber(), e = Dest->getNumber(); i != e; ++i)
185             BranchSize += BlockSizes[i].first;
186         }
187 
188         // If this branch is in range, ignore it.
189         if (isInt<16>(BranchSize)) {
190           MBBStartOffset += 4;
191           continue;
192         }
193 
194         // Otherwise, we have to expand it to a long branch.
195         MachineInstr &OldBranch = *I;
196         DebugLoc dl = OldBranch.getDebugLoc();
197 
198         if (I->getOpcode() == PPC::BCC) {
199           // The BCC operands are:
200           // 0. PPC branch predicate
201           // 1. CR register
202           // 2. Target MBB
203           PPC::Predicate Pred = (PPC::Predicate)I->getOperand(0).getImm();
204           unsigned CRReg = I->getOperand(1).getReg();
205 
206           // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition.
207           BuildMI(MBB, I, dl, TII->get(PPC::BCC))
208             .addImm(PPC::InvertPredicate(Pred)).addReg(CRReg).addImm(2);
209         } else if (I->getOpcode() == PPC::BC) {
210           unsigned CRBit = I->getOperand(0).getReg();
211           BuildMI(MBB, I, dl, TII->get(PPC::BCn)).addReg(CRBit).addImm(2);
212         } else if (I->getOpcode() == PPC::BCn) {
213           unsigned CRBit = I->getOperand(0).getReg();
214           BuildMI(MBB, I, dl, TII->get(PPC::BC)).addReg(CRBit).addImm(2);
215         } else if (I->getOpcode() == PPC::BDNZ) {
216           BuildMI(MBB, I, dl, TII->get(PPC::BDZ)).addImm(2);
217         } else if (I->getOpcode() == PPC::BDNZ8) {
218           BuildMI(MBB, I, dl, TII->get(PPC::BDZ8)).addImm(2);
219         } else if (I->getOpcode() == PPC::BDZ) {
220           BuildMI(MBB, I, dl, TII->get(PPC::BDNZ)).addImm(2);
221         } else if (I->getOpcode() == PPC::BDZ8) {
222           BuildMI(MBB, I, dl, TII->get(PPC::BDNZ8)).addImm(2);
223         } else {
224            llvm_unreachable("Unhandled branch type!");
225         }
226 
227         // Uncond branch to the real destination.
228         I = BuildMI(MBB, I, dl, TII->get(PPC::B)).addMBB(Dest);
229 
230         // Remove the old branch from the function.
231         OldBranch.eraseFromParent();
232 
233         // Remember that this instruction is 8-bytes, increase the size of the
234         // block by 4, remember to iterate.
235         BlockSizes[MBB.getNumber()].first += 4;
236         MBBStartOffset += 8;
237         ++NumExpanded;
238         MadeChange = true;
239       }
240     }
241 
242     if (MadeChange) {
243       // If we're going to iterate again, make sure we've updated our
244       // padding-based contributions to the block sizes.
245       unsigned Offset = 0;
246       for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
247            ++MFI) {
248         MachineBasicBlock *MBB = &*MFI;
249 
250         if (MBB->getNumber() > 0) {
251           auto &BS = BlockSizes[MBB->getNumber()-1];
252           BS.first -= BS.second;
253           Offset -= BS.second;
254 
255           unsigned AlignExtra = GetAlignmentAdjustment(*MBB, Offset);
256 
257           BS.first += AlignExtra;
258           BS.second = AlignExtra;
259 
260           Offset += AlignExtra;
261         }
262 
263         Offset += BlockSizes[MBB->getNumber()].first;
264       }
265     }
266 
267     EverMadeChange |= MadeChange;
268   }
269 
270   BlockSizes.clear();
271   return true;
272 }
273