1 //===-- MipsLongBranch.cpp - Emit long branches ---------------------------===//
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 // This pass expands a branch or jump instruction into a long branch if its
11 // offset is too large to fit into its immediate field.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-long-branch"
18 #include "MipsTargetMachine.h"
19 #include "MCTargetDesc/MipsBaseInfo.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/Function.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/MathExtras.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetRegisterInfo.h"
32 STATISTIC(LongBranches, "Number of long branches.");
34 static cl::opt<bool> SkipLongBranch(
35 "skip-mips-long-branch",
37 cl::desc("MIPS: Skip long branch pass."),
40 static cl::opt<bool> ForceLongBranch(
41 "force-mips-long-branch",
43 cl::desc("MIPS: Expand all branches to long format."),
47 typedef MachineBasicBlock::iterator Iter;
48 typedef MachineBasicBlock::reverse_iterator ReverseIter;
55 MBBInfo() : Size(0), HasLongBranch(false), Br(0) {}
58 class MipsLongBranch : public MachineFunctionPass {
62 MipsLongBranch(TargetMachine &tm)
63 : MachineFunctionPass(ID), TM(tm),
64 TII(static_cast<const MipsInstrInfo*>(tm.getInstrInfo())) {}
66 virtual const char *getPassName() const {
67 return "Mips Long Branch";
70 bool runOnMachineFunction(MachineFunction &F);
73 void splitMBB(MachineBasicBlock *MBB);
75 int64_t computeOffset(const MachineInstr *Br);
76 bool offsetFitsIntoField(const MachineInstr *Br);
77 unsigned addLongBranch(MachineBasicBlock &MBB, Iter Pos,
78 MachineBasicBlock *Tgt, DebugLoc DL, bool Nop);
79 void replaceBranch(MachineBasicBlock &MBB, Iter Br, DebugLoc DL,
80 MachineBasicBlock *MBBOpnd);
81 void expandToLongBranch(MBBInfo &Info);
83 const TargetMachine &TM;
84 const MipsInstrInfo *TII;
86 SmallVector<MBBInfo, 16> MBBInfos;
89 char MipsLongBranch::ID = 0;
90 } // end of anonymous namespace
92 /// createMipsLongBranchPass - Returns a pass that converts branches to long
94 FunctionPass *llvm::createMipsLongBranchPass(MipsTargetMachine &tm) {
95 return new MipsLongBranch(tm);
98 /// Iterate over list of Br's operands and search for a MachineBasicBlock
100 static MachineBasicBlock *getTargetMBB(const MachineInstr &Br) {
101 for (unsigned I = 0, E = Br.getDesc().getNumOperands(); I < E; ++I) {
102 const MachineOperand &MO = Br.getOperand(I);
108 assert(false && "This instruction does not have an MBB operand.");
112 // Traverse the list of instructions backwards until a non-debug instruction is
113 // found or it reaches E.
114 static ReverseIter getNonDebugInstr(ReverseIter B, ReverseIter E) {
116 if (!B->isDebugValue())
122 // Split MBB if it has two direct jumps/branches.
123 void MipsLongBranch::splitMBB(MachineBasicBlock *MBB) {
124 ReverseIter End = MBB->rend();
125 ReverseIter LastBr = getNonDebugInstr(MBB->rbegin(), End);
127 // Return if MBB has no branch instructions.
128 if ((LastBr == End) ||
129 (!LastBr->isConditionalBranch() && !LastBr->isUnconditionalBranch()))
132 ReverseIter FirstBr = getNonDebugInstr(llvm::next(LastBr), End);
134 // MBB has only one branch instruction if FirstBr is not a branch
136 if ((FirstBr == End) ||
137 (!FirstBr->isConditionalBranch() && !FirstBr->isUnconditionalBranch()))
140 assert(!FirstBr->isIndirectBranch() && "Unexpected indirect branch found.");
142 // Create a new MBB. Move instructions in MBB to the newly created MBB.
143 MachineBasicBlock *NewMBB =
144 MF->CreateMachineBasicBlock(MBB->getBasicBlock());
146 // Insert NewMBB and fix control flow.
147 MachineBasicBlock *Tgt = getTargetMBB(*FirstBr);
148 NewMBB->transferSuccessors(MBB);
149 NewMBB->removeSuccessor(Tgt);
150 MBB->addSuccessor(NewMBB);
151 MBB->addSuccessor(Tgt);
152 MF->insert(llvm::next(MachineFunction::iterator(MBB)), NewMBB);
154 NewMBB->splice(NewMBB->end(), MBB, (++LastBr).base(), MBB->end());
158 void MipsLongBranch::initMBBInfo() {
159 // Split the MBBs if they have two branches. Each basic block should have at
160 // most one branch after this loop is executed.
161 for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E;)
164 MF->RenumberBlocks();
166 MBBInfos.resize(MF->size());
168 for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
169 MachineBasicBlock *MBB = MF->getBlockNumbered(I);
171 // Compute size of MBB.
172 for (MachineBasicBlock::instr_iterator MI = MBB->instr_begin();
173 MI != MBB->instr_end(); ++MI)
174 MBBInfos[I].Size += TII->GetInstSizeInBytes(&*MI);
176 // Search for MBB's branch instruction.
177 ReverseIter End = MBB->rend();
178 ReverseIter Br = getNonDebugInstr(MBB->rbegin(), End);
180 if ((Br != End) && !Br->isIndirectBranch() &&
181 (Br->isConditionalBranch() || Br->isUnconditionalBranch()))
182 MBBInfos[I].Br = (++Br).base();
186 // Compute offset of branch in number of bytes.
187 int64_t MipsLongBranch::computeOffset(const MachineInstr *Br) {
189 int ThisMBB = Br->getParent()->getNumber();
190 int TargetMBB = getTargetMBB(*Br)->getNumber();
192 // Compute offset of a forward branch.
193 if (ThisMBB < TargetMBB) {
194 for (int N = ThisMBB + 1; N < TargetMBB; ++N)
195 Offset += MBBInfos[N].Size;
200 // Compute offset of a backward branch.
201 for (int N = ThisMBB; N >= TargetMBB; --N)
202 Offset += MBBInfos[N].Size;
207 // Insert the following sequence:
209 // lw $at, global_reg_slot
210 // lw $at, got($L1)($at)
211 // addiu $at, $at, lo($L1)
216 // addiu $at, $at, lo($L1)
219 unsigned MipsLongBranch::addLongBranch(MachineBasicBlock &MBB, Iter Pos,
220 MachineBasicBlock *Tgt, DebugLoc DL,
222 MF->getInfo<MipsFunctionInfo>()->setEmitNOAT();
223 bool IsPIC = (TM.getRelocationModel() == Reloc::PIC_);
224 unsigned ABI = TM.getSubtarget<MipsSubtarget>().getTargetABI();
225 bool N64 = (ABI == MipsSubtarget::N64);
229 bool HasMips64 = TM.getSubtarget<MipsSubtarget>().hasMips64();
230 unsigned AT = N64 ? Mips::AT_64 : Mips::AT;
231 unsigned Load = N64 ? Mips::LD_P8 : Mips::LW;
232 unsigned ADDiu = N64 ? Mips::DADDiu : Mips::ADDiu;
233 unsigned JR = N64 ? Mips::JR64 : Mips::JR;
234 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
235 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
236 const MipsRegisterInfo *MRI =
237 static_cast<const MipsRegisterInfo*>(TM.getRegisterInfo());
238 unsigned SP = MRI->getFrameRegister(*MF);
239 unsigned GlobalRegFI = MF->getInfo<MipsFunctionInfo>()->getGlobalRegFI();
240 int64_t Offset = MF->getFrameInfo()->getObjectOffset(GlobalRegFI);
242 if (isInt<16>(Offset)) {
243 BuildMI(MBB, Pos, DL, TII->get(Load), AT).addReg(SP).addImm(Offset);
246 unsigned ADDu = N64 ? Mips::DADDu : Mips::ADDu;
247 MipsAnalyzeImmediate::Inst LastInst(0, 0);
249 MF->getInfo<MipsFunctionInfo>()->setEmitNOAT();
250 NumInstrs = Mips::loadImmediate(Offset, N64, *TII, MBB, Pos, DL, true,
252 BuildMI(MBB, Pos, DL, TII->get(ADDu), AT).addReg(SP).addReg(AT);
253 BuildMI(MBB, Pos, DL, TII->get(Load), AT).addReg(AT)
254 .addImm(SignExtend64<16>(LastInst.ImmOpnd));
257 BuildMI(MBB, Pos, DL, TII->get(Load), AT).addReg(AT).addMBB(Tgt, GOTFlag);
258 BuildMI(MBB, Pos, DL, TII->get(ADDiu), AT).addReg(AT).addMBB(Tgt, OFSTFlag);
259 BuildMI(MBB, Pos, DL, TII->get(JR)).addReg(Mips::AT, RegState::Kill);
262 BuildMI(MBB, Pos, DL, TII->get(Mips::LUi), Mips::AT)
263 .addMBB(Tgt, MipsII::MO_ABS_HI);
264 BuildMI(MBB, Pos, DL, TII->get(Mips::ADDiu), Mips::AT)
265 .addReg(Mips::AT).addMBB(Tgt, MipsII::MO_ABS_LO);
266 BuildMI(MBB, Pos, DL, TII->get(Mips::JR)).addReg(Mips::AT, RegState::Kill);
271 BuildMI(MBB, Pos, DL, TII->get(Mips::NOP))->setIsInsideBundle();
278 // Replace Br with a branch which has the opposite condition code and a
279 // MachineBasicBlock operand MBBOpnd.
280 void MipsLongBranch::replaceBranch(MachineBasicBlock &MBB, Iter Br,
281 DebugLoc DL, MachineBasicBlock *MBBOpnd) {
282 unsigned NewOpc = Mips::GetOppositeBranchOpc(Br->getOpcode());
283 const MCInstrDesc &NewDesc = TII->get(NewOpc);
285 MachineInstrBuilder MIB = BuildMI(MBB, Br, DL, NewDesc);
287 for (unsigned I = 0, E = Br->getDesc().getNumOperands(); I < E; ++I) {
288 MachineOperand &MO = Br->getOperand(I);
291 assert(MO.isMBB() && "MBB operand expected.");
295 MIB.addReg(MO.getReg());
300 Br->eraseFromParent();
303 // Expand branch instructions to long branches.
304 void MipsLongBranch::expandToLongBranch(MBBInfo &I) {
305 I.HasLongBranch = true;
307 MachineBasicBlock *MBB = I.Br->getParent(), *Tgt = getTargetMBB(*I.Br);
308 DebugLoc DL = I.Br->getDebugLoc();
310 if (I.Br->isUnconditionalBranch()) {
311 // Unconditional branch before transformation:
315 // after transformation:
317 // lw $at, global_reg_slot
318 // lw $at, %got($tgt)($at)
319 // addiu $at, $at, %lo($tgt)
322 I.Size += (addLongBranch(*MBB, llvm::next(Iter(I.Br)), Tgt, DL, true)
325 // Remove branch and clear InsideBundle bit of the next instruction.
326 llvm::next(MachineBasicBlock::instr_iterator(I.Br))
327 ->setIsInsideBundle(false);
328 I.Br->eraseFromParent();
332 assert(I.Br->isConditionalBranch() && "Conditional branch expected.");
334 // Conditional branch before transformation:
339 // after transformation:
340 // b !cc, FallThrough
343 // lw $at, global_reg_slot
344 // lw $at, %got($tgt)($at)
345 // addiu $at, $at, %lo($tgt)
350 MachineBasicBlock *NewMBB = MF->CreateMachineBasicBlock(MBB->getBasicBlock());
351 MF->insert(llvm::next(MachineFunction::iterator(MBB)), NewMBB);
352 MBB->removeSuccessor(Tgt);
353 MBB->addSuccessor(NewMBB);
354 NewMBB->addSuccessor(Tgt);
356 I.Size += addLongBranch(*NewMBB, NewMBB->begin(), Tgt, DL, true) * 4;
357 replaceBranch(*MBB, I.Br, DL, *MBB->succ_begin());
360 static void emitGPDisp(MachineFunction &F, const MipsInstrInfo *TII) {
361 MachineBasicBlock &MBB = F.front();
362 MachineBasicBlock::iterator I = MBB.begin();
363 DebugLoc DL = MBB.findDebugLoc(MBB.begin());
364 BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::V0)
365 .addExternalSymbol("_gp_disp", MipsII::MO_ABS_HI);
366 BuildMI(MBB, I, DL, TII->get(Mips::ADDiu), Mips::V0)
367 .addReg(Mips::V0).addExternalSymbol("_gp_disp", MipsII::MO_ABS_LO);
368 MBB.removeLiveIn(Mips::V0);
371 bool MipsLongBranch::runOnMachineFunction(MachineFunction &F) {
372 if ((TM.getRelocationModel() == Reloc::PIC_) &&
373 TM.getSubtarget<MipsSubtarget>().isABI_O32() &&
374 F.getInfo<MipsFunctionInfo>()->globalBaseRegSet())
383 bool IsPIC = (TM.getRelocationModel() == Reloc::PIC_);
384 SmallVector<MBBInfo, 16>::iterator I, E = MBBInfos.end();
385 bool EverMadeChange = false, MadeChange = true;
390 for (I = MBBInfos.begin(); I != E; ++I) {
391 // Skip if this MBB doesn't have a branch or the branch has already been
392 // converted to a long branch.
393 if (!I->Br || I->HasLongBranch)
396 int64_t Offset = computeOffset(I->Br);
398 if (!ForceLongBranch) {
399 // Check if offset fits into 16-bit immediate field of branches.
400 if ((I->Br->isConditionalBranch() || IsPIC) && isInt<16>(Offset / 4))
403 // Check if offset fits into 26-bit immediate field of jumps (J).
404 if (I->Br->isUnconditionalBranch() && !IsPIC && isInt<26>(Offset / 4))
408 expandToLongBranch(*I);
410 EverMadeChange = MadeChange = true;
415 MF->RenumberBlocks();
417 return EverMadeChange;