sink dwarf finalization out of each target into AsmPrinter::doFinalization
[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/MCStreamer.h"
32 #include "llvm/CodeGen/DwarfWriter.h"
33 #include "llvm/CodeGen/MachineJumpTableInfo.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Mangler.h"
36 #include "llvm/Support/raw_ostream.h"
37 #include "llvm/Target/TargetAsmInfo.h"
38 #include "llvm/Target/TargetOptions.h"
39 using namespace llvm;
40
41 STATISTIC(EmittedInsts, "Number of machine instrs printed");
42
43 static cl::opt<bool> NewAsmPrinter("experimental-asm-printer",
44                                    cl::Hidden);
45
46 static std::string getPICLabelString(unsigned FnNum,
47                                      const TargetAsmInfo *TAI,
48                                      const X86Subtarget* Subtarget) {
49   std::string label;
50   if (Subtarget->isTargetDarwin())
51     label =  "\"L" + utostr_32(FnNum) + "$pb\"";
52   else if (Subtarget->isTargetELF())
53     label = ".Lllvm$" + utostr_32(FnNum) + "." "$piclabel";
54   else
55     assert(0 && "Don't know how to print PIC label!\n");
56
57   return label;
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 /// PrintUnmangledNameSafely - Print out the printable characters in the name.
95 /// Don't print things like \\n or \\0.
96 static void PrintUnmangledNameSafely(const Value *V, raw_ostream &OS) {
97   for (const char *Name = V->getNameStart(), *E = Name+V->getNameLen();
98        Name != E; ++Name)
99     if (isprint(*Name))
100       OS << *Name;
101 }
102
103 /// decorateName - Query FunctionInfoMap and use this information for various
104 /// name decoration.
105 void X86ATTAsmPrinter::decorateName(std::string &Name,
106                                     const GlobalValue *GV) {
107   const Function *F = dyn_cast<Function>(GV);
108   if (!F) return;
109
110   // We don't want to decorate non-stdcall or non-fastcall functions right now
111   unsigned CC = F->getCallingConv();
112   if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
113     return;
114
115   // Decorate names only when we're targeting Cygwin/Mingw32 targets
116   if (!Subtarget->isTargetCygMing())
117     return;
118
119   FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
120
121   const X86MachineFunctionInfo *Info;
122   if (info_item == FunctionInfoMap.end()) {
123     // Calculate apropriate function info and populate map
124     FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
125     Info = &FunctionInfoMap[F];
126   } else {
127     Info = &info_item->second;
128   }
129
130   const FunctionType *FT = F->getFunctionType();
131   switch (Info->getDecorationStyle()) {
132   case None:
133     break;
134   case StdCall:
135     // "Pure" variadic functions do not receive @0 suffix.
136     if (!FT->isVarArg() || (FT->getNumParams() == 0) ||
137         (FT->getNumParams() == 1 && F->hasStructRetAttr()))
138       Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
139     break;
140   case FastCall:
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
146     if (Name[0] == '_') {
147       Name[0] = '@';
148     } else {
149       Name = '@' + Name;
150     }
151     break;
152   default:
153     assert(0 && "Unsupported DecorationStyle");
154   }
155 }
156
157 void X86ATTAsmPrinter::emitFunctionHeader(const MachineFunction &MF) {
158   const Function *F = MF.getFunction();
159
160   decorateName(CurrentFnName, F);
161
162   SwitchToSection(TAI->SectionForGlobal(F));
163
164   unsigned FnAlign = 4;
165   if (F->hasFnAttr(Attribute::OptimizeForSize))
166     FnAlign = 1;
167   switch (F->getLinkage()) {
168   default: assert(0 && "Unknown linkage type!");
169   case Function::InternalLinkage:  // Symbols default to internal.
170   case Function::PrivateLinkage:
171     EmitAlignment(FnAlign, F);
172     break;
173   case Function::DLLExportLinkage:
174   case Function::ExternalLinkage:
175     EmitAlignment(FnAlign, F);
176     O << "\t.globl\t" << CurrentFnName << '\n';
177     break;
178   case Function::LinkOnceAnyLinkage:
179   case Function::LinkOnceODRLinkage:
180   case Function::WeakAnyLinkage:
181   case Function::WeakODRLinkage:
182     EmitAlignment(FnAlign, F);
183     if (Subtarget->isTargetDarwin()) {
184       O << "\t.globl\t" << CurrentFnName << '\n';
185       O << TAI->getWeakDefDirective() << CurrentFnName << '\n';
186     } else if (Subtarget->isTargetCygMing()) {
187       O << "\t.globl\t" << CurrentFnName << "\n"
188            "\t.linkonce discard\n";
189     } else {
190       O << "\t.weak\t" << CurrentFnName << '\n';
191     }
192     break;
193   }
194
195   printVisibility(CurrentFnName, F->getVisibility());
196
197   if (Subtarget->isTargetELF())
198     O << "\t.type\t" << CurrentFnName << ",@function\n";
199   else if (Subtarget->isTargetCygMing()) {
200     O << "\t.def\t " << CurrentFnName
201       << ";\t.scl\t" <<
202       (F->hasInternalLinkage() ? COFF::C_STAT : COFF::C_EXT)
203       << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
204       << ";\t.endef\n";
205   }
206
207   O << CurrentFnName << ":\n";
208   // Add some workaround for linkonce linkage on Cygwin\MinGW
209   if (Subtarget->isTargetCygMing() &&
210       (F->hasLinkOnceLinkage() || F->hasWeakLinkage()))
211     O << "Lllvm$workaround$fake$stub$" << CurrentFnName << ":\n";
212 }
213
214 /// runOnMachineFunction - This uses the printMachineInstruction()
215 /// method to print assembly for each instruction.
216 ///
217 bool X86ATTAsmPrinter::runOnMachineFunction(MachineFunction &MF) {
218   const Function *F = MF.getFunction();
219   this->MF = &MF;
220   unsigned CC = F->getCallingConv();
221
222   SetupMachineFunction(MF);
223   O << "\n\n";
224
225   // Populate function information map.  Actually, We don't want to populate
226   // non-stdcall or non-fastcall functions' information right now.
227   if (CC == CallingConv::X86_StdCall || CC == CallingConv::X86_FastCall)
228     FunctionInfoMap[F] = *MF.getInfo<X86MachineFunctionInfo>();
229
230   // Print out constants referenced by the function
231   EmitConstantPool(MF.getConstantPool());
232
233   if (F->hasDLLExportLinkage())
234     DLLExportedFns.insert(Mang->makeNameProper(F->getName(), ""));
235
236   // Print the 'header' of function
237   emitFunctionHeader(MF);
238
239   // Emit pre-function debug and/or EH information.
240   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
241     DW->BeginFunction(&MF);
242
243   // Print out code for the function.
244   bool hasAnyRealCode = false;
245   for (MachineFunction::const_iterator I = MF.begin(), E = MF.end();
246        I != E; ++I) {
247     // Print a label for the basic block.
248     if (!VerboseAsm && (I->pred_empty() || I->isOnlyReachableByFallthrough())) {
249       // This is an entry block or a block that's only reachable via a
250       // fallthrough edge. In non-VerboseAsm mode, don't print the label.
251     } else {
252       printBasicBlockLabel(I, true, true, VerboseAsm);
253       O << '\n';
254     }
255     for (MachineBasicBlock::const_iterator II = I->begin(), IE = I->end();
256          II != IE; ++II) {
257       // Print the assembly for the instruction.
258       if (!II->isLabel())
259         hasAnyRealCode = true;
260       printMachineInstruction(II);
261     }
262   }
263
264   if (Subtarget->isTargetDarwin() && !hasAnyRealCode) {
265     // If the function is empty, then we need to emit *something*. Otherwise,
266     // the function's label might be associated with something that it wasn't
267     // meant to be associated with. We emit a noop in this situation.
268     // We are assuming inline asms are code.
269     O << "\tnop\n";
270   }
271
272   if (TAI->hasDotTypeDotSizeDirective())
273     O << "\t.size\t" << CurrentFnName << ", .-" << CurrentFnName << '\n';
274
275   // Emit post-function debug information.
276   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
277     DW->EndFunction(&MF);
278
279   // Print out jump tables referenced by the function.
280   EmitJumpTableInfo(MF.getJumpTableInfo(), MF);
281
282   O.flush();
283
284   // We didn't modify anything.
285   return false;
286 }
287
288 static inline bool shouldPrintGOT(TargetMachine &TM, const X86Subtarget* ST) {
289   return ST->isPICStyleGOT() && TM.getRelocationModel() == Reloc::PIC_;
290 }
291
292 static inline bool shouldPrintPLT(TargetMachine &TM, const X86Subtarget* ST) {
293   return ST->isTargetELF() && TM.getRelocationModel() == Reloc::PIC_ &&
294       (ST->isPICStyleRIPRel() || ST->isPICStyleGOT());
295 }
296
297 static inline bool shouldPrintStub(TargetMachine &TM, const X86Subtarget* ST) {
298   return ST->isPICStyleStub() && TM.getRelocationModel() != Reloc::Static;
299 }
300
301 /// print_pcrel_imm - This is used to print an immediate value that ends up
302 /// being encoded as a pc-relative value.  These print slightly differently, for
303 /// example, a $ is not emitted.
304 void X86ATTAsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo) {
305   const MachineOperand &MO = MI->getOperand(OpNo);
306   switch (MO.getType()) {
307   default: assert(0 && "Unknown pcrel immediate operand");
308   case MachineOperand::MO_Immediate:
309     O << MO.getImm();
310     return;
311   case MachineOperand::MO_MachineBasicBlock:
312     printBasicBlockLabel(MO.getMBB(), false, false, VerboseAsm);
313     return;
314       
315   case MachineOperand::MO_GlobalAddress: {
316     const GlobalValue *GV = MO.getGlobal();
317     std::string Name = Mang->getValueName(GV);
318     decorateName(Name, GV);
319     
320     bool needCloseParen = false;
321     if (Name[0] == '$') {
322       // The name begins with a dollar-sign. In order to avoid having it look
323       // like an integer immediate to the assembler, enclose it in parens.
324       O << '(';
325       needCloseParen = true;
326     }
327     
328     if (shouldPrintStub(TM, Subtarget)) {
329       // Link-once, declaration, or Weakly-linked global variables need
330       // non-lazily-resolved stubs
331       if (GV->isDeclaration() || GV->isWeakForLinker()) {
332         // Dynamically-resolved functions need a stub for the function.
333         if (isa<Function>(GV)) {
334           // Function stubs are no longer needed for Mac OS X 10.5 and up.
335           if (Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9) {
336             O << Name;
337           } else {
338             FnStubs.insert(Name);
339             printSuffixedName(Name, "$stub");
340           }
341         } else if (GV->hasHiddenVisibility()) {
342           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
343             // Definition is not definitely in the current translation unit.
344             O << Name;
345           else {
346             HiddenGVStubs.insert(Name);
347             printSuffixedName(Name, "$non_lazy_ptr");
348           }
349         } else {
350           GVStubs.insert(Name);
351           printSuffixedName(Name, "$non_lazy_ptr");
352         }
353       } else {
354         if (GV->hasDLLImportLinkage())
355           O << "__imp_";
356         O << Name;
357       }
358     } else {
359       if (GV->hasDLLImportLinkage()) {
360         O << "__imp_";
361       }
362       O << Name;
363       
364       if (shouldPrintPLT(TM, Subtarget)) {
365         // Assemble call via PLT for externally visible symbols
366         if (!GV->hasHiddenVisibility() && !GV->hasProtectedVisibility() &&
367             !GV->hasLocalLinkage())
368           O << "@PLT";
369       }
370       if (Subtarget->isTargetCygMing() && GV->isDeclaration())
371         // Save function name for later type emission
372         FnStubs.insert(Name);
373     }
374     
375     printOffset(MO.getOffset());
376     
377     if (needCloseParen)
378       O << ')';
379     return;
380   }
381       
382   case MachineOperand::MO_ExternalSymbol: {
383     bool needCloseParen = false;
384     std::string Name(TAI->getGlobalPrefix());
385     Name += MO.getSymbolName();
386     // Print function stub suffix unless it's Mac OS X 10.5 and up.
387     if (shouldPrintStub(TM, Subtarget) && 
388         !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
389       FnStubs.insert(Name);
390       printSuffixedName(Name, "$stub");
391       return;
392     }
393     
394     if (Name[0] == '$') {
395       // The name begins with a dollar-sign. In order to avoid having it look
396       // like an integer immediate to the assembler, enclose it in parens.
397       O << '(';
398       needCloseParen = true;
399     }
400     
401     O << Name;
402     
403     if (shouldPrintPLT(TM, Subtarget)) {
404       std::string GOTName(TAI->getGlobalPrefix());
405       GOTName+="_GLOBAL_OFFSET_TABLE_";
406       if (Name == GOTName)
407         // HACK! Emit extra offset to PC during printing GOT offset to
408         // compensate for the size of popl instruction. The resulting code
409         // should look like:
410         //   call .piclabel
411         // piclabel:
412         //   popl %some_register
413         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
414         O << " + [.-"
415           << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
416       
417       O << "@PLT";
418     }
419     
420     if (needCloseParen)
421       O << ')';
422     
423     return;
424   }
425   }
426 }
427
428 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
429                                     const char *Modifier, bool NotRIPRel) {
430   const MachineOperand &MO = MI->getOperand(OpNo);
431   switch (MO.getType()) {
432   case MachineOperand::MO_Register: {
433     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
434            "Virtual registers should not make it this far!");
435     O << '%';
436     unsigned Reg = MO.getReg();
437     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
438       MVT VT = (strcmp(Modifier+6,"64") == 0) ?
439         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
440                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
441       Reg = getX86SubSuperRegister(Reg, VT);
442     }
443     O << TRI->getAsmName(Reg);
444     return;
445   }
446
447   case MachineOperand::MO_Immediate:
448     if (!Modifier || (strcmp(Modifier, "debug") &&
449                       strcmp(Modifier, "mem")))
450       O << '$';
451     O << MO.getImm();
452     return;
453   case MachineOperand::MO_JumpTableIndex: {
454     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
455     if (!isMemOp) O << '$';
456     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
457       << MO.getIndex();
458
459     if (TM.getRelocationModel() == Reloc::PIC_) {
460       if (Subtarget->isPICStyleStub())
461         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
462           << "$pb\"";
463       else if (Subtarget->isPICStyleGOT())
464         O << "@GOTOFF";
465     }
466
467     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
468       O << "(%rip)";
469     return;
470   }
471   case MachineOperand::MO_ConstantPoolIndex: {
472     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
473     if (!isMemOp) O << '$';
474     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
475       << MO.getIndex();
476
477     if (TM.getRelocationModel() == Reloc::PIC_) {
478       if (Subtarget->isPICStyleStub())
479         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
480           << "$pb\"";
481       else if (Subtarget->isPICStyleGOT())
482         O << "@GOTOFF";
483     }
484
485     printOffset(MO.getOffset());
486
487     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
488       O << "(%rip)";
489     return;
490   }
491   case MachineOperand::MO_GlobalAddress: {
492     bool isMemOp = Modifier && !strcmp(Modifier, "mem");
493     bool needCloseParen = false;
494
495     const GlobalValue *GV = MO.getGlobal();
496     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
497     if (!GVar) {
498       // If GV is an alias then use the aliasee for determining
499       // thread-localness.
500       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
501         GVar =dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
502     }
503
504     bool isThreadLocal = GVar && GVar->isThreadLocal();
505
506     std::string Name = Mang->getValueName(GV);
507     decorateName(Name, GV);
508
509     if (!isMemOp)
510       O << '$';
511     else if (Name[0] == '$') {
512       // The name begins with a dollar-sign. In order to avoid having it look
513       // like an integer immediate to the assembler, enclose it in parens.
514       O << '(';
515       needCloseParen = true;
516     }
517
518     if (shouldPrintStub(TM, Subtarget)) {
519       // Link-once, declaration, or Weakly-linked global variables need
520       // non-lazily-resolved stubs
521       if (GV->isDeclaration() || GV->isWeakForLinker()) {
522         // Dynamically-resolved functions need a stub for the function.
523         if (GV->hasHiddenVisibility()) {
524           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
525             // Definition is not definitely in the current translation unit.
526             O << Name;
527           else {
528             HiddenGVStubs.insert(Name);
529             printSuffixedName(Name, "$non_lazy_ptr");
530           }
531         } else {
532           GVStubs.insert(Name);
533           printSuffixedName(Name, "$non_lazy_ptr");
534         }
535       } else {
536         if (GV->hasDLLImportLinkage())
537           O << "__imp_";
538         O << Name;
539       }
540
541       if (TM.getRelocationModel() == Reloc::PIC_)
542         O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
543     } else {
544       if (GV->hasDLLImportLinkage())
545         O << "__imp_";
546       O << Name;
547     }
548
549     printOffset(MO.getOffset());
550
551     if (needCloseParen)
552       O << ')';
553     
554     bool isRIPRelative = false;
555     if (isThreadLocal) {
556       TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
557       switch (model) {
558       case TLSModel::GeneralDynamic:
559         O << "@TLSGD";
560         break;
561       case TLSModel::LocalDynamic:
562         // O << "@TLSLD"; // local dynamic not implemented
563         O << "@TLSGD";
564         break;
565       case TLSModel::InitialExec:
566         if (Subtarget->is64Bit()) {
567           assert (!NotRIPRel);
568           O << "@GOTTPOFF";
569           isRIPRelative = true;
570         } else {
571           O << "@INDNTPOFF";
572         }
573         break;
574       case TLSModel::LocalExec:
575         if (Subtarget->is64Bit())
576           O << "@TPOFF";
577         else
578           O << "@NTPOFF";
579         break;
580       default:
581         assert (0 && "Unknown TLS model");
582       }
583     } else if (isMemOp) {
584       if (shouldPrintGOT(TM, Subtarget)) {
585         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
586           O << "@GOT";
587         else
588           O << "@GOTOFF";
589       } else if (Subtarget->isPICStyleRIPRel() &&
590                  !NotRIPRel) {
591         if (TM.getRelocationModel() != Reloc::Static) {
592           if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
593             O << "@GOTPCREL";
594         }
595         
596         isRIPRelative = true;
597       }
598     }
599
600     // Use rip when possible to reduce code size, except when
601     // index or base register are also part of the address. e.g.
602     // foo(%rip)(%rcx,%rax,4) is not legal.
603     if (isRIPRelative)
604       O << "(%rip)";
605     
606     return;
607   }
608   case MachineOperand::MO_ExternalSymbol: {
609     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
610     bool needCloseParen = false;
611     std::string Name(TAI->getGlobalPrefix());
612     Name += MO.getSymbolName();
613
614     // Print function stub suffix unless it's Mac OS X 10.5 and up.
615     if (!isMemOp)
616       O << '$';
617     else if (Name[0] == '$') {
618       // The name begins with a dollar-sign. In order to avoid having it look
619       // like an integer immediate to the assembler, enclose it in parens.
620       O << '(';
621       needCloseParen = true;
622     }
623
624     O << Name;
625
626     if (shouldPrintPLT(TM, Subtarget)) {
627       std::string GOTName(TAI->getGlobalPrefix());
628       GOTName+="_GLOBAL_OFFSET_TABLE_";
629       if (Name == GOTName)
630         // HACK! Emit extra offset to PC during printing GOT offset to
631         // compensate for the size of popl instruction. The resulting code
632         // should look like:
633         //   call .piclabel
634         // piclabel:
635         //   popl %some_register
636         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
637         O << " + [.-"
638           << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
639     }
640
641     if (needCloseParen)
642       O << ')';
643
644     if (Subtarget->isPICStyleRIPRel())
645       O << "(%rip)";
646     return;
647   }
648   default:
649     O << "<unknown operand type>"; return;
650   }
651 }
652
653 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
654   unsigned char value = MI->getOperand(Op).getImm();
655   assert(value <= 7 && "Invalid ssecc argument!");
656   switch (value) {
657   case 0: O << "eq"; break;
658   case 1: O << "lt"; break;
659   case 2: O << "le"; break;
660   case 3: O << "unord"; break;
661   case 4: O << "neq"; break;
662   case 5: O << "nlt"; break;
663   case 6: O << "nle"; break;
664   case 7: O << "ord"; break;
665   }
666 }
667
668 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
669                                             const char *Modifier,
670                                             bool NotRIPRel) {
671   MachineOperand BaseReg  = MI->getOperand(Op);
672   MachineOperand IndexReg = MI->getOperand(Op+2);
673   const MachineOperand &DispSpec = MI->getOperand(Op+3);
674
675   NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
676   if (DispSpec.isGlobal() ||
677       DispSpec.isCPI() ||
678       DispSpec.isJTI() ||
679       DispSpec.isSymbol()) {
680     printOperand(MI, Op+3, "mem", NotRIPRel);
681   } else {
682     int DispVal = DispSpec.getImm();
683     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
684       O << DispVal;
685   }
686
687   if (IndexReg.getReg() || BaseReg.getReg()) {
688     unsigned ScaleVal = MI->getOperand(Op+1).getImm();
689     unsigned BaseRegOperand = 0, IndexRegOperand = 2;
690
691     // There are cases where we can end up with ESP/RSP in the indexreg slot.
692     // If this happens, swap the base/index register to support assemblers that
693     // don't work when the index is *SP.
694     if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
695       assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
696       std::swap(BaseReg, IndexReg);
697       std::swap(BaseRegOperand, IndexRegOperand);
698     }
699
700     O << '(';
701     if (BaseReg.getReg())
702       printOperand(MI, Op+BaseRegOperand, Modifier);
703
704     if (IndexReg.getReg()) {
705       O << ',';
706       printOperand(MI, Op+IndexRegOperand, Modifier);
707       if (ScaleVal != 1)
708         O << ',' << ScaleVal;
709     }
710     O << ')';
711   }
712 }
713
714 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
715                                          const char *Modifier, bool NotRIPRel){
716   assert(isMem(MI, Op) && "Invalid memory reference!");
717   MachineOperand Segment = MI->getOperand(Op+4);
718   if (Segment.getReg()) {
719       printOperand(MI, Op+4, Modifier);
720       O << ':';
721     }
722   printLeaMemReference(MI, Op, Modifier, NotRIPRel);
723 }
724
725 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
726                                            const MachineBasicBlock *MBB) const {
727   if (!TAI->getSetDirective())
728     return;
729
730   // We don't need .set machinery if we have GOT-style relocations
731   if (Subtarget->isPICStyleGOT())
732     return;
733
734   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
735     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
736   printBasicBlockLabel(MBB, false, false, false);
737   if (Subtarget->isPICStyleRIPRel())
738     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
739       << '_' << uid << '\n';
740   else
741     O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
742 }
743
744 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
745   std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
746   O << label << '\n' << label << ':';
747 }
748
749
750 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
751                                               const MachineBasicBlock *MBB,
752                                               unsigned uid) const
753 {
754   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
755     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
756
757   O << JTEntryDirective << ' ';
758
759   if (TM.getRelocationModel() == Reloc::PIC_) {
760     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
761       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
762         << '_' << uid << "_set_" << MBB->getNumber();
763     } else if (Subtarget->isPICStyleGOT()) {
764       printBasicBlockLabel(MBB, false, false, false);
765       O << "@GOTOFF";
766     } else
767       assert(0 && "Don't know how to print MBB label for this PIC mode");
768   } else
769     printBasicBlockLabel(MBB, false, false, false);
770 }
771
772 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
773   unsigned Reg = MO.getReg();
774   switch (Mode) {
775   default: return true;  // Unknown mode.
776   case 'b': // Print QImode register
777     Reg = getX86SubSuperRegister(Reg, MVT::i8);
778     break;
779   case 'h': // Print QImode high register
780     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
781     break;
782   case 'w': // Print HImode register
783     Reg = getX86SubSuperRegister(Reg, MVT::i16);
784     break;
785   case 'k': // Print SImode register
786     Reg = getX86SubSuperRegister(Reg, MVT::i32);
787     break;
788   case 'q': // Print DImode register
789     Reg = getX86SubSuperRegister(Reg, MVT::i64);
790     break;
791   }
792
793   O << '%'<< TRI->getAsmName(Reg);
794   return false;
795 }
796
797 /// PrintAsmOperand - Print out an operand for an inline asm expression.
798 ///
799 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
800                                        unsigned AsmVariant,
801                                        const char *ExtraCode) {
802   // Does this asm operand have a single letter operand modifier?
803   if (ExtraCode && ExtraCode[0]) {
804     if (ExtraCode[1] != 0) return true; // Unknown modifier.
805
806     switch (ExtraCode[0]) {
807     default: return true;  // Unknown modifier.
808     case 'c': // Don't print "$" before a global var name or constant.
809       printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
810       return false;
811     case 'b': // Print QImode register
812     case 'h': // Print QImode high register
813     case 'w': // Print HImode register
814     case 'k': // Print SImode register
815     case 'q': // Print DImode register
816       if (MI->getOperand(OpNo).isReg())
817         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
818       printOperand(MI, OpNo);
819       return false;
820
821     case 'P': // Don't print @PLT, but do print as memory.
822       printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
823       return false;
824     }
825   }
826
827   printOperand(MI, OpNo);
828   return false;
829 }
830
831 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
832                                              unsigned OpNo,
833                                              unsigned AsmVariant,
834                                              const char *ExtraCode) {
835   if (ExtraCode && ExtraCode[0]) {
836     if (ExtraCode[1] != 0) return true; // Unknown modifier.
837
838     switch (ExtraCode[0]) {
839     default: return true;  // Unknown modifier.
840     case 'b': // Print QImode register
841     case 'h': // Print QImode high register
842     case 'w': // Print HImode register
843     case 'k': // Print SImode register
844     case 'q': // Print SImode register
845       // These only apply to registers, ignore on mem.
846       break;
847     case 'P': // Don't print @PLT, but do print as memory.
848       printMemReference(MI, OpNo, "mem", /*NotRIPRel=*/true);
849       return false;
850     }
851   }
852   printMemReference(MI, OpNo);
853   return false;
854 }
855
856 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
857   // Convert registers in the addr mode according to subreg64.
858   for (unsigned i = 0; i != 4; ++i) {
859     if (!MI->getOperand(i).isReg()) continue;
860     
861     unsigned Reg = MI->getOperand(i).getReg();
862     if (Reg == 0) continue;
863     
864     MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
865   }
866 }
867
868 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
869 /// AT&T syntax to the current output stream.
870 ///
871 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
872   ++EmittedInsts;
873
874   if (NewAsmPrinter) {
875     if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
876       O << "\t";
877       printInlineAsm(MI);
878       return;
879     } else if (MI->isLabel()) {
880       printLabel(MI);
881       return;
882     } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
883       printDeclare(MI);
884       return;
885     } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
886       printImplicitDef(MI);
887       return;
888     }
889     
890     O << "NEW: ";
891     MCInst TmpInst;
892     
893     TmpInst.setOpcode(MI->getOpcode());
894     
895     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
896       const MachineOperand &MO = MI->getOperand(i);
897       
898       MCOperand MCOp;
899       if (MO.isReg()) {
900         MCOp.MakeReg(MO.getReg());
901       } else if (MO.isImm()) {
902         MCOp.MakeImm(MO.getImm());
903       } else if (MO.isMBB()) {
904         MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
905       } else {
906         assert(0 && "Unimp");
907       }
908       
909       TmpInst.addOperand(MCOp);
910     }
911     
912     switch (TmpInst.getOpcode()) {
913     case X86::LEA64_32r:
914       // Handle the 'subreg rewriting' for the lea64_32mem operand.
915       lower_lea64_32mem(&TmpInst, 1);
916       break;
917     }
918     
919     // FIXME: Convert TmpInst.
920     printInstruction(&TmpInst);
921     O << "OLD: ";
922   }
923   
924   // Call the autogenerated instruction printer routines.
925   printInstruction(MI);
926 }
927
928 /// doInitialization
929 bool X86ATTAsmPrinter::doInitialization(Module &M) {
930   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling()) 
931     MMI = getAnalysisIfAvailable<MachineModuleInfo>();
932   
933   if (NewAsmPrinter) {
934     Context = new MCContext();
935     // FIXME: Send this to "O" instead of outs().  For now, we force it to
936     // stdout to make it easy to compare.
937     Streamer = createAsmStreamer(*Context, outs());
938   }
939   
940   return AsmPrinter::doInitialization(M);
941 }
942
943 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
944   const TargetData *TD = TM.getTargetData();
945
946   if (!GVar->hasInitializer())
947     return;   // External global require no code
948
949   // Check to see if this is a special global used by LLVM, if so, emit it.
950   if (EmitSpecialLLVMGlobal(GVar)) {
951     if (Subtarget->isTargetDarwin() &&
952         TM.getRelocationModel() == Reloc::Static) {
953       if (GVar->getName() == "llvm.global_ctors")
954         O << ".reference .constructors_used\n";
955       else if (GVar->getName() == "llvm.global_dtors")
956         O << ".reference .destructors_used\n";
957     }
958     return;
959   }
960
961   std::string name = Mang->getValueName(GVar);
962   Constant *C = GVar->getInitializer();
963   const Type *Type = C->getType();
964   unsigned Size = TD->getTypeAllocSize(Type);
965   unsigned Align = TD->getPreferredAlignmentLog(GVar);
966
967   printVisibility(name, GVar->getVisibility());
968
969   if (Subtarget->isTargetELF())
970     O << "\t.type\t" << name << ",@object\n";
971
972   SwitchToSection(TAI->SectionForGlobal(GVar));
973
974   if (C->isNullValue() && !GVar->hasSection() &&
975       !(Subtarget->isTargetDarwin() &&
976         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
977     // FIXME: This seems to be pretty darwin-specific
978     if (GVar->hasExternalLinkage()) {
979       if (const char *Directive = TAI->getZeroFillDirective()) {
980         O << "\t.globl " << name << '\n';
981         O << Directive << "__DATA, __common, " << name << ", "
982           << Size << ", " << Align << '\n';
983         return;
984       }
985     }
986
987     if (!GVar->isThreadLocal() &&
988         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
989       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
990
991       if (TAI->getLCOMMDirective() != NULL) {
992         if (GVar->hasLocalLinkage()) {
993           O << TAI->getLCOMMDirective() << name << ',' << Size;
994           if (Subtarget->isTargetDarwin())
995             O << ',' << Align;
996         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
997           O << "\t.globl " << name << '\n'
998             << TAI->getWeakDefDirective() << name << '\n';
999           EmitAlignment(Align, GVar);
1000           O << name << ":";
1001           if (VerboseAsm) {
1002             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1003             PrintUnmangledNameSafely(GVar, O);
1004           }
1005           O << '\n';
1006           EmitGlobalConstant(C);
1007           return;
1008         } else {
1009           O << TAI->getCOMMDirective()  << name << ',' << Size;
1010           if (TAI->getCOMMDirectiveTakesAlignment())
1011             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1012         }
1013       } else {
1014         if (!Subtarget->isTargetCygMing()) {
1015           if (GVar->hasLocalLinkage())
1016             O << "\t.local\t" << name << '\n';
1017         }
1018         O << TAI->getCOMMDirective()  << name << ',' << Size;
1019         if (TAI->getCOMMDirectiveTakesAlignment())
1020           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1021       }
1022       if (VerboseAsm) {
1023         O << "\t\t" << TAI->getCommentString() << ' ';
1024         PrintUnmangledNameSafely(GVar, O);
1025       }
1026       O << '\n';
1027       return;
1028     }
1029   }
1030
1031   switch (GVar->getLinkage()) {
1032   case GlobalValue::CommonLinkage:
1033   case GlobalValue::LinkOnceAnyLinkage:
1034   case GlobalValue::LinkOnceODRLinkage:
1035   case GlobalValue::WeakAnyLinkage:
1036   case GlobalValue::WeakODRLinkage:
1037     if (Subtarget->isTargetDarwin()) {
1038       O << "\t.globl " << name << '\n'
1039         << TAI->getWeakDefDirective() << name << '\n';
1040     } else if (Subtarget->isTargetCygMing()) {
1041       O << "\t.globl\t" << name << "\n"
1042            "\t.linkonce same_size\n";
1043     } else {
1044       O << "\t.weak\t" << name << '\n';
1045     }
1046     break;
1047   case GlobalValue::DLLExportLinkage:
1048   case GlobalValue::AppendingLinkage:
1049     // FIXME: appending linkage variables should go into a section of
1050     // their name or something.  For now, just emit them as external.
1051   case GlobalValue::ExternalLinkage:
1052     // If external or appending, declare as a global symbol
1053     O << "\t.globl " << name << '\n';
1054     // FALL THROUGH
1055   case GlobalValue::PrivateLinkage:
1056   case GlobalValue::InternalLinkage:
1057      break;
1058   default:
1059     assert(0 && "Unknown linkage type!");
1060   }
1061
1062   EmitAlignment(Align, GVar);
1063   O << name << ":";
1064   if (VerboseAsm){
1065     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1066     PrintUnmangledNameSafely(GVar, O);
1067   }
1068   O << '\n';
1069   if (TAI->hasDotTypeDotSizeDirective())
1070     O << "\t.size\t" << name << ", " << Size << '\n';
1071
1072   EmitGlobalConstant(C);
1073 }
1074
1075 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1076   // Print out module-level global variables here.
1077   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1078        I != E; ++I) {
1079     printModuleLevelGV(I);
1080
1081     if (I->hasDLLExportLinkage())
1082       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1083   }
1084
1085   if (Subtarget->isTargetDarwin()) {
1086     SwitchToDataSection("");
1087     
1088     // Add the (possibly multiple) personalities to the set of global value
1089     // stubs.  Only referenced functions get into the Personalities list.
1090     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1091       const std::vector<Function*> &Personalities = MMI->getPersonalities();
1092       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1093         if (Personalities[i] == 0)
1094           continue;
1095         std::string Name = Mang->getValueName(Personalities[i]);
1096         decorateName(Name, Personalities[i]);
1097         GVStubs.insert(Name);
1098       }
1099     }
1100
1101     // Output stubs for dynamically-linked functions
1102     if (!FnStubs.empty()) {
1103       for (StringSet<>::iterator I = FnStubs.begin(), E = FnStubs.end();
1104            I != E; ++I) {
1105         SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1106                             "self_modifying_code+pure_instructions,5", 0);
1107         const char *Name = I->getKeyData();
1108         printSuffixedName(Name, "$stub");
1109         O << ":\n"
1110              "\t.indirect_symbol " << Name << "\n"
1111              "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1112       }
1113       O << '\n';
1114     }
1115
1116     // Output stubs for external and common global variables.
1117     if (!GVStubs.empty()) {
1118       SwitchToDataSection(
1119                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1120       for (StringSet<>::iterator I = GVStubs.begin(), E = GVStubs.end();
1121            I != E; ++I) {
1122         const char *Name = I->getKeyData();
1123         printSuffixedName(Name, "$non_lazy_ptr");
1124         O << ":\n\t.indirect_symbol " << Name << "\n\t.long\t0\n";
1125       }
1126     }
1127
1128     if (!HiddenGVStubs.empty()) {
1129       SwitchToSection(TAI->getDataSection());
1130       EmitAlignment(2);
1131       for (StringSet<>::iterator I = HiddenGVStubs.begin(),
1132            E = HiddenGVStubs.end(); I != E; ++I) {
1133         const char *Name = I->getKeyData();
1134         printSuffixedName(Name, "$non_lazy_ptr");
1135         O << ":\n" << TAI->getData32bitsDirective() << Name << '\n';
1136       }
1137     }
1138
1139     // Funny Darwin hack: This flag tells the linker that no global symbols
1140     // contain code that falls through to other global symbols (e.g. the obvious
1141     // implementation of multiple entry points).  If this doesn't occur, the
1142     // linker can safely perform dead code stripping.  Since LLVM never
1143     // generates code that does this, it is always safe to set.
1144     O << "\t.subsections_via_symbols\n";
1145   } else if (Subtarget->isTargetCygMing()) {
1146     // Emit type information for external functions
1147     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1148          i != e; ++i) {
1149       O << "\t.def\t " << i->getKeyData()
1150         << ";\t.scl\t" << COFF::C_EXT
1151         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1152         << ";\t.endef\n";
1153     }
1154   }
1155   
1156   
1157   // Output linker support code for dllexported globals on windows.
1158   if (!DLLExportedGVs.empty()) {
1159     SwitchToDataSection(".section .drectve");
1160   
1161     for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1162          e = DLLExportedGVs.end(); i != e; ++i)
1163       O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1164   }
1165   
1166   if (!DLLExportedFns.empty()) {
1167     SwitchToDataSection(".section .drectve");
1168   
1169     for (StringSet<>::iterator i = DLLExportedFns.begin(),
1170          e = DLLExportedFns.end();
1171          i != e; ++i)
1172       O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1173   }
1174   
1175   // Do common shutdown.
1176   bool Changed = AsmPrinter::doFinalization(M);
1177   
1178   if (NewAsmPrinter) {
1179     Streamer->Finish();
1180     
1181     delete Streamer;
1182     delete Context;
1183     Streamer = 0;
1184     Context = 0;
1185   }
1186   
1187   return Changed;
1188 }
1189
1190 // Include the auto-generated portion of the assembly writer.
1191 #include "X86GenAsmWriter.inc"