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