disable the new asmprinter by default. Both the Mangler and MCSymbol
[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 "llvm/CallingConv.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Type.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/Assembly/Writer.h"
29 #include "llvm/MC/MCStreamer.h"
30 #include "llvm/MC/MCSectionMachO.h"
31 #include "llvm/CodeGen/MachineJumpTableInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/FormattedStream.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/Target/TargetLoweringObjectFile.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, cl::init(false));
45
46 //===----------------------------------------------------------------------===//
47 // Primitive Helper Functions.
48 //===----------------------------------------------------------------------===//
49
50 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
51   // FIXME: the actual label generated doesn't matter here!  Just mangle in
52   // something unique (the function number) with Private prefix.
53   if (Subtarget->isTargetDarwin())
54     O << "\"L" << getFunctionNumber() << "$pb\"";
55   else {
56     assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
57     O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
58   }
59 }
60
61 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
62                                                     const TargetData *TD) {
63   X86MachineFunctionInfo Info;
64   uint64_t Size = 0;
65
66   switch (F->getCallingConv()) {
67   case CallingConv::X86_StdCall:
68     Info.setDecorationStyle(StdCall);
69     break;
70   case CallingConv::X86_FastCall:
71     Info.setDecorationStyle(FastCall);
72     break;
73   default:
74     return Info;
75   }
76
77   unsigned argNum = 1;
78   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
79        AI != AE; ++AI, ++argNum) {
80     const Type* Ty = AI->getType();
81
82     // 'Dereference' type in case of byval parameter attribute
83     if (F->paramHasAttr(argNum, Attribute::ByVal))
84       Ty = cast<PointerType>(Ty)->getElementType();
85
86     // Size should be aligned to DWORD boundary
87     Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
88   }
89
90   // We're not supporting tooooo huge arguments :)
91   Info.setBytesToPopOnReturn((unsigned int)Size);
92   return Info;
93 }
94
95 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
96 /// various name decorations for Cygwin and MingW.
97 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
98                                            const GlobalValue *GV) {
99   assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
100   
101   const Function *F = dyn_cast<Function>(GV);
102   if (!F) return;
103
104   // Save function name for later type emission.
105   if (F->isDeclaration())
106     CygMingStubs.insert(Name);
107   
108   // We don't want to decorate non-stdcall or non-fastcall functions right now
109   CallingConv::ID CC = F->getCallingConv();
110   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
111     return;
112
113
114   const X86MachineFunctionInfo *Info;
115   
116   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
117   if (info_item == FunctionInfoMap.end()) {
118     // Calculate apropriate function info and populate map
119     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
120     Info = &FunctionInfoMap[F];
121   } else {
122     Info = &info_item->second;
123   }
124
125   const FunctionType *FT = F->getFunctionType();
126   switch (Info->getDecorationStyle()) {
127   case None:
128     break;
129   case StdCall:
130     // "Pure" variadic functions do not receive @0 suffix.
131     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
132         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
133       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
134     break;
135   case FastCall:
136     // "Pure" variadic functions do not receive @0 suffix.
137     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
138         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
139       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
140
141     if (Name[0] == '_') {
142       Name[0] = '@';
143     } else {
144       Name = '@' + Name;
145     }
146     break;
147   default:
148     llvm_unreachable("Unsupported DecorationStyle");
149   }
150 }
151
152 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
153   unsigned FnAlign = MF.getAlignment();
154   const Function *F = MF.getFunction();
155
156   if (Subtarget->isTargetCygMing())
157     DecorateCygMingName(CurrentFnName, F);
158
159   OutStreamer.SwitchSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
160   EmitAlignment(FnAlign, F);
161
162   switch (F->getLinkage()) {
163   default: llvm_unreachable("Unknown linkage type!");
164   case Function::InternalLinkage:  // Symbols default to internal.
165   case Function::PrivateLinkage:
166     break;
167   case Function::DLLExportLinkage:
168   case Function::ExternalLinkage:
169     O << "\t.globl\t" << CurrentFnName << '\n';
170     break;
171   case Function::LinkerPrivateLinkage:
172   case Function::LinkOnceAnyLinkage:
173   case Function::LinkOnceODRLinkage:
174   case Function::WeakAnyLinkage:
175   case Function::WeakODRLinkage:
176     if (Subtarget->isTargetDarwin()) {
177       O << "\t.globl\t" << CurrentFnName << '\n';
178       O << MAI->getWeakDefDirective() << CurrentFnName << '\n';
179     } else if (Subtarget->isTargetCygMing()) {
180       O << "\t.globl\t" << CurrentFnName << "\n"
181            "\t.linkonce discard\n";
182     } else {
183       O << "\t.weak\t" << CurrentFnName << '\n';
184     }
185     break;
186   }
187
188   printVisibility(CurrentFnName, F->getVisibility());
189
190   if (Subtarget->isTargetELF())
191     O << "\t.type\t" << CurrentFnName << ",@function\n";
192   else if (Subtarget->isTargetCygMing()) {
193     O << "\t.def\t " << CurrentFnName
194       << ";\t.scl\t" <<
195       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
196       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
197       << ";\t.endef\n";
198   }
199
200   O << CurrentFnName << ':';
201   if (VerboseAsm) {
202     O.PadToColumn(MAI->getCommentColumn());
203     O << MAI->getCommentString() << ' ';
204     WriteAsOperand(O, F, /*PrintType=*/false, F->getParent());
205   }
206   O << '\n';
207
208   // Add some workaround for linkonce linkage on Cygwin\MinGW
209   if (Subtarget->isTargetCygMing() &&
210       (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
211     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
212 }
213
214 /// runOnMachineFunction - This uses the printMachineInstruction()
215 /// method to print assembly for each instruction.
216 ///
217 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
218   const Function *F = MF.getFunction();
219   this->MF = &MF;
220   CallingConv::ID CC = F->getCallingConv();
221
222   SetupMachineFunction(MF);
223   O << "\n\n";
224
225   // Populate function information map.  Actually, We don't want to populate
226   // non-stdcall or non-fastcall functions' information right now.
227   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
228     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
229
230   // Print out constants referenced by the function
231   EmitConstantPool(MF.getConstantPool());
232
233   if (F->hasDLLExportLinkage())
234     DLLExportedFns.insert(Mang->getMangledName(F));
235
236   // Print the 'header' of function
237   emitFunctionHeader(MF);
238
239   // Emit pre-function debug and/or EH information.
240   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
241     DW->BeginFunction(&MF);
242
243   // Print out code for the function.
244   bool hasAnyRealCode = false;
245   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
246        I != E; ++I) {
247     // Print a label for the basic block.
248     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
249       // This is an entry block or a block that's only reachable via a
250       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
251     } else {
252       printBasicBlockLabel(I, true, true, VerboseAsm);
253       O << '\n';
254     }
255     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
256          II != IE; ++II) {
257       // Print the assembly for the instruction.
258       if (!II->isLabel())
259         hasAnyRealCode = true;
260       printMachineInstruction(II);
261     }
262   }
263
264   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
265     // If the function is empty, then we need to emit *something*. Otherwise,
266     // the function's label might be associated with something that it wasn't
267     // meant to be associated with. We emit a noop in this situation.
268     // We are assuming inline asms are code.
269     O << "\tnop\n";
270   }
271
272   if (MAI->hasDotTypeDotSizeDirective())
273     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
274
275   // Emit post-function debug information.
276   if (MAI->doesSupportDebugInformation() || MAI->doesSupportExceptionHandling())
277     DW->EndFunction(&MF);
278
279   // Print out jump tables referenced by the function.
280   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
281
282   // We didn't modify anything.
283   return false;
284 }
285
286 /// printSymbolOperand - Print a raw symbol reference operand.  This handles
287 /// jump tables, constant pools, global address and external symbols, all of
288 /// which print to a label with various suffixes for relocation types etc.
289 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
290   switch (MO.getType()) {
291   default: llvm_unreachable("unknown symbol type!");
292   case MachineOperand::MO_JumpTableIndex:
293     O << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
294       << MO.getIndex();
295     break;
296   case MachineOperand::MO_ConstantPoolIndex:
297     O << MAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
298       << MO.getIndex();
299     printOffset(MO.getOffset());
300     break;
301   case MachineOperand::MO_GlobalAddress: {
302     const GlobalValue *GV = MO.getGlobal();
303     
304     const char *Suffix = "";
305     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
306       Suffix = "$stub";
307     else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
308              MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
309              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
310       Suffix = "$non_lazy_ptr";
311     
312     std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
313     if (Subtarget->isTargetCygMing())
314       DecorateCygMingName(Name, GV);
315     
316     // Handle dllimport linkage.
317     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
318       Name = "__imp_" + Name;
319     
320     if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
321         MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
322       GVStubs[Name] = Mang->getMangledName(GV);
323     else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
324       HiddenGVStubs[Name] = Mang->getMangledName(GV);
325     else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
326       FnStubs[Name] = Mang->getMangledName(GV);
327     
328     // If the name begins with a dollar-sign, enclose it in parens.  We do this
329     // to avoid having it look like an integer immediate to the assembler.
330     if (Name[0] == '$') 
331       O << '(' << Name << ')';
332     else
333       O << Name;
334     
335     printOffset(MO.getOffset());
336     break;
337   }
338   case MachineOperand::MO_ExternalSymbol: {
339     std::string Name = Mang->makeNameProper(MO.getSymbolName());
340     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
341       FnStubs[Name+"$stub"] = Name;
342       Name += "$stub";
343     }
344     
345     // If the name begins with a dollar-sign, enclose it in parens.  We do this
346     // to avoid having it look like an integer immediate to the assembler.
347     if (Name[0] == '$') 
348       O << '(' << Name << ')';
349     else
350       O << Name;
351     break;
352   }
353   }
354   
355   switch (MO.getTargetFlags()) {
356   default:
357     llvm_unreachable("Unknown target flag on GV operand");
358   case X86II::MO_NO_FLAG:    // No flag.
359     break;
360   case X86II::MO_DARWIN_NONLAZY:
361   case X86II::MO_DLLIMPORT:
362   case X86II::MO_DARWIN_STUB:
363     // These affect the name of the symbol, not any suffix.
364     break;
365   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
366     O << " + [.-";
367     PrintPICBaseSymbol();
368     O << ']';
369     break;      
370   case X86II::MO_PIC_BASE_OFFSET:
371   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
372   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
373     O << '-';
374     PrintPICBaseSymbol();
375     break;
376   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
377   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
378   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
379   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
380   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
381   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
382   case X86II::MO_GOT:       O << "@GOT";       break;
383   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
384   case X86II::MO_PLT:       O << "@PLT";       break;
385   }
386 }
387
388 /// print_pcrel_imm - This is used to print an immediate value that ends up
389 /// being encoded as a pc-relative value.  These print slightly differently, for
390 /// example, a $ is not emitted.
391 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
392   const MachineOperand &MO = MI->getOperand(OpNo);
393   switch (MO.getType()) {
394   default: llvm_unreachable("Unknown pcrel immediate operand");
395   case MachineOperand::MO_Immediate:
396     O << MO.getImm();
397     return;
398   case MachineOperand::MO_MachineBasicBlock:
399     printBasicBlockLabel(MO.getMBB(), false, false, false);
400     return;
401   case MachineOperand::MO_GlobalAddress:
402   case MachineOperand::MO_ExternalSymbol:
403     printSymbolOperand(MO);
404     return;
405   }
406 }
407
408
409
410 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
411                                     const char *Modifier) {
412   const MachineOperand &MO = MI->getOperand(OpNo);
413   switch (MO.getType()) {
414   default: llvm_unreachable("unknown operand type!");
415   case MachineOperand::MO_Register: {
416     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
417            "Virtual registers should not make it this far!");
418     O << '%';
419     unsigned Reg = MO.getReg();
420     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
421       EVT VT = (strcmp(Modifier+6,"64") == 0) ?
422         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
423                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
424       Reg = getX86SubSuperRegister(Reg, VT);
425     }
426     O << TRI->getAsmName(Reg);
427     return;
428   }
429
430   case MachineOperand::MO_Immediate:
431     O << '$' << MO.getImm();
432     return;
433
434   case MachineOperand::MO_JumpTableIndex:
435   case MachineOperand::MO_ConstantPoolIndex:
436   case MachineOperand::MO_GlobalAddress: 
437   case MachineOperand::MO_ExternalSymbol: {
438     O << '$';
439     printSymbolOperand(MO);
440     break;
441   }
442   }
443 }
444
445 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
446   unsigned char value = MI->getOperand(Op).getImm();
447   assert(value <= 7 && "Invalid ssecc argument!");
448   switch (value) {
449   case 0: O << "eq"; break;
450   case 1: O << "lt"; break;
451   case 2: O << "le"; break;
452   case 3: O << "unord"; break;
453   case 4: O << "neq"; break;
454   case 5: O << "nlt"; break;
455   case 6: O << "nle"; break;
456   case 7: O << "ord"; break;
457   }
458 }
459
460 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
461                                             const char *Modifier) {
462   const MachineOperand &BaseReg  = MI->getOperand(Op);
463   const MachineOperand &IndexReg = MI->getOperand(Op+2);
464   const MachineOperand &DispSpec = MI->getOperand(Op+3);
465
466   // If we really don't want to print out (rip), don't.
467   bool HasBaseReg = BaseReg.getReg() != 0;
468   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
469       BaseReg.getReg() == X86::RIP)
470     HasBaseReg = false;
471   
472   // HasParenPart - True if we will print out the () part of the mem ref.
473   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
474   
475   if (DispSpec.isImm()) {
476     int DispVal = DispSpec.getImm();
477     if (DispVal || !HasParenPart)
478       O << DispVal;
479   } else {
480     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
481            DispSpec.isJTI() || DispSpec.isSymbol());
482     printSymbolOperand(MI->getOperand(Op+3));
483   }
484
485   if (HasParenPart) {
486     assert(IndexReg.getReg() != X86::ESP &&
487            "X86 doesn't allow scaling by ESP");
488
489     O << '(';
490     if (HasBaseReg)
491       printOperand(MI, Op, Modifier);
492
493     if (IndexReg.getReg()) {
494       O << ',';
495       printOperand(MI, Op+2, Modifier);
496       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
497       if (ScaleVal != 1)
498         O << ',' << ScaleVal;
499     }
500     O << ')';
501   }
502 }
503
504 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
505                                          const char *Modifier) {
506   assert(isMem(MI, Op) && "Invalid memory reference!");
507   const MachineOperand &Segment = MI->getOperand(Op+4);
508   if (Segment.getReg()) {
509     printOperand(MI, Op+4, Modifier);
510     O << ':';
511   }
512   printLeaMemReference(MI, Op, Modifier);
513 }
514
515 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
516                                            const MachineBasicBlock *MBB) const {
517   if (!MAI->getSetDirective())
518     return;
519
520   // We don't need .set machinery if we have GOT-style relocations
521   if (Subtarget->isPICStyleGOT())
522     return;
523
524   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
525     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
526   printBasicBlockLabel(MBB, false, false, false);
527   if (Subtarget->isPICStyleRIPRel())
528     O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
529       << '_' << uid << '\n';
530   else {
531     O << '-';
532     PrintPICBaseSymbol();
533     O << '\n';
534   }
535 }
536
537
538 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
539   PrintPICBaseSymbol();
540   O << '\n';
541   PrintPICBaseSymbol();
542   O << ':';
543 }
544
545
546 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
547                                               const MachineBasicBlock *MBB,
548                                               unsigned uid) const {
549   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
550     MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
551
552   O << JTEntryDirective << ' ';
553
554   if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
555     O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
556       << '_' << uid << "_set_" << MBB->getNumber();
557   } else if (Subtarget->isPICStyleGOT()) {
558     printBasicBlockLabel(MBB, false, false, false);
559     O << "@GOTOFF";
560   } else
561     printBasicBlockLabel(MBB, false, false, false);
562 }
563
564 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
565   unsigned Reg = MO.getReg();
566   switch (Mode) {
567   default: return true;  // Unknown mode.
568   case 'b': // Print QImode register
569     Reg = getX86SubSuperRegister(Reg, MVT::i8);
570     break;
571   case 'h': // Print QImode high register
572     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
573     break;
574   case 'w': // Print HImode register
575     Reg = getX86SubSuperRegister(Reg, MVT::i16);
576     break;
577   case 'k': // Print SImode register
578     Reg = getX86SubSuperRegister(Reg, MVT::i32);
579     break;
580   case 'q': // Print DImode register
581     Reg = getX86SubSuperRegister(Reg, MVT::i64);
582     break;
583   }
584
585   O << '%'<< TRI->getAsmName(Reg);
586   return false;
587 }
588
589 /// PrintAsmOperand - Print out an operand for an inline asm expression.
590 ///
591 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
592                                        unsigned AsmVariant,
593                                        const char *ExtraCode) {
594   // Does this asm operand have a single letter operand modifier?
595   if (ExtraCode && ExtraCode[0]) {
596     if (ExtraCode[1] != 0) return true; // Unknown modifier.
597
598     const MachineOperand &MO = MI->getOperand(OpNo);
599     
600     switch (ExtraCode[0]) {
601     default: return true;  // Unknown modifier.
602     case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
603       if (MO.isImm()) {
604         O << MO.getImm();
605         return false;
606       } 
607       if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
608         printSymbolOperand(MO);
609         return false;
610       }
611       if (MO.isReg()) {
612         O << '(';
613         printOperand(MI, OpNo);
614         O << ')';
615         return false;
616       }
617       return true;
618
619     case 'c': // Don't print "$" before a global var name or constant.
620       if (MO.isImm())
621         O << MO.getImm();
622       else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
623         printSymbolOperand(MO);
624       else
625         printOperand(MI, OpNo);
626       return false;
627
628     case 'A': // Print '*' before a register (it must be a register)
629       if (MO.isReg()) {
630         O << '*';
631         printOperand(MI, OpNo);
632         return false;
633       }
634       return true;
635
636     case 'b': // Print QImode register
637     case 'h': // Print QImode high register
638     case 'w': // Print HImode register
639     case 'k': // Print SImode register
640     case 'q': // Print DImode register
641       if (MO.isReg())
642         return printAsmMRegister(MO, ExtraCode[0]);
643       printOperand(MI, OpNo);
644       return false;
645
646     case 'P': // This is the operand of a call, treat specially.
647       print_pcrel_imm(MI, OpNo);
648       return false;
649
650     case 'n':  // Negate the immediate or print a '-' before the operand.
651       // Note: this is a temporary solution. It should be handled target
652       // independently as part of the 'MC' work.
653       if (MO.isImm()) {
654         O << -MO.getImm();
655         return false;
656       }
657       O << '-';
658     }
659   }
660
661   printOperand(MI, OpNo);
662   return false;
663 }
664
665 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
666                                              unsigned OpNo,
667                                              unsigned AsmVariant,
668                                              const char *ExtraCode) {
669   if (ExtraCode && ExtraCode[0]) {
670     if (ExtraCode[1] != 0) return true; // Unknown modifier.
671
672     switch (ExtraCode[0]) {
673     default: return true;  // Unknown modifier.
674     case 'b': // Print QImode register
675     case 'h': // Print QImode high register
676     case 'w': // Print HImode register
677     case 'k': // Print SImode register
678     case 'q': // Print SImode register
679       // These only apply to registers, ignore on mem.
680       break;
681     case 'P': // Don't print @PLT, but do print as memory.
682       printMemReference(MI, OpNo, "no-rip");
683       return false;
684     }
685   }
686   printMemReference(MI, OpNo);
687   return false;
688 }
689
690
691
692 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
693 /// AT&T syntax to the current output stream.
694 ///
695 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
696   ++EmittedInsts;
697
698   // Call the autogenerated instruction printer routines.
699   if (NewAsmPrinter)
700     printInstructionThroughMCStreamer(MI);
701   else
702     printInstruction(MI);
703 }
704
705 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
706   const TargetData *TD = TM.getTargetData();
707
708   if (!GVar->hasInitializer())
709     return;   // External global require no code
710
711   // Check to see if this is a special global used by LLVM, if so, emit it.
712   if (EmitSpecialLLVMGlobal(GVar)) {
713     if (Subtarget->isTargetDarwin() &&
714         TM.getRelocationModel() == Reloc::Static) {
715       if (GVar->getName() == "llvm.global_ctors")
716         O << ".reference .constructors_used\n";
717       else if (GVar->getName() == "llvm.global_dtors")
718         O << ".reference .destructors_used\n";
719     }
720     return;
721   }
722
723   std::string name = Mang->getMangledName(GVar);
724   Constant *C = GVar->getInitializer();
725   const Type *Type = C->getType();
726   unsigned Size = TD->getTypeAllocSize(Type);
727   unsigned Align = TD->getPreferredAlignmentLog(GVar);
728
729   printVisibility(name, GVar->getVisibility());
730
731   if (Subtarget->isTargetELF())
732     O << "\t.type\t" << name << ",@object\n";
733
734   
735   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
736   const MCSection *TheSection =
737     getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
738   OutStreamer.SwitchSection(TheSection);
739
740   // FIXME: get this stuff from section kind flags.
741   if (C->isNullValue() && !GVar->hasSection() &&
742       // Don't put things that should go in the cstring section into "comm".
743       !TheSection->getKind().isMergeableCString()) {
744     if (GVar->hasExternalLinkage()) {
745       if (const char *Directive = MAI->getZeroFillDirective()) {
746         O << "\t.globl " << name << '\n';
747         O << Directive << "__DATA, __common, " << name << ", "
748           << Size << ", " << Align << '\n';
749         return;
750       }
751     }
752
753     if (!GVar->isThreadLocal() &&
754         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
755       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
756
757       if (MAI->getLCOMMDirective() != NULL) {
758         if (GVar->hasLocalLinkage()) {
759           O << MAI->getLCOMMDirective() << name << ',' << Size;
760           if (Subtarget->isTargetDarwin())
761             O << ',' << Align;
762         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
763           O << "\t.globl " << name << '\n'
764             << MAI->getWeakDefDirective() << name << '\n';
765           EmitAlignment(Align, GVar);
766           O << name << ":";
767           if (VerboseAsm) {
768             O.PadToColumn(MAI->getCommentColumn());
769             O << MAI->getCommentString() << ' ';
770             WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
771           }
772           O << '\n';
773           EmitGlobalConstant(C);
774           return;
775         } else {
776           O << MAI->getCOMMDirective()  << name << ',' << Size;
777           if (MAI->getCOMMDirectiveTakesAlignment())
778             O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
779         }
780       } else {
781         if (!Subtarget->isTargetCygMing()) {
782           if (GVar->hasLocalLinkage())
783             O << "\t.local\t" << name << '\n';
784         }
785         O << MAI->getCOMMDirective()  << name << ',' << Size;
786         if (MAI->getCOMMDirectiveTakesAlignment())
787           O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
788       }
789       if (VerboseAsm) {
790         O.PadToColumn(MAI->getCommentColumn());
791         O << MAI->getCommentString() << ' ';
792         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
793       }
794       O << '\n';
795       return;
796     }
797   }
798
799   switch (GVar->getLinkage()) {
800   case GlobalValue::CommonLinkage:
801   case GlobalValue::LinkOnceAnyLinkage:
802   case GlobalValue::LinkOnceODRLinkage:
803   case GlobalValue::WeakAnyLinkage:
804   case GlobalValue::WeakODRLinkage:
805   case GlobalValue::LinkerPrivateLinkage:
806     if (Subtarget->isTargetDarwin()) {
807       O << "\t.globl " << name << '\n'
808         << MAI->getWeakDefDirective() << name << '\n';
809     } else if (Subtarget->isTargetCygMing()) {
810       O << "\t.globl\t" << name << "\n"
811            "\t.linkonce same_size\n";
812     } else {
813       O << "\t.weak\t" << name << '\n';
814     }
815     break;
816   case GlobalValue::DLLExportLinkage:
817   case GlobalValue::AppendingLinkage:
818     // FIXME: appending linkage variables should go into a section of
819     // their name or something.  For now, just emit them as external.
820   case GlobalValue::ExternalLinkage:
821     // If external or appending, declare as a global symbol
822     O << "\t.globl " << name << '\n';
823     // FALL THROUGH
824   case GlobalValue::PrivateLinkage:
825   case GlobalValue::InternalLinkage:
826      break;
827   default:
828     llvm_unreachable("Unknown linkage type!");
829   }
830
831   EmitAlignment(Align, GVar);
832   O << name << ":";
833   if (VerboseAsm){
834     O.PadToColumn(MAI->getCommentColumn());
835     O << MAI->getCommentString() << ' ';
836     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
837   }
838   O << '\n';
839
840   EmitGlobalConstant(C);
841
842   if (MAI->hasDotTypeDotSizeDirective())
843     O << "\t.size\t" << name << ", " << Size << '\n';
844 }
845
846 bool X86ATTAsmPrinter::doFinalization(Module &M) {
847   // Print out module-level global variables here.
848   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
849        I != E; ++I) {
850     if (I->hasDLLExportLinkage())
851       DLLExportedGVs.insert(Mang->getMangledName(I));
852   }
853
854   if (Subtarget->isTargetDarwin()) {
855     // All darwin targets use mach-o.
856     TargetLoweringObjectFileMachO &TLOFMacho = 
857       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
858     
859     // Add the (possibly multiple) personalities to the set of global value
860     // stubs.  Only referenced functions get into the Personalities list.
861     if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
862       const std::vector<Function*> &Personalities = MMI->getPersonalities();
863       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
864         if (Personalities[i])
865           GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
866                                        true /*private label*/)] = 
867             Mang->getMangledName(Personalities[i]);
868       }
869     }
870
871     // Output stubs for dynamically-linked functions
872     if (!FnStubs.empty()) {
873       const MCSection *TheSection = 
874         TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
875                                   MCSectionMachO::S_SYMBOL_STUBS |
876                                   MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
877                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
878                                   5, SectionKind::getMetadata());
879       OutStreamer.SwitchSection(TheSection);
880       for (StringMap<std::string>::iterator I = FnStubs.begin(),
881            E = FnStubs.end(); I != E; ++I)
882         O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
883           << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
884       O << '\n';
885     }
886
887     // Output stubs for external and common global variables.
888     if (!GVStubs.empty()) {
889       const MCSection *TheSection = 
890         TLOFMacho.getMachOSection("__IMPORT", "__pointers",
891                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
892                                   SectionKind::getMetadata());
893       OutStreamer.SwitchSection(TheSection);
894       for (StringMap<std::string>::iterator I = GVStubs.begin(),
895            E = GVStubs.end(); I != E; ++I)
896         O << I->getKeyData() << ":\n\t.indirect_symbol "
897           << I->second << "\n\t.long\t0\n";
898     }
899
900     if (!HiddenGVStubs.empty()) {
901       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
902       EmitAlignment(2);
903       for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
904            E = HiddenGVStubs.end(); I != E; ++I)
905         O << I->getKeyData() << ":\n" << MAI->getData32bitsDirective()
906           << I->second << '\n';
907     }
908
909     // Funny Darwin hack: This flag tells the linker that no global symbols
910     // contain code that falls through to other global symbols (e.g. the obvious
911     // implementation of multiple entry points).  If this doesn't occur, the
912     // linker can safely perform dead code stripping.  Since LLVM never
913     // generates code that does this, it is always safe to set.
914     O << "\t.subsections_via_symbols\n";
915   } else if (Subtarget->isTargetCygMing()) {
916     // Emit type information for external functions
917     for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
918          i != e; ++i) {
919       O << "\t.def\t " << i->getKeyData()
920         << ";\t.scl\t" << COFF::C_EXT
921         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
922         << ";\t.endef\n";
923     }
924   }
925   
926   
927   // Output linker support code for dllexported globals on windows.
928   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
929     // dllexport symbols only exist on coff targets.
930     TargetLoweringObjectFileCOFF &TLOFMacho = 
931       static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
932     
933     OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
934                                                  SectionKind::getMetadata()));
935   
936     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
937          e = DLLExportedGVs.end(); i != e; ++i)
938       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
939   
940     for (StringSet<>::iterator i = DLLExportedFns.begin(),
941          e = DLLExportedFns.end();
942          i != e; ++i)
943       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
944   }
945   
946   // Do common shutdown.
947   return AsmPrinter::doFinalization(M);
948 }
949
950 // Include the auto-generated portion of the assembly writer.
951 #include "X86GenAsmWriter.inc"