1b22310fdSJia Liu //===-- MSP430BranchSelector.cpp - Emit long conditional branches ---------===//
2ce52fd5fSAnton Korobeynikov //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6ce52fd5fSAnton Korobeynikov //
7ce52fd5fSAnton Korobeynikov //===----------------------------------------------------------------------===//
8ce52fd5fSAnton Korobeynikov //
9ce52fd5fSAnton Korobeynikov // This file contains a pass that scans a machine function to determine which
10ce52fd5fSAnton Korobeynikov // conditional branches need more than 10 bits of displacement to reach their
11ce52fd5fSAnton Korobeynikov // target basic block. It does this in two passes; a calculation of basic block
1221fed661SGabor Greif // positions pass, and a branch pseudo op to machine branch opcode pass. This
13ce52fd5fSAnton Korobeynikov // pass should be run last, just before the assembly printer.
14ce52fd5fSAnton Korobeynikov //
15ce52fd5fSAnton Korobeynikov //===----------------------------------------------------------------------===//
16ce52fd5fSAnton Korobeynikov
17ce52fd5fSAnton Korobeynikov #include "MSP430.h"
18ce52fd5fSAnton Korobeynikov #include "MSP430InstrInfo.h"
19d913448bSEric Christopher #include "MSP430Subtarget.h"
20ce52fd5fSAnton Korobeynikov #include "llvm/ADT/Statistic.h"
21ed0881b2SChandler Carruth #include "llvm/CodeGen/MachineFunctionPass.h"
22ed0881b2SChandler Carruth #include "llvm/CodeGen/MachineInstrBuilder.h"
23*904cd3e0SReid Kleckner #include "llvm/Support/Debug.h"
24ce52fd5fSAnton Korobeynikov #include "llvm/Support/MathExtras.h"
25ed0881b2SChandler Carruth #include "llvm/Target/TargetMachine.h"
26ce52fd5fSAnton Korobeynikov using namespace llvm;
27ce52fd5fSAnton Korobeynikov
2884e68b29SChandler Carruth #define DEBUG_TYPE "msp430-branch-select"
2984e68b29SChandler Carruth
30243a4700SAnton Korobeynikov static cl::opt<bool>
31243a4700SAnton Korobeynikov BranchSelectEnabled("msp430-branch-select", cl::Hidden, cl::init(true),
32243a4700SAnton Korobeynikov cl::desc("Expand out of range branches"));
33243a4700SAnton Korobeynikov
34243a4700SAnton Korobeynikov STATISTIC(NumSplit, "Number of machine basic blocks split");
35ce52fd5fSAnton Korobeynikov STATISTIC(NumExpanded, "Number of branches expanded to long format");
36ce52fd5fSAnton Korobeynikov
37ce52fd5fSAnton Korobeynikov namespace {
38243a4700SAnton Korobeynikov class MSP430BSel : public MachineFunctionPass {
39243a4700SAnton Korobeynikov
40243a4700SAnton Korobeynikov typedef SmallVector<int, 16> OffsetVector;
41243a4700SAnton Korobeynikov
42243a4700SAnton Korobeynikov MachineFunction *MF;
43243a4700SAnton Korobeynikov const MSP430InstrInfo *TII;
44243a4700SAnton Korobeynikov
45243a4700SAnton Korobeynikov unsigned measureFunction(OffsetVector &BlockOffsets,
46243a4700SAnton Korobeynikov MachineBasicBlock *FromBB = nullptr);
47243a4700SAnton Korobeynikov bool expandBranches(OffsetVector &BlockOffsets);
48243a4700SAnton Korobeynikov
49243a4700SAnton Korobeynikov public:
50ce52fd5fSAnton Korobeynikov static char ID;
MSP430BSel()51a7aed186SOwen Anderson MSP430BSel() : MachineFunctionPass(ID) {}
52ce52fd5fSAnton Korobeynikov
53243a4700SAnton Korobeynikov bool runOnMachineFunction(MachineFunction &MF) override;
54ce52fd5fSAnton Korobeynikov
getRequiredProperties() const551dbf7a57SDerek Schuff MachineFunctionProperties getRequiredProperties() const override {
561dbf7a57SDerek Schuff return MachineFunctionProperties().set(
571eb47368SMatthias Braun MachineFunctionProperties::Property::NoVRegs);
581dbf7a57SDerek Schuff }
591dbf7a57SDerek Schuff
getPassName() const60117296c0SMehdi Amini StringRef getPassName() const override { return "MSP430 Branch Selector"; }
61ce52fd5fSAnton Korobeynikov };
62ce52fd5fSAnton Korobeynikov char MSP430BSel::ID = 0;
63f00654e3SAlexander Kornienko }
64ce52fd5fSAnton Korobeynikov
isInRage(int DistanceInBytes)65243a4700SAnton Korobeynikov static bool isInRage(int DistanceInBytes) {
66243a4700SAnton Korobeynikov // According to CC430 Family User's Guide, Section 4.5.1.3, branch
67243a4700SAnton Korobeynikov // instructions have the signed 10-bit word offset field, so first we need to
68243a4700SAnton Korobeynikov // convert the distance from bytes to words, then check if it fits in 10-bit
69243a4700SAnton Korobeynikov // signed integer.
70243a4700SAnton Korobeynikov const int WordSize = 2;
71243a4700SAnton Korobeynikov
72243a4700SAnton Korobeynikov assert((DistanceInBytes % WordSize == 0) &&
73243a4700SAnton Korobeynikov "Branch offset should be word aligned!");
74243a4700SAnton Korobeynikov
75243a4700SAnton Korobeynikov int Words = DistanceInBytes / WordSize;
76243a4700SAnton Korobeynikov return isInt<10>(Words);
77ce52fd5fSAnton Korobeynikov }
78ce52fd5fSAnton Korobeynikov
79243a4700SAnton Korobeynikov /// Measure each basic block, fill the BlockOffsets, and return the size of
80243a4700SAnton Korobeynikov /// the function, starting with BB
measureFunction(OffsetVector & BlockOffsets,MachineBasicBlock * FromBB)81243a4700SAnton Korobeynikov unsigned MSP430BSel::measureFunction(OffsetVector &BlockOffsets,
82243a4700SAnton Korobeynikov MachineBasicBlock *FromBB) {
83ce52fd5fSAnton Korobeynikov // Give the blocks of the function a dense, in-order, numbering.
84243a4700SAnton Korobeynikov MF->RenumberBlocks(FromBB);
85ce52fd5fSAnton Korobeynikov
86243a4700SAnton Korobeynikov MachineFunction::iterator Begin;
87243a4700SAnton Korobeynikov if (FromBB == nullptr) {
88243a4700SAnton Korobeynikov Begin = MF->begin();
89243a4700SAnton Korobeynikov } else {
90243a4700SAnton Korobeynikov Begin = FromBB->getIterator();
91ce52fd5fSAnton Korobeynikov }
92ce52fd5fSAnton Korobeynikov
93243a4700SAnton Korobeynikov BlockOffsets.resize(MF->getNumBlockIDs());
94243a4700SAnton Korobeynikov
95243a4700SAnton Korobeynikov unsigned TotalSize = BlockOffsets[Begin->getNumber()];
96243a4700SAnton Korobeynikov for (auto &MBB : make_range(Begin, MF->end())) {
97243a4700SAnton Korobeynikov BlockOffsets[MBB.getNumber()] = TotalSize;
98243a4700SAnton Korobeynikov for (MachineInstr &MI : MBB) {
99243a4700SAnton Korobeynikov TotalSize += TII->getInstSizeInBytes(MI);
100243a4700SAnton Korobeynikov }
101243a4700SAnton Korobeynikov }
102243a4700SAnton Korobeynikov return TotalSize;
103ce52fd5fSAnton Korobeynikov }
104ce52fd5fSAnton Korobeynikov
105243a4700SAnton Korobeynikov /// Do expand branches and split the basic blocks if necessary.
106243a4700SAnton Korobeynikov /// Returns true if made any change.
expandBranches(OffsetVector & BlockOffsets)107243a4700SAnton Korobeynikov bool MSP430BSel::expandBranches(OffsetVector &BlockOffsets) {
108ce52fd5fSAnton Korobeynikov // For each conditional branch, if the offset to its destination is larger
109ce52fd5fSAnton Korobeynikov // than the offset field allows, transform it into a long branch sequence
110ce52fd5fSAnton Korobeynikov // like this:
111ce52fd5fSAnton Korobeynikov // short branch:
112ce52fd5fSAnton Korobeynikov // bCC MBB
113ce52fd5fSAnton Korobeynikov // long branch:
114ce52fd5fSAnton Korobeynikov // b!CC $PC+6
115ce52fd5fSAnton Korobeynikov // b MBB
116ce52fd5fSAnton Korobeynikov //
117243a4700SAnton Korobeynikov bool MadeChange = false;
118243a4700SAnton Korobeynikov for (auto MBB = MF->begin(), E = MF->end(); MBB != E; ++MBB) {
119b38195c1SAnton Korobeynikov unsigned MBBStartOffset = 0;
120243a4700SAnton Korobeynikov for (auto MI = MBB->begin(), EE = MBB->end(); MI != EE; ++MI) {
121243a4700SAnton Korobeynikov MBBStartOffset += TII->getInstSizeInBytes(*MI);
122243a4700SAnton Korobeynikov
123243a4700SAnton Korobeynikov // If this instruction is not a short branch then skip it.
124243a4700SAnton Korobeynikov if (MI->getOpcode() != MSP430::JCC && MI->getOpcode() != MSP430::JMP) {
125ce52fd5fSAnton Korobeynikov continue;
126ce52fd5fSAnton Korobeynikov }
127ce52fd5fSAnton Korobeynikov
128243a4700SAnton Korobeynikov MachineBasicBlock *DestBB = MI->getOperand(0).getMBB();
129243a4700SAnton Korobeynikov // Determine the distance from the current branch to the destination
130243a4700SAnton Korobeynikov // block. MBBStartOffset already includes the size of the current branch
131243a4700SAnton Korobeynikov // instruction.
132243a4700SAnton Korobeynikov int BlockDistance =
133243a4700SAnton Korobeynikov BlockOffsets[DestBB->getNumber()] - BlockOffsets[MBB->getNumber()];
134243a4700SAnton Korobeynikov int BranchDistance = BlockDistance - MBBStartOffset;
135ce52fd5fSAnton Korobeynikov
136ce52fd5fSAnton Korobeynikov // If this branch is in range, ignore it.
137243a4700SAnton Korobeynikov if (isInRage(BranchDistance)) {
138ce52fd5fSAnton Korobeynikov continue;
139ce52fd5fSAnton Korobeynikov }
140ce52fd5fSAnton Korobeynikov
141d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Found a branch that needs expanding, "
14225528d6dSFrancis Visoiu Mistrih << printMBBReference(*DestBB) << ", Distance "
14325528d6dSFrancis Visoiu Mistrih << BranchDistance << "\n");
1442aae31a9SAnton Korobeynikov
145243a4700SAnton Korobeynikov // If JCC is not the last instruction we need to split the MBB.
146243a4700SAnton Korobeynikov if (MI->getOpcode() == MSP430::JCC && std::next(MI) != EE) {
1472aae31a9SAnton Korobeynikov
148d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " Found a basic block that needs to be split, "
14925528d6dSFrancis Visoiu Mistrih << printMBBReference(*MBB) << "\n");
1502aae31a9SAnton Korobeynikov
151243a4700SAnton Korobeynikov // Create a new basic block.
152243a4700SAnton Korobeynikov MachineBasicBlock *NewBB =
153243a4700SAnton Korobeynikov MF->CreateMachineBasicBlock(MBB->getBasicBlock());
154243a4700SAnton Korobeynikov MF->insert(std::next(MBB), NewBB);
155243a4700SAnton Korobeynikov
156243a4700SAnton Korobeynikov // Splice the instructions following MI over to the NewBB.
157243a4700SAnton Korobeynikov NewBB->splice(NewBB->end(), &*MBB, std::next(MI), MBB->end());
158243a4700SAnton Korobeynikov
159243a4700SAnton Korobeynikov // Update the successor lists.
160243a4700SAnton Korobeynikov for (MachineBasicBlock *Succ : MBB->successors()) {
161243a4700SAnton Korobeynikov if (Succ == DestBB) {
162243a4700SAnton Korobeynikov continue;
163b38195c1SAnton Korobeynikov }
164243a4700SAnton Korobeynikov MBB->replaceSuccessor(Succ, NewBB);
165243a4700SAnton Korobeynikov NewBB->addSuccessor(Succ);
166243a4700SAnton Korobeynikov }
167243a4700SAnton Korobeynikov
168243a4700SAnton Korobeynikov // We introduced a new MBB so all following blocks should be numbered
169243a4700SAnton Korobeynikov // and measured again.
170243a4700SAnton Korobeynikov measureFunction(BlockOffsets, &*MBB);
171243a4700SAnton Korobeynikov
172243a4700SAnton Korobeynikov ++NumSplit;
173243a4700SAnton Korobeynikov
174243a4700SAnton Korobeynikov // It may be not necessary to start all over at this point, but it's
175243a4700SAnton Korobeynikov // safer do this anyway.
176243a4700SAnton Korobeynikov return true;
177243a4700SAnton Korobeynikov }
178243a4700SAnton Korobeynikov
179243a4700SAnton Korobeynikov MachineInstr &OldBranch = *MI;
180243a4700SAnton Korobeynikov DebugLoc dl = OldBranch.getDebugLoc();
181243a4700SAnton Korobeynikov int InstrSizeDiff = -TII->getInstSizeInBytes(OldBranch);
182243a4700SAnton Korobeynikov
183243a4700SAnton Korobeynikov if (MI->getOpcode() == MSP430::JCC) {
184243a4700SAnton Korobeynikov MachineBasicBlock *NextMBB = &*std::next(MBB);
185243a4700SAnton Korobeynikov assert(MBB->isSuccessor(NextMBB) &&
186243a4700SAnton Korobeynikov "This block must have a layout successor!");
187243a4700SAnton Korobeynikov
188243a4700SAnton Korobeynikov // The BCC operands are:
189243a4700SAnton Korobeynikov // 0. Target MBB
190243a4700SAnton Korobeynikov // 1. MSP430 branch predicate
191243a4700SAnton Korobeynikov SmallVector<MachineOperand, 1> Cond;
192243a4700SAnton Korobeynikov Cond.push_back(MI->getOperand(1));
193243a4700SAnton Korobeynikov
194243a4700SAnton Korobeynikov // Jump over the long branch on the opposite condition
195243a4700SAnton Korobeynikov TII->reverseBranchCondition(Cond);
196243a4700SAnton Korobeynikov MI = BuildMI(*MBB, MI, dl, TII->get(MSP430::JCC))
197243a4700SAnton Korobeynikov .addMBB(NextMBB)
198116bbab4SDiana Picus .add(Cond[0]);
199243a4700SAnton Korobeynikov InstrSizeDiff += TII->getInstSizeInBytes(*MI);
200243a4700SAnton Korobeynikov ++MI;
201243a4700SAnton Korobeynikov }
202243a4700SAnton Korobeynikov
203243a4700SAnton Korobeynikov // Unconditional branch to the real destination.
204243a4700SAnton Korobeynikov MI = BuildMI(*MBB, MI, dl, TII->get(MSP430::Bi)).addMBB(DestBB);
205243a4700SAnton Korobeynikov InstrSizeDiff += TII->getInstSizeInBytes(*MI);
206ce52fd5fSAnton Korobeynikov
207ce52fd5fSAnton Korobeynikov // Remove the old branch from the function.
2088efc5b4fSDuncan P. N. Exon Smith OldBranch.eraseFromParent();
209ce52fd5fSAnton Korobeynikov
210243a4700SAnton Korobeynikov // The size of a new instruction is different from the old one, so we need
211243a4700SAnton Korobeynikov // to correct all block offsets.
212243a4700SAnton Korobeynikov for (int i = MBB->getNumber() + 1, e = BlockOffsets.size(); i < e; ++i) {
213243a4700SAnton Korobeynikov BlockOffsets[i] += InstrSizeDiff;
214243a4700SAnton Korobeynikov }
215243a4700SAnton Korobeynikov MBBStartOffset += InstrSizeDiff;
216ce52fd5fSAnton Korobeynikov
217ce52fd5fSAnton Korobeynikov ++NumExpanded;
218ce52fd5fSAnton Korobeynikov MadeChange = true;
219ce52fd5fSAnton Korobeynikov }
220ce52fd5fSAnton Korobeynikov }
221243a4700SAnton Korobeynikov return MadeChange;
222ce52fd5fSAnton Korobeynikov }
223ce52fd5fSAnton Korobeynikov
runOnMachineFunction(MachineFunction & mf)224243a4700SAnton Korobeynikov bool MSP430BSel::runOnMachineFunction(MachineFunction &mf) {
225243a4700SAnton Korobeynikov MF = &mf;
226243a4700SAnton Korobeynikov TII = static_cast<const MSP430InstrInfo *>(MF->getSubtarget().getInstrInfo());
227243a4700SAnton Korobeynikov
228243a4700SAnton Korobeynikov // If the pass is disabled, just bail early.
229243a4700SAnton Korobeynikov if (!BranchSelectEnabled)
230243a4700SAnton Korobeynikov return false;
231243a4700SAnton Korobeynikov
232d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "\n********** " << getPassName() << " **********\n");
233243a4700SAnton Korobeynikov
234243a4700SAnton Korobeynikov // BlockOffsets - Contains the distance from the beginning of the function to
235243a4700SAnton Korobeynikov // the beginning of each basic block.
236243a4700SAnton Korobeynikov OffsetVector BlockOffsets;
237243a4700SAnton Korobeynikov
238243a4700SAnton Korobeynikov unsigned FunctionSize = measureFunction(BlockOffsets);
239243a4700SAnton Korobeynikov // If the entire function is smaller than the displacement of a branch field,
240243a4700SAnton Korobeynikov // we know we don't need to expand any branches in this
241243a4700SAnton Korobeynikov // function. This is a common case.
242243a4700SAnton Korobeynikov if (isInRage(FunctionSize)) {
243243a4700SAnton Korobeynikov return false;
244243a4700SAnton Korobeynikov }
245243a4700SAnton Korobeynikov
246243a4700SAnton Korobeynikov // Iteratively expand branches until we reach a fixed point.
247243a4700SAnton Korobeynikov bool MadeChange = false;
248243a4700SAnton Korobeynikov while (expandBranches(BlockOffsets))
249243a4700SAnton Korobeynikov MadeChange = true;
250243a4700SAnton Korobeynikov
251243a4700SAnton Korobeynikov return MadeChange;
252243a4700SAnton Korobeynikov }
253243a4700SAnton Korobeynikov
254243a4700SAnton Korobeynikov /// Returns an instance of the Branch Selection Pass
createMSP430BranchSelectionPass()255243a4700SAnton Korobeynikov FunctionPass *llvm::createMSP430BranchSelectionPass() {
256243a4700SAnton Korobeynikov return new MSP430BSel();
257ce52fd5fSAnton Korobeynikov }
258