X86AsmPrinter.cpp revision 234353
1//===-- X86AsmPrinter.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 X86 machine code.
12//
13//===----------------------------------------------------------------------===//
14
15#include "X86AsmPrinter.h"
16#include "X86MCInstLower.h"
17#include "X86.h"
18#include "X86COFFMachineModuleInfo.h"
19#include "X86MachineFunctionInfo.h"
20#include "X86TargetMachine.h"
21#include "InstPrinter/X86ATTInstPrinter.h"
22#include "llvm/CallingConv.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Module.h"
25#include "llvm/Type.h"
26#include "llvm/Analysis/DebugInfo.h"
27#include "llvm/Assembly/Writer.h"
28#include "llvm/MC/MCAsmInfo.h"
29#include "llvm/MC/MCContext.h"
30#include "llvm/MC/MCExpr.h"
31#include "llvm/MC/MCSectionMachO.h"
32#include "llvm/MC/MCStreamer.h"
33#include "llvm/MC/MCSymbol.h"
34#include "llvm/CodeGen/MachineJumpTableInfo.h"
35#include "llvm/CodeGen/MachineModuleInfoImpls.h"
36#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
37#include "llvm/Target/Mangler.h"
38#include "llvm/Target/TargetOptions.h"
39#include "llvm/Support/COFF.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/TargetRegistry.h"
43#include "llvm/ADT/SmallString.h"
44using namespace llvm;
45
46//===----------------------------------------------------------------------===//
47// Primitive Helper Functions.
48//===----------------------------------------------------------------------===//
49
50/// runOnMachineFunction - Emit the function body.
51///
52bool X86AsmPrinter::runOnMachineFunction(MachineFunction &MF) {
53  SetupMachineFunction(MF);
54
55  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) {
56    bool Intrn = MF.getFunction()->hasInternalLinkage();
57    OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
58    OutStreamer.EmitCOFFSymbolStorageClass(Intrn ? COFF::IMAGE_SYM_CLASS_STATIC
59                                              : COFF::IMAGE_SYM_CLASS_EXTERNAL);
60    OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
61                                               << COFF::SCT_COMPLEX_TYPE_SHIFT);
62    OutStreamer.EndCOFFSymbolDef();
63  }
64
65  // Have common code print out the function header with linkage info etc.
66  EmitFunctionHeader();
67
68  // Emit the rest of the function body.
69  EmitFunctionBody();
70
71  // We didn't modify anything.
72  return false;
73}
74
75/// printSymbolOperand - Print a raw symbol reference operand.  This handles
76/// jump tables, constant pools, global address and external symbols, all of
77/// which print to a label with various suffixes for relocation types etc.
78void X86AsmPrinter::printSymbolOperand(const MachineOperand &MO,
79                                       raw_ostream &O) {
80  switch (MO.getType()) {
81  default: llvm_unreachable("unknown symbol type!");
82  case MachineOperand::MO_JumpTableIndex:
83    O << *GetJTISymbol(MO.getIndex());
84    break;
85  case MachineOperand::MO_ConstantPoolIndex:
86    O << *GetCPISymbol(MO.getIndex());
87    printOffset(MO.getOffset(), O);
88    break;
89  case MachineOperand::MO_GlobalAddress: {
90    const GlobalValue *GV = MO.getGlobal();
91
92    MCSymbol *GVSym;
93    if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
94      GVSym = GetSymbolWithGlobalValueBase(GV, "$stub");
95    else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
96             MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
97             MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
98      GVSym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
99    else
100      GVSym = Mang->getSymbol(GV);
101
102    // Handle dllimport linkage.
103    if (MO.getTargetFlags() == X86II::MO_DLLIMPORT)
104      GVSym = OutContext.GetOrCreateSymbol(Twine("__imp_") + GVSym->getName());
105
106    if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
107        MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE) {
108      MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
109      MachineModuleInfoImpl::StubValueTy &StubSym =
110        MMI->getObjFileInfo<MachineModuleInfoMachO>().getGVStubEntry(Sym);
111      if (StubSym.getPointer() == 0)
112        StubSym = MachineModuleInfoImpl::
113          StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
114    } else if (MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE){
115      MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$non_lazy_ptr");
116      MachineModuleInfoImpl::StubValueTy &StubSym =
117        MMI->getObjFileInfo<MachineModuleInfoMachO>().getHiddenGVStubEntry(Sym);
118      if (StubSym.getPointer() == 0)
119        StubSym = MachineModuleInfoImpl::
120          StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
121    } else if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
122      MCSymbol *Sym = GetSymbolWithGlobalValueBase(GV, "$stub");
123      MachineModuleInfoImpl::StubValueTy &StubSym =
124        MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
125      if (StubSym.getPointer() == 0)
126        StubSym = MachineModuleInfoImpl::
127          StubValueTy(Mang->getSymbol(GV), !GV->hasInternalLinkage());
128    }
129
130    // If the name begins with a dollar-sign, enclose it in parens.  We do this
131    // to avoid having it look like an integer immediate to the assembler.
132    if (GVSym->getName()[0] != '$')
133      O << *GVSym;
134    else
135      O << '(' << *GVSym << ')';
136    printOffset(MO.getOffset(), O);
137    break;
138  }
139  case MachineOperand::MO_ExternalSymbol: {
140    const MCSymbol *SymToPrint;
141    if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
142      SmallString<128> TempNameStr;
143      TempNameStr += StringRef(MO.getSymbolName());
144      TempNameStr += StringRef("$stub");
145
146      MCSymbol *Sym = GetExternalSymbolSymbol(TempNameStr.str());
147      MachineModuleInfoImpl::StubValueTy &StubSym =
148        MMI->getObjFileInfo<MachineModuleInfoMachO>().getFnStubEntry(Sym);
149      if (StubSym.getPointer() == 0) {
150        TempNameStr.erase(TempNameStr.end()-5, TempNameStr.end());
151        StubSym = MachineModuleInfoImpl::
152          StubValueTy(OutContext.GetOrCreateSymbol(TempNameStr.str()),
153                      true);
154      }
155      SymToPrint = StubSym.getPointer();
156    } else {
157      SymToPrint = GetExternalSymbolSymbol(MO.getSymbolName());
158    }
159
160    // If the name begins with a dollar-sign, enclose it in parens.  We do this
161    // to avoid having it look like an integer immediate to the assembler.
162    if (SymToPrint->getName()[0] != '$')
163      O << *SymToPrint;
164    else
165      O << '(' << *SymToPrint << '(';
166    break;
167  }
168  }
169
170  switch (MO.getTargetFlags()) {
171  default:
172    llvm_unreachable("Unknown target flag on GV operand");
173  case X86II::MO_NO_FLAG:    // No flag.
174    break;
175  case X86II::MO_DARWIN_NONLAZY:
176  case X86II::MO_DLLIMPORT:
177  case X86II::MO_DARWIN_STUB:
178    // These affect the name of the symbol, not any suffix.
179    break;
180  case X86II::MO_GOT_ABSOLUTE_ADDRESS:
181    O << " + [.-" << *MF->getPICBaseSymbol() << ']';
182    break;
183  case X86II::MO_PIC_BASE_OFFSET:
184  case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
185  case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
186    O << '-' << *MF->getPICBaseSymbol();
187    break;
188  case X86II::MO_TLSGD:     O << "@TLSGD";     break;
189  case X86II::MO_GOTTPOFF:  O << "@GOTTPOFF";  break;
190  case X86II::MO_INDNTPOFF: O << "@INDNTPOFF"; break;
191  case X86II::MO_TPOFF:     O << "@TPOFF";     break;
192  case X86II::MO_NTPOFF:    O << "@NTPOFF";    break;
193  case X86II::MO_GOTPCREL:  O << "@GOTPCREL";  break;
194  case X86II::MO_GOT:       O << "@GOT";       break;
195  case X86II::MO_GOTOFF:    O << "@GOTOFF";    break;
196  case X86II::MO_PLT:       O << "@PLT";       break;
197  case X86II::MO_TLVP:      O << "@TLVP";      break;
198  case X86II::MO_TLVP_PIC_BASE:
199    O << "@TLVP" << '-' << *MF->getPICBaseSymbol();
200    break;
201  case X86II::MO_SECREL:      O << "@SECREL";      break;
202  }
203}
204
205/// print_pcrel_imm - This is used to print an immediate value that ends up
206/// being encoded as a pc-relative value.  These print slightly differently, for
207/// example, a $ is not emitted.
208void X86AsmPrinter::print_pcrel_imm(const MachineInstr *MI, unsigned OpNo,
209                                    raw_ostream &O) {
210  const MachineOperand &MO = MI->getOperand(OpNo);
211  switch (MO.getType()) {
212  default: llvm_unreachable("Unknown pcrel immediate operand");
213  case MachineOperand::MO_Register:
214    // pc-relativeness was handled when computing the value in the reg.
215    printOperand(MI, OpNo, O);
216    return;
217  case MachineOperand::MO_Immediate:
218    O << MO.getImm();
219    return;
220  case MachineOperand::MO_MachineBasicBlock:
221    O << *MO.getMBB()->getSymbol();
222    return;
223  case MachineOperand::MO_GlobalAddress:
224  case MachineOperand::MO_ExternalSymbol:
225    printSymbolOperand(MO, O);
226    return;
227  }
228}
229
230
231void X86AsmPrinter::printOperand(const MachineInstr *MI, unsigned OpNo,
232                                 raw_ostream &O, const char *Modifier) {
233  const MachineOperand &MO = MI->getOperand(OpNo);
234  switch (MO.getType()) {
235  default: llvm_unreachable("unknown operand type!");
236  case MachineOperand::MO_Register: {
237    O << '%';
238    unsigned Reg = MO.getReg();
239    if (Modifier && strncmp(Modifier, "subreg", strlen("subreg")) == 0) {
240      EVT VT = (strcmp(Modifier+6,"64") == 0) ?
241        MVT::i64 : ((strcmp(Modifier+6, "32") == 0) ? MVT::i32 :
242                    ((strcmp(Modifier+6,"16") == 0) ? MVT::i16 : MVT::i8));
243      Reg = getX86SubSuperRegister(Reg, VT);
244    }
245    O << X86ATTInstPrinter::getRegisterName(Reg);
246    return;
247  }
248
249  case MachineOperand::MO_Immediate:
250    O << '$' << MO.getImm();
251    return;
252
253  case MachineOperand::MO_JumpTableIndex:
254  case MachineOperand::MO_ConstantPoolIndex:
255  case MachineOperand::MO_GlobalAddress:
256  case MachineOperand::MO_ExternalSymbol: {
257    O << '$';
258    printSymbolOperand(MO, O);
259    break;
260  }
261  }
262}
263
264void X86AsmPrinter::printSSECC(const MachineInstr *MI, unsigned Op,
265                               raw_ostream &O) {
266  unsigned char value = MI->getOperand(Op).getImm();
267  switch (value) {
268  default: llvm_unreachable("Invalid ssecc argument!");
269  case    0: O << "eq"; break;
270  case    1: O << "lt"; break;
271  case    2: O << "le"; break;
272  case    3: O << "unord"; break;
273  case    4: O << "neq"; break;
274  case    5: O << "nlt"; break;
275  case    6: O << "nle"; break;
276  case    7: O << "ord"; break;
277  case    8: O << "eq_uq"; break;
278  case    9: O << "nge"; break;
279  case  0xa: O << "ngt"; break;
280  case  0xb: O << "false"; break;
281  case  0xc: O << "neq_oq"; break;
282  case  0xd: O << "ge"; break;
283  case  0xe: O << "gt"; break;
284  case  0xf: O << "true"; break;
285  case 0x10: O << "eq_os"; break;
286  case 0x11: O << "lt_oq"; break;
287  case 0x12: O << "le_oq"; break;
288  case 0x13: O << "unord_s"; break;
289  case 0x14: O << "neq_us"; break;
290  case 0x15: O << "nlt_uq"; break;
291  case 0x16: O << "nle_uq"; break;
292  case 0x17: O << "ord_s"; break;
293  case 0x18: O << "eq_us"; break;
294  case 0x19: O << "nge_uq"; break;
295  case 0x1a: O << "ngt_uq"; break;
296  case 0x1b: O << "false_os"; break;
297  case 0x1c: O << "neq_os"; break;
298  case 0x1d: O << "ge_oq"; break;
299  case 0x1e: O << "gt_oq"; break;
300  case 0x1f: O << "true_us"; break;
301  }
302}
303
304void X86AsmPrinter::printLeaMemReference(const MachineInstr *MI, unsigned Op,
305                                         raw_ostream &O, const char *Modifier) {
306  const MachineOperand &BaseReg  = MI->getOperand(Op);
307  const MachineOperand &IndexReg = MI->getOperand(Op+2);
308  const MachineOperand &DispSpec = MI->getOperand(Op+3);
309
310  // If we really don't want to print out (rip), don't.
311  bool HasBaseReg = BaseReg.getReg() != 0;
312  if (HasBaseReg && Modifier && !strcmp(Modifier, "no-rip") &&
313      BaseReg.getReg() == X86::RIP)
314    HasBaseReg = false;
315
316  // HasParenPart - True if we will print out the () part of the mem ref.
317  bool HasParenPart = IndexReg.getReg() || HasBaseReg;
318
319  if (DispSpec.isImm()) {
320    int DispVal = DispSpec.getImm();
321    if (DispVal || !HasParenPart)
322      O << DispVal;
323  } else {
324    assert(DispSpec.isGlobal() || DispSpec.isCPI() ||
325           DispSpec.isJTI() || DispSpec.isSymbol());
326    printSymbolOperand(MI->getOperand(Op+3), O);
327  }
328
329  if (Modifier && strcmp(Modifier, "H") == 0)
330    O << "+8";
331
332  if (HasParenPart) {
333    assert(IndexReg.getReg() != X86::ESP &&
334           "X86 doesn't allow scaling by ESP");
335
336    O << '(';
337    if (HasBaseReg)
338      printOperand(MI, Op, O, Modifier);
339
340    if (IndexReg.getReg()) {
341      O << ',';
342      printOperand(MI, Op+2, O, Modifier);
343      unsigned ScaleVal = MI->getOperand(Op+1).getImm();
344      if (ScaleVal != 1)
345        O << ',' << ScaleVal;
346    }
347    O << ')';
348  }
349}
350
351void X86AsmPrinter::printMemReference(const MachineInstr *MI, unsigned Op,
352                                      raw_ostream &O, const char *Modifier) {
353  assert(isMem(MI, Op) && "Invalid memory reference!");
354  const MachineOperand &Segment = MI->getOperand(Op+4);
355  if (Segment.getReg()) {
356    printOperand(MI, Op+4, O, Modifier);
357    O << ':';
358  }
359  printLeaMemReference(MI, Op, O, Modifier);
360}
361
362void X86AsmPrinter::printPICLabel(const MachineInstr *MI, unsigned Op,
363                                  raw_ostream &O) {
364  O << *MF->getPICBaseSymbol() << '\n';
365  O << *MF->getPICBaseSymbol() << ':';
366}
367
368bool X86AsmPrinter::printAsmMRegister(const MachineOperand &MO, char Mode,
369                                      raw_ostream &O) {
370  unsigned Reg = MO.getReg();
371  switch (Mode) {
372  default: return true;  // Unknown mode.
373  case 'b': // Print QImode register
374    Reg = getX86SubSuperRegister(Reg, MVT::i8);
375    break;
376  case 'h': // Print QImode high register
377    Reg = getX86SubSuperRegister(Reg, MVT::i8, true);
378    break;
379  case 'w': // Print HImode register
380    Reg = getX86SubSuperRegister(Reg, MVT::i16);
381    break;
382  case 'k': // Print SImode register
383    Reg = getX86SubSuperRegister(Reg, MVT::i32);
384    break;
385  case 'q': // Print DImode register
386    Reg = getX86SubSuperRegister(Reg, MVT::i64);
387    break;
388  }
389
390  O << '%' << X86ATTInstPrinter::getRegisterName(Reg);
391  return false;
392}
393
394/// PrintAsmOperand - Print out an operand for an inline asm expression.
395///
396bool X86AsmPrinter::PrintAsmOperand(const MachineInstr *MI, unsigned OpNo,
397                                    unsigned AsmVariant,
398                                    const char *ExtraCode, raw_ostream &O) {
399  // Does this asm operand have a single letter operand modifier?
400  if (ExtraCode && ExtraCode[0]) {
401    if (ExtraCode[1] != 0) return true; // Unknown modifier.
402
403    const MachineOperand &MO = MI->getOperand(OpNo);
404
405    switch (ExtraCode[0]) {
406    default: return true;  // Unknown modifier.
407    case 'a': // This is an address.  Currently only 'i' and 'r' are expected.
408      if (MO.isImm()) {
409        O << MO.getImm();
410        return false;
411      }
412      if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol()) {
413        printSymbolOperand(MO, O);
414        if (Subtarget->isPICStyleRIPRel())
415          O << "(%rip)";
416        return false;
417      }
418      if (MO.isReg()) {
419        O << '(';
420        printOperand(MI, OpNo, O);
421        O << ')';
422        return false;
423      }
424      return true;
425
426    case 'c': // Don't print "$" before a global var name or constant.
427      if (MO.isImm())
428        O << MO.getImm();
429      else if (MO.isGlobal() || MO.isCPI() || MO.isJTI() || MO.isSymbol())
430        printSymbolOperand(MO, O);
431      else
432        printOperand(MI, OpNo, O);
433      return false;
434
435    case 'A': // Print '*' before a register (it must be a register)
436      if (MO.isReg()) {
437        O << '*';
438        printOperand(MI, OpNo, O);
439        return false;
440      }
441      return true;
442
443    case 'b': // Print QImode register
444    case 'h': // Print QImode high register
445    case 'w': // Print HImode register
446    case 'k': // Print SImode register
447    case 'q': // Print DImode register
448      if (MO.isReg())
449        return printAsmMRegister(MO, ExtraCode[0], O);
450      printOperand(MI, OpNo, O);
451      return false;
452
453    case 'P': // This is the operand of a call, treat specially.
454      print_pcrel_imm(MI, OpNo, O);
455      return false;
456
457    case 'n':  // Negate the immediate or print a '-' before the operand.
458      // Note: this is a temporary solution. It should be handled target
459      // independently as part of the 'MC' work.
460      if (MO.isImm()) {
461        O << -MO.getImm();
462        return false;
463      }
464      O << '-';
465    }
466  }
467
468  printOperand(MI, OpNo, O);
469  return false;
470}
471
472bool X86AsmPrinter::PrintAsmMemoryOperand(const MachineInstr *MI,
473                                          unsigned OpNo, unsigned AsmVariant,
474                                          const char *ExtraCode,
475                                          raw_ostream &O) {
476  if (ExtraCode && ExtraCode[0]) {
477    if (ExtraCode[1] != 0) return true; // Unknown modifier.
478
479    switch (ExtraCode[0]) {
480    default: return true;  // Unknown modifier.
481    case 'b': // Print QImode register
482    case 'h': // Print QImode high register
483    case 'w': // Print HImode register
484    case 'k': // Print SImode register
485    case 'q': // Print SImode register
486      // These only apply to registers, ignore on mem.
487      break;
488    case 'H':
489      printMemReference(MI, OpNo, O, "H");
490      return false;
491    case 'P': // Don't print @PLT, but do print as memory.
492      printMemReference(MI, OpNo, O, "no-rip");
493      return false;
494    }
495  }
496  printMemReference(MI, OpNo, O);
497  return false;
498}
499
500void X86AsmPrinter::EmitStartOfAsmFile(Module &M) {
501  if (Subtarget->isTargetEnvMacho())
502    OutStreamer.SwitchSection(getObjFileLowering().getTextSection());
503}
504
505
506void X86AsmPrinter::EmitEndOfAsmFile(Module &M) {
507  if (Subtarget->isTargetEnvMacho()) {
508    // All darwin targets use mach-o.
509    MachineModuleInfoMachO &MMIMacho =
510      MMI->getObjFileInfo<MachineModuleInfoMachO>();
511
512    // Output stubs for dynamically-linked functions.
513    MachineModuleInfoMachO::SymbolListTy Stubs;
514
515    Stubs = MMIMacho.GetFnStubList();
516    if (!Stubs.empty()) {
517      const MCSection *TheSection =
518        OutContext.getMachOSection("__IMPORT", "__jump_table",
519                                   MCSectionMachO::S_SYMBOL_STUBS |
520                                   MCSectionMachO::S_ATTR_SELF_MODIFYING_CODE |
521                                   MCSectionMachO::S_ATTR_PURE_INSTRUCTIONS,
522                                   5, SectionKind::getMetadata());
523      OutStreamer.SwitchSection(TheSection);
524
525      for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
526        // L_foo$stub:
527        OutStreamer.EmitLabel(Stubs[i].first);
528        //   .indirect_symbol _foo
529        OutStreamer.EmitSymbolAttribute(Stubs[i].second.getPointer(),
530                                        MCSA_IndirectSymbol);
531        // hlt; hlt; hlt; hlt; hlt     hlt = 0xf4.
532        const char HltInsts[] = "\xf4\xf4\xf4\xf4\xf4";
533        OutStreamer.EmitBytes(StringRef(HltInsts, 5), 0/*addrspace*/);
534      }
535
536      Stubs.clear();
537      OutStreamer.AddBlankLine();
538    }
539
540    // Output stubs for external and common global variables.
541    Stubs = MMIMacho.GetGVStubList();
542    if (!Stubs.empty()) {
543      const MCSection *TheSection =
544        OutContext.getMachOSection("__IMPORT", "__pointers",
545                                   MCSectionMachO::S_NON_LAZY_SYMBOL_POINTERS,
546                                   SectionKind::getMetadata());
547      OutStreamer.SwitchSection(TheSection);
548
549      for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
550        // L_foo$non_lazy_ptr:
551        OutStreamer.EmitLabel(Stubs[i].first);
552        // .indirect_symbol _foo
553        MachineModuleInfoImpl::StubValueTy &MCSym = Stubs[i].second;
554        OutStreamer.EmitSymbolAttribute(MCSym.getPointer(),
555                                        MCSA_IndirectSymbol);
556        // .long 0
557        if (MCSym.getInt())
558          // External to current translation unit.
559          OutStreamer.EmitIntValue(0, 4/*size*/, 0/*addrspace*/);
560        else
561          // Internal to current translation unit.
562          //
563          // When we place the LSDA into the TEXT section, the type info
564          // pointers need to be indirect and pc-rel. We accomplish this by
565          // using NLPs.  However, sometimes the types are local to the file. So
566          // we need to fill in the value for the NLP in those cases.
567          OutStreamer.EmitValue(MCSymbolRefExpr::Create(MCSym.getPointer(),
568                                                        OutContext),
569                                4/*size*/, 0/*addrspace*/);
570      }
571      Stubs.clear();
572      OutStreamer.AddBlankLine();
573    }
574
575    Stubs = MMIMacho.GetHiddenGVStubList();
576    if (!Stubs.empty()) {
577      OutStreamer.SwitchSection(getObjFileLowering().getDataSection());
578      EmitAlignment(2);
579
580      for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
581        // L_foo$non_lazy_ptr:
582        OutStreamer.EmitLabel(Stubs[i].first);
583        // .long _foo
584        OutStreamer.EmitValue(MCSymbolRefExpr::
585                              Create(Stubs[i].second.getPointer(),
586                                     OutContext),
587                              4/*size*/, 0/*addrspace*/);
588      }
589      Stubs.clear();
590      OutStreamer.AddBlankLine();
591    }
592
593    // Funny Darwin hack: This flag tells the linker that no global symbols
594    // contain code that falls through to other global symbols (e.g. the obvious
595    // implementation of multiple entry points).  If this doesn't occur, the
596    // linker can safely perform dead code stripping.  Since LLVM never
597    // generates code that does this, it is always safe to set.
598    OutStreamer.EmitAssemblerFlag(MCAF_SubsectionsViaSymbols);
599  }
600
601  if (Subtarget->isTargetWindows() && !Subtarget->isTargetCygMing() &&
602      MMI->usesVAFloatArgument()) {
603    StringRef SymbolName = Subtarget->is64Bit() ? "_fltused" : "__fltused";
604    MCSymbol *S = MMI->getContext().GetOrCreateSymbol(SymbolName);
605    OutStreamer.EmitSymbolAttribute(S, MCSA_Global);
606  }
607
608  if (Subtarget->isTargetCOFF() && !Subtarget->isTargetEnvMacho()) {
609    X86COFFMachineModuleInfo &COFFMMI =
610      MMI->getObjFileInfo<X86COFFMachineModuleInfo>();
611
612    // Emit type information for external functions
613    typedef X86COFFMachineModuleInfo::externals_iterator externals_iterator;
614    for (externals_iterator I = COFFMMI.externals_begin(),
615                            E = COFFMMI.externals_end();
616                            I != E; ++I) {
617      OutStreamer.BeginCOFFSymbolDef(CurrentFnSym);
618      OutStreamer.EmitCOFFSymbolStorageClass(COFF::IMAGE_SYM_CLASS_EXTERNAL);
619      OutStreamer.EmitCOFFSymbolType(COFF::IMAGE_SYM_DTYPE_FUNCTION
620                                               << COFF::SCT_COMPLEX_TYPE_SHIFT);
621      OutStreamer.EndCOFFSymbolDef();
622    }
623
624    // Necessary for dllexport support
625    std::vector<const MCSymbol*> DLLExportedFns, DLLExportedGlobals;
626
627    const TargetLoweringObjectFileCOFF &TLOFCOFF =
628      static_cast<const TargetLoweringObjectFileCOFF&>(getObjFileLowering());
629
630    for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
631      if (I->hasDLLExportLinkage())
632        DLLExportedFns.push_back(Mang->getSymbol(I));
633
634    for (Module::const_global_iterator I = M.global_begin(),
635           E = M.global_end(); I != E; ++I)
636      if (I->hasDLLExportLinkage())
637        DLLExportedGlobals.push_back(Mang->getSymbol(I));
638
639    // Output linker support code for dllexported globals on windows.
640    if (!DLLExportedGlobals.empty() || !DLLExportedFns.empty()) {
641      OutStreamer.SwitchSection(TLOFCOFF.getDrectveSection());
642      SmallString<128> name;
643      for (unsigned i = 0, e = DLLExportedGlobals.size(); i != e; ++i) {
644        if (Subtarget->isTargetWindows())
645          name = " /EXPORT:";
646        else
647          name = " -export:";
648        name += DLLExportedGlobals[i]->getName();
649        if (Subtarget->isTargetWindows())
650          name += ",DATA";
651        else
652        name += ",data";
653        OutStreamer.EmitBytes(name, 0);
654      }
655
656      for (unsigned i = 0, e = DLLExportedFns.size(); i != e; ++i) {
657        if (Subtarget->isTargetWindows())
658          name = " /EXPORT:";
659        else
660          name = " -export:";
661        name += DLLExportedFns[i]->getName();
662        OutStreamer.EmitBytes(name, 0);
663      }
664    }
665  }
666
667  if (Subtarget->isTargetELF()) {
668    const TargetLoweringObjectFileELF &TLOFELF =
669      static_cast<const TargetLoweringObjectFileELF &>(getObjFileLowering());
670
671    MachineModuleInfoELF &MMIELF = MMI->getObjFileInfo<MachineModuleInfoELF>();
672
673    // Output stubs for external and common global variables.
674    MachineModuleInfoELF::SymbolListTy Stubs = MMIELF.GetGVStubList();
675    if (!Stubs.empty()) {
676      OutStreamer.SwitchSection(TLOFELF.getDataRelSection());
677      const TargetData *TD = TM.getTargetData();
678
679      for (unsigned i = 0, e = Stubs.size(); i != e; ++i) {
680        OutStreamer.EmitLabel(Stubs[i].first);
681        OutStreamer.EmitSymbolValue(Stubs[i].second.getPointer(),
682                                    TD->getPointerSize(), 0);
683      }
684      Stubs.clear();
685    }
686  }
687}
688
689MachineLocation
690X86AsmPrinter::getDebugValueLocation(const MachineInstr *MI) const {
691  MachineLocation Location;
692  assert (MI->getNumOperands() == 7 && "Invalid no. of machine operands!");
693  // Frame address.  Currently handles register +- offset only.
694
695  if (MI->getOperand(0).isReg() && MI->getOperand(3).isImm())
696    Location.set(MI->getOperand(0).getReg(), MI->getOperand(3).getImm());
697  else {
698    DEBUG(dbgs() << "DBG_VALUE instruction ignored! " << *MI << "\n");
699  }
700  return Location;
701}
702
703void X86AsmPrinter::PrintDebugValueComment(const MachineInstr *MI,
704                                           raw_ostream &O) {
705  // Only the target-dependent form of DBG_VALUE should get here.
706  // Referencing the offset and metadata as NOps-2 and NOps-1 is
707  // probably portable to other targets; frame pointer location is not.
708  unsigned NOps = MI->getNumOperands();
709  assert(NOps==7);
710  O << '\t' << MAI->getCommentString() << "DEBUG_VALUE: ";
711  // cast away const; DIetc do not take const operands for some reason.
712  DIVariable V(const_cast<MDNode *>(MI->getOperand(NOps-1).getMetadata()));
713  if (V.getContext().isSubprogram())
714    O << DISubprogram(V.getContext()).getDisplayName() << ":";
715  O << V.getName();
716  O << " <- ";
717  // Frame address.  Currently handles register +- offset only.
718  O << '[';
719  if (MI->getOperand(0).isReg() && MI->getOperand(0).getReg())
720    printOperand(MI, 0, O);
721  else
722    O << "undef";
723  O << '+'; printOperand(MI, 3, O);
724  O << ']';
725  O << "+";
726  printOperand(MI, NOps-2, O);
727}
728
729
730
731//===----------------------------------------------------------------------===//
732// Target Registry Stuff
733//===----------------------------------------------------------------------===//
734
735// Force static initialization.
736extern "C" void LLVMInitializeX86AsmPrinter() {
737  RegisterAsmPrinter<X86AsmPrinter> X(TheX86_32Target);
738  RegisterAsmPrinter<X86AsmPrinter> Y(TheX86_64Target);
739}
740