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