Split EVT into MVT and EVT, the former representing _just_ a primitive type, while
[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/Type.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/MC/MCContext.h"
30 #include "llvm/MC/MCInst.h"
31 #include "llvm/MC/MCSectionMachO.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/TargetLoweringObjectFile.h"
41 #include "llvm/Target/TargetOptions.h"
42 using namespace llvm;
43
44 STATISTIC(EmittedInsts, "Number of machine instrs printed");
45
46 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
47                                    cl::Hidden);
48
49 //===----------------------------------------------------------------------===//
50 // Primitive Helper Functions.
51 //===----------------------------------------------------------------------===//
52
53 void X86ATTAsmPrinter::PrintPICBaseSymbol() const {
54   if (Subtarget->isTargetDarwin())
55     O << "\"L" << getFunctionNumber() << "$pb\"";
56   else if (Subtarget->isTargetELF())
57     O << ".Lllvm$" << getFunctionNumber() << ".$piclabel";
58   else
59     llvm_unreachable("Don't know how to print PIC label!");
60 }
61
62 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
63 /// Don't print things like \\n or \\0.
64 static void PrintUnmangledNameSafely(const Value *V, 
65                                      formatted_raw_ostream &OS) {
66   for (StringRef::iterator it = V->getName().begin(), 
67          ie = V->getName().end(); it != ie; ++it)
68     if (isprint(*it))
69       OS << *it;
70 }
71
72 static X86MachineFunctionInfo calculateFunctionInfo(const Function *F,
73                                                     const TargetData *TD) {
74   X86MachineFunctionInfo Info;
75   uint64_t Size = 0;
76
77   switch (F->getCallingConv()) {
78   case CallingConv::X86_StdCall:
79     Info.setDecorationStyle(StdCall);
80     break;
81   case CallingConv::X86_FastCall:
82     Info.setDecorationStyle(FastCall);
83     break;
84   default:
85     return Info;
86   }
87
88   unsigned argNum = 1;
89   for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
90        AI != AE; ++AI, ++argNum) {
91     const Type* Ty = AI->getType();
92
93     // 'Dereference' type in case of byval parameter attribute
94     if (F->paramHasAttr(argNum, Attribute::ByVal))
95       Ty = cast<PointerType>(Ty)->getElementType();
96
97     // Size should be aligned to DWORD boundary
98     Size += ((TD->getTypeAllocSize(Ty) + 3)/4)*4;
99   }
100
101   // We're not supporting tooooo huge arguments :)
102   Info.setBytesToPopOnReturn((unsigned int)Size);
103   return Info;
104 }
105
106 /// DecorateCygMingName - Query FunctionInfoMap and use this information for
107 /// various name decorations for Cygwin and MingW.
108 void X86ATTAsmPrinter::DecorateCygMingName(std::string &Name,
109                                            const GlobalValue *GV) {
110   assert(Subtarget->isTargetCygMing() && "This is only for cygwin and mingw");
111   
112   const Function *F = dyn_cast<Function>(GV);
113   if (!F) return;
114
115   // Save function name for later type emission.
116   if (F->isDeclaration())
117     CygMingStubs.insert(Name);
118   
119   // We don't want to decorate non-stdcall or non-fastcall functions right now
120   unsigned CC = F->getCallingConv();
121   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
122     return;
123
124
125   const X86MachineFunctionInfo *Info;
126   
127   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
128   if (info_item == FunctionInfoMap.end()) {
129     // Calculate apropriate function info and populate map
130     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
131     Info = &FunctionInfoMap[F];
132   } else {
133     Info = &info_item->second;
134   }
135
136   const FunctionType *FT = F->getFunctionType();
137   switch (Info->getDecorationStyle()) {
138   case None:
139     break;
140   case StdCall:
141     // "Pure" variadic functions do not receive @0 suffix.
142     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
143         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
144       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
145     break;
146   case FastCall:
147     // "Pure" variadic functions do not receive @0 suffix.
148     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
149         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
150       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
151
152     if (Name[0] == '_') {
153       Name[0] = '@';
154     } else {
155       Name = '@' + Name;
156     }
157     break;
158   default:
159     llvm_unreachable("Unsupported DecorationStyle");
160   }
161 }
162
163 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
164   unsigned FnAlign = MF.getAlignment();
165   const Function *F = MF.getFunction();
166
167   if (Subtarget->isTargetCygMing())
168     DecorateCygMingName(CurrentFnName, F);
169
170   SwitchToSection(getObjFileLowering().SectionForGlobal(F, Mang, TM));
171   EmitAlignment(FnAlign, F);
172
173   switch (F->getLinkage()) {
174   default: llvm_unreachable("Unknown linkage type!");
175   case Function::InternalLinkage:  // Symbols default to internal.
176   case Function::PrivateLinkage:
177   case Function::LinkerPrivateLinkage:
178     break;
179   case Function::DLLExportLinkage:
180   case Function::ExternalLinkage:
181     O << "\t.globl\t" << CurrentFnName << '\n';
182     break;
183   case Function::LinkOnceAnyLinkage:
184   case Function::LinkOnceODRLinkage:
185   case Function::WeakAnyLinkage:
186   case Function::WeakODRLinkage:
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   // 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     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
310       Suffix = "$stub";
311     else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
312              MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
313              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
314              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
315       Suffix = "$non_lazy_ptr";
316     
317     std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
318     if (Subtarget->isTargetCygMing())
319       DecorateCygMingName(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 = Mang->makeNameProper(MO.getSymbolName());
346     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
347       FnStubs[Name+"$stub"] = Name;
348       Name += "$stub";
349     }
350     
351     // If the name begins with a dollar-sign, enclose it in parens.  We do this
352     // to avoid having it look like an integer immediate to the assembler.
353     if (Name[0] == '$') 
354       O << '(' << Name << ')';
355     else
356       O << Name;
357     break;
358   }
359   }
360   
361   switch (MO.getTargetFlags()) {
362   default:
363     llvm_unreachable("Unknown target flag on GV operand");
364   case X86II::MO_NO_FLAG:    // No flag.
365     break;
366   case X86II::MO_DARWIN_NONLAZY:
367   case X86II::MO_DARWIN_HIDDEN_NONLAZY:
368   case X86II::MO_DLLIMPORT:
369   case X86II::MO_DARWIN_STUB:
370     // These affect the name of the symbol, not any suffix.
371     break;
372   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
373     O << " + [.-";
374     PrintPICBaseSymbol();
375     O << ']';
376     break;      
377   case X86II::MO_PIC_BASE_OFFSET:
378   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
379   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
380     O << '-';
381     PrintPICBaseSymbol();
382     break;
383   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
384   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
385   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
386   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
387   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
388   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
389   case X86II::MO_GOT:       O << "@GOT";       break;
390   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
391   case X86II::MO_PLT:       O << "@PLT";       break;
392   }
393 }
394
395 /// print_pcrel_imm - This is used to print an immediate value that ends up
396 /// being encoded as a pc-relative value.  These print slightly differently, for
397 /// example, a $ is not emitted.
398 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
399   const MachineOperand &MO = MI->getOperand(OpNo);
400   switch (MO.getType()) {
401   default: llvm_unreachable("Unknown pcrel immediate operand");
402   case MachineOperand::MO_Immediate:
403     O << MO.getImm();
404     return;
405   case MachineOperand::MO_MachineBasicBlock:
406     printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
407     return;
408   case MachineOperand::MO_GlobalAddress:
409   case MachineOperand::MO_ExternalSymbol:
410     printSymbolOperand(MO);
411     return;
412   }
413 }
414
415
416
417 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
418                                     const char *Modifier) {
419   const MachineOperand &MO = MI->getOperand(OpNo);
420   switch (MO.getType()) {
421   default: llvm_unreachable("unknown operand type!");
422   case MachineOperand::MO_Register: {
423     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
424            "Virtual registers should not make it this far!");
425     O << '%';
426     unsigned Reg = MO.getReg();
427     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
428       EVT VT = (strcmp(Modifier+6,"64") == 0) ?
429         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
430                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
431       Reg = getX86SubSuperRegister(Reg, VT);
432     }
433     O << TRI->getAsmName(Reg);
434     return;
435   }
436
437   case MachineOperand::MO_Immediate:
438     O << '$' << MO.getImm();
439     return;
440
441   case MachineOperand::MO_JumpTableIndex:
442   case MachineOperand::MO_ConstantPoolIndex:
443   case MachineOperand::MO_GlobalAddress: 
444   case MachineOperand::MO_ExternalSymbol: {
445     O << '$';
446     printSymbolOperand(MO);
447     break;
448   }
449   }
450 }
451
452 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
453   unsigned char value = MI->getOperand(Op).getImm();
454   assert(value <= 7 && "Invalid ssecc argument!");
455   switch (value) {
456   case 0: O << "eq"; break;
457   case 1: O << "lt"; break;
458   case 2: O << "le"; break;
459   case 3: O << "unord"; break;
460   case 4: O << "neq"; break;
461   case 5: O << "nlt"; break;
462   case 6: O << "nle"; break;
463   case 7: O << "ord"; break;
464   }
465 }
466
467 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
468                                             const char *Modifier) {
469   const MachineOperand &BaseReg  = MI->getOperand(Op);
470   const MachineOperand &IndexReg = MI->getOperand(Op+2);
471   const MachineOperand &DispSpec = MI->getOperand(Op+3);
472
473   // If we really don't want to print out (rip), don't.
474   bool HasBaseReg = BaseReg.getReg() != 0;
475   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
476       BaseReg.getReg() == X86::RIP)
477     HasBaseReg = false;
478   
479   // HasParenPart - True if we will print out the () part of the mem ref.
480   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
481   
482   if (DispSpec.isImm()) {
483     int DispVal = DispSpec.getImm();
484     if (DispVal || !HasParenPart)
485       O << DispVal;
486   } else {
487     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
488            DispSpec.isJTI() || DispSpec.isSymbol());
489     printSymbolOperand(MI->getOperand(Op+3));
490   }
491
492   if (HasParenPart) {
493     assert(IndexReg.getReg() != X86::ESP &&
494            "X86 doesn't allow scaling by ESP");
495
496     O << '(';
497     if (HasBaseReg)
498       printOperand(MI, Op, Modifier);
499
500     if (IndexReg.getReg()) {
501       O << ',';
502       printOperand(MI, Op+2, Modifier);
503       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
504       if (ScaleVal != 1)
505         O << ',' << ScaleVal;
506     }
507     O << ')';
508   }
509 }
510
511 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
512                                          const char *Modifier) {
513   assert(isMem(MI, Op) && "Invalid memory reference!");
514   const MachineOperand &Segment = MI->getOperand(Op+4);
515   if (Segment.getReg()) {
516     printOperand(MI, Op+4, Modifier);
517     O << ':';
518   }
519   printLeaMemReference(MI, Op, Modifier);
520 }
521
522 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
523                                            const MachineBasicBlock *MBB) const {
524   if (!TAI->getSetDirective())
525     return;
526
527   // We don't need .set machinery if we have GOT-style relocations
528   if (Subtarget->isPICStyleGOT())
529     return;
530
531   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
532     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
533   printBasicBlockLabel(MBB, false, false, false);
534   if (Subtarget->isPICStyleRIPRel())
535     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
536       << '_' << uid << '\n';
537   else {
538     O << '-';
539     PrintPICBaseSymbol();
540     O << '\n';
541   }
542 }
543
544
545 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
546   PrintPICBaseSymbol();
547   O << '\n';
548   PrintPICBaseSymbol();
549   O << ':';
550 }
551
552
553 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
554                                               const MachineBasicBlock *MBB,
555                                               unsigned uid) const {
556   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
557     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
558
559   O << JTEntryDirective << ' ';
560
561   if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
562     O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
563       << '_' << uid << "_set_" << MBB->getNumber();
564   } else if (Subtarget->isPICStyleGOT()) {
565     printBasicBlockLabel(MBB, false, false, false);
566     O << "@GOTOFF";
567   } else
568     printBasicBlockLabel(MBB, false, false, false);
569 }
570
571 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
572   unsigned Reg = MO.getReg();
573   switch (Mode) {
574   default: return true;  // Unknown mode.
575   case 'b': // Print QImode register
576     Reg = getX86SubSuperRegister(Reg, MVT::i8);
577     break;
578   case 'h': // Print QImode high register
579     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
580     break;
581   case 'w': // Print HImode register
582     Reg = getX86SubSuperRegister(Reg, MVT::i16);
583     break;
584   case 'k': // Print SImode register
585     Reg = getX86SubSuperRegister(Reg, MVT::i32);
586     break;
587   case 'q': // Print DImode register
588     Reg = getX86SubSuperRegister(Reg, MVT::i64);
589     break;
590   }
591
592   O << '%'<< TRI->getAsmName(Reg);
593   return false;
594 }
595
596 /// PrintAsmOperand - Print out an operand for an inline asm expression.
597 ///
598 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
599                                        unsigned AsmVariant,
600                                        const char *ExtraCode) {
601   // Does this asm operand have a single letter operand modifier?
602   if (ExtraCode && ExtraCode[0]) {
603     if (ExtraCode[1] != 0) return true; // Unknown modifier.
604
605     const MachineOperand &MO = MI->getOperand(OpNo);
606     
607     switch (ExtraCode[0]) {
608     default: return true;  // Unknown modifier.
609     case 'c': // Don't print "$" before a global var name or constant.
610       if (MO.isImm())
611         O << MO.getImm();
612       else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
613         printSymbolOperand(MO);
614       else
615         printOperand(MI, OpNo);
616       return false;
617
618     case 'A': // Print '*' before a register (it must be a register)
619       if (MO.isReg()) {
620         O << '*';
621         printOperand(MI, OpNo);
622         return false;
623       }
624       return true;
625
626     case 'b': // Print QImode register
627     case 'h': // Print QImode high register
628     case 'w': // Print HImode register
629     case 'k': // Print SImode register
630     case 'q': // Print DImode register
631       if (MO.isReg())
632         return printAsmMRegister(MO, ExtraCode[0]);
633       printOperand(MI, OpNo);
634       return false;
635
636     case 'P': // This is the operand of a call, treat specially.
637       print_pcrel_imm(MI, OpNo);
638       return false;
639
640     case 'n':  // Negate the immediate or print a '-' before the operand.
641       // Note: this is a temporary solution. It should be handled target
642       // independently as part of the 'MC' work.
643       if (MO.isImm()) {
644         O << -MO.getImm();
645         return false;
646       }
647       O << '-';
648     }
649   }
650
651   printOperand(MI, OpNo);
652   return false;
653 }
654
655 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
656                                              unsigned OpNo,
657                                              unsigned AsmVariant,
658                                              const char *ExtraCode) {
659   if (ExtraCode && ExtraCode[0]) {
660     if (ExtraCode[1] != 0) return true; // Unknown modifier.
661
662     switch (ExtraCode[0]) {
663     default: return true;  // Unknown modifier.
664     case 'b': // Print QImode register
665     case 'h': // Print QImode high register
666     case 'w': // Print HImode register
667     case 'k': // Print SImode register
668     case 'q': // Print SImode register
669       // These only apply to registers, ignore on mem.
670       break;
671     case 'P': // Don't print @PLT, but do print as memory.
672       printMemReference(MI, OpNo, "no-rip");
673       return false;
674     }
675   }
676   printMemReference(MI, OpNo);
677   return false;
678 }
679
680 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
681   // Convert registers in the addr mode according to subreg64.
682   for (unsigned i = 0; i != 4; ++i) {
683     if (!MI->getOperand(i).isReg()) continue;
684     
685     unsigned Reg = MI->getOperand(i).getReg();
686     if (Reg == 0) continue;
687     
688     MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
689   }
690 }
691
692 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
693 /// AT&T syntax to the current output stream.
694 ///
695 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
696   ++EmittedInsts;
697
698   if (NewAsmPrinter) {
699     if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
700       O << "\t";
701       printInlineAsm(MI);
702       return;
703     } else if (MI->isLabel()) {
704       printLabel(MI);
705       return;
706     } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
707       printDeclare(MI);
708       return;
709     } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
710       printImplicitDef(MI);
711       return;
712     }
713     
714     O << "NEW: ";
715     MCInst TmpInst;
716     
717     TmpInst.setOpcode(MI->getOpcode());
718     
719     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
720       const MachineOperand &MO = MI->getOperand(i);
721       
722       MCOperand MCOp;
723       if (MO.isReg()) {
724         MCOp = MCOperand::CreateReg(MO.getReg());
725       } else if (MO.isImm()) {
726         MCOp = MCOperand::CreateImm(MO.getImm());
727       } else if (MO.isMBB()) {
728         MCOp = MCOperand::CreateMBBLabel(getFunctionNumber(), 
729                                          MO.getMBB()->getNumber());
730       } else {
731         llvm_unreachable("Unimp");
732       }
733       
734       TmpInst.addOperand(MCOp);
735     }
736     
737     switch (TmpInst.getOpcode()) {
738     case X86::LEA64_32r:
739       // Handle the 'subreg rewriting' for the lea64_32mem operand.
740       lower_lea64_32mem(&TmpInst, 1);
741       break;
742     }
743     
744     // FIXME: Convert TmpInst.
745     printInstruction(&TmpInst);
746     O << "OLD: ";
747   }
748   
749   // Call the autogenerated instruction printer routines.
750   printInstruction(MI);
751 }
752
753 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
754   const TargetData *TD = TM.getTargetData();
755
756   if (!GVar->hasInitializer())
757     return;   // External global require no code
758
759   // Check to see if this is a special global used by LLVM, if so, emit it.
760   if (EmitSpecialLLVMGlobal(GVar)) {
761     if (Subtarget->isTargetDarwin() &&
762         TM.getRelocationModel() == Reloc::Static) {
763       if (GVar->getName() == "llvm.global_ctors")
764         O << ".reference .constructors_used\n";
765       else if (GVar->getName() == "llvm.global_dtors")
766         O << ".reference .destructors_used\n";
767     }
768     return;
769   }
770
771   std::string name = Mang->getMangledName(GVar);
772   Constant *C = GVar->getInitializer();
773   const Type *Type = C->getType();
774   unsigned Size = TD->getTypeAllocSize(Type);
775   unsigned Align = TD->getPreferredAlignmentLog(GVar);
776
777   printVisibility(name, GVar->getVisibility());
778
779   if (Subtarget->isTargetELF())
780     O << "\t.type\t" << name << ",@object\n";
781
782   
783   SectionKind GVKind = TargetLoweringObjectFile::getKindForGlobal(GVar, TM);
784   
785   
786   
787   const MCSection *TheSection =
788     getObjFileLowering().SectionForGlobal(GVar, GVKind, Mang, TM);
789   SwitchToSection(TheSection);
790
791   // FIXME: get this stuff from section kind flags.
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     // All darwin targets use mach-o.
903     TargetLoweringObjectFileMachO &TLOFMacho = 
904       static_cast<TargetLoweringObjectFileMachO &>(getObjFileLowering());
905     
906     // Add the (possibly multiple) personalities to the set of global value
907     // stubs.  Only referenced functions get into the Personalities list.
908     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
909       const std::vector<Function*> &Personalities = MMI->getPersonalities();
910       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
911         if (Personalities[i])
912           GVStubs[Mang->getMangledName(Personalities[i], "$non_lazy_ptr",
913                                        true /*private label*/)] = 
914             Mang->getMangledName(Personalities[i]);
915       }
916     }
917
918     // Output stubs for dynamically-linked functions
919     if (!FnStubs.empty()) {
920       const MCSection *TheSection = 
921         TLOFMacho.getMachOSection("__IMPORT", "__jump_table",
922                                   MCSectionMachO::S_SYMBOL_STUBS |
923                                   MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
924                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
925                                   5, SectionKind::getMetadata());
926       SwitchToSection(TheSection);
927       for (StringMap<std::string>::iterator I = FnStubs.begin(),
928            E = FnStubs.end(); I != E; ++I)
929         O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
930           << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
931       O << '\n';
932     }
933
934     // Output stubs for external and common global variables.
935     if (!GVStubs.empty()) {
936       const MCSection *TheSection = 
937         TLOFMacho.getMachOSection("__IMPORT", "__pointers",
938                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
939                                   SectionKind::getMetadata());
940       SwitchToSection(TheSection);
941       for (StringMap<std::string>::iterator I = GVStubs.begin(),
942            E = GVStubs.end(); I != E; ++I)
943         O << I->getKeyData() << ":\n\t.indirect_symbol "
944           << I->second << "\n\t.long\t0\n";
945     }
946
947     if (!HiddenGVStubs.empty()) {
948       SwitchToSection(getObjFileLowering().getDataSection());
949       EmitAlignment(2);
950       for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
951            E = HiddenGVStubs.end(); I != E; ++I)
952         O << I->getKeyData() << ":\n" << TAI->getData32bitsDirective()
953           << I->second << '\n';
954     }
955
956     // Funny Darwin hack: This flag tells the linker that no global symbols
957     // contain code that falls through to other global symbols (e.g. the obvious
958     // implementation of multiple entry points).  If this doesn't occur, the
959     // linker can safely perform dead code stripping.  Since LLVM never
960     // generates code that does this, it is always safe to set.
961     O << "\t.subsections_via_symbols\n";
962   } else if (Subtarget->isTargetCygMing()) {
963     // Emit type information for external functions
964     for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
965          i != e; ++i) {
966       O << "\t.def\t " << i->getKeyData()
967         << ";\t.scl\t" << COFF::C_EXT
968         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
969         << ";\t.endef\n";
970     }
971   }
972   
973   
974   // Output linker support code for dllexported globals on windows.
975   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
976     // dllexport symbols only exist on coff targets.
977     TargetLoweringObjectFileCOFF &TLOFMacho = 
978       static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
979     
980     SwitchToSection(TLOFMacho.getCOFFSection(".section .drectve", true,
981                                              SectionKind::getMetadata()));
982   
983     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
984          e = DLLExportedGVs.end(); i != e; ++i)
985       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
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   return AsmPrinter::doFinalization(M);
995 }
996
997 // Include the auto-generated portion of the assembly writer.
998 #include "X86GenAsmWriter.inc"