1 //===-- MSP430BranchSelector.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 10 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 //===----------------------------------------------------------------------===//
18 #include "MSP430InstrInfo.h"
19 #include "MSP430Subtarget.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Support/MathExtras.h"
24 #include "llvm/Target/TargetMachine.h"
27 #define DEBUG_TYPE "msp430-branch-select"
30 BranchSelectEnabled("msp430-branch-select", cl::Hidden
, cl::init(true),
31 cl::desc("Expand out of range branches"));
33 STATISTIC(NumSplit
, "Number of machine basic blocks split");
34 STATISTIC(NumExpanded
, "Number of branches expanded to long format");
37 class MSP430BSel
: public MachineFunctionPass
{
39 typedef SmallVector
<int, 16> OffsetVector
;
42 const MSP430InstrInfo
*TII
;
44 unsigned measureFunction(OffsetVector
&BlockOffsets
,
45 MachineBasicBlock
*FromBB
= nullptr);
46 bool expandBranches(OffsetVector
&BlockOffsets
);
50 MSP430BSel() : MachineFunctionPass(ID
) {}
52 bool runOnMachineFunction(MachineFunction
&MF
) override
;
54 MachineFunctionProperties
getRequiredProperties() const override
{
55 return MachineFunctionProperties().set(
56 MachineFunctionProperties::Property::NoVRegs
);
59 StringRef
getPassName() const override
{ return "MSP430 Branch Selector"; }
61 char MSP430BSel::ID
= 0;
64 static bool isInRage(int DistanceInBytes
) {
65 // According to CC430 Family User's Guide, Section 4.5.1.3, branch
66 // instructions have the signed 10-bit word offset field, so first we need to
67 // convert the distance from bytes to words, then check if it fits in 10-bit
69 const int WordSize
= 2;
71 assert((DistanceInBytes
% WordSize
== 0) &&
72 "Branch offset should be word aligned!");
74 int Words
= DistanceInBytes
/ WordSize
;
75 return isInt
<10>(Words
);
78 /// Measure each basic block, fill the BlockOffsets, and return the size of
79 /// the function, starting with BB
80 unsigned MSP430BSel::measureFunction(OffsetVector
&BlockOffsets
,
81 MachineBasicBlock
*FromBB
) {
82 // Give the blocks of the function a dense, in-order, numbering.
83 MF
->RenumberBlocks(FromBB
);
85 MachineFunction::iterator Begin
;
86 if (FromBB
== nullptr) {
89 Begin
= FromBB
->getIterator();
92 BlockOffsets
.resize(MF
->getNumBlockIDs());
94 unsigned TotalSize
= BlockOffsets
[Begin
->getNumber()];
95 for (auto &MBB
: make_range(Begin
, MF
->end())) {
96 BlockOffsets
[MBB
.getNumber()] = TotalSize
;
97 for (MachineInstr
&MI
: MBB
) {
98 TotalSize
+= TII
->getInstSizeInBytes(MI
);
104 /// Do expand branches and split the basic blocks if necessary.
105 /// Returns true if made any change.
106 bool MSP430BSel::expandBranches(OffsetVector
&BlockOffsets
) {
107 // For each conditional branch, if the offset to its destination is larger
108 // than the offset field allows, transform it into a long branch sequence
116 bool MadeChange
= false;
117 for (auto MBB
= MF
->begin(), E
= MF
->end(); MBB
!= E
; ++MBB
) {
118 unsigned MBBStartOffset
= 0;
119 for (auto MI
= MBB
->begin(), EE
= MBB
->end(); MI
!= EE
; ++MI
) {
120 MBBStartOffset
+= TII
->getInstSizeInBytes(*MI
);
122 // If this instruction is not a short branch then skip it.
123 if (MI
->getOpcode() != MSP430::JCC
&& MI
->getOpcode() != MSP430::JMP
) {
127 MachineBasicBlock
*DestBB
= MI
->getOperand(0).getMBB();
128 // Determine the distance from the current branch to the destination
129 // block. MBBStartOffset already includes the size of the current branch
132 BlockOffsets
[DestBB
->getNumber()] - BlockOffsets
[MBB
->getNumber()];
133 int BranchDistance
= BlockDistance
- MBBStartOffset
;
135 // If this branch is in range, ignore it.
136 if (isInRage(BranchDistance
)) {
140 LLVM_DEBUG(dbgs() << " Found a branch that needs expanding, "
141 << printMBBReference(*DestBB
) << ", Distance "
142 << BranchDistance
<< "\n");
144 // If JCC is not the last instruction we need to split the MBB.
145 if (MI
->getOpcode() == MSP430::JCC
&& std::next(MI
) != EE
) {
147 LLVM_DEBUG(dbgs() << " Found a basic block that needs to be split, "
148 << printMBBReference(*MBB
) << "\n");
150 // Create a new basic block.
151 MachineBasicBlock
*NewBB
=
152 MF
->CreateMachineBasicBlock(MBB
->getBasicBlock());
153 MF
->insert(std::next(MBB
), NewBB
);
155 // Splice the instructions following MI over to the NewBB.
156 NewBB
->splice(NewBB
->end(), &*MBB
, std::next(MI
), MBB
->end());
158 // Update the successor lists.
159 for (MachineBasicBlock
*Succ
: MBB
->successors()) {
160 if (Succ
== DestBB
) {
163 MBB
->replaceSuccessor(Succ
, NewBB
);
164 NewBB
->addSuccessor(Succ
);
167 // We introduced a new MBB so all following blocks should be numbered
168 // and measured again.
169 measureFunction(BlockOffsets
, &*MBB
);
173 // It may be not necessary to start all over at this point, but it's
174 // safer do this anyway.
178 MachineInstr
&OldBranch
= *MI
;
179 DebugLoc dl
= OldBranch
.getDebugLoc();
180 int InstrSizeDiff
= -TII
->getInstSizeInBytes(OldBranch
);
182 if (MI
->getOpcode() == MSP430::JCC
) {
183 MachineBasicBlock
*NextMBB
= &*std::next(MBB
);
184 assert(MBB
->isSuccessor(NextMBB
) &&
185 "This block must have a layout successor!");
187 // The BCC operands are:
189 // 1. MSP430 branch predicate
190 SmallVector
<MachineOperand
, 1> Cond
;
191 Cond
.push_back(MI
->getOperand(1));
193 // Jump over the long branch on the opposite condition
194 TII
->reverseBranchCondition(Cond
);
195 MI
= BuildMI(*MBB
, MI
, dl
, TII
->get(MSP430::JCC
))
198 InstrSizeDiff
+= TII
->getInstSizeInBytes(*MI
);
202 // Unconditional branch to the real destination.
203 MI
= BuildMI(*MBB
, MI
, dl
, TII
->get(MSP430::Bi
)).addMBB(DestBB
);
204 InstrSizeDiff
+= TII
->getInstSizeInBytes(*MI
);
206 // Remove the old branch from the function.
207 OldBranch
.eraseFromParent();
209 // The size of a new instruction is different from the old one, so we need
210 // to correct all block offsets.
211 for (int i
= MBB
->getNumber() + 1, e
= BlockOffsets
.size(); i
< e
; ++i
) {
212 BlockOffsets
[i
] += InstrSizeDiff
;
214 MBBStartOffset
+= InstrSizeDiff
;
223 bool MSP430BSel::runOnMachineFunction(MachineFunction
&mf
) {
225 TII
= static_cast<const MSP430InstrInfo
*>(MF
->getSubtarget().getInstrInfo());
227 // If the pass is disabled, just bail early.
228 if (!BranchSelectEnabled
)
231 LLVM_DEBUG(dbgs() << "\n********** " << getPassName() << " **********\n");
233 // BlockOffsets - Contains the distance from the beginning of the function to
234 // the beginning of each basic block.
235 OffsetVector BlockOffsets
;
237 unsigned FunctionSize
= measureFunction(BlockOffsets
);
238 // If the entire function is smaller than the displacement of a branch field,
239 // we know we don't need to expand any branches in this
240 // function. This is a common case.
241 if (isInRage(FunctionSize
)) {
245 // Iteratively expand branches until we reach a fixed point.
246 bool MadeChange
= false;
247 while (expandBranches(BlockOffsets
))
253 /// Returns an instance of the Branch Selection Pass
254 FunctionPass
*llvm::createMSP430BranchSelectionPass() {
255 return new MSP430BSel();