Set the correct anonymous namespace (must be last reopening), and behave correctly in the presence of the ever-annoying linkage specifications.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@130105 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Serialization/ASTReaderDecl.cpp b/lib/Serialization/ASTReaderDecl.cpp
index 3d4e4cd..52eff19 100644
--- a/lib/Serialization/ASTReaderDecl.cpp
+++ b/lib/Serialization/ASTReaderDecl.cpp
@@ -1741,10 +1741,15 @@
 
     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
       NamespaceDecl *Anon = cast<NamespaceDecl>(Reader.GetDecl(Record[Idx++]));
-      if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
-        TU->setAnonymousNamespace(Anon);
-      else
-        cast<NamespaceDecl>(D)->OrigOrAnonNamespace.setPointer(Anon);
+      // Guard against these being loaded out of original order. Don't use
+      // getNextNamespace(), since it tries to access the context and can't in
+      // the middle of deserialization.
+      if (!Anon->NextNamespace) {
+        if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
+          TU->setAnonymousNamespace(Anon);
+        else
+          cast<NamespaceDecl>(D)->OrigOrAnonNamespace.setPointer(Anon);
+      }
       break;
     }
     }
diff --git a/lib/Serialization/ASTWriterDecl.cpp b/lib/Serialization/ASTWriterDecl.cpp
index db72be3..df83f2f 100644
--- a/lib/Serialization/ASTWriterDecl.cpp
+++ b/lib/Serialization/ASTWriterDecl.cpp
@@ -708,11 +708,13 @@
     }
   }
 
-  if (Writer.hasChain() && D->isOriginalNamespace() &&
-      D->isAnonymousNamespace()) {
-    // This is an original anonymous namespace. If its parent is in a previous
-    // PCH (or is the TU), mark that parent for update.
-    Decl *Parent = cast<Decl>(D->getParent()->getPrimaryContext());
+  if (Writer.hasChain() && D->isAnonymousNamespace() && !D->getNextNamespace()){
+    // This is a most recent reopening of the anonymous namespace. If its parent
+    // is in a previous PCH (or is the TU), mark that parent for update, because
+    // the original namespace always points to the latest re-opening of its
+    // anonymous namespace.
+    Decl *Parent = cast<Decl>(
+        D->getParent()->getRedeclContext()->getPrimaryContext());
     if (Parent->getPCHLevel() > 0) {
       ASTWriter::UpdateRecord &Record = Writer.DeclUpdates[Parent];
       Record.push_back(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE);