MipsAsmPrinter.cpp revision 158413930f25ecdd0902e1cc11bb8dc3683b94f8
1//===-- MipsAsmPrinter.cpp - Mips LLVM Assembly Printer -------------------===//
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 file contains a printer that converts from our internal representation
11// of machine-dependent LLVM code to GAS-format MIPS assembly language.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "mips-asm-printer"
16#include "MipsAsmPrinter.h"
17#include "Mips.h"
18#include "MipsInstrInfo.h"
19#include "InstPrinter/MipsInstPrinter.h"
20#include "MCTargetDesc/MipsBaseInfo.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/Twine.h"
24#include "llvm/Analysis/DebugInfo.h"
25#include "llvm/BasicBlock.h"
26#include "llvm/Instructions.h"
27#include "llvm/CodeGen/MachineFunctionPass.h"
28#include "llvm/CodeGen/MachineConstantPool.h"
29#include "llvm/CodeGen/MachineFrameInfo.h"
30#include "llvm/CodeGen/MachineInstr.h"
31#include "llvm/CodeGen/MachineMemOperand.h"
32#include "llvm/Instructions.h"
33#include "llvm/MC/MCStreamer.h"
34#include "llvm/MC/MCAsmInfo.h"
35#include "llvm/MC/MCInst.h"
36#include "llvm/MC/MCSymbol.h"
37#include "llvm/Support/TargetRegistry.h"
38#include "llvm/Support/raw_ostream.h"
39#include "llvm/Target/Mangler.h"
40#include "llvm/Target/TargetData.h"
41#include "llvm/Target/TargetLoweringObjectFile.h"
42#include "llvm/Target/TargetOptions.h"
43
44using namespace llvm;
45
46bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
47  MipsFI = MF.getInfo<MipsFunctionInfo>();
48  AsmPrinter::runOnMachineFunction(MF);
49  return true;
50}
51
52void MipsAsmPrinter::EmitInstruction(const MachineInstr *MI) {
53  if (MI->isDebugValue()) {
54    SmallString<128> Str;
55    raw_svector_ostream OS(Str);
56
57    PrintDebugValueComment(MI, OS);
58    return;
59  }
60
61  MachineBasicBlock::const_instr_iterator I = MI;
62  MachineBasicBlock::const_instr_iterator E = MI->getParent()->instr_end();
63
64  do {
65    MCInst TmpInst0;
66    MCInstLowering.Lower(I++, TmpInst0);
67    OutStreamer.EmitInstruction(TmpInst0);
68  } while ((I != E) && I->isInsideBundle());
69}
70
71//===----------------------------------------------------------------------===//
72//
73//  Mips Asm Directives
74//
75//  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
76//  Describe the stack frame.
77//
78//  -- Mask directives "(f)mask  bitmask, offset"
79//  Tells the assembler which registers are saved and where.
80//  bitmask - contain a little endian bitset indicating which registers are
81//            saved on function prologue (e.g. with a 0x80000000 mask, the
82//            assembler knows the register 31 (RA) is saved at prologue.
83//  offset  - the position before stack pointer subtraction indicating where
84//            the first saved register on prologue is located. (e.g. with a
85//
86//  Consider the following function prologue:
87//
88//    .frame  $fp,48,$ra
89//    .mask   0xc0000000,-8
90//       addiu $sp, $sp, -48
91//       sw $ra, 40($sp)
92//       sw $fp, 36($sp)
93//
94//    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
95//    30 (FP) are saved at prologue. As the save order on prologue is from
96//    left to right, RA is saved first. A -8 offset means that after the
97//    stack pointer subtration, the first register in the mask (RA) will be
98//    saved at address 48-8=40.
99//
100//===----------------------------------------------------------------------===//
101
102//===----------------------------------------------------------------------===//
103// Mask directives
104//===----------------------------------------------------------------------===//
105
106// Create a bitmask with all callee saved registers for CPU or Floating Point
107// registers. For CPU registers consider RA, GP and FP for saving if necessary.
108void MipsAsmPrinter::printSavedRegsBitmask(raw_ostream &O) {
109  // CPU and FPU Saved Registers Bitmasks
110  unsigned CPUBitmask = 0, FPUBitmask = 0;
111  int CPUTopSavedRegOff, FPUTopSavedRegOff;
112
113  // Set the CPU and FPU Bitmasks
114  const MachineFrameInfo *MFI = MF->getFrameInfo();
115  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
116  // size of stack area to which FP callee-saved regs are saved.
117  unsigned CPURegSize = Mips::CPURegsRegClass.getSize();
118  unsigned FGR32RegSize = Mips::FGR32RegClass.getSize();
119  unsigned AFGR64RegSize = Mips::AFGR64RegClass.getSize();
120  bool HasAFGR64Reg = false;
121  unsigned CSFPRegsSize = 0;
122  unsigned i, e = CSI.size();
123
124  // Set FPU Bitmask.
125  for (i = 0; i != e; ++i) {
126    unsigned Reg = CSI[i].getReg();
127    if (Mips::CPURegsRegClass.contains(Reg))
128      break;
129
130    unsigned RegNum = getMipsRegisterNumbering(Reg);
131    if (Mips::AFGR64RegClass.contains(Reg)) {
132      FPUBitmask |= (3 << RegNum);
133      CSFPRegsSize += AFGR64RegSize;
134      HasAFGR64Reg = true;
135      continue;
136    }
137
138    FPUBitmask |= (1 << RegNum);
139    CSFPRegsSize += FGR32RegSize;
140  }
141
142  // Set CPU Bitmask.
143  for (; i != e; ++i) {
144    unsigned Reg = CSI[i].getReg();
145    unsigned RegNum = getMipsRegisterNumbering(Reg);
146    CPUBitmask |= (1 << RegNum);
147  }
148
149  // FP Regs are saved right below where the virtual frame pointer points to.
150  FPUTopSavedRegOff = FPUBitmask ?
151    (HasAFGR64Reg ? -AFGR64RegSize : -FGR32RegSize) : 0;
152
153  // CPU Regs are saved below FP Regs.
154  CPUTopSavedRegOff = CPUBitmask ? -CSFPRegsSize - CPURegSize : 0;
155
156  // Print CPUBitmask
157  O << "\t.mask \t"; printHex32(CPUBitmask, O);
158  O << ',' << CPUTopSavedRegOff << '\n';
159
160  // Print FPUBitmask
161  O << "\t.fmask\t"; printHex32(FPUBitmask, O);
162  O << "," << FPUTopSavedRegOff << '\n';
163}
164
165// Print a 32 bit hex number with all numbers.
166void MipsAsmPrinter::printHex32(unsigned Value, raw_ostream &O) {
167  O << "0x";
168  for (int i = 7; i >= 0; i--)
169    O.write_hex((Value & (0xF << (i*4))) >> (i*4));
170}
171
172//===----------------------------------------------------------------------===//
173// Frame and Set directives
174//===----------------------------------------------------------------------===//
175
176/// Frame Directive
177void MipsAsmPrinter::emitFrameDirective() {
178  const TargetRegisterInfo &RI = *TM.getRegisterInfo();
179
180  unsigned stackReg  = RI.getFrameRegister(*MF);
181  unsigned returnReg = RI.getRARegister();
182  unsigned stackSize = MF->getFrameInfo()->getStackSize();
183
184  if (OutStreamer.hasRawTextSupport())
185    OutStreamer.EmitRawText("\t.frame\t$" +
186           StringRef(MipsInstPrinter::getRegisterName(stackReg)).lower() +
187           "," + Twine(stackSize) + ",$" +
188           StringRef(MipsInstPrinter::getRegisterName(returnReg)).lower());
189}
190
191/// Emit Set directives.
192const char *MipsAsmPrinter::getCurrentABIString() const {
193  switch (Subtarget->getTargetABI()) {
194  case MipsSubtarget::O32:  return "abi32";
195  case MipsSubtarget::N32:  return "abiN32";
196  case MipsSubtarget::N64:  return "abi64";
197  case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
198  default: llvm_unreachable("Unknown Mips ABI");;
199  }
200}
201
202void MipsAsmPrinter::EmitFunctionEntryLabel() {
203  if (OutStreamer.hasRawTextSupport()) {
204    if (Subtarget->inMips16Mode())
205      OutStreamer.EmitRawText(StringRef("\t.set\tmips16"));
206    else
207      OutStreamer.EmitRawText(StringRef("\t.set\tnomips16"));
208    // leave out until FSF available gas has micromips changes
209    // OutStreamer.EmitRawText(StringRef("\t.set\tnomicromips"));
210    OutStreamer.EmitRawText("\t.ent\t" + Twine(CurrentFnSym->getName()));
211  }
212  OutStreamer.EmitLabel(CurrentFnSym);
213}
214
215/// EmitFunctionBodyStart - Targets can override this to emit stuff before
216/// the first basic block in the function.
217void MipsAsmPrinter::EmitFunctionBodyStart() {
218  MCInstLowering.Initialize(Mang, &MF->getContext());
219
220  emitFrameDirective();
221
222  if (OutStreamer.hasRawTextSupport()) {
223    SmallString<128> Str;
224    raw_svector_ostream OS(Str);
225    printSavedRegsBitmask(OS);
226    OutStreamer.EmitRawText(OS.str());
227
228    OutStreamer.EmitRawText(StringRef("\t.set\tnoreorder"));
229    OutStreamer.EmitRawText(StringRef("\t.set\tnomacro"));
230    if (MipsFI->getEmitNOAT())
231      OutStreamer.EmitRawText(StringRef("\t.set\tnoat"));
232  }
233
234  if ((MF->getTarget().getRelocationModel() == Reloc::PIC_) &&
235      Subtarget->isABI_O32() && MipsFI->globalBaseRegSet()) {
236    SmallVector<MCInst, 4> MCInsts;
237    MCInstLowering.LowerSETGP01(MCInsts);
238    for (SmallVector<MCInst, 4>::iterator I = MCInsts.begin();
239         I != MCInsts.end(); ++I)
240      OutStreamer.EmitInstruction(*I);
241  }
242}
243
244/// EmitFunctionBodyEnd - Targets can override this to emit stuff after
245/// the last basic block in the function.
246void MipsAsmPrinter::EmitFunctionBodyEnd() {
247  // There are instruction for this macros, but they must
248  // always be at the function end, and we can't emit and
249  // break with BB logic.
250  if (OutStreamer.hasRawTextSupport()) {
251    if (MipsFI->getEmitNOAT())
252      OutStreamer.EmitRawText(StringRef("\t.set\tat"));
253
254    OutStreamer.EmitRawText(StringRef("\t.set\tmacro"));
255    OutStreamer.EmitRawText(StringRef("\t.set\treorder"));
256    OutStreamer.EmitRawText("\t.end\t" + Twine(CurrentFnSym->getName()));
257  }
258}
259
260/// isBlockOnlyReachableByFallthough - Return true if the basic block has
261/// exactly one predecessor and the control transfer mechanism between
262/// the predecessor and this block is a fall-through.
263bool MipsAsmPrinter::isBlockOnlyReachableByFallthrough(const MachineBasicBlock*
264                                                       MBB) const {
265  // The predecessor has to be immediately before this block.
266  const MachineBasicBlock *Pred = *MBB->pred_begin();
267
268  // If the predecessor is a switch statement, assume a jump table
269  // implementation, so it is not a fall through.
270  if (const BasicBlock *bb = Pred->getBasicBlock())
271    if (isa<SwitchInst>(bb->getTerminator()))
272      return false;
273
274  // If this is a landing pad, it isn't a fall through.  If it has no preds,
275  // then nothing falls through to it.
276  if (MBB->isLandingPad() || MBB->pred_empty())
277    return false;
278
279  // If there isn't exactly one predecessor, it can't be a fall through.
280  MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), PI2 = PI;
281  ++PI2;
282
283  if (PI2 != MBB->pred_end())
284    return false;
285
286  // The predecessor has to be immediately before this block.
287  if (!Pred->isLayoutSuccessor(MBB))
288    return false;
289
290  // If the block is completely empty, then it definitely does fall through.
291  if (Pred->empty())
292    return true;
293
294  // Otherwise, check the last instruction.
295  // Check if the last terminator is an unconditional branch.
296  MachineBasicBlock::const_iterator I = Pred->end();
297  while (I != Pred->begin() && !(--I)->isTerminator()) ;
298
299  return !I->isBarrier();
300}
301
302// Print out an operand for an inline asm expression.
303bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNum,
304                                     unsigned AsmVariant,const char *ExtraCode,
305                                     raw_ostream &O) {
306  // Does this asm operand have a single letter operand modifier?
307  if (ExtraCode && ExtraCode[0]) {
308    if (ExtraCode[1] != 0) return true; // Unknown modifier.
309
310    const MachineOperand &MO = MI->getOperand(OpNum);
311    switch (ExtraCode[0]) {
312    default:
313      return true;  // Unknown modifier.
314    case 'X': // hex const int
315      if ((MO.getType()) != MachineOperand::MO_Immediate)
316        return true;
317      O << "0x" << StringRef(utohexstr(MO.getImm())).lower();
318      return false;
319    case 'x': // hex const int (low 16 bits)
320      if ((MO.getType()) != MachineOperand::MO_Immediate)
321        return true;
322      O << "0x" << StringRef(utohexstr(MO.getImm() & 0xffff)).lower();
323      return false;
324    case 'd': // decimal const int
325      if ((MO.getType()) != MachineOperand::MO_Immediate)
326        return true;
327      O << MO.getImm();
328      return false;
329    case 'm': // decimal const int minus 1
330      if ((MO.getType()) != MachineOperand::MO_Immediate)
331        return true;
332      O << MO.getImm() - 1;
333      return false;
334    }
335  }
336
337  printOperand(MI, OpNum, O);
338  return false;
339}
340
341bool MipsAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
342                                           unsigned OpNum, unsigned AsmVariant,
343                                           const char *ExtraCode,
344                                           raw_ostream &O) {
345  if (ExtraCode && ExtraCode[0])
346     return true; // Unknown modifier.
347
348  const MachineOperand &MO = MI->getOperand(OpNum);
349  assert(MO.isReg() && "unexpected inline asm memory operand");
350  O << "0($" << MipsInstPrinter::getRegisterName(MO.getReg()) << ")";
351  return false;
352}
353
354void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum,
355                                  raw_ostream &O) {
356  const MachineOperand &MO = MI->getOperand(opNum);
357  bool closeP = false;
358
359  if (MO.getTargetFlags())
360    closeP = true;
361
362  switch(MO.getTargetFlags()) {
363  case MipsII::MO_GPREL:    O << "%gp_rel("; break;
364  case MipsII::MO_GOT_CALL: O << "%call16("; break;
365  case MipsII::MO_GOT:      O << "%got(";    break;
366  case MipsII::MO_ABS_HI:   O << "%hi(";     break;
367  case MipsII::MO_ABS_LO:   O << "%lo(";     break;
368  case MipsII::MO_TLSGD:    O << "%tlsgd(";  break;
369  case MipsII::MO_GOTTPREL: O << "%gottprel("; break;
370  case MipsII::MO_TPREL_HI: O << "%tprel_hi("; break;
371  case MipsII::MO_TPREL_LO: O << "%tprel_lo("; break;
372  case MipsII::MO_GPOFF_HI: O << "%hi(%neg(%gp_rel("; break;
373  case MipsII::MO_GPOFF_LO: O << "%lo(%neg(%gp_rel("; break;
374  case MipsII::MO_GOT_DISP: O << "%got_disp("; break;
375  case MipsII::MO_GOT_PAGE: O << "%got_page("; break;
376  case MipsII::MO_GOT_OFST: O << "%got_ofst("; break;
377  }
378
379  switch (MO.getType()) {
380    case MachineOperand::MO_Register:
381      O << '$'
382        << StringRef(MipsInstPrinter::getRegisterName(MO.getReg())).lower();
383      break;
384
385    case MachineOperand::MO_Immediate:
386      O << MO.getImm();
387      break;
388
389    case MachineOperand::MO_MachineBasicBlock:
390      O << *MO.getMBB()->getSymbol();
391      return;
392
393    case MachineOperand::MO_GlobalAddress:
394      O << *Mang->getSymbol(MO.getGlobal());
395      break;
396
397    case MachineOperand::MO_BlockAddress: {
398      MCSymbol* BA = GetBlockAddressSymbol(MO.getBlockAddress());
399      O << BA->getName();
400      break;
401    }
402
403    case MachineOperand::MO_ExternalSymbol:
404      O << *GetExternalSymbolSymbol(MO.getSymbolName());
405      break;
406
407    case MachineOperand::MO_JumpTableIndex:
408      O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
409        << '_' << MO.getIndex();
410      break;
411
412    case MachineOperand::MO_ConstantPoolIndex:
413      O << MAI->getPrivateGlobalPrefix() << "CPI"
414        << getFunctionNumber() << "_" << MO.getIndex();
415      if (MO.getOffset())
416        O << "+" << MO.getOffset();
417      break;
418
419    default:
420      llvm_unreachable("<unknown operand type>");
421  }
422
423  if (closeP) O << ")";
424}
425
426void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum,
427                                      raw_ostream &O) {
428  const MachineOperand &MO = MI->getOperand(opNum);
429  if (MO.isImm())
430    O << (unsigned short int)MO.getImm();
431  else
432    printOperand(MI, opNum, O);
433}
434
435void MipsAsmPrinter::
436printMemOperand(const MachineInstr *MI, int opNum, raw_ostream &O) {
437  // Load/Store memory operands -- imm($reg)
438  // If PIC target the target is loaded as the
439  // pattern lw $25,%call16($28)
440  printOperand(MI, opNum+1, O);
441  O << "(";
442  printOperand(MI, opNum, O);
443  O << ")";
444}
445
446void MipsAsmPrinter::
447printMemOperandEA(const MachineInstr *MI, int opNum, raw_ostream &O) {
448  // when using stack locations for not load/store instructions
449  // print the same way as all normal 3 operand instructions.
450  printOperand(MI, opNum, O);
451  O << ", ";
452  printOperand(MI, opNum+1, O);
453  return;
454}
455
456void MipsAsmPrinter::
457printFCCOperand(const MachineInstr *MI, int opNum, raw_ostream &O,
458                const char *Modifier) {
459  const MachineOperand& MO = MI->getOperand(opNum);
460  O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
461}
462
463void MipsAsmPrinter::EmitStartOfAsmFile(Module &M) {
464  // FIXME: Use SwitchSection.
465
466  // Tell the assembler which ABI we are using
467  if (OutStreamer.hasRawTextSupport())
468    OutStreamer.EmitRawText("\t.section .mdebug." +
469                            Twine(getCurrentABIString()));
470
471  // TODO: handle O64 ABI
472  if (OutStreamer.hasRawTextSupport()) {
473    if (Subtarget->isABI_EABI()) {
474      if (Subtarget->isGP32bit())
475        OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long32"));
476      else
477        OutStreamer.EmitRawText(StringRef("\t.section .gcc_compiled_long64"));
478    }
479  }
480
481  // return to previous section
482  if (OutStreamer.hasRawTextSupport())
483    OutStreamer.EmitRawText(StringRef("\t.previous"));
484}
485
486MachineLocation
487MipsAsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
488  // Handles frame addresses emitted in MipsInstrInfo::emitFrameIndexDebugValue.
489  assert(MI->getNumOperands() == 4 && "Invalid no. of machine operands!");
490  assert(MI->getOperand(0).isReg() && MI->getOperand(1).isImm() &&
491         "Unexpected MachineOperand types");
492  return MachineLocation(MI->getOperand(0).getReg(),
493                         MI->getOperand(1).getImm());
494}
495
496void MipsAsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
497                                           raw_ostream &OS) {
498  // TODO: implement
499}
500
501// Force static initialization.
502extern "C" void LLVMInitializeMipsAsmPrinter() {
503  RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
504  RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
505  RegisterAsmPrinter<MipsAsmPrinter> A(TheMips64Target);
506  RegisterAsmPrinter<MipsAsmPrinter> B(TheMips64elTarget);
507}
508