blob: 6efdc9efa968459ceb7ba15ff0d2b0516aa6ca10 [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"
22#include "llvm/Pass.h"
23#include "llvm/Support/Compiler.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000024#include "llvm/Support/Debug.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000025#include "llvm/Support/Format.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000026#include "llvm/Support/MathExtras.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000027#include "llvm/Support/raw_ostream.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000028#include <cassert>
29#include <cstdint>
30#include <iterator>
31#include <memory>
Matt Arsenault36919a42016-10-06 15:38:53 +000032
Tim Northover3b0846e2014-05-24 12:50:23 +000033using namespace llvm;
34
Matt Arsenault36919a42016-10-06 15:38:53 +000035#define DEBUG_TYPE "branch-relaxation"
Tim Northover3b0846e2014-05-24 12:50:23 +000036
Tim Northover3b0846e2014-05-24 12:50:23 +000037STATISTIC(NumSplit, "Number of basic blocks split");
Matt Arsenault567631b2016-08-23 01:30:30 +000038STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
Matt Arsenault6bc43d82016-10-06 16:20:41 +000039STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
Tim Northover3b0846e2014-05-24 12:50:23 +000040
Matt Arsenault36919a42016-10-06 15:38:53 +000041#define BRANCH_RELAX_NAME "Branch relaxation pass"
Chad Rosier1c814322015-08-05 16:12:10 +000042
Tim Northover3b0846e2014-05-24 12:50:23 +000043namespace {
Eugene Zelenko618c5552017-09-13 21:15:20 +000044
Matt Arsenault36919a42016-10-06 15:38:53 +000045class BranchRelaxation : public MachineFunctionPass {
Tim Northover3b0846e2014-05-24 12:50:23 +000046 /// BasicBlockInfo - Information about the offset and size of a single
47 /// basic block.
48 struct BasicBlockInfo {
49 /// Offset - Distance from the beginning of the function to the beginning
50 /// of this basic block.
51 ///
52 /// The offset is always aligned as required by the basic block.
Eugene Zelenko618c5552017-09-13 21:15:20 +000053 unsigned Offset = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +000054
55 /// Size - Size of the basic block in bytes. If the block contains
56 /// inline assembly, this is a worst case estimate.
57 ///
58 /// The size does not include any alignment padding whether from the
59 /// beginning of the block, or from an aligned jump table at the end.
Eugene Zelenko618c5552017-09-13 21:15:20 +000060 unsigned Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +000061
Eugene Zelenko618c5552017-09-13 21:15:20 +000062 BasicBlockInfo() = default;
Tim Northover3b0846e2014-05-24 12:50:23 +000063
Matt Arsenaultef5bba02016-10-06 16:00:58 +000064 /// Compute the offset immediately following this block. \p MBB is the next
65 /// block.
66 unsigned postOffset(const MachineBasicBlock &MBB) const {
Guillaume Chatelet48904e92019-09-11 11:16:48 +000067 const unsigned PO = Offset + Size;
Guillaume Chatelet18f805a2019-09-27 12:54:21 +000068 const Align Alignment = MBB.getAlignment();
69 if (Alignment == 1)
Matt Arsenaultef5bba02016-10-06 16:00:58 +000070 return PO;
71
Guillaume Chatelet18f805a2019-09-27 12:54:21 +000072 const Align ParentAlign = MBB.getParent()->getAlignment();
73 if (Alignment <= ParentAlign)
74 return PO + offsetToAlignment(PO, Alignment);
Matt Arsenaultef5bba02016-10-06 16:00:58 +000075
76 // The alignment of this MBB is larger than the function's alignment, so we
77 // can't tell whether or not it will insert nops. Assume that it will.
Guillaume Chatelet18f805a2019-09-27 12:54:21 +000078 return PO + Alignment.value() + offsetToAlignment(PO, Alignment);
Tim Northover3b0846e2014-05-24 12:50:23 +000079 }
80 };
81
82 SmallVector<BasicBlockInfo, 16> BlockInfo;
Matt Arsenault6bc43d82016-10-06 16:20:41 +000083 std::unique_ptr<RegScavenger> RS;
Matthias Braun18198302016-12-16 23:55:37 +000084 LivePhysRegs LiveRegs;
Tim Northover3b0846e2014-05-24 12:50:23 +000085
86 MachineFunction *MF;
Matthias Braun18198302016-12-16 23:55:37 +000087 const TargetRegisterInfo *TRI;
Matt Arsenault36919a42016-10-06 15:38:53 +000088 const TargetInstrInfo *TII;
Tim Northover3b0846e2014-05-24 12:50:23 +000089
90 bool relaxBranchInstructions();
91 void scanFunction();
Matt Arsenault6bc43d82016-10-06 16:20:41 +000092
93 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &BB);
94
Matt Arsenault44deb792016-11-02 16:18:29 +000095 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
96 MachineBasicBlock *DestBB);
Fangrui Songcb0bab82018-07-16 18:51:40 +000097 void adjustBlockOffsets(MachineBasicBlock &Start);
Matt Arsenaulte8da1452016-08-02 08:06:17 +000098 bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
Matt Arsenault5b549712016-08-02 08:30:06 +000099
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000100 bool fixupConditionalBranch(MachineInstr &MI);
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000101 bool fixupUnconditionalBranch(MachineInstr &MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000102 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000103 unsigned getInstrOffset(const MachineInstr &MI) const;
Tim Northover3b0846e2014-05-24 12:50:23 +0000104 void dumpBBs();
105 void verify();
106
107public:
108 static char ID;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000109
110 BranchRelaxation() : MachineFunctionPass(ID) {}
Tim Northover3b0846e2014-05-24 12:50:23 +0000111
112 bool runOnMachineFunction(MachineFunction &MF) override;
113
Eugene Zelenko618c5552017-09-13 21:15:20 +0000114 StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000115};
Matt Arsenault36919a42016-10-06 15:38:53 +0000116
Eugene Zelenko618c5552017-09-13 21:15:20 +0000117} // end anonymous namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000118
Matt Arsenault36919a42016-10-06 15:38:53 +0000119char BranchRelaxation::ID = 0;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000120
Matt Arsenault36919a42016-10-06 15:38:53 +0000121char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
122
123INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
Chad Rosier1c814322015-08-05 16:12:10 +0000124
Tim Northover3b0846e2014-05-24 12:50:23 +0000125/// verify - check BBOffsets, BBSizes, alignment of islands
Matt Arsenault36919a42016-10-06 15:38:53 +0000126void BranchRelaxation::verify() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000127#ifndef NDEBUG
128 unsigned PrevNum = MF->begin()->getNumber();
129 for (MachineBasicBlock &MBB : *MF) {
Guillaume Chateletd4c46712019-09-18 15:49:49 +0000130 const unsigned Num = MBB.getNumber();
131 assert(isAligned(MBB.getAlignment(), BlockInfo[Num].Offset));
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000132 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
Matt Arsenault44deb792016-11-02 16:18:29 +0000133 assert(BlockInfo[Num].Size == computeBlockSize(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000134 PrevNum = Num;
135 }
136#endif
137}
138
Aaron Ballman615eb472017-10-15 14:32:27 +0000139#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Tim Northover3b0846e2014-05-24 12:50:23 +0000140/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000141LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000142 for (auto &MBB : *MF) {
143 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
Evgeniy Stepanov187c63f2019-08-16 18:23:54 +0000144 dbgs() << format("%%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
Tim Northover3b0846e2014-05-24 12:50:23 +0000145 << format("size=%#x\n", BBI.Size);
146 }
147}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000148#endif
Tim Northover3b0846e2014-05-24 12:50:23 +0000149
Tim Northover3b0846e2014-05-24 12:50:23 +0000150/// scanFunction - Do the initial scan of the function, building up
151/// information about each block.
Matt Arsenault36919a42016-10-06 15:38:53 +0000152void BranchRelaxation::scanFunction() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000153 BlockInfo.clear();
154 BlockInfo.resize(MF->getNumBlockIDs());
155
156 // First thing, compute the size of all basic blocks, and see if the function
157 // has any inline assembly in it. If so, we have to be conservative about
158 // alignment assumptions, as we don't know for sure the size of any
159 // instructions in the inline assembly.
160 for (MachineBasicBlock &MBB : *MF)
Matt Arsenault36919a42016-10-06 15:38:53 +0000161 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000162
163 // Compute block offsets and known bits.
164 adjustBlockOffsets(*MF->begin());
165}
166
167/// computeBlockSize - Compute the size for MBB.
Matt Arsenault36919a42016-10-06 15:38:53 +0000168uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
169 uint64_t Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000170 for (const MachineInstr &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000171 Size += TII->getInstSizeInBytes(MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000172 return Size;
Tim Northover3b0846e2014-05-24 12:50:23 +0000173}
174
175/// getInstrOffset - Return the current offset of the specified machine
176/// instruction from the start of the function. This offset changes as stuff is
177/// moved around inside the function.
Matt Arsenault36919a42016-10-06 15:38:53 +0000178unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000179 const MachineBasicBlock *MBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000180
181 // The offset is composed of two things: the sum of the sizes of all MBB's
182 // before this instruction's block, and the offset from the start of the block
183 // it is in.
184 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
185
186 // Sum instructions before MI in MBB.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000187 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000188 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000189 Offset += TII->getInstSizeInBytes(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000190 }
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000191
Tim Northover3b0846e2014-05-24 12:50:23 +0000192 return Offset;
193}
194
Matt Arsenault36919a42016-10-06 15:38:53 +0000195void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000196 unsigned PrevNum = Start.getNumber();
197 for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
198 unsigned Num = MBB.getNumber();
199 if (!Num) // block zero is never changed from offset zero.
200 continue;
201 // Get the offset and known bits at the end of the layout predecessor.
202 // Include the alignment of the current block.
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000203 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
204
Tim Northover3b0846e2014-05-24 12:50:23 +0000205 PrevNum = Num;
206 }
207}
208
Eugene Zelenko618c5552017-09-13 21:15:20 +0000209/// Insert a new empty basic block and insert it after \BB
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000210MachineBasicBlock *BranchRelaxation::createNewBlockAfter(MachineBasicBlock &BB) {
211 // Create a new MBB for the code after the OrigBB.
212 MachineBasicBlock *NewBB =
213 MF->CreateMachineBasicBlock(BB.getBasicBlock());
214 MF->insert(++BB.getIterator(), NewBB);
215
216 // Insert an entry into BlockInfo to align it properly with the block numbers.
217 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
218
219 return NewBB;
220}
221
Tim Northover3b0846e2014-05-24 12:50:23 +0000222/// Split the basic block containing MI into two blocks, which are joined by
223/// an unconditional branch. Update data structures and renumber blocks to
224/// account for this change and returns the newly created block.
Matt Arsenault44deb792016-11-02 16:18:29 +0000225MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
226 MachineBasicBlock *DestBB) {
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000227 MachineBasicBlock *OrigBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000228
229 // Create a new MBB for the code after the OrigBB.
230 MachineBasicBlock *NewBB =
231 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000232 MF->insert(++OrigBB->getIterator(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000233
234 // Splice the instructions starting with MI over to NewBB.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000235 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
Tim Northover3b0846e2014-05-24 12:50:23 +0000236
237 // Add an unconditional branch from OrigBB to NewBB.
238 // Note the new unconditional branch is not being recorded.
239 // There doesn't seem to be meaningful DebugInfo available; this doesn't
240 // correspond to anything in the source.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000241 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
Tim Northover3b0846e2014-05-24 12:50:23 +0000242
243 // Insert an entry into BlockInfo to align it properly with the block numbers.
244 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
245
Matt Arsenault44deb792016-11-02 16:18:29 +0000246 NewBB->transferSuccessors(OrigBB);
247 OrigBB->addSuccessor(NewBB);
248 OrigBB->addSuccessor(DestBB);
249
250 // Cleanup potential unconditional branch to successor block.
251 // Note that updateTerminator may change the size of the blocks.
252 NewBB->updateTerminator();
253 OrigBB->updateTerminator();
254
Tim Northover3b0846e2014-05-24 12:50:23 +0000255 // Figure out how large the OrigBB is. As the first half of the original
256 // block, it cannot contain a tablejump. The size includes
257 // the new jump we added. (It should be possible to do this without
258 // recounting everything, but it's very confusing, and this is rarely
259 // executed.)
Matt Arsenault36919a42016-10-06 15:38:53 +0000260 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000261
Matt Arsenault36919a42016-10-06 15:38:53 +0000262 // Figure out how large the NewMBB is. As the second half of the original
Tim Northover3b0846e2014-05-24 12:50:23 +0000263 // block, it may contain a tablejump.
Matt Arsenault36919a42016-10-06 15:38:53 +0000264 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000265
266 // All BBOffsets following these blocks must be modified.
267 adjustBlockOffsets(*OrigBB);
268
Matthias Braun18198302016-12-16 23:55:37 +0000269 // Need to fix live-in lists if we track liveness.
270 if (TRI->trackLivenessAfterRegAlloc(*MF))
Matthias Braunc9056b82017-09-06 20:45:24 +0000271 computeAndAddLiveIns(LiveRegs, *NewBB);
Matthias Braun18198302016-12-16 23:55:37 +0000272
Tim Northover3b0846e2014-05-24 12:50:23 +0000273 ++NumSplit;
274
275 return NewBB;
276}
277
278/// isBlockInRange - Returns true if the distance between specific MI and
279/// specific BB can fit in MI's displacement field.
Matt Arsenault36919a42016-10-06 15:38:53 +0000280bool BranchRelaxation::isBlockInRange(
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000281 const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000282 int64_t BrOffset = getInstrOffset(MI);
283 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000284
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000285 if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +0000286 return true;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000287
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000288 LLVM_DEBUG(dbgs() << "Out of range branch to destination "
289 << printMBBReference(DestBB) << " from "
290 << printMBBReference(*MI.getParent()) << " to "
291 << DestOffset << " offset " << DestOffset - BrOffset << '\t'
292 << MI);
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000293
294 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000295}
296
Tim Northover3b0846e2014-05-24 12:50:23 +0000297/// fixupConditionalBranch - Fix up a conditional branch whose destination is
298/// too far away to fit in its displacement field. It is converted to an inverse
299/// conditional branch + an unconditional branch to the destination.
Matt Arsenault36919a42016-10-06 15:38:53 +0000300bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
Chandler Carruthbbddf212019-04-23 01:42:07 +0000301 DebugLoc DL = MI.getDebugLoc();
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000302 MachineBasicBlock *MBB = MI.getParent();
303 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000304 MachineBasicBlock *NewBB = nullptr;
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000305 SmallVector<MachineOperand, 4> Cond;
306
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000307 auto insertUncondBranch = [&](MachineBasicBlock *MBB,
308 MachineBasicBlock *DestBB) {
309 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
310 int NewBrSize = 0;
311 TII->insertUnconditionalBranch(*MBB, DestBB, DL, &NewBrSize);
312 BBSize += NewBrSize;
313 };
314 auto insertBranch = [&](MachineBasicBlock *MBB, MachineBasicBlock *TBB,
315 MachineBasicBlock *FBB,
316 SmallVectorImpl<MachineOperand>& Cond) {
317 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
318 int NewBrSize = 0;
319 TII->insertBranch(*MBB, TBB, FBB, Cond, DL, &NewBrSize);
320 BBSize += NewBrSize;
321 };
322 auto removeBranch = [&](MachineBasicBlock *MBB) {
323 unsigned &BBSize = BlockInfo[MBB->getNumber()].Size;
324 int RemovedSize = 0;
325 TII->removeBranch(*MBB, &RemovedSize);
326 BBSize -= RemovedSize;
327 };
328
329 auto finalizeBlockChanges = [&](MachineBasicBlock *MBB,
330 MachineBasicBlock *NewBB) {
331 // Keep the block offsets up to date.
332 adjustBlockOffsets(*MBB);
333
334 // Need to fix live-in lists if we track liveness.
335 if (NewBB && TRI->trackLivenessAfterRegAlloc(*MF))
336 computeAndAddLiveIns(LiveRegs, *NewBB);
337 };
338
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000339 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
340 assert(!Fail && "branches to be relaxed must be analyzable");
341 (void)Fail;
Tim Northover3b0846e2014-05-24 12:50:23 +0000342
343 // Add an unconditional branch to the destination and invert the branch
344 // condition to jump over it:
345 // tbz L1
346 // =>
347 // tbnz L2
348 // b L1
349 // L2:
350
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000351 bool ReversedCond = !TII->reverseBranchCondition(Cond);
352 if (ReversedCond) {
353 if (FBB && isBlockInRange(MI, *FBB)) {
354 // Last MI in the BB is an unconditional branch. We can simply invert the
355 // condition and swap destinations:
356 // beq L1
357 // b L2
358 // =>
359 // bne L2
360 // b L1
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000361 LLVM_DEBUG(dbgs() << " Invert condition and swap "
362 "its destination with "
363 << MBB->back());
Tim Northover3b0846e2014-05-24 12:50:23 +0000364
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000365 removeBranch(MBB);
366 insertBranch(MBB, FBB, TBB, Cond);
367 finalizeBlockChanges(MBB, nullptr);
368 return true;
369 }
370 if (FBB) {
371 // We need to split the basic block here to obtain two long-range
372 // unconditional branches.
373 NewBB = createNewBlockAfter(*MBB);
Matt Arsenault5b549712016-08-02 08:30:06 +0000374
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000375 insertUncondBranch(NewBB, FBB);
376 // Update the succesor lists according to the transformation to follow.
377 // Do it here since if there's no split, no update is needed.
378 MBB->replaceSuccessor(FBB, NewBB);
379 NewBB->addSuccessor(FBB);
380 }
381
382 // We now have an appropriate fall-through block in place (either naturally or
383 // just created), so we can use the inverted the condition.
384 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
385
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000386 LLVM_DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)
387 << ", invert condition and change dest. to "
388 << printMBBReference(NextBB) << '\n');
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000389
390 removeBranch(MBB);
391 // Insert a new conditional branch and a new unconditional branch.
392 insertBranch(MBB, &NextBB, TBB, Cond);
393
394 finalizeBlockChanges(MBB, NewBB);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000395 return true;
Tim Northover3b0846e2014-05-24 12:50:23 +0000396 }
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000397 // Branch cond can't be inverted.
398 // In this case we always add a block after the MBB.
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000399 LLVM_DEBUG(dbgs() << " The branch condition can't be inverted. "
400 << " Insert a new BB after " << MBB->back());
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000401
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000402 if (!FBB)
403 FBB = &(*std::next(MachineFunction::iterator(MBB)));
Tim Northover3b0846e2014-05-24 12:50:23 +0000404
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000405 // This is the block with cond. branch and the distance to TBB is too long.
406 // beq L1
407 // L2:
Tim Northover3b0846e2014-05-24 12:50:23 +0000408
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000409 // We do the following transformation:
410 // beq NewBB
411 // b L2
412 // NewBB:
413 // b L1
414 // L2:
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000415
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000416 NewBB = createNewBlockAfter(*MBB);
417 insertUncondBranch(NewBB, TBB);
Matt Arsenault5b549712016-08-02 08:30:06 +0000418
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000419 LLVM_DEBUG(dbgs() << " Insert cond B to the new BB "
420 << printMBBReference(*NewBB)
421 << " Keep the exiting condition.\n"
422 << " Insert B to " << printMBBReference(*FBB) << ".\n"
423 << " In the new BB: Insert B to "
424 << printMBBReference(*TBB) << ".\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000425
Elena Demikhovskyb8f29782018-01-04 07:08:45 +0000426 // Update the successor lists according to the transformation to follow.
427 MBB->replaceSuccessor(TBB, NewBB);
428 NewBB->addSuccessor(TBB);
429
430 // Replace branch in the current (MBB) block.
431 removeBranch(MBB);
432 insertBranch(MBB, NewBB, FBB, Cond);
433
434 finalizeBlockChanges(MBB, NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000435 return true;
436}
437
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000438bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
439 MachineBasicBlock *MBB = MI.getParent();
440
441 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
442 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
443
444 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
445 int64_t SrcOffset = getInstrOffset(MI);
446
447 assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
448
449 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
450
451 MachineBasicBlock *BranchBB = MBB;
452
453 // If this was an expanded conditional branch, there is already a single
454 // unconditional branch in a block.
455 if (!MBB->empty()) {
456 BranchBB = createNewBlockAfter(*MBB);
457
458 // Add live outs.
459 for (const MachineBasicBlock *Succ : MBB->successors()) {
460 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
461 BranchBB->addLiveIn(LiveIn);
462 }
463
Matt Arsenault691efe02016-10-12 15:32:04 +0000464 BranchBB->sortUniqueLiveIns();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000465 BranchBB->addSuccessor(DestBB);
466 MBB->replaceSuccessor(DestBB, BranchBB);
467 }
468
Chandler Carruthbbddf212019-04-23 01:42:07 +0000469 DebugLoc DL = MI.getDebugLoc();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000470 MI.eraseFromParent();
Matt Arsenault44deb792016-11-02 16:18:29 +0000471 BlockInfo[BranchBB->getNumber()].Size += TII->insertIndirectBranch(
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000472 *BranchBB, *DestBB, DL, DestOffset - SrcOffset, RS.get());
473
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000474 adjustBlockOffsets(*MBB);
475 return true;
476}
477
Matt Arsenault36919a42016-10-06 15:38:53 +0000478bool BranchRelaxation::relaxBranchInstructions() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000479 bool Changed = false;
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000480
Tim Northover3b0846e2014-05-24 12:50:23 +0000481 // Relaxing branches involves creating new basic blocks, so re-eval
482 // end() for termination.
Matt Arsenaultf1c39062016-06-16 21:21:49 +0000483 for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
484 MachineBasicBlock &MBB = *I;
Matt Arsenault36919a42016-10-06 15:38:53 +0000485
Matthias Braun18198302016-12-16 23:55:37 +0000486 // Empty block?
487 MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
488 if (Last == MBB.end())
Matt Arsenaultcb578f82016-11-01 18:34:00 +0000489 continue;
490
491 // Expand the unconditional branch first if necessary. If there is a
492 // conditional branch, this will end up changing the branch destination of
493 // it to be over the newly inserted indirect branch block, which may avoid
494 // the need to try expanding the conditional branch first, saving an extra
495 // jump.
496 if (Last->isUnconditionalBranch()) {
497 // Unconditional branch destination might be unanalyzable, assume these
498 // are OK.
499 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
500 if (!isBlockInRange(*Last, *DestBB)) {
501 fixupUnconditionalBranch(*Last);
502 ++NumUnconditionalRelaxed;
503 Changed = true;
504 }
505 }
506 }
507
508 // Loop over the conditional branches.
Matt Arsenault567631b2016-08-23 01:30:30 +0000509 MachineBasicBlock::iterator Next;
510 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
511 J != MBB.end(); J = Next) {
512 Next = std::next(J);
513 MachineInstr &MI = *J;
514
515 if (MI.isConditionalBranch()) {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000516 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
Matt Arsenault567631b2016-08-23 01:30:30 +0000517 if (!isBlockInRange(MI, *DestBB)) {
518 if (Next != MBB.end() && Next->isConditionalBranch()) {
519 // If there are multiple conditional branches, this isn't an
520 // analyzable block. Split later terminators into a new block so
521 // each one will be analyzable.
522
Matt Arsenault44deb792016-11-02 16:18:29 +0000523 splitBlockBeforeInstr(*Next, DestBB);
Matt Arsenault567631b2016-08-23 01:30:30 +0000524 } else {
525 fixupConditionalBranch(MI);
526 ++NumConditionalRelaxed;
527 }
528
529 Changed = true;
530
531 // This may have modified all of the terminators, so start over.
532 Next = MBB.getFirstTerminator();
533 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000534 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000535 }
536 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000537
Tim Northover3b0846e2014-05-24 12:50:23 +0000538 return Changed;
539}
540
Matt Arsenault36919a42016-10-06 15:38:53 +0000541bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000542 MF = &mf;
543
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000544 LLVM_DEBUG(dbgs() << "***** BranchRelaxation *****\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000545
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000546 const TargetSubtargetInfo &ST = MF->getSubtarget();
547 TII = ST.getInstrInfo();
548
Matthias Braun18198302016-12-16 23:55:37 +0000549 TRI = ST.getRegisterInfo();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000550 if (TRI->trackLivenessAfterRegAlloc(*MF))
551 RS.reset(new RegScavenger());
Tim Northover3b0846e2014-05-24 12:50:23 +0000552
553 // Renumber all of the machine basic blocks in the function, guaranteeing that
554 // the numbers agree with the position of the block in the function.
555 MF->RenumberBlocks();
556
557 // Do the initial scan of the function, building up information about the
558 // sizes of each block.
559 scanFunction();
560
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000561 LLVM_DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
Tim Northover3b0846e2014-05-24 12:50:23 +0000562
563 bool MadeChange = false;
564 while (relaxBranchInstructions())
565 MadeChange = true;
566
567 // After a while, this might be made debug-only, but it is not expensive.
568 verify();
569
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000570 LLVM_DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
Tim Northover3b0846e2014-05-24 12:50:23 +0000571
572 BlockInfo.clear();
573
574 return MadeChange;
575}