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