USRGeneration.cpp 39 KB

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