blob: 0d87f142c7ccefaa1a373799d4edbbd5e834ed26 [file] [log] [blame]
Eugene Zelenko618c5552017-09-13 21:15:20 +00001//===- BranchRelaxation.cpp -----------------------------------------------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Tim Northover3b0846e2014-05-24 12:50:23 +00009
Tim Northover3b0846e2014-05-24 12:50:23 +000010#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000011#include "llvm/ADT/Statistic.h"
Matthias Braun18198302016-12-16 23:55:37 +000012#include "llvm/CodeGen/LivePhysRegs.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000013#include "llvm/CodeGen/MachineBasicBlock.h"
14#include "llvm/CodeGen/MachineFunction.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000015#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko618c5552017-09-13 21:15:20 +000016#include "llvm/CodeGen/MachineInstr.h"
Matt Arsenault6bc43d82016-10-06 16:20:41 +000017#include "llvm/CodeGen/RegisterScavenging.h"
David Blaikie3f833ed2017-11-08 01:01:31 +000018#include "llvm/CodeGen/TargetInstrInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000019#include "llvm/CodeGen/TargetRegisterInfo.h"
20#include "llvm/CodeGen/TargetSubtargetInfo.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 {
Tim Northover3b0846e2014-05-24 12:50:23 +000067 unsigned PO = Offset + Size;
Matt Arsenaultef5bba02016-10-06 16:00:58 +000068 unsigned Align = MBB.getAlignment();
69 if (Align == 0)
70 return PO;
71
72 unsigned AlignAmt = 1 << Align;
73 unsigned ParentAlign = MBB.getParent()->getAlignment();
74 if (Align <= ParentAlign)
75 return PO + OffsetToAlignment(PO, AlignAmt);
76
77 // The alignment of this MBB is larger than the function's alignment, so we
78 // can't tell whether or not it will insert nops. Assume that it will.
79 return PO + AlignAmt + OffsetToAlignment(PO, AlignAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +000080 }
81 };
82
83 SmallVector<BasicBlockInfo, 16> BlockInfo;
Matt Arsenault6bc43d82016-10-06 16:20:41 +000084 std::unique_ptr<RegScavenger> RS;
Matthias Braun18198302016-12-16 23:55:37 +000085 LivePhysRegs LiveRegs;
Tim Northover3b0846e2014-05-24 12:50:23 +000086
87 MachineFunction *MF;
Matthias Braun18198302016-12-16 23:55:37 +000088 const TargetRegisterInfo *TRI;
Matt Arsenault36919a42016-10-06 15:38:53 +000089 const TargetInstrInfo *TII;
Tim Northover3b0846e2014-05-24 12:50:23 +000090
91 bool relaxBranchInstructions();
92 void scanFunction();
Matt Arsenault6bc43d82016-10-06 16:20:41 +000093
94 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &BB);
95
Matt Arsenault44deb792016-11-02 16:18:29 +000096 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
97 MachineBasicBlock *DestBB);
Tim Northover3b0846e2014-05-24 12:50:23 +000098 void adjustBlockOffsets(MachineBasicBlock &MBB);
Matt Arsenaulte8da1452016-08-02 08:06:17 +000099 bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
Matt Arsenault5b549712016-08-02 08:30:06 +0000100
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000101 bool fixupConditionalBranch(MachineInstr &MI);
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000102 bool fixupUnconditionalBranch(MachineInstr &MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000103 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000104 unsigned getInstrOffset(const MachineInstr &MI) const;
Tim Northover3b0846e2014-05-24 12:50:23 +0000105 void dumpBBs();
106 void verify();
107
108public:
109 static char ID;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000110
111 BranchRelaxation() : MachineFunctionPass(ID) {}
Tim Northover3b0846e2014-05-24 12:50:23 +0000112
113 bool runOnMachineFunction(MachineFunction &MF) override;
114
Eugene Zelenko618c5552017-09-13 21:15:20 +0000115 StringRef getPassName() const override { return BRANCH_RELAX_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +0000116};
Matt Arsenault36919a42016-10-06 15:38:53 +0000117
Eugene Zelenko618c5552017-09-13 21:15:20 +0000118} // end anonymous namespace
Tim Northover3b0846e2014-05-24 12:50:23 +0000119
Matt Arsenault36919a42016-10-06 15:38:53 +0000120char BranchRelaxation::ID = 0;
Eugene Zelenko618c5552017-09-13 21:15:20 +0000121
Matt Arsenault36919a42016-10-06 15:38:53 +0000122char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
123
124INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
Chad Rosier1c814322015-08-05 16:12:10 +0000125
Tim Northover3b0846e2014-05-24 12:50:23 +0000126/// verify - check BBOffsets, BBSizes, alignment of islands
Matt Arsenault36919a42016-10-06 15:38:53 +0000127void BranchRelaxation::verify() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000128#ifndef NDEBUG
129 unsigned PrevNum = MF->begin()->getNumber();
130 for (MachineBasicBlock &MBB : *MF) {
131 unsigned Align = MBB.getAlignment();
132 unsigned Num = MBB.getNumber();
133 assert(BlockInfo[Num].Offset % (1u << Align) == 0);
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000134 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
Matt Arsenault44deb792016-11-02 16:18:29 +0000135 assert(BlockInfo[Num].Size == computeBlockSize(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000136 PrevNum = Num;
137 }
138#endif
139}
140
Aaron Ballman615eb472017-10-15 14:32:27 +0000141#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Tim Northover3b0846e2014-05-24 12:50:23 +0000142/// print block size and offset information - debugging
Matthias Braun8c209aa2017-01-28 02:02:38 +0000143LLVM_DUMP_METHOD void BranchRelaxation::dumpBBs() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000144 for (auto &MBB : *MF) {
145 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000146 dbgs() << format("%bb.%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
Tim Northover3b0846e2014-05-24 12:50:23 +0000147 << format("size=%#x\n", BBI.Size);
148 }
149}
Matthias Braun8c209aa2017-01-28 02:02:38 +0000150#endif
Tim Northover3b0846e2014-05-24 12:50:23 +0000151
Tim Northover3b0846e2014-05-24 12:50:23 +0000152/// scanFunction - Do the initial scan of the function, building up
153/// information about each block.
Matt Arsenault36919a42016-10-06 15:38:53 +0000154void BranchRelaxation::scanFunction() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000155 BlockInfo.clear();
156 BlockInfo.resize(MF->getNumBlockIDs());
157
158 // First thing, compute the size of all basic blocks, and see if the function
159 // has any inline assembly in it. If so, we have to be conservative about
160 // alignment assumptions, as we don't know for sure the size of any
161 // instructions in the inline assembly.
162 for (MachineBasicBlock &MBB : *MF)
Matt Arsenault36919a42016-10-06 15:38:53 +0000163 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000164
165 // Compute block offsets and known bits.
166 adjustBlockOffsets(*MF->begin());
167}
168
169/// computeBlockSize - Compute the size for MBB.
Matt Arsenault36919a42016-10-06 15:38:53 +0000170uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
171 uint64_t Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000172 for (const MachineInstr &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000173 Size += TII->getInstSizeInBytes(MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000174 return Size;
Tim Northover3b0846e2014-05-24 12:50:23 +0000175}
176
177/// getInstrOffset - Return the current offset of the specified machine
178/// instruction from the start of the function. This offset changes as stuff is
179/// moved around inside the function.
Matt Arsenault36919a42016-10-06 15:38:53 +0000180unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000181 const MachineBasicBlock *MBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000182
183 // The offset is composed of two things: the sum of the sizes of all MBB's
184 // before this instruction's block, and the offset from the start of the block
185 // it is in.
186 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
187
188 // Sum instructions before MI in MBB.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000189 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000190 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000191 Offset += TII->getInstSizeInBytes(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000192 }
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000193
Tim Northover3b0846e2014-05-24 12:50:23 +0000194 return Offset;
195}
196
Matt Arsenault36919a42016-10-06 15:38:53 +0000197void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000198 unsigned PrevNum = Start.getNumber();
199 for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
200 unsigned Num = MBB.getNumber();
201 if (!Num) // block zero is never changed from offset zero.
202 continue;
203 // Get the offset and known bits at the end of the layout predecessor.
204 // Include the alignment of the current block.
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000205 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
206
Tim Northover3b0846e2014-05-24 12:50:23 +0000207 PrevNum = Num;
208 }
209}
210
Eugene Zelenko618c5552017-09-13 21:15:20 +0000211/// Insert a new empty basic block and insert it after \BB
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000212MachineBasicBlock *BranchRelaxation::createNewBlockAfter(MachineBasicBlock &BB) {
213 // Create a new MBB for the code after the OrigBB.
214 MachineBasicBlock *NewBB =
215 MF->CreateMachineBasicBlock(BB.getBasicBlock());
216 MF->insert(++BB.getIterator(), NewBB);
217
218 // Insert an entry into BlockInfo to align it properly with the block numbers.
219 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
220
221 return NewBB;
222}
223
Tim Northover3b0846e2014-05-24 12:50:23 +0000224/// Split the basic block containing MI into two blocks, which are joined by
225/// an unconditional branch. Update data structures and renumber blocks to
226/// account for this change and returns the newly created block.
Matt Arsenault44deb792016-11-02 16:18:29 +0000227MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
228 MachineBasicBlock *DestBB) {
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000229 MachineBasicBlock *OrigBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000230
231 // Create a new MBB for the code after the OrigBB.
232 MachineBasicBlock *NewBB =
233 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000234 MF->insert(++OrigBB->getIterator(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000235
236 // Splice the instructions starting with MI over to NewBB.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000237 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
Tim Northover3b0846e2014-05-24 12:50:23 +0000238
239 // Add an unconditional branch from OrigBB to NewBB.
240 // Note the new unconditional branch is not being recorded.
241 // There doesn't seem to be meaningful DebugInfo available; this doesn't
242 // correspond to anything in the source.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000243 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
Tim Northover3b0846e2014-05-24 12:50:23 +0000244
245 // Insert an entry into BlockInfo to align it properly with the block numbers.
246 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
247
Matt Arsenault44deb792016-11-02 16:18:29 +0000248 NewBB->transferSuccessors(OrigBB);
249 OrigBB->addSuccessor(NewBB);
250 OrigBB->addSuccessor(DestBB);
251
252 // Cleanup potential unconditional branch to successor block.
253 // Note that updateTerminator may change the size of the blocks.
254 NewBB->updateTerminator();
255 OrigBB->updateTerminator();
256
Tim Northover3b0846e2014-05-24 12:50:23 +0000257 // Figure out how large the OrigBB is. As the first half of the original
258 // block, it cannot contain a tablejump. The size includes
259 // the new jump we added. (It should be possible to do this without
260 // recounting everything, but it's very confusing, and this is rarely
261 // executed.)
Matt Arsenault36919a42016-10-06 15:38:53 +0000262 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000263
Matt Arsenault36919a42016-10-06 15:38:53 +0000264 // Figure out how large the NewMBB is. As the second half of the original
Tim Northover3b0846e2014-05-24 12:50:23 +0000265 // block, it may contain a tablejump.
Matt Arsenault36919a42016-10-06 15:38:53 +0000266 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000267
268 // All BBOffsets following these blocks must be modified.
269 adjustBlockOffsets(*OrigBB);
270
Matthias Braun18198302016-12-16 23:55:37 +0000271 // Need to fix live-in lists if we track liveness.
272 if (TRI->trackLivenessAfterRegAlloc(*MF))
Matthias Braunc9056b82017-09-06 20:45:24 +0000273 computeAndAddLiveIns(LiveRegs, *NewBB);
Matthias Braun18198302016-12-16 23:55:37 +0000274
Tim Northover3b0846e2014-05-24 12:50:23 +0000275 ++NumSplit;
276
277 return NewBB;
278}
279
280/// isBlockInRange - Returns true if the distance between specific MI and
281/// specific BB can fit in MI's displacement field.
Matt Arsenault36919a42016-10-06 15:38:53 +0000282bool BranchRelaxation::isBlockInRange(
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000283 const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000284 int64_t BrOffset = getInstrOffset(MI);
285 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000286
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000287 if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +0000288 return true;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000289
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000290 DEBUG(dbgs() << "Out of range branch to destination "
291 << printMBBReference(DestBB) << " from "
292 << printMBBReference(*MI.getParent()) << " to " << DestOffset
293 << " offset " << DestOffset - BrOffset << '\t' << MI);
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000294
295 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000296}
297
Tim Northover3b0846e2014-05-24 12:50:23 +0000298/// fixupConditionalBranch - Fix up a conditional branch whose destination is
299/// too far away to fit in its displacement field. It is converted to an inverse
300/// conditional branch + an unconditional branch to the destination.
Matt Arsenault36919a42016-10-06 15:38:53 +0000301bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000302 DebugLoc DL = MI.getDebugLoc();
303 MachineBasicBlock *MBB = MI.getParent();
304 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
305 SmallVector<MachineOperand, 4> Cond;
306
307 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
308 assert(!Fail && "branches to be relaxed must be analyzable");
309 (void)Fail;
Tim Northover3b0846e2014-05-24 12:50:23 +0000310
311 // Add an unconditional branch to the destination and invert the branch
312 // condition to jump over it:
313 // tbz L1
314 // =>
315 // tbnz L2
316 // b L1
317 // L2:
318
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000319 if (FBB && isBlockInRange(MI, *FBB)) {
320 // Last MI in the BB is an unconditional branch. We can simply invert the
321 // condition and swap destinations:
322 // beq L1
323 // b L2
324 // =>
325 // bne L2
326 // b L1
327 DEBUG(dbgs() << " Invert condition and swap "
328 "its destination with " << MBB->back());
Tim Northover3b0846e2014-05-24 12:50:23 +0000329
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000330 TII->reverseBranchCondition(Cond);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000331 int OldSize = 0, NewSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000332 TII->removeBranch(*MBB, &OldSize);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000333 TII->insertBranch(*MBB, FBB, TBB, Cond, DL, &NewSize);
Matt Arsenault5b549712016-08-02 08:30:06 +0000334
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000335 BlockInfo[MBB->getNumber()].Size += (NewSize - OldSize);
336 return true;
337 } else if (FBB) {
338 // We need to split the basic block here to obtain two long-range
339 // unconditional branches.
340 auto &NewBB = *MF->CreateMachineBasicBlock(MBB->getBasicBlock());
341 MF->insert(++MBB->getIterator(), &NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000342
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000343 // Insert an entry into BlockInfo to align it properly with the block
344 // numbers.
345 BlockInfo.insert(BlockInfo.begin() + NewBB.getNumber(), BasicBlockInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000346
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000347 unsigned &NewBBSize = BlockInfo[NewBB.getNumber()].Size;
348 int NewBrSize;
349 TII->insertUnconditionalBranch(NewBB, FBB, DL, &NewBrSize);
350 NewBBSize += NewBrSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000351
352 // Update the successor lists according to the transformation to follow.
353 // Do it here since if there's no split, no update is needed.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000354 MBB->replaceSuccessor(FBB, &NewBB);
355 NewBB.addSuccessor(FBB);
Matthias Braun24dc63a2017-05-27 00:53:48 +0000356
357 // Need to fix live-in lists if we track liveness.
358 if (TRI->trackLivenessAfterRegAlloc(*MF))
Matthias Braunc9056b82017-09-06 20:45:24 +0000359 computeAndAddLiveIns(LiveRegs, NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000360 }
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000361
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000362 // We now have an appropriate fall-through block in place (either naturally or
363 // just created), so we can invert the condition.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000364 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000365
Francis Visoiu Mistrih25528d62017-12-04 17:18:51 +0000366 DEBUG(dbgs() << " Insert B to " << printMBBReference(*TBB)
367 << ", invert condition and change dest. to "
368 << printMBBReference(NextBB) << '\n');
Tim Northover3b0846e2014-05-24 12:50:23 +0000369
Matt Arsenault5b549712016-08-02 08:30:06 +0000370 unsigned &MBBSize = BlockInfo[MBB->getNumber()].Size;
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000371
Matt Arsenault5b549712016-08-02 08:30:06 +0000372 // Insert a new conditional branch and a new unconditional branch.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000373 int RemovedSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000374 TII->reverseBranchCondition(Cond);
375 TII->removeBranch(*MBB, &RemovedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000376 MBBSize -= RemovedSize;
Matt Arsenault5b549712016-08-02 08:30:06 +0000377
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000378 int AddedSize = 0;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000379 TII->insertBranch(*MBB, &NextBB, TBB, Cond, DL, &AddedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000380 MBBSize += AddedSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000381
382 // Finally, keep the block offsets up to date.
383 adjustBlockOffsets(*MBB);
384 return true;
385}
386
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000387bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
388 MachineBasicBlock *MBB = MI.getParent();
389
390 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
391 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
392
393 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
394 int64_t SrcOffset = getInstrOffset(MI);
395
396 assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
397
398 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
399
400 MachineBasicBlock *BranchBB = MBB;
401
402 // If this was an expanded conditional branch, there is already a single
403 // unconditional branch in a block.
404 if (!MBB->empty()) {
405 BranchBB = createNewBlockAfter(*MBB);
406
407 // Add live outs.
408 for (const MachineBasicBlock *Succ : MBB->successors()) {
409 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
410 BranchBB->addLiveIn(LiveIn);
411 }
412
Matt Arsenault691efe02016-10-12 15:32:04 +0000413 BranchBB->sortUniqueLiveIns();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000414 BranchBB->addSuccessor(DestBB);
415 MBB->replaceSuccessor(DestBB, BranchBB);
416 }
417
418 DebugLoc DL = MI.getDebugLoc();
419 MI.eraseFromParent();
Matt Arsenault44deb792016-11-02 16:18:29 +0000420 BlockInfo[BranchBB->getNumber()].Size += TII->insertIndirectBranch(
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000421 *BranchBB, *DestBB, DL, DestOffset - SrcOffset, RS.get());
422
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000423 adjustBlockOffsets(*MBB);
424 return true;
425}
426
Matt Arsenault36919a42016-10-06 15:38:53 +0000427bool BranchRelaxation::relaxBranchInstructions() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000428 bool Changed = false;
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000429
Tim Northover3b0846e2014-05-24 12:50:23 +0000430 // Relaxing branches involves creating new basic blocks, so re-eval
431 // end() for termination.
Matt Arsenaultf1c39062016-06-16 21:21:49 +0000432 for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
433 MachineBasicBlock &MBB = *I;
Matt Arsenault36919a42016-10-06 15:38:53 +0000434
Matthias Braun18198302016-12-16 23:55:37 +0000435 // Empty block?
436 MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
437 if (Last == MBB.end())
Matt Arsenaultcb578f82016-11-01 18:34:00 +0000438 continue;
439
440 // Expand the unconditional branch first if necessary. If there is a
441 // conditional branch, this will end up changing the branch destination of
442 // it to be over the newly inserted indirect branch block, which may avoid
443 // the need to try expanding the conditional branch first, saving an extra
444 // jump.
445 if (Last->isUnconditionalBranch()) {
446 // Unconditional branch destination might be unanalyzable, assume these
447 // are OK.
448 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
449 if (!isBlockInRange(*Last, *DestBB)) {
450 fixupUnconditionalBranch(*Last);
451 ++NumUnconditionalRelaxed;
452 Changed = true;
453 }
454 }
455 }
456
457 // Loop over the conditional branches.
Matt Arsenault567631b2016-08-23 01:30:30 +0000458 MachineBasicBlock::iterator Next;
459 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
460 J != MBB.end(); J = Next) {
461 Next = std::next(J);
462 MachineInstr &MI = *J;
463
464 if (MI.isConditionalBranch()) {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000465 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
Matt Arsenault567631b2016-08-23 01:30:30 +0000466 if (!isBlockInRange(MI, *DestBB)) {
467 if (Next != MBB.end() && Next->isConditionalBranch()) {
468 // If there are multiple conditional branches, this isn't an
469 // analyzable block. Split later terminators into a new block so
470 // each one will be analyzable.
471
Matt Arsenault44deb792016-11-02 16:18:29 +0000472 splitBlockBeforeInstr(*Next, DestBB);
Matt Arsenault567631b2016-08-23 01:30:30 +0000473 } else {
474 fixupConditionalBranch(MI);
475 ++NumConditionalRelaxed;
476 }
477
478 Changed = true;
479
480 // This may have modified all of the terminators, so start over.
481 Next = MBB.getFirstTerminator();
482 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000483 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000484 }
485 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000486
Tim Northover3b0846e2014-05-24 12:50:23 +0000487 return Changed;
488}
489
Matt Arsenault36919a42016-10-06 15:38:53 +0000490bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000491 MF = &mf;
492
Matt Arsenault36919a42016-10-06 15:38:53 +0000493 DEBUG(dbgs() << "***** BranchRelaxation *****\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000494
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000495 const TargetSubtargetInfo &ST = MF->getSubtarget();
496 TII = ST.getInstrInfo();
497
Matthias Braun18198302016-12-16 23:55:37 +0000498 TRI = ST.getRegisterInfo();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000499 if (TRI->trackLivenessAfterRegAlloc(*MF))
500 RS.reset(new RegScavenger());
Tim Northover3b0846e2014-05-24 12:50:23 +0000501
502 // Renumber all of the machine basic blocks in the function, guaranteeing that
503 // the numbers agree with the position of the block in the function.
504 MF->RenumberBlocks();
505
506 // Do the initial scan of the function, building up information about the
507 // sizes of each block.
508 scanFunction();
509
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000510 DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
Tim Northover3b0846e2014-05-24 12:50:23 +0000511
512 bool MadeChange = false;
513 while (relaxBranchInstructions())
514 MadeChange = true;
515
516 // After a while, this might be made debug-only, but it is not expensive.
517 verify();
518
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000519 DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
Tim Northover3b0846e2014-05-24 12:50:23 +0000520
521 BlockInfo.clear();
522
523 return MadeChange;
524}