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