blob: 366c303614d63fc91b9094056b220ec798ff175f [file] [log] [blame]
Eugene Zelenko618c5552017-09-13 21:15:20 +00001//===- BranchRelaxation.cpp -----------------------------------------------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Tim Northover3b0846e2014-05-24 12:50:23 +00006//
7//===----------------------------------------------------------------------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00008
Tim Northover3b0846e2014-05-24 12:50:23 +00009#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000010#include "llvm/ADT/Statistic.h"
Matthias Braun18198302016-12-16 23:55:37 +000011#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000012#include "llvm/CodeGen/MachineBasicBlock.h"
13#include "llvm/CodeGen/MachineFunction.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000014#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000015#include "llvm/CodeGen/MachineInstr.h"
Matt Arsenault6bc43d82016-10-06 16:20:41 +000016#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000017#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000018#include "llvm/CodeGen/TargetRegisterInfo.h"
19#include "llvm/CodeGen/TargetSubtargetInfo.h"
Nico Weber432a3882018-04-30 14:59:11 +000020#include "llvm/Config/llvm-config.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000021#include "llvm/IR/DebugLoc.h"
Reid Kleckner05da2fe2019-11-13 13:15:01 -080022#include "llvm/InitializePasses.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000023#include "llvm/Pass.h"
24#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/Support/Debug.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000026#include "llvm/Support/Format.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000027#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000028#include "llvm/Support/raw_ostream.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000029#include <cassert>
30#include <cstdint>
31#include <iterator>
32#include <memory>
Matt Arsenault36919a42016-10-06 15:38:53 +000033
Tim Northover3b0846e2014-05-24 12:50:23 +000034using namespace llvm;
35
Matt Arsenault36919a42016-10-06 15:38:53 +000036#define DEBUG_TYPE "branch-relaxation"
Tim Northover3b0846e2014-05-24 12:50:23 +000037
Tim Northover3b0846e2014-05-24 12:50:23 +000038STATISTIC(NumSplit, "Number of basic blocks split");
Matt Arsenault567631b2016-08-23 01:30:30 +000039STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
Matt Arsenault6bc43d82016-10-06 16:20:41 +000040STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
Tim Northover3b0846e2014-05-24 12:50:23 +000041
Matt Arsenault36919a42016-10-06 15:38:53 +000042#define BRANCH_RELAX_NAME "Branch relaxation pass"
Chad Rosier1c814322015-08-05 16:12:10 +000043
Tim Northover3b0846e2014-05-24 12:50:23 +000044namespace {
Eugene Zelenko618c5552017-09-13 21:15:20 +000045
Matt Arsenault36919a42016-10-06 15:38:53 +000046class BranchRelaxation : public MachineFunctionPass {
Tim Northover3b0846e2014-05-24 12:50:23 +000047 /// BasicBlockInfo - Information about the offset and size of a single
48 /// basic block.
49 struct BasicBlockInfo {
50 /// Offset - Distance from the beginning of the function to the beginning
51 /// of this basic block.
52 ///
53 /// The offset is always aligned as required by the basic block.
Eugene Zelenko618c5552017-09-13 21:15:20 +000054 unsigned Offset = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +000055
56 /// Size - Size of the basic block in bytes. If the block contains
57 /// inline assembly, this is a worst case estimate.
58 ///
59 /// The size does not include any alignment padding whether from the
60 /// beginning of the block, or from an aligned jump table at the end.
Eugene Zelenko618c5552017-09-13 21:15:20 +000061 unsigned Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +000062
Eugene Zelenko618c5552017-09-13 21:15:20 +000063 BasicBlockInfo() = default;
Tim Northover3b0846e2014-05-24 12:50:23 +000064
Matt Arsenaultef5bba02016-10-06 16:00:58 +000065 /// Compute the offset immediately following this block. \p MBB is the next
66 /// block.
67 unsigned postOffset(const MachineBasicBlock &MBB) const {
Guillaume Chatelet48904e92019-09-11 11:16:48 +000068 const unsigned PO = Offset + Size;
Guillaume Chatelet18f805a2019-09-27 12:54:21 +000069 const Align Alignment = MBB.getAlignment();
Guillaume Chatelet18f805a2019-09-27 12:54:21 +000070 const Align ParentAlign = MBB.getParent()->getAlignment();
71 if (Alignment <= ParentAlign)
Fangrui Song886d2c22020-01-19 14:53:45 -080072 return alignTo(PO, Alignment);
Matt Arsenaultef5bba02016-10-06 16:00:58 +000073
74 // The alignment of this MBB is larger than the function's alignment, so we
75 // can't tell whether or not it will insert nops. Assume that it will.
Fangrui Song886d2c22020-01-19 14:53:45 -080076 return alignTo(PO, Alignment) + Alignment.value() - ParentAlign.value();
Tim Northover3b0846e2014-05-24 12:50:23 +000077 }
78 };
79
80 SmallVector<BasicBlockInfo, 16> BlockInfo;
Matt Arsenault6bc43d82016-10-06 16:20:41 +000081 std::unique_ptr<RegScavenger> RS;
Matthias Braun18198302016-12-16 23:55:37 +000082 LivePhysRegs LiveRegs;
Tim Northover3b0846e2014-05-24 12:50:23 +000083
84 MachineFunction *MF;
Matthias Braun18198302016-12-16 23:55:37 +000085 const TargetRegisterInfo *TRI;
Matt Arsenault36919a42016-10-06 15:38:53 +000086 const TargetInstrInfo *TII;
Tim Northover3b0846e2014-05-24 12:50:23 +000087
88 bool relaxBranchInstructions();
89 void scanFunction();
Matt Arsenault6bc43d82016-10-06 16:20:41 +000090
91 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &BB);
92
Matt Arsenault44deb792016-11-02 16:18:29 +000093 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
94 MachineBasicBlock *DestBB);
Fangrui Songcb0bab82018-07-16 18:51:40 +000095 void adjustBlockOffsets(MachineBasicBlock &Start);
Matt Arsenaulte8da1452016-08-02 08:06:17 +000096 bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
Matt Arsenault5b549712016-08-02 08:30:06 +000097
Matt Arsenaultf7065e12016-08-02 07:20:09 +000098 bool fixupConditionalBranch(MachineInstr &MI);
Matt Arsenault6bc43d82016-10-06 16:20:41 +000099 bool fixupUnconditionalBranch(MachineInstr &MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000100 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000101 unsigned getInstrOffset(const MachineInstr &MI) const;
Tim Northover3b0846e2014-05-24 12:50:23 +0000102 void dumpBBs();
103 void verify();
104
105public:
106 static char ID;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000107
108 BranchRelaxation() : MachineFunctionPass(ID) {}
Tim Northover3b0846e2014-05-24 12:50:23 +0000109
110 bool runOnMachineFunction(MachineFunction &MF) override;
111
Eugene Zelenko618c5552017-09-13 21:15:20 +0000112 StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000113};
Matt Arsenault36919a42016-10-06 15:38:53 +0000114
Eugene Zelenko618c5552017-09-13 21:15:20 +0000115} // end anonymous namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000116
Matt Arsenault36919a42016-10-06 15:38:53 +0000117char BranchRelaxation::ID = 0;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000118
Matt Arsenault36919a42016-10-06 15:38:53 +0000119char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
120
121INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
Chad Rosier1c814322015-08-05 16:12:10 +0000122
Tim Northover3b0846e2014-05-24 12:50:23 +0000123/// verify - check BBOffsets, BBSizes, alignment of islands
Matt Arsenault36919a42016-10-06 15:38:53 +0000124void BranchRelaxation::verify() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000125#ifndef NDEBUG
126 unsigned PrevNum = MF->begin()->getNumber();
127 for (MachineBasicBlock &MBB : *MF) {
Guillaume Chateletd4c46712019-09-18 15:49:49 +0000128 const unsigned Num = MBB.getNumber();
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000129 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
Matt Arsenault44deb792016-11-02 16:18:29 +0000130 assert(BlockInfo[Num].Size == computeBlockSize(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000131 PrevNum = Num;
132 }
133#endif
134}
135
Aaron Ballman615eb472017-10-15 14:32:27 +0000136#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Tim Northover3b0846e2014-05-24 12:50:23 +0000137/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000138LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000139 for (auto &MBB : *MF) {
140 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
Evgeniy Stepanov187c63f2019-08-16 18:23:54 +0000141 dbgs() << format("%%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
Tim Northover3b0846e2014-05-24 12:50:23 +0000142 << format("size=%#x\n", BBI.Size);
143 }
144}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000145#endif
Tim Northover3b0846e2014-05-24 12:50:23 +0000146
Tim Northover3b0846e2014-05-24 12:50:23 +0000147/// scanFunction - Do the initial scan of the function, building up
148/// information about each block.
Matt Arsenault36919a42016-10-06 15:38:53 +0000149void BranchRelaxation::scanFunction() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000150 BlockInfo.clear();
151 BlockInfo.resize(MF->getNumBlockIDs());
152
153 // First thing, compute the size of all basic blocks, and see if the function
154 // has any inline assembly in it. If so, we have to be conservative about
155 // alignment assumptions, as we don't know for sure the size of any
156 // instructions in the inline assembly.
157 for (MachineBasicBlock &MBB : *MF)
Matt Arsenault36919a42016-10-06 15:38:53 +0000158 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000159
160 // Compute block offsets and known bits.
161 adjustBlockOffsets(*MF->begin());
162}
163
164/// computeBlockSize - Compute the size for MBB.
Matt Arsenault36919a42016-10-06 15:38:53 +0000165uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
166 uint64_t Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000167 for (const MachineInstr &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000168 Size += TII->getInstSizeInBytes(MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000169 return Size;
Tim Northover3b0846e2014-05-24 12:50:23 +0000170}
171
172/// getInstrOffset - Return the current offset of the specified machine
173/// instruction from the start of the function. This offset changes as stuff is
174/// moved around inside the function.
Matt Arsenault36919a42016-10-06 15:38:53 +0000175unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000176 const MachineBasicBlock *MBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000177
178 // The offset is composed of two things: the sum of the sizes of all MBB's
179 // before this instruction's block, and the offset from the start of the block
180 // it is in.
181 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
182
183 // Sum instructions before MI in MBB.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000184 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000185 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000186 Offset += TII->getInstSizeInBytes(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000187 }
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000188
Tim Northover3b0846e2014-05-24 12:50:23 +0000189 return Offset;
190}
191
Matt Arsenault36919a42016-10-06 15:38:53 +0000192void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 unsigned PrevNum = Start.getNumber();
Fangrui Song886d2c22020-01-19 14:53:45 -0800194 for (auto &MBB :
195 make_range(std::next(MachineFunction::iterator(Start)), MF->end())) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000196 unsigned Num = MBB.getNumber();
Tim Northover3b0846e2014-05-24 12:50:23 +0000197 // Get the offset and known bits at the end of the layout predecessor.
198 // Include the alignment of the current block.
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000199 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
200
Tim Northover3b0846e2014-05-24 12:50:23 +0000201 PrevNum = Num;
202 }
203}
204
Eugene Zelenko618c5552017-09-13 21:15:20 +0000205/// Insert a new empty basic block and insert it after \BB
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000206MachineBasicBlock *BranchRelaxation::createNewBlockAfter(MachineBasicBlock &BB) {
207 // Create a new MBB for the code after the OrigBB.
208 MachineBasicBlock *NewBB =
209 MF->CreateMachineBasicBlock(BB.getBasicBlock());
210 MF->insert(++BB.getIterator(), NewBB);
211
212 // Insert an entry into BlockInfo to align it properly with the block numbers.
213 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
214
215 return NewBB;
216}
217
Tim Northover3b0846e2014-05-24 12:50:23 +0000218/// Split the basic block containing MI into two blocks, which are joined by
219/// an unconditional branch. Update data structures and renumber blocks to
220/// account for this change and returns the newly created block.
Matt Arsenault44deb792016-11-02 16:18:29 +0000221MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
222 MachineBasicBlock *DestBB) {
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000223 MachineBasicBlock *OrigBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000224
225 // Create a new MBB for the code after the OrigBB.
226 MachineBasicBlock *NewBB =
227 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000228 MF->insert(++OrigBB->getIterator(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000229
230 // Splice the instructions starting with MI over to NewBB.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000231 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
Tim Northover3b0846e2014-05-24 12:50:23 +0000232
233 // Add an unconditional branch from OrigBB to NewBB.
234 // Note the new unconditional branch is not being recorded.
235 // There doesn't seem to be meaningful DebugInfo available; this doesn't
236 // correspond to anything in the source.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000237 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
Tim Northover3b0846e2014-05-24 12:50:23 +0000238
239 // Insert an entry into BlockInfo to align it properly with the block numbers.
240 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
241
Matt Arsenault44deb792016-11-02 16:18:29 +0000242 NewBB->transferSuccessors(OrigBB);
243 OrigBB->addSuccessor(NewBB);
244 OrigBB->addSuccessor(DestBB);
245
246 // Cleanup potential unconditional branch to successor block.
247 // Note that updateTerminator may change the size of the blocks.
James Y Knight19783092020-02-19 10:41:28 -0500248 OrigBB->updateTerminator(NewBB);
Matt Arsenault44deb792016-11-02 16:18:29 +0000249
Tim Northover3b0846e2014-05-24 12:50:23 +0000250 // Figure out how large the OrigBB is. As the first half of the original
251 // block, it cannot contain a tablejump. The size includes
252 // the new jump we added. (It should be possible to do this without
253 // recounting everything, but it's very confusing, and this is rarely
254 // executed.)
Matt Arsenault36919a42016-10-06 15:38:53 +0000255 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000256
Matt Arsenault36919a42016-10-06 15:38:53 +0000257 // Figure out how large the NewMBB is. As the second half of the original
Tim Northover3b0846e2014-05-24 12:50:23 +0000258 // block, it may contain a tablejump.
Matt Arsenault36919a42016-10-06 15:38:53 +0000259 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000260
261 // All BBOffsets following these blocks must be modified.
262 adjustBlockOffsets(*OrigBB);
263
Matthias Braun18198302016-12-16 23:55:37 +0000264 // Need to fix live-in lists if we track liveness.
265 if (TRI->trackLivenessAfterRegAlloc(*MF))
Matthias Braunc9056b82017-09-06 20:45:24 +0000266 computeAndAddLiveIns(LiveRegs, *NewBB);
Matthias Braun18198302016-12-16 23:55:37 +0000267
Tim Northover3b0846e2014-05-24 12:50:23 +0000268 ++NumSplit;
269
270 return NewBB;
271}
272
273/// isBlockInRange - Returns true if the distance between specific MI and
274/// specific BB can fit in MI's displacement field.
Matt Arsenault36919a42016-10-06 15:38:53 +0000275bool BranchRelaxation::isBlockInRange(
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000276 const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000277 int64_t BrOffset = getInstrOffset(MI);
278 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000279
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000280 if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +0000281 return true;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000282
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000283 LLVM_DEBUG(dbgs() << "Out of range branch to destination "
284 << printMBBReference(DestBB) << " from "
285 << printMBBReference(*MI.getParent()) << " to "
286 << DestOffset << " offset " << DestOffset - BrOffset << '\t'
287 << MI);
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000288
289 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000290}
291
Tim Northover3b0846e2014-05-24 12:50:23 +0000292/// fixupConditionalBranch - Fix up a conditional branch whose destination is
293/// too far away to fit in its displacement field. It is converted to an inverse
294/// conditional branch + an unconditional branch to the destination.
Matt Arsenault36919a42016-10-06 15:38:53 +0000295bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
Chandler Carruthbbddf212019-04-23 01:42:07 +0000296 DebugLoc DL = MI.getDebugLoc();
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000297 MachineBasicBlock *MBB = MI.getParent();
298 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000299 MachineBasicBlock *NewBB = nullptr;
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000300 SmallVector<MachineOperand, 4> Cond;
301
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000302 auto insertUncondBranch = [&](MachineBasicBlock *MBB,
303 MachineBasicBlock *DestBB) {
304 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
305 int NewBrSize = 0;
306 TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);
307 BBSize += NewBrSize;
308 };
309 auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,
310 MachineBasicBlock *FBB,
311 SmallVectorImpl<MachineOperand>& Cond) {
312 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
313 int NewBrSize = 0;
314 TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);
315 BBSize += NewBrSize;
316 };
317 auto removeBranch = [&](MachineBasicBlock *MBB) {
318 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
319 int RemovedSize = 0;
320 TII->removeBranch(*MBB, &RemovedSize);
321 BBSize -= RemovedSize;
322 };
323
324 auto finalizeBlockChanges = [&](MachineBasicBlock *MBB,
325 MachineBasicBlock *NewBB) {
326 // Keep the block offsets up to date.
327 adjustBlockOffsets(*MBB);
328
329 // Need to fix live-in lists if we track liveness.
330 if (NewBB && TRI->trackLivenessAfterRegAlloc(*MF))
331 computeAndAddLiveIns(LiveRegs, *NewBB);
332 };
333
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000334 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
335 assert(!Fail && "branches to be relaxed must be analyzable");
336 (void)Fail;
Tim Northover3b0846e2014-05-24 12:50:23 +0000337
338 // Add an unconditional branch to the destination and invert the branch
339 // condition to jump over it:
340 // tbz L1
341 // =>
342 // tbnz L2
343 // b L1
344 // L2:
345
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000346 bool ReversedCond = !TII->reverseBranchCondition(Cond);
347 if (ReversedCond) {
348 if (FBB && isBlockInRange(MI, *FBB)) {
349 // Last MI in the BB is an unconditional branch. We can simply invert the
350 // condition and swap destinations:
351 // beq L1
352 // b L2
353 // =>
354 // bne L2
355 // b L1
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000356 LLVM_DEBUG(dbgs() << " Invert condition and swap "
357 "its destination with "
358 << MBB->back());
Tim Northover3b0846e2014-05-24 12:50:23 +0000359
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000360 removeBranch(MBB);
361 insertBranch(MBB, FBB, TBB, Cond);
362 finalizeBlockChanges(MBB, nullptr);
363 return true;
364 }
365 if (FBB) {
366 // We need to split the basic block here to obtain two long-range
367 // unconditional branches.
368 NewBB = createNewBlockAfter(*MBB);
Matt Arsenault5b549712016-08-02 08:30:06 +0000369
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000370 insertUncondBranch(NewBB, FBB);
371 // Update the succesor lists according to the transformation to follow.
372 // Do it here since if there's no split, no update is needed.
373 MBB->replaceSuccessor(FBB, NewBB);
374 NewBB->addSuccessor(FBB);
375 }
376
377 // We now have an appropriate fall-through block in place (either naturally or
378 // just created), so we can use the inverted the condition.
379 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
380
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000381 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)
382 << ", invert condition and change dest. to "
383 << printMBBReference(NextBB) << '\n');
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000384
385 removeBranch(MBB);
386 // Insert a new conditional branch and a new unconditional branch.
387 insertBranch(MBB, &NextBB, TBB, Cond);
388
389 finalizeBlockChanges(MBB, NewBB);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000390 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000391 }
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000392 // Branch cond can't be inverted.
393 // In this case we always add a block after the MBB.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000394 LLVM_DEBUG(dbgs() << " The branch condition can't be inverted. "
395 << " Insert a new BB after " << MBB->back());
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000396
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000397 if (!FBB)
398 FBB = &(*std::next(MachineFunction::iterator(MBB)));
Tim Northover3b0846e2014-05-24 12:50:23 +0000399
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000400 // This is the block with cond. branch and the distance to TBB is too long.
401 // beq L1
402 // L2:
Tim Northover3b0846e2014-05-24 12:50:23 +0000403
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000404 // We do the following transformation:
405 // beq NewBB
406 // b L2
407 // NewBB:
408 // b L1
409 // L2:
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000410
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000411 NewBB = createNewBlockAfter(*MBB);
412 insertUncondBranch(NewBB, TBB);
Matt Arsenault5b549712016-08-02 08:30:06 +0000413
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000414 LLVM_DEBUG(dbgs() << " Insert cond B to the new BB "
415 << printMBBReference(*NewBB)
416 << " Keep the exiting condition.\n"
417 << " Insert B to " << printMBBReference(*FBB) << ".\n"
418 << " In the new BB: Insert B to "
419 << printMBBReference(*TBB) << ".\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000420
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000421 // Update the successor lists according to the transformation to follow.
422 MBB->replaceSuccessor(TBB, NewBB);
423 NewBB->addSuccessor(TBB);
424
425 // Replace branch in the current (MBB) block.
426 removeBranch(MBB);
427 insertBranch(MBB, NewBB, FBB, Cond);
428
429 finalizeBlockChanges(MBB, NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000430 return true;
431}
432
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000433bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
434 MachineBasicBlock *MBB = MI.getParent();
435
436 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
437 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
438
439 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
440 int64_t SrcOffset = getInstrOffset(MI);
441
442 assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
443
444 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
445
446 MachineBasicBlock *BranchBB = MBB;
447
448 // If this was an expanded conditional branch, there is already a single
449 // unconditional branch in a block.
450 if (!MBB->empty()) {
451 BranchBB = createNewBlockAfter(*MBB);
452
453 // Add live outs.
454 for (const MachineBasicBlock *Succ : MBB->successors()) {
455 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
456 BranchBB->addLiveIn(LiveIn);
457 }
458
Matt Arsenault691efe02016-10-12 15:32:04 +0000459 BranchBB->sortUniqueLiveIns();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000460 BranchBB->addSuccessor(DestBB);
461 MBB->replaceSuccessor(DestBB, BranchBB);
462 }
463
Chandler Carruthbbddf212019-04-23 01:42:07 +0000464 DebugLoc DL = MI.getDebugLoc();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000465 MI.eraseFromParent();
Matt Arsenault44deb792016-11-02 16:18:29 +0000466 BlockInfo[BranchBB->getNumber()].Size += TII->insertIndirectBranch(
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000467 *BranchBB, *DestBB, DL, DestOffset - SrcOffset, RS.get());
468
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000469 adjustBlockOffsets(*MBB);
470 return true;
471}
472
Matt Arsenault36919a42016-10-06 15:38:53 +0000473bool BranchRelaxation::relaxBranchInstructions() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000474 bool Changed = false;
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000475
Tim Northover3b0846e2014-05-24 12:50:23 +0000476 // Relaxing branches involves creating new basic blocks, so re-eval
477 // end() for termination.
Matt Arsenaultf1c39062016-06-16 21:21:49 +0000478 for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
479 MachineBasicBlock &MBB = *I;
Matt Arsenault36919a42016-10-06 15:38:53 +0000480
Matthias Braun18198302016-12-16 23:55:37 +0000481 // Empty block?
482 MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
483 if (Last == MBB.end())
Matt Arsenaultcb578f82016-11-01 18:34:00 +0000484 continue;
485
486 // Expand the unconditional branch first if necessary. If there is a
487 // conditional branch, this will end up changing the branch destination of
488 // it to be over the newly inserted indirect branch block, which may avoid
489 // the need to try expanding the conditional branch first, saving an extra
490 // jump.
491 if (Last->isUnconditionalBranch()) {
492 // Unconditional branch destination might be unanalyzable, assume these
493 // are OK.
494 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
495 if (!isBlockInRange(*Last, *DestBB)) {
496 fixupUnconditionalBranch(*Last);
497 ++NumUnconditionalRelaxed;
498 Changed = true;
499 }
500 }
501 }
502
503 // Loop over the conditional branches.
Matt Arsenault567631b2016-08-23 01:30:30 +0000504 MachineBasicBlock::iterator Next;
505 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
506 J != MBB.end(); J = Next) {
507 Next = std::next(J);
508 MachineInstr &MI = *J;
509
Philip Reamesb04c1812020-09-17 15:39:50 -0700510 if (!MI.isConditionalBranch())
511 continue;
Matt Arsenault567631b2016-08-23 01:30:30 +0000512
Philip Reamesb04c1812020-09-17 15:39:50 -0700513 if (MI.getOpcode() == TargetOpcode::FAULTING_OP)
514 // FAULTING_OP's destination is not encoded in the instruction stream
515 // and thus never needs relaxed.
516 continue;
Matt Arsenault567631b2016-08-23 01:30:30 +0000517
Philip Reamesb04c1812020-09-17 15:39:50 -0700518 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
519 if (!isBlockInRange(MI, *DestBB)) {
520 if (Next != MBB.end() && Next->isConditionalBranch()) {
521 // If there are multiple conditional branches, this isn't an
522 // analyzable block. Split later terminators into a new block so
523 // each one will be analyzable.
Matt Arsenault567631b2016-08-23 01:30:30 +0000524
Philip Reamesb04c1812020-09-17 15:39:50 -0700525 splitBlockBeforeInstr(*Next, DestBB);
526 } else {
527 fixupConditionalBranch(MI);
528 ++NumConditionalRelaxed;
Matt Arsenault567631b2016-08-23 01:30:30 +0000529 }
Philip Reamesb04c1812020-09-17 15:39:50 -0700530
531 Changed = true;
532
533 // This may have modified all of the terminators, so start over.
534 Next = MBB.getFirstTerminator();
Matt Arsenault567631b2016-08-23 01:30:30 +0000535 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000536 }
537 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000538
Tim Northover3b0846e2014-05-24 12:50:23 +0000539 return Changed;
540}
541
Matt Arsenault36919a42016-10-06 15:38:53 +0000542bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000543 MF = &mf;
544
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000545 LLVM_DEBUG(dbgs() << "***** BranchRelaxation *****\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000546
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000547 const TargetSubtargetInfo &ST = MF->getSubtarget();
548 TII = ST.getInstrInfo();
549
Matthias Braun18198302016-12-16 23:55:37 +0000550 TRI = ST.getRegisterInfo();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000551 if (TRI->trackLivenessAfterRegAlloc(*MF))
552 RS.reset(new RegScavenger());
Tim Northover3b0846e2014-05-24 12:50:23 +0000553
554 // Renumber all of the machine basic blocks in the function, guaranteeing that
555 // the numbers agree with the position of the block in the function.
556 MF->RenumberBlocks();
557
558 // Do the initial scan of the function, building up information about the
559 // sizes of each block.
560 scanFunction();
561
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000562 LLVM_DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
Tim Northover3b0846e2014-05-24 12:50:23 +0000563
564 bool MadeChange = false;
565 while (relaxBranchInstructions())
566 MadeChange = true;
567
568 // After a while, this might be made debug-only, but it is not expensive.
569 verify();
570
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000571 LLVM_DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
Tim Northover3b0846e2014-05-24 12:50:23 +0000572
573 BlockInfo.clear();
574
575 return MadeChange;
576}