Better processor definition
[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 was developed by Bruno Cardoso Lopes and is distributed under the 
6 // University of Illinois Open Source 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 "MipsInstrInfo.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsMachineFunction.h"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Module.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineConstantPool.h"
27 #include "llvm/CodeGen/MachineFrameInfo.h"
28 #include "llvm/CodeGen/MachineInstr.h"
29 #include "llvm/Target/TargetAsmInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Support/Mangler.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/ADT/SetVector.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/MathExtras.h"
39 #include <cctype>
40
41 using namespace llvm;
42
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
44
45 namespace {
46   struct VISIBILITY_HIDDEN MipsAsmPrinter : public AsmPrinter {
47     MipsAsmPrinter(std::ostream &O, MipsTargetMachine &TM, 
48                    const TargetAsmInfo *T): 
49                    AsmPrinter(O, TM, T) {}
50
51     virtual const char *getPassName() const {
52       return "Mips Assembly Printer";
53     }
54
55     enum SetDirectiveFlags {
56       REORDER,      // enables instruction reordering.
57       NOREORDER,    // disables instruction reordering.
58       MACRO,        // enables GAS macros.
59       NOMACRO       // disables GAS macros.
60     };
61
62     void printOperand(const MachineInstr *MI, int opNum);
63     void printMemOperand(const MachineInstr *MI, int opNum, 
64                          const char *Modifier = 0);
65
66     unsigned int getSavedRegsBitmask(bool isFloat, MachineFunction &MF);
67     void printHex32(unsigned int Value);
68
69     void emitFunctionStart(MachineFunction &MF);
70     void emitFunctionEnd(MachineFunction &MF);
71     void emitFrameDirective(MachineFunction &MF);
72     void emitMaskDirective(MachineFunction &MF);
73     void emitFMaskDirective(MachineFunction &MF);
74     void emitSetDirective(SetDirectiveFlags Flag);
75
76     bool printInstruction(const MachineInstr *MI);  // autogenerated.
77     bool runOnMachineFunction(MachineFunction &F);
78     bool doInitialization(Module &M);
79     bool doFinalization(Module &M);
80   };
81 } // end of anonymous namespace
82
83 #include "MipsGenAsmWriter.inc"
84
85 /// createMipsCodePrinterPass - Returns a pass that prints the MIPS
86 /// assembly code for a MachineFunction to the given output stream,
87 /// using the given target machine description.  This should work
88 /// regardless of whether the function is in SSA form.
89 FunctionPass *llvm::createMipsCodePrinterPass(std::ostream &o,
90                                               MipsTargetMachine &tm) 
91 {
92   return new MipsAsmPrinter(o, tm, tm.getTargetAsmInfo());
93 }
94
95 //===----------------------------------------------------------------------===//
96 //
97 //  Mips Asm Directives
98 //
99 //  -- Frame directive "frame Stackpointer, Stacksize, RARegister"
100 //  Describe the stack frame.
101 //
102 //  -- Mask directives "(f)mask  bitmask, offset" 
103 //  Tells the assembler which registers are saved and where.
104 //  bitmask - contain a little endian bitset indicating which registers are 
105 //            saved on function prologue (e.g. with a 0x80000000 mask, the 
106 //            assembler knows the register 31 (RA) is saved at prologue.
107 //  offset  - the position before stack pointer subtraction indicating where 
108 //            the first saved register on prologue is located. (e.g. with a
109 //
110 //  Consider the following function prologue:
111 //
112 //    .frame    $fp,48,$ra
113 //    .mask       0xc0000000,-8
114 //        addiu $sp, $sp, -48
115 //        sw $ra, 40($sp)
116 //        sw $fp, 36($sp)
117 //
118 //    With a 0xc0000000 mask, the assembler knows the register 31 (RA) and 
119 //    30 (FP) are saved at prologue. As the save order on prologue is from 
120 //    left to right, RA is saved first. A -8 offset means that after the 
121 //    stack pointer subtration, the first register in the mask (RA) will be
122 //    saved at address 48-8=40.
123 //
124 //===----------------------------------------------------------------------===//
125
126 /// Mask directive for GPR
127 void MipsAsmPrinter::
128 emitMaskDirective(MachineFunction &MF)
129 {
130   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
131
132   int StackSize = MF.getFrameInfo()->getStackSize();
133   int Offset    = (!MipsFI->getTopSavedRegOffset()) ? 0 : 
134                   (-(StackSize-MipsFI->getTopSavedRegOffset()));
135              
136   #ifndef NDEBUG
137   DOUT << "--> emitMaskDirective" << "\n";
138   DOUT << "StackSize :  " << StackSize << "\n";
139   DOUT << "getTopSavedReg : " << MipsFI->getTopSavedRegOffset() << "\n";
140   DOUT << "Offset : " << Offset << "\n\n";
141   #endif
142
143   unsigned int Bitmask = getSavedRegsBitmask(false, MF);
144   O << "\t.mask \t"; 
145   printHex32(Bitmask);
146   O << "," << Offset << "\n";
147 }
148
149 /// TODO: Mask Directive for Float Point
150 void MipsAsmPrinter::
151 emitFMaskDirective(MachineFunction &MF)
152 {
153   unsigned int Bitmask = getSavedRegsBitmask(true, MF);
154
155   O << "\t.fmask\t";
156   printHex32(Bitmask);
157   O << ",0" << "\n";
158 }
159
160 /// Frame Directive
161 void MipsAsmPrinter::
162 emitFrameDirective(MachineFunction &MF)
163 {
164   const MRegisterInfo &RI = *TM.getRegisterInfo();
165
166   unsigned stackReg  = RI.getFrameRegister(MF);
167   unsigned returnReg = RI.getRARegister();
168   unsigned stackSize = MF.getFrameInfo()->getStackSize();
169
170
171   O << "\t.frame\t" << "$" << LowercaseString(RI.get(stackReg).Name) 
172                     << "," << stackSize << ","
173                     << "$" << LowercaseString(RI.get(returnReg).Name) 
174                     << "\n";
175 }
176
177 /// Emit Set directives.
178 void MipsAsmPrinter::
179 emitSetDirective(SetDirectiveFlags Flag) 
180 {  
181   O << "\t.set\t";
182   switch(Flag) {
183       case REORDER:   O << "reorder" << "\n"; break;
184       case NOREORDER: O << "noreorder" << "\n"; break;
185       case MACRO:     O << "macro" << "\n"; break;
186       case NOMACRO:   O << "nomacro" << "\n"; break;
187       default: break;
188   }
189 }  
190
191 // Create a bitmask with all callee saved registers for CPU
192 // or Float Point registers. For CPU registers consider RA,
193 // GP and FP for saving if necessary.
194 unsigned int MipsAsmPrinter::
195 getSavedRegsBitmask(bool isFloat, MachineFunction &MF)
196 {
197   const MRegisterInfo &RI = *TM.getRegisterInfo();
198              
199   // Float Point Registers, TODO
200   if (isFloat)
201     return 0;
202
203   // CPU Registers
204   unsigned int Bitmask = 0;
205
206   MachineFrameInfo *MFI = MF.getFrameInfo();
207   const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
208   for (unsigned i = 0, e = CSI.size(); i != e; ++i)
209     Bitmask |= (1 << MipsRegisterInfo::getRegisterNumbering(CSI[i].getReg()));
210
211   if (RI.hasFP(MF)) 
212     Bitmask |= (1 << MipsRegisterInfo::
213                 getRegisterNumbering(RI.getFrameRegister(MF)));
214   
215   if (MF.getFrameInfo()->hasCalls()) 
216     Bitmask |= (1 << MipsRegisterInfo::
217                 getRegisterNumbering(RI.getRARegister()));
218
219   return Bitmask;
220 }
221
222 // Print a 32 bit hex number with all numbers.
223 void MipsAsmPrinter::
224 printHex32(unsigned int Value) 
225 {
226   O << "0x" << std::hex;
227   for (int i = 7; i >= 0; i--) 
228     O << std::hex << ( (Value & (0xF << (i*4))) >> (i*4) );
229   O << std::dec;
230 }
231
232 /// Emit the directives used by GAS on the start of functions
233 void MipsAsmPrinter::
234 emitFunctionStart(MachineFunction &MF)
235 {
236   // Print out the label for the function.
237   const Function *F = MF.getFunction();
238   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
239
240   // On Mips GAS, if .align #n is present, #n means the number of bits 
241   // to be cleared. So, if we want 4 byte alignment, we must have .align 2
242   EmitAlignment(1, F);
243
244   O << "\t.globl\t"  << CurrentFnName << "\n";
245   O << "\t.ent\t"    << CurrentFnName << "\n";
246   O << "\t.type\t"   << CurrentFnName << ", @function\n";
247   O << CurrentFnName << ":\n";
248
249   emitFrameDirective(MF);
250   emitMaskDirective(MF);
251   emitFMaskDirective(MF);
252
253   if (TM.getRelocationModel() == Reloc::Static) {
254     emitSetDirective(NOREORDER);
255     emitSetDirective(NOMACRO);
256   }
257
258   O << "\n";
259 }
260
261 /// Emit the directives used by GAS on the end of functions
262 void MipsAsmPrinter::
263 emitFunctionEnd(MachineFunction &MF) 
264 {
265   if (TM.getRelocationModel() == Reloc::Static) {
266     emitSetDirective(MACRO);
267     emitSetDirective(REORDER);
268   }    
269
270   O << "\t.end\t" << CurrentFnName << "\n";
271 }
272
273 /// runOnMachineFunction - This uses the printMachineInstruction()
274 /// method to print assembly for each instruction.
275 bool MipsAsmPrinter::
276 runOnMachineFunction(MachineFunction &MF) 
277 {
278   SetupMachineFunction(MF);
279
280   // Print out constants referenced by the function
281   EmitConstantPool(MF.getConstantPool());
282
283   O << "\n\n";
284
285   // What's my mangled name?
286   CurrentFnName = Mang->getValueName(MF.getFunction());
287
288   // Emit the function start directives
289   emitFunctionStart(MF);
290
291   // Print out code for the function.
292   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
293        I != E; ++I) {
294
295     // Print a label for the basic block.
296     if (I != MF.begin()) {
297       printBasicBlockLabel(I, true);
298       O << '\n';
299     }
300
301     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
302          II != E; ++II) {
303       // Print the assembly for the instruction.
304       O << "\t";
305       printInstruction(II);
306       ++EmittedInsts;
307     }
308
309     // Each Basic Block is separated by a newline
310     O << '\n';
311   }
312
313   // Emit function end directives
314   emitFunctionEnd(MF);
315
316   // We didn't modify anything.
317   return false;
318 }
319
320 void MipsAsmPrinter::
321 printOperand(const MachineInstr *MI, int opNum) 
322 {
323   const MachineOperand &MO = MI->getOperand(opNum);
324   const MRegisterInfo  &RI = *TM.getRegisterInfo();
325   bool closeP = false;
326   bool isPIC = (TM.getRelocationModel() == Reloc::PIC_);
327   bool isCodeLarge = (TM.getCodeModel() == CodeModel::Large);
328
329   // %hi and %lo used on mips gas to load global addresses on
330   // static code. %got is used to load global addresses when 
331   // using PIC_. %call16 is used to load direct call targets
332   // on PIC_ and small code size. %call_lo and %call_hi load 
333   // direct call targets on PIC_ and large code size.
334   if (MI->getOpcode() == Mips::LUi && !MO.isRegister() 
335       && !MO.isImmediate()) {
336     if ((isPIC) && (isCodeLarge))
337       O << "%call_hi(";
338     else
339       O << "%hi(";
340     closeP = true;
341   } else if ((MI->getOpcode() == Mips::ADDiu) && !MO.isRegister() 
342              && !MO.isImmediate()) {
343     O << "%lo(";
344     closeP = true;
345   } else if ((isPIC) && (MI->getOpcode() == Mips::LW)
346              && (!MO.isRegister()) && (!MO.isImmediate())) {
347     const MachineOperand &firstMO = MI->getOperand(opNum-1);
348     const MachineOperand &lastMO  = MI->getOperand(opNum+1);
349     if ((firstMO.isRegister()) && (lastMO.isRegister())) {
350       if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() == Mips::GP) 
351           && (!isCodeLarge))
352         O << "%call16(";
353       else if ((firstMO.getReg() != Mips::T9) && (lastMO.getReg() == Mips::GP))
354         O << "%got(";
355       else if ((firstMO.getReg() == Mips::T9) && (lastMO.getReg() != Mips::GP) 
356                && (isCodeLarge))
357         O << "%call_lo(";
358       closeP = true;
359     }
360   }
361  
362   switch (MO.getType()) 
363   {
364     case MachineOperand::MO_Register:
365       if (MRegisterInfo::isPhysicalRegister(MO.getReg()))
366         O << "$" << LowercaseString (RI.get(MO.getReg()).Name);
367       else
368         O << "$" << MO.getReg();
369       break;
370
371     case MachineOperand::MO_Immediate:
372       if ((MI->getOpcode() == Mips::SLTiu) || (MI->getOpcode() == Mips::ORi) || 
373           (MI->getOpcode() == Mips::LUi)   || (MI->getOpcode() == Mips::ANDi))
374         O << (unsigned short int)MO.getImmedValue();
375       else
376         O << (short int)MO.getImmedValue();
377       break;
378
379     case MachineOperand::MO_MachineBasicBlock:
380       printBasicBlockLabel(MO.getMachineBasicBlock());
381       return;
382
383     case MachineOperand::MO_GlobalAddress:
384       O << Mang->getValueName(MO.getGlobal());
385       break;
386
387     case MachineOperand::MO_ExternalSymbol:
388       O << MO.getSymbolName();
389       break;
390
391     // FIXME: Verify correct
392     case MachineOperand::MO_ConstantPoolIndex:
393       O << TAI->getPrivateGlobalPrefix() << "CPI"
394         << getFunctionNumber() << "_" << MO.getConstantPoolIndex();
395       break;
396   
397     default:
398       O << "<unknown operand type>"; abort (); break;
399   }
400
401   if (closeP) O << ")";
402 }
403
404 void MipsAsmPrinter::
405 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier) 
406 {
407   // when using stack locations for not load/store instructions
408   // print the same way as all normal 3 operand instructions.
409   if (Modifier && !strcmp(Modifier, "stackloc")) {
410     printOperand(MI, opNum+1);
411     O << ", ";
412     printOperand(MI, opNum);
413     return;
414   }
415
416   // Load/Store memory operands -- imm($reg) 
417   // If PIC target the target is loaded as the 
418   // pattern lw $25,%call16($28)
419   printOperand(MI, opNum);
420   O << "(";
421   printOperand(MI, opNum+1);
422   O << ")";
423 }
424
425 bool MipsAsmPrinter::
426 doInitialization(Module &M) 
427 {
428   Mang = new Mangler(M);
429   return false; // success
430 }
431
432 bool MipsAsmPrinter::
433 doFinalization(Module &M) 
434 {
435   const TargetData *TD = TM.getTargetData();
436
437   // Print out module-level global variables here.
438   for (Module::const_global_iterator I = M.global_begin(),
439          E = M.global_end(); I != E; ++I)
440
441     // External global require no code
442     if (I->hasInitializer()) {
443
444       // Check to see if this is a special global 
445       // used by LLVM, if so, emit it.
446       if (EmitSpecialLLVMGlobal(I))
447         continue;
448       
449       O << "\n\n";
450       std::string name = Mang->getValueName(I);
451       Constant *C      = I->getInitializer();
452       unsigned Size    = TD->getABITypeSize(C->getType());
453       unsigned Align   = TD->getPrefTypeAlignment(C->getType());
454
455       if (C->isNullValue() && (I->hasLinkOnceLinkage() || 
456         I->hasInternalLinkage() || I->hasWeakLinkage() 
457         /* FIXME: Verify correct */)) {
458
459         SwitchToDataSection(".data", I);
460         if (I->hasInternalLinkage())
461           O << "\t.local " << name << "\n";
462
463         O << "\t.comm " << name << "," 
464           << TD->getABITypeSize(C->getType())
465           << "," << Align << "\n";
466
467       } else {
468
469         switch (I->getLinkage()) 
470         {
471           case GlobalValue::LinkOnceLinkage:
472           case GlobalValue::WeakLinkage:   
473             // FIXME: Verify correct for weak.
474             // Nonnull linkonce -> weak
475             O << "\t.weak " << name << "\n";
476             SwitchToDataSection("", I);
477             O << "\t.section\t\".llvm.linkonce.d." << name
478                           << "\",\"aw\",@progbits\n";
479             break;
480           case GlobalValue::AppendingLinkage:
481             // FIXME: appending linkage variables 
482             // should go into a section of  their name or 
483             // something.  For now, just emit them as external.
484           case GlobalValue::ExternalLinkage:
485             // If external or appending, declare as a global symbol
486             O << "\t.globl " << name << "\n";
487           case GlobalValue::InternalLinkage:
488             if (C->isNullValue())
489               SwitchToDataSection(".bss", I);
490             else
491               SwitchToDataSection(".data", I);
492             break;
493           case GlobalValue::GhostLinkage:
494             cerr << "Should not have any" 
495                  << "unmaterialized functions!\n";
496             abort();
497           case GlobalValue::DLLImportLinkage:
498             cerr << "DLLImport linkage is" 
499                  << "not supported by this target!\n";
500             abort();
501           case GlobalValue::DLLExportLinkage:
502             cerr << "DLLExport linkage is" 
503                  << "not supported by this target!\n";
504             abort();
505           default:
506             assert(0 && "Unknown linkage type!");          
507         }
508
509         O << "\t.align " << Align << "\n";
510         O << "\t.type " << name << ",@object\n";
511         O << "\t.size " << name << "," << Size << "\n";
512         O << name << ":\n";
513         EmitGlobalConstant(C);
514     }
515   }
516
517   return AsmPrinter::doFinalization(M);
518 }