* Fix one more bug in PIC codegen: extra load is needed for *all*
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
index d7dc70c567aa21a1e8b4e58c72d8a41d36e72280..bea3914fe649be3752c28655937186af58546e7d 100644 (file)
 
 #include "X86AsmPrinter.h"
 #include "X86ATTAsmPrinter.h"
+#include "X86COFF.h"
 #include "X86IntelAsmPrinter.h"
+#include "X86MachineFunctionInfo.h"
 #include "X86Subtarget.h"
+#include "llvm/ADT/StringExtras.h"
+#include "llvm/CallingConv.h"
 #include "llvm/Constants.h"
 #include "llvm/Module.h"
 #include "llvm/Type.h"
 #include "llvm/Assembly/Writer.h"
 #include "llvm/Support/Mangler.h"
 #include "llvm/Target/TargetAsmInfo.h"
+#include "llvm/Target/TargetOptions.h"
 using namespace llvm;
 
-Statistic<> llvm::EmittedInsts("asm-printer",
-                               "Number of machine instrs printed");
+static X86FunctionInfo calculateFunctionInfo(const Function *F,
+                                             const TargetData *TD) {
+  X86FunctionInfo Info;
+  uint64_t Size = 0;
+  
+  switch (F->getCallingConv()) {
+  case CallingConv::X86_StdCall:
+    Info.setDecorationStyle(StdCall);
+    break;
+  case CallingConv::X86_FastCall:
+    Info.setDecorationStyle(FastCall);
+    break;
+  default:
+    return Info;
+  }
+
+  for (Function::const_arg_iterator AI = F->arg_begin(), AE = F->arg_end();
+       AI != AE; ++AI)
+    Size += TD->getTypeSize(AI->getType());
+
+  // Size should be aligned to DWORD boundary
+  Size = ((Size + 3)/4)*4;
+  
+  // We're not supporting tooooo huge arguments :)
+  Info.setBytesToPopOnReturn((unsigned int)Size);
+  return Info;
+}
+
+
+/// decorateName - Query FunctionInfoMap and use this information for various
+/// name decoration.
+void X86SharedAsmPrinter::decorateName(std::string &Name,
+                                       const GlobalValue *GV) {
+  const Function *F = dyn_cast<Function>(GV);
+  if (!F) return;
+
+  // We don't want to decorate non-stdcall or non-fastcall functions right now
+  unsigned CC = F->getCallingConv();
+  if (CC != CallingConv::X86_StdCall && CC != CallingConv::X86_FastCall)
+    return;
+    
+  FMFInfoMap::const_iterator info_item = FunctionInfoMap.find(F);
+
+  const X86FunctionInfo *Info;
+  if (info_item == FunctionInfoMap.end()) {
+    // Calculate apropriate function info and populate map
+    FunctionInfoMap[F] = calculateFunctionInfo(F, TM.getTargetData());
+    Info = &FunctionInfoMap[F];
+  } else {
+    Info = &info_item->second;
+  }
+        
+  switch (Info->getDecorationStyle()) {
+  case None:
+    break;
+  case StdCall:
+    if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
+      Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
+    break;
+  case FastCall:
+    if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
+      Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
+
+    if (Name[0] == '_') {
+      Name[0] = '@';
+    } else {
+      Name = '@' + Name;
+    }    
+    break;
+  default:
+    assert(0 && "Unsupported DecorationStyle");
+  }
+}
 
 /// doInitialization
 bool X86SharedAsmPrinter::doInitialization(Module &M) {
-  if (Subtarget->isTargetDarwin()) {
-    const X86Subtarget *Subtarget = &TM.getSubtarget<X86Subtarget>();
-    if (!Subtarget->is64Bit())
-      X86PICStyle = PICStyle::Stub;
-
+  if (Subtarget->isTargetELF() ||
+      Subtarget->isTargetCygMing() ||
+      Subtarget->isTargetDarwin()) {
     // Emit initial debug information.
     DW.BeginModule(&M);
   }
@@ -48,11 +122,12 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
   // 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()) continue;   // External global require no code
+    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))
@@ -61,20 +136,24 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
     std::string name = Mang->getValueName(I);
     Constant *C = I->getInitializer();
     unsigned Size = TD->getTypeSize(C->getType());
