• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- CIndexUSR.cpp - Clang-C Source Indexing Library --------------------===//
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 //
10 // This file implements the generation and use of USRs from CXEntities.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CIndexer.h"
15 #include "CXCursor.h"
16 #include "CXString.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/DeclVisitor.h"
19 #include "clang/Frontend/ASTUnit.h"
20 #include "clang/Lex/PreprocessingRecord.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace clang;
25 using namespace clang::cxstring;
26 
27 //===----------------------------------------------------------------------===//
28 // USR generation.
29 //===----------------------------------------------------------------------===//
30 
31 namespace {
32 class USRGenerator : public DeclVisitor<USRGenerator> {
33   llvm::OwningPtr<llvm::SmallString<128> > OwnedBuf;
34   llvm::SmallVectorImpl<char> &Buf;
35   llvm::raw_svector_ostream Out;
36   bool IgnoreResults;
37   ASTUnit *AU;
38   bool generatedLoc;
39 
40   llvm::DenseMap<const Type *, unsigned> TypeSubstitutions;
41 
42 public:
USRGenerator(const CXCursor * C=0,llvm::SmallVectorImpl<char> * extBuf=0)43   USRGenerator(const CXCursor *C = 0, llvm::SmallVectorImpl<char> *extBuf = 0)
44   : OwnedBuf(extBuf ? 0 : new llvm::SmallString<128>()),
45     Buf(extBuf ? *extBuf : *OwnedBuf.get()),
46     Out(Buf),
47     IgnoreResults(false),
48     AU(C ? cxcursor::getCursorASTUnit(*C) : 0),
49     generatedLoc(false)
50   {
51     // Add the USR space prefix.
52     Out << "c:";
53   }
54 
str()55   llvm::StringRef str() {
56     return Out.str();
57   }
58 
operator ->()59   USRGenerator* operator->() { return this; }
60 
61   template <typename T>
operator <<(const T & x)62   llvm::raw_svector_ostream &operator<<(const T &x) {
63     Out << x;
64     return Out;
65   }
66 
ignoreResults() const67   bool ignoreResults() const { return IgnoreResults; }
68 
69   // Visitation methods from generating USRs from AST elements.
70   void VisitDeclContext(DeclContext *D);
71   void VisitFieldDecl(FieldDecl *D);
72   void VisitFunctionDecl(FunctionDecl *D);
73   void VisitNamedDecl(NamedDecl *D);
74   void VisitNamespaceDecl(NamespaceDecl *D);
75   void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
76   void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
77   void VisitClassTemplateDecl(ClassTemplateDecl *D);
78   void VisitObjCClassDecl(ObjCClassDecl *CD);
79   void VisitObjCContainerDecl(ObjCContainerDecl *CD);
80   void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *P);
81   void VisitObjCMethodDecl(ObjCMethodDecl *MD);
82   void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
83   void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
84   void VisitTagDecl(TagDecl *D);
85   void VisitTypedefDecl(TypedefDecl *D);
86   void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
87   void VisitVarDecl(VarDecl *D);
88   void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
89   void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
VisitLinkageSpecDecl(LinkageSpecDecl * D)90   void VisitLinkageSpecDecl(LinkageSpecDecl *D) {
91     IgnoreResults = true;
92   }
VisitUsingDirectiveDecl(UsingDirectiveDecl * D)93   void VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
94     IgnoreResults = true;
95   }
VisitUsingDecl(UsingDecl * D)96   void VisitUsingDecl(UsingDecl *D) {
97     IgnoreResults = true;
98   }
VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl * D)99   void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
100     IgnoreResults = true;
101   }
VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl * D)102   void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
103     IgnoreResults = true;
104   }
105 
106   /// Generate the string component containing the location of the
107   ///  declaration.
108   bool GenLoc(const Decl *D);
109 
110   /// String generation methods used both by the visitation methods
111   /// and from other clients that want to directly generate USRs.  These
112   /// methods do not construct complete USRs (which incorporate the parents
113   /// of an AST element), but only the fragments concerning the AST element
114   /// itself.
115 
116   /// Generate a USR for an Objective-C class.
117   void GenObjCClass(llvm::StringRef cls);
118   /// Generate a USR for an Objective-C class category.
119   void GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat);
120   /// Generate a USR fragment for an Objective-C instance variable.  The
121   /// complete USR can be created by concatenating the USR for the
122   /// encompassing class with this USR fragment.
123   void GenObjCIvar(llvm::StringRef ivar);
124   /// Generate a USR fragment for an Objective-C method.
125   void GenObjCMethod(llvm::StringRef sel, bool isInstanceMethod);
126   /// Generate a USR fragment for an Objective-C property.
127   void GenObjCProperty(llvm::StringRef prop);
128   /// Generate a USR for an Objective-C protocol.
129   void GenObjCProtocol(llvm::StringRef prot);
130 
131   void VisitType(QualType T);
132   void VisitTemplateParameterList(const TemplateParameterList *Params);
133   void VisitTemplateName(TemplateName Name);
134   void VisitTemplateArgument(const TemplateArgument &Arg);
135 
136   /// Emit a Decl's name using NamedDecl::printName() and return true if
137   ///  the decl had no name.
138   bool EmitDeclName(const NamedDecl *D);
139 };
140 
141 } // end anonymous namespace
142 
143 //===----------------------------------------------------------------------===//
144 // Generating USRs from ASTS.
145 //===----------------------------------------------------------------------===//
146 
EmitDeclName(const NamedDecl * D)147 bool USRGenerator::EmitDeclName(const NamedDecl *D) {
148   Out.flush();
149   const unsigned startSize = Buf.size();
150   D->printName(Out);
151   Out.flush();
152   const unsigned endSize = Buf.size();
153   return startSize == endSize;
154 }
155 
InAnonymousNamespace(const Decl * D)156 static bool InAnonymousNamespace(const Decl *D) {
157   if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D->getDeclContext()))
158     return ND->isAnonymousNamespace();
159   return false;
160 }
161 
ShouldGenerateLocation(const NamedDecl * D)162 static inline bool ShouldGenerateLocation(const NamedDecl *D) {
163   return D->getLinkage() != ExternalLinkage && !InAnonymousNamespace(D);
164 }
165 
VisitDeclContext(DeclContext * DC)166 void USRGenerator::VisitDeclContext(DeclContext *DC) {
167   if (NamedDecl *D = dyn_cast<NamedDecl>(DC))
168     Visit(D);
169 }
170 
VisitFieldDecl(FieldDecl * D)171 void USRGenerator::VisitFieldDecl(FieldDecl *D) {
172   VisitDeclContext(D->getDeclContext());
173   Out << (isa<ObjCIvarDecl>(D) ? "@" : "@FI@");
174   if (EmitDeclName(D)) {
175     // Bit fields can be anonymous.
176     IgnoreResults = true;
177     return;
178   }
179 }
180 
VisitFunctionDecl(FunctionDecl * D)181 void USRGenerator::VisitFunctionDecl(FunctionDecl *D) {
182   if (ShouldGenerateLocation(D) && GenLoc(D))
183     return;
184 
185   VisitDeclContext(D->getDeclContext());
186   if (FunctionTemplateDecl *FunTmpl = D->getDescribedFunctionTemplate()) {
187     Out << "@FT@";
188     VisitTemplateParameterList(FunTmpl->getTemplateParameters());
189   } else
190     Out << "@F@";
191   D->printName(Out);
192 
193   ASTContext &Ctx = AU->getASTContext();
194   if (!Ctx.getLangOptions().CPlusPlus || D->isExternC())
195     return;
196 
197   // Mangle in type information for the arguments.
198   for (FunctionDecl::param_iterator I = D->param_begin(), E = D->param_end();
199        I != E; ++I) {
200     Out << '#';
201     if (ParmVarDecl *PD = *I)
202       VisitType(PD->getType());
203   }
204   if (D->isVariadic())
205     Out << '.';
206   Out << '#';
207   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
208     if (MD->isStatic())
209       Out << 'S';
210     if (unsigned quals = MD->getTypeQualifiers())
211       Out << (char)('0' + quals);
212   }
213 }
214 
VisitNamedDecl(NamedDecl * D)215 void USRGenerator::VisitNamedDecl(NamedDecl *D) {
216   VisitDeclContext(D->getDeclContext());
217   Out << "@";
218 
219   if (EmitDeclName(D)) {
220     // The string can be empty if the declaration has no name; e.g., it is
221     // the ParmDecl with no name for declaration of a function pointer type,
222     // e.g.: void  (*f)(void *);
223     // In this case, don't generate a USR.
224     IgnoreResults = true;
225   }
226 }
227 
VisitVarDecl(VarDecl * D)228 void USRGenerator::VisitVarDecl(VarDecl *D) {
229   // VarDecls can be declared 'extern' within a function or method body,
230   // but their enclosing DeclContext is the function, not the TU.  We need
231   // to check the storage class to correctly generate the USR.
232   if (ShouldGenerateLocation(D) && GenLoc(D))
233     return;
234 
235   VisitDeclContext(D->getDeclContext());
236 
237   // Variables always have simple names.
238   llvm::StringRef s = D->getName();
239 
240   // The string can be empty if the declaration has no name; e.g., it is
241   // the ParmDecl with no name for declaration of a function pointer type, e.g.:
242   //    void  (*f)(void *);
243   // In this case, don't generate a USR.
244   if (s.empty())
245     IgnoreResults = true;
246   else
247     Out << '@' << s;
248 }
249 
VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)250 void USRGenerator::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
251   GenLoc(D);
252   return;
253 }
254 
VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl * D)255 void USRGenerator::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
256   GenLoc(D);
257   return;
258 }
259 
VisitNamespaceDecl(NamespaceDecl * D)260 void USRGenerator::VisitNamespaceDecl(NamespaceDecl *D) {
261   if (D->isAnonymousNamespace()) {
262     Out << "@aN";
263     return;
264   }
265 
266   VisitDeclContext(D->getDeclContext());
267   if (!IgnoreResults)
268     Out << "@N@" << D->getName();
269 }
270 
VisitFunctionTemplateDecl(FunctionTemplateDecl * D)271 void USRGenerator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
272   VisitFunctionDecl(D->getTemplatedDecl());
273 }
274 
VisitClassTemplateDecl(ClassTemplateDecl * D)275 void USRGenerator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
276   VisitTagDecl(D->getTemplatedDecl());
277 }
278 
VisitNamespaceAliasDecl(NamespaceAliasDecl * D)279 void USRGenerator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
280   VisitDeclContext(D->getDeclContext());
281   if (!IgnoreResults)
282     Out << "@NA@" << D->getName();
283 }
284 
VisitObjCMethodDecl(ObjCMethodDecl * D)285 void USRGenerator::VisitObjCMethodDecl(ObjCMethodDecl *D) {
286   DeclContext *container = D->getDeclContext();
287   if (ObjCProtocolDecl *pd = dyn_cast<ObjCProtocolDecl>(container)) {
288     Visit(pd);
289   }
290   else {
291     // The USR for a method declared in a class extension or category is based on
292     // the ObjCInterfaceDecl, not the ObjCCategoryDecl.
293     ObjCInterfaceDecl *ID = D->getClassInterface();
294     if (!ID) {
295       IgnoreResults = true;
296       return;
297     }
298     Visit(ID);
299   }
300   // Ideally we would use 'GenObjCMethod', but this is such a hot path
301   // for Objective-C code that we don't want to use
302   // DeclarationName::getAsString().
303   Out << (D->isInstanceMethod() ? "(im)" : "(cm)");
304   DeclarationName N(D->getSelector());
305   N.printName(Out);
306 }
307 
VisitObjCClassDecl(ObjCClassDecl * D)308 void USRGenerator::VisitObjCClassDecl(ObjCClassDecl *D) {
309   // FIXME: @class declarations can refer to multiple classes.  We need
310   //  to be able to traverse these.
311   IgnoreResults = true;
312 }
313 
VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl * D)314 void USRGenerator::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
315   // FIXME: @protocol declarations can refer to multiple protocols.  We need
316   //  to be able to traverse these.
317   IgnoreResults = true;
318 }
319 
VisitObjCContainerDecl(ObjCContainerDecl * D)320 void USRGenerator::VisitObjCContainerDecl(ObjCContainerDecl *D) {
321   switch (D->getKind()) {
322     default:
323       assert(false && "Invalid ObjC container.");
324     case Decl::ObjCInterface:
325     case Decl::ObjCImplementation:
326       GenObjCClass(D->getName());
327       break;
328     case Decl::ObjCCategory: {
329       ObjCCategoryDecl *CD = cast<ObjCCategoryDecl>(D);
330       ObjCInterfaceDecl *ID = CD->getClassInterface();
331       if (!ID) {
332         // Handle invalid code where the @interface might not
333         // have been specified.
334         // FIXME: We should be able to generate this USR even if the
335         // @interface isn't available.
336         IgnoreResults = true;
337         return;
338       }
339       // Specially handle class extensions, which are anonymous categories.
340       // We want to mangle in the location to uniquely distinguish them.
341       if (CD->IsClassExtension()) {
342         Out << "objc(ext)" << ID->getName() << '@';
343         GenLoc(CD);
344       }
345       else
346         GenObjCCategory(ID->getName(), CD->getName());
347 
348       break;
349     }
350     case Decl::ObjCCategoryImpl: {
351       ObjCCategoryImplDecl *CD = cast<ObjCCategoryImplDecl>(D);
352       ObjCInterfaceDecl *ID = CD->getClassInterface();
353       if (!ID) {
354         // Handle invalid code where the @interface might not
355         // have been specified.
356         // FIXME: We should be able to generate this USR even if the
357         // @interface isn't available.
358         IgnoreResults = true;
359         return;
360       }
361       GenObjCCategory(ID->getName(), CD->getName());
362       break;
363     }
364     case Decl::ObjCProtocol:
365       GenObjCProtocol(cast<ObjCProtocolDecl>(D)->getName());
366       break;
367   }
368 }
369 
VisitObjCPropertyDecl(ObjCPropertyDecl * D)370 void USRGenerator::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
371   Visit(cast<Decl>(D->getDeclContext()));
372   GenObjCProperty(D->getName());
373 }
374 
VisitObjCPropertyImplDecl(ObjCPropertyImplDecl * D)375 void USRGenerator::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
376   if (ObjCPropertyDecl *PD = D->getPropertyDecl()) {
377     VisitObjCPropertyDecl(PD);
378     return;
379   }
380 
381   IgnoreResults = true;
382 }
383 
VisitTagDecl(TagDecl * D)384 void USRGenerator::VisitTagDecl(TagDecl *D) {
385   // Add the location of the tag decl to handle resolution across
386   // translation units.
387   if (ShouldGenerateLocation(D) && GenLoc(D))
388     return;
389 
390   D = D->getCanonicalDecl();
391   VisitDeclContext(D->getDeclContext());
392 
393   bool AlreadyStarted = false;
394   if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(D)) {
395     if (ClassTemplateDecl *ClassTmpl = CXXRecord->getDescribedClassTemplate()) {
396       AlreadyStarted = true;
397 
398       switch (D->getTagKind()) {
399       case TTK_Struct: Out << "@ST"; break;
400       case TTK_Class:  Out << "@CT"; break;
401       case TTK_Union:  Out << "@UT"; break;
402       case TTK_Enum: llvm_unreachable("enum template"); break;
403       }
404       VisitTemplateParameterList(ClassTmpl->getTemplateParameters());
405     } else if (ClassTemplatePartialSpecializationDecl *PartialSpec
406                 = dyn_cast<ClassTemplatePartialSpecializationDecl>(CXXRecord)) {
407       AlreadyStarted = true;
408 
409       switch (D->getTagKind()) {
410       case TTK_Struct: Out << "@SP"; break;
411       case TTK_Class:  Out << "@CP"; break;
412       case TTK_Union:  Out << "@UP"; break;
413       case TTK_Enum: llvm_unreachable("enum partial specialization"); break;
414       }
415       VisitTemplateParameterList(PartialSpec->getTemplateParameters());
416     }
417   }
418 
419   if (!AlreadyStarted) {
420     switch (D->getTagKind()) {
421       case TTK_Struct: Out << "@S"; break;
422       case TTK_Class:  Out << "@C"; break;
423       case TTK_Union:  Out << "@U"; break;
424       case TTK_Enum:   Out << "@E"; break;
425     }
426   }
427 
428   Out << '@';
429   Out.flush();
430   assert(Buf.size() > 0);
431   const unsigned off = Buf.size() - 1;
432 
433   if (EmitDeclName(D)) {
434     if (const TypedefNameDecl *TD = D->getTypedefNameForAnonDecl()) {
435       Buf[off] = 'A';
436       Out << '@' << TD;
437     }
438     else
439       Buf[off] = 'a';
440   }
441 
442   // For a class template specialization, mangle the template arguments.
443   if (ClassTemplateSpecializationDecl *Spec
444                               = dyn_cast<ClassTemplateSpecializationDecl>(D)) {
445     const TemplateArgumentList &Args = Spec->getTemplateInstantiationArgs();
446     Out << '>';
447     for (unsigned I = 0, N = Args.size(); I != N; ++I) {
448       Out << '#';
449       VisitTemplateArgument(Args.get(I));
450     }
451   }
452 }
453 
VisitTypedefDecl(TypedefDecl * D)454 void USRGenerator::VisitTypedefDecl(TypedefDecl *D) {
455   if (ShouldGenerateLocation(D) && GenLoc(D))
456     return;
457   DeclContext *DC = D->getDeclContext();
458   if (NamedDecl *DCN = dyn_cast<NamedDecl>(DC))
459     Visit(DCN);
460   Out << "@T@";
461   Out << D->getName();
462 }
463 
VisitTemplateTypeParmDecl(TemplateTypeParmDecl * D)464 void USRGenerator::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
465   GenLoc(D);
466   return;
467 }
468 
GenLoc(const Decl * D)469 bool USRGenerator::GenLoc(const Decl *D) {
470   if (generatedLoc)
471     return IgnoreResults;
472   generatedLoc = true;
473 
474   // Guard against null declarations in invalid code.
475   if (!D) {
476     IgnoreResults = true;
477     return true;
478   }
479 
480   // Use the location of canonical decl.
481   D = D->getCanonicalDecl();
482 
483   const SourceManager &SM = AU->getSourceManager();
484   SourceLocation L = D->getLocStart();
485   if (L.isInvalid()) {
486     IgnoreResults = true;
487     return true;
488   }
489   L = SM.getInstantiationLoc(L);
490   const std::pair<FileID, unsigned> &Decomposed = SM.getDecomposedLoc(L);
491   const FileEntry *FE = SM.getFileEntryForID(Decomposed.first);
492   if (FE) {
493     Out << llvm::sys::path::filename(FE->getName());
494   }
495   else {
496     // This case really isn't interesting.
497     IgnoreResults = true;
498     return true;
499   }
500   // Use the offest into the FileID to represent the location.  Using
501   // a line/column can cause us to look back at the original source file,
502   // which is expensive.
503   Out << '@' << Decomposed.second;
504   return IgnoreResults;
505 }
506 
VisitType(QualType T)507 void USRGenerator::VisitType(QualType T) {
508   // This method mangles in USR information for types.  It can possibly
509   // just reuse the naming-mangling logic used by codegen, although the
510   // requirements for USRs might not be the same.
511   ASTContext &Ctx = AU->getASTContext();
512 
513   do {
514     T = Ctx.getCanonicalType(T);
515     Qualifiers Q = T.getQualifiers();
516     unsigned qVal = 0;
517     if (Q.hasConst())
518       qVal |= 0x1;
519     if (Q.hasVolatile())
520       qVal |= 0x2;
521     if (Q.hasRestrict())
522       qVal |= 0x4;
523     if(qVal)
524       Out << ((char) ('0' + qVal));
525 
526     // Mangle in ObjC GC qualifiers?
527 
528     if (const PackExpansionType *Expansion = T->getAs<PackExpansionType>()) {
529       Out << 'P';
530       T = Expansion->getPattern();
531     }
532 
533     if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
534       unsigned char c = '\0';
535       switch (BT->getKind()) {
536         case BuiltinType::Void:
537           c = 'v'; break;
538         case BuiltinType::Bool:
539           c = 'b'; break;
540         case BuiltinType::Char_U:
541         case BuiltinType::UChar:
542           c = 'c'; break;
543         case BuiltinType::Char16:
544           c = 'q'; break;
545         case BuiltinType::Char32:
546           c = 'w'; break;
547         case BuiltinType::UShort:
548           c = 's'; break;
549         case BuiltinType::UInt:
550           c = 'i'; break;
551         case BuiltinType::ULong:
552           c = 'l'; break;
553         case BuiltinType::ULongLong:
554           c = 'k'; break;
555         case BuiltinType::UInt128:
556           c = 'j'; break;
557         case BuiltinType::Char_S:
558         case BuiltinType::SChar:
559           c = 'C'; break;
560         case BuiltinType::WChar_S:
561         case BuiltinType::WChar_U:
562           c = 'W'; break;
563         case BuiltinType::Short:
564           c = 'S'; break;
565         case BuiltinType::Int:
566           c = 'I'; break;
567         case BuiltinType::Long:
568           c = 'L'; break;
569         case BuiltinType::LongLong:
570           c = 'K'; break;
571         case BuiltinType::Int128:
572           c = 'J'; break;
573         case BuiltinType::Float:
574           c = 'f'; break;
575         case BuiltinType::Double:
576           c = 'd'; break;
577         case BuiltinType::LongDouble:
578           c = 'D'; break;
579         case BuiltinType::NullPtr:
580           c = 'n'; break;
581         case BuiltinType::Overload:
582         case BuiltinType::BoundMember:
583         case BuiltinType::Dependent:
584         case BuiltinType::UnknownAny:
585           IgnoreResults = true;
586           return;
587         case BuiltinType::ObjCId:
588           c = 'o'; break;
589         case BuiltinType::ObjCClass:
590           c = 'O'; break;
591         case BuiltinType::ObjCSel:
592           c = 'e'; break;
593       }
594       Out << c;
595       return;
596     }
597 
598     // If we have already seen this (non-built-in) type, use a substitution
599     // encoding.
600     llvm::DenseMap<const Type *, unsigned>::iterator Substitution
601       = TypeSubstitutions.find(T.getTypePtr());
602     if (Substitution != TypeSubstitutions.end()) {
603       Out << 'S' << Substitution->second << '_';
604       return;
605     } else {
606       // Record this as a substitution.
607       unsigned Number = TypeSubstitutions.size();
608       TypeSubstitutions[T.getTypePtr()] = Number;
609     }
610 
611     if (const PointerType *PT = T->getAs<PointerType>()) {
612       Out << '*';
613       T = PT->getPointeeType();
614       continue;
615     }
616     if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
617       Out << '&';
618       T = RT->getPointeeType();
619       continue;
620     }
621     if (const FunctionProtoType *FT = T->getAs<FunctionProtoType>()) {
622       Out << 'F';
623       VisitType(FT->getResultType());
624       for (FunctionProtoType::arg_type_iterator
625             I = FT->arg_type_begin(), E = FT->arg_type_end(); I!=E; ++I) {
626         VisitType(*I);
627       }
628       if (FT->isVariadic())
629         Out << '.';
630       return;
631     }
632     if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) {
633       Out << 'B';
634       T = BT->getPointeeType();
635       continue;
636     }
637     if (const ComplexType *CT = T->getAs<ComplexType>()) {
638       Out << '<';
639       T = CT->getElementType();
640       continue;
641     }
642     if (const TagType *TT = T->getAs<TagType>()) {
643       Out << '$';
644       VisitTagDecl(TT->getDecl());
645       return;
646     }
647     if (const TemplateTypeParmType *TTP = T->getAs<TemplateTypeParmType>()) {
648       Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
649       return;
650     }
651     if (const TemplateSpecializationType *Spec
652                                     = T->getAs<TemplateSpecializationType>()) {
653       Out << '>';
654       VisitTemplateName(Spec->getTemplateName());
655       Out << Spec->getNumArgs();
656       for (unsigned I = 0, N = Spec->getNumArgs(); I != N; ++I)
657         VisitTemplateArgument(Spec->getArg(I));
658       return;
659     }
660 
661     // Unhandled type.
662     Out << ' ';
663     break;
664   } while (true);
665 }
666 
VisitTemplateParameterList(const TemplateParameterList * Params)667 void USRGenerator::VisitTemplateParameterList(
668                                          const TemplateParameterList *Params) {
669   if (!Params)
670     return;
671   Out << '>' << Params->size();
672   for (TemplateParameterList::const_iterator P = Params->begin(),
673                                           PEnd = Params->end();
674        P != PEnd; ++P) {
675     Out << '#';
676     if (isa<TemplateTypeParmDecl>(*P)) {
677       if (cast<TemplateTypeParmDecl>(*P)->isParameterPack())
678         Out<< 'p';
679       Out << 'T';
680       continue;
681     }
682 
683     if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
684       if (NTTP->isParameterPack())
685         Out << 'p';
686       Out << 'N';
687       VisitType(NTTP->getType());
688       continue;
689     }
690 
691     TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P);
692     if (TTP->isParameterPack())
693       Out << 'p';
694     Out << 't';
695     VisitTemplateParameterList(TTP->getTemplateParameters());
696   }
697 }
698 
VisitTemplateName(TemplateName Name)699 void USRGenerator::VisitTemplateName(TemplateName Name) {
700   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
701     if (TemplateTemplateParmDecl *TTP
702                               = dyn_cast<TemplateTemplateParmDecl>(Template)) {
703       Out << 't' << TTP->getDepth() << '.' << TTP->getIndex();
704       return;
705     }
706 
707     Visit(Template);
708     return;
709   }
710 
711   // FIXME: Visit dependent template names.
712 }
713 
VisitTemplateArgument(const TemplateArgument & Arg)714 void USRGenerator::VisitTemplateArgument(const TemplateArgument &Arg) {
715   switch (Arg.getKind()) {
716   case TemplateArgument::Null:
717     break;
718 
719   case TemplateArgument::Declaration:
720     if (Decl *D = Arg.getAsDecl())
721       Visit(D);
722     break;
723 
724   case TemplateArgument::TemplateExpansion:
725     Out << 'P'; // pack expansion of...
726     // Fall through
727   case TemplateArgument::Template:
728     VisitTemplateName(Arg.getAsTemplateOrTemplatePattern());
729     break;
730 
731   case TemplateArgument::Expression:
732     // FIXME: Visit expressions.
733     break;
734 
735   case TemplateArgument::Pack:
736     Out << 'p' << Arg.pack_size();
737     for (TemplateArgument::pack_iterator P = Arg.pack_begin(), PEnd = Arg.pack_end();
738          P != PEnd; ++P)
739       VisitTemplateArgument(*P);
740     break;
741 
742   case TemplateArgument::Type:
743     VisitType(Arg.getAsType());
744     break;
745 
746   case TemplateArgument::Integral:
747     Out << 'V';
748     VisitType(Arg.getIntegralType());
749     Out << *Arg.getAsIntegral();
750     break;
751   }
752 }
753 
754 //===----------------------------------------------------------------------===//
755 // General purpose USR generation methods.
756 //===----------------------------------------------------------------------===//
757 
GenObjCClass(llvm::StringRef cls)758 void USRGenerator::GenObjCClass(llvm::StringRef cls) {
759   Out << "objc(cs)" << cls;
760 }
761 
GenObjCCategory(llvm::StringRef cls,llvm::StringRef cat)762 void USRGenerator::GenObjCCategory(llvm::StringRef cls, llvm::StringRef cat) {
763   Out << "objc(cy)" << cls << '@' << cat;
764 }
765 
GenObjCIvar(llvm::StringRef ivar)766 void USRGenerator::GenObjCIvar(llvm::StringRef ivar) {
767   Out << '@' << ivar;
768 }
769 
GenObjCMethod(llvm::StringRef meth,bool isInstanceMethod)770 void USRGenerator::GenObjCMethod(llvm::StringRef meth, bool isInstanceMethod) {
771   Out << (isInstanceMethod ? "(im)" : "(cm)") << meth;
772 }
773 
GenObjCProperty(llvm::StringRef prop)774 void USRGenerator::GenObjCProperty(llvm::StringRef prop) {
775   Out << "(py)" << prop;
776 }
777 
GenObjCProtocol(llvm::StringRef prot)778 void USRGenerator::GenObjCProtocol(llvm::StringRef prot) {
779   Out << "objc(pl)" << prot;
780 }
781 
782 //===----------------------------------------------------------------------===//
783 // API hooks.
784 //===----------------------------------------------------------------------===//
785 
extractUSRSuffix(llvm::StringRef s)786 static inline llvm::StringRef extractUSRSuffix(llvm::StringRef s) {
787   return s.startswith("c:") ? s.substr(2) : "";
788 }
789 
getDeclCursorUSR(const CXCursor & C)790 static CXString getDeclCursorUSR(const CXCursor &C) {
791   Decl *D = cxcursor::getCursorDecl(C);
792 
793   // Don't generate USRs for things with invalid locations.
794   if (!D || D->getLocStart().isInvalid())
795     return createCXString("");
796 
797   // Check if the cursor has 'NoLinkage'.
798   if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
799     switch (ND->getLinkage()) {
800       case ExternalLinkage:
801         // Generate USRs for all entities with external linkage.
802         break;
803       case NoLinkage:
804       case UniqueExternalLinkage:
805         // We allow enums, typedefs, and structs that have no linkage to
806         // have USRs that are anchored to the file they were defined in
807         // (e.g., the header).  This is a little gross, but in principal
808         // enums/anonymous structs/etc. defined in a common header file
809         // are referred to across multiple translation units.
810         if (isa<TagDecl>(ND) || isa<TypedefDecl>(ND) ||
811             isa<EnumConstantDecl>(ND) || isa<FieldDecl>(ND) ||
812             isa<VarDecl>(ND) || isa<NamespaceDecl>(ND))
813           break;
814         // Fall-through.
815       case InternalLinkage:
816         if (isa<FunctionDecl>(ND))
817           break;
818     }
819 
820   CXTranslationUnit TU = cxcursor::getCursorTU(C);
821   if (!TU)
822     return createCXString("");
823 
824   CXStringBuf *buf = cxstring::getCXStringBuf(TU);
825   if (!buf)
826     return createCXString("");
827 
828   {
829     USRGenerator UG(&C, &buf->Data);
830     UG->Visit(D);
831 
832     if (UG->ignoreResults()) {
833       disposeCXStringBuf(buf);
834       return createCXString("");
835     }
836   }
837   // Return the C-string, but don't make a copy since it is already in
838   // the string buffer.
839   buf->Data.push_back('\0');
840   return createCXString(buf);
841 }
842 
843 extern "C" {
844 
clang_getCursorUSR(CXCursor C)845 CXString clang_getCursorUSR(CXCursor C) {
846   const CXCursorKind &K = clang_getCursorKind(C);
847 
848   if (clang_isDeclaration(K))
849       return getDeclCursorUSR(C);
850 
851   if (K == CXCursor_MacroDefinition) {
852     CXTranslationUnit TU = cxcursor::getCursorTU(C);
853     if (!TU)
854       return createCXString("");
855 
856     CXStringBuf *buf = cxstring::getCXStringBuf(TU);
857     if (!buf)
858       return createCXString("");
859 
860     {
861       USRGenerator UG(&C, &buf->Data);
862       UG << "macro@"
863         << cxcursor::getCursorMacroDefinition(C)->getName()->getNameStart();
864     }
865     buf->Data.push_back('\0');
866     return createCXString(buf);
867   }
868 
869   return createCXString("");
870 }
871 
clang_constructUSR_ObjCIvar(const char * name,CXString classUSR)872 CXString clang_constructUSR_ObjCIvar(const char *name, CXString classUSR) {
873   USRGenerator UG;
874   UG << extractUSRSuffix(clang_getCString(classUSR));
875   UG->GenObjCIvar(name);
876   return createCXString(UG.str(), true);
877 }
878 
clang_constructUSR_ObjCMethod(const char * name,unsigned isInstanceMethod,CXString classUSR)879 CXString clang_constructUSR_ObjCMethod(const char *name,
880                                        unsigned isInstanceMethod,
881                                        CXString classUSR) {
882   USRGenerator UG;
883   UG << extractUSRSuffix(clang_getCString(classUSR));
884   UG->GenObjCMethod(name, isInstanceMethod);
885   return createCXString(UG.str(), true);
886 }
887 
clang_constructUSR_ObjCClass(const char * name)888 CXString clang_constructUSR_ObjCClass(const char *name) {
889   USRGenerator UG;
890   UG->GenObjCClass(name);
891   return createCXString(UG.str(), true);
892 }
893 
clang_constructUSR_ObjCProtocol(const char * name)894 CXString clang_constructUSR_ObjCProtocol(const char *name) {
895   USRGenerator UG;
896   UG->GenObjCProtocol(name);
897   return createCXString(UG.str(), true);
898 }
899 
clang_constructUSR_ObjCCategory(const char * class_name,const char * category_name)900 CXString clang_constructUSR_ObjCCategory(const char *class_name,
901                                          const char *category_name) {
902   USRGenerator UG;
903   UG->GenObjCCategory(class_name, category_name);
904   return createCXString(UG.str(), true);
905 }
906 
clang_constructUSR_ObjCProperty(const char * property,CXString classUSR)907 CXString clang_constructUSR_ObjCProperty(const char *property,
908                                          CXString classUSR) {
909   USRGenerator UG;
910   UG << extractUSRSuffix(clang_getCString(classUSR));
911   UG->GenObjCProperty(property);
912   return createCXString(UG.str(), true);
913 }
914 
915 } // end extern "C"
916