remove extraneous hack.
[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);
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 ||
310              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
311       Suffix = "$non_lazy_ptr";
312     
313     std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
314     if (Subtarget->isTargetCygMing())
315       DecorateCygMingName(Name, GV);
316     
317     // Handle dllimport linkage.
318     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
319       Name = "__imp_" + Name;
320     
321     if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
322         MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
323       GVStubs[Name] = Mang->getMangledName(GV);
324     else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
325              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
326       HiddenGVStubs[Name] = Mang->getMangledName(GV);
327     else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
328       FnStubs[Name] = Mang->getMangledName(GV);
329     
330     // If the name begins with a dollar-sign, enclose it in parens.  We do this
331     // to avoid having it look like an integer immediate to the assembler.
332     if (Name[0] == '$') 
333       O << '(' << Name << ')';
334     else
335       O << Name;
336     
337     printOffset(MO.getOffset());
338     break;
339   }
340   case MachineOperand::MO_ExternalSymbol: {
341     std::string Name = Mang->makeNameProper(MO.getSymbolName());
342     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
343       FnStubs[Name+"$stub"] = Name;
344       Name += "$stub";
345     }
346     
347     // If the name begins with a dollar-sign, enclose it in parens.  We do this
348     // to avoid having it look like an integer immediate to the assembler.
349     if (Name[0] == '$') 
350       O << '(' << Name << ')';
351     else
352       O << Name;
353     break;
354   }
355   }
356   
357   switch (MO.getTargetFlags()) {
358   default:
359     llvm_unreachable("Unknown target flag on GV operand");
360   case X86II::MO_NO_FLAG:    // No flag.
361     break;
362   case X86II::MO_DARWIN_NONLAZY:
363   case X86II::MO_DARWIN_HIDDEN_NONLAZY:
364   case X86II::MO_DLLIMPORT:
365   case X86II::MO_DARWIN_STUB:
366     // These affect the name of the symbol, not any suffix.
367     break;
368   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
369     O << " + [.-";
370     PrintPICBaseSymbol();
371     O << ']';
372     break;      
373   case X86II::MO_PIC_BASE_OFFSET:
374   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
375   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
376     O << '-';
377     PrintPICBaseSymbol();
378     break;
379   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
380   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
381   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
382   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
383   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
384   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
385   case X86II::MO_GOT:       O << "@GOT";       break;
386   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
387   case X86II::MO_PLT:       O << "@PLT";       break;
388   }
389 }
390
391 /// print_pcrel_imm - This is used to print an immediate value that ends up
392 /// being encoded as a pc-relative value.  These print slightly differently, for
393 /// example, a $ is not emitted.
394 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
395   const MachineOperand &MO = MI->getOperand(OpNo);
396   switch (MO.getType()) {
397   default: llvm_unreachable("Unknown pcrel immediate operand");
398   case MachineOperand::MO_Immediate:
399     O << MO.getImm();
400     return;
401   case MachineOperand::MO_MachineBasicBlock:
402     printBasicBlockLabel(MO.getMBB(), false, false, false);
403     return;
404   case MachineOperand::MO_GlobalAddress:
405   case MachineOperand::MO_ExternalSymbol:
406     printSymbolOperand(MO);
407     return;
408   }
409 }
410
411
412
413 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
414                                     const char *Modifier) {
415   const MachineOperand &MO = MI->getOperand(OpNo);
416   switch (MO.getType()) {
417   default: llvm_unreachable("unknown operand type!");
418   case MachineOperand::MO_Register: {
419     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
420            "Virtual registers should not make it this far!");
421     O << '%';
422     unsigned Reg = MO.getReg();
423     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
424       EVT VT = (strcmp(Modifier+6,"64") == 0) ?
425         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
426                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
427       Reg = getX86SubSuperRegister(Reg, VT);
428     }
429     O << TRI->getAsmName(Reg);
430     return;
431   }
432
433   case MachineOperand::MO_Immediate:
434     O << '$' << MO.getImm();
435     return;
436
437   case MachineOperand::MO_JumpTableIndex:
438   case MachineOperand::MO_ConstantPoolIndex:
439   case MachineOperand::MO_GlobalAddress: 
440   case MachineOperand::MO_ExternalSymbol: {
441     O << '$';
442     printSymbolOperand(MO);
443     break;
444   }
445   }
446 }
447
448 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
449   unsigned char value = MI->getOperand(Op).getImm();
450   assert(value <= 7 && "Invalid ssecc argument!");
451   switch (value) {
452   case 0: O << "eq"; break;
453   case 1: O << "lt"; break;
454   case 2: O << "le"; break;
455   case 3: O << "unord"; break;
456   case 4: O << "neq"; break;
457   case 5: O << "nlt"; break;
458   case 6: O << "nle"; break;
459   case 7: O << "ord"; break;
460   }
461 }
462
463 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
464                                             const char *Modifier) {
465   const MachineOperand &BaseReg  = MI->getOperand(Op);
466   const MachineOperand &IndexReg = MI->getOperand(Op+2);
467   const MachineOperand &DispSpec = MI->getOperand(Op+3);
468
469   // If we really don't want to print out (rip), don't.
470   bool HasBaseReg = BaseReg.getReg() != 0;
471   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
472       BaseReg.getReg() == X86::RIP)
473     HasBaseReg = false;
474   
475   // HasParenPart - True if we will print out the () part of the mem ref.
476   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
477   
478   if (DispSpec.isImm()) {
479     int DispVal = DispSpec.getImm();
480     if (DispVal || !HasParenPart)
481       O << DispVal;
482   } else {
483     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
484            DispSpec.isJTI() || DispSpec.isSymbol());
485     printSymbolOperand(MI->getOperand(Op+3));
486   }
487
488   if (HasParenPart) {
489     assert(IndexReg.getReg() != X86::ESP &&
490            "X86 doesn't allow scaling by ESP");
491
492     O << '(';
493     if (HasBaseReg)
494       printOperand(MI, Op, Modifier);
495
496     if (IndexReg.getReg()) {
497       O << ',';
498       printOperand(MI, Op+2, Modifier);
499       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
500       if (ScaleVal != 1)
501         O << ',' << ScaleVal;
502     }
503     O << ')';
504   }
505 }
506
507 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
508                                          const char *Modifier) {
509   assert(isMem(MI, Op) && "Invalid memory reference!");
510   const MachineOperand &Segment = MI->getOperand(Op+4);
511   if (Segment.getReg()) {
512     printOperand(MI, Op+4, Modifier);
513     O << ':';
514   }
515   printLeaMemReference(MI, Op, Modifier);
516 }
517
518 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
519                                            const MachineBasicBlock *MBB) const {
520   if (!MAI->getSetDirective())
521     return;
522
523   // We don't need .set machinery if we have GOT-style relocations
524   if (Subtarget->isPICStyleGOT())
525     return;
526
527   O << MAI->getSetDirective() << ' ' << MAI->getPrivateGlobalPrefix()
528     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
529   printBasicBlockLabel(MBB, false, false, false);
530   if (Subtarget->isPICStyleRIPRel())
531     O << '-' << MAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
532       << '_' << uid << '\n';
533   else {
534     O << '-';
535     PrintPICBaseSymbol();
536     O << '\n';
537   }
538 }
539
540
541 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
542   PrintPICBaseSymbol();
543   O << '\n';
544   PrintPICBaseSymbol();
545   O << ':';
546 }
547
548
549 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
550                                               const MachineBasicBlock *MBB,
551                                               unsigned uid) const {
552   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
553     MAI->getData32bitsDirective() : MAI->getData64bitsDirective();
554
555   O << JTEntryDirective << ' ';
556
557   if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
558     O << MAI->getPrivateGlobalPrefix() << getFunctionNumber()
559       << '_' << uid << "_set_" << MBB->getNumber();
560   } else if (Subtarget->isPICStyleGOT()) {
561     printBasicBlockLabel(MBB, false, false, false);
562     O << "@GOTOFF";
563   } else
564     printBasicBlockLabel(MBB, false, false, false);
565 }
566
567 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
568   unsigned Reg = MO.getReg();
569   switch (Mode) {
570   default: return true;  // Unknown mode.
571   case 'b': // Print QImode register
572     Reg = getX86SubSuperRegister(Reg, MVT::i8);
573     break;
574   case 'h': // Print QImode high register
575     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
576     break;
577   case 'w': // Print HImode register
578     Reg = getX86SubSuperRegister(Reg, MVT::i16);
579     break;
580   case 'k': // Print SImode register
581     Reg = getX86SubSuperRegister(Reg, MVT::i32);
582     break;
583   case 'q': // Print DImode register
584     Reg = getX86SubSuperRegister(Reg, MVT::i64);
585     break;
586   }
587
588   O << '%'<< TRI->getAsmName(Reg);
589   return false;
590 }
591
592 /// PrintAsmOperand - Print out an operand for an inline asm expression.
593 ///
594 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
595                                        unsigned AsmVariant,
596                                        const char *ExtraCode) {
597   // Does this asm operand have a single letter operand modifier?
598   if (ExtraCode && ExtraCode[0]) {
599     if (ExtraCode[1] != 0) return true; // Unknown modifier.
600
601     const MachineOperand &MO = MI->getOperand(OpNo);
602     
603     switch (ExtraCode[0]) {
604     default: return true;  // Unknown modifier.
605     case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
606       if (MO.isImm()) {
607         O << MO.getImm();
608         return false;
609       } 
610       if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
611         printSymbolOperand(MO);
612         return false;
613       }
614       if (MO.isReg()) {
615         O << '(';
616         printOperand(MI, OpNo);
617         O << ')';
618         return false;
619       }
620       return true;
621
622     case 'c': // Don't print "$" before a global var name or constant.
623       if (MO.isImm())
624         O << MO.getImm();
625       else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
626         printSymbolOperand(MO);
627       else
628         printOperand(MI, OpNo);
629       return false;
630
631     case 'A': // Print '*' before a register (it must be a register)
632       if (MO.isReg()) {
633         O << '*';
634         printOperand(MI, OpNo);
635         return false;
636       }
637       return true;
638
639     case 'b': // Print QImode register
640     case 'h': // Print QImode high register
641     case 'w': // Print HImode register
642     case 'k': // Print SImode register
643     case 'q': // Print DImode register
644       if (MO.isReg())
645         return printAsmMRegister(MO, ExtraCode[0]);
646       printOperand(MI, OpNo);
647       return false;
648
649     case 'P': // This is the operand of a call, treat specially.
650       print_pcrel_imm(MI, OpNo);
651       return false;
652
653     case 'n':  // Negate the immediate or print a '-' before the operand.
654       // Note: this is a temporary solution. It should be handled target
655       // independently as part of the 'MC' work.
656       if (MO.isImm()) {
657         O << -MO.getImm();
658         return false;
659       }
660       O << '-';
661     }
662   }
663
664   printOperand(MI, OpNo);
665   return false;
666 }
667
668 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
669                                              unsigned OpNo,
670                                              unsigned AsmVariant,
671                                              const char *ExtraCode) {
672   if (ExtraCode && ExtraCode[0]) {
673     if (ExtraCode[1] != 0) return true; // Unknown modifier.
674
675     switch (ExtraCode[0]) {
676     default: return true;  // Unknown modifier.
677     case 'b': // Print QImode register
678     case 'h': // Print QImode high register
679     case 'w': // Print HImode register
680     case 'k': // Print SImode register
681     case 'q': // Print SImode register
682       // These only apply to registers, ignore on mem.
683       break;
684     case 'P': // Don't print @PLT, but do print as memory.
685       printMemReference(MI, OpNo, "no-rip");
686       return false;
687     }
688   }
689   printMemReference(MI, OpNo);
690   return false;
691 }
692
693
694
695 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
696 /// AT&T syntax to the current output stream.
697 ///
698 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
699   ++EmittedInsts;
700
701   // Call the autogenerated instruction printer routines.
702   if (NewAsmPrinter)
703     printInstructionThroughMCStreamer(MI);
704   else
705     printInstruction(MI);
706 }
707
708 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
709   const TargetData *TD = TM.getTargetData();
710
711   if (!GVar->hasInitializer())
712     return;   // External global require no code
713
714   // Check to see if this is a special global used by LLVM, if so, emit it.
715   if (EmitSpecialLLVMGlobal(GVar)) {
716     if (Subtarget->isTargetDarwin() &&
717         TM.getRelocationModel() == Reloc::Static) {
718       if (GVar->getName() == "llvm.global_ctors")
719         O << ".reference .constructors_used\n";
720       else if (GVar->getName() == "llvm.global_dtors")
721         O << ".reference .destructors_used\n";
722     }
723     return;
724   }
725
726   std::string name = Mang->getMangledName(GVar);
727   Constant *C = GVar->getInitializer();
728   const Type *Type = C->getType();
729   unsigned Size = TD->getTypeAllocSize(Type);
730   unsigned Align = TD->getPreferredAlignmentLog(GVar);
731
732   printVisibility(name, GVar->getVisibility());
733
734   if (Subtarget->isTargetELF())
735     O << "\t.type\t" << name << ",@object\n";
736
737   
738   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
739   const MCSection *TheSection =
740     getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
741   OutStreamer.SwitchSection(TheSection);
742
743   // FIXME: get this stuff from section kind flags.
744   if (C->isNullValue() && !GVar->hasSection() &&
745       // Don't put things that should go in the cstring section into "comm".
746       !TheSection->getKind().isMergeableCString()) {
747     if (GVar->hasExternalLinkage()) {
748       if (const char *Directive = MAI->getZeroFillDirective()) {
749         O << "\t.globl " << name << '\n';
750         O << Directive << "__DATA, __common, " << name << ", "
751           << Size << ", " << Align << '\n';
752         return;
753       }
754     }
755
756     if (!GVar->isThreadLocal() &&
757         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
758       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
759
760       if (MAI->getLCOMMDirective() != NULL) {
761         if (GVar->hasLocalLinkage()) {
762           O << MAI->getLCOMMDirective() << name << ',' << Size;
763           if (Subtarget->isTargetDarwin())
764             O << ',' << Align;
765         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
766           O << "\t.globl " << name << '\n'
767             << MAI->getWeakDefDirective() << name << '\n';
768           EmitAlignment(Align, GVar);
769           O << name << ":";
770           if (VerboseAsm) {
771             O.PadToColumn(MAI->getCommentColumn());
772             O << MAI->getCommentString() << ' ';
773             WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
774           }
775           O << '\n';
776           EmitGlobalConstant(C);
777           return;
778         } else {
779           O << MAI->getCOMMDirective()  << name << ',' << Size;
780           if (MAI->getCOMMDirectiveTakesAlignment())
781             O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
782         }
783       } else {
784         if (!Subtarget->isTargetCygMing()) {
785           if (GVar->hasLocalLinkage())
786             O << "\t.local\t" << name << '\n';
787         }
788         O << MAI->getCOMMDirective()  << name << ',' << Size;
789         if (MAI->getCOMMDirectiveTakesAlignment())
790           O << ',' << (MAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
791       }
792       if (VerboseAsm) {
793         O.PadToColumn(MAI->getCommentColumn());
794         O << MAI->getCommentString() << ' ';
795         WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
796       }
797       O << '\n';
798       return;
799     }
800   }
801
802   switch (GVar->getLinkage()) {
803   case GlobalValue::CommonLinkage:
804   case GlobalValue::LinkOnceAnyLinkage:
805   case GlobalValue::LinkOnceODRLinkage:
806   case GlobalValue::WeakAnyLinkage:
807   case GlobalValue::WeakODRLinkage:
808   case GlobalValue::LinkerPrivateLinkage:
809     if (Subtarget->isTargetDarwin()) {
810       O << "\t.globl " << name << '\n'
811         << MAI->getWeakDefDirective() << name << '\n';
812     } else if (Subtarget->isTargetCygMing()) {
813       O << "\t.globl\t" << name << "\n"
814            "\t.linkonce same_size\n";
815     } else {
816       O << "\t.weak\t" << name << '\n';
817     }
818     break;
819   case GlobalValue::DLLExportLinkage:
820   case GlobalValue::AppendingLinkage:
821     // FIXME: appending linkage variables should go into a section of
822     // their name or something.  For now, just emit them as external.
823   case GlobalValue::ExternalLinkage:
824     // If external or appending, declare as a global symbol
825     O << "\t.globl " << name << '\n';
826     // FALL THROUGH
827   case GlobalValue::PrivateLinkage:
828   case GlobalValue::InternalLinkage:
829      break;
830   default:
831     llvm_unreachable("Unknown linkage type!");
832   }
833
834   EmitAlignment(Align, GVar);
835   O << name << ":";
836   if (VerboseAsm){
837     O.PadToColumn(MAI->getCommentColumn());
838     O << MAI->getCommentString() << ' ';
839     WriteAsOperand(O, GVar, /*PrintType=*/false, GVar->getParent());
840   }
841   O << '\n';
842
843   EmitGlobalConstant(C);
844
845   if (MAI->hasDotTypeDotSizeDirective())
846     O << "\t.size\t" << name << ", " << Size << '\n';
847 }
848
849 bool X86ATTAsmPrinter::doFinalization(Module &M) {
850   // Print out module-level global variables here.
851   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
852        I != E; ++I) {
853     if (I->hasDLLExportLinkage())
854       DLLExportedGVs.insert(Mang->getMangledName(I));
855   }
856
857   if (Subtarget->isTargetDarwin()) {
858     // All darwin targets use mach-o.
859     TargetLoweringObjectFileMachO &TLOFMacho = 
860       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
861     
862     // Add the (possibly multiple) personalities to the set of global value
863     // stubs.  Only referenced functions get into the Personalities list.
864     if (MAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
865       const std::vector<Function*> &Personalities = MMI->getPersonalities();
866       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
867         if (Personalities[i])
868           GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
869                                        true /*private label*/)] = 
870             Mang->getMangledName(Personalities[i]);
871       }
872     }
873
874     // Output stubs for dynamically-linked functions
875     if (!FnStubs.empty()) {
876       const MCSection *TheSection = 
877         TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
878                                   MCSectionMachO::S_SYMBOL_STUBS |
879                                   MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
880                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
881                                   5, SectionKind::getMetadata());
882       OutStreamer.SwitchSection(TheSection);
883       for (StringMap<std::string>::iterator I = FnStubs.begin(),
884            E = FnStubs.end(); I != E; ++I)
885         O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
886           << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
887       O << '\n';
888     }
889
890     // Output stubs for external and common global variables.
891     if (!GVStubs.empty()) {
892       const MCSection *TheSection = 
893         TLOFMacho.getMachOSection("__IMPORT", "__pointers",
894                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
895                                   SectionKind::getMetadata());
896       OutStreamer.SwitchSection(TheSection);
897       for (StringMap<std::string>::iterator I = GVStubs.begin(),
898            E = GVStubs.end(); I != E; ++I)
899         O << I->getKeyData() << ":\n\t.indirect_symbol "
900           << I->second << "\n\t.long\t0\n";
901     }
902
903     if (!HiddenGVStubs.empty()) {
904       OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
905       EmitAlignment(2);
906       for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
907            E = HiddenGVStubs.end(); I != E; ++I)
908         O << I->getKeyData() << ":\n" << MAI->getData32bitsDirective()
909           << I->second << '\n';
910     }
911
912     // Funny Darwin hack: This flag tells the linker that no global symbols
913     // contain code that falls through to other global symbols (e.g. the obvious
914     // implementation of multiple entry points).  If this doesn't occur, the
915     // linker can safely perform dead code stripping.  Since LLVM never
916     // generates code that does this, it is always safe to set.
917     O << "\t.subsections_via_symbols\n";
918   } else if (Subtarget->isTargetCygMing()) {
919     // Emit type information for external functions
920     for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
921          i != e; ++i) {
922       O << "\t.def\t " << i->getKeyData()
923         << ";\t.scl\t" << COFF::C_EXT
924         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
925         << ";\t.endef\n";
926     }
927   }
928   
929   
930   // Output linker support code for dllexported globals on windows.
931   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
932     // dllexport symbols only exist on coff targets.
933     TargetLoweringObjectFileCOFF &TLOFMacho = 
934       static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
935     
936     OutStreamer.SwitchSection(TLOFMacho.getCOFFSection(".section .drectve",true,
937                                                  SectionKind::getMetadata()));
938   
939     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
940          e = DLLExportedGVs.end(); i != e; ++i)
941       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
942   
943     for (StringSet<>::iterator i = DLLExportedFns.begin(),
944          e = DLLExportedFns.end();
945          i != e; ++i)
946       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
947   }
948   
949   // Do common shutdown.
950   return AsmPrinter::doFinalization(M);
951 }
952
953 // Include the auto-generated portion of the assembly writer.
954 #include "X86GenAsmWriter.inc"