add a AsmPrinter::GetGlobalValueSymbol and GetExternalSymbolSymbol
[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/Mangler.h"
38 #include "llvm/Support/MathExtras.h"
39 #include <cctype>
40 #include <cstring>
41 #include <map>
42 using namespace llvm;
43
44 STATISTIC(EmittedInsts, "Number of machine instrs printed");
45
46 namespace {
47   class SparcAsmPrinter : public AsmPrinter {
48     /// We name each basic block in a Function with a unique number, so
49     /// that we can consistently refer to them later. This is cleared
50     /// at the beginning of each call to runOnMachineFunction().
51     ///
52     typedef std::map<const Value *, unsigned> ValueMapTy;
53     ValueMapTy NumberForBB;
54     unsigned BBNumber;
55   public:
56     explicit SparcAsmPrinter(formatted_raw_ostream &O, TargetMachine &TM,
57                              const MCAsmInfo *T, bool V)
58       : AsmPrinter(O, TM, T, V), BBNumber(0) {}
59
60     virtual const char *getPassName() const {
61       return "Sparc Assembly Printer";
62     }
63
64     void PrintGlobalVariable(const GlobalVariable *GVar);
65     void printOperand(const MachineInstr *MI, int opNum);
66     void printMemOperand(const MachineInstr *MI, int opNum,
67                          const char *Modifier = 0);
68     void printCCOperand(const MachineInstr *MI, int opNum);
69
70     void printInstruction(const MachineInstr *MI);  // autogenerated.
71     static const char *getRegisterName(unsigned RegNo);
72
73     bool runOnMachineFunction(MachineFunction &F);
74     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
75                        unsigned AsmVariant, const char *ExtraCode);
76     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
77                              unsigned AsmVariant, const char *ExtraCode);
78
79     void emitFunctionHeader(const MachineFunction &MF);
80     bool printGetPCX(const MachineInstr *MI, unsigned OpNo);
81   };
82 } // end of anonymous namespace
83
84 #include "SparcGenAsmWriter.inc"
85
86 /// runOnMachineFunction - This uses the printInstruction()
87 /// method to print assembly for each instruction.
88 ///
89 bool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
90   this->MF = &MF;
91
92   SetupMachineFunction(MF);
93
94   // Print out constants referenced by the function
95   EmitConstantPool(MF.getConstantPool());
96
97   // BBNumber is used here so that a given Printer will never give two
98   // BBs the same name. (If you have a better way, please let me know!)
99
100   O << "\n\n";
101   emitFunctionHeader(MF);
102   
103   
104   // Emit pre-function debug information.
105   DW->BeginFunction(&MF);
106
107   // Number each basic block so that we can consistently refer to them
108   // in PC-relative references.
109   // FIXME: Why not use the MBB numbers?
110   NumberForBB.clear();
111   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
112        I != E; ++I) {
113     NumberForBB[I->getBasicBlock()] = BBNumber++;
114   }
115
116   // Print out code for the function.
117   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
118        I != E; ++I) {
119     // Print a label for the basic block.
120     if (I != MF.begin()) {
121       EmitBasicBlockStart(I);
122     }
123     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
124          II != E; ++II) {
125       // Print the assembly for the instruction.
126       processDebugLoc(II, true);
127       printInstruction(II);
128       
129       if (VerboseAsm)
130         EmitComments(*II);
131       O << '\n';
132       processDebugLoc(II, false);
133       ++EmittedInsts;
134     }
135   }
136
137   // Emit post-function debug information.
138   DW->EndFunction(&MF);
139
140   // We didn't modify anything.
141   O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
142   return false;
143 }
144
145 void SparcAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
146   const Function *F = MF.getFunction();
147   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
148   EmitAlignment(MF.getAlignment(), F);
149   
150   switch (F->getLinkage()) {
151   default: llvm_unreachable("Unknown linkage type");
152   case Function::PrivateLinkage:
153   case Function::InternalLinkage:
154     // Function is internal.
155     break;
156   case Function::DLLExportLinkage:
157   case Function::ExternalLinkage:
158     // Function is externally visible
159     O << "\t.global\t" << CurrentFnName << '\n';
160     break;
161   case Function::LinkerPrivateLinkage:
162   case Function::LinkOnceAnyLinkage:
163   case Function::LinkOnceODRLinkage:
164   case Function::WeakAnyLinkage:
165   case Function::WeakODRLinkage:
166     // Function is weak
167     O << "\t.weak\t" << CurrentFnName << '\n' ;
168     break;
169   }
170   
171   printVisibility(CurrentFnName, F->getVisibility());
172   
173   O << "\t.type\t" << CurrentFnName << ", #function\n";
174   O << CurrentFnName << ":\n";
175 }
176
177
178 void SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
179   const MachineOperand &MO = MI->getOperand (opNum);
180   bool CloseParen = false;
181   if (MI->getOpcode() == SP::SETHIi && !MO.isReg() && !MO.isImm()) {
182     O << "%hi(";
183     CloseParen = true;
184   } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri) &&
185              !MO.isReg() && !MO.isImm()) {
186     O << "%lo(";
187     CloseParen = true;
188   }
189   switch (MO.getType()) {
190   case MachineOperand::MO_Register:
191     O << "%" << LowercaseString(getRegisterName(MO.getReg()));
192     break;
193
194   case MachineOperand::MO_Immediate:
195     O << (int)MO.getImm();
196     break;
197   case MachineOperand::MO_MachineBasicBlock:
198     GetMBBSymbol(MO.getMBB()->getNumber())->print(O, MAI);
199     return;
200   case MachineOperand::MO_GlobalAddress:
201     GetGlobalValueSymbol(MO.getGlobal())->print(O, MAI);
202     break;
203   case MachineOperand::MO_ExternalSymbol:
204     O << MO.getSymbolName();
205     break;
206   case MachineOperand::MO_ConstantPoolIndex:
207     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
208       << MO.getIndex();
209     break;
210   default:
211     llvm_unreachable("<unknown operand type>");
212   }
213   if (CloseParen) O << ")";
214 }
215
216 void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
217                                       const char *Modifier) {
218   printOperand(MI, opNum);
219
220   // If this is an ADD operand, emit it like normal operands.
221   if (Modifier && !strcmp(Modifier, "arith")) {
222     O << ", ";
223     printOperand(MI, opNum+1);
224     return;
225   }
226
227   if (MI->getOperand(opNum+1).isReg() &&
228       MI->getOperand(opNum+1).getReg() == SP::G0)
229     return;   // don't print "+%g0"
230   if (MI->getOperand(opNum+1).isImm() &&
231       MI->getOperand(opNum+1).getImm() == 0)
232     return;   // don't print "+0"
233
234   O << "+";
235   if (MI->getOperand(opNum+1).isGlobal() ||
236       MI->getOperand(opNum+1).isCPI()) {
237     O << "%lo(";
238     printOperand(MI, opNum+1);
239     O << ")";
240   } else {
241     printOperand(MI, opNum+1);
242   }
243 }
244
245 bool SparcAsmPrinter::printGetPCX(const MachineInstr *MI, unsigned opNum) {
246   std::string operand = "";
247   const MachineOperand &MO = MI->getOperand(opNum);
248   switch (MO.getType()) {
249   default: assert(0 && "Operand is not a register ");
250   case MachineOperand::MO_Register:
251     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
252            "Operand is not a physical register ");
253     operand = "%" + LowercaseString(getRegisterName(MO.getReg()));
254     break;
255   }
256
257   unsigned bbNum = NumberForBB[MI->getParent()->getBasicBlock()];
258
259   O << '\n' << ".LLGETPCH" << bbNum << ":\n";
260   O << "\tcall\t.LLGETPC" << bbNum << '\n' ;
261
262   O << "\t  sethi\t"
263     << "%hi(_GLOBAL_OFFSET_TABLE_+(.-.LLGETPCH" << bbNum << ")), "  
264     << operand << '\n' ;
265
266   O << ".LLGETPC" << bbNum << ":\n" ;
267   O << "\tor\t" << operand  
268     << ", %lo(_GLOBAL_OFFSET_TABLE_+(.-.LLGETPCH" << bbNum << ")), "
269     << operand << '\n';
270   O << "\tadd\t" << operand << ", %o7, " << operand << '\n'; 
271   
272   return true;
273 }
274
275 void SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
276   int CC = (int)MI->getOperand(opNum).getImm();
277   O << SPARCCondCodeToString((SPCC::CondCodes)CC);
278 }
279
280 void SparcAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
281   const TargetData *TD = TM.getTargetData();
282
283   if (!GVar->hasInitializer())
284     return;  // External global require no code
285
286   // Check to see if this is a special global used by LLVM, if so, emit it.
287   if (EmitSpecialLLVMGlobal(GVar))
288     return;
289
290   O << "\n\n";
291   std::string name = Mang->getMangledName(GVar);
292   Constant *C = GVar->getInitializer();
293   unsigned Size = TD->getTypeAllocSize(C->getType());
294   unsigned Align = TD->getPreferredAlignment(GVar);
295
296   printVisibility(name, GVar->getVisibility());
297
298   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(GVar, Mang,
299                                                                   TM));
300
301   if (C->isNullValue() && !GVar->hasSection()) {
302     if (!GVar->isThreadLocal() &&
303         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
304       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
305
306       if (GVar->hasLocalLinkage())
307         O << "\t.local " << name << '\n';
308
309       O << MAI->getCOMMDirective() << name << ',' << 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 " << name << '\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() << name << '\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 " << name << ",#object\n";
352     O << "\t.size " << name << ',' << Size << '\n';
353   }
354
355   O << name << ":\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 }