Adding dllimport, dllexport and external weak linkage types.
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
index af805766db472ce3f76036eb31766f782d7b2952..08dc7b26502765921ef477b38774063f1f373979 100644 (file)
 //
 //===----------------------------------------------------------------------===//
 
+#include "X86AsmPrinter.h"
 #include "X86ATTAsmPrinter.h"
 #include "X86IntelAsmPrinter.h"
-#include "X86.h"
+#include "X86Subtarget.h"
+#include "llvm/Constants.h"
 #include "llvm/Module.h"
 #include "llvm/Type.h"
 #include "llvm/Assembly/Writer.h"
-#include "llvm/CodeGen/MachineConstantPool.h"
 #include "llvm/Support/Mangler.h"
-#include "llvm/Support/CommandLine.h"
+#include "llvm/Target/TargetAsmInfo.h"
 using namespace llvm;
-using namespace x86;
 
-Statistic<> llvm::x86::EmittedInsts("asm-printer",
-                                    "Number of machine instrs printed");
-
-enum AsmWriterFlavorTy { att, intel };
-cl::opt<AsmWriterFlavorTy>
-AsmWriterFlavor("x86-asm-syntax",
-                cl::desc("Choose style of code to emit from X86 backend:"),
-                cl::values(
-                           clEnumVal(att,   "  Emit AT&T-style assembly"),
-                           clEnumVal(intel, "  Emit Intel-style assembly"),
-                           clEnumValEnd),
-                cl::init(att));
+Statistic<> llvm::EmittedInsts("asm-printer",
+                               "Number of machine instrs printed");
 
 /// doInitialization
