MipsAsmPrinter.cpp revision 43d526d162c69f29a1cc6734014576eade49529b
1//===-- MipsAsmPrinter.cpp - Mips LLVM assembly writer --------------------===//
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
17#include "Mips.h"
18#include "MipsSubtarget.h"
19#include "MipsInstrInfo.h"
20#include "MipsTargetMachine.h"
21#include "MipsMachineFunction.h"
22#include "llvm/Constants.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Module.h"
25#include "llvm/CodeGen/AsmPrinter.h"
26#include "llvm/CodeGen/MachineFunctionPass.h"
27#include "llvm/CodeGen/MachineConstantPool.h"
28#include "llvm/CodeGen/MachineFrameInfo.h"
29#include "llvm/CodeGen/MachineInstr.h"
30#include "llvm/Target/TargetAsmInfo.h"
31#include "llvm/Target/TargetData.h"
32#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetOptions.h"
34#include "llvm/Support/Mangler.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/MathExtras.h"
40#include <cctype>
41
42using namespace llvm;
43
44STATISTIC(EmittedInsts, "Number of machine instrs printed");
45
46namespace {
47  struct VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
48
49    const MipsSubtarget *Subtarget;
50
51    MipsAsmPrinter(std::ostream &O, MipsTargetMachine &TM,
52                   const TargetAsmInfo *T):
53                   AsmPrinter(O, TM, T) {
54      Subtarget = &TM.getSubtarget<MipsSubtarget>();
55    }
56
57    virtual const char *getPassName() const {
58      return "Mips Assembly Printer";
59    }
60
61    void printOperand(const MachineInstr *MI, int opNum);
62    void printMemOperand(const MachineInstr *MI, int opNum,
63                         const char *Modifier = 0);
64    void printFCCOperand(const MachineInstr *MI, int opNum,
65                         const char *Modifier = 0);
66
67    unsigned int getSavedRegsBitmask(bool isFloat, MachineFunction &MF);
68    void printHex32(unsigned int Value);
69
70    const char *emitCurrentABIString(void);
71    void emitFunctionStart(MachineFunction &MF);
72    void emitFunctionEnd(MachineFunction &MF);
73    void emitFrameDirective(MachineFunction &MF);
74    void emitMaskDirective(MachineFunction &MF);
75    void emitFMaskDirective(MachineFunction &MF);
76
77    bool printInstruction(const MachineInstr *MI);  // autogenerated.
78    bool runOnMachineFunction(MachineFunction &F);
79    bool doInitialization(Module &M);
80    bool doFinalization(Module &M);
81  };
82} // end of anonymous namespace
83
84#include "MipsGenAsmWriter.inc"
85
86/// createMipsCodePrinterPass - Returns a pass that prints the MIPS
87/// assembly code for a MachineFunction to the given output stream,
88/// using the given target machine description.  This should work
89/// regardless of whether the function is in SSA form.
90FunctionPass *llvm::createMipsCodePrinterPass(std::ostream &o,
91                                              MipsTargetMachine &tm)
92{
93  return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo());
94}
95
96//===----------------------------------------------------------------------===//
97//
98//  Mips Asm Directives
99//
100//  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
101//  Describe the stack frame.
102//
103//  -- Mask directives "(f)mask  bitmask, offset"
104//  Tells the assembler which registers are saved and where.
105//  bitmask - contain a little endian bitset indicating which registers are
106//            saved on function prologue (e.g. with a 0x80000000 mask, the
107//            assembler knows the register 31 (RA) is saved at prologue.
108//  offset  - the position before stack pointer subtraction indicating where
109//            the first saved register on prologue is located. (e.g. with a
110//
111//  Consider the following function prologue:
112//
113//    .frame  $fp,48,$ra
114//    .mask   0xc0000000,-8
115//       addiu $sp, $sp, -48
116//       sw $ra, 40($sp)
117//       sw $fp, 36($sp)
118//
119//    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and
120//    30 (FP) are saved at prologue. As the save order on prologue is from
121//    left to right, RA is saved first. A -8 offset means that after the
122//    stack pointer subtration, the first register in the mask (RA) will be
123//    saved at address 48-8=40.
124//
125//===----------------------------------------------------------------------===//
126
127//===----------------------------------------------------------------------===//
128// Mask directives
129//===----------------------------------------------------------------------===//
130
131/// Mask directive for GPR
132void MipsAsmPrinter::
133emitMaskDirective(MachineFunction &MF)
134{
135  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
136
137  int StackSize = MF.getFrameInfo()->getStackSize();
138  int Offset    = (!MipsFI->getTopSavedRegOffset()) ? 0 :
139                  (-(StackSize-MipsFI->getTopSavedRegOffset()));
140
141  #ifndef NDEBUG
142  DOUT << "--> emitMaskDirective" << "\n";
143  DOUT << "StackSize :  " << StackSize << "\n";
144  DOUT << "getTopSavedReg : " << MipsFI->getTopSavedRegOffset() << "\n";
145  DOUT << "Offset : " << Offset << "\n\n";
146  #endif
147
148  unsigned int Bitmask = getSavedRegsBitmask(false, MF);
149  O << "\t.mask \t";
150  printHex32(Bitmask);
151  O << "," << Offset << "\n";
152}
153
154/// TODO: Mask Directive for Floating Point
155void MipsAsmPrinter::
156emitFMaskDirective(MachineFunction &MF)
157{
158  unsigned int Bitmask = getSavedRegsBitmask(true, MF);
159
160  O << "\t.fmask\t";
161  printHex32(Bitmask);
162  O << ",0" << "\n";
163}
164
165// Create a bitmask with all callee saved registers for CPU
166// or Floating Point registers. For CPU registers consider RA,
167// GP and FP for saving if necessary.
168unsigned int MipsAsmPrinter::
169getSavedRegsBitmask(bool isFloat, MachineFunction &MF)
170{
171  const TargetRegisterInfo &RI = *TM.getRegisterInfo();
172
173  // Floating Point Registers, TODO
174  if (isFloat)
175    return 0;
176
177  // CPU Registers
178  unsigned int Bitmask = 0;
179
180  MachineFrameInfo *MFI = MF.getFrameInfo();
181  const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
182  for (unsigned i = 0, e = CSI.size(); i != e; ++i)
183    Bitmask |= (1 << MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg()));
184
185  if (RI.hasFP(MF))
186    Bitmask |= (1 << MipsRegisterInfo::
187                getRegisterNumbering(RI.getFrameRegister(MF)));
188
189  if (MF.getFrameInfo()->hasCalls())
190    Bitmask |= (1 << MipsRegisterInfo::
191                getRegisterNumbering(RI.getRARegister()));
192
193  return Bitmask;
194}
195
196// Print a 32 bit hex number with all numbers.
197void MipsAsmPrinter::
198printHex32(unsigned int Value)
199{
200  O << "0x" << std::hex;
201  for (int i = 7; i >= 0; i--)
202    O << std::hex << ( (Value & (0xF << (i*4))) >> (i*4) );
203  O << std::dec;
204}
205
206//===----------------------------------------------------------------------===//
207// Frame and Set directives
208//===----------------------------------------------------------------------===//
209
210/// Frame Directive
211void MipsAsmPrinter::
212emitFrameDirective(MachineFunction &MF)
213{
214  const TargetRegisterInfo &RI = *TM.getRegisterInfo();
215
216  unsigned stackReg  = RI.getFrameRegister(MF);
217  unsigned returnReg = RI.getRARegister();
218  unsigned stackSize = MF.getFrameInfo()->getStackSize();
219
220
221  O << "\t.frame\t" << "$" << LowercaseString(RI.get(stackReg).AsmName)
222                    << "," << stackSize << ","
223                    << "$" << LowercaseString(RI.get(returnReg).AsmName)
224                    << "\n";
225}
226
227/// Emit Set directives.
228const char * MipsAsmPrinter::
229emitCurrentABIString(void)
230{
231  switch(Subtarget->getTargetABI()) {
232    case MipsSubtarget::O32:  return "abi32";
233    case MipsSubtarget::O64:  return "abiO64";
234    case MipsSubtarget::N32:  return "abiN32";
235    case MipsSubtarget::N64:  return "abi64";
236    case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
237    default: break;
238  }
239
240  assert(0 && "Unknown Mips ABI");
241  return NULL;
242}
243
244/// Emit the directives used by GAS on the start of functions
245void MipsAsmPrinter::
246emitFunctionStart(MachineFunction &MF)
247{
248  // Print out the label for the function.
249  const Function *F = MF.getFunction();
250  SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
251
252  // 2 bits aligned
253  EmitAlignment(2, F);
254
255  O << "\t.globl\t"  << CurrentFnName << "\n";
256  O << "\t.ent\t"    << CurrentFnName << "\n";
257
258  if ((TAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
259    O << "\t.type\t"   << CurrentFnName << ", @function\n";
260
261  O << CurrentFnName << ":\n";
262
263  emitFrameDirective(MF);
264  emitMaskDirective(MF);
265  emitFMaskDirective(MF);
266
267  O << "\n";
268}
269
270/// Emit the directives used by GAS on the end of functions
271void MipsAsmPrinter::
272emitFunctionEnd(MachineFunction &MF)
273{
274  // There are instruction for this macros, but they must
275  // always be at the function end, and we can't emit and
276  // break with BB logic.
277  O << "\t.set\tmacro\n";
278  O << "\t.set\treorder\n";
279
280  O << "\t.end\t" << CurrentFnName << "\n";
281  if (TAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
282    O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << "\n";
283}
284
285/// runOnMachineFunction - This uses the printMachineInstruction()
286/// method to print assembly for each instruction.
287bool MipsAsmPrinter::
288runOnMachineFunction(MachineFunction &MF)
289{
290  SetupMachineFunction(MF);
291
292  // Print out constants referenced by the function
293  EmitConstantPool(MF.getConstantPool());
294
295  // Print out jump tables referenced by the function
296  EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
297
298  O << "\n\n";
299
300  // What's my mangled name?
301  CurrentFnName = Mang->getValueName(MF.getFunction());
302
303  // Emit the function start directives
304  emitFunctionStart(MF);
305
306  // Print out code for the function.
307  for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
308       I != E; ++I) {
309
310    // Print a label for the basic block.
311    if (I != MF.begin()) {
312      printBasicBlockLabel(I, true, true);
313      O << '\n';
314    }
315
316    for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
317         II != E; ++II) {
318      // Print the assembly for the instruction.
319      printInstruction(II);
320      ++EmittedInsts;
321    }
322
323    // Each Basic Block is separated by a newline
324    O << '\n';
325  }
326
327  // Emit function end directives
328  emitFunctionEnd(MF);
329
330  // We didn't modify anything.
331  return false;
332}
333
334void MipsAsmPrinter::
335printOperand(const MachineInstr *MI, int opNum)
336{
337  const MachineOperand &MO = MI->getOperand(opNum);
338  const TargetRegisterInfo  &RI = *TM.getRegisterInfo();
339  bool closeP = false;
340  bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
341  bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
342
343  // %hi and %lo used on mips gas to load global addresses on
344  // static code. %got is used to load global addresses when
345  // using PIC_. %call16 is used to load direct call targets
346  // on PIC_ and small code size. %call_lo and %call_hi load
347  // direct call targets on PIC_ and large code size.
348  if (MI->getOpcode() == Mips::LUi && !MO.isRegister()
349      && !MO.isImmediate()) {
350    if ((isPIC) && (isCodeLarge))
351      O << "%call_hi(";
352    else
353      O << "%hi(";
354    closeP = true;
355  } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isRegister()
356             && !MO.isImmediate()) {
357    O << "%lo(";
358    closeP = true;
359  } else if ((isPIC) && (MI->getOpcode() == Mips::LW)
360             && (!MO.isRegister()) && (!MO.isImmediate())) {
361    const MachineOperand &firstMO = MI->getOperand(opNum-1);
362    const MachineOperand &lastMO  = MI->getOperand(opNum+1);
363    if ((firstMO.isRegister()) && (lastMO.isRegister())) {
364      if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP)
365          && (!isCodeLarge))
366        O << "%call16(";
367      else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
368        O << "%got(";
369      else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP)
370               && (isCodeLarge))
371        O << "%call_lo(";
372      closeP = true;
373    }
374  }
375
376  switch (MO.getType())
377  {
378    case MachineOperand::MO_Register:
379      if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
380        O << "$" << LowercaseString (RI.get(MO.getReg()).AsmName);
381      else
382        O << "$" << MO.getReg();
383      break;
384
385    case MachineOperand::MO_Immediate:
386      if ((MI->getOpcode() == Mips::SLTiu) || (MI->getOpcode() == Mips::ORi) ||
387          (MI->getOpcode() == Mips::LUi)   || (MI->getOpcode() == Mips::ANDi))
388        O << (unsigned short int)MO.getImm();
389      else
390        O << (short int)MO.getImm();
391      break;
392
393    case MachineOperand::MO_MachineBasicBlock:
394      printBasicBlockLabel(MO.getMBB());
395      return;
396
397    case MachineOperand::MO_GlobalAddress:
398      O << Mang->getValueName(MO.getGlobal());
399      break;
400
401    case MachineOperand::MO_ExternalSymbol:
402      O << MO.getSymbolName();
403      break;
404
405    case MachineOperand::MO_JumpTableIndex:
406      O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
407      << '_' << MO.getIndex();
408      break;
409
410    // FIXME: Verify correct
411    case MachineOperand::MO_ConstantPoolIndex:
412      O << TAI->getPrivateGlobalPrefix() << "CPI"
413        << getFunctionNumber() << "_" << MO.getIndex();
414      break;
415
416    default:
417      O << "<unknown operand type>"; abort (); break;
418  }
419
420  if (closeP) O << ")";
421}
422
423void MipsAsmPrinter::
424printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier)
425{
426  // when using stack locations for not load/store instructions
427  // print the same way as all normal 3 operand instructions.
428  if (Modifier && !strcmp(Modifier, "stackloc")) {
429    printOperand(MI, opNum+1);
430    O << ", ";
431    printOperand(MI, opNum);
432    return;
433  }
434
435  // Load/Store memory operands -- imm($reg)
436  // If PIC target the target is loaded as the
437  // pattern lw $25,%call16($28)
438  printOperand(MI, opNum);
439  O << "(";
440  printOperand(MI, opNum+1);
441  O << ")";
442}
443
444void MipsAsmPrinter::
445printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier)
446{
447  const MachineOperand& MO = MI->getOperand(opNum);
448  O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm());
449}
450
451bool MipsAsmPrinter::
452doInitialization(Module &M)
453{
454  Mang = new Mangler(M);
455
456  // Tell the assembler which ABI we are using
457  O << "\t.section .mdebug." << emitCurrentABIString() << "\n";
458
459  // TODO: handle O64 ABI
460  if (Subtarget->isABI_EABI())
461    O << "\t.section .gcc_compiled_long" <<
462      (Subtarget->isGP32bit() ? "32" : "64") << "\n";
463
464  // return to previous section
465  O << "\t.previous" << "\n";
466
467  return false; // success
468}
469
470bool MipsAsmPrinter::
471doFinalization(Module &M)
472{
473  const TargetData *TD = TM.getTargetData();
474
475  // Print out module-level global variables here.
476  for (Module::const_global_iterator I = M.global_begin(),
477         E = M.global_end(); I != E; ++I)
478
479    // External global require no code
480    if (I->hasInitializer()) {
481
482      // Check to see if this is a special global
483      // used by LLVM, if so, emit it.
484      if (EmitSpecialLLVMGlobal(I))
485        continue;
486
487      O << "\n\n";
488      std::string name = Mang->getValueName(I);
489      Constant *C      = I->getInitializer();
490      unsigned Size    = TD->getABITypeSize(C->getType());
491      unsigned Align   = TD->getPreferredAlignmentLog(I);
492
493      // Is this correct ?
494      if (C->isNullValue() && (I->hasLinkOnceLinkage() ||
495          I->hasInternalLinkage() || I->hasWeakLinkage() ||
496          I->hasCommonLinkage()))
497      {
498        if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
499
500        if (!NoZerosInBSS && TAI->getBSSSection())
501          SwitchToDataSection(TAI->getBSSSection(), I);
502        else
503          SwitchToDataSection(TAI->getDataSection(), I);
504
505        if (I->hasInternalLinkage()) {
506          if (TAI->getLCOMMDirective())
507            O << TAI->getLCOMMDirective() << name << "," << Size;
508          else
509            O << "\t.local\t" << name << "\n";
510        } else {
511          O << TAI->getCOMMDirective() << name << "," << Size;
512          // The .comm alignment in bytes.
513          if (TAI->getCOMMDirectiveTakesAlignment())
514            O << "," << (1 << Align);
515        }
516
517      } else {
518
519        switch (I->getLinkage())
520        {
521          case GlobalValue::LinkOnceLinkage:
522          case GlobalValue::CommonLinkage:
523          case GlobalValue::WeakLinkage:
524            // FIXME: Verify correct for weak.
525            // Nonnull linkonce -> weak
526            O << "\t.weak " << name << "\n";
527            SwitchToDataSection("", I);
528            O << "\t.section\t\".llvm.linkonce.d." << name
529                          << "\",\"aw\",@progbits\n";
530            break;
531          case GlobalValue::AppendingLinkage:
532            // FIXME: appending linkage variables
533            // should go into a section of  their name or
534            // something.  For now, just emit them as external.
535          case GlobalValue::ExternalLinkage:
536            // If external or appending, declare as a global symbol
537            O << TAI->getGlobalDirective() << name << "\n";
538            // Fall Through
539          case GlobalValue::InternalLinkage:
540            // FIXME: special handling for ".ctors" & ".dtors" sections
541            if (I->hasSection() && (I->getSection() == ".ctors" ||
542                I->getSection() == ".dtors")) {
543              std::string SectionName = ".section " + I->getSection();
544              SectionName += ",\"aw\",%progbits";
545              SwitchToDataSection(SectionName.c_str());
546            } else {
547              if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
548                SwitchToDataSection(TAI->getBSSSection(), I);
549              else if (!I->isConstant())
550                SwitchToDataSection(TAI->getDataSection(), I);
551              else {
552                // Read-only data.
553                if (TAI->getReadOnlySection())
554                  SwitchToDataSection(TAI->getReadOnlySection(), I);
555                else
556                  SwitchToDataSection(TAI->getDataSection(), I);
557              }
558            }
559            break;
560          case GlobalValue::GhostLinkage:
561            cerr << "Should not have any unmaterialized functions!\n";
562            abort();
563          case GlobalValue::DLLImportLinkage:
564            cerr << "DLLImport linkage is not supported by this target!\n";
565            abort();
566          case GlobalValue::DLLExportLinkage:
567            cerr << "DLLExport linkage is not supported by this target!\n";
568            abort();
569          default:
570            assert(0 && "Unknown linkage type!");
571        }
572
573        O << "\t.align " << Align << "\n";
574
575        if (TAI->hasDotTypeDotSizeDirective()) {
576          O << "\t.type " << name << ",@object\n";
577          O << "\t.size " << name << "," << Size << "\n";
578        }
579        O << name << ":\n";
580        EmitGlobalConstant(C);
581    }
582  }
583
584  O << "\n";
585
586  return AsmPrinter::doFinalization(M);
587}
588