Add constraints to Instruction class.
[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     std::string getSectionForFunction(const Function &F) const;
109
110     void printMachineInstruction(const MachineInstr *MI);
111     void printOp(const MachineOperand &MO, bool isBRCALLinsn= false);
112     bool runOnMachineFunction(MachineFunction &F);
113     bool doInitialization(Module &M);
114     bool doFinalization(Module &M);
115   };
116 } // end of anonymous namespace
117
118
119 // Include the auto-generated portion of the assembly writer.
120 #include "IA64GenAsmWriter.inc"
121
122
123 std::string IA64AsmPrinter::getSectionForFunction(const Function &F) const {
124   // This means "Allocated instruXions in mem, initialized".
125   return "\n\t.section .text, \"ax\", \"progbits\"\n";
126 }
127
128 /// runOnMachineFunction - This uses the printMachineInstruction()
129 /// method to print assembly for each instruction.
130 ///
131 bool IA64AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
132   SetupMachineFunction(MF);
133   O << "\n\n";
134
135   // Print out constants referenced by the function
136   EmitConstantPool(MF.getConstantPool());
137
138   const Function *F = MF.getFunction();
139   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
140
141   // Print out labels for the function.
142   EmitAlignment(5);
143   O << "\t.global\t" << CurrentFnName << "\n";
144   O << "\t.type\t" << CurrentFnName << ", @function\n";
145   O << CurrentFnName << ":\n";
146
147   // Print out code for the function.
148   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
149        I != E; ++I) {
150     // Print a label for the basic block if there are any predecessors.
151     if (I->pred_begin() != I->pred_end()) {
152       printBasicBlockLabel(I, true);
153       O << '\n';
154     }
155     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
156          II != E; ++II) {
157       // Print the assembly for the instruction.
158       O << "\t";
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 MRegisterInfo &RI = *TM.getRegisterInfo();
170   switch (MO.getType()) {
171   case MachineOperand::MO_Register:
172     O << RI.get(MO.getReg()).Name;
173     return;
174
175   case MachineOperand::MO_Immediate:
176     O << MO.getImmedValue();
177     return;
178   case MachineOperand::MO_MachineBasicBlock:
179     printBasicBlockLabel(MO.getMachineBasicBlock());
180     return;
181   case MachineOperand::MO_ConstantPoolIndex: {
182     O << "@gprel(" << TAI->getPrivateGlobalPrefix()
183       << "CPI" << getFunctionNumber() << "_"
184       << MO.getConstantPoolIndex() << ")";
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->isExternal()*/)
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->isExternal())
205       ExternalFunctionNames.insert(Mang->getValueName(MO.getGlobal()));
206     else
207       if (GV->isExternal()) // e.g. stuff like 'stdin'
208         ExternalObjectNames.insert(Mang->getValueName(MO.getGlobal()));
209
210     if (!isBRCALLinsn)
211       O << "@ltoff(";
212     if (Needfptr)
213       O << "@fptr(";
214     O << Mang->getValueName(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   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 false;
259 }
260
261 bool IA64AsmPrinter::doFinalization(Module &M) {
262   const TargetData *TD = TM.getTargetData();
263   
264   // Print out module-level global variables here.
265   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
266        I != E; ++I)
267     if (I->hasInitializer()) {   // External global require no code
268       // Check to see if this is a special global used by LLVM, if so, emit it.
269       if (EmitSpecialLLVMGlobal(I))
270         continue;
271       
272       O << "\n\n";
273       std::string name = Mang->getValueName(I);
274       Constant *C = I->getInitializer();
275       unsigned Size = TD->getTypeSize(C->getType());
276       unsigned Align = TD->getTypeAlignmentShift(C->getType());
277       
278       if (C->isNullValue() &&
279           (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
280            I->hasWeakLinkage() /* FIXME: Verify correct */)) {
281         SwitchToDataSection(".data", I);
282         if (I->hasInternalLinkage()) {
283           O << "\t.lcomm " << name << "#," << TD->getTypeSize(C->getType())
284           << "," << (1 << Align);
285           O << "\t\t// ";
286         } else {
287           O << "\t.common " << name << "#," << TD->getTypeSize(C->getType())
288           << "," << (1 << Align);
289           O << "\t\t// ";
290         }
291         WriteAsOperand(O, I, true, true, &M);
292         O << "\n";
293       } else {
294         switch (I->getLinkage()) {
295           case GlobalValue::LinkOnceLinkage:
296           case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
297                                            // Nonnull linkonce -> weak
298             O << "\t.weak " << name << "\n";
299             O << "\t.section\t.llvm.linkonce.d." << name
300               << ", \"aw\", \"progbits\"\n";
301             SwitchToDataSection("", I);
302             break;
303           case GlobalValue::AppendingLinkage:
304             // FIXME: appending linkage variables should go into a section of
305             // their name or something.  For now, just emit them as external.
306           case GlobalValue::ExternalLinkage:
307             // If external or appending, declare as a global symbol
308             O << "\t.global " << name << "\n";
309             // FALL THROUGH
310           case GlobalValue::InternalLinkage:
311             SwitchToDataSection(C->isNullValue() ? ".bss" : ".data", I);
312             break;
313           case GlobalValue::GhostLinkage:
314             std::cerr << "GhostLinkage cannot appear in IA64AsmPrinter!\n";
315             abort();
316           case GlobalValue::DLLImportLinkage:
317             std::cerr << "DLLImport linkage is not supported by this target!\n";
318             abort();
319           case GlobalValue::DLLExportLinkage:
320             std::cerr << "DLLExport linkage is not supported by this target!\n";
321             abort();
322           default:
323             assert(0 && "Unknown linkage type!");            
324         }
325         
326         EmitAlignment(Align);
327         O << "\t.type " << name << ",@object\n";
328         O << "\t.size " << name << "," << Size << "\n";
329         O << name << ":\t\t\t\t// ";
330         WriteAsOperand(O, I, true, true, &M);
331         O << " = ";
332         WriteAsOperand(O, C, false, false, &M);
333         O << "\n";
334         EmitGlobalConstant(C);
335       }
336     }
337       
338       // we print out ".global X \n .type X, @function" for each external function
339       O << "\n\n// br.call targets referenced (and not defined) above: \n";
340   for (std::set<std::string>::iterator i = ExternalFunctionNames.begin(),
341        e = ExternalFunctionNames.end(); i!=e; ++i) {
342     O << "\t.global " << *i << "\n\t.type " << *i << ", @function\n";
343   }
344   O << "\n\n";
345   
346   // we print out ".global X \n .type X, @object" for each external object
347   O << "\n\n// (external) symbols referenced (and not defined) above: \n";
348   for (std::set<std::string>::iterator i = ExternalObjectNames.begin(),
349        e = ExternalObjectNames.end(); i!=e; ++i) {
350     O << "\t.global " << *i << "\n\t.type " << *i << ", @object\n";
351   }
352   O << "\n\n";
353   
354   AsmPrinter::doFinalization(M);
355   return false; // success
356 }
357
358 /// createIA64CodePrinterPass - Returns a pass that prints the IA64
359 /// assembly code for a MachineFunction to the given output stream, using
360 /// the given target machine description.
361 ///
362 FunctionPass *llvm::createIA64CodePrinterPass(std::ostream &o,
363                                               IA64TargetMachine &tm) {
364   return new IA64AsmPrinter(o, tm, tm.getTargetAsmInfo());
365 }
366
367