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