diff --git a/lib/Serialization/ASTReader.cpp b/lib/Serialization/ASTReader.cpp
index 08bc6b48181d10b6bbd1796b1c2aaec3434ef159..f415573db8083ef4e08b5ac4ce5b6f14ca0fe60d 100644
--- a/lib/Serialization/ASTReader.cpp
+++ b/lib/Serialization/ASTReader.cpp
@@ -5429,13 +5429,15 @@ namespace {
     ASTReader &Reader;
     llvm::SmallVectorImpl<const DeclContext *> &Contexts;
     llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> > &Decls;
+    bool VisitAll;
 
   public:
     DeclContextAllNamesVisitor(ASTReader &Reader,
                                SmallVectorImpl<const DeclContext *> &Contexts,
                                llvm::DenseMap<DeclarationName,
-                                           SmallVector<NamedDecl *, 8> > &Decls)
-      : Reader(Reader), Contexts(Contexts), Decls(Decls) { }
+                                           SmallVector<NamedDecl *, 8> > &Decls,
+                                bool VisitAll)
+      : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
 
     static bool visit(ModuleFile &M, void *UserData) {
       DeclContextAllNamesVisitor *This
@@ -5476,7 +5478,7 @@ namespace {
         }
       }
 
-      return FoundAnything;
+      return FoundAnything && !This->VisitAll;
     }
   };
 }
@@ -5502,7 +5504,8 @@ void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
     }
   }
 
-  DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls);
+  DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
+                                     /*VisitAll=*/DC->isFileContext());
   ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
   ++NumVisibleDeclContextsRead;
 
diff --git a/test/Index/codecompletion-chained.cpp b/test/Index/codecompletion-chained.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..93e832f81ea2c21fae0c3b3d6bc619498ecc26ed
--- /dev/null
+++ b/test/Index/codecompletion-chained.cpp
@@ -0,0 +1,33 @@
+
+// <rdar://12889089>
+
+#ifndef HEADER1
+#define HEADER1
+
+// CHECK-TU: FunctionDecl:{ResultType void}{TypedText foo}
+void foo();
+
+namespace Cake {
+// CHECK-NAMESPACE: FunctionDecl:{ResultType void}{TypedText lie}
+void lie();
+}
+
+#elif !defined(HEADER2)
+#define HEADER2
+
+namespace Cake {
+extern int Baz;
+}
+
+#else
+
+void func() {
+Cake::
+}
+
+#endif
+
+// RUN: c-index-test -write-pch %t1.h.pch %s
+// RUN: c-index-test -write-pch %t2.h.pch %s -include %t1.h
+// RUN: c-index-test -code-completion-at=%s:25:1 %s -include %t2.h | FileCheck -check-prefix=CHECK-TU %s
+// RUN: c-index-test -code-completion-at=%s:25:7 %s -include %t2.h | FileCheck -check-prefix=CHECK-NAMESPACE %s