When emitting a static local variable in C++, handle
the case that the variable already exists.  Partly this is just
protection against people making crazy declarations with custom
asm labels or extern "C" names that intentionally collide with
the manglings of such variables, but the main reason is that we
can actually emit a static local variable twice with the
requirement that it match up.  There may be other cases with
(e.g.) the various nested functions, but the main exemplar is
with constructor variants, where we can be forced into
double-emitting the function body under certain circumstances
like (currently) the presence of virtual bases.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@153723 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/CodeGen/CGDecl.cpp b/lib/CodeGen/CGDecl.cpp
index 970f0b2..d6d6696 100644
--- a/lib/CodeGen/CGDecl.cpp
+++ b/lib/CodeGen/CGDecl.cpp
@@ -184,6 +184,24 @@
     Name = GetStaticDeclName(*this, D, Separator);
 
   llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
+
+  // In C++, there are strange possibilities here involving the
+  // double-emission of constructors and destructors.
+  if (CGM.getLangOpts().CPlusPlus) {
+    llvm::GlobalValue *value = CGM.getModule().getNamedValue(Name);
+    if (value && isa<llvm::GlobalVariable>(value) &&
+        value->getType() ==
+          LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(Ty)))
+      return cast<llvm::GlobalVariable>(value);
+
+    if (value) {
+      CGM.Error(D.getLocation(),
+              "problem emitting static variable: already present as "
+              "different kind of symbol");
+      // Fall through and implicitly give it a uniqued name.
+    }
+  }
+    
   llvm::GlobalVariable *GV =
     new llvm::GlobalVariable(CGM.getModule(), LTy,
                              Ty.isConstant(getContext()), Linkage,