-    unsigned Align = getPreferredAlignmentLog(I);
+    unsigned Align = TD->getPreferredAlignmentLog(I);
 
     if (C->isNullValue() && /* FIXME: Verify correct */
+        !I->hasSection() &&
         (I->hasInternalLinkage() || I->hasWeakLinkage() ||
          I->hasLinkOnceLinkage() ||
          (Subtarget->isTargetDarwin() && 
-          I->hasExternalLinkage() && !I->hasSection()))) {
+          I->hasExternalLinkage()))) {
       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 {
-        SwitchToDataSection(TAI->getDataSection(), I);
+        if (!NoZerosInBSS && TAI->getBSSSection())
+          SwitchToDataSection(TAI->getBSSSection(), I);
+        else
+          SwitchToDataSection(TAI->getDataSection(), I);
         if (TAI->getLCOMMDirective() != NULL) {
           if (I->hasInternalLinkage()) {
             O << TAI->getLCOMMDirective() << name << "," << Size;
@@ -83,7 +162,7 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
           } else
             O << TAI->getCOMMDirective()  << name << "," << Size;
         } else {
-          if (!Subtarget->isTargetCygwin()) {
+          if (!Subtarget->isTargetCygMing()) {
             if (I->hasInternalLinkage())
               O << "\t.local\t" << name << "\n";
           }
@@ -101,12 +180,19 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
           O << "\t.globl " << name << "\n"
             << "\t.weak_definition " << name << "\n";
           SwitchToDataSection(".section __DATA,__const_coal,coalesced", I);
-        } else if (Subtarget->isTargetCygwin()) {
-          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\"\n"
-            << "\t.weak " << name << "\n";
+        } else if (Subtarget->isTargetCygMing()) {
+          std::string SectionName(".section\t.data$linkonce." +
+                                  name +
+                                  ",\"aw\"");
+          SwitchToDataSection(SectionName.c_str(), I);
+          O << "\t.globl " << name << "\n"
+            << "\t.linkonce same_size\n";
         } else {
-          O << "\t.section\t.llvm.linkonce.d." << name << ",\"aw\",@progbits\n"
-            << "\t.weak " << name << "\n";
+          std::string SectionName("\t.section\t.llvm.linkonce.d." +
+                                  name +
+                                  ",\"aw\",@progbits");
+          SwitchToDataSection(SectionName.c_str(), I);
+          O << "\t.weak " << name << "\n";
         }
         break;
       case GlobalValue::AppendingLinkage:
@@ -119,9 +205,37 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
         // If external or appending, declare as a global symbol
         O << "\t.globl " << name << "\n";
         // FALL THROUGH
-      case GlobalValue::InternalLinkage:
-        SwitchToDataSection(TAI->getDataSection(), I);
+      case GlobalValue::InternalLinkage: {
+        if (I->isConstant()) {
+          const ConstantArray *CVA = dyn_cast<ConstantArray>(C);
+          if (TAI->getCStringSection() && CVA && CVA->isCString()) {
+            SwitchToDataSection(TAI->getCStringSection(), I);
+            break;
+          }
+        }
+        // FIXME: special handling for ".ctors" & ".dtors" sections
+        if (I->hasSection() &&
+            (I->getSection() == ".ctors" ||
+             I->getSection() == ".dtors")) {
+          std::string SectionName = ".section " + I->getSection();
+          
+          if (Subtarget->isTargetCygMing()) {
+            SectionName += ",\"aw\"";
+          } else {
+            assert(!Subtarget->isTargetDarwin());
+            SectionName += ",\"aw\",@progbits";
+          }
+
+          SwitchToDataSection(SectionName.c_str());
+        } else {
+          if (C->isNullValue() && !NoZerosInBSS && TAI->getBSSSection())
+            SwitchToDataSection(TAI->getBSSSection(), I);
+          else
+            SwitchToDataSection(TAI->getDataSection(), I);
+        }
+        
         break;
+      }
       default:
         assert(0 && "Unknown linkage type!");
       }
@@ -131,15 +245,26 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
         << "\n";
       if (TAI->hasDotTypeDotSizeDirective())
         O << "\t.size " << name << ", " << Size << "\n";
+      // If the initializer is a extern weak symbol, remember to emit the weak
+      // reference!
+      if (const GlobalValue *GV = dyn_cast<GlobalValue>(C))
+        if (GV->hasExternalWeakLinkage())
+          ExtWeakSymbols.insert(GV);
 
       EmitGlobalConstant(C);
       O << '\n';
     }
+    if (I->hasHiddenVisibility())
+      if (const char *Directive = TAI->getHiddenDirective())
+        O << Directive << name << "\n";
+    
+    if (Subtarget->isTargetELF())
+      O << "\t.type " << name << ",@object\n";
   }
   
   // Output linker support code for dllexported globals
   if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
-    SwitchToDataSection(".section .drectve", 0);    
+    SwitchToDataSection(".section .drectve");
   }
 
   for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
@@ -149,7 +274,7 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
   }    
 
   if (DLLExportedFns.begin() != DLLExportedFns.end()) {
-    SwitchToDataSection(".section .drectve", 0);    
+    SwitchToDataSection(".section .drectve");
   }
 
   for (std::set<std::string>::iterator i = DLLExportedFns.begin(),
@@ -157,9 +282,9 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
          i != e; ++i) {
     O << "\t.ascii \" -export:" << *i << "\"\n";
   }    
+
   if (Subtarget->isTargetDarwin()) {
-    SwitchToDataSection("", 0);
+    SwitchToDataSection("");
 
     // Output stubs for dynamically-linked functions
     unsigned j = 1;
@@ -177,7 +302,7 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
     // Output stubs for external and common global variables.
     if (GVStubs.begin() != GVStubs.end())
       SwitchToDataSection(
-                    ".section __IMPORT,__pointers,non_lazy_symbol_pointers", 0);
+                    ".section __IMPORT,__pointers,non_lazy_symbol_pointers");
     for (std::set<std::string>::iterator i = GVStubs.begin(), e = GVStubs.end();
          i != e; ++i) {
       O << "L" << *i << "$non_lazy_ptr:\n";
@@ -185,7 +310,7 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
       O << "\t.long\t0\n";
     }
 
-    // Emit initial debug information.
+    // Emit final debug information.
     DW.EndModule();
 
     // Funny Darwin hack: This flag tells the linker that no global symbols
@@ -194,6 +319,21 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
     // 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";
+  } else if (Subtarget->isTargetCygMing()) {
+    // Emit type information for external functions
+    for (std::set<std::string>::iterator i = FnStubs.begin(), e = FnStubs.end();
+         i != e; ++i) {
+      O << "\t.def\t " << *i
+        << ";\t.scl\t" << COFF::C_EXT
+        << ";\t.type\t" << (COFF::DT_FCN << COFF::N_BTSHFT)
+        << ";\t.endef\n";
+    }
+    
+    // Emit final debug information.
+    DW.EndModule();    
+  } else if (Subtarget->isTargetELF()) {
+    // Emit final debug information.
+    DW.EndModule();
   }
 
   AsmPrinter::doFinalization(M);