IdentifierResolver.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. //===- IdentifierResolver.cpp - Lexical Scope Name lookup -----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the IdentifierResolver class, which is used for lexical
  10. // scoped lookup, based on declaration names.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Sema/IdentifierResolver.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclBase.h"
  16. #include "clang/AST/DeclarationName.h"
  17. #include "clang/Basic/IdentifierTable.h"
  18. #include "clang/Basic/LangOptions.h"
  19. #include "clang/Lex/ExternalPreprocessorSource.h"
  20. #include "clang/Lex/Preprocessor.h"
  21. #include "clang/Sema/Scope.h"
  22. #include "llvm/Support/ErrorHandling.h"
  23. #include <cassert>
  24. #include <cstdint>
  25. using namespace clang;
  26. //===----------------------------------------------------------------------===//
  27. // IdDeclInfoMap class
  28. //===----------------------------------------------------------------------===//
  29. /// IdDeclInfoMap - Associates IdDeclInfos with declaration names.
  30. /// Allocates 'pools' (vectors of IdDeclInfos) to avoid allocating each
  31. /// individual IdDeclInfo to heap.
  32. class IdentifierResolver::IdDeclInfoMap {
  33. static const unsigned int POOL_SIZE = 512;
  34. /// We use our own linked-list implementation because it is sadly
  35. /// impossible to add something to a pre-C++0x STL container without
  36. /// a completely unnecessary copy.
  37. struct IdDeclInfoPool {
  38. IdDeclInfoPool *Next;
  39. IdDeclInfo Pool[POOL_SIZE];
  40. IdDeclInfoPool(IdDeclInfoPool *Next) : Next(Next) {}
  41. };
  42. IdDeclInfoPool *CurPool = nullptr;
  43. unsigned int CurIndex = POOL_SIZE;
  44. public:
  45. IdDeclInfoMap() = default;
  46. ~IdDeclInfoMap() {
  47. IdDeclInfoPool *Cur = CurPool;
  48. while (IdDeclInfoPool *P = Cur) {
  49. Cur = Cur->Next;
  50. delete P;
  51. }
  52. }
  53. /// Returns the IdDeclInfo associated to the DeclarationName.
  54. /// It creates a new IdDeclInfo if one was not created before for this id.
  55. IdDeclInfo &operator[](DeclarationName Name);
  56. };
  57. //===----------------------------------------------------------------------===//
  58. // IdDeclInfo Implementation
  59. //===----------------------------------------------------------------------===//
  60. /// RemoveDecl - Remove the decl from the scope chain.
  61. /// The decl must already be part of the decl chain.
  62. void IdentifierResolver::IdDeclInfo::RemoveDecl(NamedDecl *D) {
  63. for (DeclsTy::iterator I = Decls.end(); I != Decls.begin(); --I) {
  64. if (D == *(I-1)) {
  65. Decls.erase(I-1);
  66. return;
  67. }
  68. }
  69. llvm_unreachable("Didn't find this decl on its identifier's chain!");
  70. }
  71. //===----------------------------------------------------------------------===//
  72. // IdentifierResolver Implementation
  73. //===----------------------------------------------------------------------===//
  74. IdentifierResolver::IdentifierResolver(Preprocessor &PP)
  75. : LangOpt(PP.getLangOpts()), PP(PP), IdDeclInfos(new IdDeclInfoMap) {}
  76. IdentifierResolver::~IdentifierResolver() {
  77. delete IdDeclInfos;
  78. }
  79. /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
  80. /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
  81. /// true if 'D' belongs to the given declaration context.
  82. bool IdentifierResolver::isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S,
  83. bool AllowInlineNamespace) const {
  84. Ctx = Ctx->getRedeclContext();
  85. // The names for HLSL cbuffer/tbuffers only used by the CPU-side
  86. // reflection API which supports querying bindings. It will not have name
  87. // conflict with other Decls.
  88. if (LangOpt.HLSL && isa<HLSLBufferDecl>(D))
  89. return false;
  90. if (Ctx->isFunctionOrMethod() || (S && S->isFunctionPrototypeScope())) {
  91. // Ignore the scopes associated within transparent declaration contexts.
  92. while (S->getEntity() && S->getEntity()->isTransparentContext())
  93. S = S->getParent();
  94. if (S->isDeclScope(D))
  95. return true;
  96. if (LangOpt.CPlusPlus) {
  97. // C++ 3.3.2p3:
  98. // The name declared in a catch exception-declaration is local to the
  99. // handler and shall not be redeclared in the outermost block of the
  100. // handler.
  101. // C++ 3.3.2p4:
  102. // Names declared in the for-init-statement, and in the condition of if,
  103. // while, for, and switch statements are local to the if, while, for, or
  104. // switch statement (including the controlled statement), and shall not be
  105. // redeclared in a subsequent condition of that statement nor in the
  106. // outermost block (or, for the if statement, any of the outermost blocks)
  107. // of the controlled statement.
  108. //
  109. assert(S->getParent() && "No TUScope?");
  110. // If the current decl is in a lambda, we shouldn't consider this is a
  111. // redefinition as lambda has its own scope.
  112. if (S->getParent()->isControlScope() && !S->isFunctionScope()) {
  113. S = S->getParent();
  114. if (S->isDeclScope(D))
  115. return true;
  116. }
  117. if (S->isFnTryCatchScope())
  118. return S->getParent()->isDeclScope(D);
  119. }
  120. return false;
  121. }
  122. // FIXME: If D is a local extern declaration, this check doesn't make sense;
  123. // we should be checking its lexical context instead in that case, because
  124. // that is its scope.
  125. DeclContext *DCtx = D->getDeclContext()->getRedeclContext();
  126. return AllowInlineNamespace ? Ctx->InEnclosingNamespaceSetOf(DCtx)
  127. : Ctx->Equals(DCtx);
  128. }
  129. /// AddDecl - Link the decl to its shadowed decl chain.
  130. void IdentifierResolver::AddDecl(NamedDecl *D) {
  131. DeclarationName Name = D->getDeclName();
  132. if (IdentifierInfo *II = Name.getAsIdentifierInfo())
  133. updatingIdentifier(*II);
  134. void *Ptr = Name.getFETokenInfo();
  135. if (!Ptr) {
  136. Name.setFETokenInfo(D);
  137. return;
  138. }
  139. IdDeclInfo *IDI;
  140. if (isDeclPtr(Ptr)) {
  141. Name.setFETokenInfo(nullptr);
  142. IDI = &(*IdDeclInfos)[Name];
  143. NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
  144. IDI->AddDecl(PrevD);
  145. } else
  146. IDI = toIdDeclInfo(Ptr);
  147. IDI->AddDecl(D);
  148. }
  149. void IdentifierResolver::InsertDeclAfter(iterator Pos, NamedDecl *D) {
  150. DeclarationName Name = D->getDeclName();
  151. if (IdentifierInfo *II = Name.getAsIdentifierInfo())
  152. updatingIdentifier(*II);
  153. void *Ptr = Name.getFETokenInfo();
  154. if (!Ptr) {
  155. AddDecl(D);
  156. return;
  157. }
  158. if (isDeclPtr(Ptr)) {
  159. // We only have a single declaration: insert before or after it,
  160. // as appropriate.
  161. if (Pos == iterator()) {
  162. // Add the new declaration before the existing declaration.
  163. NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
  164. RemoveDecl(PrevD);
  165. AddDecl(D);
  166. AddDecl(PrevD);
  167. } else {
  168. // Add new declaration after the existing declaration.
  169. AddDecl(D);
  170. }
  171. return;
  172. }
  173. // General case: insert the declaration at the appropriate point in the
  174. // list, which already has at least two elements.
  175. IdDeclInfo *IDI = toIdDeclInfo(Ptr);
  176. if (Pos.isIterator()) {
  177. IDI->InsertDecl(Pos.getIterator() + 1, D);
  178. } else
  179. IDI->InsertDecl(IDI->decls_begin(), D);
  180. }
  181. /// RemoveDecl - Unlink the decl from its shadowed decl chain.
  182. /// The decl must already be part of the decl chain.
  183. void IdentifierResolver::RemoveDecl(NamedDecl *D) {
  184. assert(D && "null param passed");
  185. DeclarationName Name = D->getDeclName();
  186. if (IdentifierInfo *II = Name.getAsIdentifierInfo())
  187. updatingIdentifier(*II);
  188. void *Ptr = Name.getFETokenInfo();
  189. assert(Ptr && "Didn't find this decl on its identifier's chain!");
  190. if (isDeclPtr(Ptr)) {
  191. assert(D == Ptr && "Didn't find this decl on its identifier's chain!");
  192. Name.setFETokenInfo(nullptr);
  193. return;
  194. }
  195. return toIdDeclInfo(Ptr)->RemoveDecl(D);
  196. }
  197. /// begin - Returns an iterator for decls with name 'Name'.
  198. IdentifierResolver::iterator
  199. IdentifierResolver::begin(DeclarationName Name) {
  200. if (IdentifierInfo *II = Name.getAsIdentifierInfo())
  201. readingIdentifier(*II);
  202. void *Ptr = Name.getFETokenInfo();
  203. if (!Ptr) return end();
  204. if (isDeclPtr(Ptr))
  205. return iterator(static_cast<NamedDecl*>(Ptr));
  206. IdDeclInfo *IDI = toIdDeclInfo(Ptr);
  207. IdDeclInfo::DeclsTy::iterator I = IDI->decls_end();
  208. if (I != IDI->decls_begin())
  209. return iterator(I-1);
  210. // No decls found.
  211. return end();
  212. }
  213. namespace {
  214. enum DeclMatchKind {
  215. DMK_Different,
  216. DMK_Replace,
  217. DMK_Ignore
  218. };
  219. } // namespace
  220. /// Compare two declarations to see whether they are different or,
  221. /// if they are the same, whether the new declaration should replace the
  222. /// existing declaration.
  223. static DeclMatchKind compareDeclarations(NamedDecl *Existing, NamedDecl *New) {
  224. // If the declarations are identical, ignore the new one.
  225. if (Existing == New)
  226. return DMK_Ignore;
  227. // If the declarations have different kinds, they're obviously different.
  228. if (Existing->getKind() != New->getKind())
  229. return DMK_Different;
  230. // If the declarations are redeclarations of each other, keep the newest one.
  231. if (Existing->getCanonicalDecl() == New->getCanonicalDecl()) {
  232. // If we're adding an imported declaration, don't replace another imported
  233. // declaration.
  234. if (Existing->isFromASTFile() && New->isFromASTFile())
  235. return DMK_Different;
  236. // If either of these is the most recent declaration, use it.
  237. Decl *MostRecent = Existing->getMostRecentDecl();
  238. if (Existing == MostRecent)
  239. return DMK_Ignore;
  240. if (New == MostRecent)
  241. return DMK_Replace;
  242. // If the existing declaration is somewhere in the previous declaration
  243. // chain of the new declaration, then prefer the new declaration.
  244. for (auto *RD : New->redecls()) {
  245. if (RD == Existing)
  246. return DMK_Replace;
  247. if (RD->isCanonicalDecl())
  248. break;
  249. }
  250. return DMK_Ignore;
  251. }
  252. return DMK_Different;
  253. }
  254. bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){
  255. if (IdentifierInfo *II = Name.getAsIdentifierInfo())
  256. readingIdentifier(*II);
  257. void *Ptr = Name.getFETokenInfo();
  258. if (!Ptr) {
  259. Name.setFETokenInfo(D);
  260. return true;
  261. }
  262. IdDeclInfo *IDI;
  263. if (isDeclPtr(Ptr)) {
  264. NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
  265. switch (compareDeclarations(PrevD, D)) {
  266. case DMK_Different:
  267. break;
  268. case DMK_Ignore:
  269. return false;
  270. case DMK_Replace:
  271. Name.setFETokenInfo(D);
  272. return true;
  273. }
  274. Name.setFETokenInfo(nullptr);
  275. IDI = &(*IdDeclInfos)[Name];
  276. // If the existing declaration is not visible in translation unit scope,
  277. // then add the new top-level declaration first.
  278. if (!PrevD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  279. IDI->AddDecl(D);
  280. IDI->AddDecl(PrevD);
  281. } else {
  282. IDI->AddDecl(PrevD);
  283. IDI->AddDecl(D);
  284. }
  285. return true;
  286. }
  287. IDI = toIdDeclInfo(Ptr);
  288. // See whether this declaration is identical to any existing declarations.
  289. // If not, find the right place to insert it.
  290. for (IdDeclInfo::DeclsTy::iterator I = IDI->decls_begin(),
  291. IEnd = IDI->decls_end();
  292. I != IEnd; ++I) {
  293. switch (compareDeclarations(*I, D)) {
  294. case DMK_Different:
  295. break;
  296. case DMK_Ignore:
  297. return false;
  298. case DMK_Replace:
  299. *I = D;
  300. return true;
  301. }
  302. if (!(*I)->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
  303. // We've found a declaration that is not visible from the translation
  304. // unit (it's in an inner scope). Insert our declaration here.
  305. IDI->InsertDecl(I, D);
  306. return true;
  307. }
  308. }
  309. // Add the declaration to the end.
  310. IDI->AddDecl(D);
  311. return true;
  312. }
  313. void IdentifierResolver::readingIdentifier(IdentifierInfo &II) {
  314. if (II.isOutOfDate())
  315. PP.getExternalSource()->updateOutOfDateIdentifier(II);
  316. }
  317. void IdentifierResolver::updatingIdentifier(IdentifierInfo &II) {
  318. if (II.isOutOfDate())
  319. PP.getExternalSource()->updateOutOfDateIdentifier(II);
  320. if (II.isFromAST())
  321. II.setFETokenInfoChangedSinceDeserialization();
  322. }
  323. //===----------------------------------------------------------------------===//
  324. // IdDeclInfoMap Implementation
  325. //===----------------------------------------------------------------------===//
  326. /// Returns the IdDeclInfo associated to the DeclarationName.
  327. /// It creates a new IdDeclInfo if one was not created before for this id.
  328. IdentifierResolver::IdDeclInfo &
  329. IdentifierResolver::IdDeclInfoMap::operator[](DeclarationName Name) {
  330. void *Ptr = Name.getFETokenInfo();
  331. if (Ptr) return *toIdDeclInfo(Ptr);
  332. if (CurIndex == POOL_SIZE) {
  333. CurPool = new IdDeclInfoPool(CurPool);
  334. CurIndex = 0;
  335. }
  336. IdDeclInfo *IDI = &CurPool->Pool[CurIndex];
  337. Name.setFETokenInfo(reinterpret_cast<void*>(
  338. reinterpret_cast<uintptr_t>(IDI) | 0x1)
  339. );
  340. ++CurIndex;
  341. return *IDI;
  342. }
  343. void IdentifierResolver::iterator::incrementSlowCase() {
  344. NamedDecl *D = **this;
  345. void *InfoPtr = D->getDeclName().getFETokenInfo();
  346. assert(!isDeclPtr(InfoPtr) && "Decl with wrong id ?");
  347. IdDeclInfo *Info = toIdDeclInfo(InfoPtr);
  348. BaseIter I = getIterator();
  349. if (I != Info->decls_begin())
  350. *this = iterator(I-1);
  351. else // No more decls.
  352. *this = iterator();
  353. }