convert some uses of printBasicBlockLabel to use GetMBBSymbol
[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 VISIBILITY_HIDDEN 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     bool runOnMachineFunction(MachineFunction &F);
86     bool doInitialization(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(RI.get(stackReg).AsmName)
191                     << ',' << stackSize << ','
192                     << '$' << LowercaseString(RI.get(returnReg).AsmName)
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"  << CurrentFnName << '\n';
221   O << "\t.ent\t"    << CurrentFnName << '\n';
222
223   printVisibility(CurrentFnName, F->getVisibility());
224
225   if ((MAI->hasDotTypeDotSizeDirective()) && Subtarget->isLinux())
226     O << "\t.type\t"   << CurrentFnName << ", @function\n";
227
228   O << CurrentFnName << ":\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" << CurrentFnName << '\n';
245   if (MAI->hasDotTypeDotSizeDirective() && !Subtarget->isLinux())
246     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\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       printBasicBlockLabel(I, true, true);
274       O << '\n';
275     }
276
277     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
278          II != E; ++II) {
279       processDebugLoc(II->getDebugLoc());
280
281       // Print the assembly for the instruction.
282       printInstruction(II);
283       
284       if (VerboseAsm && !II->getDebugLoc().isUnknown())
285         EmitComments(*II);
286       O << '\n';
287       
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   const TargetRegisterInfo  &RI = *TM.getRegisterInfo();
316   bool closeP = false;
317
318   if (MO.getTargetFlags())
319     closeP = true;
320
321   switch(MO.getTargetFlags()) {
322   case MipsII::MO_GPREL:    O << "%gp_rel("; break;
323   case MipsII::MO_GOT_CALL: O << "%call16("; break;
324   case MipsII::MO_GOT:
325     if (MI->getOpcode() == Mips::LW)
326       O << "%got(";
327     else
328       O << "%lo(";
329     break;
330   case MipsII::MO_ABS_HILO:
331     if (MI->getOpcode() == Mips::LUi)
332       O << "%hi(";
333     else
334       O << "%lo(";     
335     break;
336   }
337
338   switch (MO.getType()) 
339   {
340     case MachineOperand::MO_Register:
341       if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
342         O << '$' << LowercaseString (RI.get(MO.getReg()).AsmName);
343       else
344         O << '$' << MO.getReg();
345       break;
346
347     case MachineOperand::MO_Immediate:
348       O << (short int)MO.getImm();
349       break;
350
351     case MachineOperand::MO_MachineBasicBlock:
352       GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
353       return;
354
355     case MachineOperand::MO_GlobalAddress:
356       O << Mang->getMangledName(MO.getGlobal());
357       break;
358
359     case MachineOperand::MO_ExternalSymbol:
360       O << MO.getSymbolName();
361       break;
362
363     case MachineOperand::MO_JumpTableIndex:
364       O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
365       << '_' << MO.getIndex();
366       break;
367
368     case MachineOperand::MO_ConstantPoolIndex:
369       O << MAI->getPrivateGlobalPrefix() << "CPI"
370         << getFunctionNumber() << "_" << MO.getIndex();
371       break;
372   
373     default:
374       llvm_unreachable("<unknown operand type>");
375   }
376
377   if (closeP) O << ")";
378 }
379
380 void MipsAsmPrinter::printUnsignedImm(const MachineInstr *MI, int opNum) {
381   const MachineOperand &MO = MI->getOperand(opNum);
382   if (MO.getType() == MachineOperand::MO_Immediate)
383     O << (unsigned short int)MO.getImm();
384   else 
385     printOperand(MI, opNum);
386 }
387
388 void MipsAsmPrinter::
389 printMemOperand(const MachineInstr *MI, int opNum, const char *Modifier) {
390   // when using stack locations for not load/store instructions
391   // print the same way as all normal 3 operand instructions.
392   if (Modifier && !strcmp(Modifier, "stackloc")) {
393     printOperand(MI, opNum+1);
394     O << ", ";
395     printOperand(MI, opNum);
396     return;
397   }
398
399   // Load/Store memory operands -- imm($reg) 
400   // If PIC target the target is loaded as the 
401   // pattern lw $25,%call16($28)
402   printOperand(MI, opNum);
403   O << "(";
404   printOperand(MI, opNum+1);
405   O << ")";
406 }
407
408 void MipsAsmPrinter::
409 printFCCOperand(const MachineInstr *MI, int opNum, const char *Modifier) {
410   const MachineOperand& MO = MI->getOperand(opNum);
411   O << Mips::MipsFCCToString((Mips::CondCode)MO.getImm()); 
412 }
413
414 bool MipsAsmPrinter::doInitialization(Module &M) {
415   // FIXME: Use SwitchSection.
416   
417   // Tell the assembler which ABI we are using
418   O << "\t.section .mdebug." << emitCurrentABIString() << '\n';
419
420   // TODO: handle O64 ABI
421   if (Subtarget->isABI_EABI())
422     O << "\t.section .gcc_compiled_long" << 
423       (Subtarget->isGP32bit() ? "32" : "64") << '\n';
424
425   // return to previous section
426   O << "\t.previous" << '\n'; 
427
428   return AsmPrinter::doInitialization(M);
429 }
430
431 void MipsAsmPrinter::PrintGlobalVariable(const GlobalVariable *GVar) {
432   const TargetData *TD = TM.getTargetData();
433
434   if (!GVar->hasInitializer())
435     return;   // External global require no code
436
437   // Check to see if this is a special global used by LLVM, if so, emit it.
438   if (EmitSpecialLLVMGlobal(GVar))
439     return;
440
441   O << "\n\n";
442   std::string name = Mang->getMangledName(GVar);
443   Constant *C = GVar->getInitializer();
444   const Type *CTy = C->getType();
445   unsigned Size = TD->getTypeAllocSize(CTy);
446   const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
447   bool printSizeAndType = true;
448
449   // A data structure or array is aligned in memory to the largest
450   // alignment boundary required by any data type inside it (this matches
451   // the Preferred Type Alignment). For integral types, the alignment is
452   // the type size.
453   unsigned Align;
454   if (CTy->getTypeID() == Type::IntegerTyID ||
455       CTy->getTypeID() == Type::VoidTyID) {
456     assert(!(Size & (Size-1)) && "Alignment is not a power of two!");
457     Align = Log2_32(Size);
458   } else
459     Align = TD->getPreferredTypeAlignmentShift(CTy);
460
461   printVisibility(name, GVar->getVisibility());
462
463   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
464                                                                   TM));
465
466   if (C->isNullValue() && !GVar->hasSection()) {
467     if (!GVar->isThreadLocal() &&
468         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
469       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
470
471       if (GVar->hasLocalLinkage())
472         O << "\t.local\t" << name << '\n';
473
474       O << MAI->getCOMMDirective() << name << ',' << Size;
475       if (MAI->getCOMMDirectiveTakesAlignment())
476         O << ',' << (1 << Align);
477
478       O << '\n';
479       return;
480     }
481   }
482   switch (GVar->getLinkage()) {
483    case GlobalValue::LinkOnceAnyLinkage:
484    case GlobalValue::LinkOnceODRLinkage:
485    case GlobalValue::CommonLinkage:
486    case GlobalValue::WeakAnyLinkage:
487    case GlobalValue::WeakODRLinkage:
488     // FIXME: Verify correct for weak.
489     // Nonnull linkonce -> weak
490     O << "\t.weak " << name << '\n';
491     break;
492    case GlobalValue::AppendingLinkage:
493     // FIXME: appending linkage variables should go into a section of their name
494     // or something.  For now, just emit them as external.
495    case GlobalValue::ExternalLinkage:
496     // If external or appending, declare as a global symbol
497     O << MAI->getGlobalDirective() << name << '\n';
498     // Fall Through
499    case GlobalValue::PrivateLinkage:
500    case GlobalValue::LinkerPrivateLinkage:
501    case GlobalValue::InternalLinkage:
502     if (CVA && CVA->isCString())
503       printSizeAndType = false;
504     break;
505    case GlobalValue::GhostLinkage:
506     llvm_unreachable("Should not have any unmaterialized functions!");
507    case GlobalValue::DLLImportLinkage:
508     llvm_unreachable("DLLImport linkage is not supported by this target!");
509    case GlobalValue::DLLExportLinkage:
510     llvm_unreachable("DLLExport linkage is not supported by this target!");
511    default:
512     llvm_unreachable("Unknown linkage type!");
513   }
514
515   EmitAlignment(Align, GVar);
516
517   if (MAI->hasDotTypeDotSizeDirective() && printSizeAndType) {
518     O << "\t.type " << name << ",@object\n";
519     O << "\t.size " << name << ',' << Size << '\n';
520   }
521
522   O << name << ":\n";
523   EmitGlobalConstant(C);
524 }
525
526
527 // Force static initialization.
528 extern "C" void LLVMInitializeMipsAsmPrinter() { 
529   RegisterAsmPrinter<MipsAsmPrinter> X(TheMipsTarget);
530   RegisterAsmPrinter<MipsAsmPrinter> Y(TheMipselTarget);
531 }