Mangle static variables with an extra name to distinguish them from non-static variables in the same TU.
Fixes PR5966 for real this time; also reverts r92911, which had a incorrect fix.


git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@94352 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/CodeGen/Mangle.cpp b/lib/CodeGen/Mangle.cpp
index d873cfe..b6bebd0 100644
--- a/lib/CodeGen/Mangle.cpp
+++ b/lib/CodeGen/Mangle.cpp
@@ -171,14 +171,15 @@
       isInExternCSystemHeader(D->getLocation()))
     return false;
 
-  // Variables at global scope are not mangled.
+  // Variables at global scope with non-internal linkage are not mangled
   if (!FD) {
     const DeclContext *DC = D->getDeclContext();
     // Check for extern variable declared locally.
     if (isa<FunctionDecl>(DC) && D->hasLinkage())
       while (!DC->isNamespace() && !DC->isTranslationUnit())
         DC = DC->getParent();
-    if (DC->isTranslationUnit())
+    if (DC->isTranslationUnit() &&
+        D->getLinkage() != NamedDecl::InternalLinkage)
       return false;
   }
 
@@ -199,13 +200,10 @@
     return;
   }
 
-  // <mangled-name> ::= _Z [L] <encoding>
+  // <mangled-name> ::= _Z <encoding>
   //            ::= <data name>
   //            ::= <special-name>
   Out << Prefix;
-  if (D->getLinkage() == NamedDecl::InternalLinkage) // match gcc behavior
-    Out << 'L';
-
   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
     mangleFunctionEncoding(FD);
   else
@@ -419,6 +417,13 @@
     }
 
     if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
+      // We must avoid conflicts between internally- and externally-
+      // linked names in the same TU. This naming convention is the
+      // same as that followed by GCC, though it shouldn't actually matter.
+      if (ND->getLinkage() == NamedDecl::InternalLinkage &&
+          ND->getDeclContext()->isFileContext())
+        Out << 'L';
+
       mangleSourceName(II);
       break;
     }