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