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