blob: 6042b0a96247a841ebfb5d96324ba13b6d1a03ad [file] [log] [blame]
Tim Northover3b0846e2014-05-24 12:50:23 +00001//===-- AArch64BranchRelaxation.cpp - AArch64 branch relaxation -----------===//
2//
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
10#include "AArch64.h"
11#include "AArch64InstrInfo.h"
12#include "AArch64MachineFunctionInfo.h"
Eric Christopherd9134482014-08-04 21:25:23 +000013#include "AArch64Subtarget.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000014#include "llvm/ADT/SmallVector.h"
Benjamin Kramer1f8930e2014-07-25 11:42:14 +000015#include "llvm/ADT/Statistic.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000016#include "llvm/CodeGen/MachineFunctionPass.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000017#include "llvm/Support/Debug.h"
18#include "llvm/Support/ErrorHandling.h"
19#include "llvm/Support/Format.h"
20#include "llvm/Support/raw_ostream.h"
Tim Northover3b0846e2014-05-24 12:50:23 +000021using namespace llvm;
22
23#define DEBUG_TYPE "aarch64-branch-relax"
24
Tim Northover3b0846e2014-05-24 12:50:23 +000025STATISTIC(NumSplit, "Number of basic blocks split");
Matt Arsenault567631b2016-08-23 01:30:30 +000026STATISTIC(NumConditionalRelaxed, "Number of conditional branches relaxed");
Tim Northover3b0846e2014-05-24 12:50:23 +000027
Chad Rosier1c814322015-08-05 16:12:10 +000028namespace llvm {
29void initializeAArch64BranchRelaxationPass(PassRegistry &);
30}
31
32#define AARCH64_BR_RELAX_NAME "AArch64 branch relaxation pass"
33
Tim Northover3b0846e2014-05-24 12:50:23 +000034namespace {
35class AArch64BranchRelaxation : public MachineFunctionPass {
36 /// BasicBlockInfo - Information about the offset and size of a single
37 /// basic block.
38 struct BasicBlockInfo {
39 /// Offset - Distance from the beginning of the function to the beginning
40 /// of this basic block.
41 ///
42 /// The offset is always aligned as required by the basic block.
43 unsigned Offset;
44
45 /// Size - Size of the basic block in bytes. If the block contains
46 /// inline assembly, this is a worst case estimate.
47 ///
48 /// The size does not include any alignment padding whether from the
49 /// beginning of the block, or from an aligned jump table at the end.
50 unsigned Size;
51
52 BasicBlockInfo() : Offset(0), Size(0) {}
53
54 /// Compute the offset immediately following this block. If LogAlign is
55 /// specified, return the offset the successor block will get if it has
56 /// this alignment.
57 unsigned postOffset(unsigned LogAlign = 0) const {
58 unsigned PO = Offset + Size;
59 unsigned Align = 1 << LogAlign;
60 return (PO + Align - 1) / Align * Align;
61 }
62 };
63
64 SmallVector<BasicBlockInfo, 16> BlockInfo;
65
66 MachineFunction *MF;
67 const AArch64InstrInfo *TII;
68
69 bool relaxBranchInstructions();
70 void scanFunction();
Matt Arsenaultf7065e12016-08-02 07:20:09 +000071 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr &MI);
Tim Northover3b0846e2014-05-24 12:50:23 +000072 void adjustBlockOffsets(MachineBasicBlock &MBB);
Matt Arsenaulte8da1452016-08-02 08:06:17 +000073 bool isBlockInRange(const MachineInstr &MI, const MachineBasicBlock &BB) const;
Matt Arsenault5b549712016-08-02 08:30:06 +000074
Matt Arsenaultf7065e12016-08-02 07:20:09 +000075 bool fixupConditionalBranch(MachineInstr &MI);
Tim Northover3b0846e2014-05-24 12:50:23 +000076 void computeBlockSize(const MachineBasicBlock &MBB);
Matt Arsenaulte8da1452016-08-02 08:06:17 +000077 unsigned getInstrOffset(const MachineInstr &MI) const;
Tim Northover3b0846e2014-05-24 12:50:23 +000078 void dumpBBs();
79 void verify();
80
81public:
82 static char ID;
Chad Rosier1c814322015-08-05 16:12:10 +000083 AArch64BranchRelaxation() : MachineFunctionPass(ID) {
84 initializeAArch64BranchRelaxationPass(*PassRegistry::getPassRegistry());
85 }
Tim Northover3b0846e2014-05-24 12:50:23 +000086
87 bool runOnMachineFunction(MachineFunction &MF) override;
88
Mehdi Amini117296c2016-10-01 02:56:57 +000089 StringRef getPassName() const override { return AARCH64_BR_RELAX_NAME; }
Tim Northover3b0846e2014-05-24 12:50:23 +000090};
91char AArch64BranchRelaxation::ID = 0;
Alexander Kornienkof00654e2015-06-23 09:49:53 +000092}
Tim Northover3b0846e2014-05-24 12:50:23 +000093
Chad Rosier1c814322015-08-05 16:12:10 +000094INITIALIZE_PASS(AArch64BranchRelaxation, "aarch64-branch-relax",
95 AARCH64_BR_RELAX_NAME, false, false)
96
Tim Northover3b0846e2014-05-24 12:50:23 +000097/// verify - check BBOffsets, BBSizes, alignment of islands
98void AArch64BranchRelaxation::verify() {
99#ifndef NDEBUG
100 unsigned PrevNum = MF->begin()->getNumber();
101 for (MachineBasicBlock &MBB : *MF) {
102 unsigned Align = MBB.getAlignment();
103 unsigned Num = MBB.getNumber();
104 assert(BlockInfo[Num].Offset % (1u << Align) == 0);
105 assert(!Num || BlockInfo[PrevNum].postOffset() <= BlockInfo[Num].Offset);
106 PrevNum = Num;
107 }
108#endif
109}
110
111/// print block size and offset information - debugging
112void AArch64BranchRelaxation::dumpBBs() {
113 for (auto &MBB : *MF) {
114 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
115 dbgs() << format("BB#%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
116 << format("size=%#x\n", BBI.Size);
117 }
118}
119
Tim Northover3b0846e2014-05-24 12:50:23 +0000120/// scanFunction - Do the initial scan of the function, building up
121/// information about each block.
122void AArch64BranchRelaxation::scanFunction() {
123 BlockInfo.clear();
124 BlockInfo.resize(MF->getNumBlockIDs());
125
126 // First thing, compute the size of all basic blocks, and see if the function
127 // has any inline assembly in it. If so, we have to be conservative about
128 // alignment assumptions, as we don't know for sure the size of any
129 // instructions in the inline assembly.
130 for (MachineBasicBlock &MBB : *MF)
131 computeBlockSize(MBB);
132
133 // Compute block offsets and known bits.
134 adjustBlockOffsets(*MF->begin());
135}
136
137/// computeBlockSize - Compute the size for MBB.
138/// This function updates BlockInfo directly.
139void AArch64BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) {
140 unsigned Size = 0;
141 for (const MachineInstr &MI : MBB)
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000142 Size += TII->getInstSizeInBytes(MI);
Tim Northover3b0846e2014-05-24 12:50:23 +0000143 BlockInfo[MBB.getNumber()].Size = Size;
144}
145
146/// getInstrOffset - Return the current offset of the specified machine
147/// instruction from the start of the function. This offset changes as stuff is
148/// moved around inside the function.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000149unsigned AArch64BranchRelaxation::getInstrOffset(const MachineInstr &MI) const {
150 const MachineBasicBlock *MBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000151
152 // The offset is composed of two things: the sum of the sizes of all MBB's
153 // before this instruction's block, and the offset from the start of the block
154 // it is in.
155 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
156
157 // Sum instructions before MI in MBB.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000158 for (MachineBasicBlock::const_iterator I = MBB->begin(); &*I != &MI; ++I) {
Tim Northover3b0846e2014-05-24 12:50:23 +0000159 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
Sjoerd Meijer89217f82016-07-28 16:32:22 +0000160 Offset += TII->getInstSizeInBytes(*I);
Tim Northover3b0846e2014-05-24 12:50:23 +0000161 }
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000162
Tim Northover3b0846e2014-05-24 12:50:23 +0000163 return Offset;
164}
165
166void AArch64BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
167 unsigned PrevNum = Start.getNumber();
168 for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
169 unsigned Num = MBB.getNumber();
170 if (!Num) // block zero is never changed from offset zero.
171 continue;
172 // Get the offset and known bits at the end of the layout predecessor.
173 // Include the alignment of the current block.
174 unsigned LogAlign = MBB.getAlignment();
175 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(LogAlign);
176 PrevNum = Num;
177 }
178}
179
180/// Split the basic block containing MI into two blocks, which are joined by
181/// an unconditional branch. Update data structures and renumber blocks to
182/// account for this change and returns the newly created block.
183/// NOTE: Successor list of the original BB is out of date after this function,
184/// and must be updated by the caller! Other transforms follow using this
185/// utility function, so no point updating now rather than waiting.
186MachineBasicBlock *
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000187AArch64BranchRelaxation::splitBlockBeforeInstr(MachineInstr &MI) {
188 MachineBasicBlock *OrigBB = MI.getParent();
Tim Northover3b0846e2014-05-24 12:50:23 +0000189
190 // Create a new MBB for the code after the OrigBB.
191 MachineBasicBlock *NewBB =
192 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
Duncan P. N. Exon Smithd3b9df02015-10-13 20:02:15 +0000193 MF->insert(++OrigBB->getIterator(), NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000194
195 // Splice the instructions starting with MI over to NewBB.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000196 NewBB->splice(NewBB->end(), OrigBB, MI.getIterator(), OrigBB->end());
Tim Northover3b0846e2014-05-24 12:50:23 +0000197
198 // Add an unconditional branch from OrigBB to NewBB.
199 // Note the new unconditional branch is not being recorded.
200 // There doesn't seem to be meaningful DebugInfo available; this doesn't
201 // correspond to anything in the source.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000202 TII->insertUnconditionalBranch(*OrigBB, NewBB, DebugLoc());
Tim Northover3b0846e2014-05-24 12:50:23 +0000203
204 // Insert an entry into BlockInfo to align it properly with the block numbers.
205 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
206
207 // Figure out how large the OrigBB is. As the first half of the original
208 // block, it cannot contain a tablejump. The size includes
209 // the new jump we added. (It should be possible to do this without
210 // recounting everything, but it's very confusing, and this is rarely
211 // executed.)
212 computeBlockSize(*OrigBB);
213
214 // Figure out how large the NewMBB is. As the second half of the original
215 // block, it may contain a tablejump.
216 computeBlockSize(*NewBB);
217
218 // All BBOffsets following these blocks must be modified.
219 adjustBlockOffsets(*OrigBB);
220
221 ++NumSplit;
222
223 return NewBB;
224}
225
226/// isBlockInRange - Returns true if the distance between specific MI and
227/// specific BB can fit in MI's displacement field.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000228bool AArch64BranchRelaxation::isBlockInRange(
229 const MachineInstr &MI, const MachineBasicBlock &DestBB) const {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000230 int64_t BrOffset = getInstrOffset(MI);
231 int64_t DestOffset = BlockInfo[DestBB.getNumber()].Offset;
Tim Northover3b0846e2014-05-24 12:50:23 +0000232
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000233 if (TII->isBranchOffsetInRange(MI.getOpcode(), DestOffset - BrOffset))
Tim Northover3b0846e2014-05-24 12:50:23 +0000234 return true;
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000235
236 DEBUG(
237 dbgs() << "Out of range branch to destination BB#" << DestBB.getNumber()
238 << " from BB#" << MI.getParent()->getNumber()
239 << " to " << DestOffset
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000240 << " offset " << DestOffset - BrOffset
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000241 << '\t' << MI
242 );
243
244 return false;
Tim Northover3b0846e2014-05-24 12:50:23 +0000245}
246
Tim Northover3b0846e2014-05-24 12:50:23 +0000247/// fixupConditionalBranch - Fix up a conditional branch whose destination is
248/// too far away to fit in its displacement field. It is converted to an inverse
249/// conditional branch + an unconditional branch to the destination.
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000250bool AArch64BranchRelaxation::fixupConditionalBranch(MachineInstr &MI) {
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000251 DebugLoc DL = MI.getDebugLoc();
252 MachineBasicBlock *MBB = MI.getParent();
253 MachineBasicBlock *TBB = nullptr, *FBB = nullptr;
254 SmallVector<MachineOperand, 4> Cond;
255
256 bool Fail = TII->analyzeBranch(*MBB, TBB, FBB, Cond);
257 assert(!Fail && "branches to be relaxed must be analyzable");
258 (void)Fail;
Tim Northover3b0846e2014-05-24 12:50:23 +0000259
260 // Add an unconditional branch to the destination and invert the branch
261 // condition to jump over it:
262 // tbz L1
263 // =>
264 // tbnz L2
265 // b L1
266 // L2:
267
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000268 if (FBB && isBlockInRange(MI, *FBB)) {
269 // Last MI in the BB is an unconditional branch. We can simply invert the
270 // condition and swap destinations:
271 // beq L1
272 // b L2
273 // =>
274 // bne L2
275 // b L1
276 DEBUG(dbgs() << " Invert condition and swap "
277 "its destination with " << MBB->back());
Tim Northover3b0846e2014-05-24 12:50:23 +0000278
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000279 TII->reverseBranchCondition(Cond);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000280 int OldSize = 0, NewSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000281 TII->removeBranch(*MBB, &OldSize);
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000282 TII->insertBranch(*MBB, FBB, TBB, Cond, DL, &NewSize);
Matt Arsenault5b549712016-08-02 08:30:06 +0000283
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000284 BlockInfo[MBB->getNumber()].Size += (NewSize - OldSize);
285 return true;
286 } else if (FBB) {
287 // We need to split the basic block here to obtain two long-range
288 // unconditional branches.
289 auto &NewBB = *MF->CreateMachineBasicBlock(MBB->getBasicBlock());
290 MF->insert(++MBB->getIterator(), &NewBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000291
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000292 // Insert an entry into BlockInfo to align it properly with the block
293 // numbers.
294 BlockInfo.insert(BlockInfo.begin() + NewBB.getNumber(), BasicBlockInfo());
Tim Northover3b0846e2014-05-24 12:50:23 +0000295
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000296 unsigned &NewBBSize = BlockInfo[NewBB.getNumber()].Size;
297 int NewBrSize;
298 TII->insertUnconditionalBranch(NewBB, FBB, DL, &NewBrSize);
299 NewBBSize += NewBrSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000300
301 // Update the successor lists according to the transformation to follow.
302 // Do it here since if there's no split, no update is needed.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000303 MBB->replaceSuccessor(FBB, &NewBB);
304 NewBB.addSuccessor(FBB);
Tim Northover3b0846e2014-05-24 12:50:23 +0000305 }
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000306
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000307 // We now have an appropriate fall-through block in place (either naturally or
308 // just created), so we can invert the condition.
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000309 MachineBasicBlock &NextBB = *std::next(MachineFunction::iterator(MBB));
Tim Northover3b0846e2014-05-24 12:50:23 +0000310
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000311 DEBUG(dbgs() << " Insert B to BB#" << TBB->getNumber()
Tim Northover3b0846e2014-05-24 12:50:23 +0000312 << ", invert condition and change dest. to BB#"
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000313 << NextBB.getNumber() << '\n');
Tim Northover3b0846e2014-05-24 12:50:23 +0000314
Matt Arsenault5b549712016-08-02 08:30:06 +0000315 unsigned &MBBSize = BlockInfo[MBB->getNumber()].Size;
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000316
Matt Arsenault5b549712016-08-02 08:30:06 +0000317 // Insert a new conditional branch and a new unconditional branch.
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000318 int RemovedSize = 0;
Matt Arsenault1b9fc8e2016-09-14 20:43:16 +0000319 TII->reverseBranchCondition(Cond);
320 TII->removeBranch(*MBB, &RemovedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000321 MBBSize -= RemovedSize;
Matt Arsenault5b549712016-08-02 08:30:06 +0000322
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000323 int AddedSize = 0;
Matt Arsenaulte8e0f5c2016-09-14 17:24:15 +0000324 TII->insertBranch(*MBB, &NextBB, TBB, Cond, DL, &AddedSize);
Matt Arsenaulta2b036e2016-09-14 17:23:48 +0000325 MBBSize += AddedSize;
Tim Northover3b0846e2014-05-24 12:50:23 +0000326
327 // Finally, keep the block offsets up to date.
328 adjustBlockOffsets(*MBB);
329 return true;
330}
331
332bool AArch64BranchRelaxation::relaxBranchInstructions() {
333 bool Changed = false;
334 // Relaxing branches involves creating new basic blocks, so re-eval
335 // end() for termination.
Matt Arsenaultf1c39062016-06-16 21:21:49 +0000336 for (MachineFunction::iterator I = MF->begin(); I != MF->end(); ++I) {
337 MachineBasicBlock &MBB = *I;
Matt Arsenaultf7065e12016-08-02 07:20:09 +0000338 MachineBasicBlock::iterator J = MBB.getFirstTerminator();
339 if (J == MBB.end())
340 continue;
341
Matt Arsenault567631b2016-08-23 01:30:30 +0000342 MachineBasicBlock::iterator Next;
343 for (MachineBasicBlock::iterator J = MBB.getFirstTerminator();
344 J != MBB.end(); J = Next) {
345 Next = std::next(J);
346 MachineInstr &MI = *J;
347
348 if (MI.isConditionalBranch()) {
Matt Arsenault0a3ea892016-10-06 15:38:09 +0000349 MachineBasicBlock *DestBB = TII->getBranchDestBlock(MI);
Matt Arsenault567631b2016-08-23 01:30:30 +0000350 if (!isBlockInRange(MI, *DestBB)) {
351 if (Next != MBB.end() && Next->isConditionalBranch()) {
352 // If there are multiple conditional branches, this isn't an
353 // analyzable block. Split later terminators into a new block so
354 // each one will be analyzable.
355
356 MachineBasicBlock *NewBB = splitBlockBeforeInstr(*Next);
357 NewBB->transferSuccessors(&MBB);
358 MBB.addSuccessor(NewBB);
359 MBB.addSuccessor(DestBB);
360
361 // Cleanup potential unconditional branch to successor block.
362 NewBB->updateTerminator();
363 MBB.updateTerminator();
364 } else {
365 fixupConditionalBranch(MI);
366 ++NumConditionalRelaxed;
367 }
368
369 Changed = true;
370
371 // This may have modified all of the terminators, so start over.
372 Next = MBB.getFirstTerminator();
373 }
374
375 }
Tim Northover3b0846e2014-05-24 12:50:23 +0000376 }
377 }
Matt Arsenault567631b2016-08-23 01:30:30 +0000378
Tim Northover3b0846e2014-05-24 12:50:23 +0000379 return Changed;
380}
381
382bool AArch64BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
383 MF = &mf;
384
Tim Northover3b0846e2014-05-24 12:50:23 +0000385 DEBUG(dbgs() << "***** AArch64BranchRelaxation *****\n");
386
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000387 TII = MF->getSubtarget<AArch64Subtarget>().getInstrInfo();
Tim Northover3b0846e2014-05-24 12:50:23 +0000388
389 // Renumber all of the machine basic blocks in the function, guaranteeing that
390 // the numbers agree with the position of the block in the function.
391 MF->RenumberBlocks();
392
393 // Do the initial scan of the function, building up information about the
394 // sizes of each block.
395 scanFunction();
396
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000397 DEBUG(dbgs() << " Basic blocks before relaxation\n"; dumpBBs(););
Tim Northover3b0846e2014-05-24 12:50:23 +0000398
399 bool MadeChange = false;
400 while (relaxBranchInstructions())
401 MadeChange = true;
402
403 // After a while, this might be made debug-only, but it is not expensive.
404 verify();
405
Matt Arsenaulte8da1452016-08-02 08:06:17 +0000406 DEBUG(dbgs() << " Basic blocks after relaxation\n\n"; dumpBBs());
Tim Northover3b0846e2014-05-24 12:50:23 +0000407
408 BlockInfo.clear();
409
410 return MadeChange;
411}
412
Chad Rosier59bcbba2016-03-25 14:37:43 +0000413/// Returns an instance of the AArch64 Branch Relaxation pass.
Tim Northover3b0846e2014-05-24 12:50:23 +0000414FunctionPass *llvm::createAArch64BranchRelaxation() {
415 return new AArch64BranchRelaxation();
416}