Adding dllimport, dllexport and external weak linkage types.
[oota-llvm.git] / lib / Target / IA64 / IA64AsmPrinter.cpp
1 //===-- IA64AsmPrinter.cpp - Print out IA64 LLVM as assembly --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Duraid Madina and is distributed under the
6 // University of Illinois Open Source 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 assembly accepted by the GNU binutils 'gas'
12 // assembler. The Intel 'ias' and HP-UX 'as' assemblers *may* choke on this
13 // output, but if so that's a bug I'd like to hear about: please file a bug
14 // report in bugzilla. FYI, the not too bad 'ias' assembler is bundled with
15 // the Intel C/C++ compiler for Itanium Linux.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "IA64.h"
20 #include "IA64TargetMachine.h"
21 #include "llvm/Module.h"
22 #include "llvm/Type.h"
23 #include "llvm/Assembly/Writer.h"
24 #include "llvm/CodeGen/AsmPrinter.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/Target/TargetAsmInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/ADT/Statistic.h"
30 #include <iostream>
31 using namespace llvm;
32
33 namespace {
34   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
35   
36   struct IA64AsmPrinter : public AsmPrinter {
37     std::set<std::string> ExternalFunctionNames, ExternalObjectNames;
38
39     IA64AsmPrinter(std::ostream &O, TargetMachine &TM, const TargetAsmInfo *T)
40       : AsmPrinter(O, TM, T) {
41     }
42
43     virtual const char *getPassName() const {
44       return "IA64 Assembly Printer";
45     }
46
47     /// printInstruction - This method is automatically generated by tablegen
48     /// from the instruction set description.  This method returns true if the
49     /// machine instruction was sufficiently described to print it, otherwise it
50     /// returns false.
51     bool printInstruction(const MachineInstr *MI);
52
53     // This method is used by the tablegen'erated instruction printer.
54     void printOperand(const MachineInstr *MI, unsigned OpNo){
55       const MachineOperand &MO = MI->getOperand(OpNo);
56       if (MO.getType() == MachineOperand::MO_Register) {
57         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
58         //XXX Bug Workaround: See note in Printer::doInitialization about %.
59         O << TM.getRegisterInfo()->get(MO.getReg()).Name;
60       } else {
61         printOp(MO);
62       }
63     }
64
65     void printS8ImmOperand(const MachineInstr *MI, unsigned OpNo) {
66       int val=(unsigned int)MI->getOperand(OpNo).getImmedValue();
67       if(val>=128) val=val-256; // if negative, flip sign
68       O << val;
69     }
70     void printS14ImmOperand(const MachineInstr *MI, unsigned OpNo) {
71       int val=(unsigned int)MI->getOperand(OpNo).getImmedValue();
72       if(val>=8192) val=val-16384; // if negative, flip sign
73       O << val;
74     }
75     void printS22ImmOperand(const MachineInstr *MI, unsigned OpNo) {
76       int val=(unsigned int)MI->getOperand(OpNo).getImmedValue();
77       if(val>=2097152) val=val-4194304; // if negative, flip sign
78       O << val;
79     }
80     void printU64ImmOperand(const MachineInstr *MI, unsigned OpNo) {
81       O << (uint64_t)MI->getOperand(OpNo).getImmedValue();
82     }
83     void printS64ImmOperand(const MachineInstr *MI, unsigned OpNo) {
84 // XXX : nasty hack to avoid GPREL22 "relocation truncated to fit" linker
85 // errors - instead of add rX = @gprel(CPI<whatever>), r1;; we now
86 // emit movl rX = @gprel(CPI<whatever);;
87 //      add  rX = rX, r1; 
88 // this gives us 64 bits instead of 22 (for the add long imm) to play
89 // with, which shuts up the linker. The problem is that the constant
90 // pool entries aren't immediates at this stage, so we check here. 
91 // If it's an immediate, print it the old fashioned way. If it's
92 // not, we print it as a constant pool index. 
93       if(MI->getOperand(OpNo).isImmediate()) {
94         O << (int64_t)MI->getOperand(OpNo).getImmedValue();
95       } else { // this is a constant pool reference: FIXME: assert this
96         printOp(MI->getOperand(OpNo));
97       }
98     }
99
100     void printGlobalOperand(const MachineInstr *MI, unsigned OpNo) {
101       printOp(MI->getOperand(OpNo), false); // this is NOT a br.call instruction
102     }
103
104     void printCallOperand(const MachineInstr *MI, unsigned OpNo) {
105       printOp(MI->getOperand(OpNo), true); // this is a br.call instruction
106     }
107
108     void printMachineInstruction(const MachineInstr *MI);
109     void printOp(const MachineOperand &MO, bool isBRCALLinsn= false);
110     bool runOnMachineFunction(MachineFunction &F);
111     bool doInitialization(Module &M);
112     bool doFinalization(Module &M);
113   };
114 } // end of anonymous namespace
115
116
117 // Include the auto-generated portion of the assembly writer.
118 #include "IA64GenAsmWriter.inc"
119
120
121 /// runOnMachineFunction - This uses the printMachineInstruction()
122 /// method to print assembly for each instruction.
123 ///
124 bool IA64AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
125   SetupMachineFunction(MF);
126   O << "\n\n";
127
128   // Print out constants referenced by the function
129   EmitConstantPool(MF.getConstantPool());
130
131   // Print out labels for the function.
132   SwitchToTextSection("\n\t.section .text, \"ax\", \"progbits\"\n", 
133                       MF.getFunction());
134   // ^^  means "Allocated instruXions in mem, initialized"
135   EmitAlignment(5);
136   O << "\t.global\t" << CurrentFnName << "\n";
137   O << "\t.type\t" << CurrentFnName << ", @function\n";
138   O << CurrentFnName << ":\n";
139
140   // Print out code for the function.
141   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
142        I != E; ++I) {
143     // Print a label for the basic block if there are any predecessors.
144     if (I->pred_begin() != I->pred_end()) {
145       printBasicBlockLabel(I, true);
146       O << '\n';
147     }
148     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
149          II != E; ++II) {
150       // Print the assembly for the instruction.
151       O << "\t";
152       printMachineInstruction(II);
153     }
154   }
155
156   // We didn't modify anything.
157   return false;
158 }
159
160 void IA64AsmPrinter::printOp(const MachineOperand &MO,
161                              bool isBRCALLinsn /* = false */) {
162   const MRegisterInfo &RI = *TM.getRegisterInfo();
163   switch (MO.getType()) {
164   case MachineOperand::MO_Register:
165     O << RI.get(MO.getReg()).Name;
166     return;
167
168   case MachineOperand::MO_Immediate:
169     O << MO.getImmedValue();
170     return;
171   case MachineOperand::MO_MachineBasicBlock:
172     printBasicBlockLabel(MO.getMachineBasicBlock());
173     return;
174   case MachineOperand::MO_ConstantPoolIndex: {
175     O << "@gprel(" << TAI->getPrivateGlobalPrefix()
176       << "CPI" << getFunctionNumber() << "_"
177       << MO.getConstantPoolIndex() << ")";
178     return;
179   }
180
181   case MachineOperand::MO_GlobalAddress: {
182
183     // functions need @ltoff(@fptr(fn_name)) form
184     GlobalValue *GV = MO.getGlobal();
185     Function *F = dyn_cast<Function>(GV);
186
187     bool Needfptr=false; // if we're computing an address @ltoff(X), do
188                          // we need to decorate it so it becomes
189                          // @ltoff(@fptr(X)) ?
190     if (F && !isBRCALLinsn /*&& F->isExternal()*/)
191       Needfptr=true;
192
193     // if this is the target of a call instruction, we should define
194     // the function somewhere (GNU gas has no problem without this, but
195     // Intel ias rightly complains of an 'undefined symbol')
196
197     if (F /*&& isBRCALLinsn*/ && F->isExternal())
198       ExternalFunctionNames.insert(Mang->getValueName(MO.getGlobal()));
199     else
200       if (GV->isExternal()) // e.g. stuff like 'stdin'
201         ExternalObjectNames.insert(Mang->getValueName(MO.getGlobal()));
202
203     if (!isBRCALLinsn)
204       O << "@ltoff(";
205     if (Needfptr)
206       O << "@fptr(";
207     O << Mang->getValueName(MO.getGlobal());
208     
209     if (Needfptr && !isBRCALLinsn)
210       O << "#))"; // close both fptr( and ltoff(
211     else {
212       if (Needfptr)
213         O << "#)"; // close only fptr(
214       if (!isBRCALLinsn)
215         O << "#)"; // close only ltoff(
216     }
217     
218     int Offset = MO.getOffset();
219     if (Offset > 0)
220       O << " + " << Offset;
221     else if (Offset < 0)
222       O << " - " << -Offset;
223     return;
224   }
225   case MachineOperand::MO_ExternalSymbol:
226     O << MO.getSymbolName();
227     ExternalFunctionNames.insert(MO.getSymbolName());
228     return;
229   default:
230     O << "<AsmPrinter: unknown operand type: " << MO.getType() << " >"; return;
231   }
232 }
233
234 /// printMachineInstruction -- Print out a single IA64 LLVM instruction
235 /// MI to the current output stream.
236 ///
237 void IA64AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
238   ++EmittedInsts;
239
240   // Call the autogenerated instruction printer routines.
241   printInstruction(MI);
242 }
243
244 bool IA64AsmPrinter::doInitialization(Module &M) {
245   AsmPrinter::doInitialization(M);
246
247   O << "\n.ident \"LLVM-ia64\"\n\n"
248     << "\t.psr    lsb\n"  // should be "msb" on HP-UX, for starters
249     << "\t.radix  C\n"
250     << "\t.psr    abi64\n"; // we only support 64 bits for now
251   return false;
252 }
253
254 bool IA64AsmPrinter::doFinalization(Module &M) {
255   const TargetData *TD = TM.getTargetData();
256   
257   // Print out module-level global variables here.
258   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
259        I != E; ++I)
260     if (I->hasInitializer()) {   // External global require no code
261       // Check to see if this is a special global used by LLVM, if so, emit it.
262       if (EmitSpecialLLVMGlobal(I))
263         continue;
264       
265       O << "\n\n";
266       std::string name = Mang->getValueName(I);
267       Constant *C = I->getInitializer();
268       unsigned Size = TD->getTypeSize(C->getType());
269       unsigned Align = TD->getTypeAlignmentShift(C->getType());
270       
271       if (C->isNullValue() &&
272           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
273            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
274         SwitchToDataSection(".data", I);
275         if (I->hasInternalLinkage()) {
276           O << "\t.lcomm " << name << "#," << TD->getTypeSize(C->getType())
277           << "," << (1 << Align);
278           O << "\t\t// ";
279         } else {
280           O << "\t.common " << name << "#," << TD->getTypeSize(C->getType())
281           << "," << (1 << Align);
282           O << "\t\t// ";
283         }
284         WriteAsOperand(O, I, true, true, &M);
285         O << "\n";
286       } else {
287         switch (I->getLinkage()) {
288           case GlobalValue::LinkOnceLinkage:
289           case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
290                                            // Nonnull linkonce -> weak
291             O << "\t.weak " << name << "\n";
292             O << "\t.section\t.llvm.linkonce.d." << name
293               << ", \"aw\", \"progbits\"\n";
294             SwitchToDataSection("", I);
295             break;
296           case GlobalValue::AppendingLinkage:
297             // FIXME: appending linkage variables should go into a section of
298             // their name or something.  For now, just emit them as external.
299           case GlobalValue::ExternalLinkage:
300             // If external or appending, declare as a global symbol
301             O << "\t.global " << name << "\n";
302             // FALL THROUGH
303           case GlobalValue::InternalLinkage:
304             SwitchToDataSection(C->isNullValue() ? ".bss" : ".data", I);
305             break;
306           case GlobalValue::GhostLinkage:
307             std::cerr << "GhostLinkage cannot appear in IA64AsmPrinter!\n";
308             abort();
309           case GlobalValue::DLLImportLinkage:
310             std::cerr << "DLLImport linkage is not supported by this target!\n";
311             abort();
312           case GlobalValue::DLLExportLinkage:
313             std::cerr << "DLLExport linkage is not supported by this target!\n";
314             abort();
315           default:
316             assert(0 && "Unknown linkage type!");            
317         }
318         
319         EmitAlignment(Align);
320         O << "\t.type " << name << ",@object\n";
321         O << "\t.size " << name << "," << Size << "\n";
322         O << name << ":\t\t\t\t// ";
323         WriteAsOperand(O, I, true, true, &M);
324         O << " = ";
325         WriteAsOperand(O, C, false, false, &M);
326         O << "\n";
327         EmitGlobalConstant(C);
328       }
329     }
330       
331       // we print out ".global X \n .type X, @function" for each external function
332       O << "\n\n// br.call targets referenced (and not defined) above: \n";
333   for (std::set<std::string>::iterator i = ExternalFunctionNames.begin(),
334        e = ExternalFunctionNames.end(); i!=e; ++i) {
335     O << "\t.global " << *i << "\n\t.type " << *i << ", @function\n";
336   }
337   O << "\n\n";
338   
339   // we print out ".global X \n .type X, @object" for each external object
340   O << "\n\n// (external) symbols referenced (and not defined) above: \n";
341   for (std::set<std::string>::iterator i = ExternalObjectNames.begin(),
342        e = ExternalObjectNames.end(); i!=e; ++i) {
343     O << "\t.global " << *i << "\n\t.type " << *i << ", @object\n";
344   }
345   O << "\n\n";
346   
347   AsmPrinter::doFinalization(M);
348   return false; // success
349 }
350
351 /// createIA64CodePrinterPass - Returns a pass that prints the IA64
352 /// assembly code for a MachineFunction to the given output stream, using
353 /// the given target machine description.
354 ///
355 FunctionPass *llvm::createIA64CodePrinterPass(std::ostream &o,
356                                               IA64TargetMachine &tm) {
357   return new IA64AsmPrinter(o, tm, tm.getTargetAsmInfo());
358 }
359
360