b95acddc73865a961ab58aee8209d92144524804
[oota-llvm.git] / lib / Target / Sparc / 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/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineConstantPool.h"
24 #include "llvm/CodeGen/MachineInstr.h"
25 #include "llvm/Target/TargetAsmInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/MathExtras.h"
33 #include <cctype>
34 using namespace llvm;
35
36 STATISTIC(EmittedInsts, "Number of machine instrs printed");
37
38 namespace {
39   struct VISIBILITY_HIDDEN SparcAsmPrinter : public AsmPrinter {
40     SparcAsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
41       : AsmPrinter(O, TM, T) {
42     }
43
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
51     virtual const char *getPassName() const {
52       return "Sparc Assembly Printer";
53     }
54
55     void printOperand(const MachineInstr *MI, int opNum);
56     void printMemOperand(const MachineInstr *MI, int opNum,
57                          const char *Modifier = 0);
58     void printCCOperand(const MachineInstr *MI, int opNum);
59
60     bool printInstruction(const MachineInstr *MI);  // autogenerated.
61     bool runOnMachineFunction(MachineFunction &F);
62     bool doInitialization(Module &M);
63     bool doFinalization(Module &M);
64   };
65 } // end of anonymous namespace
66
67 #include "SparcGenAsmWriter.inc"
68
69 /// createSparcCodePrinterPass - Returns a pass that prints the SPARC
70 /// assembly code for a MachineFunction to the given output stream,
71 /// using the given target machine description.  This should work
72 /// regardless of whether the function is in SSA form.
73 ///
74 FunctionPass *llvm::createSparcCodePrinterPass(std::ostream &o,
75                                                TargetMachine &tm) {
76   return new SparcAsmPrinter(o, tm, tm.getTargetAsmInfo());
77 }
78
79 /// runOnMachineFunction - This uses the printInstruction()
80 /// method to print assembly for each instruction.
81 ///
82 bool SparcAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
83   SetupMachineFunction(MF);
84
85   // Print out constants referenced by the function
86   EmitConstantPool(MF.getConstantPool());
87
88   // BBNumber is used here so that a given Printer will never give two
89   // BBs the same name. (If you have a better way, please let me know!)
90   static unsigned BBNumber = 0;
91
92   O << "\n\n";
93   // What's my mangled name?
94   CurrentFnName = Mang->getValueName(MF.getFunction());
95
96   // Print out the label for the function.
97   const Function *F = MF.getFunction();
98   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
99   EmitAlignment(4, F);
100   O << "\t.globl\t" << CurrentFnName << "\n";
101   O << "\t.type\t" << CurrentFnName << ", #function\n";
102   O << CurrentFnName << ":\n";
103
104   // Number each basic block so that we can consistently refer to them
105   // in PC-relative references.
106   // FIXME: Why not use the MBB numbers?
107   NumberForBB.clear();
108   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
109        I != E; ++I) {
110     NumberForBB[I->getBasicBlock()] = BBNumber++;
111   }
112
113   // Print out code for the function.
114   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
115        I != E; ++I) {
116     // Print a label for the basic block.
117     if (I != MF.begin()) {
118       printBasicBlockLabel(I, true);
119       O << '\n';
120     }
121     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
122          II != E; ++II) {
123       // Print the assembly for the instruction.
124       printInstruction(II);
125       ++EmittedInsts;
126     }
127   }
128
129   // We didn't modify anything.
130   return false;
131 }
132
133 void SparcAsmPrinter::printOperand(const MachineInstr *MI, int opNum) {
134   const MachineOperand &MO = MI->getOperand (opNum);
135   const TargetRegisterInfo &RI = *TM.getRegisterInfo();
136   bool CloseParen = false;
137   if (MI->getOpcode() == SP::SETHIi && !MO.isRegister() && !MO.isImmediate()) {
138     O << "%hi(";
139     CloseParen = true;
140   } else if ((MI->getOpcode() == SP::ORri || MI->getOpcode() == SP::ADDri)
141              && !MO.isRegister() && !MO.isImmediate()) {
142     O << "%lo(";
143     CloseParen = true;
144   }
145   switch (MO.getType()) {
146   case MachineOperand::MO_Register:
147     if (TargetRegisterInfo::isPhysicalRegister(MO.getReg()))
148       O << "%" << LowercaseString (RI.get(MO.getReg()).Name);
149     else
150       O << "%reg" << MO.getReg();
151     break;
152
153   case MachineOperand::MO_Immediate:
154     O << (int)MO.getImm();
155     break;
156   case MachineOperand::MO_MachineBasicBlock:
157     printBasicBlockLabel(MO.getMBB());
158     return;
159   case MachineOperand::MO_GlobalAddress:
160     O << Mang->getValueName(MO.getGlobal());
161     break;
162   case MachineOperand::MO_ExternalSymbol:
163     O << MO.getSymbolName();
164     break;
165   case MachineOperand::MO_ConstantPoolIndex:
166     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
167       << MO.getIndex();
168     break;
169   default:
170     O << "<unknown operand type>"; abort (); break;
171   }
172   if (CloseParen) O << ")";
173 }
174
175 void SparcAsmPrinter::printMemOperand(const MachineInstr *MI, int opNum,
176                                       const char *Modifier) {
177   printOperand(MI, opNum);
178   
179   // If this is an ADD operand, emit it like normal operands.
180   if (Modifier && !strcmp(Modifier, "arith")) {
181     O << ", ";
182     printOperand(MI, opNum+1);
183     return;
184   }
185   
186   if (MI->getOperand(opNum+1).isRegister() &&
187       MI->getOperand(opNum+1).getReg() == SP::G0)
188     return;   // don't print "+%g0"
189   if (MI->getOperand(opNum+1).isImmediate() &&
190       MI->getOperand(opNum+1).getImm() == 0)
191     return;   // don't print "+0"
192   
193   O << "+";
194   if (MI->getOperand(opNum+1).isGlobalAddress() ||
195       MI->getOperand(opNum+1).isConstantPoolIndex()) {
196     O << "%lo(";
197     printOperand(MI, opNum+1);
198     O << ")";
199   } else {
200     printOperand(MI, opNum+1);
201   }
202 }
203
204 void SparcAsmPrinter::printCCOperand(const MachineInstr *MI, int opNum) {
205   int CC = (int)MI->getOperand(opNum).getImm();
206   O << SPARCCondCodeToString((SPCC::CondCodes)CC);
207 }
208
209
210
211 bool SparcAsmPrinter::doInitialization(Module &M) {
212   Mang = new Mangler(M);
213   return false; // success
214 }
215
216 bool SparcAsmPrinter::doFinalization(Module &M) {
217   const TargetData *TD = TM.getTargetData();
218
219   // Print out module-level global variables here.
220   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
221        I != E; ++I)
222     if (I->hasInitializer()) {   // External global require no code
223       // Check to see if this is a special global used by LLVM, if so, emit it.
224       if (EmitSpecialLLVMGlobal(I))
225         continue;
226       
227       O << "\n\n";
228       std::string name = Mang->getValueName(I);
229       Constant *C = I->getInitializer();
230       unsigned Size = TD->getABITypeSize(C->getType());
231       unsigned Align = TD->getPreferredAlignment(I);
232
233       if (C->isNullValue() &&
234           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
235            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
236         SwitchToDataSection(".data", I);
237         if (I->hasInternalLinkage())
238           O << "\t.local " << name << "\n";
239
240         O << "\t.comm " << name << "," << TD->getABITypeSize(C->getType())
241           << "," << Align;
242         O << "\n";
243       } else {
244         switch (I->getLinkage()) {
245         case GlobalValue::LinkOnceLinkage:
246         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
247           // Nonnull linkonce -> weak
248           O << "\t.weak " << name << "\n";
249           SwitchToDataSection("", I);
250           O << "\t.section\t\".llvm.linkonce.d." << name
251             << "\",\"aw\",@progbits\n";
252           break;
253
254         case GlobalValue::AppendingLinkage:
255           // FIXME: appending linkage variables should go into a section of
256           // their name or something.  For now, just emit them as external.
257         case GlobalValue::ExternalLinkage:
258           // If external or appending, declare as a global symbol
259           O << "\t.globl " << name << "\n";
260           // FALL THROUGH
261         case GlobalValue::InternalLinkage:
262           if (C->isNullValue())
263             SwitchToDataSection(".bss", I);
264           else
265             SwitchToDataSection(".data", I);
266           break;
267         case GlobalValue::GhostLinkage:
268           cerr << "Should not have any unmaterialized functions!\n";
269           abort();
270         case GlobalValue::DLLImportLinkage:
271           cerr << "DLLImport linkage is not supported by this target!\n";
272           abort();
273         case GlobalValue::DLLExportLinkage:
274           cerr << "DLLExport linkage is not supported by this target!\n";
275           abort();
276         default:
277           assert(0 && "Unknown linkage type!");          
278         }
279
280         O << "\t.align " << Align << "\n";
281         O << "\t.type " << name << ",#object\n";
282         O << "\t.size " << name << "," << Size << "\n";
283         O << name << ":\n";
284         EmitGlobalConstant(C);
285       }
286     }
287
288   return AsmPrinter::doFinalization(M);
289 }