a3618751fb958f1c64648397868db50c8e77281c
[oota-llvm.git] / lib / Target / X86 / AsmPrinter / X86ATTAsmPrinter.cpp
1 //===-- X86ATTAsmPrinter.cpp - Convert X86 LLVM code to AT&T assembly -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // 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/CallingConv.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Module.h"
26 #include "llvm/Type.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCStreamer.h"
32 #include "llvm/CodeGen/DwarfWriter.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetAsmInfo.h"
38 #include "llvm/Target/TargetOptions.h"
39 using namespace llvm;
40
41 STATISTIC(EmittedInsts, "Number of machine instrs printed");
42
43 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
44                                    cl::Hidden);
45
46
47 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
48   if (Subtarget->isTargetDarwin())
49     O << "\"L" << getFunctionNumber() << "$pb\"";
50   else if (Subtarget->isTargetELF())
51     O << ".Lllvm$" << getFunctionNumber() << "." "$piclabel";
52   else
53     assert(0 && "Don't know how to print PIC label!\n");
54 }
55
56
57 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
58                                                     const TargetData *TD) {
59   X86MachineFunctionInfo Info;
60   uint64_t Size = 0;
61
62   switch (F->getCallingConv()) {
63   case CallingConv::X86_StdCall:
64     Info.setDecorationStyle(StdCall);
65     break;
66   case CallingConv::X86_FastCall:
67     Info.setDecorationStyle(FastCall);
68     break;
69   default:
70     return Info;
71   }
72
73   unsigned argNum = 1;
74   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
75        AI != AE; ++AI, ++argNum) {
76     const Type* Ty = AI->getType();
77
78     // 'Dereference' type in case of byval parameter attribute
79     if (F->paramHasAttr(argNum, Attribute::ByVal))
80       Ty = cast<PointerType>(Ty)->getElementType();
81
82     // Size should be aligned to DWORD boundary
83     Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
84   }
85
86   // We're not supporting tooooo huge arguments :)
87   Info.setBytesToPopOnReturn((unsigned int)Size);
88   return Info;
89 }
90
91 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
92 /// Don't print things like \\n or \\0.
93 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
94   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
95        Name != E; ++Name)
96     if (isprint(*Name))
97       OS << *Name;
98 }
99
100 /// decorateName - Query FunctionInfoMap and use this information for various
101 /// name decoration.
102 void X86ATTAsmPrinter::decorateName(std::string &Name,
103                                     const GlobalValue *GV) {
104   const Function *F = dyn_cast<Function>(GV);
105   if (!F) return;
106
107   // We don't want to decorate non-stdcall or non-fastcall functions right now
108   unsigned CC = F->getCallingConv();
109   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
110     return;
111
112   // Decorate names only when we're targeting Cygwin/Mingw32 targets
113   if (!Subtarget->isTargetCygMing())
114     return;
115
116   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
117
118   const X86MachineFunctionInfo *Info;
119   if (info_item == FunctionInfoMap.end()) {
120     // Calculate apropriate function info and populate map
121     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
122     Info = &FunctionInfoMap[F];
123   } else {
124     Info = &info_item->second;
125   }
126
127   const FunctionType *FT = F->getFunctionType();
128   switch (Info->getDecorationStyle()) {
129   case None:
130     break;
131   case StdCall:
132     // "Pure" variadic functions do not receive @0 suffix.
133     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
134         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
135       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
136     break;
137   case FastCall:
138     // "Pure" variadic functions do not receive @0 suffix.
139     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
140         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
141       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
142
143     if (Name[0] == '_') {
144       Name[0] = '@';
145     } else {
146       Name = '@' + Name;
147     }
148     break;
149   default:
150     assert(0 && "Unsupported DecorationStyle");
151   }
152 }
153
154 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
155   const Function *F = MF.getFunction();
156
157   decorateName(CurrentFnName, F);
158
159   SwitchToSection(TAI->SectionForGlobal(F));
160
161   unsigned FnAlign = 4;
162   if (F->hasFnAttr(Attribute::OptimizeForSize))
163     FnAlign = 1;
164   switch (F->getLinkage()) {
165   default: assert(0 && "Unknown linkage type!");
166   case Function::InternalLinkage:  // Symbols default to internal.
167   case Function::PrivateLinkage:
168     EmitAlignment(FnAlign, F);
169     break;
170   case Function::DLLExportLinkage:
171   case Function::ExternalLinkage:
172     EmitAlignment(FnAlign, F);
173     O << "\t.globl\t" << CurrentFnName << '\n';
174     break;
175   case Function::LinkOnceAnyLinkage:
176   case Function::LinkOnceODRLinkage:
177   case Function::WeakAnyLinkage:
178   case Function::WeakODRLinkage:
179     EmitAlignment(FnAlign, F);
180     if (Subtarget->isTargetDarwin()) {
181       O << "\t.globl\t" << CurrentFnName << '\n';
182       O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
183     } else if (Subtarget->isTargetCygMing()) {
184       O << "\t.globl\t" << CurrentFnName << "\n"
185            "\t.linkonce discard\n";
186     } else {
187       O << "\t.weak\t" << CurrentFnName << '\n';
188     }
189     break;
190   }
191
192   printVisibility(CurrentFnName, F->getVisibility());
193
194   if (Subtarget->isTargetELF())
195     O << "\t.type\t" << CurrentFnName << ",@function\n";
196   else if (Subtarget->isTargetCygMing()) {
197     O << "\t.def\t " << CurrentFnName
198       << ";\t.scl\t" <<
199       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
200       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
201       << ";\t.endef\n";
202   }
203
204   O << CurrentFnName << ":\n";
205   // Add some workaround for linkonce linkage on Cygwin\MinGW
206   if (Subtarget->isTargetCygMing() &&
207       (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
208     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
209 }
210
211 /// runOnMachineFunction - This uses the printMachineInstruction()
212 /// method to print assembly for each instruction.
213 ///
214 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
215   const Function *F = MF.getFunction();
216   this->MF = &MF;
217   unsigned CC = F->getCallingConv();
218
219   SetupMachineFunction(MF);
220   O << "\n\n";
221
222   // Populate function information map.  Actually, We don't want to populate
223   // non-stdcall or non-fastcall functions' information right now.
224   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
225     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
226
227   // Print out constants referenced by the function
228   EmitConstantPool(MF.getConstantPool());
229
230   if (F->hasDLLExportLinkage())
231     DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
232
233   // Print the 'header' of function
234   emitFunctionHeader(MF);
235
236   // Emit pre-function debug and/or EH information.
237   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
238     DW->BeginFunction(&MF);
239
240   // Print out code for the function.
241   bool hasAnyRealCode = false;
242   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
243        I != E; ++I) {
244     // Print a label for the basic block.
245     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
246       // This is an entry block or a block that's only reachable via a
247       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
248     } else {
249       printBasicBlockLabel(I, true, true, VerboseAsm);
250       O << '\n';
251     }
252     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
253          II != IE; ++II) {
254       // Print the assembly for the instruction.
255       if (!II->isLabel())
256         hasAnyRealCode = true;
257       printMachineInstruction(II);
258     }
259   }
260
261   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
262     // If the function is empty, then we need to emit *something*. Otherwise,
263     // the function's label might be associated with something that it wasn't
264     // meant to be associated with. We emit a noop in this situation.
265     // We are assuming inline asms are code.
266     O << "\tnop\n";
267   }
268
269   if (TAI->hasDotTypeDotSizeDirective())
270     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
271
272   // Emit post-function debug information.
273   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
274     DW->EndFunction(&MF);
275
276   // Print out jump tables referenced by the function.
277   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
278
279   O.flush();
280
281   // We didn't modify anything.
282   return false;
283 }
284
285 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
286   return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
287 }
288
289 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
290   return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
291       (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
292 }
293
294 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
295   return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
296 }
297
298 /// print_pcrel_imm - This is used to print an immediate value that ends up
299 /// being encoded as a pc-relative value.  These print slightly differently, for
300 /// example, a $ is not emitted.
301 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
302   const MachineOperand &MO = MI->getOperand(OpNo);
303   switch (MO.getType()) {
304   default: assert(0 && "Unknown pcrel immediate operand");
305   case MachineOperand::MO_Immediate:
306     O << MO.getImm();
307     return;
308   case MachineOperand::MO_MachineBasicBlock:
309     printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
310     return;
311       
312   case MachineOperand::MO_GlobalAddress: {
313     const GlobalValue *GV = MO.getGlobal();
314     std::string Name = Mang->getValueName(GV);
315     decorateName(Name, GV);
316     
317     bool needCloseParen = false;
318     if (Name[0] == '$') {
319       // The name begins with a dollar-sign. In order to avoid having it look
320       // like an integer immediate to the assembler, enclose it in parens.
321       O << '(';
322       needCloseParen = true;
323     }
324     
325     if (shouldPrintStub(TM, Subtarget)) {
326       // Link-once, declaration, or Weakly-linked global variables need
327       // non-lazily-resolved stubs
328       if (GV->isDeclaration() || GV->isWeakForLinker()) {
329         // Dynamically-resolved functions need a stub for the function.
330         if (isa<Function>(GV)) {
331           // Function stubs are no longer needed for Mac OS X 10.5 and up.
332           if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
333             O << Name;
334           } else {
335             FnStubs.insert(Name);
336             printSuffixedName(Name, "$stub");
337           }
338         } else if (GV->hasHiddenVisibility()) {
339           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
340             // Definition is not definitely in the current translation unit.
341             O << Name;
342           else {
343             HiddenGVStubs.insert(Name);
344             printSuffixedName(Name, "$non_lazy_ptr");
345           }
346         } else {
347           GVStubs.insert(Name);
348           printSuffixedName(Name, "$non_lazy_ptr");
349         }
350       } else {
351         if (GV->hasDLLImportLinkage())
352           O << "__imp_";
353         O << Name;
354       }
355     } else {
356       if (GV->hasDLLImportLinkage()) {
357         O << "__imp_";
358       }
359       O << Name;
360       
361       if (shouldPrintPLT(TM, Subtarget)) {
362         // Assemble call via PLT for externally visible symbols
363         if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
364             !GV->hasLocalLinkage())
365           O << "@PLT";
366       }
367       if (Subtarget->isTargetCygMing() && GV->isDeclaration())
368         // Save function name for later type emission
369         FnStubs.insert(Name);
370     }
371     
372     printOffset(MO.getOffset());
373     
374     if (needCloseParen)
375       O << ')';
376     return;
377   }
378       
379   case MachineOperand::MO_ExternalSymbol: {
380     bool needCloseParen = false;
381     std::string Name(TAI->getGlobalPrefix());
382     Name += MO.getSymbolName();
383     // Print function stub suffix unless it's Mac OS X 10.5 and up.
384     if (shouldPrintStub(TM, Subtarget) && 
385         !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
386       FnStubs.insert(Name);
387       printSuffixedName(Name, "$stub");
388       return;
389     }
390     
391     if (Name[0] == '$') {
392       // The name begins with a dollar-sign. In order to avoid having it look
393       // like an integer immediate to the assembler, enclose it in parens.
394       O << '(';
395       needCloseParen = true;
396     }
397     
398     O << Name;
399     
400     if (shouldPrintPLT(TM, Subtarget)) {
401       std::string GOTName(TAI->getGlobalPrefix());
402       GOTName+="_GLOBAL_OFFSET_TABLE_";
403       if (Name == GOTName) {
404         // HACK! Emit extra offset to PC during printing GOT offset to
405         // compensate for the size of popl instruction. The resulting code
406         // should look like:
407         //   call .piclabel
408         // piclabel:
409         //   popl %some_register
410         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
411         O << " + [.-";
412         PrintPICBaseSymbol();
413         O << ']';
414       }
415       
416       O << "@PLT";
417     }
418     
419     if (needCloseParen)
420       O << ')';
421     
422     return;
423   }
424   }
425 }
426
427 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
428                                     const char *Modifier, bool NotRIPRel) {
429   const MachineOperand &MO = MI->getOperand(OpNo);
430   switch (MO.getType()) {
431   case MachineOperand::MO_Register: {
432     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
433            "Virtual registers should not make it this far!");
434     O << '%';
435     unsigned Reg = MO.getReg();
436     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
437       MVT VT = (strcmp(Modifier+6,"64") == 0) ?
438         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
439                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
440       Reg = getX86SubSuperRegister(Reg, VT);
441     }
442     O << TRI->getAsmName(Reg);
443     return;
444   }
445
446   case MachineOperand::MO_Immediate:
447     if (!Modifier || (strcmp(Modifier, "debug") &&
448                       strcmp(Modifier, "mem")))
449       O << '$';
450     O << MO.getImm();
451     return;
452   case MachineOperand::MO_JumpTableIndex: {
453     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
454     if (!isMemOp) O << '$';
455     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
456       << MO.getIndex();
457
458     if (TM.getRelocationModel() == Reloc::PIC_) {
459       if (Subtarget->isPICStyleStub())
460         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
461           << "$pb\"";
462       else if (Subtarget->isPICStyleGOT())
463         O << "@GOTOFF";
464     }
465
466     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
467       O << "(%rip)";
468     return;
469   }
470   case MachineOperand::MO_ConstantPoolIndex: {
471     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
472     if (!isMemOp) O << '$';
473     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
474       << MO.getIndex();
475
476     if (TM.getRelocationModel() == Reloc::PIC_) {
477       if (Subtarget->isPICStyleStub())
478         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
479           << "$pb\"";
480       else if (Subtarget->isPICStyleGOT())
481         O << "@GOTOFF";
482     }
483
484     printOffset(MO.getOffset());
485
486     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
487       O << "(%rip)";
488     return;
489   }
490   case MachineOperand::MO_GlobalAddress: {
491     bool isMemOp = Modifier && !strcmp(Modifier, "mem");
492     bool needCloseParen = false;
493
494     const GlobalValue *GV = MO.getGlobal();
495     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
496     if (!GVar) {
497       // If GV is an alias then use the aliasee for determining
498       // thread-localness.
499       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
500         GVar =dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
501     }
502
503     bool isThreadLocal = GVar && GVar->isThreadLocal();
504
505     std::string Name = Mang->getValueName(GV);
506     decorateName(Name, GV);
507
508     if (!isMemOp)
509       O << '$';
510     else if (Name[0] == '$') {
511       // The name begins with a dollar-sign. In order to avoid having it look
512       // like an integer immediate to the assembler, enclose it in parens.
513       O << '(';
514       needCloseParen = true;
515     }
516
517     if (shouldPrintStub(TM, Subtarget)) {
518       // Link-once, declaration, or Weakly-linked global variables need
519       // non-lazily-resolved stubs
520       if (GV->isDeclaration() || GV->isWeakForLinker()) {
521         // Dynamically-resolved functions need a stub for the function.
522         if (GV->hasHiddenVisibility()) {
523           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
524             // Definition is not definitely in the current translation unit.
525             O << Name;
526           else {
527             HiddenGVStubs.insert(Name);
528             printSuffixedName(Name, "$non_lazy_ptr");
529           }
530         } else {
531           GVStubs.insert(Name);
532           printSuffixedName(Name, "$non_lazy_ptr");
533         }
534       } else {
535         if (GV->hasDLLImportLinkage())
536           O << "__imp_";
537         O << Name;
538       }
539
540       if (TM.getRelocationModel() == Reloc::PIC_) {
541         O << '-';
542         PrintPICBaseSymbol();
543       }        
544     } else {
545       if (GV->hasDLLImportLinkage())
546         O << "__imp_";
547       O << Name;
548     }
549
550     printOffset(MO.getOffset());
551
552     if (needCloseParen)
553       O << ')';
554     
555     bool isRIPRelative = false;
556     if (isThreadLocal) {
557       TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
558       switch (model) {
559       case TLSModel::GeneralDynamic:
560         O << "@TLSGD";
561         break;
562       case TLSModel::LocalDynamic:
563         // O << "@TLSLD"; // local dynamic not implemented
564         O << "@TLSGD";
565         break;
566       case TLSModel::InitialExec:
567         if (Subtarget->is64Bit()) {
568           assert (!NotRIPRel);
569           O << "@GOTTPOFF";
570           isRIPRelative = true;
571         } else {
572           O << "@INDNTPOFF";
573         }
574         break;
575       case TLSModel::LocalExec:
576         if (Subtarget->is64Bit())
577           O << "@TPOFF";
578         else
579           O << "@NTPOFF";
580         break;
581       default:
582         assert (0 && "Unknown TLS model");
583       }
584     } else if (isMemOp) {
585       if (shouldPrintGOT(TM, Subtarget)) {
586         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
587           O << "@GOT";
588         else
589           O << "@GOTOFF";
590       } else if (Subtarget->isPICStyleRIPRel() &&
591                  !NotRIPRel) {
592         if (TM.getRelocationModel() != Reloc::Static) {
593           if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
594             O << "@GOTPCREL";
595         }
596         
597         isRIPRelative = true;
598       }
599     }
600
601     // Use rip when possible to reduce code size, except when
602     // index or base register are also part of the address. e.g.
603     // foo(%rip)(%rcx,%rax,4) is not legal.
604     if (isRIPRelative)
605       O << "(%rip)";
606     
607     return;
608   }
609   case MachineOperand::MO_ExternalSymbol: {
610     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
611     bool needCloseParen = false;
612     std::string Name(TAI->getGlobalPrefix());
613     Name += MO.getSymbolName();
614
615     // Print function stub suffix unless it's Mac OS X 10.5 and up.
616     if (!isMemOp)
617       O << '$';
618     else if (Name[0] == '$') {
619       // The name begins with a dollar-sign. In order to avoid having it look
620       // like an integer immediate to the assembler, enclose it in parens.
621       O << '(';
622       needCloseParen = true;
623     }
624
625     O << Name;
626
627     if (shouldPrintPLT(TM, Subtarget)) {
628       std::string GOTName(TAI->getGlobalPrefix());
629       GOTName+="_GLOBAL_OFFSET_TABLE_";
630       if (Name == GOTName) {
631         // HACK! Emit extra offset to PC during printing GOT offset to
632         // compensate for the size of popl instruction. The resulting code
633         // should look like:
634         //   call .piclabel
635         // piclabel:
636         //   popl %some_register
637         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
638         O << " + [.-";
639         PrintPICBaseSymbol();
640         O << ']';
641       }
642     }
643
644     if (needCloseParen)
645       O << ')';
646
647     if (Subtarget->isPICStyleRIPRel())
648       O << "(%rip)";
649     return;
650   }
651   default:
652     O << "<unknown operand type>"; return;
653   }
654 }
655
656 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
657   unsigned char value = MI->getOperand(Op).getImm();
658   assert(value <= 7 && "Invalid ssecc argument!");
659   switch (value) {
660   case 0: O << "eq"; break;
661   case 1: O << "lt"; break;
662   case 2: O << "le"; break;
663   case 3: O << "unord"; break;
664   case 4: O << "neq"; break;
665   case 5: O << "nlt"; break;
666   case 6: O << "nle"; break;
667   case 7: O << "ord"; break;
668   }
669 }
670
671 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
672                                             const char *Modifier,
673                                             bool NotRIPRel) {
674   MachineOperand BaseReg  = MI->getOperand(Op);
675   MachineOperand IndexReg = MI->getOperand(Op+2);
676   const MachineOperand &DispSpec = MI->getOperand(Op+3);
677
678   NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
679   if (DispSpec.isGlobal() ||
680       DispSpec.isCPI() ||
681       DispSpec.isJTI() ||
682       DispSpec.isSymbol()) {
683     printOperand(MI, Op+3, "mem", NotRIPRel);
684   } else {
685     int DispVal = DispSpec.getImm();
686     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
687       O << DispVal;
688   }
689
690   if (IndexReg.getReg() || BaseReg.getReg()) {
691     unsigned ScaleVal = MI->getOperand(Op+1).getImm();
692     unsigned BaseRegOperand = 0, IndexRegOperand = 2;
693
694     // There are cases where we can end up with ESP/RSP in the indexreg slot.
695     // If this happens, swap the base/index register to support assemblers that
696     // don't work when the index is *SP.
697     if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
698       assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
699       std::swap(BaseReg, IndexReg);
700       std::swap(BaseRegOperand, IndexRegOperand);
701     }
702
703     O << '(';
704     if (BaseReg.getReg())
705       printOperand(MI, Op+BaseRegOperand, Modifier);
706
707     if (IndexReg.getReg()) {
708       O << ',';
709       printOperand(MI, Op+IndexRegOperand, Modifier);
710       if (ScaleVal != 1)
711         O << ',' << ScaleVal;
712     }
713     O << ')';
714   }
715 }
716
717 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
718                                          const char *Modifier, bool NotRIPRel){
719   assert(isMem(MI, Op) && "Invalid memory reference!");
720   MachineOperand Segment = MI->getOperand(Op+4);
721   if (Segment.getReg()) {
722       printOperand(MI, Op+4, Modifier);
723       O << ':';
724     }
725   printLeaMemReference(MI, Op, Modifier, NotRIPRel);
726 }
727
728 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
729                                            const MachineBasicBlock *MBB) const {
730   if (!TAI->getSetDirective())
731     return;
732
733   // We don't need .set machinery if we have GOT-style relocations
734   if (Subtarget->isPICStyleGOT())
735     return;
736
737   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
738     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
739   printBasicBlockLabel(MBB, false, false, false);
740   if (Subtarget->isPICStyleRIPRel())
741     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
742       << '_' << uid << '\n';
743   else {
744     O << '-';
745     PrintPICBaseSymbol();
746     O << '\n';
747   }
748 }
749
750
751 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
752   PrintPICBaseSymbol();
753   O << '\n';
754   PrintPICBaseSymbol();
755   O << ':';
756 }
757
758
759 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
760                                               const MachineBasicBlock *MBB,
761                                               unsigned uid) const
762 {
763   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
764     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
765
766   O << JTEntryDirective << ' ';
767
768   if (TM.getRelocationModel() == Reloc::PIC_) {
769     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
770       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
771         << '_' << uid << "_set_" << MBB->getNumber();
772     } else if (Subtarget->isPICStyleGOT()) {
773       printBasicBlockLabel(MBB, false, false, false);
774       O << "@GOTOFF";
775     } else
776       assert(0 && "Don't know how to print MBB label for this PIC mode");
777   } else
778     printBasicBlockLabel(MBB, false, false, false);
779 }
780
781 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
782   unsigned Reg = MO.getReg();
783   switch (Mode) {
784   default: return true;  // Unknown mode.
785   case 'b': // Print QImode register
786     Reg = getX86SubSuperRegister(Reg, MVT::i8);
787     break;
788   case 'h': // Print QImode high register
789     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
790     break;
791   case 'w': // Print HImode register
792     Reg = getX86SubSuperRegister(Reg, MVT::i16);
793     break;
794   case 'k': // Print SImode register
795     Reg = getX86SubSuperRegister(Reg, MVT::i32);
796     break;
797   case 'q': // Print DImode register
798     Reg = getX86SubSuperRegister(Reg, MVT::i64);
799     break;
800   }
801
802   O << '%'<< TRI->getAsmName(Reg);
803   return false;
804 }
805
806 /// PrintAsmOperand - Print out an operand for an inline asm expression.
807 ///
808 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
809                                        unsigned AsmVariant,
810                                        const char *ExtraCode) {
811   // Does this asm operand have a single letter operand modifier?
812   if (ExtraCode && ExtraCode[0]) {
813     if (ExtraCode[1] != 0) return true; // Unknown modifier.
814
815     switch (ExtraCode[0]) {
816     default: return true;  // Unknown modifier.
817     case 'c': // Don't print "$" before a global var name or constant.
818       printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
819       return false;
820     case 'b': // Print QImode register
821     case 'h': // Print QImode high register
822     case 'w': // Print HImode register
823     case 'k': // Print SImode register
824     case 'q': // Print DImode register
825       if (MI->getOperand(OpNo).isReg())
826         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
827       printOperand(MI, OpNo);
828       return false;
829
830     case 'P': // Don't print @PLT, but do print as memory.
831       printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
832       return false;
833     }
834   }
835
836   printOperand(MI, OpNo);
837   return false;
838 }
839
840 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
841                                              unsigned OpNo,
842                                              unsigned AsmVariant,
843                                              const char *ExtraCode) {
844   if (ExtraCode && ExtraCode[0]) {
845     if (ExtraCode[1] != 0) return true; // Unknown modifier.
846
847     switch (ExtraCode[0]) {
848     default: return true;  // Unknown modifier.
849     case 'b': // Print QImode register
850     case 'h': // Print QImode high register
851     case 'w': // Print HImode register
852     case 'k': // Print SImode register
853     case 'q': // Print SImode register
854       // These only apply to registers, ignore on mem.
855       break;
856     case 'P': // Don't print @PLT, but do print as memory.
857       printMemReference(MI, OpNo, "mem", /*NotRIPRel=*/true);
858       return false;
859     }
860   }
861   printMemReference(MI, OpNo);
862   return false;
863 }
864
865 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
866   // Convert registers in the addr mode according to subreg64.
867   for (unsigned i = 0; i != 4; ++i) {
868     if (!MI->getOperand(i).isReg()) continue;
869     
870     unsigned Reg = MI->getOperand(i).getReg();
871     if (Reg == 0) continue;
872     
873     MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
874   }
875 }
876
877 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
878 /// AT&T syntax to the current output stream.
879 ///
880 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
881   ++EmittedInsts;
882
883   if (NewAsmPrinter) {
884     if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
885       O << "\t";
886       printInlineAsm(MI);
887       return;
888     } else if (MI->isLabel()) {
889       printLabel(MI);
890       return;
891     } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
892       printDeclare(MI);
893       return;
894     } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
895       printImplicitDef(MI);
896       return;
897     }
898     
899     O << "NEW: ";
900     MCInst TmpInst;
901     
902     TmpInst.setOpcode(MI->getOpcode());
903     
904     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
905       const MachineOperand &MO = MI->getOperand(i);
906       
907       MCOperand MCOp;
908       if (MO.isReg()) {
909         MCOp.MakeReg(MO.getReg());
910       } else if (MO.isImm()) {
911         MCOp.MakeImm(MO.getImm());
912       } else if (MO.isMBB()) {
913         MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
914       } else {
915         assert(0 && "Unimp");
916       }
917       
918       TmpInst.addOperand(MCOp);
919     }
920     
921     switch (TmpInst.getOpcode()) {
922     case X86::LEA64_32r:
923       // Handle the 'subreg rewriting' for the lea64_32mem operand.
924       lower_lea64_32mem(&TmpInst, 1);
925       break;
926     }
927     
928     // FIXME: Convert TmpInst.
929     printInstruction(&TmpInst);
930     O << "OLD: ";
931   }
932   
933   // Call the autogenerated instruction printer routines.
934   printInstruction(MI);
935 }
936
937 /// doInitialization
938 bool X86ATTAsmPrinter::doInitialization(Module &M) {
939   if (NewAsmPrinter) {
940     Context = new MCContext();
941     // FIXME: Send this to "O" instead of outs().  For now, we force it to
942     // stdout to make it easy to compare.
943     Streamer = createAsmStreamer(*Context, outs());
944   }
945   
946   return AsmPrinter::doInitialization(M);
947 }
948
949 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
950   const TargetData *TD = TM.getTargetData();
951
952   if (!GVar->hasInitializer())
953     return;   // External global require no code
954
955   // Check to see if this is a special global used by LLVM, if so, emit it.
956   if (EmitSpecialLLVMGlobal(GVar)) {
957     if (Subtarget->isTargetDarwin() &&
958         TM.getRelocationModel() == Reloc::Static) {
959       if (GVar->getName() == "llvm.global_ctors")
960         O << ".reference .constructors_used\n";
961       else if (GVar->getName() == "llvm.global_dtors")
962         O << ".reference .destructors_used\n";
963     }
964     return;
965   }
966
967   std::string name = Mang->getValueName(GVar);
968   Constant *C = GVar->getInitializer();
969   const Type *Type = C->getType();
970   unsigned Size = TD->getTypeAllocSize(Type);
971   unsigned Align = TD->getPreferredAlignmentLog(GVar);
972
973   printVisibility(name, GVar->getVisibility());
974
975   if (Subtarget->isTargetELF())
976     O << "\t.type\t" << name << ",@object\n";
977
978   SwitchToSection(TAI->SectionForGlobal(GVar));
979
980   if (C->isNullValue() && !GVar->hasSection() &&
981       !(Subtarget->isTargetDarwin() &&
982         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
983     // FIXME: This seems to be pretty darwin-specific
984     if (GVar->hasExternalLinkage()) {
985       if (const char *Directive = TAI->getZeroFillDirective()) {
986         O << "\t.globl " << name << '\n';
987         O << Directive << "__DATA, __common, " << name << ", "
988           << Size << ", " << Align << '\n';
989         return;
990       }
991     }
992
993     if (!GVar->isThreadLocal() &&
994         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
995       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
996
997       if (TAI->getLCOMMDirective() != NULL) {
998         if (GVar->hasLocalLinkage()) {
999           O << TAI->getLCOMMDirective() << name << ',' << Size;
1000           if (Subtarget->isTargetDarwin())
1001             O << ',' << Align;
1002         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
1003           O << "\t.globl " << name << '\n'
1004             << TAI->getWeakDefDirective() << name << '\n';
1005           EmitAlignment(Align, GVar);
1006           O << name << ":";
1007           if (VerboseAsm) {
1008             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1009             PrintUnmangledNameSafely(GVar, O);
1010           }
1011           O << '\n';
1012           EmitGlobalConstant(C);
1013           return;
1014         } else {
1015           O << TAI->getCOMMDirective()  << name << ',' << Size;
1016           if (TAI->getCOMMDirectiveTakesAlignment())
1017             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1018         }
1019       } else {
1020         if (!Subtarget->isTargetCygMing()) {
1021           if (GVar->hasLocalLinkage())
1022             O << "\t.local\t" << name << '\n';
1023         }
1024         O << TAI->getCOMMDirective()  << name << ',' << Size;
1025         if (TAI->getCOMMDirectiveTakesAlignment())
1026           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1027       }
1028       if (VerboseAsm) {
1029         O << "\t\t" << TAI->getCommentString() << ' ';
1030         PrintUnmangledNameSafely(GVar, O);
1031       }
1032       O << '\n';
1033       return;
1034     }
1035   }
1036
1037   switch (GVar->getLinkage()) {
1038   case GlobalValue::CommonLinkage:
1039   case GlobalValue::LinkOnceAnyLinkage:
1040   case GlobalValue::LinkOnceODRLinkage:
1041   case GlobalValue::WeakAnyLinkage:
1042   case GlobalValue::WeakODRLinkage:
1043     if (Subtarget->isTargetDarwin()) {
1044       O << "\t.globl " << name << '\n'
1045         << TAI->getWeakDefDirective() << name << '\n';
1046     } else if (Subtarget->isTargetCygMing()) {
1047       O << "\t.globl\t" << name << "\n"
1048            "\t.linkonce same_size\n";
1049     } else {
1050       O << "\t.weak\t" << name << '\n';
1051     }
1052     break;
1053   case GlobalValue::DLLExportLinkage:
1054   case GlobalValue::AppendingLinkage:
1055     // FIXME: appending linkage variables should go into a section of
1056     // their name or something.  For now, just emit them as external.
1057   case GlobalValue::ExternalLinkage:
1058     // If external or appending, declare as a global symbol
1059     O << "\t.globl " << name << '\n';
1060     // FALL THROUGH
1061   case GlobalValue::PrivateLinkage:
1062   case GlobalValue::InternalLinkage:
1063      break;
1064   default:
1065     assert(0 && "Unknown linkage type!");
1066   }
1067
1068   EmitAlignment(Align, GVar);
1069   O << name << ":";
1070   if (VerboseAsm){
1071     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1072     PrintUnmangledNameSafely(GVar, O);
1073   }
1074   O << '\n';
1075   if (TAI->hasDotTypeDotSizeDirective())
1076     O << "\t.size\t" << name << ", " << Size << '\n';
1077
1078   EmitGlobalConstant(C);
1079 }
1080
1081 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1082   // Print out module-level global variables here.
1083   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1084        I != E; ++I) {
1085     printModuleLevelGV(I);
1086
1087     if (I->hasDLLExportLinkage())
1088       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1089   }
1090
1091   if (Subtarget->isTargetDarwin()) {
1092     SwitchToDataSection("");
1093     
1094     // Add the (possibly multiple) personalities to the set of global value
1095     // stubs.  Only referenced functions get into the Personalities list.
1096     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1097       const std::vector<Function*> &Personalities = MMI->getPersonalities();
1098       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1099         if (Personalities[i] == 0)
1100           continue;
1101         std::string Name = Mang->getValueName(Personalities[i]);
1102         decorateName(Name, Personalities[i]);
1103         GVStubs.insert(Name);
1104       }
1105     }
1106
1107     // Output stubs for dynamically-linked functions
1108     if (!FnStubs.empty()) {
1109       for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1110            I != E; ++I) {
1111         SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1112                             "self_modifying_code+pure_instructions,5", 0);
1113         const char *Name = I->getKeyData();
1114         printSuffixedName(Name, "$stub");
1115         O << ":\n"
1116              "\t.indirect_symbol " << Name << "\n"
1117              "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1118       }
1119       O << '\n';
1120     }
1121
1122     // Output stubs for external and common global variables.
1123     if (!GVStubs.empty()) {
1124       SwitchToDataSection(
1125                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1126       for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1127            I != E; ++I) {
1128         const char *Name = I->getKeyData();
1129         printSuffixedName(Name, "$non_lazy_ptr");
1130         O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1131       }
1132     }
1133
1134     if (!HiddenGVStubs.empty()) {
1135       SwitchToSection(TAI->getDataSection());
1136       EmitAlignment(2);
1137       for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1138            E = HiddenGVStubs.end(); I != E; ++I) {
1139         const char *Name = I->getKeyData();
1140         printSuffixedName(Name, "$non_lazy_ptr");
1141         O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1142       }
1143     }
1144
1145     // Funny Darwin hack: This flag tells the linker that no global symbols
1146     // contain code that falls through to other global symbols (e.g. the obvious
1147     // implementation of multiple entry points).  If this doesn't occur, the
1148     // linker can safely perform dead code stripping.  Since LLVM never
1149     // generates code that does this, it is always safe to set.
1150     O << "\t.subsections_via_symbols\n";
1151   } else if (Subtarget->isTargetCygMing()) {
1152     // Emit type information for external functions
1153     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1154          i != e; ++i) {
1155       O << "\t.def\t " << i->getKeyData()
1156         << ";\t.scl\t" << COFF::C_EXT
1157         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1158         << ";\t.endef\n";
1159     }
1160   }
1161   
1162   
1163   // Output linker support code for dllexported globals on windows.
1164   if (!DLLExportedGVs.empty()) {
1165     SwitchToDataSection(".section .drectve");
1166   
1167     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1168          e = DLLExportedGVs.end(); i != e; ++i)
1169       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1170   }
1171   
1172   if (!DLLExportedFns.empty()) {
1173     SwitchToDataSection(".section .drectve");
1174   
1175     for (StringSet<>::iterator i = DLLExportedFns.begin(),
1176          e = DLLExportedFns.end();
1177          i != e; ++i)
1178       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1179   }
1180   
1181   // Do common shutdown.
1182   bool Changed = AsmPrinter::doFinalization(M);
1183   
1184   if (NewAsmPrinter) {
1185     Streamer->Finish();
1186     
1187     delete Streamer;
1188     delete Context;
1189     Streamer = 0;
1190     Context = 0;
1191   }
1192   
1193   return Changed;
1194 }
1195
1196 // Include the auto-generated portion of the assembly writer.
1197 #include "X86GenAsmWriter.inc"