- Switch X86-64 JIT to large code size model.
[oota-llvm.git] / lib / Target / X86 / X86ATTAsmPrinter.cpp
1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to Intel assembly ----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the 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 AT&T format assembly
12 // language. This printer is the output mechanism used by `llc'.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86ATTAsmPrinter.h"
17 #include "X86.h"
18 #include "X86MachineFunctionInfo.h"
19 #include "X86TargetMachine.h"
20 #include "X86TargetAsmInfo.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Module.h"
23 #include "llvm/Support/Mangler.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetOptions.h"
26 using namespace llvm;
27
28 /// getSectionForFunction - Return the section that we should emit the
29 /// specified function body into.
30 std::string X86ATTAsmPrinter::getSectionForFunction(const Function &F) const {
31   switch (F.getLinkage()) {
32   default: assert(0 && "Unknown linkage type!");
33   case Function::InternalLinkage: 
34   case Function::DLLExportLinkage:
35   case Function::ExternalLinkage:
36     return TAI->getTextSection();
37   case Function::WeakLinkage:
38   case Function::LinkOnceLinkage:
39     if (Subtarget->isTargetDarwin()) {
40       return ".section __TEXT,__textcoal_nt,coalesced,pure_instructions";
41     } else if (Subtarget->isTargetCygwin()) {
42       return "\t.section\t.text$linkonce." + CurrentFnName + ",\"ax\"\n";
43     } else {
44       return "\t.section\t.llvm.linkonce.t." + CurrentFnName +
45              ",\"ax\",@progbits\n";
46     }
47   }
48 }
49
50 /// runOnMachineFunction - This uses the printMachineInstruction()
51 /// method to print assembly for each instruction.
52 ///
53 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
54   if (Subtarget->isTargetDarwin() ||
55       Subtarget->isTargetELF() ||
56       Subtarget->isTargetCygwin()) {
57     // Let PassManager know we need debug information and relay
58     // the MachineDebugInfo address on to DwarfWriter.
59     DW.SetDebugInfo(&getAnalysis<MachineDebugInfo>());
60   }
61
62   SetupMachineFunction(MF);
63   O << "\n\n";
64
65   // Print out constants referenced by the function
66   EmitConstantPool(MF.getConstantPool());
67
68   // Print out labels for the function.
69   const Function *F = MF.getFunction();
70   unsigned CC = F->getCallingConv();
71
72   // Populate function information map.  Actually, We don't want to populate
73   // non-stdcall or non-fastcall functions' information right now.
74   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
75     FunctionInfoMap[F] = *MF.getInfo<X86FunctionInfo>();
76
77   X86SharedAsmPrinter::decorateName(CurrentFnName, F);
78
79   SwitchToTextSection(getSectionForFunction(*F).c_str(), F);
80   
81   switch (F->getLinkage()) {
82   default: assert(0 && "Unknown linkage type!");
83   case Function::InternalLinkage:  // Symbols default to internal.
84     EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
85     break;
86   case Function::DLLExportLinkage:
87     DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
88     //FALLS THROUGH
89   case Function::ExternalLinkage:
90     EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
91     O << "\t.globl\t" << CurrentFnName << "\n";    
92     break;
93   case Function::LinkOnceLinkage:
94   case Function::WeakLinkage:
95     if (Subtarget->isTargetDarwin()) {
96       O << "\t.globl\t" << CurrentFnName << "\n";
97       O << "\t.weak_definition\t" << CurrentFnName << "\n";
98     } else if (Subtarget->isTargetCygwin()) {
99       EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
100       O << "\t.linkonce discard\n";
101       O << "\t.globl " << CurrentFnName << "\n";
102     } else {
103       EmitAlignment(4, F);     // FIXME: This should be parameterized somewhere.
104       O << "\t.weak " << CurrentFnName << "\n";
105     }
106     break;
107   }
108   O << CurrentFnName << ":\n";
109   // Add some workaround for linkonce linkage on Cygwin\MinGW
110   if (Subtarget->isTargetCygwin() &&
111       (F->getLinkage() == Function::LinkOnceLinkage ||
112        F->getLinkage() == Function::WeakLinkage))
113     O << "_llvm$workaround$fake$stub_" << CurrentFnName << ":\n";
114
115   if (Subtarget->isTargetDarwin() ||
116       Subtarget->isTargetELF() ||
117       Subtarget->isTargetCygwin()) {
118     // Emit pre-function debug information.
119     DW.BeginFunction(&MF);
120   }
121
122   // Print out code for the function.
123   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
124        I != E; ++I) {
125     // Print a label for the basic block.
126     if (I->pred_begin() != I->pred_end()) {
127       printBasicBlockLabel(I, true);
128       O << '\n';
129     }
130     for (MachineBasicBlock::const_iterator II = I->begin(), E = I->end();
131          II != E; ++II) {
132       // Print the assembly for the instruction.
133       O << "\t";
134       printMachineInstruction(II);
135     }
136   }
137
138   // Print out jump tables referenced by the function.
139   
140   // Mac OS X requires that the jump table follow the function, so that the jump
141   // table is part of the same atom that the function is in.
142   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
143   
144   if (TAI->hasDotTypeDotSizeDirective())
145     O << "\t.size " << CurrentFnName << ", .-" << CurrentFnName << "\n";
146
147   if (Subtarget->isTargetDarwin() ||
148       Subtarget->isTargetELF() ||
149       Subtarget->isTargetCygwin()) {
150     // Emit post-function debug information.
151     DW.EndFunction();
152   }
153
154   // We didn't modify anything.
155   return false;
156 }
157
158 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
159                                     const char *Modifier, bool NotRIPRel) {
160   const MachineOperand &MO = MI->getOperand(OpNo);
161   const MRegisterInfo &RI = *TM.getRegisterInfo();
162   switch (MO.getType()) {
163   case MachineOperand::MO_Register: {
164     assert(MRegisterInfo::isPhysicalRegister(MO.getReg()) &&
165            "Virtual registers should not make it this far!");
166     O << '%';
167     unsigned Reg = MO.getReg();
168     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
169       MVT::ValueType VT = (strcmp(Modifier+6,"64") == 0) ?
170         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
171                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
172       Reg = getX86SubSuperRegister(Reg, VT);
173     }
174     for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
175       O << (char)tolower(*Name);
176     return;
177   }
178
179   case MachineOperand::MO_Immediate:
180     if (!Modifier || strcmp(Modifier, "debug") != 0)
181       O << '$';
182     O << MO.getImmedValue();
183     return;
184   case MachineOperand::MO_MachineBasicBlock:
185     printBasicBlockLabel(MO.getMachineBasicBlock());
186     return;
187   case MachineOperand::MO_JumpTableIndex: {
188     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
189     if (!isMemOp) O << '$';
190     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << "_"
191       << MO.getJumpTableIndex();
192     if (X86PICStyle == PICStyle::Stub &&
193         TM.getRelocationModel() == Reloc::PIC_)
194       O << "-\"L" << getFunctionNumber() << "$pb\"";
195     if (isMemOp && Subtarget->is64Bit() && !NotRIPRel)
196       O << "(%rip)";
197     return;
198   }
199   case MachineOperand::MO_ConstantPoolIndex: {
200     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
201     if (!isMemOp) O << '$';
202     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << "_"
203       << MO.getConstantPoolIndex();
204     if (X86PICStyle == PICStyle::Stub &&
205         TM.getRelocationModel() == Reloc::PIC_)
206       O << "-\"L" << getFunctionNumber() << "$pb\"";
207     int Offset = MO.getOffset();
208     if (Offset > 0)
209       O << "+" << Offset;
210     else if (Offset < 0)
211       O << Offset;
212
213     if (isMemOp && Subtarget->is64Bit() && !NotRIPRel)
214       O << "(%rip)";
215     return;
216   }
217   case MachineOperand::MO_GlobalAddress: {
218     bool isCallOp = Modifier && !strcmp(Modifier, "call");
219     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
220     if (!isMemOp && !isCallOp) O << '$';
221
222     GlobalValue *GV = MO.getGlobal();
223     std::string Name = Mang->getValueName(GV);
224     
225     bool isExt = (GV->isExternal() || GV->hasWeakLinkage() ||
226                   GV->hasLinkOnceLinkage());
227     
228     X86SharedAsmPrinter::decorateName(Name, GV);
229     
230     if (X86PICStyle == PICStyle::Stub &&
231         TM.getRelocationModel() != Reloc::Static) {
232       // Link-once, External, or Weakly-linked global variables need
233       // non-lazily-resolved stubs
234       if (isExt) {
235         // Dynamically-resolved functions need a stub for the function.
236         if (isCallOp && isa<Function>(GV)) {
237           FnStubs.insert(Name);
238           O << "L" << Name << "$stub";
239         } else {
240           GVStubs.insert(Name);
241           O << "L" << Name << "$non_lazy_ptr";
242         }
243       } else {
244         if (GV->hasDLLImportLinkage()) {
245           O << "__imp_";          
246         } 
247         O << Name;
248       }
249       
250       if (!isCallOp && TM.getRelocationModel() == Reloc::PIC_)
251         O << "-\"L" << getFunctionNumber() << "$pb\"";
252     } else {
253       if (GV->hasDLLImportLinkage()) {
254         O << "__imp_";          
255       }       
256       O << Name;
257     }
258
259     if (GV->hasExternalWeakLinkage())
260       ExtWeakSymbols.insert(Name);
261     
262     int Offset = MO.getOffset();
263     if (Offset > 0)
264       O << "+" << Offset;
265     else if (Offset < 0)
266       O << Offset;
267
268     if (isMemOp && Subtarget->is64Bit()) {
269       if (isExt && TM.getRelocationModel() != Reloc::Static)
270         O << "@GOTPCREL(%rip)";
271       else if (!NotRIPRel)
272         // Use rip when possible to reduce code size, except when index or
273         // base register are also part of the address. e.g.
274         // foo(%rip)(%rcx,%rax,4) is not legal
275         O << "(%rip)";        
276     }
277
278     return;
279   }
280   case MachineOperand::MO_ExternalSymbol: {
281     bool isCallOp = Modifier && !strcmp(Modifier, "call");
282     if (isCallOp && 
283         X86PICStyle == PICStyle::Stub &&
284         TM.getRelocationModel() != Reloc::Static) {
285       std::string Name(TAI->getGlobalPrefix());
286       Name += MO.getSymbolName();
287       FnStubs.insert(Name);
288       O << "L" << Name << "$stub";
289       return;
290     }
291     if (!isCallOp) O << '$';
292     O << TAI->getGlobalPrefix() << MO.getSymbolName();
293
294     if (!isCallOp && Subtarget->is64Bit())
295       O << "(%rip)";
296
297     return;
298   }
299   default:
300     O << "<unknown operand type>"; return;
301   }
302 }
303
304 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
305   unsigned char value = MI->getOperand(Op).getImmedValue();
306   assert(value <= 7 && "Invalid ssecc argument!");
307   switch (value) {
308   case 0: O << "eq"; break;
309   case 1: O << "lt"; break;
310   case 2: O << "le"; break;
311   case 3: O << "unord"; break;
312   case 4: O << "neq"; break;
313   case 5: O << "nlt"; break;
314   case 6: O << "nle"; break;
315   case 7: O << "ord"; break;
316   }
317 }
318
319 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
320                                          const char *Modifier){
321   assert(isMem(MI, Op) && "Invalid memory reference!");
322
323   const MachineOperand &BaseReg  = MI->getOperand(Op);
324   int ScaleVal                   = MI->getOperand(Op+1).getImmedValue();
325   const MachineOperand &IndexReg = MI->getOperand(Op+2);
326   const MachineOperand &DispSpec = MI->getOperand(Op+3);
327
328   if (BaseReg.isFrameIndex()) {
329     O << "[frame slot #" << BaseReg.getFrameIndex();
330     if (DispSpec.getImmedValue())
331       O << " + " << DispSpec.getImmedValue();
332     O << "]";
333     return;
334   }
335
336   bool NotRIPRel = IndexReg.getReg() || BaseReg.getReg();
337   if (DispSpec.isGlobalAddress() ||
338       DispSpec.isConstantPoolIndex() ||
339       DispSpec.isJumpTableIndex()) {
340     printOperand(MI, Op+3, "mem", NotRIPRel);
341   } else {
342     int DispVal = DispSpec.getImmedValue();
343     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
344       O << DispVal;
345   }
346
347   if (IndexReg.getReg() || BaseReg.getReg()) {
348     O << "(";
349     if (BaseReg.getReg()) {
350       printOperand(MI, Op, Modifier);
351     }
352
353     if (IndexReg.getReg()) {
354       O << ",";
355       printOperand(MI, Op+2, Modifier);
356       if (ScaleVal != 1)
357         O << "," << ScaleVal;
358     }
359
360     O << ")";
361   }
362 }
363
364 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
365   O << "\"L" << getFunctionNumber() << "$pb\"\n";
366   O << "\"L" << getFunctionNumber() << "$pb\":";
367 }
368
369
370 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO,
371                                          const char Mode) {
372   const MRegisterInfo &RI = *TM.getRegisterInfo();
373   unsigned Reg = MO.getReg();
374   switch (Mode) {
375   default: return true;  // Unknown mode.
376   case 'b': // Print QImode register
377     Reg = getX86SubSuperRegister(Reg, MVT::i8);
378     break;
379   case 'h': // Print QImode high register
380     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
381     break;
382   case 'w': // Print HImode register
383     Reg = getX86SubSuperRegister(Reg, MVT::i16);
384     break;
385   case 'k': // Print SImode register
386     Reg = getX86SubSuperRegister(Reg, MVT::i32);
387     break;
388   }
389
390   O << '%';
391   for (const char *Name = RI.get(Reg).Name; *Name; ++Name)
392     O << (char)tolower(*Name);
393   return false;
394 }
395
396 /// PrintAsmOperand - Print out an operand for an inline asm expression.
397 ///
398 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
399                                        unsigned AsmVariant, 
400                                        const char *ExtraCode) {
401   // Does this asm operand have a single letter operand modifier?
402   if (ExtraCode && ExtraCode[0]) {
403     if (ExtraCode[1] != 0) return true; // Unknown modifier.
404     
405     switch (ExtraCode[0]) {
406     default: return true;  // Unknown modifier.
407     case 'c': // Don't print "$" before a global var name.
408       printOperand(MI, OpNo, "mem");
409       return false;
410     case 'b': // Print QImode register
411     case 'h': // Print QImode high register
412     case 'w': // Print HImode register
413     case 'k': // Print SImode register
414       return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
415     }
416   }
417   
418   printOperand(MI, OpNo);
419   return false;
420 }
421
422 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
423                                              unsigned OpNo,
424                                              unsigned AsmVariant, 
425                                              const char *ExtraCode) {
426   if (ExtraCode && ExtraCode[0])
427     return true; // Unknown modifier.
428   printMemReference(MI, OpNo);
429   return false;
430 }
431
432 /// printMachineInstruction -- Print out a single X86 LLVM instruction
433 /// MI in Intel syntax to the current output stream.
434 ///
435 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
436   ++EmittedInsts;
437
438   // See if a truncate instruction can be turned into a nop.
439   switch (MI->getOpcode()) {
440   default: break;
441   case X86::TRUNC_64to32:
442   case X86::TRUNC_64to16:
443   case X86::TRUNC_32to16:
444   case X86::TRUNC_32to8:
445   case X86::TRUNC_16to8:
446   case X86::TRUNC_32_to8:
447   case X86::TRUNC_16_to8: {
448     const MachineOperand &MO0 = MI->getOperand(0);
449     const MachineOperand &MO1 = MI->getOperand(1);
450     unsigned Reg0 = MO0.getReg();
451     unsigned Reg1 = MO1.getReg();
452     unsigned Opc = MI->getOpcode();
453     if (Opc == X86::TRUNC_64to32)
454       Reg1 = getX86SubSuperRegister(Reg1, MVT::i32);
455     else if (Opc == X86::TRUNC_32to16 || Opc == X86::TRUNC_64to16)
456       Reg1 = getX86SubSuperRegister(Reg1, MVT::i16);
457     else
458       Reg1 = getX86SubSuperRegister(Reg1, MVT::i8);
459     O << TAI->getCommentString() << " TRUNCATE ";
460     if (Reg0 != Reg1)
461       O << "\n\t";
462     break;
463   }
464   case X86::PsMOVZX64rr32:
465     O << TAI->getCommentString() << " ZERO-EXTEND " << "\n\t";
466     break;
467   }
468
469   // Call the autogenerated instruction printer routines.
470   printInstruction(MI);
471 }
472
473 // Include the auto-generated portion of the assembly writer.
474 #include "X86GenAsmWriter.inc"
475