Move DebugInfo checks into EmitComments and remove them from
[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/Support/Mangler.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/Support/Debug.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/FormattedStream.h"
46 #include "llvm/Support/MathExtras.h"
47 #include <cctype>
48
49 using namespace llvm;
50
51 STATISTIC(EmittedInsts, "Number of machine instrs printed");
52
53 namespace {
54   class MipsAsmPrinter : public AsmPrinter {
55     const MipsSubtarget *Subtarget;
56   public:
57     explicit MipsAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM, 
58                             const MCAsmInfo *T, bool V)
59       : AsmPrinter(O, TM, T, V) {
60       Subtarget = &TM.getSubtarget<MipsSubtarget>();
61     }
62
63     virtual const char *getPassName() const {
64       return "Mips Assembly Printer";
65     }
66
67     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 
68                          unsigned AsmVariant, const char *ExtraCode);
69     void printOperand(const MachineInstr *MI, int opNum);
70     void printUnsignedImm(const MachineInstr *MI, int opNum);
71     void printMemOperand(const MachineInstr *MI, int opNum, 
72                          const char *Modifier = 0);
73     void printFCCOperand(const MachineInstr *MI, int opNum, 
74                          const char *Modifier = 0);
75     void PrintGlobalVariable(const GlobalVariable *GVar);
76     void printSavedRegsBitmask(MachineFunction &MF);
77     void printHex32(unsigned int Value);
78
79     const char *emitCurrentABIString();
80     void emitFunctionStart(MachineFunction &MF);
81     void emitFunctionEnd(MachineFunction &MF);
82     void emitFrameDirective(MachineFunction &MF);
83
84     void printInstruction(const MachineInstr *MI);  // autogenerated.
85     static const char *getRegisterName(unsigned RegNo);
86
87     bool runOnMachineFunction(MachineFunction &F);
88     void EmitStartOfAsmFile(Module &M);
89   };
90 } // end of anonymous namespace
91
92 #include "MipsGenAsmWriter.inc"
93
94 //===----------------------------------------------------------------------===//
95 //
96 //  Mips Asm Directives
97 //
98 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
99 //  Describe the stack frame.
100 //
101 //  -- Mask directives "(f)mask  bitmask, offset" 
102 //  Tells the assembler which registers are saved and where.
103 //  bitmask - contain a little endian bitset indicating which registers are 
104 //            saved on function prologue (e.g. with a 0x80000000 mask, the 
105 //            assembler knows the register 31 (RA) is saved at prologue.
106 //  offset  - the position before stack pointer subtraction indicating where 
107 //            the first saved register on prologue is located. (e.g. with a
108 //
109 //  Consider the following function prologue:
110 //
111 //    .frame  $fp,48,$ra
112 //    .mask   0xc0000000,-8
113 //       addiu $sp, $sp, -48
114 //       sw $ra, 40($sp)
115 //       sw $fp, 36($sp)
116 //
117 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and 
118 //    30 (FP) are saved at prologue. As the save order on prologue is from 
119 //    left to right, RA is saved first. A -8 offset means that after the 
120 //    stack pointer subtration, the first register in the mask (RA) will be
121 //    saved at address 48-8=40.
122 //
123 //===----------------------------------------------------------------------===//
124
125 //===----------------------------------------------------------------------===//
126 // Mask directives
127 //===----------------------------------------------------------------------===//
128
129 // Create a bitmask with all callee saved registers for CPU or Floating Point 
130 // registers. For CPU registers consider RA, GP and FP for saving if necessary.
131 void MipsAsmPrinter::
132 printSavedRegsBitmask(MachineFunction &MF)
133 {
134   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
135   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
136              
137   // CPU and FPU Saved Registers Bitmasks
138   unsigned int CPUBitmask = 0;
139   unsigned int FPUBitmask = 0;
140
141   // Set the CPU and FPU Bitmasks
142   MachineFrameInfo *MFI = MF.getFrameInfo();
143   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
144   for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
145     unsigned RegNum = MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg());
146     if (CSI[i].getRegClass() == Mips::CPURegsRegisterClass)
147       CPUBitmask |= (1 << RegNum);
148     else
149       FPUBitmask |= (1 << RegNum);
150   }
151
152   // Return Address and Frame registers must also be set in CPUBitmask.
153   if (RI.hasFP(MF)) 
154     CPUBitmask |= (1 << MipsRegisterInfo::
155                 getRegisterNumbering(RI.getFrameRegister(MF)));
156   
157   if (MF.getFrameInfo()->hasCalls()) 
158     CPUBitmask |= (1 << MipsRegisterInfo::
159                 getRegisterNumbering(RI.getRARegister()));
160
161   // Print CPUBitmask
162   O << "\t.mask \t"; printHex32(CPUBitmask); O << ','
163     << MipsFI->getCPUTopSavedRegOff() << '\n';
164
165   // Print FPUBitmask
166   O << "\t.fmask\t"; printHex32(FPUBitmask); O << ","
167     << MipsFI->getFPUTopSavedRegOff() << '\n';
168 }
169
170 // Print a 32 bit hex number with all numbers.
171 void MipsAsmPrinter::
172 printHex32(unsigned int Value) 
173 {
174   O << "0x";
175   for (int i = 7; i >= 0; i--) 
176     O << utohexstr( (Value & (0xF << (i*4))) >> (i*4) );
177 }
178
179 //===----------------------------------------------------------------------===//
180 // Frame and Set directives
181 //===----------------------------------------------------------------------===//
182
183 /// Frame Directive
184 void MipsAsmPrinter::emitFrameDirective(MachineFunction &MF) {
185   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
186
187   unsigned stackReg  = RI.getFrameRegister(MF);
188   unsigned returnReg = RI.getRARegister();
189   unsigned stackSize = MF.getFrameInfo()->getStackSize();
190
191
192   O << "\t.frame\t" << '$' << LowercaseString(getRegisterName(stackReg))
193                     << ',' << stackSize << ','
194                     << '$' << LowercaseString(getRegisterName(returnReg))
195                     << '\n';
196 }
197
198 /// Emit Set directives.
199 const char *MipsAsmPrinter::emitCurrentABIString() {  
200   switch(Subtarget->getTargetABI()) {
201     case MipsSubtarget::O32:  return "abi32";  
202     case MipsSubtarget::O64:  return "abiO64";
203     case MipsSubtarget::N32:  return "abiN32";
204     case MipsSubtarget::N64:  return "abi64";
205     case MipsSubtarget::EABI: return "eabi32"; // TODO: handle eabi64
206     default: break;
207   }
208
209   llvm_unreachable("Unknown Mips ABI");
210   return NULL;
211 }  
212
213 /// Emit the directives used by GAS on the start of functions
214 void MipsAsmPrinter::emitFunctionStart(MachineFunction &MF) {
215   // Print out the label for the function.
216   const Function *F = MF.getFunction();
217   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
218
219   // 2 bits aligned
220   EmitAlignment(MF.getAlignment(), F);
221
222   O << "\t.globl\t"  << CurrentFnName << '\n';
223   O << "\t.ent\t"    << CurrentFnName << '\n';
224
225   printVisibility(CurrentFnName, F->getVisibility());
226
227   if ((MAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
228     O << "\t.type\t"   << CurrentFnName << ", @function\n";
229
230   O << CurrentFnName << ":\n";
231
232   emitFrameDirective(MF);
233   printSavedRegsBitmask(MF);
234
235   O << '\n';
236 }
237
238 /// Emit the directives used by GAS on the end of functions
239 void MipsAsmPrinter::emitFunctionEnd(MachineFunction &MF) {
240   // There are instruction for this macros, but they must
241   // always be at the function end, and we can't emit and
242   // break with BB logic. 
243   O << "\t.set\tmacro\n"; 
244   O << "\t.set\treorder\n"; 
245
246   O << "\t.end\t" << CurrentFnName << '\n';
247   if (MAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
248     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
249 }
250
251 /// runOnMachineFunction - This uses the printMachineInstruction()
252 /// method to print assembly for each instruction.
253 bool MipsAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
254   this->MF = &MF;
255
256   SetupMachineFunction(MF);
257
258   // Print out constants referenced by the function
259   EmitConstantPool(MF.getConstantPool());
260
261   // Print out jump tables referenced by the function
262   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
263
264   O << "\n\n";
265
266   // Emit the function start directives
267   emitFunctionStart(MF);
268
269   // Print out code for the function.
270   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
271        I != E; ++I) {
272
273     // Print a label for the basic block.
274     if (I != MF.begin()) {
275       EmitBasicBlockStart(I);
276     }
277
278     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
279          II != E; ++II) {
280       processDebugLoc(II, true);
281
282       // Print the assembly for the instruction.
283       printInstruction(II);
284       
285       if (VerboseAsm)
286         EmitComments(*II);
287       O << '\n';
288
289       processDebugLoc(II, false);      
290       ++EmittedInsts;
291     }
292
293     // Each Basic Block is separated by a newline
294     O << '\n';
295   }
296
297   // Emit function end directives
298   emitFunctionEnd(MF);
299
300   // We didn't modify anything.
301   return false;
302 }
303
304 // Print out an operand for an inline asm expression.
305 bool MipsAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 
306                                      unsigned AsmVariant,const char *ExtraCode){
307   // Does this asm operand have a single letter operand modifier?
308   if (ExtraCode && ExtraCode[0]) 
309     return true; // Unknown modifier.
310
311   printOperand(MI, OpNo);
312   return false;
313 }
314
315 void MipsAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
316   const MachineOperand &MO = MI->getOperand(opNum);
317   bool closeP = false;
318
319   if (MO.getTargetFlags())
320     closeP = true;
321
322   switch(MO.getTargetFlags()) {
323   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
324   case MipsII::MO_GOT_CALL: O << "%call16("; break;
325   case MipsII::MO_GOT:
326     if (MI->getOpcode() == Mips::LW)
327       O << "%got(";
328     else
329       O << "%lo(";
330     break;
331   case MipsII::MO_ABS_HILO:
332     if (MI->getOpcode() == Mips::LUi)
333       O << "%hi(";
334     else
335       O << "%lo(";     
336     break;
337   }
338
339   switch (MO.getType()) {
340     case MachineOperand::MO_Register:
341       O << '$' << LowercaseString(getRegisterName(MO.getReg()));
342       break;
343
344     case MachineOperand::MO_Immediate:
345       O << (short int)MO.getImm();
346       break;
347
348     case MachineOperand::MO_MachineBasicBlock:
349       GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
350       return;
351
352     case MachineOperand::MO_GlobalAddress:
353       O << Mang->getMangledName(MO.getGlobal());
354       break;
355
356     case MachineOperand::MO_ExternalSymbol:
357       O << MO.getSymbolName();
358       break;
359
360     case MachineOperand::MO_JumpTableIndex:
361       O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
362       << '_' << MO.getIndex();
363       break;
364
365     case MachineOperand::MO_ConstantPoolIndex:
366       O << MAI->getPrivateGlobalPrefix() << "CPI"
367         << getFunctionNumber() << "_" << MO.getIndex();
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   std::string name = Mang->getMangledName(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(name, 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" << name << '\n';
468
469       O << MAI->getCOMMDirective() << name << ',' << 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 " << name << '\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() << name << '\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 " << name << ",@object\n";
514     O << "\t.size " << name << ',' << Size << '\n';
515   }
516
517   O << name << ":\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 }