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