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