remove dead code now that personality functions don't print stubs directly.
[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     if (GV->hasExternalWeakLinkage())
376       ExtWeakSymbols.insert(GV);
377     
378     printOffset(MO.getOffset());
379     
380     if (needCloseParen)
381       O << ')';
382     return;
383   }
384       
385   case MachineOperand::MO_ExternalSymbol: {
386     bool needCloseParen = false;
387     std::string Name(TAI->getGlobalPrefix());
388     Name += MO.getSymbolName();
389     // Print function stub suffix unless it's Mac OS X 10.5 and up.
390     if (shouldPrintStub(TM, Subtarget) && 
391         !(Subtarget->isTargetDarwin() && Subtarget->getDarwinVers() >= 9)) {
392       FnStubs.insert(Name);
393       printSuffixedName(Name, "$stub");
394       return;
395     }
396     
397     if (Name[0] == '$') {
398       // The name begins with a dollar-sign. In order to avoid having it look
399       // like an integer immediate to the assembler, enclose it in parens.
400       O << '(';
401       needCloseParen = true;
402     }
403     
404     O << Name;
405     
406     if (shouldPrintPLT(TM, Subtarget)) {
407       std::string GOTName(TAI->getGlobalPrefix());
408       GOTName+="_GLOBAL_OFFSET_TABLE_";
409       if (Name == GOTName)
410         // HACK! Emit extra offset to PC during printing GOT offset to
411         // compensate for the size of popl instruction. The resulting code
412         // should look like:
413         //   call .piclabel
414         // piclabel:
415         //   popl %some_register
416         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
417         O << " + [.-"
418           << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
419       
420       O << "@PLT";
421     }
422     
423     if (needCloseParen)
424       O << ')';
425     
426     return;
427   }
428   }
429 }
430
431 void X86ATTAsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
432                                     const char *Modifier, bool NotRIPRel) {
433   const MachineOperand &MO = MI->getOperand(OpNo);
434   switch (MO.getType()) {
435   case MachineOperand::MO_Register: {
436     assert(TargetRegisterInfo::isPhysicalRegister(MO.getReg()) &&
437            "Virtual registers should not make it this far!");
438     O << '%';
439     unsigned Reg = MO.getReg();
440     if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
441       MVT VT = (strcmp(Modifier+6,"64") == 0) ?
442         MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
443                     ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
444       Reg = getX86SubSuperRegister(Reg, VT);
445     }
446     O << TRI->getAsmName(Reg);
447     return;
448   }
449
450   case MachineOperand::MO_Immediate:
451     if (!Modifier || (strcmp(Modifier, "debug") &&
452                       strcmp(Modifier, "mem")))
453       O << '$';
454     O << MO.getImm();
455     return;
456   case MachineOperand::MO_JumpTableIndex: {
457     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
458     if (!isMemOp) O << '$';
459     O << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber() << '_'
460       << MO.getIndex();
461
462     if (TM.getRelocationModel() == Reloc::PIC_) {
463       if (Subtarget->isPICStyleStub())
464         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
465           << "$pb\"";
466       else if (Subtarget->isPICStyleGOT())
467         O << "@GOTOFF";
468     }
469
470     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
471       O << "(%rip)";
472     return;
473   }
474   case MachineOperand::MO_ConstantPoolIndex: {
475     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
476     if (!isMemOp) O << '$';
477     O << TAI->getPrivateGlobalPrefix() << "CPI" << getFunctionNumber() << '_'
478       << MO.getIndex();
479
480     if (TM.getRelocationModel() == Reloc::PIC_) {
481       if (Subtarget->isPICStyleStub())
482         O << "-\"" << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
483           << "$pb\"";
484       else if (Subtarget->isPICStyleGOT())
485         O << "@GOTOFF";
486     }
487
488     printOffset(MO.getOffset());
489
490     if (isMemOp && Subtarget->isPICStyleRIPRel() && !NotRIPRel)
491       O << "(%rip)";
492     return;
493   }
494   case MachineOperand::MO_GlobalAddress: {
495     bool isMemOp = Modifier && !strcmp(Modifier, "mem");
496     bool needCloseParen = false;
497
498     const GlobalValue *GV = MO.getGlobal();
499     const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
500     if (!GVar) {
501       // If GV is an alias then use the aliasee for determining
502       // thread-localness.
503       if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
504         GVar =dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
505     }
506
507     bool isThreadLocal = GVar && GVar->isThreadLocal();
508
509     std::string Name = Mang->getValueName(GV);
510     decorateName(Name, GV);
511
512     if (!isMemOp)
513       O << '$';
514     else if (Name[0] == '$') {
515       // The name begins with a dollar-sign. In order to avoid having it look
516       // like an integer immediate to the assembler, enclose it in parens.
517       O << '(';
518       needCloseParen = true;
519     }
520
521     if (shouldPrintStub(TM, Subtarget)) {
522       // Link-once, declaration, or Weakly-linked global variables need
523       // non-lazily-resolved stubs
524       if (GV->isDeclaration() || GV->isWeakForLinker()) {
525         // Dynamically-resolved functions need a stub for the function.
526         if (GV->hasHiddenVisibility()) {
527           if (!GV->isDeclaration() && !GV->hasCommonLinkage())
528             // Definition is not definitely in the current translation unit.
529             O << Name;
530           else {
531             HiddenGVStubs.insert(Name);
532             printSuffixedName(Name, "$non_lazy_ptr");
533           }
534         } else {
535           GVStubs.insert(Name);
536           printSuffixedName(Name, "$non_lazy_ptr");
537         }
538       } else {
539         if (GV->hasDLLImportLinkage())
540           O << "__imp_";
541         O << Name;
542       }
543
544       if (TM.getRelocationModel() == Reloc::PIC_)
545         O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget);
546     } else {
547       if (GV->hasDLLImportLinkage())
548         O << "__imp_";
549       O << Name;
550     }
551
552     if (GV->hasExternalWeakLinkage())
553       ExtWeakSymbols.insert(GV);
554
555     printOffset(MO.getOffset());
556
557     if (needCloseParen)
558       O << ')';
559     
560     bool isRIPRelative = false;
561     if (isThreadLocal) {
562       TLSModel::Model model = getTLSModel(GVar, TM.getRelocationModel());
563       switch (model) {
564       case TLSModel::GeneralDynamic:
565         O << "@TLSGD";
566         break;
567       case TLSModel::LocalDynamic:
568         // O << "@TLSLD"; // local dynamic not implemented
569         O << "@TLSGD";
570         break;
571       case TLSModel::InitialExec:
572         if (Subtarget->is64Bit()) {
573           assert (!NotRIPRel);
574           O << "@GOTTPOFF";
575           isRIPRelative = true;
576         } else {
577           O << "@INDNTPOFF";
578         }
579         break;
580       case TLSModel::LocalExec:
581         if (Subtarget->is64Bit())
582           O << "@TPOFF";
583         else
584           O << "@NTPOFF";
585         break;
586       default:
587         assert (0 && "Unknown TLS model");
588       }
589     } else if (isMemOp) {
590       if (shouldPrintGOT(TM, Subtarget)) {
591         if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
592           O << "@GOT";
593         else
594           O << "@GOTOFF";
595       } else if (Subtarget->isPICStyleRIPRel() &&
596                  !NotRIPRel) {
597         if (TM.getRelocationModel() != Reloc::Static) {
598           if (Subtarget->GVRequiresExtraLoad(GV, TM, false))
599             O << "@GOTPCREL";
600         }
601         
602         isRIPRelative = true;
603       }
604     }
605
606     // Use rip when possible to reduce code size, except when
607     // index or base register are also part of the address. e.g.
608     // foo(%rip)(%rcx,%rax,4) is not legal.
609     if (isRIPRelative)
610       O << "(%rip)";
611     
612     return;
613   }
614   case MachineOperand::MO_ExternalSymbol: {
615     bool isMemOp  = Modifier && !strcmp(Modifier, "mem");
616     bool needCloseParen = false;
617     std::string Name(TAI->getGlobalPrefix());
618     Name += MO.getSymbolName();
619
620     // Print function stub suffix unless it's Mac OS X 10.5 and up.
621     if (!isMemOp)
622       O << '$';
623     else if (Name[0] == '$') {
624       // The name begins with a dollar-sign. In order to avoid having it look
625       // like an integer immediate to the assembler, enclose it in parens.
626       O << '(';
627       needCloseParen = true;
628     }
629
630     O << Name;
631
632     if (shouldPrintPLT(TM, Subtarget)) {
633       std::string GOTName(TAI->getGlobalPrefix());
634       GOTName+="_GLOBAL_OFFSET_TABLE_";
635       if (Name == GOTName)
636         // HACK! Emit extra offset to PC during printing GOT offset to
637         // compensate for the size of popl instruction. The resulting code
638         // should look like:
639         //   call .piclabel
640         // piclabel:
641         //   popl %some_register
642         //   addl $_GLOBAL_ADDRESS_TABLE_ + [.-piclabel], %some_register
643         O << " + [.-"
644           << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << ']';
645     }
646
647     if (needCloseParen)
648       O << ')';
649
650     if (Subtarget->isPICStyleRIPRel())
651       O << "(%rip)";
652     return;
653   }
654   default:
655     O << "<unknown operand type>"; return;
656   }
657 }
658
659 void X86ATTAsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op) {
660   unsigned char value = MI->getOperand(Op).getImm();
661   assert(value <= 7 && "Invalid ssecc argument!");
662   switch (value) {
663   case 0: O << "eq"; break;
664   case 1: O << "lt"; break;
665   case 2: O << "le"; break;
666   case 3: O << "unord"; break;
667   case 4: O << "neq"; break;
668   case 5: O << "nlt"; break;
669   case 6: O << "nle"; break;
670   case 7: O << "ord"; break;
671   }
672 }
673
674 void X86ATTAsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
675                                             const char *Modifier,
676                                             bool NotRIPRel) {
677   MachineOperand BaseReg  = MI->getOperand(Op);
678   MachineOperand IndexReg = MI->getOperand(Op+2);
679   const MachineOperand &DispSpec = MI->getOperand(Op+3);
680
681   NotRIPRel |= IndexReg.getReg() || BaseReg.getReg();
682   if (DispSpec.isGlobal() ||
683       DispSpec.isCPI() ||
684       DispSpec.isJTI() ||
685       DispSpec.isSymbol()) {
686     printOperand(MI, Op+3, "mem", NotRIPRel);
687   } else {
688     int DispVal = DispSpec.getImm();
689     if (DispVal || (!IndexReg.getReg() && !BaseReg.getReg()))
690       O << DispVal;
691   }
692
693   if (IndexReg.getReg() || BaseReg.getReg()) {
694     unsigned ScaleVal = MI->getOperand(Op+1).getImm();
695     unsigned BaseRegOperand = 0, IndexRegOperand = 2;
696
697     // There are cases where we can end up with ESP/RSP in the indexreg slot.
698     // If this happens, swap the base/index register to support assemblers that
699     // don't work when the index is *SP.
700     if (IndexReg.getReg() == X86::ESP || IndexReg.getReg() == X86::RSP) {
701       assert(ScaleVal == 1 && "Scale not supported for stack pointer!");
702       std::swap(BaseReg, IndexReg);
703       std::swap(BaseRegOperand, IndexRegOperand);
704     }
705
706     O << '(';
707     if (BaseReg.getReg())
708       printOperand(MI, Op+BaseRegOperand, Modifier);
709
710     if (IndexReg.getReg()) {
711       O << ',';
712       printOperand(MI, Op+IndexRegOperand, Modifier);
713       if (ScaleVal != 1)
714         O << ',' << ScaleVal;
715     }
716     O << ')';
717   }
718 }
719
720 void X86ATTAsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
721                                          const char *Modifier, bool NotRIPRel){
722   assert(isMem(MI, Op) && "Invalid memory reference!");
723   MachineOperand Segment = MI->getOperand(Op+4);
724   if (Segment.getReg()) {
725       printOperand(MI, Op+4, Modifier);
726       O << ':';
727     }
728   printLeaMemReference(MI, Op, Modifier, NotRIPRel);
729 }
730
731 void X86ATTAsmPrinter::printPICJumpTableSetLabel(unsigned uid,
732                                            const MachineBasicBlock *MBB) const {
733   if (!TAI->getSetDirective())
734     return;
735
736   // We don't need .set machinery if we have GOT-style relocations
737   if (Subtarget->isPICStyleGOT())
738     return;
739
740   O << TAI->getSetDirective() << ' ' << TAI->getPrivateGlobalPrefix()
741     << getFunctionNumber() << '_' << uid << "_set_" << MBB->getNumber() << ',';
742   printBasicBlockLabel(MBB, false, false, false);
743   if (Subtarget->isPICStyleRIPRel())
744     O << '-' << TAI->getPrivateGlobalPrefix() << "JTI" << getFunctionNumber()
745       << '_' << uid << '\n';
746   else
747     O << '-' << getPICLabelString(getFunctionNumber(), TAI, Subtarget) << '\n';
748 }
749
750 void X86ATTAsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op) {
751   std::string label = getPICLabelString(getFunctionNumber(), TAI, Subtarget);
752   O << label << '\n' << label << ':';
753 }
754
755
756 void X86ATTAsmPrinter::printPICJumpTableEntry(const MachineJumpTableInfo *MJTI,
757                                               const MachineBasicBlock *MBB,
758                                               unsigned uid) const
759 {
760   const char *JTEntryDirective = MJTI->getEntrySize() == 4 ?
761     TAI->getData32bitsDirective() : TAI->getData64bitsDirective();
762
763   O << JTEntryDirective << ' ';
764
765   if (TM.getRelocationModel() == Reloc::PIC_) {
766     if (Subtarget->isPICStyleRIPRel() || Subtarget->isPICStyleStub()) {
767       O << TAI->getPrivateGlobalPrefix() << getFunctionNumber()
768         << '_' << uid << "_set_" << MBB->getNumber();
769     } else if (Subtarget->isPICStyleGOT()) {
770       printBasicBlockLabel(MBB, false, false, false);
771       O << "@GOTOFF";
772     } else
773       assert(0 && "Don't know how to print MBB label for this PIC mode");
774   } else
775     printBasicBlockLabel(MBB, false, false, false);
776 }
777
778 bool X86ATTAsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode) {
779   unsigned Reg = MO.getReg();
780   switch (Mode) {
781   default: return true;  // Unknown mode.
782   case 'b': // Print QImode register
783     Reg = getX86SubSuperRegister(Reg, MVT::i8);
784     break;
785   case 'h': // Print QImode high register
786     Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
787     break;
788   case 'w': // Print HImode register
789     Reg = getX86SubSuperRegister(Reg, MVT::i16);
790     break;
791   case 'k': // Print SImode register
792     Reg = getX86SubSuperRegister(Reg, MVT::i32);
793     break;
794   case 'q': // Print DImode register
795     Reg = getX86SubSuperRegister(Reg, MVT::i64);
796     break;
797   }
798
799   O << '%'<< TRI->getAsmName(Reg);
800   return false;
801 }
802
803 /// PrintAsmOperand - Print out an operand for an inline asm expression.
804 ///
805 bool X86ATTAsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
806                                        unsigned AsmVariant,
807                                        const char *ExtraCode) {
808   // Does this asm operand have a single letter operand modifier?
809   if (ExtraCode && ExtraCode[0]) {
810     if (ExtraCode[1] != 0) return true; // Unknown modifier.
811
812     switch (ExtraCode[0]) {
813     default: return true;  // Unknown modifier.
814     case 'c': // Don't print "$" before a global var name or constant.
815       printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
816       return false;
817     case 'b': // Print QImode register
818     case 'h': // Print QImode high register
819     case 'w': // Print HImode register
820     case 'k': // Print SImode register
821     case 'q': // Print DImode register
822       if (MI->getOperand(OpNo).isReg())
823         return printAsmMRegister(MI->getOperand(OpNo), ExtraCode[0]);
824       printOperand(MI, OpNo);
825       return false;
826
827     case 'P': // Don't print @PLT, but do print as memory.
828       printOperand(MI, OpNo, "mem", /*NotRIPRel=*/true);
829       return false;
830     }
831   }
832
833   printOperand(MI, OpNo);
834   return false;
835 }
836
837 bool X86ATTAsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
838                                              unsigned OpNo,
839                                              unsigned AsmVariant,
840                                              const char *ExtraCode) {
841   if (ExtraCode && ExtraCode[0]) {
842     if (ExtraCode[1] != 0) return true; // Unknown modifier.
843
844     switch (ExtraCode[0]) {
845     default: return true;  // Unknown modifier.
846     case 'b': // Print QImode register
847     case 'h': // Print QImode high register
848     case 'w': // Print HImode register
849     case 'k': // Print SImode register
850     case 'q': // Print SImode register
851       // These only apply to registers, ignore on mem.
852       break;
853     case 'P': // Don't print @PLT, but do print as memory.
854       printMemReference(MI, OpNo, "mem", /*NotRIPRel=*/true);
855       return false;
856     }
857   }
858   printMemReference(MI, OpNo);
859   return false;
860 }
861
862 static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
863   // Convert registers in the addr mode according to subreg64.
864   for (unsigned i = 0; i != 4; ++i) {
865     if (!MI->getOperand(i).isReg()) continue;
866     
867     unsigned Reg = MI->getOperand(i).getReg();
868     if (Reg == 0) continue;
869     
870     MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
871   }
872 }
873
874 /// printMachineInstruction -- Print out a single X86 LLVM instruction MI in
875 /// AT&T syntax to the current output stream.
876 ///
877 void X86ATTAsmPrinter::printMachineInstruction(const MachineInstr *MI) {
878   ++EmittedInsts;
879
880   if (NewAsmPrinter) {
881     if (MI->getOpcode() == TargetInstrInfo::INLINEASM) {
882       O << "\t";
883       printInlineAsm(MI);
884       return;
885     } else if (MI->isLabel()) {
886       printLabel(MI);
887       return;
888     } else if (MI->getOpcode() == TargetInstrInfo::DECLARE) {
889       printDeclare(MI);
890       return;
891     } else if (MI->getOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
892       printImplicitDef(MI);
893       return;
894     }
895     
896     O << "NEW: ";
897     MCInst TmpInst;
898     
899     TmpInst.setOpcode(MI->getOpcode());
900     
901     for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
902       const MachineOperand &MO = MI->getOperand(i);
903       
904       MCOperand MCOp;
905       if (MO.isReg()) {
906         MCOp.MakeReg(MO.getReg());
907       } else if (MO.isImm()) {
908         MCOp.MakeImm(MO.getImm());
909       } else if (MO.isMBB()) {
910         MCOp.MakeMBBLabel(getFunctionNumber(), MO.getMBB()->getNumber());
911       } else {
912         assert(0 && "Unimp");
913       }
914       
915       TmpInst.addOperand(MCOp);
916     }
917     
918     switch (TmpInst.getOpcode()) {
919     case X86::LEA64_32r:
920       // Handle the 'subreg rewriting' for the lea64_32mem operand.
921       lower_lea64_32mem(&TmpInst, 1);
922       break;
923     }
924     
925     // FIXME: Convert TmpInst.
926     printInstruction(&TmpInst);
927     O << "OLD: ";
928   }
929   
930   // Call the autogenerated instruction printer routines.
931   printInstruction(MI);
932 }
933
934 /// doInitialization
935 bool X86ATTAsmPrinter::doInitialization(Module &M) {
936   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling()) 
937     MMI = getAnalysisIfAvailable<MachineModuleInfo>();
938   
939   if (NewAsmPrinter) {
940     Context = new MCContext();
941     // FIXME: Send this to "O" instead of outs().  For now, we force it to
942     // stdout to make it easy to compare.
943     Streamer = createAsmStreamer(*Context, outs());
944   }
945   
946   return AsmPrinter::doInitialization(M);
947 }
948
949 void X86ATTAsmPrinter::printModuleLevelGV(const GlobalVariable* GVar) {
950   const TargetData *TD = TM.getTargetData();
951
952   if (!GVar->hasInitializer())
953     return;   // External global require no code
954
955   // Check to see if this is a special global used by LLVM, if so, emit it.
956   if (EmitSpecialLLVMGlobal(GVar)) {
957     if (Subtarget->isTargetDarwin() &&
958         TM.getRelocationModel() == Reloc::Static) {
959       if (GVar->getName() == "llvm.global_ctors")
960         O << ".reference .constructors_used\n";
961       else if (GVar->getName() == "llvm.global_dtors")
962         O << ".reference .destructors_used\n";
963     }
964     return;
965   }
966
967   std::string name = Mang->getValueName(GVar);
968   Constant *C = GVar->getInitializer();
969   const Type *Type = C->getType();
970   unsigned Size = TD->getTypeAllocSize(Type);
971   unsigned Align = TD->getPreferredAlignmentLog(GVar);
972
973   printVisibility(name, GVar->getVisibility());
974
975   if (Subtarget->isTargetELF())
976     O << "\t.type\t" << name << ",@object\n";
977
978   SwitchToSection(TAI->SectionForGlobal(GVar));
979
980   if (C->isNullValue() && !GVar->hasSection() &&
981       !(Subtarget->isTargetDarwin() &&
982         TAI->SectionKindForGlobal(GVar) == SectionKind::RODataMergeStr)) {
983     // FIXME: This seems to be pretty darwin-specific
984     if (GVar->hasExternalLinkage()) {
985       if (const char *Directive = TAI->getZeroFillDirective()) {
986         O << "\t.globl " << name << '\n';
987         O << Directive << "__DATA, __common, " << name << ", "
988           << Size << ", " << Align << '\n';
989         return;
990       }
991     }
992
993     if (!GVar->isThreadLocal() &&
994         (GVar->hasLocalLinkage() || GVar->isWeakForLinker())) {
995       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
996
997       if (TAI->getLCOMMDirective() != NULL) {
998         if (GVar->hasLocalLinkage()) {
999           O << TAI->getLCOMMDirective() << name << ',' << Size;
1000           if (Subtarget->isTargetDarwin())
1001             O << ',' << Align;
1002         } else if (Subtarget->isTargetDarwin() && !GVar->hasCommonLinkage()) {
1003           O << "\t.globl " << name << '\n'
1004             << TAI->getWeakDefDirective() << name << '\n';
1005           EmitAlignment(Align, GVar);
1006           O << name << ":";
1007           if (VerboseAsm) {
1008             O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1009             PrintUnmangledNameSafely(GVar, O);
1010           }
1011           O << '\n';
1012           EmitGlobalConstant(C);
1013           return;
1014         } else {
1015           O << TAI->getCOMMDirective()  << name << ',' << Size;
1016           if (TAI->getCOMMDirectiveTakesAlignment())
1017             O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1018         }
1019       } else {
1020         if (!Subtarget->isTargetCygMing()) {
1021           if (GVar->hasLocalLinkage())
1022             O << "\t.local\t" << name << '\n';
1023         }
1024         O << TAI->getCOMMDirective()  << name << ',' << Size;
1025         if (TAI->getCOMMDirectiveTakesAlignment())
1026           O << ',' << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
1027       }
1028       if (VerboseAsm) {
1029         O << "\t\t" << TAI->getCommentString() << ' ';
1030         PrintUnmangledNameSafely(GVar, O);
1031       }
1032       O << '\n';
1033       return;
1034     }
1035   }
1036
1037   switch (GVar->getLinkage()) {
1038   case GlobalValue::CommonLinkage:
1039   case GlobalValue::LinkOnceAnyLinkage:
1040   case GlobalValue::LinkOnceODRLinkage:
1041   case GlobalValue::WeakAnyLinkage:
1042   case GlobalValue::WeakODRLinkage:
1043     if (Subtarget->isTargetDarwin()) {
1044       O << "\t.globl " << name << '\n'
1045         << TAI->getWeakDefDirective() << name << '\n';
1046     } else if (Subtarget->isTargetCygMing()) {
1047       O << "\t.globl\t" << name << "\n"
1048            "\t.linkonce same_size\n";
1049     } else {
1050       O << "\t.weak\t" << name << '\n';
1051     }
1052     break;
1053   case GlobalValue::DLLExportLinkage:
1054   case GlobalValue::AppendingLinkage:
1055     // FIXME: appending linkage variables should go into a section of
1056     // their name or something.  For now, just emit them as external.
1057   case GlobalValue::ExternalLinkage:
1058     // If external or appending, declare as a global symbol
1059     O << "\t.globl " << name << '\n';
1060     // FALL THROUGH
1061   case GlobalValue::PrivateLinkage:
1062   case GlobalValue::InternalLinkage:
1063      break;
1064   default:
1065     assert(0 && "Unknown linkage type!");
1066   }
1067
1068   EmitAlignment(Align, GVar);
1069   O << name << ":";
1070   if (VerboseAsm){
1071     O << "\t\t\t\t" << TAI->getCommentString() << ' ';
1072     PrintUnmangledNameSafely(GVar, O);
1073   }
1074   O << '\n';
1075   if (TAI->hasDotTypeDotSizeDirective())
1076     O << "\t.size\t" << name << ", " << Size << '\n';
1077
1078   EmitGlobalConstant(C);
1079 }
1080
1081 /// printGVStub - Print stub for a global value.
1082 ///
1083 void X86ATTAsmPrinter::printGVStub(const char *GV) {
1084   printSuffixedName(GV, "$non_lazy_ptr");
1085   O << ":\n\t.indirect_symbol " << GV << "\n\t.long\t0\n";
1086 }
1087
1088 /// printHiddenGVStub - Print stub for a hidden global value.
1089 ///
1090 void X86ATTAsmPrinter::printHiddenGVStub(const char *GV) {
1091   EmitAlignment(2);
1092   printSuffixedName(GV, "$non_lazy_ptr");
1093   O << ":\n" << TAI->getData32bitsDirective() << GV << '\n';
1094 }
1095
1096
1097 bool X86ATTAsmPrinter::doFinalization(Module &M) {
1098   // Print out module-level global variables here.
1099   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
1100        I != E; ++I) {
1101     printModuleLevelGV(I);
1102
1103     if (I->hasDLLExportLinkage())
1104       DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
1105
1106     // If the global is a extern weak symbol, remember to emit the weak
1107     // reference!
1108     // FIXME: This is rather hacky, since we'll emit references to ALL weak
1109     // stuff, not used. But currently it's the only way to deal with extern weak
1110     // initializers hidden deep inside constant expressions.
1111     if (I->hasExternalWeakLinkage())
1112       ExtWeakSymbols.insert(I);
1113   }
1114
1115   for (Module::const_iterator I = M.begin(), E = M.end();
1116        I != E; ++I) {
1117     // If the global is a extern weak symbol, remember to emit the weak
1118     // reference!
1119     // FIXME: This is rather hacky, since we'll emit references to ALL weak
1120     // stuff, not used. But currently it's the only way to deal with extern weak
1121     // initializers hidden deep inside constant expressions.
1122     if (I->hasExternalWeakLinkage())
1123       ExtWeakSymbols.insert(I);
1124   }
1125
1126   // Output linker support code for dllexported globals
1127   if (!DLLExportedGVs.empty())
1128     SwitchToDataSection(".section .drectve");
1129
1130   for (StringSet<>::iterator i = DLLExportedGVs.begin(),
1131          e = DLLExportedGVs.end();
1132          i != e; ++i)
1133     O << "\t.ascii \" -export:" << i->getKeyData() << ",data\"\n";
1134
1135   if (!DLLExportedFns.empty())
1136     SwitchToDataSection(".section .drectve");
1137
1138   for (StringSet<>::iterator i = DLLExportedFns.begin(),
1139          e = DLLExportedFns.end();
1140          i != e; ++i)
1141     O << "\t.ascii \" -export:" << i->getKeyData() << "\"\n";
1142
1143   if (Subtarget->isTargetDarwin()) {
1144     SwitchToDataSection("");
1145
1146     // Output stubs for dynamically-linked functions
1147     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1148          i != e; ++i) {
1149       SwitchToDataSection("\t.section __IMPORT,__jump_table,symbol_stubs,"
1150                           "self_modifying_code+pure_instructions,5", 0);
1151       const char *p = i->getKeyData();
1152       printSuffixedName(p, "$stub");
1153       O << ":\n"
1154            "\t.indirect_symbol " << p << "\n"
1155            "\thlt ; hlt ; hlt ; hlt ; hlt\n";
1156     }
1157
1158     O << '\n';
1159
1160     // Add the (possibly multiple) personalities to the set of global value
1161     // stubs.  Only referenced functions get into the Personalities list.
1162     if (TAI->doesSupportExceptionHandling() && MMI && !Subtarget->is64Bit()) {
1163       const std::vector<Function*> &Personalities = MMI->getPersonalities();
1164       for (unsigned i = 0, e = Personalities.size(); i != e; ++i) {
1165         if (Personalities[i] == 0)
1166           continue;
1167         std::string Name = Mang->getValueName(Personalities[i]);
1168         decorateName(Name, Personalities[i]);
1169         GVStubs.insert(Name);
1170       }
1171     }
1172
1173     // Output stubs for external and common global variables.
1174     if (!GVStubs.empty())
1175       SwitchToDataSection(
1176                     "\t.section __IMPORT,__pointers,non_lazy_symbol_pointers");
1177     for (StringSet<>::iterator i = GVStubs.begin(), e = GVStubs.end();
1178          i != e; ++i)
1179       printGVStub(i->getKeyData());
1180
1181     if (!HiddenGVStubs.empty()) {
1182       SwitchToSection(TAI->getDataSection());
1183       for (StringSet<>::iterator i = HiddenGVStubs.begin(), e = HiddenGVStubs.end();
1184            i != e; ++i)
1185         printHiddenGVStub(i->getKeyData());
1186     }
1187
1188     // Funny Darwin hack: This flag tells the linker that no global symbols
1189     // contain code that falls through to other global symbols (e.g. the obvious
1190     // implementation of multiple entry points).  If this doesn't occur, the
1191     // linker can safely perform dead code stripping.  Since LLVM never
1192     // generates code that does this, it is always safe to set.
1193     O << "\t.subsections_via_symbols\n";
1194   } else if (Subtarget->isTargetCygMing()) {
1195     // Emit type information for external functions
1196     for (StringSet<>::iterator i = FnStubs.begin(), e = FnStubs.end();
1197          i != e; ++i) {
1198       O << "\t.def\t " << i->getKeyData()
1199         << ";\t.scl\t" << COFF::C_EXT
1200         << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
1201         << ";\t.endef\n";
1202     }
1203   }
1204   
1205   // Emit final debug information.
1206   if (TAI->doesSupportDebugInformation() || TAI->doesSupportExceptionHandling())
1207     DW->EndModule();
1208   
1209   
1210   if (NewAsmPrinter) {
1211     Streamer->Finish();
1212     
1213     delete Streamer;
1214     delete Context;
1215     Streamer = 0;
1216     Context = 0;
1217   }
1218   
1219   return AsmPrinter::doFinalization(M);
1220 }
1221
1222 // Include the auto-generated portion of the assembly writer.
1223 #include "X86GenAsmWriter.inc"