Rename PaddedSize to AllocSize, in the hope that this
[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 "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Module.h"
21 #include "llvm/CodeGen/AsmPrinter.h"
22 #include "llvm/CodeGen/DwarfWriter.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineInstr.h"
26 #include "llvm/Target/TargetAsmInfo.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetMachine.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   public:
51     explicit SparcAsmPrinter(raw_ostream &O, TargetMachine &TM,
52                              const TargetAsmInfo *T, CodeGenOpt::Level OL,
53                              bool V)
54       : AsmPrinter(O, TM, T, OL, V) {}
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                                                CodeGenOpt::Level OptLevel,
87                                                bool verbose) {
88   return new SparcAsmPrinter(o, tm, tm.getTargetAsmInfo(), OptLevel, verbose);
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   static unsigned BBNumber = 0;
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(4, 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     {
176       const GlobalValue *GV = MO.getGlobal();
177       O << Mang->getValueName(GV);
178     }
179     break;
180   case MachineOperand::MO_ExternalSymbol:
181     O << MO.getSymbolName();
182     break;
183   case MachineOperand::MO_ConstantPoolIndex:
184     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
185       << MO.getIndex();
186     break;
187   default:
188     O << "<unknown operand type>"; abort (); break;
189   }
190   if (CloseParen) O << ")";
191 }
192
193 void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
194                                       const char *Modifier) {
195   printOperand(MI, opNum);
196
197   // If this is an ADD operand, emit it like normal operands.
198   if (Modifier && !strcmp(Modifier, "arith")) {
199     O << ", ";
200     printOperand(MI, opNum+1);
201     return;
202   }
203
204   if (MI->getOperand(opNum+1).isReg() &&
205       MI->getOperand(opNum+1).getReg() == SP::G0)
206     return;   // don't print "+%g0"
207   if (MI->getOperand(opNum+1).isImm() &&
208       MI->getOperand(opNum+1).getImm() == 0)
209     return;   // don't print "+0"
210
211   O << "+";
212   if (MI->getOperand(opNum+1).isGlobal() ||
213       MI->getOperand(opNum+1).isCPI()) {
214     O << "%lo(";
215     printOperand(MI, opNum+1);
216     O << ")";
217   } else {
218     printOperand(MI, opNum+1);
219   }
220 }
221
222 void SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
223   int CC = (int)MI->getOperand(opNum).getImm();
224   O << SPARCCondCodeToString((SPCC::CondCodes)CC);
225 }
226
227 bool SparcAsmPrinter::doInitialization(Module &M) {
228   Mang = new Mangler(M, "", TAI->getPrivateGlobalPrefix());
229   return false; // success
230 }
231
232 bool SparcAsmPrinter::doFinalization(Module &M) {
233   // Print out module-level global variables here.
234   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
235        I != E; ++I)
236     printModuleLevelGV(I);
237
238   O << '\n';
239
240   return AsmPrinter::doFinalization(M);
241 }
242
243 void SparcAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
244   const TargetData *TD = TM.getTargetData();
245
246   if (!GVar->hasInitializer())
247     return;  // External global require no code
248
249   // Check to see if this is a special global used by LLVM, if so, emit it.
250   if (EmitSpecialLLVMGlobal(GVar))
251     return;
252
253   O << "\n\n";
254   std::string name = Mang->getValueName(GVar);
255   Constant *C = GVar->getInitializer();
256   unsigned Size = TD->getTypeAllocSize(C->getType());
257   unsigned Align = TD->getPreferredAlignment(GVar);
258
259   printVisibility(name, GVar->getVisibility());
260
261   SwitchToSection(TAI->SectionForGlobal(GVar));
262
263   if (C->isNullValue() && !GVar->hasSection()) {
264     if (!GVar->isThreadLocal() &&
265         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
266       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
267
268       if (GVar->hasLocalLinkage())
269         O << "\t.local " << name << '\n';
270
271       O << TAI->getCOMMDirective() << name << ',' << Size;
272       if (TAI->getCOMMDirectiveTakesAlignment())
273         O << ',' << (1 << Align);
274
275       O << '\n';
276       return;
277     }
278   }
279
280   switch (GVar->getLinkage()) {
281    case GlobalValue::CommonLinkage:
282    case GlobalValue::LinkOnceAnyLinkage:
283    case GlobalValue::LinkOnceODRLinkage:
284    case GlobalValue::WeakAnyLinkage: // FIXME: Verify correct for weak.
285    case GlobalValue::WeakODRLinkage: // FIXME: Verify correct for weak.
286     // Nonnull linkonce -> weak
287     O << "\t.weak " << name << '\n';
288     break;
289    case GlobalValue::AppendingLinkage:
290     // FIXME: appending linkage variables should go into a section of
291     // their name or something.  For now, just emit them as external.
292    case GlobalValue::ExternalLinkage:
293     // If external or appending, declare as a global symbol
294     O << TAI->getGlobalDirective() << name << '\n';
295     // FALL THROUGH
296    case GlobalValue::PrivateLinkage:
297    case GlobalValue::InternalLinkage:
298     break;
299    case GlobalValue::GhostLinkage:
300     cerr << "Should not have any unmaterialized functions!\n";
301     abort();
302    case GlobalValue::DLLImportLinkage:
303     cerr << "DLLImport linkage is not supported by this target!\n";
304     abort();
305    case GlobalValue::DLLExportLinkage:
306     cerr << "DLLExport linkage is not supported by this target!\n";
307     abort();
308    default:
309     assert(0 && "Unknown linkage type!");
310   }
311
312   EmitAlignment(Align, GVar);
313
314   if (TAI->hasDotTypeDotSizeDirective()) {
315     O << "\t.type " << name << ",#object\n";
316     O << "\t.size " << name << ',' << Size << '\n';
317   }
318
319   O << name << ":\n";
320   EmitGlobalConstant(C);
321 }
322
323 /// PrintAsmOperand - Print out an operand for an inline asm expression.
324 ///
325 bool SparcAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
326                                       unsigned AsmVariant,
327                                       const char *ExtraCode) {
328   if (ExtraCode && ExtraCode[0]) {
329     if (ExtraCode[1] != 0) return true; // Unknown modifier.
330
331     switch (ExtraCode[0]) {
332     default: return true;  // Unknown modifier.
333     case 'r':
334      break;
335     }
336   }
337
338   printOperand(MI, OpNo);
339
340   return false;
341 }
342
343 bool SparcAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
344                                             unsigned OpNo,
345                                             unsigned AsmVariant,
346                                             const char *ExtraCode) {
347   if (ExtraCode && ExtraCode[0])
348     return true;  // Unknown modifier
349
350   O << '[';
351   printMemOperand(MI, OpNo);
352   O << ']';
353
354   return false;
355 }