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