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