LLVM 23.0.0git
MSP430BranchSelector.cpp
Go to the documentation of this file.
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"
25#include "llvm/IR/Analysis.h"
26#include "llvm/Support/Debug.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(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
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>(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(FromBB);
93
95 if (FromBB == nullptr) {
96 Begin = MF->begin();
97 } else {
98 Begin = FromBB->getIterator();
99 }
100
101 BlockOffsets.resize(MF->getNumBlockIDs());
102
103 unsigned TotalSize = BlockOffsets[Begin->getNumber()];
104 for (auto &MBB : make_range(Begin, 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);
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(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(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(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 =
162 MF->insert(std::next(MBB), NewBB);
163
164 // Splice the instructions following MI over to the NewBB.
165 NewBB->splice(NewBB->end(), &*MBB, std::next(MI), MBB->end());
166
167 // Update the successor lists.
168 for (MachineBasicBlock *Succ : MBB->successors()) {
169 if (Succ == DestBB) {
170 continue;
171 }
172 MBB->replaceSuccessor(Succ, 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, &*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(OldBranch);
190
191 if (MI->getOpcode() == MSP430::JCC) {
192 MachineBasicBlock *NextMBB = &*std::next(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
200 Cond.push_back(MI->getOperand(1));
201
202 // Jump over the long branch on the opposite condition
204 MI = BuildMI(*MBB, MI, dl, TII->get(MSP430::JCC))
205 .addMBB(NextMBB)
206 .add(Cond[0]);
207 InstrSizeDiff += TII->getInstSizeInBytes(*MI);
208 ++MI;
209 }
210
211 // Unconditional branch to the real destination.
212 MI = BuildMI(*MBB, MI, dl, TII->get(MSP430::Bi)).addMBB(DestBB);
213 InstrSizeDiff += TII->getInstSizeInBytes(*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.
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(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);
264}
265
266PreservedAnalyses
269 return MSP430BSelImpl().runOnMachineFunction(MF)
272}
273
274/// Returns an instance of the Branch Selection Pass
276 return new MSP430BranchSelectLegacyPass();
277}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
#define DEBUG_TYPE
const HexagonInstrInfo * TII
IRTranslator LLVM IR MI
static bool isInRage(int DistanceInBytes)
static cl::opt< bool > BranchSelectEnabled("msp430-branch-select", cl::Hidden, cl::init(true), cl::desc("Expand out of range branches"))
const SmallVectorImpl< MachineOperand > & Cond
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
bool reverseBranchCondition(SmallVectorImpl< MachineOperand > &Cond) const override
Reverses the branch condition of the specified condition list, returning false on success and true if...
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
LLVM_ABI void replaceSuccessor(MachineBasicBlock *Old, MachineBasicBlock *New)
Replace successor OLD with NEW and update probability info.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
iterator_range< succ_iterator > successors()
LLVM_ABI bool isSuccessor(const MachineBasicBlock *MBB) const
Return true if the specified MBB is a successor of this block.
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
BasicBlockListType::iterator iterator
void RenumberBlocks(MachineBasicBlock *MBBFrom=nullptr)
RenumberBlocks - This discards all of the MachineBasicBlock numbers and recomputes them.
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *BB=nullptr, std::optional< UniqueBBID > BBID=std::nullopt)
CreateMachineInstr - Allocate a new MachineInstr.
void insert(iterator MBBI, MachineBasicBlock *MBB)
const MachineInstrBuilder & add(const MachineOperand &MO) const
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
const DebugLoc & getDebugLoc() const
Returns the debug location id of this MachineInstr.
LLVM_ABI MachineInstrBundleIterator< MachineInstr > eraseFromParent()
Unlink 'this' from the containing basic block and delete it.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
self_iterator getIterator()
Definition ilist_node.h:123
Pass manager infrastructure for declaring and invalidating analyses.
initializer< Ty > init(const Ty &Val)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr bool isInt(int64_t x)
Checks if an integer fits into the given bit width.
Definition MathExtras.h:165
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
FunctionPass * createMSP430BranchSelectLegacyPass()
Returns an instance of the Branch Selection Pass.
LLVM_ABI Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.