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