1 //===-- ARM64BranchRelaxation.cpp - ARM64 branch relaxation ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 //===----------------------------------------------------------------------===//
13 #include "ARM64InstrInfo.h"
14 #include "ARM64MachineFunctionInfo.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/CodeGen/MachineFunctionPass.h"
17 #include "llvm/CodeGen/MachineInstrBuilder.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/ErrorHandling.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Support/CommandLine.h"
26 #define DEBUG_TYPE "arm64-branch-relax"
29 BranchRelaxation("arm64-branch-relax", cl::Hidden, cl::init(true),
30 cl::desc("Relax out of range conditional branches"));
32 static cl::opt<unsigned>
33 TBZDisplacementBits("arm64-tbz-offset-bits", cl::Hidden, cl::init(14),
34 cl::desc("Restrict range of TB[N]Z instructions (DEBUG)"));
36 static cl::opt<unsigned>
37 CBZDisplacementBits("arm64-cbz-offset-bits", cl::Hidden, cl::init(19),
38 cl::desc("Restrict range of CB[N]Z instructions (DEBUG)"));
40 static cl::opt<unsigned>
41 BCCDisplacementBits("arm64-bcc-offset-bits", cl::Hidden, cl::init(19),
42 cl::desc("Restrict range of Bcc instructions (DEBUG)"));
44 STATISTIC(NumSplit, "Number of basic blocks split");
45 STATISTIC(NumRelaxed, "Number of conditional branches relaxed");
48 class ARM64BranchRelaxation : public MachineFunctionPass {
49 /// BasicBlockInfo - Information about the offset and size of a single
51 struct BasicBlockInfo {
52 /// Offset - Distance from the beginning of the function to the beginning
53 /// of this basic block.
55 /// The offset is always aligned as required by the basic block.
58 /// Size - Size of the basic block in bytes. If the block contains
59 /// inline assembly, this is a worst case estimate.
61 /// The size does not include any alignment padding whether from the
62 /// beginning of the block, or from an aligned jump table at the end.
65 BasicBlockInfo() : Offset(0), Size(0) {}
67 /// Compute the offset immediately following this block. If LogAlign is
68 /// specified, return the offset the successor block will get if it has
70 unsigned postOffset(unsigned LogAlign = 0) const {
71 unsigned PO = Offset + Size;
72 unsigned Align = 1 << LogAlign;
73 return (PO + Align - 1) / Align * Align;
77 SmallVector<BasicBlockInfo, 16> BlockInfo;
80 const ARM64InstrInfo *TII;
82 bool relaxBranchInstructions();
84 MachineBasicBlock *splitBlockBeforeInstr(MachineInstr *MI);
85 void adjustBlockOffsets(MachineBasicBlock &MBB);
86 bool isBlockInRange(MachineInstr *MI, MachineBasicBlock *BB, unsigned Disp);
87 bool fixupConditionalBranch(MachineInstr *MI);
88 void computeBlockSize(const MachineBasicBlock &MBB);
89 unsigned getInstrOffset(MachineInstr *MI) const;
95 ARM64BranchRelaxation() : MachineFunctionPass(ID) {}
97 virtual bool runOnMachineFunction(MachineFunction &MF);
99 virtual const char *getPassName() const {
100 return "ARM64 branch relaxation pass";
103 char ARM64BranchRelaxation::ID = 0;
106 /// verify - check BBOffsets, BBSizes, alignment of islands
107 void ARM64BranchRelaxation::verify() {
109 unsigned PrevNum = MF->begin()->getNumber();
110 for (MachineBasicBlock &MBB : *MF) {
111 unsigned Align = MBB.getAlignment();
112 unsigned Num = MBB.getNumber();
113 assert(BlockInfo[Num].Offset % (1u << Align) == 0);
114 assert(!Num || BlockInfo[PrevNum].postOffset() <= BlockInfo[Num].Offset);
120 /// print block size and offset information - debugging
121 void ARM64BranchRelaxation::dumpBBs() {
122 for (auto &MBB : *MF) {
123 const BasicBlockInfo &BBI = BlockInfo[MBB.getNumber()];
124 dbgs() << format("BB#%u\toffset=%08x\t", MBB.getNumber(), BBI.Offset)
125 << format("size=%#x\n", BBI.Size);
129 /// BBHasFallthrough - Return true if the specified basic block can fallthrough
130 /// into the block immediately after it.
131 static bool BBHasFallthrough(MachineBasicBlock *MBB) {
132 // Get the next machine basic block in the function.
133 MachineFunction::iterator MBBI = MBB;
134 // Can't fall off end of function.
135 MachineBasicBlock *NextBB = std::next(MBBI);
136 if (NextBB == MBB->getParent()->end())
139 for (MachineBasicBlock *S : MBB->successors())
146 /// scanFunction - Do the initial scan of the function, building up
147 /// information about each block.
148 void ARM64BranchRelaxation::scanFunction() {
150 BlockInfo.resize(MF->getNumBlockIDs());
152 // First thing, compute the size of all basic blocks, and see if the function
153 // has any inline assembly in it. If so, we have to be conservative about
154 // alignment assumptions, as we don't know for sure the size of any
155 // instructions in the inline assembly.
156 for (MachineBasicBlock &MBB : *MF)
157 computeBlockSize(MBB);
159 // Compute block offsets and known bits.
160 adjustBlockOffsets(*MF->begin());
163 /// computeBlockSize - Compute the size for MBB.
164 /// This function updates BlockInfo directly.
165 void ARM64BranchRelaxation::computeBlockSize(const MachineBasicBlock &MBB) {
167 for (const MachineInstr &MI : MBB)
168 Size += TII->GetInstSizeInBytes(&MI);
169 BlockInfo[MBB.getNumber()].Size = Size;
172 /// getInstrOffset - Return the current offset of the specified machine
173 /// instruction from the start of the function. This offset changes as stuff is
174 /// moved around inside the function.
175 unsigned ARM64BranchRelaxation::getInstrOffset(MachineInstr *MI) const {
176 MachineBasicBlock *MBB = MI->getParent();
178 // The offset is composed of two things: the sum of the sizes of all MBB's
179 // before this instruction's block, and the offset from the start of the block
181 unsigned Offset = BlockInfo[MBB->getNumber()].Offset;
183 // Sum instructions before MI in MBB.
184 for (MachineBasicBlock::iterator I = MBB->begin(); &*I != MI; ++I) {
185 assert(I != MBB->end() && "Didn't find MI in its own basic block?");
186 Offset += TII->GetInstSizeInBytes(I);
191 void ARM64BranchRelaxation::adjustBlockOffsets(MachineBasicBlock &Start) {
192 unsigned PrevNum = Start.getNumber();
193 for (auto &MBB : make_range(MachineFunction::iterator(Start), MF->end())) {
194 unsigned Num = MBB.getNumber();
195 if (!Num) // block zero is never changed from offset zero.
197 // Get the offset and known bits at the end of the layout predecessor.
198 // Include the alignment of the current block.
199 unsigned LogAlign = MBB.getAlignment();
200 BlockInfo[Num].Offset = BlockInfo[PrevNum].postOffset(LogAlign);
205 /// Split the basic block containing MI into two blocks, which are joined by
206 /// an unconditional branch. Update data structures and renumber blocks to
207 /// account for this change and returns the newly created block.
208 /// NOTE: Successor list of the original BB is out of date after this function,
209 /// and must be updated by the caller! Other transforms follow using this
210 /// utility function, so no point updating now rather than waiting.
212 ARM64BranchRelaxation::splitBlockBeforeInstr(MachineInstr *MI) {
213 MachineBasicBlock *OrigBB = MI->getParent();
215 // Create a new MBB for the code after the OrigBB.
216 MachineBasicBlock *NewBB =
217 MF->CreateMachineBasicBlock(OrigBB->getBasicBlock());
218 MachineFunction::iterator MBBI = OrigBB;
220 MF->insert(MBBI, NewBB);
222 // Splice the instructions starting with MI over to NewBB.
223 NewBB->splice(NewBB->end(), OrigBB, MI, OrigBB->end());
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.
229 BuildMI(OrigBB, DebugLoc(), TII->get(ARM64::B)).addMBB(NewBB);
231 // Insert an entry into BlockInfo to align it properly with the block numbers.
232 BlockInfo.insert(BlockInfo.begin() + NewBB->getNumber(), BasicBlockInfo());
234 // Figure out how large the OrigBB is. As the first half of the original
235 // block, it cannot contain a tablejump. The size includes
236 // the new jump we added. (It should be possible to do this without
237 // recounting everything, but it's very confusing, and this is rarely
239 computeBlockSize(*OrigBB);
241 // Figure out how large the NewMBB is. As the second half of the original
242 // block, it may contain a tablejump.
243 computeBlockSize(*NewBB);
245 // All BBOffsets following these blocks must be modified.
246 adjustBlockOffsets(*OrigBB);
253 /// isBlockInRange - Returns true if the distance between specific MI and
254 /// specific BB can fit in MI's displacement field.
255 bool ARM64BranchRelaxation::isBlockInRange(MachineInstr *MI,
256 MachineBasicBlock *DestBB,
258 unsigned MaxOffs = ((1 << (Bits - 1)) - 1) << 2;
259 unsigned BrOffset = getInstrOffset(MI);
260 unsigned DestOffset = BlockInfo[DestBB->getNumber()].Offset;
262 DEBUG(dbgs() << "Branch of destination BB#" << DestBB->getNumber()
263 << " from BB#" << MI->getParent()->getNumber()
264 << " max delta=" << MaxOffs << " from " << getInstrOffset(MI)
265 << " to " << DestOffset << " offset "
266 << int(DestOffset - BrOffset) << "\t" << *MI);
268 // Branch before the Dest.
269 if (BrOffset <= DestOffset)
270 return (DestOffset - BrOffset <= MaxOffs);
271 return (BrOffset - DestOffset <= MaxOffs);
274 static bool isConditionalBranch(unsigned Opc) {
289 static MachineBasicBlock *getDestBlock(MachineInstr *MI) {
290 switch (MI->getOpcode()) {
292 assert(0 && "unexpected opcode!");
295 return MI->getOperand(2).getMBB();
301 return MI->getOperand(1).getMBB();
305 static unsigned getOppositeConditionOpcode(unsigned Opc) {
308 assert(0 && "unexpected opcode!");
309 case ARM64::TBNZ: return ARM64::TBZ;
310 case ARM64::TBZ: return ARM64::TBNZ;
311 case ARM64::CBNZW: return ARM64::CBZW;
312 case ARM64::CBNZX: return ARM64::CBZX;
313 case ARM64::CBZW: return ARM64::CBNZW;
314 case ARM64::CBZX: return ARM64::CBNZX;
315 case ARM64::Bcc: return ARM64::Bcc; // Condition is an operand for Bcc.
319 static unsigned getBranchDisplacementBits(unsigned Opc) {
322 assert(0 && "unexpected opcode!");
325 return TBZDisplacementBits;
330 return CBZDisplacementBits;
332 return BCCDisplacementBits;
336 static inline void invertBccCondition(MachineInstr *MI) {
337 assert(MI->getOpcode() == ARM64::Bcc && "Unexpected opcode!");
338 ARM64CC::CondCode CC = (ARM64CC::CondCode)MI->getOperand(0).getImm();
339 CC = ARM64CC::getInvertedCondCode(CC);
340 MI->getOperand(0).setImm((int64_t)CC);
343 /// fixupConditionalBranch - Fix up a conditional branch whose destination is
344 /// too far away to fit in its displacement field. It is converted to an inverse
345 /// conditional branch + an unconditional branch to the destination.
346 bool ARM64BranchRelaxation::fixupConditionalBranch(MachineInstr *MI) {
347 MachineBasicBlock *DestBB = getDestBlock(MI);
349 // Add an unconditional branch to the destination and invert the branch
350 // condition to jump over it:
357 // If the branch is at the end of its MBB and that has a fall-through block,
358 // direct the updated conditional branch to the fall-through block. Otherwise,
359 // split the MBB before the next instruction.
360 MachineBasicBlock *MBB = MI->getParent();
361 MachineInstr *BMI = &MBB->back();
362 bool NeedSplit = (BMI != MI) || !BBHasFallthrough(MBB);
365 if (std::next(MachineBasicBlock::iterator(MI)) ==
366 std::prev(MBB->getLastNonDebugInstr()) &&
367 BMI->getOpcode() == ARM64::B) {
368 // Last MI in the BB is an unconditional branch. Can we simply invert the
369 // condition and swap destinations:
375 MachineBasicBlock *NewDest = BMI->getOperand(0).getMBB();
376 if (isBlockInRange(MI, NewDest,
377 getBranchDisplacementBits(MI->getOpcode()))) {
378 DEBUG(dbgs() << " Invert condition and swap its destination with "
380 BMI->getOperand(0).setMBB(DestBB);
382 (MI->getOpcode() == ARM64::TBZ || MI->getOpcode() == ARM64::TBNZ)
385 MI->getOperand(OpNum).setMBB(NewDest);
386 MI->setDesc(TII->get(getOppositeConditionOpcode(MI->getOpcode())));
387 if (MI->getOpcode() == ARM64::Bcc)
388 invertBccCondition(MI);
395 // Analyze the branch so we know how to update the successor lists.
396 MachineBasicBlock *TBB, *FBB;
397 SmallVector<MachineOperand, 2> Cond;
398 TII->AnalyzeBranch(*MBB, TBB, FBB, Cond, false);
400 MachineBasicBlock *NewBB = splitBlockBeforeInstr(MI);
401 // No need for the branch to the next block. We're adding an unconditional
402 // branch to the destination.
403 int delta = TII->GetInstSizeInBytes(&MBB->back());
404 BlockInfo[MBB->getNumber()].Size -= delta;
405 MBB->back().eraseFromParent();
406 // BlockInfo[SplitBB].Offset is wrong temporarily, fixed below
408 // Update the successor lists according to the transformation to follow.
409 // Do it here since if there's no split, no update is needed.
410 MBB->replaceSuccessor(FBB, NewBB);
411 NewBB->addSuccessor(FBB);
413 MachineBasicBlock *NextBB = std::next(MachineFunction::iterator(MBB));
415 DEBUG(dbgs() << " Insert B to BB#" << DestBB->getNumber()
416 << ", invert condition and change dest. to BB#"
417 << NextBB->getNumber() << "\n");
419 // Insert a new conditional branch and a new unconditional branch.
420 MachineInstrBuilder MIB = BuildMI(
421 MBB, DebugLoc(), TII->get(getOppositeConditionOpcode(MI->getOpcode())))
422 .addOperand(MI->getOperand(0));
423 if (MI->getOpcode() == ARM64::TBZ || MI->getOpcode() == ARM64::TBNZ)
424 MIB.addOperand(MI->getOperand(1));
425 if (MI->getOpcode() == ARM64::Bcc)
426 invertBccCondition(MIB);
428 BlockInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
429 BuildMI(MBB, DebugLoc(), TII->get(ARM64::B)).addMBB(DestBB);
430 BlockInfo[MBB->getNumber()].Size += TII->GetInstSizeInBytes(&MBB->back());
432 // Remove the old conditional branch. It may or may not still be in MBB.
433 BlockInfo[MI->getParent()->getNumber()].Size -= TII->GetInstSizeInBytes(MI);
434 MI->eraseFromParent();
436 // Finally, keep the block offsets up to date.
437 adjustBlockOffsets(*MBB);
441 bool ARM64BranchRelaxation::relaxBranchInstructions() {
442 bool Changed = false;
443 // Relaxing branches involves creating new basic blocks, so re-eval
444 // end() for termination.
445 for (auto &MBB : *MF) {
446 MachineInstr *MI = MBB.getFirstTerminator();
447 if (isConditionalBranch(MI->getOpcode()) &&
448 !isBlockInRange(MI, getDestBlock(MI),
449 getBranchDisplacementBits(MI->getOpcode()))) {
450 fixupConditionalBranch(MI);
458 bool ARM64BranchRelaxation::runOnMachineFunction(MachineFunction &mf) {
461 // If the pass is disabled, just bail early.
462 if (!BranchRelaxation)
465 DEBUG(dbgs() << "***** ARM64BranchRelaxation *****\n");
467 TII = (const ARM64InstrInfo *)MF->getTarget().getInstrInfo();
469 // Renumber all of the machine basic blocks in the function, guaranteeing that
470 // the numbers agree with the position of the block in the function.
471 MF->RenumberBlocks();
473 // Do the initial scan of the function, building up information about the
474 // sizes of each block.
477 DEBUG(dbgs() << " Basic blocks before relaxation\n");
480 bool MadeChange = false;
481 while (relaxBranchInstructions())
484 // After a while, this might be made debug-only, but it is not expensive.
487 DEBUG(dbgs() << " Basic blocks after relaxation\n");
488 DEBUG(dbgs() << '\n'; dumpBBs());
495 /// createARM64BranchRelaxation - returns an instance of the constpool
497 FunctionPass *llvm::createARM64BranchRelaxation() {
498 return new ARM64BranchRelaxation();