1//===-- MSP430BranchSelector.cpp - Emit long conditional branches ---------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
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.
14//
15//===----------------------------------------------------------------------===//
16
17#include "MSP430.h"
18#include "MSP430InstrInfo.h"
19#include "MSP430Subtarget.h"
20#include "llvm/ADT/Statistic.h"
21#include "llvm/CodeGen/MachineFunctionAnalysisManager.h"
22#include "llvm/CodeGen/MachineFunctionPass.h"
23#include "llvm/CodeGen/MachineInstrBuilder.h"
24#include "llvm/CodeGen/MachinePassManager.h"
25#include "llvm/IR/Analysis.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/MathExtras.h"
28#include "llvm/Target/TargetMachine.h"
29using namespace llvm;
30
31#define DEBUG_TYPE "msp430-branch-select"
32
33static cl::opt<bool>
34 BranchSelectEnabled("msp430-branch-select", cl::Hidden, cl::init(Val: true),
35 cl::desc("Expand out of range branches"));
36
37STATISTIC(NumSplit, "Number of machine basic blocks split");
38STATISTIC(NumExpanded, "Number of branches expanded to long format");
39
40namespace {
41class MSP430BSelImpl {
42
43 typedef SmallVector<int, 16> OffsetVector;
44
45 MachineFunction *MF;
46 const MSP430InstrInfo *TII;
47
48 unsigned measureFunction(OffsetVector &BlockOffsets,
49 MachineBasicBlock *FromBB = nullptr);
50 bool expandBranches(OffsetVector &BlockOffsets);
51
52public:
53 bool runOnMachineFunction(MachineFunction &MF);
54};
55
56class MSP430BranchSelectLegacyPass : public MachineFunctionPass {
57public:
58 static char ID;
59 MSP430BranchSelectLegacyPass() : MachineFunctionPass(ID) {}
60
61 bool runOnMachineFunction(MachineFunction &MF) override;
62
63 MachineFunctionProperties getRequiredProperties() const override {
64 return MachineFunctionProperties().setNoVRegs();
65 }
66
67 StringRef getPassName() const override { return "MSP430 Branch Selector"; }
68};
69
70char MSP430BranchSelectLegacyPass::ID = 0;
71} // namespace
72
73static bool isInRage(int DistanceInBytes) {
74 // According to CC430 Family User's Guide, Section 4.5.1.3, branch
75 // instructions have the signed 10-bit word offset field, so first we need to
76 // convert the distance from bytes to words, then check if it fits in 10-bit
77 // signed integer.
78 const int WordSize = 2;
79
80 assert((DistanceInBytes % WordSize == 0) &&
81 "Branch offset should be word aligned!");
82
83 int Words = DistanceInBytes / WordSize;
84 return isInt<10>(x: Words);
85}
86
87/// Measure each basic block, fill the BlockOffsets, and return the size of
88/// the function, starting with BB
89unsigned MSP430BSelImpl::measureFunction(OffsetVector &BlockOffsets,
90 MachineBasicBlock *FromBB) {
91 // Give the blocks of the function a dense, in-order, numbering.
92 MF->RenumberBlocks(MBBFrom: FromBB);
93
94 MachineFunction::iterator Begin;
95 if (FromBB == nullptr) {
96 Begin = MF->begin();
97 } else {
98 Begin = FromBB->getIterator();
99 }
100
101 BlockOffsets.resize(N: MF->getNumBlockIDs());
102
103 unsigned TotalSize = BlockOffsets[Begin->getNumber()];
104 for (auto &MBB : make_range(x: Begin, y: MF->end())) {
105 BlockOffsets[MBB.getNumber()] = TotalSize;
106 for (MachineInstr &MI : MBB) {
107 TotalSize += TII->getInstSizeInBytes(MI);
108 }
109 }
110 return TotalSize;
111}
112
113/// Do expand branches and split the basic blocks if necessary.
114/// Returns true if made any change.
115bool MSP430BSelImpl::expandBranches(OffsetVector &BlockOffsets) {
116 // For each conditional branch, if the offset to its destination is larger
117 // than the offset field allows, transform it into a long branch sequence
118 // like this:
119 // short branch:
120 // bCC MBB
121 // long branch:
122 // b!CC $PC+6
123 // b MBB
124 //
125 bool MadeChange = false;
126 for (auto MBB = MF->begin(), E = MF->end(); MBB != E; ++MBB) {
127 unsigned MBBStartOffset = 0;
128 for (auto MI = MBB->begin(), EE = MBB->end(); MI != EE; ++MI) {
129 MBBStartOffset += TII->getInstSizeInBytes(MI: *MI);
130
131 // If this instruction is not a short branch then skip it.
132 if (MI->getOpcode() != MSP430::JCC && MI->getOpcode() != MSP430::JMP) {
133 continue;
134 }
135
136 MachineBasicBlock *DestBB = MI->getOperand(i: 0).getMBB();
137 // Determine the distance from the current branch to the destination
138 // block. MBBStartOffset already includes the size of the current branch
139 // instruction.
140 int BlockDistance =
141 BlockOffsets[DestBB->getNumber()] - BlockOffsets[MBB->getNumber()];
142 int BranchDistance = BlockDistance - MBBStartOffset;
143
144 // If this branch is in range, ignore it.
145 if (isInRage(DistanceInBytes: BranchDistance)) {
146 continue;
147 }
148
149 LLVM_DEBUG(dbgs() << " Found a branch that needs expanding, "
150 << printMBBReference(*DestBB) << ", Distance "
151 << BranchDistance << "\n");
152
153 // If JCC is not the last instruction we need to split the MBB.
154 if (MI->getOpcode() == MSP430::JCC && std::next(x: MI) != EE) {
155
156 LLVM_DEBUG(dbgs() << " Found a basic block that needs to be split, "
157 << printMBBReference(*MBB) << "\n");
158
159 // Create a new basic block.
160 MachineBasicBlock *NewBB =
161 MF->CreateMachineBasicBlock(BB: MBB->getBasicBlock());
162 MF->insert(MBBI: std::next(x: MBB), MBB: NewBB);
163
164 // Splice the instructions following MI over to the NewBB.
165 NewBB->splice(Where: NewBB->end(), Other: &*MBB, From: std::next(x: MI), To: MBB->end());
166
167 // Update the successor lists.
168 for (MachineBasicBlock *Succ : MBB->successors()) {
169 if (Succ == DestBB) {
170 continue;
171 }
172 MBB->replaceSuccessor(Old: Succ, New: NewBB);
173 NewBB->addSuccessor(Succ);
174 }
175
176 // We introduced a new MBB so all following blocks should be numbered
177 // and measured again.
178 measureFunction(BlockOffsets, FromBB: &*MBB);
179
180 ++NumSplit;
181
182 // It may be not necessary to start all over at this point, but it's
183 // safer do this anyway.
184 return true;
185 }
186
187 MachineInstr &OldBranch = *MI;
188 DebugLoc dl = OldBranch.getDebugLoc();
189 int InstrSizeDiff = -TII->getInstSizeInBytes(MI: OldBranch);
190
191 if (MI->getOpcode() == MSP430::JCC) {
192 MachineBasicBlock *NextMBB = &*std::next(x: MBB);
193 assert(MBB->isSuccessor(NextMBB) &&
194 "This block must have a layout successor!");
195
196 // The BCC operands are:
197 // 0. Target MBB
198 // 1. MSP430 branch predicate
199 SmallVector<MachineOperand, 1> Cond;
200 Cond.push_back(Elt: MI->getOperand(i: 1));
201
202 // Jump over the long branch on the opposite condition
203 TII->reverseBranchCondition(Cond);
204 MI = BuildMI(BB&: *MBB, I: MI, MIMD: dl, MCID: TII->get(Opcode: MSP430::JCC))
205 .addMBB(MBB: NextMBB)
206 .add(MO: Cond[0]);
207 InstrSizeDiff += TII->getInstSizeInBytes(MI: *MI);
208 ++MI;
209 }
210
211 // Unconditional branch to the real destination.
212 MI = BuildMI(BB&: *MBB, I: MI, MIMD: dl, MCID: TII->get(Opcode: MSP430::Bi)).addMBB(MBB: DestBB);
213 InstrSizeDiff += TII->getInstSizeInBytes(MI: *MI);
214
215 // Remove the old branch from the function.
216 OldBranch.eraseFromParent();
217
218 // The size of a new instruction is different from the old one, so we need
219 // to correct all block offsets.
220 for (int i = MBB->getNumber() + 1, e = BlockOffsets.size(); i < e; ++i) {
221 BlockOffsets[i] += InstrSizeDiff;
222 }
223 MBBStartOffset += InstrSizeDiff;
224
225 ++NumExpanded;
226 MadeChange = true;
227 }
228 }
229 return MadeChange;
230}
231
232bool MSP430BSelImpl::runOnMachineFunction(MachineFunction &mf) {
233 MF = &mf;
234 TII = static_cast<const MSP430InstrInfo *>(MF->getSubtarget().getInstrInfo());
235
236 // If the pass is disabled, just bail early.
237 if (!BranchSelectEnabled)
238 return false;
239
240 LLVM_DEBUG(dbgs() << "\n********** " << DEBUG_TYPE << " **********\n");
241
242 // BlockOffsets - Contains the distance from the beginning of the function to
243 // the beginning of each basic block.
244 OffsetVector BlockOffsets;
245
246 unsigned FunctionSize = measureFunction(BlockOffsets);
247 // If the entire function is smaller than the displacement of a branch field,
248 // we know we don't need to expand any branches in this
249 // function. This is a common case.
250 if (isInRage(DistanceInBytes: FunctionSize)) {
251 return false;
252 }
253
254 // Iteratively expand branches until we reach a fixed point.
255 bool MadeChange = false;
256 while (expandBranches(BlockOffsets))
257 MadeChange = true;
258
259 return MadeChange;
260}
261
262bool MSP430BranchSelectLegacyPass::runOnMachineFunction(MachineFunction &MF) {
263 return MSP430BSelImpl().runOnMachineFunction(mf&: MF);
264}
265
266PreservedAnalyses
267MSP430BranchSelectPass::run(MachineFunction &MF,
268 MachineFunctionAnalysisManager &MFAM) {
269 return MSP430BSelImpl().runOnMachineFunction(mf&: MF)
270 ? getMachineFunctionPassPreservedAnalyses()
271 : PreservedAnalyses::all();
272}
273
274/// Returns an instance of the Branch Selection Pass
275FunctionPass *llvm::createMSP430BranchSelectLegacyPass() {
276 return new MSP430BranchSelectLegacyPass();
277}
278