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