blob: 8b27570a17f47ce9e3721793562c5557839fab24 [file] [log] [blame]
Matt Arsenault36919a42016-10-06 15:38:53 +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
Matt Arsenault36919a42016-10-06 15:38:53 +000010#include "llvm/CodeGen/Passes.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000011#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000012#include "llvm/ADT/Statistic.h"
Matthias Braun18198302016-12-16 23:55:37 +000013#include "llvm/CodeGen/LivePhysRegs.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000014#include "llvm/CodeGen/MachineFunctionPass.h"
Matt Arsenault6bc43d82016-10-06 16:20:41 +000015#include "llvm/CodeGen/RegisterScavenging.h"
Matt Arsenault36919a42016-10-06 15:38:53 +000016#include "llvm/Target/TargetInstrInfo.h"
17#include "llvm/Target/TargetSubtargetInfo.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000018#include "llvm/Support/Debug.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000019#include "llvm/Support/Format.h"
20#include "llvm/Support/raw_ostream.h"
Matt Arsenault36919a42016-10-06 15:38:53 +000021
Tim Northover3b0846e2014-05-24 12:50:23 +000022using namespace llvm;
23
Matt Arsenault36919a42016-10-06 15:38:53 +000024#define DEBUG_TYPE "branch-relaxation"
Tim Northover3b0846e2014-05-24 12:50:23 +000025
Tim Northover3b0846e2014-05-24 12:50:23 +000026STATISTIC(NumSplit, "Number of basic blocks split");
Matt Arsenault567631b2016-08-23 01:30:30 +000027STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
Matt Arsenault6bc43d82016-10-06 16:20:41 +000028STATISTIC(NumUnconditionalRelaxed, "Number of unconditional branches relaxed");
Tim Northover3b0846e2014-05-24 12:50:23 +000029
Matt Arsenault36919a42016-10-06 15:38:53 +000030#define BRANCH_RELAX_NAME "Branch relaxation pass"
Chad Rosier1c814322015-08-05 16:12:10 +000031
Tim Northover3b0846e2014-05-24 12:50:23 +000032namespace {
Matt Arsenault36919a42016-10-06 15:38:53 +000033class BranchRelaxation : public MachineFunctionPass {
Tim Northover3b0846e2014-05-24 12:50:23 +000034 /// BasicBlockInfo - Information about the offset and size of a single
35 /// basic block.
36 struct BasicBlockInfo {
37 /// Offset - Distance from the beginning of the function to the beginning
38 /// of this basic block.
39 ///
40 /// The offset is always aligned as required by the basic block.
41 unsigned Offset;
42
43 /// Size - Size of the basic block in bytes. If the block contains
44 /// inline assembly, this is a worst case estimate.
45 ///
46 /// The size does not include any alignment padding whether from the
47 /// beginning of the block, or from an aligned jump table at the end.
48 unsigned Size;
49
50 BasicBlockInfo() : Offset(0), Size(0) {}
51
Matt Arsenaultef5bba02016-10-06 16:00:58 +000052 /// Compute the offset immediately following this block. \p MBB is the next
53 /// block.
54 unsigned postOffset(const MachineBasicBlock &MBB) const {
Tim Northover3b0846e2014-05-24 12:50:23 +000055 unsigned PO = Offset + Size;
Matt Arsenaultef5bba02016-10-06 16:00:58 +000056 unsigned Align = MBB.getAlignment();
57 if (Align == 0)
58 return PO;
59
60 unsigned AlignAmt = 1 << Align;
61 unsigned ParentAlign = MBB.getParent()->getAlignment();
62 if (Align <= ParentAlign)
63 return PO + OffsetToAlignment(PO, AlignAmt);
64
65 // The alignment of this MBB is larger than the function's alignment, so we
66 // can't tell whether or not it will insert nops. Assume that it will.
67 return PO + AlignAmt + OffsetToAlignment(PO, AlignAmt);
Tim Northover3b0846e2014-05-24 12:50:23 +000068 }
69 };
70
71 SmallVector<BasicBlockInfo, 16> BlockInfo;
Matt Arsenault6bc43d82016-10-06 16:20:41 +000072 std::unique_ptr<RegScavenger> RS;
Matthias Braun18198302016-12-16 23:55:37 +000073 LivePhysRegs LiveRegs;
Tim Northover3b0846e2014-05-24 12:50:23 +000074
75 MachineFunction *MF;
Matthias Braun18198302016-12-16 23:55:37 +000076 const TargetRegisterInfo *TRI;
Matt Arsenault36919a42016-10-06 15:38:53 +000077 const TargetInstrInfo *TII;
Tim Northover3b0846e2014-05-24 12:50:23 +000078
79 bool relaxBranchInstructions();
80 void scanFunction();
Matt Arsenault6bc43d82016-10-06 16:20:41 +000081
82 MachineBasicBlock *createNewBlockAfter(MachineBasicBlock &BB);
83
Matt Arsenault44deb792016-11-02 16:18:29 +000084 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI,
85 MachineBasicBlock *DestBB);
Tim Northover3b0846e2014-05-24 12:50:23 +000086 void adjustBlockOffsets(MachineBasicBlock &MBB);
Matt Arsenaulte8da1452016-08-02 08:06:17 +000087 bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
Matt Arsenault5b549712016-08-02 08:30:06 +000088
Matt Arsenaultf7065e12016-08-02 07:20:09 +000089 bool fixupConditionalBranch(MachineInstr &MI);
Matt Arsenault6bc43d82016-10-06 16:20:41 +000090 bool fixupUnconditionalBranch(MachineInstr &MI);
Matt Arsenault36919a42016-10-06 15:38:53 +000091 uint64_t computeBlockSize(const MachineBasicBlock &MBB) const;
Matt Arsenaulte8da1452016-08-02 08:06:17 +000092 unsigned getInstrOffset(const MachineInstr &MI) const;
Tim Northover3b0846e2014-05-24 12:50:23 +000093 void dumpBBs();
94 void verify();
95
96public:
97 static char ID;
Matt Arsenault36919a42016-10-06 15:38:53 +000098 BranchRelaxation() : MachineFunctionPass(ID) { }
Tim Northover3b0846e2014-05-24 12:50:23 +000099
100 bool runOnMachineFunction(MachineFunction &MF) override;
101
Matt Arsenault36919a42016-10-06 15:38:53 +0000102 StringRef getPassName() const override {
103 return BRANCH_RELAX_NAME;
104 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000105};
Matt Arsenault36919a42016-10-06 15:38:53 +0000106
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000107}
Tim Northover3b0846e2014-05-24 12:50:23 +0000108
Matt Arsenault36919a42016-10-06 15:38:53 +0000109char BranchRelaxation::ID = 0;
110char &llvm::BranchRelaxationPassID = BranchRelaxation::ID;
111
112INITIALIZE_PASS(BranchRelaxation, DEBUG_TYPE, BRANCH_RELAX_NAME, false, false)
Chad Rosier1c814322015-08-05 16:12:10 +0000113
Tim Northover3b0846e2014-05-24 12:50:23 +0000114/// verify - check BBOffsets, BBSizes, alignment of islands
Matt Arsenault36919a42016-10-06 15:38:53 +0000115void BranchRelaxation::verify() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000116#ifndef NDEBUG
117 unsigned PrevNum = MF->begin()->getNumber();
118 for (MachineBasicBlock &MBB : *MF) {
119 unsigned Align = MBB.getAlignment();
120 unsigned Num = MBB.getNumber();
121 assert(BlockInfo[Num].Offset % (1u << Align) == 0);
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000122 assert(!Num || BlockInfo[PrevNum].postOffset(MBB) <= BlockInfo[Num].Offset);
Matt Arsenault44deb792016-11-02 16:18:29 +0000123 assert(BlockInfo[Num].Size == computeBlockSize(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000124 PrevNum = Num;
125 }
126#endif
127}
128
129/// print block size and offset information - debugging
Matt Arsenault36919a42016-10-06 15:38:53 +0000130void BranchRelaxation::dumpBBs() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000131 for (auto &MBB : *MF) {
132 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
133 dbgs() << format("BB#%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
134 << format("size=%#x\n", BBI.Size);
135 }
136}
137
Tim Northover3b0846e2014-05-24 12:50:23 +0000138/// scanFunction - Do the initial scan of the function, building up
139/// information about each block.
Matt Arsenault36919a42016-10-06 15:38:53 +0000140void BranchRelaxation::scanFunction() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000141 BlockInfo.clear();
142 BlockInfo.resize(MF->getNumBlockIDs());
143
144 // First thing, compute the size of all basic blocks, and see if the function
145 // has any inline assembly in it. If so, we have to be conservative about
146 // alignment assumptions, as we don't know for sure the size of any
147 // instructions in the inline assembly.
148 for (MachineBasicBlock &MBB : *MF)
Matt Arsenault36919a42016-10-06 15:38:53 +0000149 BlockInfo[MBB.getNumber()].Size = computeBlockSize(MBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000150
151 // Compute block offsets and known bits.
152 adjustBlockOffsets(*MF->begin());
153}
154
155/// computeBlockSize - Compute the size for MBB.
Matt Arsenault36919a42016-10-06 15:38:53 +0000156uint64_t BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) const {
157 uint64_t Size = 0;
Tim Northover3b0846e2014-05-24 12:50:23 +0000158 for (const MachineInstr &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000159 Size += TII->getInstSizeInBytes(MI);
Matt Arsenault36919a42016-10-06 15:38:53 +0000160 return Size;
Tim Northover3b0846e2014-05-24 12:50:23 +0000161}
162
163/// getInstrOffset - Return the current offset of the specified machine
164/// instruction from the start of the function. This offset changes as stuff is
165/// moved around inside the function.
Matt Arsenault36919a42016-10-06 15:38:53 +0000166unsigned BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000167 const MachineBasicBlock *MBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000168
169 // The offset is composed of two things: the sum of the sizes of all MBB's
170 // before this instruction's block, and the offset from the start of the block
171 // it is in.
172 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
173
174 // Sum instructions before MI in MBB.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000175 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000176 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000177 Offset += TII->getInstSizeInBytes(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000178 }
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000179
Tim Northover3b0846e2014-05-24 12:50:23 +0000180 return Offset;
181}
182
Matt Arsenault36919a42016-10-06 15:38:53 +0000183void BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000184 unsigned PrevNum = Start.getNumber();
185 for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
186 unsigned Num = MBB.getNumber();
187 if (!Num) // block zero is never changed from offset zero.
188 continue;
189 // Get the offset and known bits at the end of the layout predecessor.
190 // Include the alignment of the current block.
Matt Arsenaultef5bba02016-10-06 16:00:58 +0000191 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(MBB);
192
Tim Northover3b0846e2014-05-24 12:50:23 +0000193 PrevNum = Num;
194 }
195}
196
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000197 /// Insert a new empty basic block and insert it after \BB
198MachineBasicBlock *BranchRelaxation::createNewBlockAfter(MachineBasicBlock &BB) {
199 // Create a new MBB for the code after the OrigBB.
200 MachineBasicBlock *NewBB =
201 MF->CreateMachineBasicBlock(BB.getBasicBlock());
202 MF->insert(++BB.getIterator(), NewBB);
203
204 // Insert an entry into BlockInfo to align it properly with the block numbers.
205 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
206
207 return NewBB;
208}
209
Tim Northover3b0846e2014-05-24 12:50:23 +0000210/// Split the basic block containing MI into two blocks, which are joined by
211/// an unconditional branch. Update data structures and renumber blocks to
212/// account for this change and returns the newly created block.
Matt Arsenault44deb792016-11-02 16:18:29 +0000213MachineBasicBlock *BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI,
214 MachineBasicBlock *DestBB) {
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000215 MachineBasicBlock *OrigBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000216
217 // Create a new MBB for the code after the OrigBB.
218 MachineBasicBlock *NewBB =
219 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000220 MF->insert(++OrigBB->getIterator(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000221
222 // Splice the instructions starting with MI over to NewBB.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000223 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
Tim Northover3b0846e2014-05-24 12:50:23 +0000224
225 // Add an unconditional branch from OrigBB to NewBB.
226 // Note the new unconditional branch is not being recorded.
227 // There doesn't seem to be meaningful DebugInfo available; this doesn't
228 // correspond to anything in the source.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000229 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
Tim Northover3b0846e2014-05-24 12:50:23 +0000230
231 // Insert an entry into BlockInfo to align it properly with the block numbers.
232 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
233
Matt Arsenault44deb792016-11-02 16:18:29 +0000234
235 NewBB->transferSuccessors(OrigBB);
236 OrigBB->addSuccessor(NewBB);
237 OrigBB->addSuccessor(DestBB);
238
239 // Cleanup potential unconditional branch to successor block.
240 // Note that updateTerminator may change the size of the blocks.
241 NewBB->updateTerminator();
242 OrigBB->updateTerminator();
243
Tim Northover3b0846e2014-05-24 12:50:23 +0000244 // Figure out how large the OrigBB is. As the first half of the original
245 // block, it cannot contain a tablejump. The size includes
246 // the new jump we added. (It should be possible to do this without
247 // recounting everything, but it's very confusing, and this is rarely
248 // executed.)
Matt Arsenault36919a42016-10-06 15:38:53 +0000249 BlockInfo[OrigBB->getNumber()].Size = computeBlockSize(*OrigBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000250
Matt Arsenault36919a42016-10-06 15:38:53 +0000251 // Figure out how large the NewMBB is. As the second half of the original
Tim Northover3b0846e2014-05-24 12:50:23 +0000252 // block, it may contain a tablejump.
Matt Arsenault36919a42016-10-06 15:38:53 +0000253 BlockInfo[NewBB->getNumber()].Size = computeBlockSize(*NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000254
255 // All BBOffsets following these blocks must be modified.
256 adjustBlockOffsets(*OrigBB);
257
Matthias Braun18198302016-12-16 23:55:37 +0000258 // Need to fix live-in lists if we track liveness.
259 if (TRI->trackLivenessAfterRegAlloc(*MF))
260 computeLiveIns(LiveRegs, *TRI, *NewBB);
261
Tim Northover3b0846e2014-05-24 12:50:23 +0000262 ++NumSplit;
263
264 return NewBB;
265}
266
267/// isBlockInRange - Returns true if the distance between specific MI and
268/// specific BB can fit in MI's displacement field.
Matt Arsenault36919a42016-10-06 15:38:53 +0000269bool BranchRelaxation::isBlockInRange(
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000270 const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000271 int64_t BrOffset = getInstrOffset(MI);
272 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000273
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000274 if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +0000275 return true;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000276
277 DEBUG(
278 dbgs() << "Out of range branch to destination BB#" << DestBB.getNumber()
279 << " from BB#" << MI.getParent()->getNumber()
280 << " to " << DestOffset
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000281 << " offset " << DestOffset - BrOffset
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000282 << '\t' << MI
283 );
284
285 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000286}
287
Tim Northover3b0846e2014-05-24 12:50:23 +0000288/// fixupConditionalBranch - Fix up a conditional branch whose destination is
289/// too far away to fit in its displacement field. It is converted to an inverse
290/// conditional branch + an unconditional branch to the destination.
Matt Arsenault36919a42016-10-06 15:38:53 +0000291bool BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000292 DebugLoc DL = MI.getDebugLoc();
293 MachineBasicBlock *MBB = MI.getParent();
294 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
295 SmallVector<MachineOperand, 4> Cond;
296
297 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
298 assert(!Fail && "branches to be relaxed must be analyzable");
299 (void)Fail;
Tim Northover3b0846e2014-05-24 12:50:23 +0000300
301 // Add an unconditional branch to the destination and invert the branch
302 // condition to jump over it:
303 // tbz L1
304 // =>
305 // tbnz L2
306 // b L1
307 // L2:
308
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000309 if (FBB && isBlockInRange(MI, *FBB)) {
310 // Last MI in the BB is an unconditional branch. We can simply invert the
311 // condition and swap destinations:
312 // beq L1
313 // b L2
314 // =>
315 // bne L2
316 // b L1
317 DEBUG(dbgs() << " Invert condition and swap "
318 "its destination with " << MBB->back());
Tim Northover3b0846e2014-05-24 12:50:23 +0000319
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000320 TII->reverseBranchCondition(Cond);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000321 int OldSize = 0, NewSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000322 TII->removeBranch(*MBB, &OldSize);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000323 TII->insertBranch(*MBB, FBB, TBB, Cond, DL, &NewSize);
Matt Arsenault5b549712016-08-02 08:30:06 +0000324
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000325 BlockInfo[MBB->getNumber()].Size += (NewSize - OldSize);
326 return true;
327 } else if (FBB) {
328 // We need to split the basic block here to obtain two long-range
329 // unconditional branches.
330 auto &NewBB = *MF->CreateMachineBasicBlock(MBB->getBasicBlock());
331 MF->insert(++MBB->getIterator(), &NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000332
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000333 // Insert an entry into BlockInfo to align it properly with the block
334 // numbers.
335 BlockInfo.insert(BlockInfo.begin() + NewBB.getNumber(), BasicBlockInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000336
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000337 unsigned &NewBBSize = BlockInfo[NewBB.getNumber()].Size;
338 int NewBrSize;
339 TII->insertUnconditionalBranch(NewBB, FBB, DL, &NewBrSize);
340 NewBBSize += NewBrSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000341
342 // Update the successor lists according to the transformation to follow.
343 // Do it here since if there's no split, no update is needed.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000344 MBB->replaceSuccessor(FBB, &NewBB);
345 NewBB.addSuccessor(FBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000346 }
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000347
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000348 // We now have an appropriate fall-through block in place (either naturally or
349 // just created), so we can invert the condition.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000350 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000351
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000352 DEBUG(dbgs() << " Insert B to BB#" << TBB->getNumber()
Tim Northover3b0846e2014-05-24 12:50:23 +0000353 << ", invert condition and change dest. to BB#"
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000354 << NextBB.getNumber() << '\n');
Tim Northover3b0846e2014-05-24 12:50:23 +0000355
Matt Arsenault5b549712016-08-02 08:30:06 +0000356 unsigned &MBBSize = BlockInfo[MBB->getNumber()].Size;
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000357
Matt Arsenault5b549712016-08-02 08:30:06 +0000358 // Insert a new conditional branch and a new unconditional branch.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000359 int RemovedSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000360 TII->reverseBranchCondition(Cond);
361 TII->removeBranch(*MBB, &RemovedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000362 MBBSize -= RemovedSize;
Matt Arsenault5b549712016-08-02 08:30:06 +0000363
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000364 int AddedSize = 0;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000365 TII->insertBranch(*MBB, &NextBB, TBB, Cond, DL, &AddedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000366 MBBSize += AddedSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000367
368 // Finally, keep the block offsets up to date.
369 adjustBlockOffsets(*MBB);
370 return true;
371}
372
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000373bool BranchRelaxation::fixupUnconditionalBranch(MachineInstr &MI) {
374 MachineBasicBlock *MBB = MI.getParent();
375
376 unsigned OldBrSize = TII->getInstSizeInBytes(MI);
377 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
378
379 int64_t DestOffset = BlockInfo[DestBB->getNumber()].Offset;
380 int64_t SrcOffset = getInstrOffset(MI);
381
382 assert(!TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - SrcOffset));
383
384 BlockInfo[MBB->getNumber()].Size -= OldBrSize;
385
386 MachineBasicBlock *BranchBB = MBB;
387
388 // If this was an expanded conditional branch, there is already a single
389 // unconditional branch in a block.
390 if (!MBB->empty()) {
391 BranchBB = createNewBlockAfter(*MBB);
392
393 // Add live outs.
394 for (const MachineBasicBlock *Succ : MBB->successors()) {
395 for (const MachineBasicBlock::RegisterMaskPair &LiveIn : Succ->liveins())
396 BranchBB->addLiveIn(LiveIn);
397 }
398
Matt Arsenault691efe02016-10-12 15:32:04 +0000399 BranchBB->sortUniqueLiveIns();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000400 BranchBB->addSuccessor(DestBB);
401 MBB->replaceSuccessor(DestBB, BranchBB);
402 }
403
404 DebugLoc DL = MI.getDebugLoc();
405 MI.eraseFromParent();
Matt Arsenault44deb792016-11-02 16:18:29 +0000406 BlockInfo[BranchBB->getNumber()].Size += TII->insertIndirectBranch(
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000407 *BranchBB, *DestBB, DL, DestOffset - SrcOffset, RS.get());
408
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000409 adjustBlockOffsets(*MBB);
410 return true;
411}
412
Matt Arsenault36919a42016-10-06 15:38:53 +0000413bool BranchRelaxation::relaxBranchInstructions() {
Tim Northover3b0846e2014-05-24 12:50:23 +0000414 bool Changed = false;
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000415
Tim Northover3b0846e2014-05-24 12:50:23 +0000416 // Relaxing branches involves creating new basic blocks, so re-eval
417 // end() for termination.
Matt Arsenaultf1c39062016-06-16 21:21:49 +0000418 for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
419 MachineBasicBlock &MBB = *I;
Matt Arsenault36919a42016-10-06 15:38:53 +0000420
Matthias Braun18198302016-12-16 23:55:37 +0000421 // Empty block?
422 MachineBasicBlock::iterator Last = MBB.getLastNonDebugInstr();
423 if (Last == MBB.end())
Matt Arsenaultcb578f82016-11-01 18:34:00 +0000424 continue;
425
426 // Expand the unconditional branch first if necessary. If there is a
427 // conditional branch, this will end up changing the branch destination of
428 // it to be over the newly inserted indirect branch block, which may avoid
429 // the need to try expanding the conditional branch first, saving an extra
430 // jump.
431 if (Last->isUnconditionalBranch()) {
432 // Unconditional branch destination might be unanalyzable, assume these
433 // are OK.
434 if (MachineBasicBlock *DestBB = TII->getBranchDestBlock(*Last)) {
435 if (!isBlockInRange(*Last, *DestBB)) {
436 fixupUnconditionalBranch(*Last);
437 ++NumUnconditionalRelaxed;
438 Changed = true;
439 }
440 }
441 }
442
443 // Loop over the conditional branches.
Matt Arsenault567631b2016-08-23 01:30:30 +0000444 MachineBasicBlock::iterator Next;
445 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
446 J != MBB.end(); J = Next) {
447 Next = std::next(J);
448 MachineInstr &MI = *J;
449
450 if (MI.isConditionalBranch()) {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000451 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
Matt Arsenault567631b2016-08-23 01:30:30 +0000452 if (!isBlockInRange(MI, *DestBB)) {
453 if (Next != MBB.end() && Next->isConditionalBranch()) {
454 // If there are multiple conditional branches, this isn't an
455 // analyzable block. Split later terminators into a new block so
456 // each one will be analyzable.
457
Matt Arsenault44deb792016-11-02 16:18:29 +0000458 splitBlockBeforeInstr(*Next, DestBB);
Matt Arsenault567631b2016-08-23 01:30:30 +0000459 } else {
460 fixupConditionalBranch(MI);
461 ++NumConditionalRelaxed;
462 }
463
464 Changed = true;
465
466 // This may have modified all of the terminators, so start over.
467 Next = MBB.getFirstTerminator();
468 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000469 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000470 }
471 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000472
Tim Northover3b0846e2014-05-24 12:50:23 +0000473 return Changed;
474}
475
Matt Arsenault36919a42016-10-06 15:38:53 +0000476bool BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000477 MF = &mf;
478
Matt Arsenault36919a42016-10-06 15:38:53 +0000479 DEBUG(dbgs() << "***** BranchRelaxation *****\n");
Tim Northover3b0846e2014-05-24 12:50:23 +0000480
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000481 const TargetSubtargetInfo &ST = MF->getSubtarget();
482 TII = ST.getInstrInfo();
483
Matthias Braun18198302016-12-16 23:55:37 +0000484 TRI = ST.getRegisterInfo();
Matt Arsenault6bc43d82016-10-06 16:20:41 +0000485 if (TRI->trackLivenessAfterRegAlloc(*MF))
486 RS.reset(new RegScavenger());
Tim Northover3b0846e2014-05-24 12:50:23 +0000487
488 // Renumber all of the machine basic blocks in the function, guaranteeing that
489 // the numbers agree with the position of the block in the function.
490 MF->RenumberBlocks();
491
492 // Do the initial scan of the function, building up information about the
493 // sizes of each block.
494 scanFunction();
495
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000496 DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
Tim Northover3b0846e2014-05-24 12:50:23 +0000497
498 bool MadeChange = false;
499 while (relaxBranchInstructions())
500 MadeChange = true;
501
502 // After a while, this might be made debug-only, but it is not expensive.
503 verify();
504
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000505 DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
Tim Northover3b0846e2014-05-24 12:50:23 +0000506
507 BlockInfo.clear();
508
509 return MadeChange;
510}