USRGeneration.cpp 36 KB

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