Reapply my previous asmprinter changes now with more testing and two
[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/Mangler.h"
38 #include "llvm/Support/raw_ostream.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, raw_ostream &OS) {
64   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
65        Name != E; ++Name)
66     if (isprint(*Name))
67       OS << *Name;
68 }
69
70 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
71                                                     const TargetData *TD) {
72   X86MachineFunctionInfo Info;
73   uint64_t Size = 0;
74
75   switch (F->getCallingConv()) {
76   case CallingConv::X86_StdCall:
77     Info.setDecorationStyle(StdCall);
78     break;
79   case CallingConv::X86_FastCall:
80     Info.setDecorationStyle(FastCall);
81     break;
82   default:
83     return Info;
84   }
85
86   unsigned argNum = 1;
87   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
88        AI != AE; ++AI, ++argNum) {
89     const Type* Ty = AI->getType();
90
91     // 'Dereference' type in case of byval parameter attribute
92     if (F->paramHasAttr(argNum, Attribute::ByVal))
93       Ty = cast<PointerType>(Ty)->getElementType();
94
95     // Size should be aligned to DWORD boundary
96     Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
97   }
98
99   // We're not supporting tooooo huge arguments :)
100   Info.setBytesToPopOnReturn((unsigned int)Size);
101   return Info;
102 }
103
104 /// decorateName - Query FunctionInfoMap and use this information for various
105 /// name decoration.
106 void X86ATTAsmPrinter::decorateName(std::string &Name,
107                                     const GlobalValue *GV) {
108   const Function *F = dyn_cast<Function>(GV);
109   if (!F) return;
110
111   // Save function name for later type emission.
112   if (Subtarget->isTargetCygMing() && F->isDeclaration())
113     CygMingStubs.insert(Name);
114   
115   // We don't want to decorate non-stdcall or non-fastcall functions right now
116   unsigned CC = F->getCallingConv();
117   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
118     return;
119
120   // Decorate names only when we're targeting Cygwin/Mingw32 targets
121   if (!Subtarget->isTargetCygMing())
122     return;
123
124   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
125
126   const X86MachineFunctionInfo *Info;
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   decorateName(CurrentFnName, F);
167
168   SwitchToSection(TAI->SectionForGlobal(F));
169   switch (F->getLinkage()) {
170   default: llvm_unreachable("Unknown linkage type!");
171   case Function::InternalLinkage:  // Symbols default to internal.
172   case Function::PrivateLinkage:
173     EmitAlignment(FnAlign, F);
174     break;
175   case Function::DLLExportLinkage:
176   case Function::ExternalLinkage:
177     EmitAlignment(FnAlign, F);
178     O << "\t.globl\t" << CurrentFnName << '\n';
179     break;
180   case Function::LinkOnceAnyLinkage:
181   case Function::LinkOnceODRLinkage:
182   case Function::WeakAnyLinkage:
183   case Function::WeakODRLinkage:
184     EmitAlignment(FnAlign, F);
185     if (Subtarget->isTargetDarwin()) {
186       O << "\t.globl\t" << CurrentFnName << '\n';
187       O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
188     } else if (Subtarget->isTargetCygMing()) {
189       O << "\t.globl\t" << CurrentFnName << "\n"
190            "\t.linkonce discard\n";
191     } else {
192       O << "\t.weak\t" << CurrentFnName << '\n';
193     }
194     break;
195   }
196
197   printVisibility(CurrentFnName, F->getVisibility());
198
199   if (Subtarget->isTargetELF())
200     O << "\t.type\t" << CurrentFnName << ",@function\n";
201   else if (Subtarget->isTargetCygMing()) {
202     O << "\t.def\t " << CurrentFnName
203       << ";\t.scl\t" <<
204       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
205       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
206       << ";\t.endef\n";
207   }
208
209   O << CurrentFnName << ":\n";
210   // Add some workaround for linkonce linkage on Cygwin\MinGW
211   if (Subtarget->isTargetCygMing() &&
212       (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
213     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
214 }
215
216 /// runOnMachineFunction - This uses the printMachineInstruction()
217 /// method to print assembly for each instruction.
218 ///
219 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
220   const Function *F = MF.getFunction();
221   this->MF = &MF;
222   unsigned CC = F->getCallingConv();
223
224   SetupMachineFunction(MF);
225   O << "\n\n";
226
227   // Populate function information map.  Actually, We don't want to populate
228   // non-stdcall or non-fastcall functions' information right now.
229   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
230     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
231
232   // Print out constants referenced by the function
233   EmitConstantPool(MF.getConstantPool());
234
235   if (F->hasDLLExportLinkage())
236     DLLExportedFns.insert(Mang->getMangledName(F));
237
238   // Print the 'header' of function
239   emitFunctionHeader(MF);
240
241   // Emit pre-function debug and/or EH information.
242   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
243     DW->BeginFunction(&MF);
244
245   // Print out code for the function.
246   bool hasAnyRealCode = false;
247   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
248        I != E; ++I) {
249     // Print a label for the basic block.
250     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
251       // This is an entry block or a block that's only reachable via a
252       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
253     } else {
254       printBasicBlockLabel(I, true, true, VerboseAsm);
255       O << '\n';
256     }
257     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
258          II != IE; ++II) {
259       // Print the assembly for the instruction.
260       if (!II->isLabel())
261         hasAnyRealCode = true;
262       printMachineInstruction(II);
263     }
264   }
265
266   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
267     // If the function is empty, then we need to emit *something*. Otherwise,
268     // the function's label might be associated with something that it wasn't
269     // meant to be associated with. We emit a noop in this situation.
270     // We are assuming inline asms are code.
271     O << "\tnop\n";
272   }
273
274   if (TAI->hasDotTypeDotSizeDirective())
275     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
276
277   // Emit post-function debug information.
278   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
279     DW->EndFunction(&MF);
280
281   // Print out jump tables referenced by the function.
282   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
283
284   O.flush();
285
286   // We didn't modify anything.
287   return false;
288 }
289
290 /// printSymbolOperand - Print a raw symbol reference operand.  This handles
291 /// jump tables, constant pools, global address and external symbols, all of
292 /// which print to a label with various suffixes for relocation types etc.
293 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
294   switch (MO.getType()) {
295   default: llvm_unreachable("unknown symbol type!");
296   case MachineOperand::MO_JumpTableIndex:
297     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
298       << MO.getIndex();
299     break;
300   case MachineOperand::MO_ConstantPoolIndex:
301     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
302       << MO.getIndex();
303     printOffset(MO.getOffset());
304     break;
305   case MachineOperand::MO_GlobalAddress: {
306     const GlobalValue *GV = MO.getGlobal();
307     
308     const char *Suffix = "";
309     
310     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
311       Suffix = "$stub";
312     else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
313              MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
314              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
315              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
316       Suffix = "$non_lazy_ptr";
317     
318     std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
319     decorateName(Name, GV);
320     
321     // Handle dllimport linkage.
322     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
323       Name = "__imp_" + Name;
324     
325     if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
326         MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
327       GVStubs[Name] = Mang->getMangledName(GV);
328     else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
329              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
330       HiddenGVStubs[Name] = Mang->getMangledName(GV);
331     else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
332       FnStubs[Name] = Mang->getMangledName(GV);
333     
334     // If the name begins with a dollar-sign, enclose it in parens.  We do this
335     // to avoid having it look like an integer immediate to the assembler.
336     if (Name[0] == '$') 
337       O << '(' << Name << ')';
338     else
339       O << Name;
340     
341     printOffset(MO.getOffset());
342     break;
343   }
344   case MachineOperand::MO_ExternalSymbol: {
345     std::string Name(TAI->getGlobalPrefix());
346     Name += MO.getSymbolName();
347
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     printSymbolOperand(MO);
412     return;
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.MakeReg(MO.getReg());
729       } else if (MO.isImm()) {
730         MCOp.MakeImm(MO.getImm());
731       } else if (MO.isMBB()) {
732         MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
733       } else {
734         llvm_unreachable("Unimp");
735       }
736       
737       TmpInst.addOperand(MCOp);
738     }
739     
740     switch (TmpInst.getOpcode()) {
741     case X86::LEA64_32r:
742       // Handle the 'subreg rewriting' for the lea64_32mem operand.
743       lower_lea64_32mem(&TmpInst, 1);
744       break;
745     }
746     
747     // FIXME: Convert TmpInst.
748     printInstruction(&TmpInst);
749     O << "OLD: ";
750   }
751   
752   // Call the autogenerated instruction printer routines.
753   printInstruction(MI);
754 }
755
756 /// doInitialization
757 bool X86ATTAsmPrinter::doInitialization(Module &M) {
758   if (NewAsmPrinter) {
759     Context = new MCContext();
760     // FIXME: Send this to "O" instead of outs().  For now, we force it to
761     // stdout to make it easy to compare.
762     Streamer = createAsmStreamer(*Context, outs());
763   }
764   
765   return AsmPrinter::doInitialization(M);
766 }
767
768 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
769   const TargetData *TD = TM.getTargetData();
770
771   if (!GVar->hasInitializer())
772     return;   // External global require no code
773
774   // Check to see if this is a special global used by LLVM, if so, emit it.
775   if (EmitSpecialLLVMGlobal(GVar)) {
776     if (Subtarget->isTargetDarwin() &&
777         TM.getRelocationModel() == Reloc::Static) {
778       if (GVar->getName() == "llvm.global_ctors")
779         O << ".reference .constructors_used\n";
780       else if (GVar->getName() == "llvm.global_dtors")
781         O << ".reference .destructors_used\n";
782     }
783     return;
784   }
785
786   std::string name = Mang->getMangledName(GVar);
787   Constant *C = GVar->getInitializer();
788   if (isa<MDNode>(C) || isa<MDString>(C))
789     return;
790   const Type *Type = C->getType();
791   unsigned Size = TD->getTypeAllocSize(Type);
792   unsigned Align = TD->getPreferredAlignmentLog(GVar);
793
794   printVisibility(name, GVar->getVisibility());
795
796   if (Subtarget->isTargetELF())
797     O << "\t.type\t" << name << ",@object\n";
798
799   SwitchToSection(TAI->SectionForGlobal(GVar));
800
801   if (C->isNullValue() && !GVar->hasSection() &&
802       !(Subtarget->isTargetDarwin() &&
803         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
804     // FIXME: This seems to be pretty darwin-specific
805     if (GVar->hasExternalLinkage()) {
806       if (const char *Directive = TAI->getZeroFillDirective()) {
807         O << "\t.globl " << name << '\n';
808         O << Directive << "__DATA, __common, " << name << ", "
809           << Size << ", " << Align << '\n';
810         return;
811       }
812     }
813
814     if (!GVar->isThreadLocal() &&
815         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
816       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
817
818       if (TAI->getLCOMMDirective() != NULL) {
819         if (GVar->hasLocalLinkage()) {
820           O << TAI->getLCOMMDirective() << name << ',' << Size;
821           if (Subtarget->isTargetDarwin())
822             O << ',' << Align;
823         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
824           O << "\t.globl " << name << '\n'
825             << TAI->getWeakDefDirective() << name << '\n';
826           EmitAlignment(Align, GVar);
827           O << name << ":";
828           if (VerboseAsm) {
829             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
830             PrintUnmangledNameSafely(GVar, O);
831           }
832           O << '\n';
833           EmitGlobalConstant(C);
834           return;
835         } else {
836           O << TAI->getCOMMDirective()  << name << ',' << Size;
837           if (TAI->getCOMMDirectiveTakesAlignment())
838             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
839         }
840       } else {
841         if (!Subtarget->isTargetCygMing()) {
842           if (GVar->hasLocalLinkage())
843             O << "\t.local\t" << name << '\n';
844         }
845         O << TAI->getCOMMDirective()  << name << ',' << Size;
846         if (TAI->getCOMMDirectiveTakesAlignment())
847           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
848       }
849       if (VerboseAsm) {
850         O << "\t\t" << TAI->getCommentString() << ' ';
851         PrintUnmangledNameSafely(GVar, O);
852       }
853       O << '\n';
854       return;
855     }
856   }
857
858   switch (GVar->getLinkage()) {
859   case GlobalValue::CommonLinkage:
860   case GlobalValue::LinkOnceAnyLinkage:
861   case GlobalValue::LinkOnceODRLinkage:
862   case GlobalValue::WeakAnyLinkage:
863   case GlobalValue::WeakODRLinkage:
864     if (Subtarget->isTargetDarwin()) {
865       O << "\t.globl " << name << '\n'
866         << TAI->getWeakDefDirective() << name << '\n';
867     } else if (Subtarget->isTargetCygMing()) {
868       O << "\t.globl\t" << name << "\n"
869            "\t.linkonce same_size\n";
870     } else {
871       O << "\t.weak\t" << name << '\n';
872     }
873     break;
874   case GlobalValue::DLLExportLinkage:
875   case GlobalValue::AppendingLinkage:
876     // FIXME: appending linkage variables should go into a section of
877     // their name or something.  For now, just emit them as external.
878   case GlobalValue::ExternalLinkage:
879     // If external or appending, declare as a global symbol
880     O << "\t.globl " << name << '\n';
881     // FALL THROUGH
882   case GlobalValue::PrivateLinkage:
883   case GlobalValue::InternalLinkage:
884      break;
885   default:
886     llvm_unreachable("Unknown linkage type!");
887   }
888
889   EmitAlignment(Align, GVar);
890   O << name << ":";
891   if (VerboseAsm){
892     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
893     PrintUnmangledNameSafely(GVar, O);
894   }
895   O << '\n';
896   if (TAI->hasDotTypeDotSizeDirective())
897     O << "\t.size\t" << name << ", " << Size << '\n';
898
899   EmitGlobalConstant(C);
900 }
901
902 bool X86ATTAsmPrinter::doFinalization(Module &M) {
903   // Print out module-level global variables here.
904   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
905        I != E; ++I) {
906     printModuleLevelGV(I);
907
908     if (I->hasDLLExportLinkage())
909       DLLExportedGVs.insert(Mang->getMangledName(I));
910   }
911
912   if (Subtarget->isTargetDarwin()) {
913     SwitchToDataSection("");
914     
915     // Add the (possibly multiple) personalities to the set of global value
916     // stubs.  Only referenced functions get into the Personalities list.
917     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
918       const std::vector<Function*> &Personalities = MMI->getPersonalities();
919       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
920         if (Personalities[i])
921           GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
922                                        true /*private label*/)] = 
923             Mang->getMangledName(Personalities[i]);
924       }
925     }
926
927     // Output stubs for dynamically-linked functions
928     if (!FnStubs.empty()) {
929       SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
930                           "self_modifying_code+pure_instructions,5", 0);
931       for (StringMap<std::string>::iterator I = FnStubs.begin(),
932            E = FnStubs.end(); I != E; ++I)
933         O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
934           << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
935       O << '\n';
936     }
937
938     // Output stubs for external and common global variables.
939     if (!GVStubs.empty()) {
940       SwitchToDataSection(
941                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
942       for (StringMap<std::string>::iterator I = GVStubs.begin(),
943            E = GVStubs.end(); I != E; ++I)
944         O << I->getKeyData() << ":\n\t.indirect_symbol "
945           << I->second << "\n\t.long\t0\n";
946     }
947
948     if (!HiddenGVStubs.empty()) {
949       SwitchToSection(TAI->getDataSection());
950       EmitAlignment(2);
951       for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
952            E = HiddenGVStubs.end(); I != E; ++I)
953         O << I->getKeyData() << ":\n" << TAI->getData32bitsDirective()
954           << I->second << '\n';
955     }
956
957     // Funny Darwin hack: This flag tells the linker that no global symbols
958     // contain code that falls through to other global symbols (e.g. the obvious
959     // implementation of multiple entry points).  If this doesn't occur, the
960     // linker can safely perform dead code stripping.  Since LLVM never
961     // generates code that does this, it is always safe to set.
962     O << "\t.subsections_via_symbols\n";
963   } else if (Subtarget->isTargetCygMing()) {
964     // Emit type information for external functions
965     for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
966          i != e; ++i) {
967       O << "\t.def\t " << i->getKeyData()
968         << ";\t.scl\t" << COFF::C_EXT
969         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
970         << ";\t.endef\n";
971     }
972   }
973   
974   
975   // Output linker support code for dllexported globals on windows.
976   if (!DLLExportedGVs.empty()) {
977     SwitchToDataSection(".section .drectve");
978   
979     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
980          e = DLLExportedGVs.end(); i != e; ++i)
981       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
982   }
983   
984   if (!DLLExportedFns.empty()) {
985     SwitchToDataSection(".section .drectve");
986   
987     for (StringSet<>::iterator i = DLLExportedFns.begin(),
988          e = DLLExportedFns.end();
989          i != e; ++i)
990       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
991   }
992   
993   // Do common shutdown.
994   bool Changed = AsmPrinter::doFinalization(M);
995   
996   if (NewAsmPrinter) {
997     Streamer->Finish();
998     
999     delete Streamer;
1000     delete Context;
1001     Streamer = 0;
1002     Context = 0;
1003   }
1004   
1005   return Changed;
1006 }
1007
1008 // Include the auto-generated portion of the assembly writer.
1009 #include "X86GenAsmWriter.inc"