now that MCSymbol::print doesn't use it's MAI argument, we can
[oota-llvm.git] / lib / Target / Sparc / AsmPrinter / SparcAsmPrinter.cpp
1 //===-- SparcAsmPrinter.cpp - Sparc 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 SPARC assembly language.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #define DEBUG_TYPE "asm-printer"
16 #include "Sparc.h"
17 #include "SparcInstrInfo.h"
18 #include "SparcTargetMachine.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Module.h"
22 #include "llvm/CodeGen/AsmPrinter.h"
23 #include "llvm/CodeGen/DwarfWriter.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineConstantPool.h"
26 #include "llvm/CodeGen/MachineInstr.h"
27 #include "llvm/MC/MCAsmInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Target/TargetLoweringObjectFile.h"
31 #include "llvm/Target/TargetRegistry.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/FormattedStream.h"
37 #include "llvm/Support/MathExtras.h"
38 #include <cctype>
39 #include <cstring>
40 #include <map>
41 using namespace llvm;
42
43 STATISTIC(EmittedInsts, "Number of machine instrs printed");
44
45 namespace {
46   class SparcAsmPrinter : public AsmPrinter {
47     /// We name each basic block in a Function with a unique number, so
48     /// that we can consistently refer to them later. This is cleared
49     /// at the beginning of each call to runOnMachineFunction().
50     ///
51     typedef std::map<const Value *, unsigned> ValueMapTy;
52     ValueMapTy NumberForBB;
53     unsigned BBNumber;
54   public:
55     explicit SparcAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
56                              const MCAsmInfo *T, bool V)
57       : AsmPrinter(O, TM, T, V), BBNumber(0) {}
58
59     virtual const char *getPassName() const {
60       return "Sparc Assembly Printer";
61     }
62
63     void PrintGlobalVariable(const GlobalVariable *GVar);
64     void printOperand(const MachineInstr *MI, int opNum);
65     void printMemOperand(const MachineInstr *MI, int opNum,
66                          const char *Modifier = 0);
67     void printCCOperand(const MachineInstr *MI, int opNum);
68
69     void printInstruction(const MachineInstr *MI);  // autogenerated.
70     static const char *getRegisterName(unsigned RegNo);
71
72     bool runOnMachineFunction(MachineFunction &F);
73     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
74                        unsigned AsmVariant, const char *ExtraCode);
75     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
76                              unsigned AsmVariant, const char *ExtraCode);
77
78     void emitFunctionHeader(const MachineFunction &MF);
79     bool printGetPCX(const MachineInstr *MI, unsigned OpNo);
80   };
81 } // end of anonymous namespace
82
83 #include "SparcGenAsmWriter.inc"
84
85 /// runOnMachineFunction - This uses the printInstruction()
86 /// method to print assembly for each instruction.
87 ///
88 bool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
89   this->MF = &MF;
90
91   SetupMachineFunction(MF);
92
93   // Print out constants referenced by the function
94   EmitConstantPool(MF.getConstantPool());
95
96   // BBNumber is used here so that a given Printer will never give two
97   // BBs the same name. (If you have a better way, please let me know!)
98
99   O << "\n\n";
100   emitFunctionHeader(MF);
101   
102   
103   // Emit pre-function debug information.
104   DW->BeginFunction(&MF);
105
106   // Number each basic block so that we can consistently refer to them
107   // in PC-relative references.
108   // FIXME: Why not use the MBB numbers?
109   NumberForBB.clear();
110   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
111        I != E; ++I) {
112     NumberForBB[I->getBasicBlock()] = BBNumber++;
113   }
114
115   // Print out code for the function.
116   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
117        I != E; ++I) {
118     // Print a label for the basic block.
119     if (I != MF.begin()) {
120       EmitBasicBlockStart(I);
121     }
122     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
123          II != E; ++II) {
124       // Print the assembly for the instruction.
125       processDebugLoc(II, true);
126       printInstruction(II);
127       
128       if (VerboseAsm)
129         EmitComments(*II);
130       O << '\n';
131       processDebugLoc(II, false);
132       ++EmittedInsts;
133     }
134   }
135
136   // Emit post-function debug information.
137   DW->EndFunction(&MF);
138
139   // We didn't modify anything.
140   O << "\t.size\t" << *CurrentFnSym << ", .-" << *CurrentFnSym << '\n';
141   return false;
142 }
143
144 void SparcAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
145   const Function *F = MF.getFunction();
146   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
147   EmitAlignment(MF.getAlignment(), F);
148   
149   switch (F->getLinkage()) {
150   default: llvm_unreachable("Unknown linkage type");
151   case Function::PrivateLinkage:
152   case Function::InternalLinkage:
153     // Function is internal.
154     break;
155   case Function::DLLExportLinkage:
156   case Function::ExternalLinkage:
157     // Function is externally visible
158     O << "\t.global\t" << *CurrentFnSym << '\n';
159     break;
160   case Function::LinkerPrivateLinkage:
161   case Function::LinkOnceAnyLinkage:
162   case Function::LinkOnceODRLinkage:
163   case Function::WeakAnyLinkage:
164   case Function::WeakODRLinkage:
165     // Function is weak
166     O << "\t.weak\t" << *CurrentFnSym << '\n';
167     break;
168   }
169   
170   printVisibility(CurrentFnSym, F->getVisibility());
171   
172   O << "\t.type\t" << *CurrentFnSym << ", #function\n";
173   O << *CurrentFnSym << ":\n";
174 }
175
176
177 void SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
178   const MachineOperand &MO = MI->getOperand (opNum);
179   bool CloseParen = false;
180   if (MI->getOpcode() == SP::SETHIi && !MO.isReg() && !MO.isImm()) {
181     O << "%hi(";
182     CloseParen = true;
183   } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri) &&
184              !MO.isReg() && !MO.isImm()) {
185     O << "%lo(";
186     CloseParen = true;
187   }
188   switch (MO.getType()) {
189   case MachineOperand::MO_Register:
190     O << "%" << LowercaseString(getRegisterName(MO.getReg()));
191     break;
192
193   case MachineOperand::MO_Immediate:
194     O << (int)MO.getImm();
195     break;
196   case MachineOperand::MO_MachineBasicBlock:
197     O << *GetMBBSymbol(MO.getMBB()->getNumber());
198     return;
199   case MachineOperand::MO_GlobalAddress:
200     O << *GetGlobalValueSymbol(MO.getGlobal());
201     break;
202   case MachineOperand::MO_ExternalSymbol:
203     O << MO.getSymbolName();
204     break;
205   case MachineOperand::MO_ConstantPoolIndex:
206     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
207       << MO.getIndex();
208     break;
209   default:
210     llvm_unreachable("<unknown operand type>");
211   }
212   if (CloseParen) O << ")";
213 }
214
215 void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
216                                       const char *Modifier) {
217   printOperand(MI, opNum);
218
219   // If this is an ADD operand, emit it like normal operands.
220   if (Modifier && !strcmp(Modifier, "arith")) {
221     O << ", ";
222     printOperand(MI, opNum+1);
223     return;
224   }
225
226   if (MI->getOperand(opNum+1).isReg() &&
227       MI->getOperand(opNum+1).getReg() == SP::G0)
228     return;   // don't print "+%g0"
229   if (MI->getOperand(opNum+1).isImm() &&
230       MI->getOperand(opNum+1).getImm() == 0)
231     return;   // don't print "+0"
232
233   O << "+";
234   if (MI->getOperand(opNum+1).isGlobal() ||
235       MI->getOperand(opNum+1).isCPI()) {
236     O << "%lo(";
237     printOperand(MI, opNum+1);
238     O << ")";
239   } else {
240     printOperand(MI, opNum+1);
241   }
242 }
243
244 bool SparcAsmPrinter::printGetPCX(const MachineInstr *MI, unsigned opNum) {
245   std::string operand = "";
246   const MachineOperand &MO = MI->getOperand(opNum);
247   switch (MO.getType()) {
248   default: assert(0 && "Operand is not a register ");
249   case MachineOperand::MO_Register:
250     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
251            "Operand is not a physical register ");
252     operand = "%" + LowercaseString(getRegisterName(MO.getReg()));
253     break;
254   }
255
256   unsigned bbNum = NumberForBB[MI->getParent()->getBasicBlock()];
257
258   O << '\n' << ".LLGETPCH" << bbNum << ":\n";
259   O << "\tcall\t.LLGETPC" << bbNum << '\n' ;
260
261   O << "\t  sethi\t"
262     << "%hi(_GLOBAL_OFFSET_TABLE_+(.-.LLGETPCH" << bbNum << ")), "  
263     << operand << '\n' ;
264
265   O << ".LLGETPC" << bbNum << ":\n" ;
266   O << "\tor\t" << operand  
267     << ", %lo(_GLOBAL_OFFSET_TABLE_+(.-.LLGETPCH" << bbNum << ")), "
268     << operand << '\n';
269   O << "\tadd\t" << operand << ", %o7, " << operand << '\n'; 
270   
271   return true;
272 }
273
274 void SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
275   int CC = (int)MI->getOperand(opNum).getImm();
276   O << SPARCCondCodeToString((SPCC::CondCodes)CC);
277 }
278
279 void SparcAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
280   const TargetData *TD = TM.getTargetData();
281
282   if (!GVar->hasInitializer())
283     return;  // External global require no code
284
285   // Check to see if this is a special global used by LLVM, if so, emit it.
286   if (EmitSpecialLLVMGlobal(GVar))
287     return;
288
289   O << "\n\n";
290   MCSymbol *GVarSym = GetGlobalValueSymbol(GVar);
291   Constant *C = GVar->getInitializer();
292   unsigned Size = TD->getTypeAllocSize(C->getType());
293   unsigned Align = TD->getPreferredAlignment(GVar);
294
295   printVisibility(GVarSym, GVar->getVisibility());
296
297   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
298                                                                   TM));
299
300   if (C->isNullValue() && !GVar->hasSection()) {
301     if (!GVar->isThreadLocal() &&
302         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
303       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
304
305       if (GVar->hasLocalLinkage()) {
306         O << "\t.local " << *GVarSym << '\n';
307       }
308
309       O << MAI->getCOMMDirective() << *GVarSym << ',' << Size;
310       if (MAI->getCOMMDirectiveTakesAlignment())
311         O << ',' << (1 << Align);
312
313       O << '\n';
314       return;
315     }
316   }
317
318   switch (GVar->getLinkage()) {
319    case GlobalValue::CommonLinkage:
320    case GlobalValue::LinkOnceAnyLinkage:
321    case GlobalValue::LinkOnceODRLinkage:
322    case GlobalValue::WeakAnyLinkage: // FIXME: Verify correct for weak.
323    case GlobalValue::WeakODRLinkage: // FIXME: Verify correct for weak.
324     // Nonnull linkonce -> weak
325     O << "\t.weak " << *GVarSym << '\n';
326     break;
327    case GlobalValue::AppendingLinkage:
328     // FIXME: appending linkage variables should go into a section of
329     // their name or something.  For now, just emit them as external.
330    case GlobalValue::ExternalLinkage:
331     // If external or appending, declare as a global symbol
332     O << MAI->getGlobalDirective() << *GVarSym << '\n';
333     // FALL THROUGH
334    case GlobalValue::PrivateLinkage:
335    case GlobalValue::LinkerPrivateLinkage:
336    case GlobalValue::InternalLinkage:
337     break;
338    case GlobalValue::GhostLinkage:
339     llvm_unreachable("Should not have any unmaterialized functions!");
340    case GlobalValue::DLLImportLinkage:
341     llvm_unreachable("DLLImport linkage is not supported by this target!");
342    case GlobalValue::DLLExportLinkage:
343     llvm_unreachable("DLLExport linkage is not supported by this target!");
344    default:
345     llvm_unreachable("Unknown linkage type!");
346   }
347
348   EmitAlignment(Align, GVar);
349
350   if (MAI->hasDotTypeDotSizeDirective()) {
351     O << "\t.type " << *GVarSym << ",#object\n";
352     O << "\t.size " << *GVarSym << ',' << Size << '\n';
353   }
354
355   O << *GVarSym << ":\n";
356   EmitGlobalConstant(C);
357 }
358
359 /// PrintAsmOperand - Print out an operand for an inline asm expression.
360 ///
361 bool SparcAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
362                                       unsigned AsmVariant,
363                                       const char *ExtraCode) {
364   if (ExtraCode && ExtraCode[0]) {
365     if (ExtraCode[1] != 0) return true; // Unknown modifier.
366
367     switch (ExtraCode[0]) {
368     default: return true;  // Unknown modifier.
369     case 'r':
370      break;
371     }
372   }
373
374   printOperand(MI, OpNo);
375
376   return false;
377 }
378
379 bool SparcAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
380                                             unsigned OpNo,
381                                             unsigned AsmVariant,
382                                             const char *ExtraCode) {
383   if (ExtraCode && ExtraCode[0])
384     return true;  // Unknown modifier
385
386   O << '[';
387   printMemOperand(MI, OpNo);
388   O << ']';
389
390   return false;
391 }
392
393 // Force static initialization.
394 extern "C" void LLVMInitializeSparcAsmPrinter() { 
395   RegisterAsmPrinter<SparcAsmPrinter> X(TheSparcTarget);
396 }