[modules] Fix handling of initializers for templated global variables.

For global variables with unordered initialization that are instantiated
within a module, we previously did not emit the global (or its
initializer) at all unless it was used in the importing translation unit
(and sometimes not even then!), leading to misbehavior and link errors.

We now emit the initializer for an instantiated global variable with
unordered initialization with side-effects in a module into every
translation unit that imports the module. This is unfortunate, but
mostly matches the behavior of a non-modular compilation and seems to be
the best that we can reasonably do.

llvm-svn: 353240
diff --git a/clang/lib/Serialization/ASTCommon.h b/clang/lib/Serialization/ASTCommon.h
index 298b471..2678103 100644
--- a/clang/lib/Serialization/ASTCommon.h
+++ b/clang/lib/Serialization/ASTCommon.h
@@ -108,6 +108,21 @@
   }
 }
 
+/// Determine whether the given declaration will be included in the per-module
+/// initializer if it needs to be eagerly handed to the AST consumer. If so, we
+/// should not hand it to the consumer when deserializing it, nor include it in
+/// the list of eagerly deserialized declarations.
+inline bool isPartOfPerModuleInitializer(const Decl *D) {
+  if (isa<ImportDecl>(D))
+    return true;
+  // Template instantiations are notionally in an "instantiation unit" rather
+  // than in any particular translation unit, so they need not be part of any
+  // particular (sub)module's per-module initializer.
+  if (auto *VD = dyn_cast<VarDecl>(D))
+    return !isTemplateInstantiation(VD->getTemplateSpecializationKind());
+  return false;
+}
+
 } // namespace serialization
 
 } // namespace clang
diff --git a/clang/lib/Serialization/ASTReaderDecl.cpp b/clang/lib/Serialization/ASTReaderDecl.cpp
index 1c56cdb..6d02f4d 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -2779,7 +2779,7 @@
 
   // An ImportDecl or VarDecl imported from a module map module will get
   // emitted when we import the relevant module.
-  if (isa<ImportDecl>(D) || isa<VarDecl>(D)) {
+  if (isPartOfPerModuleInitializer(D)) {
     auto *M = D->getImportedOwningModule();
     if (M && M->Kind == Module::ModuleMapModule &&
         Ctx.DeclMustBeEmitted(D))
diff --git a/clang/lib/Serialization/ASTWriterDecl.cpp b/clang/lib/Serialization/ASTWriterDecl.cpp
index bd5191d..ff0c56b 100644
--- a/clang/lib/Serialization/ASTWriterDecl.cpp
+++ b/clang/lib/Serialization/ASTWriterDecl.cpp
@@ -2272,7 +2272,7 @@
   if (isa<FileScopeAsmDecl>(D) || isa<ObjCImplDecl>(D))
     return true;
 
-  if (WritingModule && (isa<VarDecl>(D) || isa<ImportDecl>(D))) {
+  if (WritingModule && isPartOfPerModuleInitializer(D)) {
     // These declarations are part of the module initializer, and are emitted
     // if and when the module is imported, rather than being emitted eagerly.
     return false;