1 //===--- FindTarget.cpp - What does an AST node refer to? -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "FindTarget.h"
10 #include "AST.h"
11 #include "HeuristicResolver.h"
12 #include "support/Logger.h"
13 #include "clang/AST/ASTTypeTraits.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclBase.h"
16 #include "clang/AST/DeclCXX.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/DeclVisitor.h"
19 #include "clang/AST/DeclarationName.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/ExprConcepts.h"
23 #include "clang/AST/ExprObjC.h"
24 #include "clang/AST/NestedNameSpecifier.h"
25 #include "clang/AST/PrettyPrinter.h"
26 #include "clang/AST/RecursiveASTVisitor.h"
27 #include "clang/AST/StmtVisitor.h"
28 #include "clang/AST/TemplateBase.h"
29 #include "clang/AST/Type.h"
30 #include "clang/AST/TypeLoc.h"
31 #include "clang/AST/TypeLocVisitor.h"
32 #include "clang/AST/TypeVisitor.h"
33 #include "clang/Basic/LangOptions.h"
34 #include "clang/Basic/SourceLocation.h"
35 #include "clang/Basic/SourceManager.h"
36 #include "clang/Basic/Specifiers.h"
37 #include "llvm/ADT/STLExtras.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/StringExtras.h"
40 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Compiler.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include <iterator>
44 #include <string>
45 #include <utility>
46 #include <vector>
47 
48 namespace clang {
49 namespace clangd {
50 namespace {
51 
52 LLVM_ATTRIBUTE_UNUSED std::string nodeToString(const DynTypedNode &N) {
53   std::string S = std::string(N.getNodeKind().asStringRef());
54   {
55     llvm::raw_string_ostream OS(S);
56     OS << ": ";
57     N.print(OS, PrintingPolicy(LangOptions()));
58   }
59   std::replace(S.begin(), S.end(), '\n', ' ');
60   return S;
61 }
62 
63 const NamedDecl *getTemplatePattern(const NamedDecl *D) {
64   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(D)) {
65     if (const auto *Result = CRD->getTemplateInstantiationPattern())
66       return Result;
67     // getTemplateInstantiationPattern returns null if the Specialization is
68     // incomplete (e.g. the type didn't need to be complete), fall back to the
69     // primary template.
70     if (CRD->getTemplateSpecializationKind() == TSK_Undeclared)
71       if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(CRD))
72         return Spec->getSpecializedTemplate()->getTemplatedDecl();
73   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
74     return FD->getTemplateInstantiationPattern();
75   } else if (auto *VD = dyn_cast<VarDecl>(D)) {
76     // Hmm: getTIP returns its arg if it's not an instantiation?!
77     VarDecl *T = VD->getTemplateInstantiationPattern();
78     return (T == D) ? nullptr : T;
79   } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
80     return ED->getInstantiatedFromMemberEnum();
81   } else if (isa<FieldDecl>(D) || isa<TypedefNameDecl>(D)) {
82     if (const auto *Parent = llvm::dyn_cast<NamedDecl>(D->getDeclContext()))
83       if (const DeclContext *ParentPat =
84               dyn_cast_or_null<DeclContext>(getTemplatePattern(Parent)))
85         for (const NamedDecl *BaseND : ParentPat->lookup(D->getDeclName()))
86           if (!BaseND->isImplicit() && BaseND->getKind() == D->getKind())
87             return BaseND;
88   } else if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
89     if (const auto *ED = dyn_cast<EnumDecl>(ECD->getDeclContext())) {
90       if (const EnumDecl *Pattern = ED->getInstantiatedFromMemberEnum()) {
91         for (const NamedDecl *BaseECD : Pattern->lookup(ECD->getDeclName()))
92           return BaseECD;
93       }
94     }
95   }
96   return nullptr;
97 }
98 
99 // Returns true if the `TypedefNameDecl` should not be reported.
100 bool shouldSkipTypedef(const TypedefNameDecl *TD) {
101   // These should be treated as keywords rather than decls - the typedef is an
102   // odd implementation detail.
103   if (TD == TD->getASTContext().getObjCInstanceTypeDecl() ||
104       TD == TD->getASTContext().getObjCIdDecl())
105     return true;
106   return false;
107 }
108 
109 // TargetFinder locates the entities that an AST node refers to.
110 //
111 // Typically this is (possibly) one declaration and (possibly) one type, but
112 // may be more:
113 //  - for ambiguous nodes like OverloadExpr
114 //  - if we want to include e.g. both typedefs and the underlying type
115 //
116 // This is organized as a set of mutually recursive helpers for particular node
117 // types, but for most nodes this is a short walk rather than a deep traversal.
118 //
119 // It's tempting to do e.g. typedef resolution as a second normalization step,
120 // after finding the 'primary' decl etc. But we do this monolithically instead
121 // because:
122 //  - normalization may require these traversals again (e.g. unwrapping a
123 //    typedef reveals a decltype which must be traversed)
124 //  - it doesn't simplify that much, e.g. the first stage must still be able
125 //    to yield multiple decls to handle OverloadExpr
126 //  - there are cases where it's required for correctness. e.g:
127 //      template<class X> using pvec = vector<x*>; pvec<int> x;
128 //    There's no Decl `pvec<int>`, we must choose `pvec<X>` or `vector<int*>`
129 //    and both are lossy. We must know upfront what the caller ultimately wants.
130 //
131 // FIXME: improve common dependent scope using name lookup in primary templates.
132 // We currently handle several dependent constructs, but some others remain to
133 // be handled:
134 //  - UnresolvedUsingTypenameDecl
135 struct TargetFinder {
136   using RelSet = DeclRelationSet;
137   using Rel = DeclRelation;
138 
139 private:
140   const HeuristicResolver *Resolver;
141   llvm::SmallDenseMap<const NamedDecl *,
142                       std::pair<RelSet, /*InsertionOrder*/ size_t>>
143       Decls;
144   llvm::SmallDenseMap<const Decl *, RelSet> Seen;
145   RelSet Flags;
146 
147   template <typename T> void debug(T &Node, RelSet Flags) {
148     dlog("visit [{0}] {1}", Flags, nodeToString(DynTypedNode::create(Node)));
149   }
150 
151   void report(const NamedDecl *D, RelSet Flags) {
152     dlog("--> [{0}] {1}", Flags, nodeToString(DynTypedNode::create(*D)));
153     auto It = Decls.try_emplace(D, std::make_pair(Flags, Decls.size()));
154     // If already exists, update the flags.
155     if (!It.second)
156       It.first->second.first |= Flags;
157   }
158 
159 public:
160   TargetFinder(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
161 
162   llvm::SmallVector<std::pair<const NamedDecl *, RelSet>, 1> takeDecls() const {
163     using ValTy = std::pair<const NamedDecl *, RelSet>;
164     llvm::SmallVector<ValTy, 1> Result;
165     Result.resize(Decls.size());
166     for (const auto &Elem : Decls)
167       Result[Elem.second.second] = {Elem.first, Elem.second.first};
168     return Result;
169   }
170 
171   void add(const Decl *Dcl, RelSet Flags) {
172     const NamedDecl *D = llvm::dyn_cast_or_null<NamedDecl>(Dcl);
173     if (!D)
174       return;
175     debug(*D, Flags);
176 
177     // Avoid recursion (which can arise in the presence of heuristic
178     // resolution of dependent names) by exiting early if we have
179     // already seen this decl with all flags in Flags.
180     auto Res = Seen.try_emplace(D);
181     if (!Res.second && Res.first->second.contains(Flags))
182       return;
183     Res.first->second |= Flags;
184 
185     if (const UsingDirectiveDecl *UDD = llvm::dyn_cast<UsingDirectiveDecl>(D))
186       D = UDD->getNominatedNamespaceAsWritten();
187 
188     if (const TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D)) {
189       add(TND->getUnderlyingType(), Flags | Rel::Underlying);
190       Flags |= Rel::Alias; // continue with the alias.
191     } else if (const UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
192       // no Underlying as this is a non-renaming alias.
193       for (const UsingShadowDecl *S : UD->shadows())
194         add(S->getUnderlyingDecl(), Flags);
195       Flags |= Rel::Alias; // continue with the alias.
196     } else if (const UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D)) {
197       add(UED->getEnumDecl(), Flags);
198       Flags |= Rel::Alias; // continue with the alias.
199     } else if (const auto *NAD = dyn_cast<NamespaceAliasDecl>(D)) {
200       add(NAD->getUnderlyingDecl(), Flags | Rel::Underlying);
201       Flags |= Rel::Alias; // continue with the alias
202     } else if (const UnresolvedUsingValueDecl *UUVD =
203                    dyn_cast<UnresolvedUsingValueDecl>(D)) {
204       if (Resolver) {
205         for (const NamedDecl *Target : Resolver->resolveUsingValueDecl(UUVD)) {
206           add(Target, Flags); // no Underlying as this is a non-renaming alias
207         }
208       }
209       Flags |= Rel::Alias; // continue with the alias
210     } else if (const UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) {
211       // Include the Introducing decl, but don't traverse it. This may end up
212       // including *all* shadows, which we don't want.
213       report(USD->getIntroducer(), Flags | Rel::Alias);
214       // Shadow decls are synthetic and not themselves interesting.
215       // Record the underlying decl instead, if allowed.
216       D = USD->getTargetDecl();
217     } else if (const auto *DG = dyn_cast<CXXDeductionGuideDecl>(D)) {
218       D = DG->getDeducedTemplate();
219     } else if (const ObjCImplementationDecl *IID =
220                    dyn_cast<ObjCImplementationDecl>(D)) {
221       // Treat ObjC{Interface,Implementation}Decl as if they were a decl/def
222       // pair as long as the interface isn't implicit.
223       if (const auto *CID = IID->getClassInterface())
224         if (const auto *DD = CID->getDefinition())
225           if (!DD->isImplicitInterfaceDecl())
226             D = DD;
227     } else if (const ObjCCategoryImplDecl *CID =
228                    dyn_cast<ObjCCategoryImplDecl>(D)) {
229       // Treat ObjC{Category,CategoryImpl}Decl as if they were a decl/def pair.
230       D = CID->getCategoryDecl();
231     }
232     if (!D)
233       return;
234 
235     if (const Decl *Pat = getTemplatePattern(D)) {
236       assert(Pat != D);
237       add(Pat, Flags | Rel::TemplatePattern);
238       // Now continue with the instantiation.
239       Flags |= Rel::TemplateInstantiation;
240     }
241 
242     report(D, Flags);
243   }
244 
245   void add(const Stmt *S, RelSet Flags) {
246     if (!S)
247       return;
248     debug(*S, Flags);
249     struct Visitor : public ConstStmtVisitor<Visitor> {
250       TargetFinder &Outer;
251       RelSet Flags;
252       Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
253 
254       void VisitCallExpr(const CallExpr *CE) {
255         Outer.add(CE->getCalleeDecl(), Flags);
256       }
257       void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
258         Outer.add(E->getNamedConcept(), Flags);
259       }
260       void VisitDeclRefExpr(const DeclRefExpr *DRE) {
261         const Decl *D = DRE->getDecl();
262         // UsingShadowDecl allows us to record the UsingDecl.
263         // getFoundDecl() returns the wrong thing in other cases (templates).
264         if (auto *USD = llvm::dyn_cast<UsingShadowDecl>(DRE->getFoundDecl()))
265           D = USD;
266         Outer.add(D, Flags);
267       }
268       void VisitMemberExpr(const MemberExpr *ME) {
269         const Decl *D = ME->getMemberDecl();
270         if (auto *USD =
271                 llvm::dyn_cast<UsingShadowDecl>(ME->getFoundDecl().getDecl()))
272           D = USD;
273         Outer.add(D, Flags);
274       }
275       void VisitOverloadExpr(const OverloadExpr *OE) {
276         for (auto *D : OE->decls())
277           Outer.add(D, Flags);
278       }
279       void VisitSizeOfPackExpr(const SizeOfPackExpr *SE) {
280         Outer.add(SE->getPack(), Flags);
281       }
282       void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
283         Outer.add(CCE->getConstructor(), Flags);
284       }
285       void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) {
286         for (const DesignatedInitExpr::Designator &D :
287              llvm::reverse(DIE->designators()))
288           if (D.isFieldDesignator()) {
289             Outer.add(D.getField(), Flags);
290             // We don't know which designator was intended, we assume the outer.
291             break;
292           }
293       }
294       void VisitGotoStmt(const GotoStmt *Goto) {
295         if (auto *LabelDecl = Goto->getLabel())
296           Outer.add(LabelDecl, Flags);
297       }
298       void VisitLabelStmt(const LabelStmt *Label) {
299         if (auto *LabelDecl = Label->getDecl())
300           Outer.add(LabelDecl, Flags);
301       }
302       void
303       VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
304         if (Outer.Resolver) {
305           for (const NamedDecl *D : Outer.Resolver->resolveMemberExpr(E)) {
306             Outer.add(D, Flags);
307           }
308         }
309       }
310       void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
311         if (Outer.Resolver) {
312           for (const NamedDecl *D : Outer.Resolver->resolveDeclRefExpr(E)) {
313             Outer.add(D, Flags);
314           }
315         }
316       }
317       void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
318         Outer.add(OIRE->getDecl(), Flags);
319       }
320       void VisitObjCMessageExpr(const ObjCMessageExpr *OME) {
321         Outer.add(OME->getMethodDecl(), Flags);
322       }
323       void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *OPRE) {
324         if (OPRE->isExplicitProperty())
325           Outer.add(OPRE->getExplicitProperty(), Flags);
326         else {
327           if (OPRE->isMessagingGetter())
328             Outer.add(OPRE->getImplicitPropertyGetter(), Flags);
329           if (OPRE->isMessagingSetter())
330             Outer.add(OPRE->getImplicitPropertySetter(), Flags);
331         }
332       }
333       void VisitObjCProtocolExpr(const ObjCProtocolExpr *OPE) {
334         Outer.add(OPE->getProtocol(), Flags);
335       }
336       void VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) {
337         Outer.add(OVE->getSourceExpr(), Flags);
338       }
339       void VisitPseudoObjectExpr(const PseudoObjectExpr *POE) {
340         Outer.add(POE->getSyntacticForm(), Flags);
341       }
342       void VisitCXXNewExpr(const CXXNewExpr *CNE) {
343         Outer.add(CNE->getOperatorNew(), Flags);
344       }
345       void VisitCXXDeleteExpr(const CXXDeleteExpr *CDE) {
346         Outer.add(CDE->getOperatorDelete(), Flags);
347       }
348     };
349     Visitor(*this, Flags).Visit(S);
350   }
351 
352   void add(QualType T, RelSet Flags) {
353     if (T.isNull())
354       return;
355     debug(T, Flags);
356     struct Visitor : public TypeVisitor<Visitor> {
357       TargetFinder &Outer;
358       RelSet Flags;
359       Visitor(TargetFinder &Outer, RelSet Flags) : Outer(Outer), Flags(Flags) {}
360 
361       void VisitTagType(const TagType *TT) {
362         Outer.add(TT->getAsTagDecl(), Flags);
363       }
364 
365       void VisitElaboratedType(const ElaboratedType *ET) {
366         Outer.add(ET->desugar(), Flags);
367       }
368 
369       void VisitUsingType(const UsingType *ET) {
370         Outer.add(ET->getFoundDecl(), Flags);
371       }
372 
373       void VisitInjectedClassNameType(const InjectedClassNameType *ICNT) {
374         Outer.add(ICNT->getDecl(), Flags);
375       }
376 
377       void VisitDecltypeType(const DecltypeType *DTT) {
378         Outer.add(DTT->getUnderlyingType(), Flags | Rel::Underlying);
379       }
380       void VisitDeducedType(const DeducedType *DT) {
381         // FIXME: In practice this doesn't work: the AutoType you find inside
382         // TypeLoc never has a deduced type. https://llvm.org/PR42914
383         Outer.add(DT->getDeducedType(), Flags);
384       }
385       void VisitDeducedTemplateSpecializationType(
386           const DeducedTemplateSpecializationType *DTST) {
387         if (const auto *USD = DTST->getTemplateName().getAsUsingShadowDecl())
388           Outer.add(USD, Flags);
389 
390         // FIXME: This is a workaround for https://llvm.org/PR42914,
391         // which is causing DTST->getDeducedType() to be empty. We
392         // fall back to the template pattern and miss the instantiation
393         // even when it's known in principle. Once that bug is fixed,
394         // the following code can be removed (the existing handling in
395         // VisitDeducedType() is sufficient).
396         if (auto *TD = DTST->getTemplateName().getAsTemplateDecl())
397           Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
398       }
399       void VisitDependentNameType(const DependentNameType *DNT) {
400         if (Outer.Resolver) {
401           for (const NamedDecl *ND :
402                Outer.Resolver->resolveDependentNameType(DNT)) {
403             Outer.add(ND, Flags);
404           }
405         }
406       }
407       void VisitDependentTemplateSpecializationType(
408           const DependentTemplateSpecializationType *DTST) {
409         if (Outer.Resolver) {
410           for (const NamedDecl *ND :
411                Outer.Resolver->resolveTemplateSpecializationType(DTST)) {
412             Outer.add(ND, Flags);
413           }
414         }
415       }
416       void VisitTypedefType(const TypedefType *TT) {
417         if (shouldSkipTypedef(TT->getDecl()))
418           return;
419         Outer.add(TT->getDecl(), Flags);
420       }
421       void
422       VisitTemplateSpecializationType(const TemplateSpecializationType *TST) {
423         // Have to handle these case-by-case.
424 
425         if (const auto *UTN = TST->getTemplateName().getAsUsingShadowDecl())
426           Outer.add(UTN, Flags);
427 
428         // templated type aliases: there's no specialized/instantiated using
429         // decl to point to. So try to find a decl for the underlying type
430         // (after substitution), and failing that point to the (templated) using
431         // decl.
432         if (TST->isTypeAlias()) {
433           Outer.add(TST->getAliasedType(), Flags | Rel::Underlying);
434           // Don't *traverse* the alias, which would result in traversing the
435           // template of the underlying type.
436           Outer.report(
437               TST->getTemplateName().getAsTemplateDecl()->getTemplatedDecl(),
438               Flags | Rel::Alias | Rel::TemplatePattern);
439         }
440         // specializations of template template parameters aren't instantiated
441         // into decls, so they must refer to the parameter itself.
442         else if (const auto *Parm =
443                      llvm::dyn_cast_or_null<TemplateTemplateParmDecl>(
444                          TST->getTemplateName().getAsTemplateDecl()))
445           Outer.add(Parm, Flags);
446         // class template specializations have a (specialized) CXXRecordDecl.
447         else if (const CXXRecordDecl *RD = TST->getAsCXXRecordDecl())
448           Outer.add(RD, Flags); // add(Decl) will despecialize if needed.
449         else {
450           // fallback: the (un-specialized) declaration from primary template.
451           if (auto *TD = TST->getTemplateName().getAsTemplateDecl())
452             Outer.add(TD->getTemplatedDecl(), Flags | Rel::TemplatePattern);
453         }
454       }
455       void VisitTemplateTypeParmType(const TemplateTypeParmType *TTPT) {
456         Outer.add(TTPT->getDecl(), Flags);
457       }
458       void VisitObjCInterfaceType(const ObjCInterfaceType *OIT) {
459         Outer.add(OIT->getDecl(), Flags);
460       }
461     };
462     Visitor(*this, Flags).Visit(T.getTypePtr());
463   }
464 
465   void add(const NestedNameSpecifier *NNS, RelSet Flags) {
466     if (!NNS)
467       return;
468     debug(*NNS, Flags);
469     switch (NNS->getKind()) {
470     case NestedNameSpecifier::Namespace:
471       add(NNS->getAsNamespace(), Flags);
472       return;
473     case NestedNameSpecifier::NamespaceAlias:
474       add(NNS->getAsNamespaceAlias(), Flags);
475       return;
476     case NestedNameSpecifier::Identifier:
477       if (Resolver) {
478         add(QualType(Resolver->resolveNestedNameSpecifierToType(NNS), 0),
479             Flags);
480       }
481       return;
482     case NestedNameSpecifier::TypeSpec:
483     case NestedNameSpecifier::TypeSpecWithTemplate:
484       add(QualType(NNS->getAsType(), 0), Flags);
485       return;
486     case NestedNameSpecifier::Global:
487       // This should be TUDecl, but we can't get a pointer to it!
488       return;
489     case NestedNameSpecifier::Super:
490       add(NNS->getAsRecordDecl(), Flags);
491       return;
492     }
493     llvm_unreachable("unhandled NestedNameSpecifier::SpecifierKind");
494   }
495 
496   void add(const CXXCtorInitializer *CCI, RelSet Flags) {
497     if (!CCI)
498       return;
499     debug(*CCI, Flags);
500 
501     if (CCI->isAnyMemberInitializer())
502       add(CCI->getAnyMember(), Flags);
503     // Constructor calls contain a TypeLoc node, so we don't handle them here.
504   }
505 
506   void add(const TemplateArgument &Arg, RelSet Flags) {
507     // Only used for template template arguments.
508     // For type and non-type template arguments, SelectionTree
509     // will hit a more specific node (e.g. a TypeLoc or a
510     // DeclRefExpr).
511     if (Arg.getKind() == TemplateArgument::Template ||
512         Arg.getKind() == TemplateArgument::TemplateExpansion) {
513       if (TemplateDecl *TD =
514               Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()) {
515         report(TD, Flags);
516       }
517       if (const auto *USD =
518               Arg.getAsTemplateOrTemplatePattern().getAsUsingShadowDecl())
519         add(USD, Flags);
520     }
521   }
522 };
523 
524 } // namespace
525 
526 llvm::SmallVector<std::pair<const NamedDecl *, DeclRelationSet>, 1>
527 allTargetDecls(const DynTypedNode &N, const HeuristicResolver *Resolver) {
528   dlog("allTargetDecls({0})", nodeToString(N));
529   TargetFinder Finder(Resolver);
530   DeclRelationSet Flags;
531   if (const Decl *D = N.get<Decl>())
532     Finder.add(D, Flags);
533   else if (const Stmt *S = N.get<Stmt>())
534     Finder.add(S, Flags);
535   else if (const NestedNameSpecifierLoc *NNSL = N.get<NestedNameSpecifierLoc>())
536     Finder.add(NNSL->getNestedNameSpecifier(), Flags);
537   else if (const NestedNameSpecifier *NNS = N.get<NestedNameSpecifier>())
538     Finder.add(NNS, Flags);
539   else if (const TypeLoc *TL = N.get<TypeLoc>())
540     Finder.add(TL->getType(), Flags);
541   else if (const QualType *QT = N.get<QualType>())
542     Finder.add(*QT, Flags);
543   else if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>())
544     Finder.add(CCI, Flags);
545   else if (const TemplateArgumentLoc *TAL = N.get<TemplateArgumentLoc>())
546     Finder.add(TAL->getArgument(), Flags);
547   else if (const CXXBaseSpecifier *CBS = N.get<CXXBaseSpecifier>())
548     Finder.add(CBS->getTypeSourceInfo()->getType(), Flags);
549   else if (const ObjCProtocolLoc *PL = N.get<ObjCProtocolLoc>())
550     Finder.add(PL->getProtocol(), Flags);
551   return Finder.takeDecls();
552 }
553 
554 llvm::SmallVector<const NamedDecl *, 1>
555 targetDecl(const DynTypedNode &N, DeclRelationSet Mask,
556            const HeuristicResolver *Resolver) {
557   llvm::SmallVector<const NamedDecl *, 1> Result;
558   for (const auto &Entry : allTargetDecls(N, Resolver)) {
559     if (!(Entry.second & ~Mask))
560       Result.push_back(Entry.first);
561   }
562   return Result;
563 }
564 
565 llvm::SmallVector<const NamedDecl *, 1>
566 explicitReferenceTargets(DynTypedNode N, DeclRelationSet Mask,
567                          const HeuristicResolver *Resolver) {
568   assert(!(Mask & (DeclRelation::TemplatePattern |
569                    DeclRelation::TemplateInstantiation)) &&
570          "explicitReferenceTargets handles templates on its own");
571   auto Decls = allTargetDecls(N, Resolver);
572 
573   // We prefer to return template instantiation, but fallback to template
574   // pattern if instantiation is not available.
575   Mask |= DeclRelation::TemplatePattern | DeclRelation::TemplateInstantiation;
576 
577   llvm::SmallVector<const NamedDecl *, 1> TemplatePatterns;
578   llvm::SmallVector<const NamedDecl *, 1> Targets;
579   bool SeenTemplateInstantiations = false;
580   for (auto &D : Decls) {
581     if (D.second & ~Mask)
582       continue;
583     if (D.second & DeclRelation::TemplatePattern) {
584       TemplatePatterns.push_back(D.first);
585       continue;
586     }
587     if (D.second & DeclRelation::TemplateInstantiation)
588       SeenTemplateInstantiations = true;
589     Targets.push_back(D.first);
590   }
591   if (!SeenTemplateInstantiations)
592     Targets.insert(Targets.end(), TemplatePatterns.begin(),
593                    TemplatePatterns.end());
594   return Targets;
595 }
596 
597 namespace {
598 llvm::SmallVector<ReferenceLoc> refInDecl(const Decl *D,
599                                           const HeuristicResolver *Resolver) {
600   struct Visitor : ConstDeclVisitor<Visitor> {
601     Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
602 
603     const HeuristicResolver *Resolver;
604     llvm::SmallVector<ReferenceLoc> Refs;
605 
606     void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
607       // We want to keep it as non-declaration references, as the
608       // "using namespace" declaration doesn't have a name.
609       Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
610                                   D->getIdentLocation(),
611                                   /*IsDecl=*/false,
612                                   {D->getNominatedNamespaceAsWritten()}});
613     }
614 
615     void VisitUsingDecl(const UsingDecl *D) {
616       // "using ns::identifier;" is a non-declaration reference.
617       Refs.push_back(ReferenceLoc{
618           D->getQualifierLoc(), D->getLocation(), /*IsDecl=*/false,
619           explicitReferenceTargets(DynTypedNode::create(*D),
620                                    DeclRelation::Underlying, Resolver)});
621     }
622 
623     void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
624       // For namespace alias, "namespace Foo = Target;", we add two references.
625       // Add a declaration reference for Foo.
626       VisitNamedDecl(D);
627       // Add a non-declaration reference for Target.
628       Refs.push_back(ReferenceLoc{D->getQualifierLoc(),
629                                   D->getTargetNameLoc(),
630                                   /*IsDecl=*/false,
631                                   {D->getAliasedNamespace()}});
632     }
633 
634     void VisitNamedDecl(const NamedDecl *ND) {
635       // We choose to ignore {Class, Function, Var, TypeAlias}TemplateDecls. As
636       // as their underlying decls, covering the same range, will be visited.
637       if (llvm::isa<ClassTemplateDecl>(ND) ||
638           llvm::isa<FunctionTemplateDecl>(ND) ||
639           llvm::isa<VarTemplateDecl>(ND) ||
640           llvm::isa<TypeAliasTemplateDecl>(ND))
641         return;
642       // FIXME: decide on how to surface destructors when we need them.
643       if (llvm::isa<CXXDestructorDecl>(ND))
644         return;
645       // Filter anonymous decls, name location will point outside the name token
646       // and the clients are not prepared to handle that.
647       if (ND->getDeclName().isIdentifier() &&
648           !ND->getDeclName().getAsIdentifierInfo())
649         return;
650       Refs.push_back(ReferenceLoc{getQualifierLoc(*ND),
651                                   ND->getLocation(),
652                                   /*IsDecl=*/true,
653                                   {ND}});
654     }
655 
656     void VisitCXXDeductionGuideDecl(const CXXDeductionGuideDecl *DG) {
657       // The class template name in a deduction guide targets the class
658       // template.
659       Refs.push_back(ReferenceLoc{DG->getQualifierLoc(),
660                                   DG->getNameInfo().getLoc(),
661                                   /*IsDecl=*/false,
662                                   {DG->getDeducedTemplate()}});
663     }
664 
665     void VisitObjCMethodDecl(const ObjCMethodDecl *OMD) {
666       // The name may have several tokens, we can only report the first.
667       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
668                                   OMD->getSelectorStartLoc(),
669                                   /*IsDecl=*/true,
670                                   {OMD}});
671     }
672 
673     void VisitObjCCategoryDecl(const ObjCCategoryDecl *OCD) {
674       // getLocation is the extended class's location, not the category's.
675       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
676                                   OCD->getLocation(),
677                                   /*IsDecl=*/false,
678                                   {OCD->getClassInterface()}});
679       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
680                                   OCD->getCategoryNameLoc(),
681                                   /*IsDecl=*/true,
682                                   {OCD}});
683     }
684 
685     void VisitObjCCategoryImplDecl(const ObjCCategoryImplDecl *OCID) {
686       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
687                                   OCID->getLocation(),
688                                   /*IsDecl=*/false,
689                                   {OCID->getClassInterface()}});
690       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
691                                   OCID->getCategoryNameLoc(),
692                                   /*IsDecl=*/true,
693                                   {OCID->getCategoryDecl()}});
694     }
695   };
696 
697   Visitor V{Resolver};
698   V.Visit(D);
699   return V.Refs;
700 }
701 
702 llvm::SmallVector<ReferenceLoc> refInStmt(const Stmt *S,
703                                           const HeuristicResolver *Resolver) {
704   struct Visitor : ConstStmtVisitor<Visitor> {
705     Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
706 
707     const HeuristicResolver *Resolver;
708     // FIXME: handle more complicated cases: more ObjC, designated initializers.
709     llvm::SmallVector<ReferenceLoc> Refs;
710 
711     void VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
712       Refs.push_back(ReferenceLoc{E->getNestedNameSpecifierLoc(),
713                                   E->getConceptNameLoc(),
714                                   /*IsDecl=*/false,
715                                   {E->getNamedConcept()}});
716     }
717 
718     void VisitDeclRefExpr(const DeclRefExpr *E) {
719       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
720                                   E->getNameInfo().getLoc(),
721                                   /*IsDecl=*/false,
722                                   {E->getFoundDecl()}});
723     }
724 
725     void VisitDependentScopeDeclRefExpr(const DependentScopeDeclRefExpr *E) {
726       Refs.push_back(ReferenceLoc{
727           E->getQualifierLoc(), E->getNameInfo().getLoc(), /*IsDecl=*/false,
728           explicitReferenceTargets(DynTypedNode::create(*E), {}, Resolver)});
729     }
730 
731     void VisitMemberExpr(const MemberExpr *E) {
732       // Skip destructor calls to avoid duplication: TypeLoc within will be
733       // visited separately.
734       if (llvm::isa<CXXDestructorDecl>(E->getFoundDecl().getDecl()))
735         return;
736       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
737                                   E->getMemberNameInfo().getLoc(),
738                                   /*IsDecl=*/false,
739                                   {E->getFoundDecl()}});
740     }
741 
742     void
743     VisitCXXDependentScopeMemberExpr(const CXXDependentScopeMemberExpr *E) {
744       Refs.push_back(ReferenceLoc{
745           E->getQualifierLoc(), E->getMemberNameInfo().getLoc(),
746           /*IsDecl=*/false,
747           explicitReferenceTargets(DynTypedNode::create(*E), {}, Resolver)});
748     }
749 
750     void VisitOverloadExpr(const OverloadExpr *E) {
751       Refs.push_back(ReferenceLoc{E->getQualifierLoc(),
752                                   E->getNameInfo().getLoc(),
753                                   /*IsDecl=*/false,
754                                   llvm::SmallVector<const NamedDecl *, 1>(
755                                       E->decls().begin(), E->decls().end())});
756     }
757 
758     void VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
759       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
760                                   E->getPackLoc(),
761                                   /*IsDecl=*/false,
762                                   {E->getPack()}});
763     }
764 
765     void VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) {
766       Refs.push_back(ReferenceLoc{
767           NestedNameSpecifierLoc(), E->getLocation(),
768           /*IsDecl=*/false,
769           // Select the getter, setter, or @property depending on the call.
770           explicitReferenceTargets(DynTypedNode::create(*E), {}, Resolver)});
771     }
772 
773     void VisitObjCIvarRefExpr(const ObjCIvarRefExpr *OIRE) {
774       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
775                                   OIRE->getLocation(),
776                                   /*IsDecl=*/false,
777                                   {OIRE->getDecl()}});
778     }
779 
780     void VisitObjCMessageExpr(const ObjCMessageExpr *E) {
781       // The name may have several tokens, we can only report the first.
782       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
783                                   E->getSelectorStartLoc(),
784                                   /*IsDecl=*/false,
785                                   {E->getMethodDecl()}});
786     }
787 
788     void VisitDesignatedInitExpr(const DesignatedInitExpr *DIE) {
789       for (const DesignatedInitExpr::Designator &D : DIE->designators()) {
790         if (!D.isFieldDesignator())
791           continue;
792 
793         Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
794                                     D.getFieldLoc(),
795                                     /*IsDecl=*/false,
796                                     {D.getField()}});
797       }
798     }
799 
800     void VisitGotoStmt(const GotoStmt *GS) {
801       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
802                                   GS->getLabelLoc(),
803                                   /*IsDecl=*/false,
804                                   {GS->getLabel()}});
805     }
806 
807     void VisitLabelStmt(const LabelStmt *LS) {
808       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
809                                   LS->getIdentLoc(),
810                                   /*IsDecl=*/true,
811                                   {LS->getDecl()}});
812     }
813   };
814 
815   Visitor V{Resolver};
816   V.Visit(S);
817   return V.Refs;
818 }
819 
820 llvm::SmallVector<ReferenceLoc>
821 refInTypeLoc(TypeLoc L, const HeuristicResolver *Resolver) {
822   struct Visitor : TypeLocVisitor<Visitor> {
823     Visitor(const HeuristicResolver *Resolver) : Resolver(Resolver) {}
824 
825     const HeuristicResolver *Resolver;
826     llvm::SmallVector<ReferenceLoc> Refs;
827 
828     void VisitElaboratedTypeLoc(ElaboratedTypeLoc L) {
829       // We only know about qualifier, rest if filled by inner locations.
830       size_t InitialSize = Refs.size();
831       Visit(L.getNamedTypeLoc().getUnqualifiedLoc());
832       size_t NewSize = Refs.size();
833       // Add qualifier for the newly-added refs.
834       for (unsigned I = InitialSize; I < NewSize; ++I) {
835         ReferenceLoc *Ref = &Refs[I];
836         // Fill in the qualifier.
837         assert(!Ref->Qualifier.hasQualifier() && "qualifier already set");
838         Ref->Qualifier = L.getQualifierLoc();
839       }
840     }
841 
842     void VisitUsingTypeLoc(UsingTypeLoc L) {
843       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
844                                   L.getLocalSourceRange().getBegin(),
845                                   /*IsDecl=*/false,
846                                   {L.getFoundDecl()}});
847     }
848 
849     void VisitTagTypeLoc(TagTypeLoc L) {
850       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
851                                   L.getNameLoc(),
852                                   /*IsDecl=*/false,
853                                   {L.getDecl()}});
854     }
855 
856     void VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc L) {
857       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
858                                   L.getNameLoc(),
859                                   /*IsDecl=*/false,
860                                   {L.getDecl()}});
861     }
862 
863     void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc L) {
864       // We must ensure template type aliases are included in results if they
865       // were written in the source code, e.g. in
866       //    template <class T> using valias = vector<T>;
867       //    ^valias<int> x;
868       // 'explicitReferenceTargets' will return:
869       //    1. valias with mask 'Alias'.
870       //    2. 'vector<int>' with mask 'Underlying'.
871       //  we want to return only #1 in this case.
872       Refs.push_back(ReferenceLoc{
873           NestedNameSpecifierLoc(), L.getTemplateNameLoc(), /*IsDecl=*/false,
874           explicitReferenceTargets(DynTypedNode::create(L.getType()),
875                                    DeclRelation::Alias, Resolver)});
876     }
877     void VisitDeducedTemplateSpecializationTypeLoc(
878         DeducedTemplateSpecializationTypeLoc L) {
879       Refs.push_back(ReferenceLoc{
880           NestedNameSpecifierLoc(), L.getNameLoc(), /*IsDecl=*/false,
881           explicitReferenceTargets(DynTypedNode::create(L.getType()),
882                                    DeclRelation::Alias, Resolver)});
883     }
884 
885     void VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
886       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
887                                   TL.getNameLoc(),
888                                   /*IsDecl=*/false,
889                                   {TL.getDecl()}});
890     }
891 
892     void VisitDependentTemplateSpecializationTypeLoc(
893         DependentTemplateSpecializationTypeLoc L) {
894       Refs.push_back(
895           ReferenceLoc{L.getQualifierLoc(), L.getTemplateNameLoc(),
896                        /*IsDecl=*/false,
897                        explicitReferenceTargets(
898                            DynTypedNode::create(L.getType()), {}, Resolver)});
899     }
900 
901     void VisitDependentNameTypeLoc(DependentNameTypeLoc L) {
902       Refs.push_back(
903           ReferenceLoc{L.getQualifierLoc(), L.getNameLoc(),
904                        /*IsDecl=*/false,
905                        explicitReferenceTargets(
906                            DynTypedNode::create(L.getType()), {}, Resolver)});
907     }
908 
909     void VisitTypedefTypeLoc(TypedefTypeLoc L) {
910       if (shouldSkipTypedef(L.getTypedefNameDecl()))
911         return;
912       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
913                                   L.getNameLoc(),
914                                   /*IsDecl=*/false,
915                                   {L.getTypedefNameDecl()}});
916     }
917 
918     void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc L) {
919       Refs.push_back(ReferenceLoc{NestedNameSpecifierLoc(),
920                                   L.getNameLoc(),
921                                   /*IsDecl=*/false,
922                                   {L.getIFaceDecl()}});
923     }
924   };
925 
926   Visitor V{Resolver};
927   V.Visit(L.getUnqualifiedLoc());
928   return V.Refs;
929 }
930 
931 class ExplicitReferenceCollector
932     : public RecursiveASTVisitor<ExplicitReferenceCollector> {
933 public:
934   ExplicitReferenceCollector(llvm::function_ref<void(ReferenceLoc)> Out,
935                              const HeuristicResolver *Resolver)
936       : Out(Out), Resolver(Resolver) {
937     assert(Out);
938   }
939 
940   bool VisitTypeLoc(TypeLoc TTL) {
941     if (TypeLocsToSkip.count(TTL.getBeginLoc()))
942       return true;
943     visitNode(DynTypedNode::create(TTL));
944     return true;
945   }
946 
947   bool TraverseElaboratedTypeLoc(ElaboratedTypeLoc L) {
948     // ElaboratedTypeLoc will reports information for its inner type loc.
949     // Otherwise we loose information about inner types loc's qualifier.
950     TypeLoc Inner = L.getNamedTypeLoc().getUnqualifiedLoc();
951     TypeLocsToSkip.insert(Inner.getBeginLoc());
952     return RecursiveASTVisitor::TraverseElaboratedTypeLoc(L);
953   }
954 
955   bool VisitStmt(Stmt *S) {
956     visitNode(DynTypedNode::create(*S));
957     return true;
958   }
959 
960   bool TraverseOpaqueValueExpr(OpaqueValueExpr *OVE) {
961     visitNode(DynTypedNode::create(*OVE));
962     // Not clear why the source expression is skipped by default...
963     // FIXME: can we just make RecursiveASTVisitor do this?
964     return RecursiveASTVisitor::TraverseStmt(OVE->getSourceExpr());
965   }
966 
967   bool TraversePseudoObjectExpr(PseudoObjectExpr *POE) {
968     visitNode(DynTypedNode::create(*POE));
969     // Traverse only the syntactic form to find the *written* references.
970     // (The semantic form also contains lots of duplication)
971     return RecursiveASTVisitor::TraverseStmt(POE->getSyntacticForm());
972   }
973 
974   // We re-define Traverse*, since there's no corresponding Visit*.
975   // TemplateArgumentLoc is the only way to get locations for references to
976   // template template parameters.
977   bool TraverseTemplateArgumentLoc(TemplateArgumentLoc A) {
978     switch (A.getArgument().getKind()) {
979     case TemplateArgument::Template:
980     case TemplateArgument::TemplateExpansion:
981       reportReference(ReferenceLoc{A.getTemplateQualifierLoc(),
982                                    A.getTemplateNameLoc(),
983                                    /*IsDecl=*/false,
984                                    {A.getArgument()
985                                         .getAsTemplateOrTemplatePattern()
986                                         .getAsTemplateDecl()}},
987                       DynTypedNode::create(A.getArgument()));
988       break;
989     case TemplateArgument::Declaration:
990       break; // FIXME: can this actually happen in TemplateArgumentLoc?
991     case TemplateArgument::Integral:
992     case TemplateArgument::Null:
993     case TemplateArgument::NullPtr:
994       break; // no references.
995     case TemplateArgument::Pack:
996     case TemplateArgument::Type:
997     case TemplateArgument::Expression:
998       break; // Handled by VisitType and VisitExpression.
999     };
1000     return RecursiveASTVisitor::TraverseTemplateArgumentLoc(A);
1001   }
1002 
1003   bool VisitDecl(Decl *D) {
1004     visitNode(DynTypedNode::create(*D));
1005     return true;
1006   }
1007 
1008   // We have to use Traverse* because there is no corresponding Visit*.
1009   bool TraverseNestedNameSpecifierLoc(NestedNameSpecifierLoc L) {
1010     if (!L.getNestedNameSpecifier())
1011       return true;
1012     visitNode(DynTypedNode::create(L));
1013     // Inner type is missing information about its qualifier, skip it.
1014     if (auto TL = L.getTypeLoc())
1015       TypeLocsToSkip.insert(TL.getBeginLoc());
1016     return RecursiveASTVisitor::TraverseNestedNameSpecifierLoc(L);
1017   }
1018 
1019   bool TraverseObjCProtocolLoc(ObjCProtocolLoc ProtocolLoc) {
1020     visitNode(DynTypedNode::create(ProtocolLoc));
1021     return true;
1022   }
1023 
1024   bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
1025     visitNode(DynTypedNode::create(*Init));
1026     return RecursiveASTVisitor::TraverseConstructorInitializer(Init);
1027   }
1028 
1029 private:
1030   /// Obtain information about a reference directly defined in \p N. Does not
1031   /// recurse into child nodes, e.g. do not expect references for constructor
1032   /// initializers
1033   ///
1034   /// Any of the fields in the returned structure can be empty, but not all of
1035   /// them, e.g.
1036   ///   - for implicitly generated nodes (e.g. MemberExpr from range-based-for),
1037   ///     source location information may be missing,
1038   ///   - for dependent code, targets may be empty.
1039   ///
1040   /// (!) For the purposes of this function declarations are not considered to
1041   ///     be references. However, declarations can have references inside them,
1042   ///     e.g. 'namespace foo = std' references namespace 'std' and this
1043   ///     function will return the corresponding reference.
1044   llvm::SmallVector<ReferenceLoc> explicitReference(DynTypedNode N) {
1045     if (auto *D = N.get<Decl>())
1046       return refInDecl(D, Resolver);
1047     if (auto *S = N.get<Stmt>())
1048       return refInStmt(S, Resolver);
1049     if (auto *NNSL = N.get<NestedNameSpecifierLoc>()) {
1050       // (!) 'DeclRelation::Alias' ensures we do not loose namespace aliases.
1051       return {ReferenceLoc{
1052           NNSL->getPrefix(), NNSL->getLocalBeginLoc(), false,
1053           explicitReferenceTargets(
1054               DynTypedNode::create(*NNSL->getNestedNameSpecifier()),
1055               DeclRelation::Alias, Resolver)}};
1056     }
1057     if (const TypeLoc *TL = N.get<TypeLoc>())
1058       return refInTypeLoc(*TL, Resolver);
1059     if (const CXXCtorInitializer *CCI = N.get<CXXCtorInitializer>()) {
1060       // Other type initializers (e.g. base initializer) are handled by visiting
1061       // the typeLoc.
1062       if (CCI->isAnyMemberInitializer()) {
1063         return {ReferenceLoc{NestedNameSpecifierLoc(),
1064                              CCI->getMemberLocation(),
1065                              /*IsDecl=*/false,
1066                              {CCI->getAnyMember()}}};
1067       }
1068     }
1069     if (const ObjCProtocolLoc *PL = N.get<ObjCProtocolLoc>())
1070       return {ReferenceLoc{NestedNameSpecifierLoc(),
1071                            PL->getLocation(),
1072                            /*IsDecl=*/false,
1073                            {PL->getProtocol()}}};
1074 
1075     // We do not have location information for other nodes (QualType, etc)
1076     return {};
1077   }
1078 
1079   void visitNode(DynTypedNode N) {
1080     for (auto &R : explicitReference(N))
1081       reportReference(std::move(R), N);
1082   }
1083 
1084   void reportReference(ReferenceLoc &&Ref, DynTypedNode N) {
1085     // Strip null targets that can arise from invalid code.
1086     // (This avoids having to check for null everywhere we insert)
1087     llvm::erase_value(Ref.Targets, nullptr);
1088     // Our promise is to return only references from the source code. If we lack
1089     // location information, skip these nodes.
1090     // Normally this should not happen in practice, unless there are bugs in the
1091     // traversals or users started the traversal at an implicit node.
1092     if (Ref.NameLoc.isInvalid()) {
1093       dlog("invalid location at node {0}", nodeToString(N));
1094       return;
1095     }
1096     Out(Ref);
1097   }
1098 
1099   llvm::function_ref<void(ReferenceLoc)> Out;
1100   const HeuristicResolver *Resolver;
1101   /// TypeLocs starting at these locations must be skipped, see
1102   /// TraverseElaboratedTypeSpecifierLoc for details.
1103   llvm::DenseSet<SourceLocation> TypeLocsToSkip;
1104 };
1105 } // namespace
1106 
1107 void findExplicitReferences(const Stmt *S,
1108                             llvm::function_ref<void(ReferenceLoc)> Out,
1109                             const HeuristicResolver *Resolver) {
1110   assert(S);
1111   ExplicitReferenceCollector(Out, Resolver).TraverseStmt(const_cast<Stmt *>(S));
1112 }
1113 void findExplicitReferences(const Decl *D,
1114                             llvm::function_ref<void(ReferenceLoc)> Out,
1115                             const HeuristicResolver *Resolver) {
1116   assert(D);
1117   ExplicitReferenceCollector(Out, Resolver).TraverseDecl(const_cast<Decl *>(D));
1118 }
1119 void findExplicitReferences(const ASTContext &AST,
1120                             llvm::function_ref<void(ReferenceLoc)> Out,
1121                             const HeuristicResolver *Resolver) {
1122   ExplicitReferenceCollector(Out, Resolver)
1123       .TraverseAST(const_cast<ASTContext &>(AST));
1124 }
1125 
1126 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelation R) {
1127   switch (R) {
1128 #define REL_CASE(X)                                                            \
1129   case DeclRelation::X:                                                        \
1130     return OS << #X;
1131     REL_CASE(Alias);
1132     REL_CASE(Underlying);
1133     REL_CASE(TemplateInstantiation);
1134     REL_CASE(TemplatePattern);
1135 #undef REL_CASE
1136   }
1137   llvm_unreachable("Unhandled DeclRelation enum");
1138 }
1139 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, DeclRelationSet RS) {
1140   const char *Sep = "";
1141   for (unsigned I = 0; I < RS.S.size(); ++I) {
1142     if (RS.S.test(I)) {
1143       OS << Sep << static_cast<DeclRelation>(I);
1144       Sep = "|";
1145     }
1146   }
1147   return OS;
1148 }
1149 
1150 llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, ReferenceLoc R) {
1151   // note we cannot print R.NameLoc without a source manager.
1152   OS << "targets = {";
1153   llvm::SmallVector<std::string> Targets;
1154   for (const NamedDecl *T : R.Targets) {
1155     llvm::raw_string_ostream Target(Targets.emplace_back());
1156     Target << printQualifiedName(*T) << printTemplateSpecializationArgs(*T);
1157   }
1158   llvm::sort(Targets);
1159   OS << llvm::join(Targets, ", ");
1160   OS << "}";
1161   if (R.Qualifier) {
1162     OS << ", qualifier = '";
1163     R.Qualifier.getNestedNameSpecifier()->print(OS,
1164                                                 PrintingPolicy(LangOptions()));
1165     OS << "'";
1166   }
1167   if (R.IsDecl)
1168     OS << ", decl";
1169   return OS;
1170 }
1171 
1172 } // namespace clangd
1173 } // namespace clang
1174