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