[mips] Modify long branch for NaCl:
[oota-llvm.git] / lib / Target / Mips / MipsLongBranch.cpp
1 //===-- MipsLongBranch.cpp - Emit long branches ---------------------------===//
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 //===----------------------------------------------------------------------===//
9 //
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.
12 //
13 // FIXME: Fix pc-region jump instructions which cross 256MB segment boundaries.
14 //===----------------------------------------------------------------------===//
15
16 #include "Mips.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MCTargetDesc/MipsMCNaCl.h"
19 #include "MipsTargetMachine.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/IR/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"
29
30 using namespace llvm;
31
32 #define DEBUG_TYPE "mips-long-branch"
33
34 STATISTIC(LongBranches, "Number of long branches.");
35
36 static cl::opt<bool> SkipLongBranch(
37   "skip-mips-long-branch",
38   cl::init(false),
39   cl::desc("MIPS: Skip long branch pass."),
40   cl::Hidden);
41
42 static cl::opt<bool> ForceLongBranch(
43   "force-mips-long-branch",
44   cl::init(false),
45   cl::desc("MIPS: Expand all branches to long format."),
46   cl::Hidden);
47
48 namespace {
49   typedef MachineBasicBlock::iterator Iter;
50   typedef MachineBasicBlock::reverse_iterator ReverseIter;
51
52   struct MBBInfo {
53     uint64_t Size, Address;
54     bool HasLongBranch;
55     MachineInstr *Br;
56
57     MBBInfo() : Size(0), HasLongBranch(false), Br(nullptr) {}
58   };
59
60   class MipsLongBranch : public MachineFunctionPass {
61
62   public:
63     static char ID;
64     MipsLongBranch(TargetMachine &tm)
65       : MachineFunctionPass(ID), TM(tm),
66         IsPIC(TM.getRelocationModel() == Reloc::PIC_),
67         ABI(TM.getSubtarget<MipsSubtarget>().getTargetABI()),
68         LongBranchSeqSize(!IsPIC ? 2 : (ABI == MipsSubtarget::N64 ? 10 :
69             (!TM.getSubtarget<MipsSubtarget>().isTargetNaCl() ? 9 : 10))) {}
70
71     const char *getPassName() const override {
72       return "Mips Long Branch";
73     }
74
75     bool runOnMachineFunction(MachineFunction &F) override;
76
77   private:
78     void splitMBB(MachineBasicBlock *MBB);
79     void initMBBInfo();
80     int64_t computeOffset(const MachineInstr *Br);
81     void replaceBranch(MachineBasicBlock &MBB, Iter Br, DebugLoc DL,
82                        MachineBasicBlock *MBBOpnd);
83     void expandToLongBranch(MBBInfo &Info);
84
85     const TargetMachine &TM;
86     MachineFunction *MF;
87     SmallVector<MBBInfo, 16> MBBInfos;
88     bool IsPIC;
89     unsigned ABI;
90     unsigned LongBranchSeqSize;
91   };
92
93   char MipsLongBranch::ID = 0;
94 } // end of anonymous namespace
95
96 /// createMipsLongBranchPass - Returns a pass that converts branches to long
97 /// branches.
98 FunctionPass *llvm::createMipsLongBranchPass(MipsTargetMachine &tm) {
99   return new MipsLongBranch(tm);
100 }
101
102 /// Iterate over list of Br's operands and search for a MachineBasicBlock
103 /// operand.
104 static MachineBasicBlock *getTargetMBB(const MachineInstr &Br) {
105   for (unsigned I = 0, E = Br.getDesc().getNumOperands(); I < E; ++I) {
106     const MachineOperand &MO = Br.getOperand(I);
107
108     if (MO.isMBB())
109       return MO.getMBB();
110   }
111
112   assert(false && "This instruction does not have an MBB operand.");
113   return nullptr;
114 }
115
116 // Traverse the list of instructions backwards until a non-debug instruction is
117 // found or it reaches E.
118 static ReverseIter getNonDebugInstr(ReverseIter B, ReverseIter E) {
119   for (; B != E; ++B)
120     if (!B->isDebugValue())
121       return B;
122
123   return E;
124 }
125
126 // Split MBB if it has two direct jumps/branches.
127 void MipsLongBranch::splitMBB(MachineBasicBlock *MBB) {
128   ReverseIter End = MBB->rend();
129   ReverseIter LastBr = getNonDebugInstr(MBB->rbegin(), End);
130
131   // Return if MBB has no branch instructions.
132   if ((LastBr == End) ||
133       (!LastBr->isConditionalBranch() && !LastBr->isUnconditionalBranch()))
134     return;
135
136   ReverseIter FirstBr = getNonDebugInstr(std::next(LastBr), End);
137
138   // MBB has only one branch instruction if FirstBr is not a branch
139   // instruction.
140   if ((FirstBr == End) ||
141       (!FirstBr->isConditionalBranch() && !FirstBr->isUnconditionalBranch()))
142     return;
143
144   assert(!FirstBr->isIndirectBranch() && "Unexpected indirect branch found.");
145
146   // Create a new MBB. Move instructions in MBB to the newly created MBB.
147   MachineBasicBlock *NewMBB =
148     MF->CreateMachineBasicBlock(MBB->getBasicBlock());
149
150   // Insert NewMBB and fix control flow.
151   MachineBasicBlock *Tgt = getTargetMBB(*FirstBr);
152   NewMBB->transferSuccessors(MBB);
153   NewMBB->removeSuccessor(Tgt);
154   MBB->addSuccessor(NewMBB);
155   MBB->addSuccessor(Tgt);
156   MF->insert(std::next(MachineFunction::iterator(MBB)), NewMBB);
157
158   NewMBB->splice(NewMBB->end(), MBB, (++LastBr).base(), MBB->end());
159 }
160
161 // Fill MBBInfos.
162 void MipsLongBranch::initMBBInfo() {
163   // Split the MBBs if they have two branches. Each basic block should have at
164   // most one branch after this loop is executed.
165   for (MachineFunction::iterator I = MF->begin(), E = MF->end(); I != E;)
166     splitMBB(I++);
167
168   MF->RenumberBlocks();
169   MBBInfos.clear();
170   MBBInfos.resize(MF->size());
171
172   const MipsInstrInfo *TII =
173     static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
174   for (unsigned I = 0, E = MBBInfos.size(); I < E; ++I) {
175     MachineBasicBlock *MBB = MF->getBlockNumbered(I);
176
177     // Compute size of MBB.
178     for (MachineBasicBlock::instr_iterator MI = MBB->instr_begin();
179          MI != MBB->instr_end(); ++MI)
180       MBBInfos[I].Size += TII->GetInstSizeInBytes(&*MI);
181
182     // Search for MBB's branch instruction.
183     ReverseIter End = MBB->rend();
184     ReverseIter Br = getNonDebugInstr(MBB->rbegin(), End);
185
186     if ((Br != End) && !Br->isIndirectBranch() &&
187         (Br->isConditionalBranch() ||
188          (Br->isUnconditionalBranch() &&
189           TM.getRelocationModel() == Reloc::PIC_)))
190       MBBInfos[I].Br = (++Br).base();
191   }
192 }
193
194 // Compute offset of branch in number of bytes.
195 int64_t MipsLongBranch::computeOffset(const MachineInstr *Br) {
196   int64_t Offset = 0;
197   int ThisMBB = Br->getParent()->getNumber();
198   int TargetMBB = getTargetMBB(*Br)->getNumber();
199
200   // Compute offset of a forward branch.
201   if (ThisMBB < TargetMBB) {
202     for (int N = ThisMBB + 1; N < TargetMBB; ++N)
203       Offset += MBBInfos[N].Size;
204
205     return Offset + 4;
206   }
207
208   // Compute offset of a backward branch.
209   for (int N = ThisMBB; N >= TargetMBB; --N)
210     Offset += MBBInfos[N].Size;
211
212   return -Offset + 4;
213 }
214
215 // Replace Br with a branch which has the opposite condition code and a
216 // MachineBasicBlock operand MBBOpnd.
217 void MipsLongBranch::replaceBranch(MachineBasicBlock &MBB, Iter Br,
218                                    DebugLoc DL, MachineBasicBlock *MBBOpnd) {
219   const MipsInstrInfo *TII =
220     static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
221   unsigned NewOpc = TII->getOppositeBranchOpc(Br->getOpcode());
222   const MCInstrDesc &NewDesc = TII->get(NewOpc);
223
224   MachineInstrBuilder MIB = BuildMI(MBB, Br, DL, NewDesc);
225
226   for (unsigned I = 0, E = Br->getDesc().getNumOperands(); I < E; ++I) {
227     MachineOperand &MO = Br->getOperand(I);
228
229     if (!MO.isReg()) {
230       assert(MO.isMBB() && "MBB operand expected.");
231       break;
232     }
233
234     MIB.addReg(MO.getReg());
235   }
236
237   MIB.addMBB(MBBOpnd);
238
239   // Bundle the instruction in the delay slot to the newly created branch
240   // and erase the original branch.
241   assert(Br->isBundledWithSucc());
242   MachineBasicBlock::instr_iterator II(Br);
243   MIBundleBuilder(&*MIB).append((++II)->removeFromBundle());
244   Br->eraseFromParent();
245 }
246
247 // Expand branch instructions to long branches.
248 void MipsLongBranch::expandToLongBranch(MBBInfo &I) {
249   MachineBasicBlock::iterator Pos;
250   MachineBasicBlock *MBB = I.Br->getParent(), *TgtMBB = getTargetMBB(*I.Br);
251   DebugLoc DL = I.Br->getDebugLoc();
252   const BasicBlock *BB = MBB->getBasicBlock();
253   MachineFunction::iterator FallThroughMBB = ++MachineFunction::iterator(MBB);
254   MachineBasicBlock *LongBrMBB = MF->CreateMachineBasicBlock(BB);
255
256   const MipsInstrInfo *TII =
257     static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
258
259   MF->insert(FallThroughMBB, LongBrMBB);
260   MBB->removeSuccessor(TgtMBB);
261   MBB->addSuccessor(LongBrMBB);
262
263   if (IsPIC) {
264     MachineBasicBlock *BalTgtMBB = MF->CreateMachineBasicBlock(BB);
265     MF->insert(FallThroughMBB, BalTgtMBB);
266     LongBrMBB->addSuccessor(BalTgtMBB);
267     BalTgtMBB->addSuccessor(TgtMBB);
268
269     if (ABI != MipsSubtarget::N64) {
270       // $longbr:
271       //  addiu $sp, $sp, -8
272       //  sw $ra, 0($sp)
273       //  lui $at, %hi($tgt - $baltgt)
274       //  bal $baltgt
275       //  addiu $at, $at, %lo($tgt - $baltgt)
276       // $baltgt:
277       //  addu $at, $ra, $at
278       //  lw $ra, 0($sp)
279       //  jr $at
280       //  addiu $sp, $sp, 8
281       // $fallthrough:
282       //
283
284       Pos = LongBrMBB->begin();
285
286       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
287         .addReg(Mips::SP).addImm(-8);
288       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SW)).addReg(Mips::RA)
289         .addReg(Mips::SP).addImm(0);
290
291       // LUi and ADDiu instructions create 32-bit offset of the target basic
292       // block from the target of BAL instruction.  We cannot use immediate
293       // value for this offset because it cannot be determined accurately when
294       // the program has inline assembly statements.  We therefore use the
295       // relocation expressions %hi($tgt-$baltgt) and %lo($tgt-$baltgt) which
296       // are resolved during the fixup, so the values will always be correct.
297       //
298       // Since we cannot create %hi($tgt-$baltgt) and %lo($tgt-$baltgt)
299       // expressions at this point (it is possible only at the MC layer),
300       // we replace LUi and ADDiu with pseudo instructions
301       // LONG_BRANCH_LUi and LONG_BRANCH_ADDiu, and add both basic
302       // blocks as operands to these instructions.  When lowering these pseudo
303       // instructions to LUi and ADDiu in the MC layer, we will create
304       // %hi($tgt-$baltgt) and %lo($tgt-$baltgt) expressions and add them as
305       // operands to lowered instructions.
306
307       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_LUi), Mips::AT)
308         .addMBB(TgtMBB).addMBB(BalTgtMBB);
309       MIBundleBuilder(*LongBrMBB, Pos)
310         .append(BuildMI(*MF, DL, TII->get(Mips::BAL_BR)).addMBB(BalTgtMBB))
311         .append(BuildMI(*MF, DL, TII->get(Mips::LONG_BRANCH_ADDiu), Mips::AT)
312                   .addReg(Mips::AT).addMBB(TgtMBB).addMBB(BalTgtMBB));
313
314       Pos = BalTgtMBB->begin();
315
316       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDu), Mips::AT)
317         .addReg(Mips::RA).addReg(Mips::AT);
318       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LW), Mips::RA)
319         .addReg(Mips::SP).addImm(0);
320
321       if (!TM.getSubtarget<MipsSubtarget>().isTargetNaCl()) {
322         MIBundleBuilder(*BalTgtMBB, Pos)
323           .append(BuildMI(*MF, DL, TII->get(Mips::JR)).addReg(Mips::AT))
324           .append(BuildMI(*MF, DL, TII->get(Mips::ADDiu), Mips::SP)
325                   .addReg(Mips::SP).addImm(8));
326       } else {
327         // In NaCl, modifying the sp is not allowed in branch delay slot.
328         BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::ADDiu), Mips::SP)
329           .addReg(Mips::SP).addImm(8);
330
331         MIBundleBuilder(*BalTgtMBB, Pos)
332           .append(BuildMI(*MF, DL, TII->get(Mips::JR)).addReg(Mips::AT))
333           .append(BuildMI(*MF, DL, TII->get(Mips::NOP)));
334
335         // Bundle-align the target of indirect branch JR.
336         TgtMBB->setAlignment(MIPS_NACL_BUNDLE_ALIGN);
337       }
338     } else {
339       // $longbr:
340       //  daddiu $sp, $sp, -16
341       //  sd $ra, 0($sp)
342       //  daddiu $at, $zero, %hi($tgt - $baltgt)
343       //  dsll $at, $at, 16
344       //  bal $baltgt
345       //  daddiu $at, $at, %lo($tgt - $baltgt)
346       // $baltgt:
347       //  daddu $at, $ra, $at
348       //  ld $ra, 0($sp)
349       //  jr64 $at
350       //  daddiu $sp, $sp, 16
351       // $fallthrough:
352       //
353
354       // We assume the branch is within-function, and that offset is within
355       // +/- 2GB.  High 32 bits will therefore always be zero.
356
357       // Note that this will work even if the offset is negative, because
358       // of the +1 modification that's added in that case.  For example, if the
359       // offset is -1MB (0xFFFFFFFFFFF00000), the computation for %higher is
360       //
361       // 0xFFFFFFFFFFF00000 + 0x80008000 = 0x000000007FF08000
362       //
363       // and the bits [47:32] are zero.  For %highest
364       //
365       // 0xFFFFFFFFFFF00000 + 0x800080008000 = 0x000080007FF08000
366       //
367       // and the bits [63:48] are zero.
368
369       Pos = LongBrMBB->begin();
370
371       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DADDiu), Mips::SP_64)
372         .addReg(Mips::SP_64).addImm(-16);
373       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::SD)).addReg(Mips::RA_64)
374         .addReg(Mips::SP_64).addImm(0);
375       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::LONG_BRANCH_DADDiu),
376               Mips::AT_64).addReg(Mips::ZERO_64)
377                           .addMBB(TgtMBB, MipsII::MO_ABS_HI).addMBB(BalTgtMBB);
378       BuildMI(*LongBrMBB, Pos, DL, TII->get(Mips::DSLL), Mips::AT_64)
379         .addReg(Mips::AT_64).addImm(16);
380
381       MIBundleBuilder(*LongBrMBB, Pos)
382         .append(BuildMI(*MF, DL, TII->get(Mips::BAL_BR)).addMBB(BalTgtMBB))
383         .append(BuildMI(*MF, DL, TII->get(Mips::LONG_BRANCH_DADDiu),
384                         Mips::AT_64).addReg(Mips::AT_64)
385                                     .addMBB(TgtMBB, MipsII::MO_ABS_LO)
386                                     .addMBB(BalTgtMBB));
387
388       Pos = BalTgtMBB->begin();
389
390       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::DADDu), Mips::AT_64)
391         .addReg(Mips::RA_64).addReg(Mips::AT_64);
392       BuildMI(*BalTgtMBB, Pos, DL, TII->get(Mips::LD), Mips::RA_64)
393         .addReg(Mips::SP_64).addImm(0);
394
395       MIBundleBuilder(*BalTgtMBB, Pos)
396         .append(BuildMI(*MF, DL, TII->get(Mips::JR64)).addReg(Mips::AT_64))
397         .append(BuildMI(*MF, DL, TII->get(Mips::DADDiu), Mips::SP_64)
398                 .addReg(Mips::SP_64).addImm(16));
399     }
400
401     assert(LongBrMBB->size() + BalTgtMBB->size() == LongBranchSeqSize);
402   } else {
403     // $longbr:
404     //  j $tgt
405     //  nop
406     // $fallthrough:
407     //
408     Pos = LongBrMBB->begin();
409     LongBrMBB->addSuccessor(TgtMBB);
410     MIBundleBuilder(*LongBrMBB, Pos)
411       .append(BuildMI(*MF, DL, TII->get(Mips::J)).addMBB(TgtMBB))
412       .append(BuildMI(*MF, DL, TII->get(Mips::NOP)));
413
414     assert(LongBrMBB->size() == LongBranchSeqSize);
415   }
416
417   if (I.Br->isUnconditionalBranch()) {
418     // Change branch destination.
419     assert(I.Br->getDesc().getNumOperands() == 1);
420     I.Br->RemoveOperand(0);
421     I.Br->addOperand(MachineOperand::CreateMBB(LongBrMBB));
422   } else
423     // Change branch destination and reverse condition.
424     replaceBranch(*MBB, I.Br, DL, FallThroughMBB);
425 }
426
427 static void emitGPDisp(MachineFunction &F, const MipsInstrInfo *TII) {
428   MachineBasicBlock &MBB = F.front();
429   MachineBasicBlock::iterator I = MBB.begin();
430   DebugLoc DL = MBB.findDebugLoc(MBB.begin());
431   BuildMI(MBB, I, DL, TII->get(Mips::LUi), Mips::V0)
432     .addExternalSymbol("_gp_disp", MipsII::MO_ABS_HI);
433   BuildMI(MBB, I, DL, TII->get(Mips::ADDiu), Mips::V0)
434     .addReg(Mips::V0).addExternalSymbol("_gp_disp", MipsII::MO_ABS_LO);
435   MBB.removeLiveIn(Mips::V0);
436 }
437
438 bool MipsLongBranch::runOnMachineFunction(MachineFunction &F) {
439   const MipsInstrInfo *TII =
440     static_cast<const MipsInstrInfo*>(TM.getInstrInfo());
441
442   if (TM.getSubtarget<MipsSubtarget>().inMips16Mode())
443     return false;
444   if ((TM.getRelocationModel() == Reloc::PIC_) &&
445       TM.getSubtarget<MipsSubtarget>().isABI_O32() &&
446       F.getInfo<MipsFunctionInfo>()->globalBaseRegSet())
447     emitGPDisp(F, TII);
448
449   if (SkipLongBranch)
450     return true;
451
452   MF = &F;
453   initMBBInfo();
454
455   SmallVectorImpl<MBBInfo>::iterator I, E = MBBInfos.end();
456   bool EverMadeChange = false, MadeChange = true;
457
458   while (MadeChange) {
459     MadeChange = false;
460
461     for (I = MBBInfos.begin(); I != E; ++I) {
462       // Skip if this MBB doesn't have a branch or the branch has already been
463       // converted to a long branch.
464       if (!I->Br || I->HasLongBranch)
465         continue;
466
467       int ShVal = TM.getSubtarget<MipsSubtarget>().inMicroMipsMode() ? 2 : 4;
468       int64_t Offset = computeOffset(I->Br) / ShVal;
469
470       if (TM.getSubtarget<MipsSubtarget>().isTargetNaCl()) {
471         // The offset calculation does not include sandboxing instructions
472         // that will be added later in the MC layer.  Since at this point we
473         // don't know the exact amount of code that "sandboxing" will add, we
474         // conservatively estimate that code will not grow more than 100%.
475         Offset *= 2;
476       }
477
478       // Check if offset fits into 16-bit immediate field of branches.
479       if (!ForceLongBranch && isInt<16>(Offset))
480         continue;
481
482       I->HasLongBranch = true;
483       I->Size += LongBranchSeqSize * 4;
484       ++LongBranches;
485       EverMadeChange = MadeChange = true;
486     }
487   }
488
489   if (!EverMadeChange)
490     return true;
491
492   // Compute basic block addresses.
493   if (TM.getRelocationModel() == Reloc::PIC_) {
494     uint64_t Address = 0;
495
496     for (I = MBBInfos.begin(); I != E; Address += I->Size, ++I)
497       I->Address = Address;
498   }
499
500   // Do the expansion.
501   for (I = MBBInfos.begin(); I != E; ++I)
502     if (I->HasLongBranch)
503       expandToLongBranch(*I);
504
505   MF->RenumberBlocks();
506
507   return true;
508 }