and so it begins...
[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 excellent '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/Assembly/Writer.h"
23 #include "llvm/CodeGen/AsmPrinter.h"
24 #include "llvm/CodeGen/MachineConstantPool.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/ValueTypes.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/Mangler.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/Support/CommandLine.h"
31 using namespace llvm;
32
33 namespace {
34   Statistic<> EmittedInsts("asm-printer", "Number of machine instrs printed");
35
36   struct IA64SharedAsmPrinter : public AsmPrinter {
37
38     std::set<std::string> ExternalFunctionNames;
39     
40     IA64SharedAsmPrinter(std::ostream &O, TargetMachine &TM)
41       : AsmPrinter(O, TM) { }
42
43     void printConstantPool(MachineConstantPool *MCP);
44     bool doFinalization(Module &M);
45   };
46 }
47
48 static bool isScale(const MachineOperand &MO) {
49   return MO.isImmediate() &&
50     (MO.getImmedValue() == 1 || MO.getImmedValue() == 2 ||
51      MO.getImmedValue() == 4 || MO.getImmedValue() == 8);
52 }
53
54 static bool isMem(const MachineInstr *MI, unsigned Op) {
55   if (MI->getOperand(Op).isFrameIndex()) return true;
56   if (MI->getOperand(Op).isConstantPoolIndex()) return true;
57   return Op+4 <= MI->getNumOperands() &&
58     MI->getOperand(Op  ).isRegister() && isScale(MI->getOperand(Op+1)) &&
59     MI->getOperand(Op+2).isRegister() && (MI->getOperand(Op+3).isImmediate() ||
60         MI->getOperand(Op+3).isGlobalAddress());
61 }
62
63 // SwitchSection - Switch to the specified section of the executable if we are
64 // not already in it!
65 //
66 static void SwitchSection(std::ostream &OS, std::string &CurSection,
67                           const char *NewSection) {
68   if (CurSection != NewSection) {
69     CurSection = NewSection;
70     if (!CurSection.empty())
71       OS << "\t" << NewSection << "\n";
72   }
73 }
74
75 /// printConstantPool - Print to the current output stream assembly
76 /// representations of the constants in the constant pool MCP. This is
77 /// used to print out constants which have been "spilled to memory" by
78 /// the code generator.
79 ///
80 void IA64SharedAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
81   const std::vector<Constant*> &CP = MCP->getConstants();
82   const TargetData &TD = TM.getTargetData();
83  
84   if (CP.empty()) return;
85
86   O << "\n\t.section .data\n"; // would be nice to have this rodata? hmmm
87   for (unsigned i = 0, e = CP.size(); i != e; ++i) {
88     emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
89     O << ".CPI" << CurrentFnName << "_" << i << ":\t\t\t\t\t" << CommentString
90       << *CP[i] << "\n";
91     emitGlobalConstant(CP[i]);
92   }
93 }
94
95 bool IA64SharedAsmPrinter::doFinalization(Module &M) {
96   const TargetData &TD = TM.getTargetData();
97   std::string CurSection;
98
99   // Print out module-level global variables here.
100   for (Module::const_giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
101     if (I->hasInitializer()) {   // External global require no code
102       O << "\n\n";
103       std::string name = Mang->getValueName(I);
104       Constant *C = I->getInitializer();
105       unsigned Size = TD.getTypeSize(C->getType());
106       unsigned Align = TD.getTypeAlignmentShift(C->getType());
107
108       if (C->isNullValue() && 
109           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
110            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
111         SwitchSection(O, CurSection, ".data");
112         if (I->hasInternalLinkage())
113           O << "\t.local " << name << "\n";
114         
115         O << "\t.common " << name << "," << TD.getTypeSize(C->getType())
116           << "," << (1 << Align);
117         O << "\t\t// ";
118         WriteAsOperand(O, I, true, true, &M);
119         O << "\n";
120       } else {
121         switch (I->getLinkage()) {
122         case GlobalValue::LinkOnceLinkage:
123         case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
124           // Nonnull linkonce -> weak
125           O << "\t.weak " << name << "\n";
126           SwitchSection(O, CurSection, "");
127           O << "\t.section\t.llvm.linkonce.d." << name
128             << ", \"aw\", \"progbits\"\n";
129           break;
130         case GlobalValue::AppendingLinkage:
131           // FIXME: appending linkage variables should go into a section of
132           // their name or something.  For now, just emit them as external.
133         case GlobalValue::ExternalLinkage:
134           // If external or appending, declare as a global symbol
135           O << "\t.global " << name << "\n";
136           // FALL THROUGH
137         case GlobalValue::InternalLinkage:
138           if (C->isNullValue())
139             SwitchSection(O, CurSection, ".data"); // FIXME: this was
140           // '.bss', but in ia64-land .bss means "nobits" (i.e. uninitialized)
141           // hmm.
142           else
143             SwitchSection(O, CurSection, ".data");
144           break;
145         case GlobalValue::GhostLinkage:
146           std::cerr << "GhostLinkage cannot appear in IA64AsmPrinter!\n";
147           abort();
148         }
149
150         emitAlignment(Align);
151         O << "\t.type " << name << ",@object\n";
152         O << "\t.size " << name << "," << Size << "\n";
153         O << name << ":\t\t\t\t// ";
154         WriteAsOperand(O, I, true, true, &M);
155         O << " = ";
156         WriteAsOperand(O, C, false, false, &M);
157         O << "\n";
158         emitGlobalConstant(C);
159       }
160     }
161
162   // we print out ".global X \n .type X, @function" for each external function
163   O << "\n\n// br.call targets referenced (and not defined) above: \n";
164   for (std::set<std::string>::iterator i = ExternalFunctionNames.begin(),
165        e = ExternalFunctionNames.end(); i!=e; ++i) {
166     O << "\t.global " << *i << "\n\t.type " << *i << ", @function\n";
167   }
168   O << "\n\n";
169  
170   AsmPrinter::doFinalization(M);
171   return false; // success
172 }
173
174 namespace {
175   struct IA64AsmPrinter : public IA64SharedAsmPrinter {
176     IA64AsmPrinter(std::ostream &O, TargetMachine &TM)
177       : IA64SharedAsmPrinter(O, TM) {
178
179       CommentString = "//";
180       Data8bitsDirective = "\tdata1\t";
181       Data16bitsDirective = "\tdata2\t";
182       Data32bitsDirective = "\tdata4\t";
183       Data64bitsDirective = "\tdata8\t";
184       ZeroDirective = "\t.skip\t";
185       AsciiDirective = "\tstring\t";
186
187     }
188
189     virtual const char *getPassName() const {
190       return "IA64 Assembly Printer";
191     }
192
193     /// printInstruction - This method is automatically generated by tablegen
194     /// from the instruction set description.  This method returns true if the
195     /// machine instruction was sufficiently described to print it, otherwise it
196     /// returns false.
197     bool printInstruction(const MachineInstr *MI);
198
199     // This method is used by the tablegen'erated instruction printer.
200     void printOperand(const MachineInstr *MI, unsigned OpNo, MVT::ValueType VT){
201       const MachineOperand &MO = MI->getOperand(OpNo);
202       if (MO.getType() == MachineOperand::MO_MachineRegister) {
203         assert(MRegisterInfo::isPhysicalRegister(MO.getReg())&&"Not physref??");
204         //XXX Bug Workaround: See note in Printer::doInitialization about %.
205         O << TM.getRegisterInfo()->get(MO.getReg()).Name;
206       } else {
207         printOp(MO);
208       }
209     }
210     
211     void printS16ImmOperand(const MachineInstr *MI, unsigned OpNo,
212                             MVT::ValueType VT) {
213       O << (short)MI->getOperand(OpNo).getImmedValue();
214     }
215     void printU16ImmOperand(const MachineInstr *MI, unsigned OpNo,
216                             MVT::ValueType VT) {
217       O << (unsigned short)MI->getOperand(OpNo).getImmedValue();
218     }
219     void printS21ImmOperand(const MachineInstr *MI, unsigned OpNo,
220                             MVT::ValueType VT) {
221       O << (int)MI->getOperand(OpNo).getImmedValue(); // FIXME (21, not 32!)
222     }
223     void printS32ImmOperand(const MachineInstr *MI, unsigned OpNo,
224                             MVT::ValueType VT) {
225       O << (int)MI->getOperand(OpNo).getImmedValue();
226     }
227     void printU32ImmOperand(const MachineInstr *MI, unsigned OpNo,
228                             MVT::ValueType VT) {
229       O << (unsigned int)MI->getOperand(OpNo).getImmedValue();
230     }
231     void printU64ImmOperand(const MachineInstr *MI, unsigned OpNo,
232                             MVT::ValueType VT) {
233       O << (uint64_t)MI->getOperand(OpNo).getImmedValue();
234     }
235    
236     void printCallOperand(const MachineInstr *MI, unsigned OpNo,
237                           MVT::ValueType VT) {
238       printOp(MI->getOperand(OpNo), true); // this is a br.call instruction 
239     }
240
241     void printMachineInstruction(const MachineInstr *MI);
242     void printOp(const MachineOperand &MO, bool isBRCALLinsn= false);
243     bool runOnMachineFunction(MachineFunction &F);    
244     bool doInitialization(Module &M);
245   };
246 } // end of anonymous namespace
247
248
249 // Include the auto-generated portion of the assembly writer.
250 #include "IA64GenAsmWriter.inc"
251
252
253 /// runOnMachineFunction - This uses the printMachineInstruction()
254 /// method to print assembly for each instruction.
255 ///
256 bool IA64AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
257   setupMachineFunction(MF);
258   O << "\n\n";
259
260   // Print out constants referenced by the function
261   printConstantPool(MF.getConstantPool());
262
263   // Print out labels for the function.
264   O << "\n\t.section .text, \"ax\", \"progbits\"\n";
265               // ^^  means "Allocated instruXions in mem, initialized"
266   emitAlignment(4);
267   O << "\t.global\t" << CurrentFnName << "\n";
268   O << "\t.type\t" << CurrentFnName << ", @function\n";
269   O << CurrentFnName << ":\n";
270
271   // Print out code for the function.
272   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
273        I != E; ++I) {
274     // Print a label for the basic block if there are any predecessors.
275     if (I->pred_begin() != I->pred_end())
276       O << ".LBB" << CurrentFnName << "_" << I->getNumber() << ":\t"
277         << CommentString << " " << I->getBasicBlock()->getName() << "\n";
278     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
279          II != E; ++II) {
280       // Print the assembly for the instruction.
281       O << "\t";
282       printMachineInstruction(II);
283     }
284   }
285
286   // We didn't modify anything.
287   return false;
288 }
289
290 void IA64AsmPrinter::printOp(const MachineOperand &MO,
291                                  bool isBRCALLinsn /* = false */) {
292   const MRegisterInfo &RI = *TM.getRegisterInfo();
293   switch (MO.getType()) {
294   case MachineOperand::MO_VirtualRegister:
295     if (Value *V = MO.getVRegValueOrNull()) {
296       O << "<" << V->getName() << ">";
297       return;
298     }
299     // FALLTHROUGH
300   case MachineOperand::MO_MachineRegister:
301   case MachineOperand::MO_CCRegister: {
302     O << RI.get(MO.getReg()).Name;
303     return;
304   }
305
306   case MachineOperand::MO_SignExtendedImmed:
307   case MachineOperand::MO_UnextendedImmed:
308     O << /*(unsigned int)*/MO.getImmedValue();
309     return;
310   case MachineOperand::MO_MachineBasicBlock: {
311     MachineBasicBlock *MBBOp = MO.getMachineBasicBlock();
312     O << ".LBB" << Mang->getValueName(MBBOp->getParent()->getFunction())
313       << "_" << MBBOp->getNumber () << "\t// "
314       << MBBOp->getBasicBlock ()->getName ();
315     return;
316   }
317   case MachineOperand::MO_PCRelativeDisp:
318     std::cerr << "Shouldn't use addPCDisp() when building IA64 MachineInstrs";
319     abort ();
320     return;
321
322   case MachineOperand::MO_ConstantPoolIndex: {
323     O << "@gprel(.CPI" << CurrentFnName << "_"
324       << MO.getConstantPoolIndex() << ")";
325     return;
326   }
327
328   case MachineOperand::MO_GlobalAddress: {
329
330     // functions need @ltoff(@fptr(fn_name)) form
331     GlobalValue *GV = MO.getGlobal();
332     Function *F = dyn_cast<Function>(GV);
333
334     bool Needfptr=false; // if we're computing an address @ltoff(X), do
335                          // we need to decorate it so it becomes
336                          // @ltoff(@fptr(X)) ?
337     if(F && !isBRCALLinsn && F->isExternal())
338       Needfptr=true;
339    
340     // if this is the target of a call instruction, we should define
341     // the function somewhere (GNU gas has no problem without this, but
342     // Intel ias rightly complains of an 'undefined symbol')
343   
344     if(F && isBRCALLinsn && F->isExternal())
345       ExternalFunctionNames.insert(Mang->getValueName(MO.getGlobal()));
346     
347     if (!isBRCALLinsn)
348       O << "@ltoff(";
349     if (Needfptr)
350       O << "@fptr(";
351     O << Mang->getValueName(MO.getGlobal());
352     if (Needfptr)
353       O << ")"; // close fptr(
354     if (!isBRCALLinsn)
355       O << ")"; // close ltoff(
356     int Offset = MO.getOffset();
357     if (Offset > 0)
358       O << " + " << Offset;
359     else if (Offset < 0)
360       O << " - " << -Offset;
361     return;
362   }
363   case MachineOperand::MO_ExternalSymbol:
364     O << MO.getSymbolName();
365     return;
366   default:
367     O << "<AsmPrinter: unknown operand type: " << MO.getType() << " >"; return;    
368   }
369 }
370
371 /// printMachineInstruction -- Print out a single IA64 LLVM instruction
372 /// MI to the current output stream.
373 ///
374 void IA64AsmPrinter::printMachineInstruction(const MachineInstr *MI) {
375   
376   ++EmittedInsts;
377   
378   // Call the autogenerated instruction printer routines.
379   printInstruction(MI);
380 }
381
382 bool IA64AsmPrinter::doInitialization(Module &M) {
383   AsmPrinter::doInitialization(M);
384   
385   O << "\t.psr    lsb\n"  // should be "msb" on HP-UX, for starters
386     << "\t.radix  C\n"
387     << "\t.psr    abi64\n"; // we only support 64 bits for now
388   return false;
389 }
390
391 /// createIA64CodePrinterPass - Returns a pass that prints the IA64
392 /// assembly code for a MachineFunction to the given output stream, using
393 /// the given target machine description.
394 ///
395 FunctionPass *llvm::createIA64CodePrinterPass(std::ostream &o,TargetMachine &tm){
396   return new IA64AsmPrinter(o, tm);
397 }
398
399