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