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