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