make MergeableCString be a SectionKind "abstract class", and
[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   EmitAlignment(FnAlign, F);
173
174   switch (F->getLinkage()) {
175   default: llvm_unreachable("Unknown linkage type!");
176   case Function::InternalLinkage:  // Symbols default to internal.
177   case Function::PrivateLinkage:
178   case Function::LinkerPrivateLinkage:
179     break;
180   case Function::DLLExportLinkage:
181   case Function::ExternalLinkage:
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     if (Subtarget->isTargetDarwin()) {
189       O << "\t.globl\t" << CurrentFnName << '\n';
190       O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
191     } else if (Subtarget->isTargetCygMing()) {
192       O << "\t.globl\t" << CurrentFnName << "\n"
193            "\t.linkonce discard\n";
194     } else {
195       O << "\t.weak\t" << CurrentFnName << '\n';
196     }
197     break;
198   }
199
200   printVisibility(CurrentFnName, F->getVisibility());
201
202   if (Subtarget->isTargetELF())
203     O << "\t.type\t" << CurrentFnName << ",@function\n";
204   else if (Subtarget->isTargetCygMing()) {
205     O << "\t.def\t " << CurrentFnName
206       << ";\t.scl\t" <<
207       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
208       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
209       << ";\t.endef\n";
210   }
211
212   O << CurrentFnName << ":\n";
213   // Add some workaround for linkonce linkage on Cygwin\MinGW
214   if (Subtarget->isTargetCygMing() &&
215       (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
216     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
217 }
218
219 /// runOnMachineFunction - This uses the printMachineInstruction()
220 /// method to print assembly for each instruction.
221 ///
222 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
223   const Function *F = MF.getFunction();
224   this->MF = &MF;
225   unsigned CC = F->getCallingConv();
226
227   SetupMachineFunction(MF);
228   O << "\n\n";
229
230   // Populate function information map.  Actually, We don't want to populate
231   // non-stdcall or non-fastcall functions' information right now.
232   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
233     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
234
235   // Print out constants referenced by the function
236   EmitConstantPool(MF.getConstantPool());
237
238   if (F->hasDLLExportLinkage())
239     DLLExportedFns.insert(Mang->getMangledName(F));
240
241   // Print the 'header' of function
242   emitFunctionHeader(MF);
243
244   // Emit pre-function debug and/or EH information.
245   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
246     DW->BeginFunction(&MF);
247
248   // Print out code for the function.
249   bool hasAnyRealCode = false;
250   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
251        I != E; ++I) {
252     // Print a label for the basic block.
253     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
254       // This is an entry block or a block that's only reachable via a
255       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
256     } else {
257       printBasicBlockLabel(I, true, true, VerboseAsm);
258       O << '\n';
259     }
260     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
261          II != IE; ++II) {
262       // Print the assembly for the instruction.
263       if (!II->isLabel())
264         hasAnyRealCode = true;
265       printMachineInstruction(II);
266     }
267   }
268
269   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
270     // If the function is empty, then we need to emit *something*. Otherwise,
271     // the function's label might be associated with something that it wasn't
272     // meant to be associated with. We emit a noop in this situation.
273     // We are assuming inline asms are code.
274     O << "\tnop\n";
275   }
276
277   if (TAI->hasDotTypeDotSizeDirective())
278     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
279
280   // Emit post-function debug information.
281   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
282     DW->EndFunction(&MF);
283
284   // Print out jump tables referenced by the function.
285   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
286
287   O.flush();
288
289   // We didn't modify anything.
290   return false;
291 }
292
293 /// printSymbolOperand - Print a raw symbol reference operand.  This handles
294 /// jump tables, constant pools, global address and external symbols, all of
295 /// which print to a label with various suffixes for relocation types etc.
296 void X86ATTAsmPrinter::printSymbolOperand(const MachineOperand &MO) {
297   switch (MO.getType()) {
298   default: llvm_unreachable("unknown symbol type!");
299   case MachineOperand::MO_JumpTableIndex:
300     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
301       << MO.getIndex();
302     break;
303   case MachineOperand::MO_ConstantPoolIndex:
304     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
305       << MO.getIndex();
306     printOffset(MO.getOffset());
307     break;
308   case MachineOperand::MO_GlobalAddress: {
309     const GlobalValue *GV = MO.getGlobal();
310     
311     const char *Suffix = "";
312     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
313       Suffix = "$stub";
314     else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
315              MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
316              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
317              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
318       Suffix = "$non_lazy_ptr";
319     
320     std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
321     if (Subtarget->isTargetCygMing())
322       DecorateCygMingName(Name, GV);
323     
324     // Handle dllimport linkage.
325     if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
326       Name = "__imp_" + Name;
327     
328     if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
329         MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE)
330       GVStubs[Name] = Mang->getMangledName(GV);
331     else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY ||
332              MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
333       HiddenGVStubs[Name] = Mang->getMangledName(GV);
334     else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
335       FnStubs[Name] = Mang->getMangledName(GV);
336     
337     // If the name begins with a dollar-sign, enclose it in parens.  We do this
338     // to avoid having it look like an integer immediate to the assembler.
339     if (Name[0] == '$') 
340       O << '(' << Name << ')';
341     else
342       O << Name;
343     
344     printOffset(MO.getOffset());
345     break;
346   }
347   case MachineOperand::MO_ExternalSymbol: {
348     std::string Name = Mang->makeNameProper(MO.getSymbolName());
349     if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
350       FnStubs[Name+"$stub"] = Name;
351       Name += "$stub";
352     }
353     
354     // If the name begins with a dollar-sign, enclose it in parens.  We do this
355     // to avoid having it look like an integer immediate to the assembler.
356     if (Name[0] == '$') 
357       O << '(' << Name << ')';
358     else
359       O << Name;
360     break;
361   }
362   }
363   
364   switch (MO.getTargetFlags()) {
365   default:
366     llvm_unreachable("Unknown target flag on GV operand");
367   case X86II::MO_NO_FLAG:    // No flag.
368     break;
369   case X86II::MO_DARWIN_NONLAZY:
370   case X86II::MO_DARWIN_HIDDEN_NONLAZY:
371   case X86II::MO_DLLIMPORT:
372   case X86II::MO_DARWIN_STUB:
373     // These affect the name of the symbol, not any suffix.
374     break;
375   case X86II::MO_GOT_ABSOLUTE_ADDRESS:
376     O << " + [.-";
377     PrintPICBaseSymbol();
378     O << ']';
379     break;      
380   case X86II::MO_PIC_BASE_OFFSET:
381   case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
382   case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
383     O << '-';
384     PrintPICBaseSymbol();
385     break;
386   case X86II::MO_TLSGD:     O << "@TLSGD";     break;
387   case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
388   case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
389   case X86II::MO_TPOFF:     O << "@TPOFF";     break;
390   case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
391   case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
392   case X86II::MO_GOT:       O << "@GOT";       break;
393   case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
394   case X86II::MO_PLT:       O << "@PLT";       break;
395   }
396 }
397
398 /// print_pcrel_imm - This is used to print an immediate value that ends up
399 /// being encoded as a pc-relative value.  These print slightly differently, for
400 /// example, a $ is not emitted.
401 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
402   const MachineOperand &MO = MI->getOperand(OpNo);
403   switch (MO.getType()) {
404   default: llvm_unreachable("Unknown pcrel immediate operand");
405   case MachineOperand::MO_Immediate:
406     O << MO.getImm();
407     return;
408   case MachineOperand::MO_MachineBasicBlock:
409     printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
410     return;
411   case MachineOperand::MO_GlobalAddress:
412   case MachineOperand::MO_ExternalSymbol:
413     printSymbolOperand(MO);
414     return;
415   }
416 }
417
418
419
420 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
421                                     const char *Modifier) {
422   const MachineOperand &MO = MI->getOperand(OpNo);
423   switch (MO.getType()) {
424   default: llvm_unreachable("unknown operand type!");
425   case MachineOperand::MO_Register: {
426     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
427            "Virtual registers should not make it this far!");
428     O << '%';
429     unsigned Reg = MO.getReg();
430     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
431       MVT VT = (strcmp(Modifier+6,"64") == 0) ?
432         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
433                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
434       Reg = getX86SubSuperRegister(Reg, VT);
435     }
436     O << TRI->getAsmName(Reg);
437     return;
438   }
439
440   case MachineOperand::MO_Immediate:
441     O << '$' << MO.getImm();
442     return;
443
444   case MachineOperand::MO_JumpTableIndex:
445   case MachineOperand::MO_ConstantPoolIndex:
446   case MachineOperand::MO_GlobalAddress: 
447   case MachineOperand::MO_ExternalSymbol: {
448     O << '$';
449     printSymbolOperand(MO);
450     break;
451   }
452   }
453 }
454
455 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
456   unsigned char value = MI->getOperand(Op).getImm();
457   assert(value <= 7 && "Invalid ssecc argument!");
458   switch (value) {
459   case 0: O << "eq"; break;
460   case 1: O << "lt"; break;
461   case 2: O << "le"; break;
462   case 3: O << "unord"; break;
463   case 4: O << "neq"; break;
464   case 5: O << "nlt"; break;
465   case 6: O << "nle"; break;
466   case 7: O << "ord"; break;
467   }
468 }
469
470 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
471                                             const char *Modifier) {
472   const MachineOperand &BaseReg  = MI->getOperand(Op);
473   const MachineOperand &IndexReg = MI->getOperand(Op+2);
474   const MachineOperand &DispSpec = MI->getOperand(Op+3);
475
476   // If we really don't want to print out (rip), don't.
477   bool HasBaseReg = BaseReg.getReg() != 0;
478   if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
479       BaseReg.getReg() == X86::RIP)
480     HasBaseReg = false;
481   
482   // HasParenPart - True if we will print out the () part of the mem ref.
483   bool HasParenPart = IndexReg.getReg() || HasBaseReg;
484   
485   if (DispSpec.isImm()) {
486     int DispVal = DispSpec.getImm();
487     if (DispVal || !HasParenPart)
488       O << DispVal;
489   } else {
490     assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
491            DispSpec.isJTI() || DispSpec.isSymbol());
492     printSymbolOperand(MI->getOperand(Op+3));
493   }
494
495   if (HasParenPart) {
496     assert(IndexReg.getReg() != X86::ESP &&
497            "X86 doesn't allow scaling by ESP");
498
499     O << '(';
500     if (HasBaseReg)
501       printOperand(MI, Op, Modifier);
502
503     if (IndexReg.getReg()) {
504       O << ',';
505       printOperand(MI, Op+2, Modifier);
506       unsigned ScaleVal = MI->getOperand(Op+1).getImm();
507       if (ScaleVal != 1)
508         O << ',' << ScaleVal;
509     }
510     O << ')';
511   }
512 }
513
514 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
515                                          const char *Modifier) {
516   assert(isMem(MI, Op) && "Invalid memory reference!");
517   const MachineOperand &Segment = MI->getOperand(Op+4);
518   if (Segment.getReg()) {
519     printOperand(MI, Op+4, Modifier);
520     O << ':';
521   }
522   printLeaMemReference(MI, Op, Modifier);
523 }
524
525 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
526                                            const MachineBasicBlock *MBB) const {
527   if (!TAI->getSetDirective())
528     return;
529
530   // We don't need .set machinery if we have GOT-style relocations
531   if (Subtarget->isPICStyleGOT())
532     return;
533
534   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
535     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
536   printBasicBlockLabel(MBB, false, false, false);
537   if (Subtarget->isPICStyleRIPRel())
538     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
539       << '_' << uid << '\n';
540   else {
541     O << '-';
542     PrintPICBaseSymbol();
543     O << '\n';
544   }
545 }
546
547
548 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
549   PrintPICBaseSymbol();
550   O << '\n';
551   PrintPICBaseSymbol();
552   O << ':';
553 }
554
555
556 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
557                                               const MachineBasicBlock *MBB,
558                                               unsigned uid) const {
559   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
560     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
561
562   O << JTEntryDirective << ' ';
563
564   if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStubPIC()) {
565     O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
566       << '_' << uid << "_set_" << MBB->getNumber();
567   } else if (Subtarget->isPICStyleGOT()) {
568     printBasicBlockLabel(MBB, false, false, false);
569     O << "@GOTOFF";
570   } else
571     printBasicBlockLabel(MBB, false, false, false);
572 }
573
574 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
575   unsigned Reg = MO.getReg();
576   switch (Mode) {
577   default: return true;  // Unknown mode.
578   case 'b': // Print QImode register
579     Reg = getX86SubSuperRegister(Reg, MVT::i8);
580     break;
581   case 'h': // Print QImode high register
582     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
583     break;
584   case 'w': // Print HImode register
585     Reg = getX86SubSuperRegister(Reg, MVT::i16);
586     break;
587   case 'k': // Print SImode register
588     Reg = getX86SubSuperRegister(Reg, MVT::i32);
589     break;
590   case 'q': // Print DImode register
591     Reg = getX86SubSuperRegister(Reg, MVT::i64);
592     break;
593   }
594
595   O << '%'<< TRI->getAsmName(Reg);
596   return false;
597 }
598
599 /// PrintAsmOperand - Print out an operand for an inline asm expression.
600 ///
601 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
602                                        unsigned AsmVariant,
603                                        const char *ExtraCode) {
604   // Does this asm operand have a single letter operand modifier?
605   if (ExtraCode && ExtraCode[0]) {
606     if (ExtraCode[1] != 0) return true; // Unknown modifier.
607
608     const MachineOperand &MO = MI->getOperand(OpNo);
609     
610     switch (ExtraCode[0]) {
611     default: return true;  // Unknown modifier.
612     case 'c': // Don't print "$" before a global var name or constant.
613       if (MO.isImm())
614         O << MO.getImm();
615       else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
616         printSymbolOperand(MO);
617       else
618         printOperand(MI, OpNo);
619       return false;
620
621     case 'A': // Print '*' before a register (it must be a register)
622       if (MO.isReg()) {
623         O << '*';
624         printOperand(MI, OpNo);
625         return false;
626       }
627       return true;
628
629     case 'b': // Print QImode register
630     case 'h': // Print QImode high register
631     case 'w': // Print HImode register
632     case 'k': // Print SImode register
633     case 'q': // Print DImode register
634       if (MO.isReg())
635         return printAsmMRegister(MO, ExtraCode[0]);
636       printOperand(MI, OpNo);
637       return false;
638
639     case 'P': // This is the operand of a call, treat specially.
640       print_pcrel_imm(MI, OpNo);
641       return false;
642
643     case 'n':  // Negate the immediate or print a '-' before the operand.
644       // Note: this is a temporary solution. It should be handled target
645       // independently as part of the 'MC' work.
646       if (MO.isImm()) {
647         O << -MO.getImm();
648         return false;
649       }
650       O << '-';
651     }
652   }
653
654   printOperand(MI, OpNo);
655   return false;
656 }
657
658 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
659                                              unsigned OpNo,
660                                              unsigned AsmVariant,
661                                              const char *ExtraCode) {
662   if (ExtraCode && ExtraCode[0]) {
663     if (ExtraCode[1] != 0) return true; // Unknown modifier.
664
665     switch (ExtraCode[0]) {
666     default: return true;  // Unknown modifier.
667     case 'b': // Print QImode register
668     case 'h': // Print QImode high register
669     case 'w': // Print HImode register
670     case 'k': // Print SImode register
671     case 'q': // Print SImode register
672       // These only apply to registers, ignore on mem.
673       break;
674     case 'P': // Don't print @PLT, but do print as memory.
675       printMemReference(MI, OpNo, "no-rip");
676       return false;
677     }
678   }
679   printMemReference(MI, OpNo);
680   return false;
681 }
682
683 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
684   // Convert registers in the addr mode according to subreg64.
685   for (unsigned i = 0; i != 4; ++i) {
686     if (!MI->getOperand(i).isReg()) continue;
687     
688     unsigned Reg = MI->getOperand(i).getReg();
689     if (Reg == 0) continue;
690     
691     MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
692   }
693 }
694
695 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
696 /// AT&T syntax to the current output stream.
697 ///
698 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
699   ++EmittedInsts;
700
701   if (NewAsmPrinter) {
702     if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
703       O << "\t";
704       printInlineAsm(MI);
705       return;
706     } else if (MI->isLabel()) {
707       printLabel(MI);
708       return;
709     } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
710       printDeclare(MI);
711       return;
712     } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
713       printImplicitDef(MI);
714       return;
715     }
716     
717     O << "NEW: ";
718     MCInst TmpInst;
719     
720     TmpInst.setOpcode(MI->getOpcode());
721     
722     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
723       const MachineOperand &MO = MI->getOperand(i);
724       
725       MCOperand MCOp;
726       if (MO.isReg()) {
727         MCOp = MCOperand::CreateReg(MO.getReg());
728       } else if (MO.isImm()) {
729         MCOp = MCOperand::CreateImm(MO.getImm());
730       } else if (MO.isMBB()) {
731         MCOp = MCOperand::CreateMBBLabel(getFunctionNumber(), 
732                                          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 void X86ATTAsmPrinter::PrintGlobalVariable(const GlobalVariable* GVar) {
757   const TargetData *TD = TM.getTargetData();
758
759   if (!GVar->hasInitializer())
760     return;   // External global require no code
761
762   // Check to see if this is a special global used by LLVM, if so, emit it.
763   if (EmitSpecialLLVMGlobal(GVar)) {
764     if (Subtarget->isTargetDarwin() &&
765         TM.getRelocationModel() == Reloc::Static) {
766       if (GVar->getName() == "llvm.global_ctors")
767         O << ".reference .constructors_used\n";
768       else if (GVar->getName() == "llvm.global_dtors")
769         O << ".reference .destructors_used\n";
770     }
771     return;
772   }
773
774   std::string name = Mang->getMangledName(GVar);
775   Constant *C = GVar->getInitializer();
776   if (isa<MDNode>(C) || isa<MDString>(C))
777     return;
778   const Type *Type = C->getType();
779   unsigned Size = TD->getTypeAllocSize(Type);
780   unsigned Align = TD->getPreferredAlignmentLog(GVar);
781
782   printVisibility(name, GVar->getVisibility());
783
784   if (Subtarget->isTargetELF())
785     O << "\t.type\t" << name << ",@object\n";
786
787   const MCSection *TheSection =
788     getObjFileLowering().SectionForGlobal(GVar, 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("\t.section __IMPORT,__jump_table,symbol_stubs,"
922                                 "self_modifying_code+pure_instructions,5", true,
923                                 SectionKind::getMetadata());
924       SwitchToSection(TheSection);
925       for (StringMap<std::string>::iterator I = FnStubs.begin(),
926            E = FnStubs.end(); I != E; ++I)
927         O << I->getKeyData() << ":\n" << "\t.indirect_symbol " << I->second
928           << "\n\thlt ; hlt ; hlt ; hlt ; hlt\n";
929       O << '\n';
930     }
931
932     // Output stubs for external and common global variables.
933     if (!GVStubs.empty()) {
934       const MCSection *TheSection = 
935         TLOFMacho.getMachOSection("\t.section __IMPORT,__pointers,"
936                                   "non_lazy_symbol_pointers", true,
937                                   SectionKind::getMetadata());
938       SwitchToSection(TheSection);
939       for (StringMap<std::string>::iterator I = GVStubs.begin(),
940            E = GVStubs.end(); I != E; ++I)
941         O << I->getKeyData() << ":\n\t.indirect_symbol "
942           << I->second << "\n\t.long\t0\n";
943     }
944
945     if (!HiddenGVStubs.empty()) {
946       SwitchToSection(getObjFileLowering().getDataSection());
947       EmitAlignment(2);
948       for (StringMap<std::string>::iterator I = HiddenGVStubs.begin(),
949            E = HiddenGVStubs.end(); I != E; ++I)
950         O << I->getKeyData() << ":\n" << TAI->getData32bitsDirective()
951           << I->second << '\n';
952     }
953
954     // Funny Darwin hack: This flag tells the linker that no global symbols
955     // contain code that falls through to other global symbols (e.g. the obvious
956     // implementation of multiple entry points).  If this doesn't occur, the
957     // linker can safely perform dead code stripping.  Since LLVM never
958     // generates code that does this, it is always safe to set.
959     O << "\t.subsections_via_symbols\n";
960   } else if (Subtarget->isTargetCygMing()) {
961     // Emit type information for external functions
962     for (StringSet<>::iterator i = CygMingStubs.begin(), e = CygMingStubs.end();
963          i != e; ++i) {
964       O << "\t.def\t " << i->getKeyData()
965         << ";\t.scl\t" << COFF::C_EXT
966         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
967         << ";\t.endef\n";
968     }
969   }
970   
971   
972   // Output linker support code for dllexported globals on windows.
973   if (!DLLExportedGVs.empty() || !DLLExportedFns.empty()) {
974     // dllexport symbols only exist on coff targets.
975     TargetLoweringObjectFileCOFF &TLOFMacho = 
976       static_cast<TargetLoweringObjectFileCOFF&>(getObjFileLowering());
977     
978     SwitchToSection(TLOFMacho.getCOFFSection(".section .drectve", true,
979                                              SectionKind::getMetadata()));
980   
981     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
982          e = DLLExportedGVs.end(); i != e; ++i)
983       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
984   
985     for (StringSet<>::iterator i = DLLExportedFns.begin(),
986          e = DLLExportedFns.end();
987          i != e; ++i)
988       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
989   }
990   
991   // Do common shutdown.
992   return AsmPrinter::doFinalization(M);
993 }
994
995 // Include the auto-generated portion of the assembly writer.
996 #include "X86GenAsmWriter.inc"