Introduce new headers whose inclusion forces linking and
[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/Target/TargetAsmInfo.h"
32 #include "llvm/Target/TargetData.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include "llvm/Target/TargetOptions.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/MathExtras.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include <cctype>
43
44 using namespace llvm;
45
46 STATISTIC(EmittedInsts, "Number of machine instrs printed");
47
48 namespace {
49   class VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
50     const MipsSubtarget *Subtarget;
51   public:
52     explicit MipsAsmPrinter(raw_ostream &O, MipsTargetMachine &TM, 
53                             const TargetAsmInfo *T, CodeGenOpt::Level OL,
54                             bool V)
55       : AsmPrinter(O, TM, T, OL, V) {
56       Subtarget = &TM.getSubtarget<MipsSubtarget>();
57     }
58
59     virtual const char *getPassName() const {
60       return "Mips Assembly Printer";
61     }
62
63     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo, 
64                          unsigned AsmVariant, const char *ExtraCode);
65     void printOperand(const MachineInstr *MI, int opNum);
66     void printUnsignedImm(const MachineInstr *MI, int opNum);
67     void printMemOperand(const MachineInstr *MI, int opNum, 
68                          const char *Modifier = 0);
69     void printFCCOperand(const MachineInstr *MI, int opNum, 
70                          const char *Modifier = 0);
71     void printModuleLevelGV(const GlobalVariable* GVar);
72     void printSavedRegsBitmask(MachineFunction &MF);
73     void printHex32(unsigned int Value);
74
75     const char *emitCurrentABIString(void);
76     void emitFunctionStart(MachineFunction &MF);
77     void emitFunctionEnd(MachineFunction &MF);
78     void emitFrameDirective(MachineFunction &MF);
79
80     bool printInstruction(const MachineInstr *MI);  // autogenerated.
81     bool runOnMachineFunction(MachineFunction &F);
82     bool doInitialization(Module &M);
83     bool doFinalization(Module &M);
84   };
85 } // end of anonymous namespace
86
87 #include "MipsGenAsmWriter.inc"
88
89 /// createMipsCodePrinterPass - Returns a pass that prints the MIPS
90 /// assembly code for a MachineFunction to the given output stream,
91 /// using the given target machine description.  This should work
92 /// regardless of whether the function is in SSA form.
93 FunctionPass *llvm::createMipsCodePrinterPass(raw_ostream &o,
94                                               MipsTargetMachine &tm,
95                                               CodeGenOpt::Level OptLevel,
96                                               bool verbose) {
97   return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo(), OptLevel, 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(2, 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       O << "<unknown operand type>"; abort (); break;
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   const Type *CTy = C->getType();
487   unsigned Size = TD->getTypeAllocSize(CTy);
488   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
489   bool printSizeAndType = true;
490
491   // A data structure or array is aligned in memory to the largest
492   // alignment boundary required by any data type inside it (this matches
493   // the Preferred Type Alignment). For integral types, the alignment is
494   // the type size.
495   unsigned Align;
496   if (CTy->getTypeID() == Type::IntegerTyID ||
497       CTy->getTypeID() == Type::VoidTyID) {
498     assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
499     Align = Log2_32(Size);
500   } else
501     Align = TD->getPreferredTypeAlignmentShift(CTy);
502
503   printVisibility(name, GVar->getVisibility());
504
505   SwitchToSection(TAI->SectionForGlobal(GVar));
506
507   if (C->isNullValue() && !GVar->hasSection()) {
508     if (!GVar->isThreadLocal() &&
509         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
510       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
511
512       if (GVar->hasLocalLinkage())
513         O << "\t.local\t" << name << '\n';
514
515       O << TAI->getCOMMDirective() << name << ',' << Size;
516       if (TAI->getCOMMDirectiveTakesAlignment())
517         O << ',' << (1 << Align);
518
519       O << '\n';
520       return;
521     }
522   }
523   switch (GVar->getLinkage()) {
524    case GlobalValue::LinkOnceAnyLinkage:
525    case GlobalValue::LinkOnceODRLinkage:
526    case GlobalValue::CommonLinkage:
527    case GlobalValue::WeakAnyLinkage:
528    case GlobalValue::WeakODRLinkage:
529     // FIXME: Verify correct for weak.
530     // Nonnull linkonce -> weak
531     O << "\t.weak " << name << '\n';
532     break;
533    case GlobalValue::AppendingLinkage:
534     // FIXME: appending linkage variables should go into a section of their name
535     // or something.  For now, just emit them as external.
536    case GlobalValue::ExternalLinkage:
537     // If external or appending, declare as a global symbol
538     O << TAI->getGlobalDirective() << name << '\n';
539     // Fall Through
540    case GlobalValue::PrivateLinkage:
541    case GlobalValue::InternalLinkage:
542     if (CVA && CVA->isCString())
543       printSizeAndType = false;
544     break;
545    case GlobalValue::GhostLinkage:
546     cerr << "Should not have any unmaterialized functions!\n";
547     abort();
548    case GlobalValue::DLLImportLinkage:
549     cerr << "DLLImport linkage is not supported by this target!\n";
550     abort();
551    case GlobalValue::DLLExportLinkage:
552     cerr << "DLLExport linkage is not supported by this target!\n";
553     abort();
554    default:
555     assert(0 && "Unknown linkage type!");
556   }
557
558   EmitAlignment(Align, GVar);
559
560   if (TAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
561     O << "\t.type " << name << ",@object\n";
562     O << "\t.size " << name << ',' << Size << '\n';
563   }
564
565   O << name << ":\n";
566   EmitGlobalConstant(C);
567 }
568
569 bool MipsAsmPrinter::
570 doFinalization(Module &M)
571 {
572   // Print out module-level global variables here.
573   for (Module::const_global_iterator I = M.global_begin(),
574          E = M.global_end(); I != E; ++I)
575     printModuleLevelGV(I);
576
577   O << '\n';
578
579   return AsmPrinter::doFinalization(M);
580 }
581
582 // Force static initialization when called from
583 // llvm/InitializeAllAsmPrinters.h
584 namespace llvm {
585   void InitializeMipsAsmPrinter() { }
586 }