Index: lib/Sema/SemaLookup.cpp
===================================================================
--- lib/Sema/SemaLookup.cpp	(revision 186060)
+++ lib/Sema/SemaLookup.cpp	(working copy)
@@ -2751,6 +2751,7 @@
     //        namespaces even if they are not visible during an ordinary
     //        lookup (11.4).
     DeclContext::lookup_result R = (*NS)->lookup(Name);
+    llvm::SmallPtrSet<Decl*, 8> VisitedFriendDecls;
     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
          ++I) {
       NamedDecl *D = *I;
@@ -2759,6 +2760,8 @@
       if (D->getIdentifierNamespace() == Decl::IDNS_OrdinaryFriend) {
         bool DeclaredInAssociatedClass = false;
         for (Decl *DI = D; DI; DI = D->getPreviousDecl()) {
+          if (!VisitedFriendDecls.insert(DI))
+            break;
           DeclContext *LexDC = DI->getLexicalDeclContext();
           if (AssociatedClasses.count(cast<CXXRecordDecl>(LexDC))) {
             DeclaredInAssociatedClass = true;
