blob: a15ad12b098861ff15d89ef60439b4bcc128dfcb [file] [log] [blame]
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +00001//===- USRGeneration.cpp - Routines for USR generation --------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Argyrios Kyrtzidis15a2fcc2013-08-17 00:40:41 +000010#include "clang/Index/USRGeneration.h"
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +000011#include "clang/AST/ASTContext.h"
12#include "clang/AST/DeclTemplate.h"
13#include "clang/AST/DeclVisitor.h"
Dmitri Gribenko237769e2014-03-28 22:21:26 +000014#include "clang/Lex/PreprocessingRecord.h"
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +000015#include "llvm/ADT/SmallString.h"
16#include "llvm/Support/Path.h"
17#include "llvm/Support/raw_ostream.h"
18
19using namespace clang;
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +000020using namespace clang::index;
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +000021
22//===----------------------------------------------------------------------===//
23// USR generation.
24//===----------------------------------------------------------------------===//
25
Dmitri Gribenko237769e2014-03-28 22:21:26 +000026/// \returns true on error.
27static bool printLoc(llvm::raw_ostream &OS, SourceLocation Loc,
28 const SourceManager &SM, bool IncludeOffset) {
29 if (Loc.isInvalid()) {
30 return true;
31 }
32 Loc = SM.getExpansionLoc(Loc);
33 const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(Loc);
34 const FileEntry *FE = SM.getFileEntryForID(Decomposed.first);
35 if (FE) {
36 OS << llvm::sys::path::filename(FE->getName());
37 } else {
38 // This case really isn't interesting.
39 return true;
40 }
41 if (IncludeOffset) {
42 // Use the offest into the FileID to represent the location. Using
43 // a line/column can cause us to look back at the original source file,
44 // which is expensive.
45 OS << '@' << Decomposed.second;
46 }
47 return false;
48}
49
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +000050namespace {
51class USRGenerator : public ConstDeclVisitor<USRGenerator> {
52 SmallVectorImpl<char> &Buf;
53 llvm::raw_svector_ostream Out;
54 bool IgnoreResults;
55 ASTContext *Context;
56 bool generatedLoc;
57
58 llvm::DenseMap<const Type *, unsigned> TypeSubstitutions;
59
60public:
61 explicit USRGenerator(ASTContext *Ctx, SmallVectorImpl<char> &Buf)
62 : Buf(Buf),
63 Out(Buf),
64 IgnoreResults(false),
65 Context(Ctx),
66 generatedLoc(false)
67 {
68 // Add the USR space prefix.
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +000069 Out << getUSRSpacePrefix();
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +000070 }
71
72 bool ignoreResults() const { return IgnoreResults; }
73
74 // Visitation methods from generating USRs from AST elements.
75 void VisitDeclContext(const DeclContext *D);
76 void VisitFieldDecl(const FieldDecl *D);
77 void VisitFunctionDecl(const FunctionDecl *D);
78 void VisitNamedDecl(const NamedDecl *D);
79 void VisitNamespaceDecl(const NamespaceDecl *D);
80 void VisitNamespaceAliasDecl(const NamespaceAliasDecl *D);
81 void VisitFunctionTemplateDecl(const FunctionTemplateDecl *D);
82 void VisitClassTemplateDecl(const ClassTemplateDecl *D);
83 void VisitObjCContainerDecl(const ObjCContainerDecl *CD);
84 void VisitObjCMethodDecl(const ObjCMethodDecl *MD);
85 void VisitObjCPropertyDecl(const ObjCPropertyDecl *D);
86 void VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D);
87 void VisitTagDecl(const TagDecl *D);
88 void VisitTypedefDecl(const TypedefDecl *D);
89 void VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D);
90 void VisitVarDecl(const VarDecl *D);
91 void VisitNonTypeTemplateParmDecl(const NonTypeTemplateParmDecl *D);
92 void VisitTemplateTemplateParmDecl(const TemplateTemplateParmDecl *D);
Eugene Zelenko1ced5092016-02-12 22:53:10 +000093
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +000094 void VisitLinkageSpecDecl(const LinkageSpecDecl *D) {
95 IgnoreResults = true;
96 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +000097
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +000098 void VisitUsingDirectiveDecl(const UsingDirectiveDecl *D) {
99 IgnoreResults = true;
100 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000101
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000102 void VisitUsingDecl(const UsingDecl *D) {
103 IgnoreResults = true;
104 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000105
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000106 void VisitUnresolvedUsingValueDecl(const UnresolvedUsingValueDecl *D) {
107 IgnoreResults = true;
108 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000109
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000110 void VisitUnresolvedUsingTypenameDecl(const UnresolvedUsingTypenameDecl *D) {
111 IgnoreResults = true;
112 }
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000113
114 bool ShouldGenerateLocation(const NamedDecl *D);
115
116 bool isLocal(const NamedDecl *D) {
Craig Topper236bde32014-05-26 06:21:51 +0000117 return D->getParentFunctionOrMethod() != nullptr;
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000118 }
119
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000120 /// Generate the string component containing the location of the
121 /// declaration.
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000122 bool GenLoc(const Decl *D, bool IncludeOffset);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000123
124 /// String generation methods used both by the visitation methods
125 /// and from other clients that want to directly generate USRs. These
126 /// methods do not construct complete USRs (which incorporate the parents
127 /// of an AST element), but only the fragments concerning the AST element
128 /// itself.
129
130 /// Generate a USR for an Objective-C class.
131 void GenObjCClass(StringRef cls) {
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000132 generateUSRForObjCClass(cls, Out);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000133 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000134
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000135 /// Generate a USR for an Objective-C class category.
136 void GenObjCCategory(StringRef cls, StringRef cat) {
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000137 generateUSRForObjCCategory(cls, cat, Out);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000138 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000139
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000140 /// Generate a USR fragment for an Objective-C property.
141 void GenObjCProperty(StringRef prop) {
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000142 generateUSRForObjCProperty(prop, Out);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000143 }
Eugene Zelenko1ced5092016-02-12 22:53:10 +0000144
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000145 /// Generate a USR for an Objective-C protocol.
146 void GenObjCProtocol(StringRef prot) {
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000147 generateUSRForObjCProtocol(prot, Out);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000148 }
149
150 void VisitType(QualType T);
151 void VisitTemplateParameterList(const TemplateParameterList *Params);
152 void VisitTemplateName(TemplateName Name);
153 void VisitTemplateArgument(const TemplateArgument &Arg);
154
155 /// Emit a Decl's name using NamedDecl::printName() and return true if
156 /// the decl had no name.
157 bool EmitDeclName(const NamedDecl *D);
158};
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000159} // end anonymous namespace
160
161//===----------------------------------------------------------------------===//
162// Generating USRs from ASTS.
163//===----------------------------------------------------------------------===//
164
165bool USRGenerator::EmitDeclName(const NamedDecl *D) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000166 const unsigned startSize = Buf.size();
167 D->printName(Out);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000168 const unsigned endSize = Buf.size();
169 return startSize == endSize;
170}
171
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000172bool USRGenerator::ShouldGenerateLocation(const NamedDecl *D) {
173 if (D->isExternallyVisible())
174 return false;
175 if (D->getParentFunctionOrMethod())
176 return true;
177 const SourceManager &SM = Context->getSourceManager();
178 return !SM.isInSystemHeader(D->getLocation());
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000179}
180
181void USRGenerator::VisitDeclContext(const DeclContext *DC) {
182 if (const NamedDecl *D = dyn_cast<NamedDecl>(DC))
183 Visit(D);
184}
185
186void USRGenerator::VisitFieldDecl(const FieldDecl *D) {
187 // The USR for an ivar declared in a class extension is based on the
188 // ObjCInterfaceDecl, not the ObjCCategoryDecl.
189 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
190 Visit(ID);
191 else
192 VisitDeclContext(D->getDeclContext());
193 Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@");
194 if (EmitDeclName(D)) {
195 // Bit fields can be anonymous.
196 IgnoreResults = true;
197 return;
198 }
199}
200
201void USRGenerator::VisitFunctionDecl(const FunctionDecl *D) {
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000202 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000203 return;
204
205 VisitDeclContext(D->getDeclContext());
Argyrios Kyrtzidisd06ce402014-12-08 08:48:11 +0000206 bool IsTemplate = false;
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000207 if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {
Argyrios Kyrtzidisd06ce402014-12-08 08:48:11 +0000208 IsTemplate = true;
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000209 Out << "@FT@";
210 VisitTemplateParameterList(FunTmpl->getTemplateParameters());
211 } else
212 Out << "@F@";
Argyrios Kyrtzidisd5719082016-02-15 01:32:36 +0000213
214 PrintingPolicy Policy(Context->getLangOpts());
215 // Forward references can have different template argument names. Suppress the
216 // template argument names in constructors to make their USR more stable.
217 Policy.SuppressTemplateArgsInCXXConstructors = true;
218 D->getDeclName().print(Out, Policy);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000219
220 ASTContext &Ctx = *Context;
Argyrios Kyrtzidis2682f9e2016-03-04 07:17:48 +0000221 if ((!Ctx.getLangOpts().CPlusPlus || D->isExternC()) &&
222 !D->hasAttr<OverloadableAttr>())
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000223 return;
224
225 if (const TemplateArgumentList *
226 SpecArgs = D->getTemplateSpecializationArgs()) {
227 Out << '<';
228 for (unsigned I = 0, N = SpecArgs->size(); I != N; ++I) {
229 Out << '#';
230 VisitTemplateArgument(SpecArgs->get(I));
231 }
232 Out << '>';
233 }
234
235 // Mangle in type information for the arguments.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +0000236 for (auto PD : D->params()) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000237 Out << '#';
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +0000238 VisitType(PD->getType());
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000239 }
240 if (D->isVariadic())
241 Out << '.';
Argyrios Kyrtzidisd06ce402014-12-08 08:48:11 +0000242 if (IsTemplate) {
243 // Function templates can be overloaded by return type, for example:
244 // \code
245 // template <class T> typename T::A foo() {}
246 // template <class T> typename T::B foo() {}
247 // \endcode
248 Out << '#';
249 VisitType(D->getReturnType());
250 }
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000251 Out << '#';
252 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
253 if (MD->isStatic())
254 Out << 'S';
255 if (unsigned quals = MD->getTypeQualifiers())
256 Out << (char)('0' + quals);
Argyrios Kyrtzidisf5819092014-12-08 08:48:21 +0000257 switch (MD->getRefQualifier()) {
258 case RQ_None: break;
259 case RQ_LValue: Out << '&'; break;
260 case RQ_RValue: Out << "&&"; break;
261 }
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000262 }
263}
264
265void USRGenerator::VisitNamedDecl(const NamedDecl *D) {
266 VisitDeclContext(D->getDeclContext());
267 Out << "@";
268
269 if (EmitDeclName(D)) {
270 // The string can be empty if the declaration has no name; e.g., it is
271 // the ParmDecl with no name for declaration of a function pointer type,
272 // e.g.: void (*f)(void *);
273 // In this case, don't generate a USR.
274 IgnoreResults = true;
275 }
276}
277
278void USRGenerator::VisitVarDecl(const VarDecl *D) {
279 // VarDecls can be declared 'extern' within a function or method body,
280 // but their enclosing DeclContext is the function, not the TU. We need
281 // to check the storage class to correctly generate the USR.
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000282 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000283 return;
284
285 VisitDeclContext(D->getDeclContext());
286
287 // Variables always have simple names.
288 StringRef s = D->getName();
289
290 // The string can be empty if the declaration has no name; e.g., it is
291 // the ParmDecl with no name for declaration of a function pointer type, e.g.:
292 // void (*f)(void *);
293 // In this case, don't generate a USR.
294 if (s.empty())
295 IgnoreResults = true;
296 else
297 Out << '@' << s;
298}
299
300void USRGenerator::VisitNonTypeTemplateParmDecl(
301 const NonTypeTemplateParmDecl *D) {
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000302 GenLoc(D, /*IncludeOffset=*/true);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000303}
304
305void USRGenerator::VisitTemplateTemplateParmDecl(
306 const TemplateTemplateParmDecl *D) {
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000307 GenLoc(D, /*IncludeOffset=*/true);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000308}
309
310void USRGenerator::VisitNamespaceDecl(const NamespaceDecl *D) {
311 if (D->isAnonymousNamespace()) {
312 Out << "@aN";
313 return;
314 }
315
316 VisitDeclContext(D->getDeclContext());
317 if (!IgnoreResults)
318 Out << "@N@" << D->getName();
319}
320
321void USRGenerator::VisitFunctionTemplateDecl(const FunctionTemplateDecl *D) {
322 VisitFunctionDecl(D->getTemplatedDecl());
323}
324
325void USRGenerator::VisitClassTemplateDecl(const ClassTemplateDecl *D) {
326 VisitTagDecl(D->getTemplatedDecl());
327}
328
329void USRGenerator::VisitNamespaceAliasDecl(const NamespaceAliasDecl *D) {
330 VisitDeclContext(D->getDeclContext());
331 if (!IgnoreResults)
332 Out << "@NA@" << D->getName();
333}
334
335void USRGenerator::VisitObjCMethodDecl(const ObjCMethodDecl *D) {
336 const DeclContext *container = D->getDeclContext();
337 if (const ObjCProtocolDecl *pd = dyn_cast<ObjCProtocolDecl>(container)) {
338 Visit(pd);
339 }
340 else {
341 // The USR for a method declared in a class extension or category is based on
342 // the ObjCInterfaceDecl, not the ObjCCategoryDecl.
343 const ObjCInterfaceDecl *ID = D->getClassInterface();
344 if (!ID) {
345 IgnoreResults = true;
346 return;
347 }
348 Visit(ID);
349 }
350 // Ideally we would use 'GenObjCMethod', but this is such a hot path
351 // for Objective-C code that we don't want to use
352 // DeclarationName::getAsString().
353 Out << (D->isInstanceMethod() ? "(im)" : "(cm)")
354 << DeclarationName(D->getSelector());
355}
356
357void USRGenerator::VisitObjCContainerDecl(const ObjCContainerDecl *D) {
358 switch (D->getKind()) {
359 default:
360 llvm_unreachable("Invalid ObjC container.");
361 case Decl::ObjCInterface:
362 case Decl::ObjCImplementation:
363 GenObjCClass(D->getName());
364 break;
365 case Decl::ObjCCategory: {
366 const ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
367 const ObjCInterfaceDecl *ID = CD->getClassInterface();
368 if (!ID) {
369 // Handle invalid code where the @interface might not
370 // have been specified.
371 // FIXME: We should be able to generate this USR even if the
372 // @interface isn't available.
373 IgnoreResults = true;
374 return;
375 }
376 // Specially handle class extensions, which are anonymous categories.
377 // We want to mangle in the location to uniquely distinguish them.
378 if (CD->IsClassExtension()) {
379 Out << "objc(ext)" << ID->getName() << '@';
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000380 GenLoc(CD, /*IncludeOffset=*/true);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000381 }
382 else
383 GenObjCCategory(ID->getName(), CD->getName());
384
385 break;
386 }
387 case Decl::ObjCCategoryImpl: {
388 const ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
389 const ObjCInterfaceDecl *ID = CD->getClassInterface();
390 if (!ID) {
391 // Handle invalid code where the @interface might not
392 // have been specified.
393 // FIXME: We should be able to generate this USR even if the
394 // @interface isn't available.
395 IgnoreResults = true;
396 return;
397 }
398 GenObjCCategory(ID->getName(), CD->getName());
399 break;
400 }
401 case Decl::ObjCProtocol:
402 GenObjCProtocol(cast<ObjCProtocolDecl>(D)->getName());
403 break;
404 }
405}
406
407void USRGenerator::VisitObjCPropertyDecl(const ObjCPropertyDecl *D) {
408 // The USR for a property declared in a class extension or category is based
409 // on the ObjCInterfaceDecl, not the ObjCCategoryDecl.
410 if (const ObjCInterfaceDecl *ID = Context->getObjContainingInterface(D))
411 Visit(ID);
412 else
413 Visit(cast<Decl>(D->getDeclContext()));
414 GenObjCProperty(D->getName());
415}
416
417void USRGenerator::VisitObjCPropertyImplDecl(const ObjCPropertyImplDecl *D) {
418 if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {
419 VisitObjCPropertyDecl(PD);
420 return;
421 }
422
423 IgnoreResults = true;
424}
425
426void USRGenerator::VisitTagDecl(const TagDecl *D) {
427 // Add the location of the tag decl to handle resolution across
428 // translation units.
Argyrios Kyrtzidis73321062016-03-04 07:17:53 +0000429 if (!isa<EnumDecl>(D) &&
430 ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000431 return;
432
433 D = D->getCanonicalDecl();
434 VisitDeclContext(D->getDeclContext());
435
436 bool AlreadyStarted = false;
437 if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) {
438 if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) {
439 AlreadyStarted = true;
440
441 switch (D->getTagKind()) {
442 case TTK_Interface:
Argyrios Kyrtzidisf66cef72014-12-08 08:48:33 +0000443 case TTK_Class:
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000444 case TTK_Struct: Out << "@ST"; break;
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000445 case TTK_Union: Out << "@UT"; break;
446 case TTK_Enum: llvm_unreachable("enum template");
447 }
448 VisitTemplateParameterList(ClassTmpl->getTemplateParameters());
449 } else if (const ClassTemplatePartialSpecializationDecl *PartialSpec
450 = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) {
451 AlreadyStarted = true;
452
453 switch (D->getTagKind()) {
454 case TTK_Interface:
Argyrios Kyrtzidisf66cef72014-12-08 08:48:33 +0000455 case TTK_Class:
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000456 case TTK_Struct: Out << "@SP"; break;
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000457 case TTK_Union: Out << "@UP"; break;
458 case TTK_Enum: llvm_unreachable("enum partial specialization");
459 }
460 VisitTemplateParameterList(PartialSpec->getTemplateParameters());
461 }
462 }
463
464 if (!AlreadyStarted) {
465 switch (D->getTagKind()) {
466 case TTK_Interface:
Argyrios Kyrtzidisf66cef72014-12-08 08:48:33 +0000467 case TTK_Class:
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000468 case TTK_Struct: Out << "@S"; break;
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000469 case TTK_Union: Out << "@U"; break;
470 case TTK_Enum: Out << "@E"; break;
471 }
472 }
473
474 Out << '@';
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000475 assert(Buf.size() > 0);
476 const unsigned off = Buf.size() - 1;
477
478 if (EmitDeclName(D)) {
479 if (const TypedefNameDecl *TD = D->getTypedefNameForAnonDecl()) {
480 Buf[off] = 'A';
481 Out << '@' << *TD;
482 }
Argyrios Kyrtzidis80537a42014-12-08 08:48:37 +0000483 else {
484 if (D->isEmbeddedInDeclarator() && !D->isFreeStanding()) {
485 printLoc(Out, D->getLocation(), Context->getSourceManager(), true);
Argyrios Kyrtzidis73321062016-03-04 07:17:53 +0000486 } else {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000487 Buf[off] = 'a';
Argyrios Kyrtzidis73321062016-03-04 07:17:53 +0000488 if (auto *ED = dyn_cast<EnumDecl>(D)) {
489 // Distinguish USRs of anonymous enums by using their first enumerator.
490 auto enum_range = ED->enumerators();
491 if (enum_range.begin() != enum_range.end()) {
492 Out << '@' << **enum_range.begin();
493 }
494 }
495 }
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000496 }
Argyrios Kyrtzidis80537a42014-12-08 08:48:37 +0000497 }
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000498
499 // For a class template specialization, mangle the template arguments.
500 if (const ClassTemplateSpecializationDecl *Spec
501 = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
502 const TemplateArgumentList &Args = Spec->getTemplateInstantiationArgs();
503 Out << '>';
504 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
505 Out << '#';
506 VisitTemplateArgument(Args.get(I));
507 }
508 }
509}
510
511void USRGenerator::VisitTypedefDecl(const TypedefDecl *D) {
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000512 if (ShouldGenerateLocation(D) && GenLoc(D, /*IncludeOffset=*/isLocal(D)))
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000513 return;
514 const DeclContext *DC = D->getDeclContext();
515 if (const NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
516 Visit(DCN);
517 Out << "@T@";
518 Out << D->getName();
519}
520
521void USRGenerator::VisitTemplateTypeParmDecl(const TemplateTypeParmDecl *D) {
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000522 GenLoc(D, /*IncludeOffset=*/true);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000523}
524
Argyrios Kyrtzidisd3ba4102014-02-23 18:23:29 +0000525bool USRGenerator::GenLoc(const Decl *D, bool IncludeOffset) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000526 if (generatedLoc)
527 return IgnoreResults;
528 generatedLoc = true;
Dmitri Gribenko237769e2014-03-28 22:21:26 +0000529
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000530 // Guard against null declarations in invalid code.
531 if (!D) {
532 IgnoreResults = true;
533 return true;
534 }
535
536 // Use the location of canonical decl.
537 D = D->getCanonicalDecl();
538
Dmitri Gribenko237769e2014-03-28 22:21:26 +0000539 IgnoreResults =
540 IgnoreResults || printLoc(Out, D->getLocStart(),
541 Context->getSourceManager(), IncludeOffset);
542
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000543 return IgnoreResults;
544}
545
546void USRGenerator::VisitType(QualType T) {
547 // This method mangles in USR information for types. It can possibly
548 // just reuse the naming-mangling logic used by codegen, although the
549 // requirements for USRs might not be the same.
550 ASTContext &Ctx = *Context;
551
552 do {
553 T = Ctx.getCanonicalType(T);
554 Qualifiers Q = T.getQualifiers();
555 unsigned qVal = 0;
556 if (Q.hasConst())
557 qVal |= 0x1;
558 if (Q.hasVolatile())
559 qVal |= 0x2;
560 if (Q.hasRestrict())
561 qVal |= 0x4;
562 if(qVal)
563 Out << ((char) ('0' + qVal));
564
565 // Mangle in ObjC GC qualifiers?
566
567 if (const PackExpansionType *Expansion = T->getAs<PackExpansionType>()) {
568 Out << 'P';
569 T = Expansion->getPattern();
570 }
571
572 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
573 unsigned char c = '\0';
574 switch (BT->getKind()) {
575 case BuiltinType::Void:
576 c = 'v'; break;
577 case BuiltinType::Bool:
578 c = 'b'; break;
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000579 case BuiltinType::UChar:
580 c = 'c'; break;
581 case BuiltinType::Char16:
582 c = 'q'; break;
583 case BuiltinType::Char32:
584 c = 'w'; break;
585 case BuiltinType::UShort:
586 c = 's'; break;
587 case BuiltinType::UInt:
588 c = 'i'; break;
589 case BuiltinType::ULong:
590 c = 'l'; break;
591 case BuiltinType::ULongLong:
592 c = 'k'; break;
593 case BuiltinType::UInt128:
594 c = 'j'; break;
Argyrios Kyrtzidis56af7e62014-12-08 09:09:05 +0000595 case BuiltinType::Char_U:
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000596 case BuiltinType::Char_S:
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000597 c = 'C'; break;
Argyrios Kyrtzidisca044542014-12-08 08:48:17 +0000598 case BuiltinType::SChar:
599 c = 'r'; break;
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000600 case BuiltinType::WChar_S:
601 case BuiltinType::WChar_U:
602 c = 'W'; break;
603 case BuiltinType::Short:
604 c = 'S'; break;
605 case BuiltinType::Int:
606 c = 'I'; break;
607 case BuiltinType::Long:
608 c = 'L'; break;
609 case BuiltinType::LongLong:
610 c = 'K'; break;
611 case BuiltinType::Int128:
612 c = 'J'; break;
613 case BuiltinType::Half:
614 c = 'h'; break;
615 case BuiltinType::Float:
616 c = 'f'; break;
617 case BuiltinType::Double:
618 c = 'd'; break;
619 case BuiltinType::LongDouble:
620 c = 'D'; break;
621 case BuiltinType::NullPtr:
622 c = 'n'; break;
623#define BUILTIN_TYPE(Id, SingletonId)
624#define PLACEHOLDER_TYPE(Id, SingletonId) case BuiltinType::Id:
625#include "clang/AST/BuiltinTypes.def"
626 case BuiltinType::Dependent:
Alexey Bader954ba212016-04-08 13:40:33 +0000627#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
628 case BuiltinType::Id:
629#include "clang/AST/OpenCLImageTypes.def"
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000630 case BuiltinType::OCLEvent:
Alexey Bader9c8453f2015-09-15 11:18:52 +0000631 case BuiltinType::OCLClkEvent:
632 case BuiltinType::OCLQueue:
633 case BuiltinType::OCLNDRange:
634 case BuiltinType::OCLReserveID:
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000635 case BuiltinType::OCLSampler:
636 IgnoreResults = true;
637 return;
638 case BuiltinType::ObjCId:
639 c = 'o'; break;
640 case BuiltinType::ObjCClass:
641 c = 'O'; break;
642 case BuiltinType::ObjCSel:
643 c = 'e'; break;
644 }
645 Out << c;
646 return;
647 }
648
649 // If we have already seen this (non-built-in) type, use a substitution
650 // encoding.
651 llvm::DenseMap<const Type *, unsigned>::iterator Substitution
652 = TypeSubstitutions.find(T.getTypePtr());
653 if (Substitution != TypeSubstitutions.end()) {
654 Out << 'S' << Substitution->second << '_';
655 return;
656 } else {
657 // Record this as a substitution.
658 unsigned Number = TypeSubstitutions.size();
659 TypeSubstitutions[T.getTypePtr()] = Number;
660 }
661
662 if (const PointerType *PT = T->getAs<PointerType>()) {
663 Out << '*';
664 T = PT->getPointeeType();
665 continue;
666 }
Argyrios Kyrtzidis9c998672016-03-04 07:17:43 +0000667 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) {
668 Out << '*';
669 T = OPT->getPointeeType();
670 continue;
671 }
Argyrios Kyrtzidis0e387dc2014-12-08 08:48:27 +0000672 if (const RValueReferenceType *RT = T->getAs<RValueReferenceType>()) {
673 Out << "&&";
674 T = RT->getPointeeType();
675 continue;
676 }
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000677 if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
678 Out << '&';
679 T = RT->getPointeeType();
680 continue;
681 }
682 if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {
683 Out << 'F';
Alp Toker314cc812014-01-25 16:55:45 +0000684 VisitType(FT->getReturnType());
Aaron Ballman40bd0aa2014-03-17 15:23:01 +0000685 for (const auto &I : FT->param_types())
686 VisitType(I);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000687 if (FT->isVariadic())
688 Out << '.';
689 return;
690 }
691 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
692 Out << 'B';
693 T = BT->getPointeeType();
694 continue;
695 }
696 if (const ComplexType *CT = T->getAs<ComplexType>()) {
697 Out << '<';
698 T = CT->getElementType();
699 continue;
700 }
701 if (const TagType *TT = T->getAs<TagType>()) {
702 Out << '$';
703 VisitTagDecl(TT->getDecl());
704 return;
705 }
Argyrios Kyrtzidis9c998672016-03-04 07:17:43 +0000706 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) {
707 Out << '$';
708 VisitObjCInterfaceDecl(OIT->getDecl());
709 return;
710 }
711 if (const ObjCObjectType *OIT = T->getAs<ObjCObjectType>()) {
712 Out << 'Q';
713 VisitType(OIT->getBaseType());
714 for (auto *Prot : OIT->getProtocols())
715 VisitObjCProtocolDecl(Prot);
716 return;
717 }
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000718 if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {
719 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
720 return;
721 }
722 if (const TemplateSpecializationType *Spec
723 = T->getAs<TemplateSpecializationType>()) {
724 Out << '>';
725 VisitTemplateName(Spec->getTemplateName());
726 Out << Spec->getNumArgs();
727 for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
728 VisitTemplateArgument(Spec->getArg(I));
729 return;
730 }
Argyrios Kyrtzidisd06ce402014-12-08 08:48:11 +0000731 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) {
732 Out << '^';
733 // FIXME: Encode the qualifier, don't just print it.
734 PrintingPolicy PO(Ctx.getLangOpts());
735 PO.SuppressTagKeyword = true;
736 PO.SuppressUnwrittenScope = true;
737 PO.ConstantArraySizeAsWritten = false;
738 PO.AnonymousTagLocations = false;
739 DNT->getQualifier()->print(Out, PO);
740 Out << ':' << DNT->getIdentifier()->getName();
741 return;
742 }
Argyrios Kyrtzidis1d5e5422014-12-08 08:48:43 +0000743 if (const InjectedClassNameType *InjT = T->getAs<InjectedClassNameType>()) {
744 T = InjT->getInjectedSpecializationType();
745 continue;
746 }
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000747
748 // Unhandled type.
749 Out << ' ';
750 break;
751 } while (true);
752}
753
754void USRGenerator::VisitTemplateParameterList(
755 const TemplateParameterList *Params) {
756 if (!Params)
757 return;
758 Out << '>' << Params->size();
759 for (TemplateParameterList::const_iterator P = Params->begin(),
760 PEnd = Params->end();
761 P != PEnd; ++P) {
762 Out << '#';
763 if (isa<TemplateTypeParmDecl>(*P)) {
764 if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())
765 Out<< 'p';
766 Out << 'T';
767 continue;
768 }
769
770 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
771 if (NTTP->isParameterPack())
772 Out << 'p';
773 Out << 'N';
774 VisitType(NTTP->getType());
775 continue;
776 }
777
778 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
779 if (TTP->isParameterPack())
780 Out << 'p';
781 Out << 't';
782 VisitTemplateParameterList(TTP->getTemplateParameters());
783 }
784}
785
786void USRGenerator::VisitTemplateName(TemplateName Name) {
787 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
788 if (TemplateTemplateParmDecl *TTP
789 = dyn_cast<TemplateTemplateParmDecl>(Template)) {
790 Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
791 return;
792 }
793
794 Visit(Template);
795 return;
796 }
797
798 // FIXME: Visit dependent template names.
799}
800
801void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {
802 switch (Arg.getKind()) {
803 case TemplateArgument::Null:
804 break;
805
806 case TemplateArgument::Declaration:
807 Visit(Arg.getAsDecl());
808 break;
809
810 case TemplateArgument::NullPtr:
811 break;
812
813 case TemplateArgument::TemplateExpansion:
814 Out << 'P'; // pack expansion of...
815 // Fall through
816 case TemplateArgument::Template:
817 VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
818 break;
819
820 case TemplateArgument::Expression:
821 // FIXME: Visit expressions.
822 break;
823
824 case TemplateArgument::Pack:
825 Out << 'p' << Arg.pack_size();
Aaron Ballman2a89e852014-07-15 21:32:31 +0000826 for (const auto &P : Arg.pack_elements())
827 VisitTemplateArgument(P);
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000828 break;
829
830 case TemplateArgument::Type:
831 VisitType(Arg.getAsType());
832 break;
833
834 case TemplateArgument::Integral:
835 Out << 'V';
836 VisitType(Arg.getIntegralType());
837 Out << Arg.getAsIntegral();
838 break;
839 }
840}
841
842//===----------------------------------------------------------------------===//
843// USR generation functions.
844//===----------------------------------------------------------------------===//
845
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000846void clang::index::generateUSRForObjCClass(StringRef Cls, raw_ostream &OS) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000847 OS << "objc(cs)" << Cls;
848}
849
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000850void clang::index::generateUSRForObjCCategory(StringRef Cls, StringRef Cat,
851 raw_ostream &OS) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000852 OS << "objc(cy)" << Cls << '@' << Cat;
853}
854
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000855void clang::index::generateUSRForObjCIvar(StringRef Ivar, raw_ostream &OS) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000856 OS << '@' << Ivar;
857}
858
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000859void clang::index::generateUSRForObjCMethod(StringRef Sel,
860 bool IsInstanceMethod,
861 raw_ostream &OS) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000862 OS << (IsInstanceMethod ? "(im)" : "(cm)") << Sel;
863}
864
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000865void clang::index::generateUSRForObjCProperty(StringRef Prop, raw_ostream &OS) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000866 OS << "(py)" << Prop;
867}
868
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000869void clang::index::generateUSRForObjCProtocol(StringRef Prot, raw_ostream &OS) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000870 OS << "objc(pl)" << Prot;
871}
872
Argyrios Kyrtzidis5234b492013-08-21 00:49:25 +0000873bool clang::index::generateUSRForDecl(const Decl *D,
874 SmallVectorImpl<char> &Buf) {
Argyrios Kyrtzidis4b2b4602013-08-16 18:17:55 +0000875 // Don't generate USRs for things with invalid locations.
876 if (!D || D->getLocStart().isInvalid())
877 return true;
878
879 USRGenerator UG(&D->getASTContext(), Buf);
880 UG.Visit(D);
881 return UG.ignoreResults();
882}
Dmitri Gribenko237769e2014-03-28 22:21:26 +0000883
Richard Smith66a81862015-05-04 02:25:31 +0000884bool clang::index::generateUSRForMacro(const MacroDefinitionRecord *MD,
Dmitri Gribenko237769e2014-03-28 22:21:26 +0000885 const SourceManager &SM,
886 SmallVectorImpl<char> &Buf) {
887 // Don't generate USRs for things with invalid locations.
888 if (!MD || MD->getLocation().isInvalid())
889 return true;
890
891 llvm::raw_svector_ostream Out(Buf);
892
893 // Assume that system headers are sane. Don't put source location
894 // information into the USR if the macro comes from a system header.
895 SourceLocation Loc = MD->getLocation();
896 bool ShouldGenerateLocation = !SM.isInSystemHeader(Loc);
897
898 Out << getUSRSpacePrefix();
899 if (ShouldGenerateLocation)
900 printLoc(Out, Loc, SM, /*IncludeOffset=*/true);
901 Out << "@macro@";
Alp Toker541d5072014-06-07 23:30:53 +0000902 Out << MD->getName()->getName();
Dmitri Gribenko237769e2014-03-28 22:21:26 +0000903 return false;
904}