0.7.0
C++ to UML diagram generator based on Clang
Loading...
Searching...
No Matches
USRGeneration.cpp
Go to the documentation of this file.
1//===- USRGeneration.cpp - Routines for USR generation --------------------===//
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 "USRGeneration.h"
10
11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Attr.h"
13#include "clang/AST/DeclTemplate.h"
14#include "clang/AST/DeclVisitor.h"
15#include "clang/Basic/FileManager.h"
16#include "clang/Lex/PreprocessingRecord.h"
17#include "llvm/Support/Path.h"
18#include "llvm/Support/raw_ostream.h"
19
20namespace clanguml {
21// clang-format off
22using namespace clang;
23
24//===----------------------------------------------------------------------===//
25// USR generation.
26//===----------------------------------------------------------------------===//
27
28/// \returns true on error.
29static bool printLoc(llvm::raw_ostream &OS, SourceLocation Loc,
30 const SourceManager &SM, bool IncludeOffset) {
31 if (Loc.isInvalid()) {
32 return true;
33 }
34 Loc = SM.getExpansionLoc(Loc);
35 const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(Loc);
36 const FileEntry *FE = SM.getFileEntryForID(Decomposed.first);
37 if (FE) {
38 OS << llvm::sys::path::filename(FE->getName());
39 } else {
40 // This case really isn't interesting.
41 return true;
42 }
43 if (IncludeOffset) {
44 // Use the offest into the FileID to represent the location. Using
45 // a line/column can cause us to look back at the original source file,
46 // which is expensive.
47 OS << '@' << Decomposed.second;
48 }
49 return false;
50}
51
52static StringRef GetExternalSourceContainer(const NamedDecl *D) {
53 if (!D)
54 return StringRef();
55 if (auto *attr = D->getExternalSourceSymbolAttr()) {
56 return attr->getDefinedIn();
57 }
58 return StringRef();
59}
60
61namespace {
62class USRGenerator : public ConstDeclVisitor<USRGenerator> {
63 SmallVectorImpl<char> &Buf;
64 llvm::raw_svector_ostream Out;
66 ASTContext *Context;
68
69 llvm::DenseMap<const Type *, unsigned> TypeSubstitutions;
70
71public:
72 explicit USRGenerator(ASTContext *Ctx, SmallVectorImpl<char> &Buf)
73 : Buf(Buf),
74 Out(Buf),
75 IgnoreResults(false),
76 Context(Ctx),
77 generatedLoc(false)
78 {
79 // Add the USR space prefix.
81 }
82
83 bool ignoreResults() const { return IgnoreResults; }
84
85 // Visitation methods from generating USRs from AST elements.
86 void VisitDeclContext(const DeclContext *D);
87 void VisitFieldDecl(const FieldDecl *D);
88 void VisitFunctionDecl(const FunctionDecl *D);
89 void VisitNamedDecl(const NamedDecl *D);
90 void VisitNamespaceDecl(const NamespaceDecl *D);
91 void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D);
92 void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D);
93 void VisitClassTemplateDecl(const ClassTemplateDecl *D);
94 void VisitObjCContainerDecl(const ObjCContainerDecl *CD,
95 const ObjCCategoryDecl *CatD = nullptr);
96 void VisitObjCMethodDecl(const ObjCMethodDecl *MD);
97 void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
98 void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
99 void VisitTagDecl(const TagDecl *D);
100 void VisitTypedefDecl(const TypedefDecl *D);
101 void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
102 void VisitVarDecl(const VarDecl *D);
103 void VisitBindingDecl(const BindingDecl *D);
104 void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
105 void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
106 void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D);
107 void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D);
108 void VisitConceptDecl(const ConceptDecl *D);
109
110 void VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
111 IgnoreResults = true; // No USRs for linkage specs themselves.
112 }
113
114 void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
115 IgnoreResults = true;
116 }
117
118 void VisitUsingDecl(const UsingDecl *D) {
119 VisitDeclContext(D->getDeclContext());
120 Out << "@UD@";
121
122 bool EmittedDeclName = !EmitDeclName(D);
123 assert(EmittedDeclName && "EmitDeclName can not fail for UsingDecls");
124 (void)EmittedDeclName;
125 }
126
127 bool ShouldGenerateLocation(const NamedDecl *D);
128
129 bool isLocal(const NamedDecl *D) {
130 return D->getParentFunctionOrMethod() != nullptr;
131 }
132
133 void GenExtSymbolContainer(const NamedDecl *D);
134
135 /// Generate the string component containing the location of the
136 /// declaration.
137 bool GenLoc(const Decl *D, bool IncludeOffset);
138
139 /// String generation methods used both by the visitation methods
140 /// and from other clients that want to directly generate USRs. These
141 /// methods do not construct complete USRs (which incorporate the parents
142 /// of an AST element), but only the fragments concerning the AST element
143 /// itself.
144
145 /// Generate a USR for an Objective-C class.
146 void GenObjCClass(StringRef cls, StringRef ExtSymDefinedIn,
147 StringRef CategoryContextExtSymbolDefinedIn) {
148 common::index::generateUSRForObjCClass(cls, Out, ExtSymDefinedIn,
149 CategoryContextExtSymbolDefinedIn);
150 }
151
152 /// Generate a USR for an Objective-C class category.
153 void GenObjCCategory(StringRef cls, StringRef cat,
154 StringRef clsExt, StringRef catExt) {
155 common::index::generateUSRForObjCCategory(cls, cat, Out, clsExt, catExt);
156 }
157
158 /// Generate a USR fragment for an Objective-C property.
159 void GenObjCProperty(StringRef prop, bool isClassProp) {
160 common::index::generateUSRForObjCProperty(prop, isClassProp, Out);
161 }
162
163 /// Generate a USR for an Objective-C protocol.
164 void GenObjCProtocol(StringRef prot, StringRef ext) {
166 }
167
168 void VisitType(QualType T);
169 void VisitTemplateParameterList(const TemplateParameterList *Params);
170 void VisitTemplateName(TemplateName Name);
171 void VisitTemplateArgument(const TemplateArgument &Arg);
172
173 void VisitMSGuidDecl(const MSGuidDecl *D);
174
175 /// Emit a Decl's name using NamedDecl::printName() and return true if
176 /// the decl had no name.
177 bool EmitDeclName(const NamedDecl *D);
178};
179} // end anonymous namespace
180
181//===----------------------------------------------------------------------===//
182// Generating USRs from ASTS.
183//===----------------------------------------------------------------------===//
184
185bool USRGenerator::EmitDeclName(const NamedDecl *D) {
186 DeclarationName N = D->getDeclName();
187 if (N.isEmpty())
188 return true;
189 Out << N;
190 return false;
191}
192
193bool USRGenerator::ShouldGenerateLocation(const NamedDecl *D) {
194 if (D->isExternallyVisible())
195 return false;
196 if (D->getParentFunctionOrMethod())
197 return true;
198 SourceLocation Loc = D->getLocation();
199 if (Loc.isInvalid())
200 return false;
201 const SourceManager &SM = Context->getSourceManager();
202 return !SM.isInSystemHeader(Loc);
203}
204
205void USRGenerator::VisitDeclContext(const DeclContext *DC) {
206 if (const NamedDecl *D = dyn_cast<NamedDecl>(DC))
207 Visit(D);
208 else if (isa<LinkageSpecDecl>(DC)) // Linkage specs are transparent in USRs.
209 VisitDeclContext(DC->getParent());
210}
211
212void USRGenerator::VisitFieldDecl(const FieldDecl *D) {
213 // The USR for an ivar declared in a class extension is based on the
214 // ObjCInterfaceDecl, not the ObjCCategoryDecl.
215 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
216 Visit(ID);
217 else
218 VisitDeclContext(D->getDeclContext());
219 Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@");
220 if (EmitDeclName(D)) {
221 // Bit fields can be anonymous.
222 IgnoreResults = true;
223 return;
224 }
225}
226
227void USRGenerator::VisitFunctionDecl(const FunctionDecl *D) {
228 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
229 return;
230
231 if (D->getType().isNull()) {
232 IgnoreResults = true;
233 return;
234 }
235
236 const unsigned StartSize = Buf.size();
237 VisitDeclContext(D->getDeclContext());
238 if (Buf.size() == StartSize)
239 GenExtSymbolContainer(D);
240
241 bool IsTemplate = false;
242 if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {
243 IsTemplate = true;
244 Out << "@FT@";
245 VisitTemplateParameterList(FunTmpl->getTemplateParameters());
246 } else
247 Out << "@F@";
248
249 PrintingPolicy Policy(Context->getLangOpts());
250 // Forward references can have different template argument names. Suppress the
251 // template argument names in constructors to make their USR more stable.
252 Policy.SuppressTemplateArgsInCXXConstructors = true;
253 D->getDeclName().print(Out, Policy);
254
255 ASTContext &Ctx = *Context;
256 if ((!Ctx.getLangOpts().CPlusPlus || D->isExternC()) &&
257 !D->hasAttr<OverloadableAttr>())
258 return;
259
260 if (const TemplateArgumentList *
261 SpecArgs = D->getTemplateSpecializationArgs()) {
262 Out << '<';
263 for (unsigned I = 0, N = SpecArgs->size(); I != N; ++I) {
264 Out << '#';
265 VisitTemplateArgument(SpecArgs->get(I));
266 }
267 Out << '>';
268 }
269
270 // Mangle in type information for the arguments.
271 for (auto *PD : D->parameters()) {
272 Out << '#';
273 VisitType(PD->getType());
274 }
275 if (D->isVariadic())
276 Out << '.';
277 if (IsTemplate) {
278 // Function templates can be overloaded by return type, for example:
279 // \code
280 // template <class T> typename T::A foo() {}
281 // template <class T> typename T::B foo() {}
282 // \endcode
283 Out << '#';
284 VisitType(D->getReturnType());
285 }
286 Out << '#';
287 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
288 if (MD->isStatic())
289 Out << 'S';
290 // FIXME: OpenCL: Need to consider address spaces
291 if (unsigned quals = MD->getMethodQualifiers().getCVRUQualifiers())
292 Out << (char)('0' + quals);
293 switch (MD->getRefQualifier()) {
294 case RQ_None: break;
295 case RQ_LValue: Out << '&'; break;
296 case RQ_RValue: Out << "&&"; break;
297 }
298 }
299}
300
301void USRGenerator::VisitNamedDecl(const NamedDecl *D) {
302 VisitDeclContext(D->getDeclContext());
303 Out << "@";
304
305 if (EmitDeclName(D)) {
306 // The string can be empty if the declaration has no name; e.g., it is
307 // the ParmDecl with no name for declaration of a function pointer type,
308 // e.g.: void (*f)(void *);
309 // In this case, don't generate a USR.
310 IgnoreResults = true;
311 }
312}
313
314void USRGenerator::VisitVarDecl(const VarDecl *D) {
315 // VarDecls can be declared 'extern' within a function or method body,
316 // but their enclosing DeclContext is the function, not the TU. We need
317 // to check the storage class to correctly generate the USR.
318 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
319 return;
320
321 VisitDeclContext(D->getDeclContext());
322
323 if (VarTemplateDecl *VarTmpl = D->getDescribedVarTemplate()) {
324 Out << "@VT";
325 VisitTemplateParameterList(VarTmpl->getTemplateParameters());
326 } else if (const VarTemplatePartialSpecializationDecl *PartialSpec
327 = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
328 Out << "@VP";
329 VisitTemplateParameterList(PartialSpec->getTemplateParameters());
330 }
331
332 // Variables always have simple names.
333 StringRef s = D->getName();
334
335 // The string can be empty if the declaration has no name; e.g., it is
336 // the ParmDecl with no name for declaration of a function pointer type, e.g.:
337 // void (*f)(void *);
338 // In this case, don't generate a USR.
339 if (s.empty())
340 IgnoreResults = true;
341 else
342 Out << '@' << s;
343
344 // For a template specialization, mangle the template arguments.
345 if (const VarTemplateSpecializationDecl *Spec
346 = dyn_cast<VarTemplateSpecializationDecl>(D)) {
347 const TemplateArgumentList &Args = Spec->getTemplateArgs();
348 Out << '>';
349 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
350 Out << '#';
351 VisitTemplateArgument(Args.get(I));
352 }
353 }
354}
355
356void USRGenerator::VisitBindingDecl(const BindingDecl *D) {
357 if (isLocal(D) && GenLoc(D, /*IncludeOffset=*/true))
358 return;
359 VisitNamedDecl(D);
360}
361
362void USRGenerator::VisitNonTypeTemplateParmDecl(
363 const NonTypeTemplateParmDecl *D) {
364 GenLoc(D, /*IncludeOffset=*/true);
365}
366
367void USRGenerator::VisitTemplateTemplateParmDecl(
368 const TemplateTemplateParmDecl *D) {
369 GenLoc(D, /*IncludeOffset=*/true);
370}
371
372void USRGenerator::VisitNamespaceDecl(const NamespaceDecl *D) {
373 if (D->isAnonymousNamespace()) {
374 Out << "@aN";
375 return;
376 }
377
378 VisitDeclContext(D->getDeclContext());
379 if (!IgnoreResults)
380 Out << "@N@" << D->getName();
381}
382
383void USRGenerator::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
384 VisitFunctionDecl(D->getTemplatedDecl());
385}
386
387void USRGenerator::VisitClassTemplateDecl(const ClassTemplateDecl *D) {
388 VisitTagDecl(D->getTemplatedDecl());
389}
390
391void USRGenerator::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
392 VisitDeclContext(D->getDeclContext());
393 if (!IgnoreResults)
394 Out << "@NA@" << D->getName();
395}
396
397static const ObjCCategoryDecl *getCategoryContext(const NamedDecl *D) {
398 if (auto *CD = dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
399 return CD;
400 if (auto *ICD = dyn_cast<ObjCCategoryImplDecl>(D->getDeclContext()))
401 return ICD->getCategoryDecl();
402 return nullptr;
403}
404
405void USRGenerator::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
406 const DeclContext *container = D->getDeclContext();
407 if (const ObjCProtocolDecl *pd = dyn_cast<ObjCProtocolDecl>(container)) {
408 Visit(pd);
409 }
410 else {
411 // The USR for a method declared in a class extension or category is based on
412 // the ObjCInterfaceDecl, not the ObjCCategoryDecl.
413 const ObjCInterfaceDecl *ID = D->getClassInterface();
414 if (!ID) {
415 IgnoreResults = true;
416 return;
417 }
418 auto *CD = getCategoryContext(D);
419 VisitObjCContainerDecl(ID, CD);
420 }
421 // Ideally we would use 'GenObjCMethod', but this is such a hot path
422 // for Objective-C code that we don't want to use
423 // DeclarationName::getAsString().
424 Out << (D->isInstanceMethod() ? "(im)" : "(cm)")
425 << DeclarationName(D->getSelector());
426}
427
428void USRGenerator::VisitObjCContainerDecl(const ObjCContainerDecl *D,
429 const ObjCCategoryDecl *CatD) {
430 switch (D->getKind()) {
431 default:
432 llvm_unreachable("Invalid ObjC container.");
433 case Decl::ObjCInterface:
434 case Decl::ObjCImplementation:
435 GenObjCClass(D->getName(), GetExternalSourceContainer(D),
437 break;
438 case Decl::ObjCCategory: {
439 const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
440 const ObjCInterfaceDecl *ID = CD->getClassInterface();
441 if (!ID) {
442 // Handle invalid code where the @interface might not
443 // have been specified.
444 // FIXME: We should be able to generate this USR even if the
445 // @interface isn't available.
446 IgnoreResults = true;
447 return;
448 }
449 // Specially handle class extensions, which are anonymous categories.
450 // We want to mangle in the location to uniquely distinguish them.
451 if (CD->IsClassExtension()) {
452 Out << "objc(ext)" << ID->getName() << '@';
453 GenLoc(CD, /*IncludeOffset=*/true);
454 }
455 else
456 GenObjCCategory(ID->getName(), CD->getName(),
459
460 break;
461 }
462 case Decl::ObjCCategoryImpl: {
463 const ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
464 const ObjCInterfaceDecl *ID = CD->getClassInterface();
465 if (!ID) {
466 // Handle invalid code where the @interface might not
467 // have been specified.
468 // FIXME: We should be able to generate this USR even if the
469 // @interface isn't available.
470 IgnoreResults = true;
471 return;
472 }
473 GenObjCCategory(ID->getName(), CD->getName(),
476 break;
477 }
478 case Decl::ObjCProtocol: {
479 const ObjCProtocolDecl *PD = cast<ObjCProtocolDecl>(D);
480 GenObjCProtocol(PD->getName(), GetExternalSourceContainer(PD));
481 break;
482 }
483 }
484}
485
486void USRGenerator::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
487 // The USR for a property declared in a class extension or category is based
488 // on the ObjCInterfaceDecl, not the ObjCCategoryDecl.
489 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
490 VisitObjCContainerDecl(ID, getCategoryContext(D));
491 else
492 Visit(cast<Decl>(D->getDeclContext()));
493 GenObjCProperty(D->getName(), D->isClassProperty());
494}
495
496void USRGenerator::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
497 if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {
498 VisitObjCPropertyDecl(PD);
499 return;
500 }
501
502 IgnoreResults = true;
503}
504
505void USRGenerator::VisitTagDecl(const TagDecl *D) {
506 // Add the location of the tag decl to handle resolution across
507 // translation units.
508 if (!isa<EnumDecl>(D) &&
509 ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
510 return;
511
512 GenExtSymbolContainer(D);
513
514 D = D->getCanonicalDecl();
515 VisitDeclContext(D->getDeclContext());
516
517 bool AlreadyStarted = false;
518 if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) {
519 if(CXXRecord->isLambda()) {
520 Out << "@L";
521 printLoc(Out, CXXRecord->getBeginLoc(), Context->getSourceManager(), true);
522 }
523 else if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) {
524 AlreadyStarted = true;
525
526 switch (D->getTagKind()) {
527 case TTK_Interface:
528 case TTK_Class:
529 case TTK_Struct: Out << "@ST"; break;
530 case TTK_Union: Out << "@UT"; break;
531 case TTK_Enum: llvm_unreachable("enum template");
532 }
533 VisitTemplateParameterList(ClassTmpl->getTemplateParameters());
534 } else if (const ClassTemplatePartialSpecializationDecl *PartialSpec
535 = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) {
536 AlreadyStarted = true;
537
538 switch (D->getTagKind()) {
539 case TTK_Interface:
540 case TTK_Class:
541 case TTK_Struct: Out << "@SP"; break;
542 case TTK_Union: Out << "@UP"; break;
543 case TTK_Enum: llvm_unreachable("enum partial specialization");
544 }
545 VisitTemplateParameterList(PartialSpec->getTemplateParameters());
546 }
547 }
548
549 if (!AlreadyStarted) {
550 switch (D->getTagKind()) {
551 case TTK_Interface:
552 case TTK_Class:
553 case TTK_Struct: Out << "@S"; break;
554 case TTK_Union: Out << "@U"; break;
555 case TTK_Enum: Out << "@E"; break;
556 }
557 }
558
559 Out << '@';
560 assert(Buf.size() > 0);
561 const unsigned off = Buf.size() - 1;
562
563 if (EmitDeclName(D)) {
564 if (const TypedefNameDecl *TD = D->getTypedefNameForAnonDecl()) {
565 Buf[off] = 'A';
566 Out << '@' << *TD;
567 } else {
568 if (D->isEmbeddedInDeclarator() && !D->isFreeStanding()) {
569 printLoc(Out, D->getLocation(), Context->getSourceManager(), true);
570 } else {
571 Buf[off] = 'a';
572 if (auto *ED = dyn_cast<EnumDecl>(D)) {
573 // Distinguish USRs of anonymous enums by using their first
574 // enumerator.
575 auto enum_range = ED->enumerators();
576 if (enum_range.begin() != enum_range.end()) {
577 Out << '@' << **enum_range.begin();
578 }
579 }
580 }
581 }
582 }
583
584 // For a class template specialization, mangle the template arguments.
585 if (const ClassTemplateSpecializationDecl *Spec
586 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
587 const TemplateArgumentList &Args = Spec->getTemplateArgs();
588 Out << '>';
589 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
590 Out << '#';
591 VisitTemplateArgument(Args.get(I));
592 }
593 }
594}
595
596void USRGenerator::VisitTypedefDecl(const TypedefDecl *D) {
597 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
598 return;
599 const DeclContext *DC = D->getDeclContext();
600 if (const NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
601 Visit(DCN);
602 Out << "@T@";
603 Out << D->getName();
604}
605
606void USRGenerator::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
607 GenLoc(D, /*IncludeOffset=*/true);
608}
609
610void USRGenerator::GenExtSymbolContainer(const NamedDecl *D) {
611 StringRef Container = GetExternalSourceContainer(D);
612 if (!Container.empty())
613 Out << "@M@" << Container;
614}
615
616bool USRGenerator::GenLoc(const Decl *D, bool IncludeOffset) {
617 if (generatedLoc)
618 return IgnoreResults;
619 generatedLoc = true;
620
621 // Guard against null declarations in invalid code.
622 if (!D) {
623 IgnoreResults = true;
624 return true;
625 }
626
627 // Use the location of canonical decl.
628 D = D->getCanonicalDecl();
629
631 IgnoreResults || printLoc(Out, D->getBeginLoc(),
632 Context->getSourceManager(), IncludeOffset);
633
634 return IgnoreResults;
635}
636
637static void printQualifier(llvm::raw_ostream &Out, ASTContext &Ctx, NestedNameSpecifier *NNS) {
638 // FIXME: Encode the qualifier, don't just print it.
639 PrintingPolicy PO(Ctx.getLangOpts());
640 PO.SuppressTagKeyword = true;
641 PO.SuppressUnwrittenScope = true;
642 PO.ConstantArraySizeAsWritten = false;
643 PO.AnonymousTagLocations = false;
644 NNS->print(Out, PO);
645}
646
647void USRGenerator::VisitType(QualType T) {
648 // This method mangles in USR information for types. It can possibly
649 // just reuse the naming-mangling logic used by codegen, although the
650 // requirements for USRs might not be the same.
651 ASTContext &Ctx = *Context;
652
653 do {
654 T = Ctx.getCanonicalType(T);
655 Qualifiers Q = T.getQualifiers();
656 unsigned qVal = 0;
657 if (Q.hasConst())
658 qVal |= 0x1;
659 if (Q.hasVolatile())
660 qVal |= 0x2;
661 if (Q.hasRestrict())
662 qVal |= 0x4;
663 if(qVal)
664 Out << ((char) ('0' + qVal));
665
666 // Mangle in ObjC GC qualifiers?
667
668 if (const PackExpansionType *Expansion = T->getAs<PackExpansionType>()) {
669 Out << 'P';
670 T = Expansion->getPattern();
671 }
672
673 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
674 switch (BT->getKind()) {
675 case BuiltinType::Void:
676 Out << 'v'; break;
677 case BuiltinType::Bool:
678 Out << 'b'; break;
679 case BuiltinType::UChar:
680 Out << 'c'; break;
681 case BuiltinType::Char8:
682 Out << 'u'; break;
683 case BuiltinType::Char16:
684 Out << 'q'; break;
685 case BuiltinType::Char32:
686 Out << 'w'; break;
687 case BuiltinType::UShort:
688 Out << 's'; break;
689 case BuiltinType::UInt:
690 Out << 'i'; break;
691 case BuiltinType::ULong:
692 Out << 'l'; break;
693 case BuiltinType::ULongLong:
694 Out << 'k'; break;
695 case BuiltinType::UInt128:
696 Out << 'j'; break;
697 case BuiltinType::Char_U:
698 case BuiltinType::Char_S:
699 Out << 'C'; break;
700 case BuiltinType::SChar:
701 Out << 'r'; break;
702 case BuiltinType::WChar_S:
703 case BuiltinType::WChar_U:
704 Out << 'W'; break;
705 case BuiltinType::Short:
706 Out << 'S'; break;
707 case BuiltinType::Int:
708 Out << 'I'; break;
709 case BuiltinType::Long:
710 Out << 'L'; break;
711 case BuiltinType::LongLong:
712 Out << 'K'; break;
713 case BuiltinType::Int128:
714 Out << 'J'; break;
715 case BuiltinType::Float16:
716 case BuiltinType::Half:
717 Out << 'h'; break;
718 case BuiltinType::Float:
719 Out << 'f'; break;
720 case BuiltinType::Double:
721 Out << 'd'; break;
722 case BuiltinType::LongDouble:
723 Out << 'D'; break;
724 case BuiltinType::Float128:
725 Out << 'Q'; break;
726 case BuiltinType::NullPtr:
727 Out << 'n'; break;
728#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
729 case BuiltinType::Id: \
730 Out << "@BT@" << #Suffix << "_" << #ImgType; break;
731#include "clang/Basic/OpenCLImageTypes.def"
732#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
733 case BuiltinType::Id: \
734 Out << "@BT@" << #ExtType; break;
735#include "clang/Basic/OpenCLExtensionTypes.def"
736 case BuiltinType::OCLEvent:
737 Out << "@BT@OCLEvent"; break;
738 case BuiltinType::OCLClkEvent:
739 Out << "@BT@OCLClkEvent"; break;
740 case BuiltinType::OCLQueue:
741 Out << "@BT@OCLQueue"; break;
742 case BuiltinType::OCLReserveID:
743 Out << "@BT@OCLReserveID"; break;
744 case BuiltinType::OCLSampler:
745 Out << "@BT@OCLSampler"; break;
746#define SVE_TYPE(Name, Id, SingletonId) \
747 case BuiltinType::Id: \
748 Out << "@BT@" << Name; break;
749#include "clang/Basic/AArch64SVEACLETypes.def"
750#define PPC_VECTOR_TYPE(Name, Id, Size) \
751 case BuiltinType::Id: \
752 Out << "@BT@" << #Name; break;
753#include "clang/Basic/PPCTypes.def"
754#define RVV_TYPE(Name, Id, SingletonId) \
755 case BuiltinType::Id: \
756 Out << "@BT@" << Name; break;
757#include "clang/Basic/RISCVVTypes.def"
758#define WASM_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
759#include "clang/Basic/WebAssemblyReferenceTypes.def"
760 case BuiltinType::ShortAccum:
761 Out << "@BT@ShortAccum"; break;
762 case BuiltinType::Accum:
763 Out << "@BT@Accum"; break;
764 case BuiltinType::LongAccum:
765 Out << "@BT@LongAccum"; break;
766 case BuiltinType::UShortAccum:
767 Out << "@BT@UShortAccum"; break;
768 case BuiltinType::UAccum:
769 Out << "@BT@UAccum"; break;
770 case BuiltinType::ULongAccum:
771 Out << "@BT@ULongAccum"; break;
772 case BuiltinType::ShortFract:
773 Out << "@BT@ShortFract"; break;
774 case BuiltinType::Fract:
775 Out << "@BT@Fract"; break;
776 case BuiltinType::LongFract:
777 Out << "@BT@LongFract"; break;
778 case BuiltinType::UShortFract:
779 Out << "@BT@UShortFract"; break;
780 case BuiltinType::UFract:
781 Out << "@BT@UFract"; break;
782 case BuiltinType::ULongFract:
783 Out << "@BT@ULongFract"; break;
784 case BuiltinType::SatShortAccum:
785 Out << "@BT@SatShortAccum"; break;
786 case BuiltinType::SatAccum:
787 Out << "@BT@SatAccum"; break;
788 case BuiltinType::SatLongAccum:
789 Out << "@BT@SatLongAccum"; break;
790 case BuiltinType::SatUShortAccum:
791 Out << "@BT@SatUShortAccum"; break;
792 case BuiltinType::SatUAccum:
793 Out << "@BT@SatUAccum"; break;
794 case BuiltinType::SatULongAccum:
795 Out << "@BT@SatULongAccum"; break;
796 case BuiltinType::SatShortFract:
797 Out << "@BT@SatShortFract"; break;
798 case BuiltinType::SatFract:
799 Out << "@BT@SatFract"; break;
800 case BuiltinType::SatLongFract:
801 Out << "@BT@SatLongFract"; break;
802 case BuiltinType::SatUShortFract:
803 Out << "@BT@SatUShortFract"; break;
804 case BuiltinType::SatUFract:
805 Out << "@BT@SatUFract"; break;
806 case BuiltinType::SatULongFract:
807 Out << "@BT@SatULongFract"; break;
808 case BuiltinType::BFloat16:
809 Out << "@BT@__bf16"; break;
810 case BuiltinType::Ibm128:
811 Out << "@BT@__ibm128"; break;
812 case BuiltinType::ObjCId:
813 Out << 'o'; break;
814 case BuiltinType::ObjCClass:
815 Out << 'O'; break;
816 case BuiltinType::ObjCSel:
817 Out << 'e'; break;
818#define BUILTIN_TYPE(Id, SingletonId)
819#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
820#include "clang/AST/BuiltinTypes.def"
821 case BuiltinType::Dependent:
822 // If you're adding a new builtin type, please add its name prefixed
823 // with "@BT@" to `Out` (see cases above).
824 IgnoreResults = true;
825 break;
826 }
827 return;
828 }
829
830 // If we have already seen this (non-built-in) type, use a substitution
831 // encoding.
832 llvm::DenseMap<const Type *, unsigned>::iterator Substitution
833 = TypeSubstitutions.find(T.getTypePtr());
834 if (Substitution != TypeSubstitutions.end()) {
835 Out << 'S' << Substitution->second << '_';
836 return;
837 } else {
838 // Record this as a substitution.
839 unsigned Number = TypeSubstitutions.size();
840 TypeSubstitutions[T.getTypePtr()] = Number;
841 }
842
843 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
844 Out << "*M";
845 T = MPT->getPointeeType();
846 continue;
847 }
848 if (const PointerType *PT = T->getAs<PointerType>()) {
849 Out << '*';
850 T = PT->getPointeeType();
851 continue;
852 }
853 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
854 Out << '*';
855 T = OPT->getPointeeType();
856 continue;
857 }
858 if (const RValueReferenceType *RT = T->getAs<RValueReferenceType>()) {
859 Out << "&&";
860 T = RT->getPointeeType();
861 continue;
862 }
863 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
864 Out << '&';
865 T = RT->getPointeeType();
866 continue;
867 }
868 if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {
869 Out << 'F';
870 VisitType(FT->getReturnType());
871 Out << '(';
872 for (const auto &I : FT->param_types()) {
873 Out << '#';
874 VisitType(I);
875 }
876 Out << ')';
877 if (FT->isVariadic())
878 Out << '.';
879
880 clang::RefQualifierKind rq = FT->getRefQualifier();
881
882 switch (rq) {
883 case clang::RQ_None:
884 // No ref-qualifier
885 break;
886 case clang::RQ_LValue:
887 Out << "&&";
888 break;
889 case clang::RQ_RValue:
890 Out << '&';
891 break;
892 }
893
894 return;
895 }
896 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
897 Out << 'B';
898 T = BT->getPointeeType();
899 continue;
900 }
901 if (const ComplexType *CT = T->getAs<ComplexType>()) {
902 Out << '<';
903 T = CT->getElementType();
904 continue;
905 }
906 if (const TagType *TT = T->getAs<TagType>()) {
907 Out << '$';
908 VisitTagDecl(TT->getDecl());
909 return;
910 }
911 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
912 Out << '$';
913 VisitObjCInterfaceDecl(OIT->getDecl());
914 return;
915 }
916 if (const ObjCObjectType *OIT = T->getAs<ObjCObjectType>()) {
917 Out << 'Q';
918 VisitType(OIT->getBaseType());
919 for (auto *Prot : OIT->getProtocols())
920 VisitObjCProtocolDecl(Prot);
921 return;
922 }
923 if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {
924 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
925 return;
926 }
927 if (const TemplateSpecializationType *Spec
928 = T->getAs<TemplateSpecializationType>()) {
929 Out << '>';
930 VisitTemplateName(Spec->getTemplateName());
931 Out << Spec->template_arguments().size();
932 for (const auto &Arg : Spec->template_arguments())
933 VisitTemplateArgument(Arg);
934 return;
935 }
936 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
937 Out << '^';
938 printQualifier(Out, Ctx, DNT->getQualifier());
939 Out << ':' << DNT->getIdentifier()->getName();
940 return;
941 }
942 if (const InjectedClassNameType *InjT = T->getAs<InjectedClassNameType>()) {
943 T = InjT->getInjectedSpecializationType();
944 continue;
945 }
946 if (const auto *VT = T->getAs<VectorType>()) {
947 Out << (T->isExtVectorType() ? ']' : '[');
948 Out << VT->getNumElements();
949 T = VT->getElementType();
950 continue;
951 }
952 if (const auto *const AT = dyn_cast<ArrayType>(T)) {
953 Out << '{';
954 switch (AT->getSizeModifier()) {
955 case ArrayType::Static:
956 Out << 's';
957 break;
958 case ArrayType::Star:
959 Out << '*';
960 break;
961 case ArrayType::Normal:
962 Out << 'n';
963 break;
964 }
965 if (const auto *const CAT = dyn_cast<ConstantArrayType>(T))
966 Out << CAT->getSize();
967
968 T = AT->getElementType();
969 continue;
970 }
971
972 // Unhandled type.
973 Out << ' ';
974 break;
975 } while (true);
976}
977
978void USRGenerator::VisitTemplateParameterList(
979 const TemplateParameterList *Params) {
980 if (!Params)
981 return;
982 Out << '>' << Params->size();
983 for (TemplateParameterList::const_iterator P = Params->begin(),
984 PEnd = Params->end();
985 P != PEnd; ++P) {
986 Out << '#';
987 if (isa<TemplateTypeParmDecl>(*P)) {
988 if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())
989 Out<< 'p';
990 Out << 'T';
991 continue;
992 }
993
994 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
995 if (NTTP->isParameterPack())
996 Out << 'p';
997 Out << 'N';
998 VisitType(NTTP->getType());
999 continue;
1000 }
1001
1002 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
1003 if (TTP->isParameterPack())
1004 Out << 'p';
1005 Out << 't';
1006 VisitTemplateParameterList(TTP->getTemplateParameters());
1007 }
1008}
1009
1010void USRGenerator::VisitTemplateName(TemplateName Name) {
1011 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
1012 if (TemplateTemplateParmDecl *TTP
1013 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
1014 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
1015 return;
1016 }
1017
1018 Visit(Template);
1019 return;
1020 }
1021
1022 // FIXME: Visit dependent template names.
1023}
1024
1025void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {
1026 switch (Arg.getKind()) {
1027 case TemplateArgument::Null:
1028 break;
1029
1030 case TemplateArgument::Declaration:
1031 Visit(Arg.getAsDecl());
1032 break;
1033
1034 case TemplateArgument::NullPtr:
1035 break;
1036
1037 case TemplateArgument::TemplateExpansion:
1038 Out << 'P'; // pack expansion of...
1039 [[fallthrough]];
1040 case TemplateArgument::Template:
1041 VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
1042 break;
1043
1044 case TemplateArgument::Expression:
1045 // FIXME: Visit expressions.
1046 break;
1047
1048 case TemplateArgument::Pack:
1049 Out << 'p' << Arg.pack_size();
1050 for (const auto &P : Arg.pack_elements())
1051 VisitTemplateArgument(P);
1052 break;
1053
1054 case TemplateArgument::Type:
1055 VisitType(Arg.getAsType());
1056 break;
1057
1058 case TemplateArgument::Integral:
1059 Out << 'V';
1060 VisitType(Arg.getIntegralType());
1061 Out << Arg.getAsIntegral();
1062 break;
1063 }
1064}
1065
1066void USRGenerator::VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
1067 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
1068 return;
1069 VisitDeclContext(D->getDeclContext());
1070 Out << "@UUV@";
1071 printQualifier(Out, D->getASTContext(), D->getQualifier());
1072 EmitDeclName(D);
1073}
1074
1075void USRGenerator::VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D) {
1076 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
1077 return;
1078 VisitDeclContext(D->getDeclContext());
1079 Out << "@UUT@";
1080 printQualifier(Out, D->getASTContext(), D->getQualifier());
1081 Out << D->getName(); // Simple name.
1082}
1083
1084void USRGenerator::VisitConceptDecl(const ConceptDecl *D) {
1085 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
1086 return;
1087 VisitDeclContext(D->getDeclContext());
1088 Out << "@CT@";
1089 EmitDeclName(D);
1090}
1091
1092void USRGenerator::VisitMSGuidDecl(const MSGuidDecl *D) {
1093 VisitDeclContext(D->getDeclContext());
1094 Out << "@MG@";
1095 D->NamedDecl::printName(Out);
1096}
1097
1098//===----------------------------------------------------------------------===//
1099// USR generation functions.
1100//===----------------------------------------------------------------------===//
1101
1102static void combineClassAndCategoryExtContainers(StringRef ClsSymDefinedIn,
1103 StringRef CatSymDefinedIn,
1104 raw_ostream &OS) {
1105 if (ClsSymDefinedIn.empty() && CatSymDefinedIn.empty())
1106 return;
1107 if (CatSymDefinedIn.empty()) {
1108 OS << "@M@" << ClsSymDefinedIn << '@';
1109 return;
1110 }
1111 OS << "@CM@" << CatSymDefinedIn << '@';
1112 if (ClsSymDefinedIn != CatSymDefinedIn) {
1113 OS << ClsSymDefinedIn << '@';
1114 }
1115}
1116
1117void common::index::generateUSRForObjCClass(StringRef Cls, raw_ostream &OS,
1118 StringRef ExtSymDefinedIn,
1119 StringRef CategoryContextExtSymbolDefinedIn) {
1121 CategoryContextExtSymbolDefinedIn, OS);
1122 OS << "objc(cs)" << Cls;
1123}
1124
1125void common::index::generateUSRForObjCCategory(StringRef Cls, StringRef Cat,
1126 raw_ostream &OS,
1127 StringRef ClsSymDefinedIn,
1128 StringRef CatSymDefinedIn) {
1129 combineClassAndCategoryExtContainers(ClsSymDefinedIn, CatSymDefinedIn, OS);
1130 OS << "objc(cy)" << Cls << '@' << Cat;
1131}
1132
1133void common::index::generateUSRForObjCIvar(StringRef Ivar, raw_ostream &OS) {
1134 OS << '@' << Ivar;
1135}
1136
1138 bool IsInstanceMethod,
1139 raw_ostream &OS) {
1140 OS << (IsInstanceMethod ? "(im)" : "(cm)") << Sel;
1141}
1142
1143void common::index::generateUSRForObjCProperty(StringRef Prop, bool isClassProp,
1144 raw_ostream &OS) {
1145 OS << (isClassProp ? "(cpy)" : "(py)") << Prop;
1146}
1147
1148void common::index::generateUSRForObjCProtocol(StringRef Prot, raw_ostream &OS,
1149 StringRef ExtSymDefinedIn) {
1150 if (!ExtSymDefinedIn.empty())
1151 OS << "@M@" << ExtSymDefinedIn << '@';
1152 OS << "objc(pl)" << Prot;
1153}
1154
1155void common::index::generateUSRForGlobalEnum(StringRef EnumName, raw_ostream &OS,
1156 StringRef ExtSymDefinedIn) {
1157 if (!ExtSymDefinedIn.empty())
1158 OS << "@M@" << ExtSymDefinedIn;
1159 OS << "@E@" << EnumName;
1160}
1161
1162void common::index::generateUSRForEnumConstant(StringRef EnumConstantName,
1163 raw_ostream &OS) {
1164 OS << '@' << EnumConstantName;
1165}
1166
1167bool common::index::generateUSRForDecl(const Decl *D,
1168 SmallVectorImpl<char> &Buf) {
1169 if (!D)
1170 return true;
1171 // We don't ignore decls with invalid source locations. Implicit decls, like
1172 // C++'s operator new function, can have invalid locations but it is fine to
1173 // create USRs that can identify them.
1174
1175 // Check if the declaration has explicit external USR specified.
1176 auto *CD = D->getCanonicalDecl();
1177 if (auto *ExternalSymAttr = CD->getAttr<ExternalSourceSymbolAttr>()) {
1178 if (!ExternalSymAttr->getUSR().empty()) {
1179 llvm::raw_svector_ostream Out(Buf);
1180 Out << ExternalSymAttr->getUSR();
1181 return false;
1182 }
1183 }
1184 USRGenerator UG(&D->getASTContext(), Buf);
1185 UG.Visit(D);
1186 return UG.ignoreResults();
1187}
1188
1189bool common::index::generateUSRForMacro(const MacroDefinitionRecord *MD,
1190 const SourceManager &SM,
1191 SmallVectorImpl<char> &Buf) {
1192 if (!MD)
1193 return true;
1194 return generateUSRForMacro(MD->getName()->getName(), MD->getLocation(),
1195 SM, Buf);
1196
1197}
1198
1199bool common::index::generateUSRForMacro(StringRef MacroName, SourceLocation Loc,
1200 const SourceManager &SM,
1201 SmallVectorImpl<char> &Buf) {
1202 if (MacroName.empty())
1203 return true;
1204
1205 llvm::raw_svector_ostream Out(Buf);
1206
1207 // Assume that system headers are sane. Don't put source location
1208 // information into the USR if the macro comes from a system header.
1209 bool ShouldGenerateLocation = Loc.isValid() && !SM.isInSystemHeader(Loc);
1210
1211 Out << getUSRSpacePrefix();
1212 if (ShouldGenerateLocation)
1213 printLoc(Out, Loc, SM, /*IncludeOffset=*/true);
1214 Out << "@macro@";
1215 Out << MacroName;
1216 return false;
1217}
1218
1219bool common::index::generateUSRForType(QualType T, ASTContext &Ctx,
1220 SmallVectorImpl<char> &Buf) {
1221 if (T.isNull())
1222 return true;
1223 T = T.getCanonicalType();
1224
1225 USRGenerator UG(&Ctx, Buf);
1226 UG.VisitType(T);
1227 return UG.ignoreResults();
1228}
1229
1230bool common::index::generateFullUSRForModule(const Module *Mod,
1231 raw_ostream &OS) {
1232 if (!Mod->Parent)
1233 return generateFullUSRForTopLevelModuleName(Mod->Name, OS);
1234 if (generateFullUSRForModule(Mod->Parent, OS))
1235 return true;
1236 return generateUSRFragmentForModule(Mod, OS);
1237}
1238
1240 raw_ostream &OS) {
1241 OS << getUSRSpacePrefix();
1242 return generateUSRFragmentForModuleName(ModName, OS);
1243}
1244
1245bool common::index::generateUSRFragmentForModule(const Module *Mod,
1246 raw_ostream &OS) {
1247 return generateUSRFragmentForModuleName(Mod->Name, OS);
1248}
1249
1251 raw_ostream &OS) {
1252 OS << "@M@" << ModName;
1253 return false;
1254}
1255
1256} // namespace clanguml