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