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