1 //===-- PPCBranchSelector.cpp - Emit long conditional branches ------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file contains a pass that scans a machine function to determine which
10 // conditional branches need more than 16 bits of displacement to reach their
11 // target basic block. It does this in two passes; a calculation of basic block
12 // positions pass, and a branch pseudo op to machine branch opcode pass. This
13 // pass should be run last, just before the assembly printer.
15 //===----------------------------------------------------------------------===//
17 #include "MCTargetDesc/PPCPredicates.h"
19 #include "PPCInstrInfo.h"
20 #include "PPCSubtarget.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/TargetSubtargetInfo.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Target/TargetMachine.h"
30 #define DEBUG_TYPE "ppc-branch-select"
32 STATISTIC(NumExpanded
, "Number of branches expanded to long format");
33 STATISTIC(NumPrefixed
, "Number of prefixed instructions");
34 STATISTIC(NumPrefixedAligned
,
35 "Number of prefixed instructions that have been aligned");
38 struct PPCBSel
: public MachineFunctionPass
{
40 PPCBSel() : MachineFunctionPass(ID
) {
41 initializePPCBSelPass(*PassRegistry::getPassRegistry());
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
;
49 // The first block number which has imprecise instruction address.
50 int FirstImpreciseBlock
= -1;
52 unsigned GetAlignmentAdjustment(MachineBasicBlock
&MBB
, unsigned Offset
);
53 unsigned ComputeBlockSizes(MachineFunction
&Fn
);
54 void modifyAdjustment(MachineFunction
&Fn
);
55 int computeBranchSize(MachineFunction
&Fn
,
56 const MachineBasicBlock
*Src
,
57 const MachineBasicBlock
*Dest
,
60 bool runOnMachineFunction(MachineFunction
&Fn
) override
;
62 MachineFunctionProperties
getRequiredProperties() const override
{
63 return MachineFunctionProperties().set(
64 MachineFunctionProperties::Property::NoVRegs
);
67 StringRef
getPassName() const override
{ return "PowerPC Branch Selector"; }
72 INITIALIZE_PASS(PPCBSel
, "ppc-branch-select", "PowerPC Branch Selector",
75 /// createPPCBranchSelectionPass - returns an instance of the Branch Selection
78 FunctionPass
*llvm::createPPCBranchSelectionPass() {
82 /// In order to make MBB aligned, we need to add an adjustment value to the
84 unsigned PPCBSel::GetAlignmentAdjustment(MachineBasicBlock
&MBB
,
86 const Align Alignment
= MBB
.getAlignment();
87 if (Alignment
== Align(1))
90 const Align ParentAlign
= MBB
.getParent()->getAlignment();
92 if (Alignment
<= ParentAlign
)
93 return offsetToAlignment(Offset
, Alignment
);
95 // The alignment of this MBB is larger than the function's alignment, so we
96 // can't tell whether or not it will insert nops. Assume that it will.
97 if (FirstImpreciseBlock
< 0)
98 FirstImpreciseBlock
= MBB
.getNumber();
99 return Alignment
.value() + offsetToAlignment(Offset
, Alignment
);
102 /// We need to be careful about the offset of the first block in the function
103 /// because it might not have the function's alignment. This happens because,
104 /// under the ELFv2 ABI, for functions which require a TOC pointer, we add a
105 /// two-instruction sequence to the start of the function.
106 /// Note: This needs to be synchronized with the check in
107 /// PPCLinuxAsmPrinter::EmitFunctionBodyStart.
108 static inline unsigned GetInitialOffset(MachineFunction
&Fn
) {
109 unsigned InitialOffset
= 0;
110 if (Fn
.getSubtarget
<PPCSubtarget
>().isELFv2ABI() &&
111 !Fn
.getRegInfo().use_empty(PPC::X2
))
113 return InitialOffset
;
116 /// Measure each MBB and compute a size for the entire function.
117 unsigned PPCBSel::ComputeBlockSizes(MachineFunction
&Fn
) {
118 const PPCInstrInfo
*TII
=
119 static_cast<const PPCInstrInfo
*>(Fn
.getSubtarget().getInstrInfo());
120 unsigned FuncSize
= GetInitialOffset(Fn
);
122 for (MachineBasicBlock
&MBB
: Fn
) {
123 // The end of the previous block may have extra nops if this block has an
124 // alignment requirement.
125 if (MBB
.getNumber() > 0) {
126 unsigned AlignExtra
= GetAlignmentAdjustment(MBB
, FuncSize
);
128 auto &BS
= BlockSizes
[MBB
.getNumber()-1];
129 BS
.first
+= AlignExtra
;
130 BS
.second
= AlignExtra
;
132 FuncSize
+= AlignExtra
;
135 unsigned BlockSize
= 0;
136 unsigned UnalignedBytesRemaining
= 0;
137 for (MachineInstr
&MI
: MBB
) {
138 unsigned MINumBytes
= TII
->getInstSizeInBytes(MI
);
139 if (MI
.isInlineAsm() && (FirstImpreciseBlock
< 0))
140 FirstImpreciseBlock
= MBB
.getNumber();
141 if (TII
->isPrefixed(MI
.getOpcode())) {
144 // All 8 byte instructions may require alignment. Each 8 byte
145 // instruction may be aligned by another 4 bytes.
146 // This means that an 8 byte instruction may require 12 bytes
147 // (8 for the instruction itself and 4 for the alignment nop).
148 // This will happen if an 8 byte instruction can be aligned to 64 bytes
149 // by only adding a 4 byte nop.
150 // We don't know the alignment at this point in the code so we have to
151 // adopt a more pessimistic approach. If an instruction may need
152 // alignment we assume that it does need alignment and add 4 bytes to
153 // it. As a result we may end up with more long branches than before
154 // but we are in the safe position where if we need a long branch we
156 // The if statement checks to make sure that two 8 byte instructions
157 // are at least 64 bytes away from each other. It is not possible for
158 // two instructions that both need alignment to be within 64 bytes of
160 if (!UnalignedBytesRemaining
) {
162 UnalignedBytesRemaining
= 60;
163 NumPrefixedAligned
++;
166 UnalignedBytesRemaining
-= std::min(UnalignedBytesRemaining
, MINumBytes
);
167 BlockSize
+= MINumBytes
;
170 BlockSizes
[MBB
.getNumber()].first
= BlockSize
;
171 FuncSize
+= BlockSize
;
177 /// Modify the basic block align adjustment.
178 void PPCBSel::modifyAdjustment(MachineFunction
&Fn
) {
179 unsigned Offset
= GetInitialOffset(Fn
);
180 for (MachineBasicBlock
&MBB
: Fn
) {
181 if (MBB
.getNumber() > 0) {
182 auto &BS
= BlockSizes
[MBB
.getNumber()-1];
183 BS
.first
-= BS
.second
;
186 unsigned AlignExtra
= GetAlignmentAdjustment(MBB
, Offset
);
188 BS
.first
+= AlignExtra
;
189 BS
.second
= AlignExtra
;
191 Offset
+= AlignExtra
;
194 Offset
+= BlockSizes
[MBB
.getNumber()].first
;
198 /// Determine the offset from the branch in Src block to the Dest block.
199 /// BrOffset is the offset of the branch instruction inside Src block.
200 int PPCBSel::computeBranchSize(MachineFunction
&Fn
,
201 const MachineBasicBlock
*Src
,
202 const MachineBasicBlock
*Dest
,
205 Align MaxAlign
= Align(4);
206 bool NeedExtraAdjustment
= false;
207 if (Dest
->getNumber() <= Src
->getNumber()) {
208 // If this is a backwards branch, the delta is the offset from the
209 // start of this block to this branch, plus the sizes of all blocks
210 // from this block to the dest.
211 BranchSize
= BrOffset
;
212 MaxAlign
= std::max(MaxAlign
, Src
->getAlignment());
214 int DestBlock
= Dest
->getNumber();
215 BranchSize
+= BlockSizes
[DestBlock
].first
;
216 for (unsigned i
= DestBlock
+1, e
= Src
->getNumber(); i
< e
; ++i
) {
217 BranchSize
+= BlockSizes
[i
].first
;
218 MaxAlign
= std::max(MaxAlign
, Fn
.getBlockNumbered(i
)->getAlignment());
221 NeedExtraAdjustment
= (FirstImpreciseBlock
>= 0) &&
222 (DestBlock
>= FirstImpreciseBlock
);
224 // Otherwise, add the size of the blocks between this block and the
225 // dest to the number of bytes left in this block.
226 unsigned StartBlock
= Src
->getNumber();
227 BranchSize
= BlockSizes
[StartBlock
].first
- BrOffset
;
229 MaxAlign
= std::max(MaxAlign
, Dest
->getAlignment());
230 for (unsigned i
= StartBlock
+1, e
= Dest
->getNumber(); i
!= e
; ++i
) {
231 BranchSize
+= BlockSizes
[i
].first
;
232 MaxAlign
= std::max(MaxAlign
, Fn
.getBlockNumbered(i
)->getAlignment());
235 NeedExtraAdjustment
= (FirstImpreciseBlock
>= 0) &&
236 (Src
->getNumber() >= FirstImpreciseBlock
);
239 // We tend to over estimate code size due to large alignment and
240 // inline assembly. Usually it causes larger computed branch offset.
241 // But sometimes it may also causes smaller computed branch offset
242 // than actual branch offset. If the offset is close to the limit of
243 // encoding, it may cause problem at run time.
244 // Following is a simplified example.
255 // Actual offset: 0x8108 - 0x100 = 0x8008
256 // Computed offset: 0x8108 - 0x10c = 0x7ffc
258 // This example also shows when we can get the largest gap between
259 // estimated offset and actual offset. If there is an aligned block
260 // ABB between branch and target, assume its alignment is <align>
261 // bits. Now consider the accumulated function size FSIZE till the end
262 // of previous block PBB. If the estimated FSIZE is multiple of
263 // 2^<align>, we don't need any padding for the estimated address of
264 // ABB. If actual FSIZE at the end of PBB is 4 bytes more than
265 // multiple of 2^<align>, then we need (2^<align> - 4) bytes of
266 // padding. It also means the actual branch offset is (2^<align> - 4)
267 // larger than computed offset. Other actual FSIZE needs less padding
268 // bytes, so causes smaller gap between actual and computed offset.
270 // On the other hand, if the inline asm or large alignment occurs
271 // between the branch block and destination block, the estimated address
272 // can be <delta> larger than actual address. If padding bytes are
273 // needed for a later aligned block, the actual number of padding bytes
274 // is at most <delta> more than estimated padding bytes. So the actual
275 // aligned block address is less than or equal to the estimated aligned
276 // block address. So the actual branch offset is less than or equal to
277 // computed branch offset.
279 // The computed offset is at most ((1 << alignment) - 4) bytes smaller
280 // than actual offset. So we add this number to the offset for safety.
281 if (NeedExtraAdjustment
)
282 BranchSize
+= MaxAlign
.value() - 4;
287 bool PPCBSel::runOnMachineFunction(MachineFunction
&Fn
) {
288 const PPCInstrInfo
*TII
=
289 static_cast<const PPCInstrInfo
*>(Fn
.getSubtarget().getInstrInfo());
290 // Give the blocks of the function a dense, in-order, numbering.
292 BlockSizes
.resize(Fn
.getNumBlockIDs());
293 FirstImpreciseBlock
= -1;
295 // Measure each MBB and compute a size for the entire function.
296 unsigned FuncSize
= ComputeBlockSizes(Fn
);
298 // If the entire function is smaller than the displacement of a branch field,
299 // we know we don't need to shrink any branches in this function. This is a
301 if (FuncSize
< (1 << 15)) {
306 // For each conditional branch, if the offset to its destination is larger
307 // than the offset field allows, transform it into a long branch sequence
315 bool MadeChange
= true;
316 bool EverMadeChange
= false;
318 // Iteratively expand branches until we reach a fixed point.
321 for (MachineFunction::iterator MFI
= Fn
.begin(), E
= Fn
.end(); MFI
!= E
;
323 MachineBasicBlock
&MBB
= *MFI
;
324 unsigned MBBStartOffset
= 0;
325 for (MachineBasicBlock::iterator I
= MBB
.begin(), E
= MBB
.end();
327 MachineBasicBlock
*Dest
= nullptr;
328 if (I
->getOpcode() == PPC::BCC
&& !I
->getOperand(2).isImm())
329 Dest
= I
->getOperand(2).getMBB();
330 else if ((I
->getOpcode() == PPC::BC
|| I
->getOpcode() == PPC::BCn
) &&
331 !I
->getOperand(1).isImm())
332 Dest
= I
->getOperand(1).getMBB();
333 else if ((I
->getOpcode() == PPC::BDNZ8
|| I
->getOpcode() == PPC::BDNZ
||
334 I
->getOpcode() == PPC::BDZ8
|| I
->getOpcode() == PPC::BDZ
) &&
335 !I
->getOperand(0).isImm())
336 Dest
= I
->getOperand(0).getMBB();
339 MBBStartOffset
+= TII
->getInstSizeInBytes(*I
);
343 // Determine the offset from the current branch to the destination
345 int BranchSize
= computeBranchSize(Fn
, &MBB
, Dest
, MBBStartOffset
);
347 // If this branch is in range, ignore it.
348 if (isInt
<16>(BranchSize
)) {
353 // Otherwise, we have to expand it to a long branch.
354 MachineInstr
&OldBranch
= *I
;
355 DebugLoc dl
= OldBranch
.getDebugLoc();
357 if (I
->getOpcode() == PPC::BCC
) {
358 // The BCC operands are:
359 // 0. PPC branch predicate
362 PPC::Predicate Pred
= (PPC::Predicate
)I
->getOperand(0).getImm();
363 Register CRReg
= I
->getOperand(1).getReg();
365 // Jump over the uncond branch inst (i.e. $PC+8) on opposite condition.
366 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BCC
))
367 .addImm(PPC::InvertPredicate(Pred
)).addReg(CRReg
).addImm(2);
368 } else if (I
->getOpcode() == PPC::BC
) {
369 Register CRBit
= I
->getOperand(0).getReg();
370 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BCn
)).addReg(CRBit
).addImm(2);
371 } else if (I
->getOpcode() == PPC::BCn
) {
372 Register CRBit
= I
->getOperand(0).getReg();
373 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BC
)).addReg(CRBit
).addImm(2);
374 } else if (I
->getOpcode() == PPC::BDNZ
) {
375 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BDZ
)).addImm(2);
376 } else if (I
->getOpcode() == PPC::BDNZ8
) {
377 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BDZ8
)).addImm(2);
378 } else if (I
->getOpcode() == PPC::BDZ
) {
379 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BDNZ
)).addImm(2);
380 } else if (I
->getOpcode() == PPC::BDZ8
) {
381 BuildMI(MBB
, I
, dl
, TII
->get(PPC::BDNZ8
)).addImm(2);
383 llvm_unreachable("Unhandled branch type!");
386 // Uncond branch to the real destination.
387 I
= BuildMI(MBB
, I
, dl
, TII
->get(PPC::B
)).addMBB(Dest
);
389 // Remove the old branch from the function.
390 OldBranch
.eraseFromParent();
392 // Remember that this instruction is 8-bytes, increase the size of the
393 // block by 4, remember to iterate.
394 BlockSizes
[MBB
.getNumber()].first
+= 4;
402 // If we're going to iterate again, make sure we've updated our
403 // padding-based contributions to the block sizes.
404 modifyAdjustment(Fn
);
407 EverMadeChange
|= MadeChange
;
411 return EverMadeChange
;