-bool X86SharedAsmPrinter::doInitialization(Module& M) {
-  bool leadingUnderscore = false;
-  forCygwin = false;
-  const std::string& TT = M.getTargetTriple();
-  if (TT.length() > 5) {
-    forCygwin = TT.find("cygwin") != std::string::npos ||
-                TT.find("mingw")  != std::string::npos;
-    forDarwin = TT.find("darwin") != std::string::npos;
-  } else if (TT.empty()) {
-#if defined(__CYGWIN__) || defined(__MINGW32__)
-    forCygwin = true;
-#elif defined(__APPLE__)
-    forDarwin = true;
-#elif defined(_WIN32)
-    leadingUnderscore = true;
-#else
-    leadingUnderscore = false;
-#endif
-  }
-
-  if (leadingUnderscore || forCygwin || forDarwin)
-    GlobalPrefix = "_";
-
-  if (forDarwin) {
-    AlignmentIsInBytes = false;
-    Data64bitsDirective = 0;       // we can't emit a 64-bit unit
-    ZeroDirective = "\t.space\t";  // ".space N" emits N zeros.
-    PrivateGlobalPrefix = "L";     // Marker for constant pool idxs
+bool X86SharedAsmPrinter::doInitialization(Module &M) {
+  if (Subtarget->isTargetDarwin()) {
+    const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
+    if (!Subtarget->is64Bit())
+      X86PICStyle = PICStyle::Stub;
+
+    // Emit initial debug information.
+    DW.BeginModule(&M);
   }
 
   return AsmPrinter::doInitialization(M);
 }
 
-/// printConstantPool - Print to the current output stream assembly
-/// representations of the constants in the constant pool MCP. This is
-/// used to print out constants which have been "spilled to memory" by
-/// the code generator.
-///
-void X86SharedAsmPrinter::printConstantPool(MachineConstantPool *MCP) {
-  const std::vector<Constant*> &CP = MCP->getConstants();
-  const TargetData &TD = TM.getTargetData();
-
-  if (CP.empty()) return;
-
-  if (forDarwin) {
-    O << "\t.const\n";
-  } else {
-    O << "\t.section .rodata\n";
-  }
-  
-  for (unsigned i = 0, e = CP.size(); i != e; ++i) {
-    // FIXME: force doubles to be naturally aligned.  We should handle this
-    // more correctly in the future.
-    if (CP[i]->getType() == Type::DoubleTy)
-      emitAlignment(3);
-    else
-      emitAlignment(TD.getTypeAlignmentShift(CP[i]->getType()));
-    O << PrivateGlobalPrefix << "CPI" << CurrentFnName << "_" << i
-      << ":\t\t\t\t\t" << CommentString << *CP[i] << "\n";
-    emitGlobalConstant(CP[i]);
-  }
-}
-
 bool X86SharedAsmPrinter::doFinalization(Module &M) {
-  const TargetData &TD = TM.getTargetData();
-  std::string CurSection;
+  // Note: this code is not shared by the Intel printer as it is too different
+  // from how MASM does things.  When making changes here don't forget to look
+  // at X86IntelAsmPrinter::doFinalization().
+  const TargetData *TD = TM.getTargetData();
 
   // Print out module-level global variables here.
-  for (Module::const_global_iterator I = M.global_begin(),
-         E = M.global_end(); I != E; ++I)
-    if (I->hasInitializer()) {   // External global require no code
-      O << "\n\n";
-      std::string name = Mang->getValueName(I);
-      Constant *C = I->getInitializer();
-      unsigned Size = TD.getTypeSize(C->getType());
-      unsigned Align = TD.getTypeAlignmentShift(C->getType());
-
-      if (C->isNullValue() &&
-          (I->hasLinkOnceLinkage() || I->hasInternalLinkage() ||
-           I->hasWeakLinkage() /* FIXME: Verify correct */)) {
-        switchSection(O, CurSection, ".data");
-        if (!forCygwin && !forDarwin && I->hasInternalLinkage())
-          O << "\t.local " << name << "\n";
-        if (forDarwin && I->hasInternalLinkage())
-          O << "\t.lcomm " << name << "," << Size << "," << Align;
-        else
-          O << "\t.comm " << name << "," << Size;
-        if (!forCygwin && !forDarwin)
-          O << "," << (1 << Align);
-        O << "\t\t# ";
-        WriteAsOperand(O, I, true, true, &M);
-        O << "\n";
+  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
+       I != E; ++I) {
+    if (!I->hasInitializer()) continue;   // External global require no code
+    
+    // Check to see if this is a special global used by LLVM, if so, emit it.
+    if (EmitSpecialLLVMGlobal(I))
+      continue;
+    
+    std::string name = Mang->getValueName(I);
+    Constant *C = I->getInitializer();
+    unsigned Size = TD->getTypeSize(C->getType());
+    unsigned Align = getPreferredAlignmentLog(I);
+
+    if (C->isNullValue() && /* FIXME: Verify correct */
+        (I->hasInternalLinkage() || I->hasWeakLinkage() ||
+         I->hasLinkOnceLinkage() ||
+         (Subtarget->isTargetDarwin() && 
+          I->hasExternalLinkage() && !I->hasSection()))) {
+      if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
+      if (I->hasExternalLinkage()) {
+          O << "\t.globl\t" << name << "\n";
+          O << "\t.zerofill __DATA__, __common, " << name << ", "
+            << Size << ", " << Align;
       } else {
-        switch (I->getLinkage()) {
-        default: assert(0 && "Unknown linkage type!");
-        case GlobalValue::LinkOnceLinkage:
-        case GlobalValue::WeakLinkage:   // FIXME: Verify correct for weak.
-          // Nonnull linkonce -> weak
-          O << "\t.weak " << name << "\n";
-          switchSection(O, CurSection, "");
-          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n";
-          break;
-        case GlobalValue::AppendingLinkage:
-          // FIXME: appending linkage variables should go into a section of
-          // their name or something.  For now, just emit them as external.
-        case GlobalValue::ExternalLinkage:
-          // If external or appending, declare as a global symbol
-          O << "\t.globl " << name << "\n";
-          // FALL THROUGH
-        case GlobalValue::InternalLinkage:
-          if (C->isNullValue())
-            switchSection(O, CurSection, ".bss");
-          else
-            switchSection(O, CurSection, ".data");
-          break;
+        SwitchToDataSection(TAI->getDataSection(), I);
+        if (TAI->getLCOMMDirective() != NULL) {
+          if (I->hasInternalLinkage()) {
+            O << TAI->getLCOMMDirective() << name << "," << Size;
+            if (Subtarget->isTargetDarwin())
+              O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
+          } else
+            O << TAI->getCOMMDirective()  << name << "," << Size;
+        } else {
+          if (Subtarget->TargetType != X86Subtarget::isCygwin) {
+            if (I->hasInternalLinkage())
+              O << "\t.local\t" << name << "\n";
+          }
+          O << TAI->getCOMMDirective()  << name << "," << Size;
+          if (TAI->getCOMMDirectiveTakesAlignment())
+            O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
         }
-
-        emitAlignment(Align);
-        if (!forCygwin && !forDarwin) {
-          O << "\t.type " << name << ",@object\n";
-          O << "\t.size " << name << "," << Size << "\n";
+      }
+      O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
+    } else {
+      switch (I->getLinkage()) {
+      case GlobalValue::LinkOnceLinkage:
+      case GlobalValue::WeakLinkage:
+        if (Subtarget->isTargetDarwin()) {
+          O << "\t.globl " << name << "\n"
+            << "\t.weak_definition " << name << "\n";
+          SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
+        } else if (Subtarget->TargetType == X86Subtarget::isCygwin) {
+          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\"\n"
+            << "\t.weak " << name << "\n";
+        } else {
+          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"
+            << "\t.weak " << name << "\n";
         }
-        O << name << ":\t\t\t\t# ";
-        WriteAsOperand(O, I, true, true, &M);
-        O << " = ";
-        WriteAsOperand(O, C, false, false, &M);
-        O << "\n";
-        emitGlobalConstant(C);
+        break;
+      case GlobalValue::AppendingLinkage:
+        // FIXME: appending linkage variables should go into a section of
+        // their name or something.  For now, just emit them as external.
+      case GlobalValue::DLLExportLinkage:
+        DLLExportedGVs.insert(Mang->makeNameProper(I->getName(),""));
+        // FALL THROUGH
+      case GlobalValue::ExternalLinkage:
+        // If external or appending, declare as a global symbol
+        O << "\t.globl " << name << "\n";
+        // FALL THROUGH
+      case GlobalValue::InternalLinkage:
+        SwitchToDataSection(TAI->getDataSection(), I);
+        break;
+      default:
+        assert(0 && "Unknown linkage type!");
       }
+
+      EmitAlignment(Align, I);
+      O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
+        << "\n";
+      if (TAI->hasDotTypeDotSizeDirective())
+        O << "\t.size " << name << ", " << Size << "\n";
+
+      EmitGlobalConstant(C);
+      O << '\n';
     }
+  }
+  
+  // Output linker support code for dllexported globals
+  if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
+    SwitchToDataSection(".section .drectve", 0);    
+  }
 
-  if (forDarwin) {
-    // Output stubs for external global variables
-    if (GVStubs.begin() != GVStubs.end())
-      O << "\t.non_lazy_symbol_pointer\n";
-    for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
+  for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
+         e = DLLExportedGVs.end();
          i != e; ++i) {
-      O << "L" << *i << "$non_lazy_ptr:\n";
-      O << "\t.indirect_symbol " << *i << "\n";
-      O << "\t.long\t0\n";
-    }
+    O << "\t.ascii \" -export:" << *i << ",data\"\n";
+  }    
+
+  if (DLLExportedFns.begin() != DLLExportedFns.end()) {
+    SwitchToDataSection(".section .drectve", 0);    
+  }
+
+  for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
+         e = DLLExportedFns.end();
+         i != e; ++i) {
+    O << "\t.ascii \" -export:" << *i << "\"\n";
+  }    
+  if (Subtarget->isTargetDarwin()) {
+    SwitchToDataSection("", 0);
 
     // Output stubs for dynamically-linked functions
     unsigned j = 1;
     for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
          i != e; ++i, ++j) {
-      O << "\t.symbol_stub\n";
+      SwitchToDataSection(".section __IMPORT,__jump_table,symbol_stubs,"
+                          "self_modifying_code+pure_instructions,5", 0);
       O << "L" << *i << "$stub:\n";
       O << "\t.indirect_symbol " << *i << "\n";
-      O << "\tjmp\t*L" << j << "$lz\n";
-      O << "L" << *i << "$stub_binder:\n";
-      O << "\tpushl\t$L" << j << "$lz\n";
-      O << "\tjmp\tdyld_stub_binding_helper\n";
-      O << "\t.section __DATA, __la_sym_ptr3,lazy_symbol_pointers\n";
-      O << "L" << j << "$lz:\n";
-      O << "\t.indirect_symbol " << *i << "\n";
-      O << "\t.long\tL" << *i << "$stub_binder\n";
+      O << "\thlt ; hlt ; hlt ; hlt ; hlt\n";
     }
 
     O << "\n";
 
-    // Output stubs for link-once variables
-    if (LinkOnceStubs.begin() != LinkOnceStubs.end())
-      O << ".data\n.align 2\n";
-    for (std::set<std::string>::iterator i = LinkOnceStubs.begin(),
-         e = LinkOnceStubs.end(); i != e; ++i) {
-      O << "L" << *i << "$non_lazy_ptr:\n"
-        << "\t.long\t" << *i << '\n';
+    // Output stubs for external and common global variables.
+    if (GVStubs.begin() != GVStubs.end())
+      SwitchToDataSection(
+                    ".section __IMPORT,__pointers,non_lazy_symbol_pointers", 0);
+    for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
+         i != e; ++i) {
+      O << "L" << *i << "$non_lazy_ptr:\n";
+      O << "\t.indirect_symbol " << *i << "\n";
+      O << "\t.long\t0\n";
     }
+
+    // Emit initial debug information.
+    DW.EndModule();
+
+    // Funny Darwin hack: This flag tells the linker that no global symbols
+    // contain code that falls through to other global symbols (e.g. the obvious
+    // implementation of multiple entry points).  If this doesn't occur, the
+    // linker can safely perform dead code stripping.  Since LLVM never
+    // generates code that does this, it is always safe to set.
+    O << "\t.subsections_via_symbols\n";
   }
 
   AsmPrinter::doFinalization(M);
@@ -219,13 +204,13 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
 /// for a MachineFunction to the given output stream, using the given target
 /// machine description.
 ///
-FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,TargetMachine &tm){
-  switch (AsmWriterFlavor) {
-  default:
-    assert(0 && "Unknown asm flavor!");
-  case intel:
-    return new X86IntelAsmPrinter(o, tm);
-  case att:
-    return new X86ATTAsmPrinter(o, tm);
+FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
+                                             X86TargetMachine &tm) {
+  const X86Subtarget *Subtarget = &tm.getSubtarget<X86Subtarget>();
+
+  if (Subtarget->isFlavorIntel()) {
+    return new X86IntelAsmPrinter(o, tm, tm.getTargetAsmInfo());
+  } else {
+    return new X86ATTAsmPrinter(o, tm, tm.getTargetAsmInfo());
   }
 }