simplify printing of MO_ExternalSymbol in a non-pcrel context.
[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     printOffset(MO.getOffset());
490
491     switch (MO.getTargetFlags()) {
492     default:
493       assert(0 && "Unknown target flag on constant pool operand");
494     case X86II::MO_NO_FLAG:
495       // FIXME: REMOVE EVENTUALLY.
496       if (TM.getRelocationModel() == Reloc::PIC_) {
497         assert(!Subtarget->isPICStyleStub() &&
498                !Subtarget->isPICStyleGOT() &&
499                "Should have operand flag!");
500       }
501       
502       break;
503     case X86II::MO_PIC_BASE_OFFSET:
504       O << '-';
505       PrintPICBaseSymbol();
506       break;
507     case X86II::MO_GOTOFF:
508       O << "@GOTOFF";
509       break;
510     }
511
512     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
513       O << "(%rip)";
514     return;
515   }
516   case MachineOperand::MO_GlobalAddress: {
517     bool isMemOp = Modifier && !strcmp(Modifier, "mem");
518     bool needCloseParen = false;
519
520     const GlobalValue *GV = MO.getGlobal();
521     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
522     if (!GVar) {
523       // If GV is an alias then use the aliasee for determining
524       // thread-localness.
525       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
526         GVar =dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
527     }
528
529     bool isThreadLocal = GVar && GVar->isThreadLocal();
530
531     std::string Name = Mang->getValueName(GV);
532     decorateName(Name, GV);
533
534     if (!isMemOp)
535       O << '$';
536     else if (Name[0] == '$') {
537       // The name begins with a dollar-sign. In order to avoid having it look
538       // like an integer immediate to the assembler, enclose it in parens.
539       O << '(';
540       needCloseParen = true;
541     }
542
543     if (shouldPrintStub(TM, Subtarget)) {
544       // DARWIN/X86-32 in != static mode.
545
546       // Link-once, declaration, or Weakly-linked global variables need
547       // non-lazily-resolved stubs
548       if (GV->isDeclaration() || GV->isWeakForLinker()) {
549         // Dynamically-resolved functions need a stub for the function.
550         if (GV->hasHiddenVisibility()) {
551           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
552             // Definition is not definitely in the current translation unit.
553             O << Name;
554           else {
555             HiddenGVStubs.insert(Name);
556             printSuffixedName(Name, "$non_lazy_ptr");
557           }
558         } else {
559           GVStubs.insert(Name);
560           printSuffixedName(Name, "$non_lazy_ptr");
561         }
562       } else {
563         if (GV->hasDLLImportLinkage())
564           O << "__imp_";
565         O << Name;
566       }
567
568       if (TM.getRelocationModel() == Reloc::PIC_) {
569         O << '-';
570         PrintPICBaseSymbol();
571       }        
572     } else {
573       if (GV->hasDLLImportLinkage())
574         O << "__imp_";
575       O << Name;
576     }
577
578     printOffset(MO.getOffset());
579
580     if (needCloseParen)
581       O << ')';
582     
583     bool isRIPRelative = false;
584
585     switch (MO.getTargetFlags()) {
586     default:
587       assert(0 && "Unknown target flag on GV operand");
588     case X86II::MO_NO_FLAG:
589       // FIXME: RIP THIS CHECKING CODE OUT EVENTUALLY.
590       if (isThreadLocal)
591         assert(0 && "Not lowered right");
592       break;
593     case X86II::MO_TLSGD:
594       O << "@TLSGD";
595       break;
596     case X86II::MO_GOTTPOFF:
597       O << "@GOTTPOFF";
598       assert(!NotRIPRel);
599       isRIPRelative = true;
600       break;
601     case X86II::MO_INDNTPOFF:
602       O << "@INDNTPOFF";
603       break;
604     case X86II::MO_TPOFF:
605       O << "@TPOFF";
606       break;
607     case X86II::MO_NTPOFF:
608       O << "@NTPOFF";
609       break;
610     }
611     
612     if (isThreadLocal) {
613       // DEAD
614     } else if (isMemOp) {
615       if (shouldPrintGOT(TM, Subtarget)) {
616         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
617           O << "@GOT";
618         else
619           O << "@GOTOFF";
620       } else if (Subtarget->isPICStyleRIPRel() &&
621                  !NotRIPRel) {
622         if (TM.getRelocationModel() != Reloc::Static) {
623           if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
624             O << "@GOTPCREL";
625         }
626         
627         isRIPRelative = true;
628       }
629     }
630
631     // Use rip when possible to reduce code size, except when
632     // index or base register are also part of the address. e.g.
633     // foo(%rip)(%rcx,%rax,4) is not legal.
634     if (isRIPRelative)
635       O << "(%rip)";
636     
637     return;
638   }
639   case MachineOperand::MO_ExternalSymbol: {
640     /// NOTE: MO_ExternalSymbol in a non-pcrel_imm context is *only* generated
641     /// by _GLOBAL_OFFSET_TABLE_ on X86-32.  All others are call operands, which
642     /// are pcrel_imm's.
643     assert(!Subtarget->is64Bit() && !Subtarget->isPICStyleRIPRel());
644     // These are never used as memory operands.
645     assert(!(Modifier && !strcmp(Modifier, "mem")));
646     
647     O << '$';
648     O << TAI->getGlobalPrefix();
649     O << MO.getSymbolName();
650     
651     if (MO.getTargetFlags() == X86II::MO_GOT_ABSOLUTE_ADDRESS) {
652       O << " + [.-";
653       PrintPICBaseSymbol();
654       O << ']';
655     } else {
656       assert(MO.getTargetFlags() == X86II::MO_NO_FLAG &&
657              "Unknown operand flag for external symbol");
658     }
659     return;
660   }
661   default:
662     O << "<unknown operand type>"; return;
663   }
664 }
665
666 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
667   unsigned char value = MI->getOperand(Op).getImm();
668   assert(value <= 7 && "Invalid ssecc argument!");
669   switch (value) {
670   case 0: O << "eq"; break;
671   case 1: O << "lt"; break;
672   case 2: O << "le"; break;
673   case 3: O << "unord"; break;
674   case 4: O << "neq"; break;
675   case 5: O << "nlt"; break;
676   case 6: O << "nle"; break;
677   case 7: O << "ord"; break;
678   }
679 }
680
681 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
682                                             const char *Modifier,
683                                             bool NotRIPRel) {
684   MachineOperand BaseReg  = MI->getOperand(Op);
685   MachineOperand IndexReg = MI->getOperand(Op+2);
686   const MachineOperand &DispSpec = MI->getOperand(Op+3);
687
688   NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
689   if (DispSpec.isGlobal() ||
690       DispSpec.isCPI() ||
691       DispSpec.isJTI() ||
692       DispSpec.isSymbol()) {
693     printOperand(MI, Op+3, "mem", NotRIPRel);
694   } else {
695     int DispVal = DispSpec.getImm();
696     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
697       O << DispVal;
698   }
699
700   if (IndexReg.getReg() || BaseReg.getReg()) {
701     unsigned ScaleVal = MI->getOperand(Op+1).getImm();
702     unsigned BaseRegOperand = 0, IndexRegOperand = 2;
703
704     // There are cases where we can end up with ESP/RSP in the indexreg slot.
705     // If this happens, swap the base/index register to support assemblers that
706     // don't work when the index is *SP.
707     if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
708       assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
709       std::swap(BaseReg, IndexReg);
710       std::swap(BaseRegOperand, IndexRegOperand);
711     }
712
713     O << '(';
714     if (BaseReg.getReg())
715       printOperand(MI, Op+BaseRegOperand, Modifier);
716
717     if (IndexReg.getReg()) {
718       O << ',';
719       printOperand(MI, Op+IndexRegOperand, Modifier);
720       if (ScaleVal != 1)
721         O << ',' << ScaleVal;
722     }
723     O << ')';
724   }
725 }
726
727 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
728                                          const char *Modifier, bool NotRIPRel){
729   assert(isMem(MI, Op) && "Invalid memory reference!");
730   MachineOperand Segment = MI->getOperand(Op+4);
731   if (Segment.getReg()) {
732       printOperand(MI, Op+4, Modifier);
733       O << ':';
734     }
735   printLeaMemReference(MI, Op, Modifier, NotRIPRel);
736 }
737
738 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
739                                            const MachineBasicBlock *MBB) const {
740   if (!TAI->getSetDirective())
741     return;
742
743   // We don't need .set machinery if we have GOT-style relocations
744   if (Subtarget->isPICStyleGOT())
745     return;
746
747   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
748     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
749   printBasicBlockLabel(MBB, false, false, false);
750   if (Subtarget->isPICStyleRIPRel())
751     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
752       << '_' << uid << '\n';
753   else {
754     O << '-';
755     PrintPICBaseSymbol();
756     O << '\n';
757   }
758 }
759
760
761 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
762   PrintPICBaseSymbol();
763   O << '\n';
764   PrintPICBaseSymbol();
765   O << ':';
766 }
767
768
769 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
770                                               const MachineBasicBlock *MBB,
771                                               unsigned uid) const
772 {
773   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
774     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
775
776   O << JTEntryDirective << ' ';
777
778   if (TM.getRelocationModel() == Reloc::PIC_) {
779     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
780       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
781         << '_' << uid << "_set_" << MBB->getNumber();
782     } else if (Subtarget->isPICStyleGOT()) {
783       printBasicBlockLabel(MBB, false, false, false);
784       O << "@GOTOFF";
785     } else
786       assert(0 && "Don't know how to print MBB label for this PIC mode");
787   } else
788     printBasicBlockLabel(MBB, false, false, false);
789 }
790
791 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
792   unsigned Reg = MO.getReg();
793   switch (Mode) {
794   default: return true;  // Unknown mode.
795   case 'b': // Print QImode register
796     Reg = getX86SubSuperRegister(Reg, MVT::i8);
797     break;
798   case 'h': // Print QImode high register
799     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
800     break;
801   case 'w': // Print HImode register
802     Reg = getX86SubSuperRegister(Reg, MVT::i16);
803     break;
804   case 'k': // Print SImode register
805     Reg = getX86SubSuperRegister(Reg, MVT::i32);
806     break;
807   case 'q': // Print DImode register
808     Reg = getX86SubSuperRegister(Reg, MVT::i64);
809     break;
810   }
811
812   O << '%'<< TRI->getAsmName(Reg);
813   return false;
814 }
815
816 /// PrintAsmOperand - Print out an operand for an inline asm expression.
817 ///
818 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
819                                        unsigned AsmVariant,
820                                        const char *ExtraCode) {
821   // Does this asm operand have a single letter operand modifier?
822   if (ExtraCode && ExtraCode[0]) {
823     if (ExtraCode[1] != 0) return true; // Unknown modifier.
824
825     switch (ExtraCode[0]) {
826     default: return true;  // Unknown modifier.
827     case 'c': // Don't print "$" before a global var name or constant.
828       printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
829       return false;
830     case 'b': // Print QImode register
831     case 'h': // Print QImode high register
832     case 'w': // Print HImode register
833     case 'k': // Print SImode register
834     case 'q': // Print DImode register
835       if (MI->getOperand(OpNo).isReg())
836         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
837       printOperand(MI, OpNo);
838       return false;
839
840     case 'P': // Don't print @PLT, but do print as memory.
841       printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
842       return false;
843     }
844   }
845
846   printOperand(MI, OpNo);
847   return false;
848 }
849
850 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
851                                              unsigned OpNo,
852                                              unsigned AsmVariant,
853                                              const char *ExtraCode) {
854   if (ExtraCode && ExtraCode[0]) {
855     if (ExtraCode[1] != 0) return true; // Unknown modifier.
856
857     switch (ExtraCode[0]) {
858     default: return true;  // Unknown modifier.
859     case 'b': // Print QImode register
860     case 'h': // Print QImode high register
861     case 'w': // Print HImode register
862     case 'k': // Print SImode register
863     case 'q': // Print SImode register
864       // These only apply to registers, ignore on mem.
865       break;
866     case 'P': // Don't print @PLT, but do print as memory.
867       printMemReference(MI, OpNo, "mem", /*NotRIPRel=*/true);
868       return false;
869     }
870   }
871   printMemReference(MI, OpNo);
872   return false;
873 }
874
875 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
876   // Convert registers in the addr mode according to subreg64.
877   for (unsigned i = 0; i != 4; ++i) {
878     if (!MI->getOperand(i).isReg()) continue;
879     
880     unsigned Reg = MI->getOperand(i).getReg();
881     if (Reg == 0) continue;
882     
883     MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
884   }
885 }
886
887 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
888 /// AT&T syntax to the current output stream.
889 ///
890 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
891   ++EmittedInsts;
892
893   if (NewAsmPrinter) {
894     if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
895       O << "\t";
896       printInlineAsm(MI);
897       return;
898     } else if (MI->isLabel()) {
899       printLabel(MI);
900       return;
901     } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
902       printDeclare(MI);
903       return;
904     } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
905       printImplicitDef(MI);
906       return;
907     }
908     
909     O << "NEW: ";
910     MCInst TmpInst;
911     
912     TmpInst.setOpcode(MI->getOpcode());
913     
914     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
915       const MachineOperand &MO = MI->getOperand(i);
916       
917       MCOperand MCOp;
918       if (MO.isReg()) {
919         MCOp.MakeReg(MO.getReg());
920       } else if (MO.isImm()) {
921         MCOp.MakeImm(MO.getImm());
922       } else if (MO.isMBB()) {
923         MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
924       } else {
925         assert(0 && "Unimp");
926       }
927       
928       TmpInst.addOperand(MCOp);
929     }
930     
931     switch (TmpInst.getOpcode()) {
932     case X86::LEA64_32r:
933       // Handle the 'subreg rewriting' for the lea64_32mem operand.
934       lower_lea64_32mem(&TmpInst, 1);
935       break;
936     }
937     
938     // FIXME: Convert TmpInst.
939     printInstruction(&TmpInst);
940     O << "OLD: ";
941   }
942   
943   // Call the autogenerated instruction printer routines.
944   printInstruction(MI);
945 }
946
947 /// doInitialization
948 bool X86ATTAsmPrinter::doInitialization(Module &M) {
949   if (NewAsmPrinter) {
950     Context = new MCContext();
951     // FIXME: Send this to "O" instead of outs().  For now, we force it to
952     // stdout to make it easy to compare.
953     Streamer = createAsmStreamer(*Context, outs());
954   }
955   
956   return AsmPrinter::doInitialization(M);
957 }
958
959 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
960   const TargetData *TD = TM.getTargetData();
961
962   if (!GVar->hasInitializer())
963     return;   // External global require no code
964
965   // Check to see if this is a special global used by LLVM, if so, emit it.
966   if (EmitSpecialLLVMGlobal(GVar)) {
967     if (Subtarget->isTargetDarwin() &&
968         TM.getRelocationModel() == Reloc::Static) {
969       if (GVar->getName() == "llvm.global_ctors")
970         O << ".reference .constructors_used\n";
971       else if (GVar->getName() == "llvm.global_dtors")
972         O << ".reference .destructors_used\n";
973     }
974     return;
975   }
976
977   std::string name = Mang->getValueName(GVar);
978   Constant *C = GVar->getInitializer();
979   if (isa<MDNode>(C) || isa<MDString>(C))
980     return;
981   const Type *Type = C->getType();
982   unsigned Size = TD->getTypeAllocSize(Type);
983   unsigned Align = TD->getPreferredAlignmentLog(GVar);
984
985   printVisibility(name, GVar->getVisibility());
986
987   if (Subtarget->isTargetELF())
988     O << "\t.type\t" << name << ",@object\n";
989
990   SwitchToSection(TAI->SectionForGlobal(GVar));
991
992   if (C->isNullValue() && !GVar->hasSection() &&
993       !(Subtarget->isTargetDarwin() &&
994         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
995     // FIXME: This seems to be pretty darwin-specific
996     if (GVar->hasExternalLinkage()) {
997       if (const char *Directive = TAI->getZeroFillDirective()) {
998         O << "\t.globl " << name << '\n';
999         O << Directive << "__DATA, __common, " << name << ", "
1000           << Size << ", " << Align << '\n';
1001         return;
1002       }
1003     }
1004
1005     if (!GVar->isThreadLocal() &&
1006         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
1007       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
1008
1009       if (TAI->getLCOMMDirective() != NULL) {
1010         if (GVar->hasLocalLinkage()) {
1011           O << TAI->getLCOMMDirective() << name << ',' << Size;
1012           if (Subtarget->isTargetDarwin())
1013             O << ',' << Align;
1014         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
1015           O << "\t.globl " << name << '\n'
1016             << TAI->getWeakDefDirective() << name << '\n';
1017           EmitAlignment(Align, GVar);
1018           O << name << ":";
1019           if (VerboseAsm) {
1020             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1021             PrintUnmangledNameSafely(GVar, O);
1022           }
1023           O << '\n';
1024           EmitGlobalConstant(C);
1025           return;
1026         } else {
1027           O << TAI->getCOMMDirective()  << name << ',' << Size;
1028           if (TAI->getCOMMDirectiveTakesAlignment())
1029             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1030         }
1031       } else {
1032         if (!Subtarget->isTargetCygMing()) {
1033           if (GVar->hasLocalLinkage())
1034             O << "\t.local\t" << name << '\n';
1035         }
1036         O << TAI->getCOMMDirective()  << name << ',' << Size;
1037         if (TAI->getCOMMDirectiveTakesAlignment())
1038           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1039       }
1040       if (VerboseAsm) {
1041         O << "\t\t" << TAI->getCommentString() << ' ';
1042         PrintUnmangledNameSafely(GVar, O);
1043       }
1044       O << '\n';
1045       return;
1046     }
1047   }
1048
1049   switch (GVar->getLinkage()) {
1050   case GlobalValue::CommonLinkage:
1051   case GlobalValue::LinkOnceAnyLinkage:
1052   case GlobalValue::LinkOnceODRLinkage:
1053   case GlobalValue::WeakAnyLinkage:
1054   case GlobalValue::WeakODRLinkage:
1055     if (Subtarget->isTargetDarwin()) {
1056       O << "\t.globl " << name << '\n'
1057         << TAI->getWeakDefDirective() << name << '\n';
1058     } else if (Subtarget->isTargetCygMing()) {
1059       O << "\t.globl\t" << name << "\n"
1060            "\t.linkonce same_size\n";
1061     } else {
1062       O << "\t.weak\t" << name << '\n';
1063     }
1064     break;
1065   case GlobalValue::DLLExportLinkage:
1066   case GlobalValue::AppendingLinkage:
1067     // FIXME: appending linkage variables should go into a section of
1068     // their name or something.  For now, just emit them as external.
1069   case GlobalValue::ExternalLinkage:
1070     // If external or appending, declare as a global symbol
1071     O << "\t.globl " << name << '\n';
1072     // FALL THROUGH
1073   case GlobalValue::PrivateLinkage:
1074   case GlobalValue::InternalLinkage:
1075      break;
1076   default:
1077     assert(0 && "Unknown linkage type!");
1078   }
1079
1080   EmitAlignment(Align, GVar);
1081   O << name << ":";
1082   if (VerboseAsm){
1083     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1084     PrintUnmangledNameSafely(GVar, O);
1085   }
1086   O << '\n';
1087   if (TAI->hasDotTypeDotSizeDirective())
1088     O << "\t.size\t" << name << ", " << Size << '\n';
1089
1090   EmitGlobalConstant(C);
1091 }
1092
1093 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1094   // Print out module-level global variables here.
1095   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1096        I != E; ++I) {
1097     printModuleLevelGV(I);
1098
1099     if (I->hasDLLExportLinkage())
1100       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1101   }
1102
1103   if (Subtarget->isTargetDarwin()) {
1104     SwitchToDataSection("");
1105     
1106     // Add the (possibly multiple) personalities to the set of global value
1107     // stubs.  Only referenced functions get into the Personalities list.
1108     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1109       const std::vector<Function*> &Personalities = MMI->getPersonalities();
1110       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1111         if (Personalities[i] == 0)
1112           continue;
1113         std::string Name = Mang->getValueName(Personalities[i]);
1114         decorateName(Name, Personalities[i]);
1115         GVStubs.insert(Name);
1116       }
1117     }
1118
1119     // Output stubs for dynamically-linked functions
1120     if (!FnStubs.empty()) {
1121       for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1122            I != E; ++I) {
1123         SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1124                             "self_modifying_code+pure_instructions,5", 0);
1125         const char *Name = I->getKeyData();
1126         printSuffixedName(Name, "$stub");
1127         O << ":\n"
1128              "\t.indirect_symbol " << Name << "\n"
1129              "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1130       }
1131       O << '\n';
1132     }
1133
1134     // Output stubs for external and common global variables.
1135     if (!GVStubs.empty()) {
1136       SwitchToDataSection(
1137                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1138       for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1139            I != E; ++I) {
1140         const char *Name = I->getKeyData();
1141         printSuffixedName(Name, "$non_lazy_ptr");
1142         O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1143       }
1144     }
1145
1146     if (!HiddenGVStubs.empty()) {
1147       SwitchToSection(TAI->getDataSection());
1148       EmitAlignment(2);
1149       for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1150            E = HiddenGVStubs.end(); I != E; ++I) {
1151         const char *Name = I->getKeyData();
1152         printSuffixedName(Name, "$non_lazy_ptr");
1153         O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1154       }
1155     }
1156
1157     // Funny Darwin hack: This flag tells the linker that no global symbols
1158     // contain code that falls through to other global symbols (e.g. the obvious
1159     // implementation of multiple entry points).  If this doesn't occur, the
1160     // linker can safely perform dead code stripping.  Since LLVM never
1161     // generates code that does this, it is always safe to set.
1162     O << "\t.subsections_via_symbols\n";
1163   } else if (Subtarget->isTargetCygMing()) {
1164     // Emit type information for external functions
1165     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1166          i != e; ++i) {
1167       O << "\t.def\t " << i->getKeyData()
1168         << ";\t.scl\t" << COFF::C_EXT
1169         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1170         << ";\t.endef\n";
1171     }
1172   }
1173   
1174   
1175   // Output linker support code for dllexported globals on windows.
1176   if (!DLLExportedGVs.empty()) {
1177     SwitchToDataSection(".section .drectve");
1178   
1179     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1180          e = DLLExportedGVs.end(); i != e; ++i)
1181       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1182   }
1183   
1184   if (!DLLExportedFns.empty()) {
1185     SwitchToDataSection(".section .drectve");
1186   
1187     for (StringSet<>::iterator i = DLLExportedFns.begin(),
1188          e = DLLExportedFns.end();
1189          i != e; ++i)
1190       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1191   }
1192   
1193   // Do common shutdown.
1194   bool Changed = AsmPrinter::doFinalization(M);
1195   
1196   if (NewAsmPrinter) {
1197     Streamer->Finish();
1198     
1199     delete Streamer;
1200     delete Context;
1201     Streamer = 0;
1202     Context = 0;
1203   }
1204   
1205   return Changed;
1206 }
1207
1208 // Include the auto-generated portion of the assembly writer.
1209 #include "X86GenAsmWriter.inc"