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