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