Add debug support for X86/ELF targets (Linux). This allows llvm-gcc4
[oota-llvm.git] / lib / Target / X86 / X86AsmPrinter.cpp
index c366acc2f621e3ccbf97994637d3cd938f0869e9..60316517a829e5edd6302b73ea3f5dd2f28463f5 100644 (file)
 #include "X86AsmPrinter.h"
 #include "X86ATTAsmPrinter.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/Support/CommandLine.h"
+#include "llvm/Target/TargetAsmInfo.h"
+
 using namespace llvm;
 
 Statistic<> llvm::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),
-#ifdef _MSC_VER
-                cl::init(intel)
-#else
-                cl::init(att)
-#endif
-                );
+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;
+  }
 
-/// doInitialization
-bool X86SharedAsmPrinter::doInitialization(Module &M) {
-  PrivateGlobalPrefix = ".L";
-  DefaultTextSection = ".text";
-  DefaultDataSection = ".data";
+  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;
   
-  switch (Subtarget->TargetType) {
-  case X86Subtarget::isDarwin:
-    AlignmentIsInBytes = false;
-    GlobalPrefix = "_";
-    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
-    ConstantPoolSection = "\t.const\n";
-    JumpTableSection = "\t.const\n"; // FIXME: depends on PIC mode
-    LCOMMDirective = "\t.lcomm\t";
-    COMMDirectiveTakesAlignment = false;
-    HasDotTypeDotSizeDirective = false;
-    StaticCtorsSection = ".mod_init_func";
-    StaticDtorsSection = ".mod_term_func";
-    InlineAsmStart = "# InlineAsm Start";
-    InlineAsmEnd = "# InlineAsm End";
+  // 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 X86Subtarget::isCygwin:
-    GlobalPrefix = "_";
-    COMMDirectiveTakesAlignment = false;
-    HasDotTypeDotSizeDirective = false;
-    StaticCtorsSection = "\t.section .ctors,\"aw\"";
-    StaticDtorsSection = "\t.section .dtors,\"aw\"";
+  case StdCall:
+    if (!F->isVarArg()) // Variadic functions do not receive @0 suffix.
+      Name += '@' + utostr_32(Info->getBytesToPopOnReturn());
     break;
-  case X86Subtarget::isWindows:
-    GlobalPrefix = "_";
-    HasDotTypeDotSizeDirective = false;
+  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: break;
+  default:
+    assert(0 && "Unsupported DecorationStyle");
   }
-  
-  if (Subtarget->TargetType == X86Subtarget::isDarwin) {
+}
+
+/// doInitialization
+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);
+  } else if (Subtarget->isTargetELF()) {
     // Emit initial debug information.
     DW.BeginModule(&M);
   }
@@ -107,12 +142,12 @@ 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->hasInternalLinkage() || I->hasWeakLinkage() ||
          I->hasLinkOnceLinkage() ||
-         (Subtarget->TargetType == X86Subtarget::isDarwin && 
+         (Subtarget->isTargetDarwin() && 
           I->hasExternalLinkage() && !I->hasSection()))) {
       if (Size == 0) Size = 1;   // .comm Foo, 0 is undefined, avoid it.
       if (I->hasExternalLinkage()) {
@@ -120,59 +155,77 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
           O << "\t.zerofill __DATA__, __common, " << name << ", "
             << Size << ", " << Align;
       } else {
-        SwitchToDataSection(DefaultDataSection, I);
-        if (LCOMMDirective != NULL) {
+        SwitchToDataSection(TAI->getDataSection(), I);
+        if (TAI->getLCOMMDirective() != NULL) {
           if (I->hasInternalLinkage()) {
-            O << LCOMMDirective << name << "," << Size;
-            if (Subtarget->TargetType == X86Subtarget::isDarwin)
-              O << "," << (AlignmentIsInBytes ? (1 << Align) : Align);
+            O << TAI->getLCOMMDirective() << name << "," << Size;
+            if (Subtarget->isTargetDarwin())
+              O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
           } else
-            O << COMMDirective  << name << "," << Size;
+            O << TAI->getCOMMDirective()  << name << "," << Size;
         } else {
-          if (Subtarget->TargetType != X86Subtarget::isCygwin) {
+          if (!Subtarget->isTargetCygwin()) {
             if (I->hasInternalLinkage())
               O << "\t.local\t" << name << "\n";
           }
-          O << COMMDirective  << name << "," << Size;
-          if (COMMDirectiveTakesAlignment)
-            O << "," << (AlignmentIsInBytes ? (1 << Align) : Align);
+          O << TAI->getCOMMDirective()  << name << "," << Size;
+          if (TAI->getCOMMDirectiveTakesAlignment())
+            O << "," << (TAI->getAlignmentIsInBytes() ? (1 << Align) : Align);
         }
       }
-      O << "\t\t" << CommentString << " " << I->getName() << "\n";
+      O << "\t\t" << TAI->getCommentString() << " " << I->getName() << "\n";
     } else {
       switch (I->getLinkage()) {
       case GlobalValue::LinkOnceLinkage:
       case GlobalValue::WeakLinkage:
-        if (Subtarget->TargetType == X86Subtarget::isDarwin) {
+        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 if (Subtarget->isTargetCygwin()) {
+          std::string SectionName(".section\t.data$linkonce." +
+                                  name +
+                                  ",\"aw\"\n");
+          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\n");
+          SwitchToDataSection(SectionName.c_str(), I);
+          O << "\t.weak " << name << "\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::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(DefaultDataSection, 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;
+          }
+        }
+        SwitchToDataSection(TAI->getDataSection(), I);
         break;
+      }
       default:
         assert(0 && "Unknown linkage type!");
       }
 
       EmitAlignment(Align, I);
-      O << name << ":\t\t\t\t" << CommentString << " " << I->getName()
+      O << name << ":\t\t\t\t" << TAI->getCommentString() << " " << I->getName()
         << "\n";
-      if (HasDotTypeDotSizeDirective)
+      if (TAI->hasDotTypeDotSizeDirective())
         O << "\t.size " << name << ", " << Size << "\n";
 
       EmitGlobalConstant(C);
@@ -180,7 +233,28 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
     }
   }
   
-  if (Subtarget->TargetType == X86Subtarget::isDarwin) {
+  // Output linker support code for dllexported globals
+  if (DLLExportedGVs.begin() != DLLExportedGVs.end()) {
+    SwitchToDataSection(".section .drectve", 0);    
+  }
+
+  for (std::set<std::string>::iterator i = DLLExportedGVs.begin(),
+         e = DLLExportedGVs.end();
+         i != e; ++i) {
+    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
@@ -207,7 +281,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
@@ -216,6 +290,9 @@ 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->isTargetELF()) {
+    // Emit final debug information.
+    DW.EndModule();
   }
 
   AsmPrinter::doFinalization(M);
@@ -227,13 +304,12 @@ bool X86SharedAsmPrinter::doFinalization(Module &M) {
 /// machine description.
 ///
 FunctionPass *llvm::createX86CodePrinterPass(std::ostream &o,
-                                             X86TargetMachine &tm){
-  switch (AsmWriterFlavor) {
-  default:
-    assert(0 && "Unknown asm flavor!");
-  case intel:
-    return new X86IntelAsmPrinter(o, tm);
-  case att:
-    return new X86ATTAsmPrinter(o, tm);
+                                             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());
   }
 }