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