71bd0dee206854556599531ed3668daaa91a60f1
[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/Support/Mangler.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/Statistic.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/MathExtras.h"
35 #include <cctype>
36 #include <cstring>
37 #include <map>
38 using namespace llvm;
39
40 STATISTIC(EmittedInsts, "Number of machine instrs printed");
41
42 namespace {
43   class VISIBILITY_HIDDEN SparcAsmPrinter : public AsmPrinter {
44     /// We name each basic block in a Function with a unique number, so
45     /// that we can consistently refer to them later. This is cleared
46     /// at the beginning of each call to runOnMachineFunction().
47     ///
48     typedef std::map<const Value *, unsigned> ValueMapTy;
49     ValueMapTy NumberForBB;
50     unsigned BBNumber;
51   public:
52     explicit SparcAsmPrinter(raw_ostream &O, TargetMachine &TM,
53                              const TargetAsmInfo *T, bool V)
54       : AsmPrinter(O, TM, T, V), BBNumber(0) {}
55
56     virtual const char *getPassName() const {
57       return "Sparc Assembly Printer";
58     }
59
60     void printModuleLevelGV(const GlobalVariable* GVar);
61     void printOperand(const MachineInstr *MI, int opNum);
62     void printMemOperand(const MachineInstr *MI, int opNum,
63                          const char *Modifier = 0);
64     void printCCOperand(const MachineInstr *MI, int opNum);
65
66     bool printInstruction(const MachineInstr *MI);  // autogenerated.
67     bool runOnMachineFunction(MachineFunction &F);
68     bool doInitialization(Module &M);
69     bool doFinalization(Module &M);
70     bool PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
71                        unsigned AsmVariant, const char *ExtraCode);
72     bool PrintAsmMemoryOperand(const MachineInstr *MI, unsigned OpNo,
73                              unsigned AsmVariant, const char *ExtraCode);
74   };
75 } // end of anonymous namespace
76
77 #include "SparcGenAsmWriter.inc"
78
79 /// createSparcCodePrinterPass - Returns a pass that prints the SPARC
80 /// assembly code for a MachineFunction to the given output stream,
81 /// using the given target machine description.  This should work
82 /// regardless of whether the function is in SSA form.
83 ///
84 FunctionPass *llvm::createSparcCodePrinterPass(raw_ostream &o,
85                                                TargetMachine &tm,
86                                                bool verbose) {
87   return new SparcAsmPrinter(o, tm, tm.getTargetAsmInfo(), verbose);
88 }
89
90
91 /// runOnMachineFunction - This uses the printInstruction()
92 /// method to print assembly for each instruction.
93 ///
94 bool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
95   this->MF = &MF;
96
97   SetupMachineFunction(MF);
98
99   // Print out constants referenced by the function
100   EmitConstantPool(MF.getConstantPool());
101
102   // BBNumber is used here so that a given Printer will never give two
103   // BBs the same name. (If you have a better way, please let me know!)
104
105   O << "\n\n";
106
107   // Print out the label for the function.
108   const Function *F = MF.getFunction();
109   SwitchToSection(TAI->SectionForGlobal(F));
110   EmitAlignment(MF.getAlignment(), F);
111   O << "\t.globl\t" << CurrentFnName << '\n';
112
113   printVisibility(CurrentFnName, F->getVisibility());
114
115   O << "\t.type\t" << CurrentFnName << ", #function\n";
116   O << CurrentFnName << ":\n";
117
118   // Number each basic block so that we can consistently refer to them
119   // in PC-relative references.
120   // FIXME: Why not use the MBB numbers?
121   NumberForBB.clear();
122   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
123        I != E; ++I) {
124     NumberForBB[I->getBasicBlock()] = BBNumber++;
125   }
126
127   // Print out code for the function.
128   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
129        I != E; ++I) {
130     // Print a label for the basic block.
131     if (I != MF.begin()) {
132       printBasicBlockLabel(I, true, true);
133       O << '\n';
134     }
135     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
136          II != E; ++II) {
137       // Print the assembly for the instruction.
138       printInstruction(II);
139       ++EmittedInsts;
140     }
141   }
142
143   // We didn't modify anything.
144   return false;
145 }
146
147 void SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
148   const MachineOperand &MO = MI->getOperand (opNum);
149   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
150   bool CloseParen = false;
151   if (MI->getOpcode() == SP::SETHIi && !MO.isReg() && !MO.isImm()) {
152     O << "%hi(";
153     CloseParen = true;
154   } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri) &&
155              !MO.isReg() && !MO.isImm()) {
156     O << "%lo(";
157     CloseParen = true;
158   }
159   switch (MO.getType()) {
160   case MachineOperand::MO_Register:
161     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
162       O << "%" << LowercaseString (RI.get(MO.getReg()).AsmName);
163     else
164       O << "%reg" << MO.getReg();
165     break;
166
167   case MachineOperand::MO_Immediate:
168     O << (int)MO.getImm();
169     break;
170   case MachineOperand::MO_MachineBasicBlock:
171     printBasicBlockLabel(MO.getMBB());
172     return;
173   case MachineOperand::MO_GlobalAddress:
174     {
175       const GlobalValue *GV = MO.getGlobal();
176       O << Mang->getValueName(GV);
177     }
178     break;
179   case MachineOperand::MO_ExternalSymbol:
180     O << MO.getSymbolName();
181     break;
182   case MachineOperand::MO_ConstantPoolIndex:
183     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
184       << MO.getIndex();
185     break;
186   default:
187     O << "<unknown operand type>"; abort (); break;
188   }
189   if (CloseParen) O << ")";
190 }
191
192 void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
193                                       const char *Modifier) {
194   printOperand(MI, opNum);
195
196   // If this is an ADD operand, emit it like normal operands.
197   if (Modifier && !strcmp(Modifier, "arith")) {
198     O << ", ";
199     printOperand(MI, opNum+1);
200     return;
201   }
202
203   if (MI->getOperand(opNum+1).isReg() &&
204       MI->getOperand(opNum+1).getReg() == SP::G0)
205     return;   // don't print "+%g0"
206   if (MI->getOperand(opNum+1).isImm() &&
207       MI->getOperand(opNum+1).getImm() == 0)
208     return;   // don't print "+0"
209
210   O << "+";
211   if (MI->getOperand(opNum+1).isGlobal() ||
212       MI->getOperand(opNum+1).isCPI()) {
213     O << "%lo(";
214     printOperand(MI, opNum+1);
215     O << ")";
216   } else {
217     printOperand(MI, opNum+1);
218   }
219 }
220
221 void SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
222   int CC = (int)MI->getOperand(opNum).getImm();
223   O << SPARCCondCodeToString((SPCC::CondCodes)CC);
224 }
225
226 bool SparcAsmPrinter::doInitialization(Module &M) {
227   Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
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->getValueName(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::InternalLinkage:
299     break;
300    case GlobalValue::GhostLinkage:
301     cerr << "Should not have any unmaterialized functions!\n";
302     abort();
303    case GlobalValue::DLLImportLinkage:
304     cerr << "DLLImport linkage is not supported by this target!\n";
305     abort();
306    case GlobalValue::DLLExportLinkage:
307     cerr << "DLLExport linkage is not supported by this target!\n";
308     abort();
309    default:
310     assert(0 && "Unknown linkage type!");
311   }
312
313   EmitAlignment(Align, GVar);
314
315   if (TAI->hasDotTypeDotSizeDirective()) {
316     O << "\t.type " << name << ",#object\n";
317     O << "\t.size " << name << ',' << Size << '\n';
318   }
319
320   O << name << ":\n";
321   EmitGlobalConstant(C);
322 }
323
324 /// PrintAsmOperand - Print out an operand for an inline asm expression.
325 ///
326 bool SparcAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
327                                       unsigned AsmVariant,
328                                       const char *ExtraCode) {
329   if (ExtraCode && ExtraCode[0]) {
330     if (ExtraCode[1] != 0) return true; // Unknown modifier.
331
332     switch (ExtraCode[0]) {
333     default: return true;  // Unknown modifier.
334     case 'r':
335      break;
336     }
337   }
338
339   printOperand(MI, OpNo);
340
341   return false;
342 }
343
344 bool SparcAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
345                                             unsigned OpNo,
346                                             unsigned AsmVariant,
347                                             const char *ExtraCode) {
348   if (ExtraCode && ExtraCode[0])
349     return true;  // Unknown modifier
350
351   O << '[';
352   printMemOperand(MI, OpNo);
353   O << ']';
354
355   return false;
356 }
357
358 namespace {
359   static struct Register {
360     Register() {
361       SparcTargetMachine::registerAsmPrinter(createSparcCodePrinterPass);
362     }
363   } Registrator;
364 }
365
366 // Force static initialization.
367 extern "C" void LLVMInitializeSparcAsmPrinter() { }