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     StringRef getPassName() const override { return "PowerPC Branch Selector"; }
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 
106       auto &BS = BlockSizes[MBB->getNumber()-1];
107       BS.first += AlignExtra;
108       BS.second = AlignExtra;
109 
110       FuncSize += AlignExtra;
111     }
112 
113     unsigned BlockSize = 0;
114     for (MachineInstr &MI : *MBB)
115       BlockSize += TII->getInstSizeInBytes(MI);
116 
117     BlockSizes[MBB->getNumber()].first = BlockSize;
118     FuncSize += BlockSize;
119   }
120 
121   // If the entire function is smaller than the displacement of a branch field,
122   // we know we don't need to shrink any branches in this function.  This is a
123   // common case.
124   if (FuncSize < (1 << 15)) {
125     BlockSizes.clear();
126     return false;
127   }
128 
129   // For each conditional branch, if the offset to its destination is larger
130   // than the offset field allows, transform it into a long branch sequence
131   // like this:
132   //   short branch:
133   //     bCC MBB
134   //   long branch:
135   //     b!CC $PC+8
136   //     b MBB
137   //
138   bool MadeChange = true;
139   bool EverMadeChange = false;
140   while (MadeChange) {
141     // Iteratively expand branches until we reach a fixed point.
142     MadeChange = false;
143 
144     for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
145          ++MFI) {
146       MachineBasicBlock &MBB = *MFI;
147       unsigned MBBStartOffset = 0;
148       for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
149            I != E; ++I) {
150         MachineBasicBlock *Dest = nullptr;
151         if (I->getOpcode() == PPC::BCC && !I->getOperand(2).isImm())
152           Dest = I->getOperand(2).getMBB();
153         else if ((I->getOpcode() == PPC::BC || I->getOpcode() == PPC::BCn) &&
154                  !I->getOperand(1).isImm())
155           Dest = I->getOperand(1).getMBB();
156         else if ((I->getOpcode() == PPC::BDNZ8 || I->getOpcode() == PPC::BDNZ ||
157                   I->getOpcode() == PPC::BDZ8  || I->getOpcode() == PPC::BDZ) &&
158                  !I->getOperand(0).isImm())
159           Dest = I->getOperand(0).getMBB();
160 
161         if (!Dest) {
162           MBBStartOffset += TII->getInstSizeInBytes(*I);
163           continue;
164         }
165 
166         // Determine the offset from the current branch to the destination
167         // block.
168         int BranchSize;
169         if (Dest->getNumber() <= MBB.getNumber()) {
170           // If this is a backwards branch, the delta is the offset from the
171           // start of this block to this branch, plus the sizes of all blocks
172           // from this block to the dest.
173           BranchSize = MBBStartOffset;
174 
175           for (unsigned i = Dest->getNumber(), e = MBB.getNumber(); i != e; ++i)
176             BranchSize += BlockSizes[i].first;
177         } else {
178           // Otherwise, add the size of the blocks between this block and the
179           // dest to the number of bytes left in this block.
180           BranchSize = -MBBStartOffset;
181 
182           for (unsigned i = MBB.getNumber(), e = Dest->getNumber(); i != e; ++i)
183             BranchSize += BlockSizes[i].first;
184         }
185 
186         // If this branch is in range, ignore it.
187         if (isInt<16>(BranchSize)) {
188           MBBStartOffset += 4;
189           continue;
190         }
191 
192         // Otherwise, we have to expand it to a long branch.
193         MachineInstr &OldBranch = *I;
194         DebugLoc dl = OldBranch.getDebugLoc();
195 
196         if (I->getOpcode() == PPC::BCC) {
197           // The BCC operands are:
198           // 0. PPC branch predicate
199           // 1. CR register
200           // 2. Target MBB
201           PPC::Predicate Pred = (PPC::Predicate)I->getOperand(0).getImm();
202           unsigned CRReg = I->getOperand(1).getReg();
203 
204           // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition.
205           BuildMI(MBB, I, dl, TII->get(PPC::BCC))
206             .addImm(PPC::InvertPredicate(Pred)).addReg(CRReg).addImm(2);
207         } else if (I->getOpcode() == PPC::BC) {
208           unsigned CRBit = I->getOperand(0).getReg();
209           BuildMI(MBB, I, dl, TII->get(PPC::BCn)).addReg(CRBit).addImm(2);
210         } else if (I->getOpcode() == PPC::BCn) {
211           unsigned CRBit = I->getOperand(0).getReg();
212           BuildMI(MBB, I, dl, TII->get(PPC::BC)).addReg(CRBit).addImm(2);
213         } else if (I->getOpcode() == PPC::BDNZ) {
214           BuildMI(MBB, I, dl, TII->get(PPC::BDZ)).addImm(2);
215         } else if (I->getOpcode() == PPC::BDNZ8) {
216           BuildMI(MBB, I, dl, TII->get(PPC::BDZ8)).addImm(2);
217         } else if (I->getOpcode() == PPC::BDZ) {
218           BuildMI(MBB, I, dl, TII->get(PPC::BDNZ)).addImm(2);
219         } else if (I->getOpcode() == PPC::BDZ8) {
220           BuildMI(MBB, I, dl, TII->get(PPC::BDNZ8)).addImm(2);
221         } else {
222            llvm_unreachable("Unhandled branch type!");
223         }
224 
225         // Uncond branch to the real destination.
226         I = BuildMI(MBB, I, dl, TII->get(PPC::B)).addMBB(Dest);
227 
228         // Remove the old branch from the function.
229         OldBranch.eraseFromParent();
230 
231         // Remember that this instruction is 8-bytes, increase the size of the
232         // block by 4, remember to iterate.
233         BlockSizes[MBB.getNumber()].first += 4;
234         MBBStartOffset += 8;
235         ++NumExpanded;
236         MadeChange = true;
237       }
238     }
239 
240     if (MadeChange) {
241       // If we're going to iterate again, make sure we've updated our
242       // padding-based contributions to the block sizes.
243       unsigned Offset = 0;
244       for (MachineFunction::iterator MFI = Fn.begin(), E = Fn.end(); MFI != E;
245            ++MFI) {
246         MachineBasicBlock *MBB = &*MFI;
247 
248         if (MBB->getNumber() > 0) {
249           auto &BS = BlockSizes[MBB->getNumber()-1];
250           BS.first -= BS.second;
251           Offset -= BS.second;
252 
253           unsigned AlignExtra = GetAlignmentAdjustment(*MBB, Offset);
254 
255           BS.first += AlignExtra;
256           BS.second = AlignExtra;
257 
258           Offset += AlignExtra;
259         }
260 
261         Offset += BlockSizes[MBB->getNumber()].first;
262       }
263     }
264 
265     EverMadeChange |= MadeChange;
266   }
267 
268   BlockSizes.clear();
269   return true;
270 }
271