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