DeclBase.cpp 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017
  1. //===- DeclBase.cpp - Declaration AST Node Implementation -----------------===//
  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 Decl and DeclContext classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/DeclBase.h"
  13. #include "clang/AST/ASTContext.h"
  14. #include "clang/AST/ASTLambda.h"
  15. #include "clang/AST/ASTMutationListener.h"
  16. #include "clang/AST/Attr.h"
  17. #include "clang/AST/AttrIterator.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclContextInternals.h"
  21. #include "clang/AST/DeclFriend.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/AST/DeclOpenMP.h"
  24. #include "clang/AST/DeclTemplate.h"
  25. #include "clang/AST/DependentDiagnostic.h"
  26. #include "clang/AST/ExternalASTSource.h"
  27. #include "clang/AST/Stmt.h"
  28. #include "clang/AST/Type.h"
  29. #include "clang/Basic/IdentifierTable.h"
  30. #include "clang/Basic/LLVM.h"
  31. #include "clang/Basic/LangOptions.h"
  32. #include "clang/Basic/ObjCRuntime.h"
  33. #include "clang/Basic/PartialDiagnostic.h"
  34. #include "clang/Basic/SourceLocation.h"
  35. #include "clang/Basic/TargetInfo.h"
  36. #include "llvm/ADT/ArrayRef.h"
  37. #include "llvm/ADT/PointerIntPair.h"
  38. #include "llvm/ADT/SmallVector.h"
  39. #include "llvm/ADT/StringRef.h"
  40. #include "llvm/Support/Casting.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/MathExtras.h"
  43. #include "llvm/Support/VersionTuple.h"
  44. #include "llvm/Support/raw_ostream.h"
  45. #include <algorithm>
  46. #include <cassert>
  47. #include <cstddef>
  48. #include <string>
  49. #include <tuple>
  50. #include <utility>
  51. using namespace clang;
  52. //===----------------------------------------------------------------------===//
  53. // Statistics
  54. //===----------------------------------------------------------------------===//
  55. #define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
  56. #define ABSTRACT_DECL(DECL)
  57. #include "clang/AST/DeclNodes.inc"
  58. void Decl::updateOutOfDate(IdentifierInfo &II) const {
  59. getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
  60. }
  61. #define DECL(DERIVED, BASE) \
  62. static_assert(alignof(Decl) >= alignof(DERIVED##Decl), \
  63. "Alignment sufficient after objects prepended to " #DERIVED);
  64. #define ABSTRACT_DECL(DECL)
  65. #include "clang/AST/DeclNodes.inc"
  66. void *Decl::operator new(std::size_t Size, const ASTContext &Context,
  67. unsigned ID, std::size_t Extra) {
  68. // Allocate an extra 8 bytes worth of storage, which ensures that the
  69. // resulting pointer will still be 8-byte aligned.
  70. static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
  71. "Decl won't be misaligned");
  72. void *Start = Context.Allocate(Size + Extra + 8);
  73. void *Result = (char*)Start + 8;
  74. unsigned *PrefixPtr = (unsigned *)Result - 2;
  75. // Zero out the first 4 bytes; this is used to store the owning module ID.
  76. PrefixPtr[0] = 0;
  77. // Store the global declaration ID in the second 4 bytes.
  78. PrefixPtr[1] = ID;
  79. return Result;
  80. }
  81. void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
  82. DeclContext *Parent, std::size_t Extra) {
  83. assert(!Parent || &Parent->getParentASTContext() == &Ctx);
  84. // With local visibility enabled, we track the owning module even for local
  85. // declarations. We create the TU decl early and may not yet know what the
  86. // LangOpts are, so conservatively allocate the storage.
  87. if (Ctx.getLangOpts().trackLocalOwningModule() || !Parent) {
  88. // Ensure required alignment of the resulting object by adding extra
  89. // padding at the start if required.
  90. size_t ExtraAlign =
  91. llvm::offsetToAlignment(sizeof(Module *), llvm::Align(alignof(Decl)));
  92. auto *Buffer = reinterpret_cast<char *>(
  93. ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
  94. Buffer += ExtraAlign;
  95. auto *ParentModule =
  96. Parent ? cast<Decl>(Parent)->getOwningModule() : nullptr;
  97. return new (Buffer) Module*(ParentModule) + 1;
  98. }
  99. return ::operator new(Size + Extra, Ctx);
  100. }
  101. Module *Decl::getOwningModuleSlow() const {
  102. assert(isFromASTFile() && "Not from AST file?");
  103. return getASTContext().getExternalSource()->getModule(getOwningModuleID());
  104. }
  105. bool Decl::hasLocalOwningModuleStorage() const {
  106. return getASTContext().getLangOpts().trackLocalOwningModule();
  107. }
  108. const char *Decl::getDeclKindName() const {
  109. switch (DeclKind) {
  110. default: llvm_unreachable("Declaration not in DeclNodes.inc!");
  111. #define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
  112. #define ABSTRACT_DECL(DECL)
  113. #include "clang/AST/DeclNodes.inc"
  114. }
  115. }
  116. void Decl::setInvalidDecl(bool Invalid) {
  117. InvalidDecl = Invalid;
  118. assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
  119. if (!Invalid) {
  120. return;
  121. }
  122. if (!isa<ParmVarDecl>(this)) {
  123. // Defensive maneuver for ill-formed code: we're likely not to make it to
  124. // a point where we set the access specifier, so default it to "public"
  125. // to avoid triggering asserts elsewhere in the front end.
  126. setAccess(AS_public);
  127. }
  128. // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
  129. // are invalid too.
  130. if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
  131. for (auto *Binding : DD->bindings()) {
  132. Binding->setInvalidDecl();
  133. }
  134. }
  135. }
  136. const char *DeclContext::getDeclKindName() const {
  137. switch (getDeclKind()) {
  138. #define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
  139. #define ABSTRACT_DECL(DECL)
  140. #include "clang/AST/DeclNodes.inc"
  141. }
  142. llvm_unreachable("Declaration context not in DeclNodes.inc!");
  143. }
  144. bool Decl::StatisticsEnabled = false;
  145. void Decl::EnableStatistics() {
  146. StatisticsEnabled = true;
  147. }
  148. void Decl::PrintStats() {
  149. llvm::errs() << "\n*** Decl Stats:\n";
  150. int totalDecls = 0;
  151. #define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
  152. #define ABSTRACT_DECL(DECL)
  153. #include "clang/AST/DeclNodes.inc"
  154. llvm::errs() << " " << totalDecls << " decls total.\n";
  155. int totalBytes = 0;
  156. #define DECL(DERIVED, BASE) \
  157. if (n##DERIVED##s > 0) { \
  158. totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl)); \
  159. llvm::errs() << " " << n##DERIVED##s << " " #DERIVED " decls, " \
  160. << sizeof(DERIVED##Decl) << " each (" \
  161. << n##DERIVED##s * sizeof(DERIVED##Decl) \
  162. << " bytes)\n"; \
  163. }
  164. #define ABSTRACT_DECL(DECL)
  165. #include "clang/AST/DeclNodes.inc"
  166. llvm::errs() << "Total bytes = " << totalBytes << "\n";
  167. }
  168. void Decl::add(Kind k) {
  169. switch (k) {
  170. #define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
  171. #define ABSTRACT_DECL(DECL)
  172. #include "clang/AST/DeclNodes.inc"
  173. }
  174. }
  175. bool Decl::isTemplateParameterPack() const {
  176. if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
  177. return TTP->isParameterPack();
  178. if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
  179. return NTTP->isParameterPack();
  180. if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
  181. return TTP->isParameterPack();
  182. return false;
  183. }
  184. bool Decl::isParameterPack() const {
  185. if (const auto *Var = dyn_cast<VarDecl>(this))
  186. return Var->isParameterPack();
  187. return isTemplateParameterPack();
  188. }
  189. FunctionDecl *Decl::getAsFunction() {
  190. if (auto *FD = dyn_cast<FunctionDecl>(this))
  191. return FD;
  192. if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
  193. return FTD->getTemplatedDecl();
  194. return nullptr;
  195. }
  196. bool Decl::isTemplateDecl() const {
  197. return isa<TemplateDecl>(this);
  198. }
  199. TemplateDecl *Decl::getDescribedTemplate() const {
  200. if (auto *FD = dyn_cast<FunctionDecl>(this))
  201. return FD->getDescribedFunctionTemplate();
  202. if (auto *RD = dyn_cast<CXXRecordDecl>(this))
  203. return RD->getDescribedClassTemplate();
  204. if (auto *VD = dyn_cast<VarDecl>(this))
  205. return VD->getDescribedVarTemplate();
  206. if (auto *AD = dyn_cast<TypeAliasDecl>(this))
  207. return AD->getDescribedAliasTemplate();
  208. return nullptr;
  209. }
  210. const TemplateParameterList *Decl::getDescribedTemplateParams() const {
  211. if (auto *TD = getDescribedTemplate())
  212. return TD->getTemplateParameters();
  213. if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(this))
  214. return CTPSD->getTemplateParameters();
  215. if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(this))
  216. return VTPSD->getTemplateParameters();
  217. return nullptr;
  218. }
  219. bool Decl::isTemplated() const {
  220. // A declaration is templated if it is a template or a template pattern, or
  221. // is within (lexcially for a friend, semantically otherwise) a dependent
  222. // context.
  223. // FIXME: Should local extern declarations be treated like friends?
  224. if (auto *AsDC = dyn_cast<DeclContext>(this))
  225. return AsDC->isDependentContext();
  226. auto *DC = getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
  227. return DC->isDependentContext() || isTemplateDecl() ||
  228. getDescribedTemplateParams();
  229. }
  230. unsigned Decl::getTemplateDepth() const {
  231. if (auto *DC = dyn_cast<DeclContext>(this))
  232. if (DC->isFileContext())
  233. return 0;
  234. if (auto *TPL = getDescribedTemplateParams())
  235. return TPL->getDepth() + 1;
  236. // If this is a dependent lambda, there might be an enclosing variable
  237. // template. In this case, the next step is not the parent DeclContext (or
  238. // even a DeclContext at all).
  239. auto *RD = dyn_cast<CXXRecordDecl>(this);
  240. if (RD && RD->isDependentLambda())
  241. if (Decl *Context = RD->getLambdaContextDecl())
  242. return Context->getTemplateDepth();
  243. const DeclContext *DC =
  244. getFriendObjectKind() ? getLexicalDeclContext() : getDeclContext();
  245. return cast<Decl>(DC)->getTemplateDepth();
  246. }
  247. const DeclContext *Decl::getParentFunctionOrMethod() const {
  248. for (const DeclContext *DC = getDeclContext();
  249. DC && !DC->isTranslationUnit() && !DC->isNamespace();
  250. DC = DC->getParent())
  251. if (DC->isFunctionOrMethod())
  252. return DC;
  253. return nullptr;
  254. }
  255. //===----------------------------------------------------------------------===//
  256. // PrettyStackTraceDecl Implementation
  257. //===----------------------------------------------------------------------===//
  258. void PrettyStackTraceDecl::print(raw_ostream &OS) const {
  259. SourceLocation TheLoc = Loc;
  260. if (TheLoc.isInvalid() && TheDecl)
  261. TheLoc = TheDecl->getLocation();
  262. if (TheLoc.isValid()) {
  263. TheLoc.print(OS, SM);
  264. OS << ": ";
  265. }
  266. OS << Message;
  267. if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
  268. OS << " '";
  269. DN->printQualifiedName(OS);
  270. OS << '\'';
  271. }
  272. OS << '\n';
  273. }
  274. //===----------------------------------------------------------------------===//
  275. // Decl Implementation
  276. //===----------------------------------------------------------------------===//
  277. // Out-of-line virtual method providing a home for Decl.
  278. Decl::~Decl() = default;
  279. void Decl::setDeclContext(DeclContext *DC) {
  280. DeclCtx = DC;
  281. }
  282. void Decl::setLexicalDeclContext(DeclContext *DC) {
  283. if (DC == getLexicalDeclContext())
  284. return;
  285. if (isInSemaDC()) {
  286. setDeclContextsImpl(getDeclContext(), DC, getASTContext());
  287. } else {
  288. getMultipleDC()->LexicalDC = DC;
  289. }
  290. // FIXME: We shouldn't be changing the lexical context of declarations
  291. // imported from AST files.
  292. if (!isFromASTFile()) {
  293. setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
  294. if (hasOwningModule())
  295. setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
  296. }
  297. assert(
  298. (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
  299. getOwningModule()) &&
  300. "hidden declaration has no owning module");
  301. }
  302. void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
  303. ASTContext &Ctx) {
  304. if (SemaDC == LexicalDC) {
  305. DeclCtx = SemaDC;
  306. } else {
  307. auto *MDC = new (Ctx) Decl::MultipleDC();
  308. MDC->SemanticDC = SemaDC;
  309. MDC->LexicalDC = LexicalDC;
  310. DeclCtx = MDC;
  311. }
  312. }
  313. bool Decl::isInLocalScopeForInstantiation() const {
  314. const DeclContext *LDC = getLexicalDeclContext();
  315. if (!LDC->isDependentContext())
  316. return false;
  317. while (true) {
  318. if (LDC->isFunctionOrMethod())
  319. return true;
  320. if (!isa<TagDecl>(LDC))
  321. return false;
  322. if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
  323. if (CRD->isLambda())
  324. return true;
  325. LDC = LDC->getLexicalParent();
  326. }
  327. return false;
  328. }
  329. bool Decl::isInAnonymousNamespace() const {
  330. for (const DeclContext *DC = getDeclContext(); DC; DC = DC->getParent()) {
  331. if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
  332. if (ND->isAnonymousNamespace())
  333. return true;
  334. }
  335. return false;
  336. }
  337. bool Decl::isInStdNamespace() const {
  338. const DeclContext *DC = getDeclContext();
  339. return DC && DC->isStdNamespace();
  340. }
  341. TranslationUnitDecl *Decl::getTranslationUnitDecl() {
  342. if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
  343. return TUD;
  344. DeclContext *DC = getDeclContext();
  345. assert(DC && "This decl is not contained in a translation unit!");
  346. while (!DC->isTranslationUnit()) {
  347. DC = DC->getParent();
  348. assert(DC && "This decl is not contained in a translation unit!");
  349. }
  350. return cast<TranslationUnitDecl>(DC);
  351. }
  352. ASTContext &Decl::getASTContext() const {
  353. return getTranslationUnitDecl()->getASTContext();
  354. }
  355. /// Helper to get the language options from the ASTContext.
  356. /// Defined out of line to avoid depending on ASTContext.h.
  357. const LangOptions &Decl::getLangOpts() const {
  358. return getASTContext().getLangOpts();
  359. }
  360. ASTMutationListener *Decl::getASTMutationListener() const {
  361. return getASTContext().getASTMutationListener();
  362. }
  363. unsigned Decl::getMaxAlignment() const {
  364. if (!hasAttrs())
  365. return 0;
  366. unsigned Align = 0;
  367. const AttrVec &V = getAttrs();
  368. ASTContext &Ctx = getASTContext();
  369. specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
  370. for (; I != E; ++I) {
  371. if (!I->isAlignmentErrorDependent())
  372. Align = std::max(Align, I->getAlignment(Ctx));
  373. }
  374. return Align;
  375. }
  376. bool Decl::isUsed(bool CheckUsedAttr) const {
  377. const Decl *CanonD = getCanonicalDecl();
  378. if (CanonD->Used)
  379. return true;
  380. // Check for used attribute.
  381. // Ask the most recent decl, since attributes accumulate in the redecl chain.
  382. if (CheckUsedAttr && getMostRecentDecl()->hasAttr<UsedAttr>())
  383. return true;
  384. // The information may have not been deserialized yet. Force deserialization
  385. // to complete the needed information.
  386. return getMostRecentDecl()->getCanonicalDecl()->Used;
  387. }
  388. void Decl::markUsed(ASTContext &C) {
  389. if (isUsed(false))
  390. return;
  391. if (C.getASTMutationListener())
  392. C.getASTMutationListener()->DeclarationMarkedUsed(this);
  393. setIsUsed();
  394. }
  395. bool Decl::isReferenced() const {
  396. if (Referenced)
  397. return true;
  398. // Check redeclarations.
  399. for (const auto *I : redecls())
  400. if (I->Referenced)
  401. return true;
  402. return false;
  403. }
  404. ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
  405. const Decl *Definition = nullptr;
  406. if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
  407. Definition = ID->getDefinition();
  408. } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
  409. Definition = PD->getDefinition();
  410. } else if (auto *TD = dyn_cast<TagDecl>(this)) {
  411. Definition = TD->getDefinition();
  412. }
  413. if (!Definition)
  414. Definition = this;
  415. if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
  416. return attr;
  417. if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
  418. return dcd->getAttr<ExternalSourceSymbolAttr>();
  419. }
  420. return nullptr;
  421. }
  422. bool Decl::hasDefiningAttr() const {
  423. return hasAttr<AliasAttr>() || hasAttr<IFuncAttr>() ||
  424. hasAttr<LoaderUninitializedAttr>();
  425. }
  426. const Attr *Decl::getDefiningAttr() const {
  427. if (auto *AA = getAttr<AliasAttr>())
  428. return AA;
  429. if (auto *IFA = getAttr<IFuncAttr>())
  430. return IFA;
  431. if (auto *NZA = getAttr<LoaderUninitializedAttr>())
  432. return NZA;
  433. return nullptr;
  434. }
  435. static StringRef getRealizedPlatform(const AvailabilityAttr *A,
  436. const ASTContext &Context) {
  437. // Check if this is an App Extension "platform", and if so chop off
  438. // the suffix for matching with the actual platform.
  439. StringRef RealizedPlatform = A->getPlatform()->getName();
  440. if (!Context.getLangOpts().AppExt)
  441. return RealizedPlatform;
  442. size_t suffix = RealizedPlatform.rfind("_app_extension");
  443. if (suffix != StringRef::npos)
  444. return RealizedPlatform.slice(0, suffix);
  445. return RealizedPlatform;
  446. }
  447. /// Determine the availability of the given declaration based on
  448. /// the target platform.
  449. ///
  450. /// When it returns an availability result other than \c AR_Available,
  451. /// if the \p Message parameter is non-NULL, it will be set to a
  452. /// string describing why the entity is unavailable.
  453. ///
  454. /// FIXME: Make these strings localizable, since they end up in
  455. /// diagnostics.
  456. static AvailabilityResult CheckAvailability(ASTContext &Context,
  457. const AvailabilityAttr *A,
  458. std::string *Message,
  459. VersionTuple EnclosingVersion) {
  460. if (EnclosingVersion.empty())
  461. EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
  462. if (EnclosingVersion.empty())
  463. return AR_Available;
  464. StringRef ActualPlatform = A->getPlatform()->getName();
  465. StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
  466. // Match the platform name.
  467. if (getRealizedPlatform(A, Context) != TargetPlatform)
  468. return AR_Available;
  469. StringRef PrettyPlatformName
  470. = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
  471. if (PrettyPlatformName.empty())
  472. PrettyPlatformName = ActualPlatform;
  473. std::string HintMessage;
  474. if (!A->getMessage().empty()) {
  475. HintMessage = " - ";
  476. HintMessage += A->getMessage();
  477. }
  478. // Make sure that this declaration has not been marked 'unavailable'.
  479. if (A->getUnavailable()) {
  480. if (Message) {
  481. Message->clear();
  482. llvm::raw_string_ostream Out(*Message);
  483. Out << "not available on " << PrettyPlatformName
  484. << HintMessage;
  485. }
  486. return AR_Unavailable;
  487. }
  488. // Make sure that this declaration has already been introduced.
  489. if (!A->getIntroduced().empty() &&
  490. EnclosingVersion < A->getIntroduced()) {
  491. if (Message) {
  492. Message->clear();
  493. llvm::raw_string_ostream Out(*Message);
  494. VersionTuple VTI(A->getIntroduced());
  495. Out << "introduced in " << PrettyPlatformName << ' '
  496. << VTI << HintMessage;
  497. }
  498. return A->getStrict() ? AR_Unavailable : AR_NotYetIntroduced;
  499. }
  500. // Make sure that this declaration hasn't been obsoleted.
  501. if (!A->getObsoleted().empty() && EnclosingVersion >= A->getObsoleted()) {
  502. if (Message) {
  503. Message->clear();
  504. llvm::raw_string_ostream Out(*Message);
  505. VersionTuple VTO(A->getObsoleted());
  506. Out << "obsoleted in " << PrettyPlatformName << ' '
  507. << VTO << HintMessage;
  508. }
  509. return AR_Unavailable;
  510. }
  511. // Make sure that this declaration hasn't been deprecated.
  512. if (!A->getDeprecated().empty() && EnclosingVersion >= A->getDeprecated()) {
  513. if (Message) {
  514. Message->clear();
  515. llvm::raw_string_ostream Out(*Message);
  516. VersionTuple VTD(A->getDeprecated());
  517. Out << "first deprecated in " << PrettyPlatformName << ' '
  518. << VTD << HintMessage;
  519. }
  520. return AR_Deprecated;
  521. }
  522. return AR_Available;
  523. }
  524. AvailabilityResult Decl::getAvailability(std::string *Message,
  525. VersionTuple EnclosingVersion,
  526. StringRef *RealizedPlatform) const {
  527. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
  528. return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
  529. RealizedPlatform);
  530. AvailabilityResult Result = AR_Available;
  531. std::string ResultMessage;
  532. for (const auto *A : attrs()) {
  533. if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
  534. if (Result >= AR_Deprecated)
  535. continue;
  536. if (Message)
  537. ResultMessage = std::string(Deprecated->getMessage());
  538. Result = AR_Deprecated;
  539. continue;
  540. }
  541. if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
  542. if (Message)
  543. *Message = std::string(Unavailable->getMessage());
  544. return AR_Unavailable;
  545. }
  546. if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
  547. AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
  548. Message, EnclosingVersion);
  549. if (AR == AR_Unavailable) {
  550. if (RealizedPlatform)
  551. *RealizedPlatform = Availability->getPlatform()->getName();
  552. return AR_Unavailable;
  553. }
  554. if (AR > Result) {
  555. Result = AR;
  556. if (Message)
  557. ResultMessage.swap(*Message);
  558. }
  559. continue;
  560. }
  561. }
  562. if (Message)
  563. Message->swap(ResultMessage);
  564. return Result;
  565. }
  566. VersionTuple Decl::getVersionIntroduced() const {
  567. const ASTContext &Context = getASTContext();
  568. StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
  569. for (const auto *A : attrs()) {
  570. if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
  571. if (getRealizedPlatform(Availability, Context) != TargetPlatform)
  572. continue;
  573. if (!Availability->getIntroduced().empty())
  574. return Availability->getIntroduced();
  575. }
  576. }
  577. return {};
  578. }
  579. bool Decl::canBeWeakImported(bool &IsDefinition) const {
  580. IsDefinition = false;
  581. // Variables, if they aren't definitions.
  582. if (const auto *Var = dyn_cast<VarDecl>(this)) {
  583. if (Var->isThisDeclarationADefinition()) {
  584. IsDefinition = true;
  585. return false;
  586. }
  587. return true;
  588. }
  589. // Functions, if they aren't definitions.
  590. if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
  591. if (FD->hasBody()) {
  592. IsDefinition = true;
  593. return false;
  594. }
  595. return true;
  596. }
  597. // Objective-C classes, if this is the non-fragile runtime.
  598. if (isa<ObjCInterfaceDecl>(this) &&
  599. getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()) {
  600. return true;
  601. }
  602. // Nothing else.
  603. return false;
  604. }
  605. bool Decl::isWeakImported() const {
  606. bool IsDefinition;
  607. if (!canBeWeakImported(IsDefinition))
  608. return false;
  609. for (const auto *A : getMostRecentDecl()->attrs()) {
  610. if (isa<WeakImportAttr>(A))
  611. return true;
  612. if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
  613. if (CheckAvailability(getASTContext(), Availability, nullptr,
  614. VersionTuple()) == AR_NotYetIntroduced)
  615. return true;
  616. }
  617. }
  618. return false;
  619. }
  620. unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
  621. switch (DeclKind) {
  622. case Function:
  623. case CXXDeductionGuide:
  624. case CXXMethod:
  625. case CXXConstructor:
  626. case ConstructorUsingShadow:
  627. case CXXDestructor:
  628. case CXXConversion:
  629. case EnumConstant:
  630. case Var:
  631. case ImplicitParam:
  632. case ParmVar:
  633. case ObjCMethod:
  634. case ObjCProperty:
  635. case MSProperty:
  636. return IDNS_Ordinary;
  637. case Label:
  638. return IDNS_Label;
  639. case IndirectField:
  640. return IDNS_Ordinary | IDNS_Member;
  641. case Binding:
  642. case NonTypeTemplateParm:
  643. case VarTemplate:
  644. case Concept:
  645. // These (C++-only) declarations are found by redeclaration lookup for
  646. // tag types, so we include them in the tag namespace.
  647. return IDNS_Ordinary | IDNS_Tag;
  648. case ObjCCompatibleAlias:
  649. case ObjCInterface:
  650. return IDNS_Ordinary | IDNS_Type;
  651. case Typedef:
  652. case TypeAlias:
  653. case TemplateTypeParm:
  654. case ObjCTypeParam:
  655. return IDNS_Ordinary | IDNS_Type;
  656. case UnresolvedUsingTypename:
  657. return IDNS_Ordinary | IDNS_Type | IDNS_Using;
  658. case UsingShadow:
  659. return 0; // we'll actually overwrite this later
  660. case UnresolvedUsingValue:
  661. return IDNS_Ordinary | IDNS_Using;
  662. case Using:
  663. case UsingPack:
  664. case UsingEnum:
  665. return IDNS_Using;
  666. case ObjCProtocol:
  667. return IDNS_ObjCProtocol;
  668. case Field:
  669. case ObjCAtDefsField:
  670. case ObjCIvar:
  671. return IDNS_Member;
  672. case Record:
  673. case CXXRecord:
  674. case Enum:
  675. return IDNS_Tag | IDNS_Type;
  676. case Namespace:
  677. case NamespaceAlias:
  678. return IDNS_Namespace;
  679. case FunctionTemplate:
  680. return IDNS_Ordinary;
  681. case ClassTemplate:
  682. case TemplateTemplateParm:
  683. case TypeAliasTemplate:
  684. return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
  685. case UnresolvedUsingIfExists:
  686. return IDNS_Type | IDNS_Ordinary;
  687. case OMPDeclareReduction:
  688. return IDNS_OMPReduction;
  689. case OMPDeclareMapper:
  690. return IDNS_OMPMapper;
  691. // Never have names.
  692. case Friend:
  693. case FriendTemplate:
  694. case AccessSpec:
  695. case LinkageSpec:
  696. case Export:
  697. case FileScopeAsm:
  698. case StaticAssert:
  699. case ObjCPropertyImpl:
  700. case PragmaComment:
  701. case PragmaDetectMismatch:
  702. case Block:
  703. case Captured:
  704. case TranslationUnit:
  705. case ExternCContext:
  706. case Decomposition:
  707. case MSGuid:
  708. case TemplateParamObject:
  709. case UsingDirective:
  710. case BuiltinTemplate:
  711. case ClassTemplateSpecialization:
  712. case ClassTemplatePartialSpecialization:
  713. case ClassScopeFunctionSpecialization:
  714. case VarTemplateSpecialization:
  715. case VarTemplatePartialSpecialization:
  716. case ObjCImplementation:
  717. case ObjCCategory:
  718. case ObjCCategoryImpl:
  719. case Import:
  720. case OMPThreadPrivate:
  721. case OMPAllocate:
  722. case OMPRequires:
  723. case OMPCapturedExpr:
  724. case Empty:
  725. case LifetimeExtendedTemporary:
  726. case RequiresExprBody:
  727. // Never looked up by name.
  728. return 0;
  729. }
  730. llvm_unreachable("Invalid DeclKind!");
  731. }
  732. void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
  733. assert(!HasAttrs && "Decl already contains attrs.");
  734. AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
  735. assert(AttrBlank.empty() && "HasAttrs was wrong?");
  736. AttrBlank = attrs;
  737. HasAttrs = true;
  738. }
  739. void Decl::dropAttrs() {
  740. if (!HasAttrs) return;
  741. HasAttrs = false;
  742. getASTContext().eraseDeclAttrs(this);
  743. }
  744. void Decl::addAttr(Attr *A) {
  745. if (!hasAttrs()) {
  746. setAttrs(AttrVec(1, A));
  747. return;
  748. }
  749. AttrVec &Attrs = getAttrs();
  750. if (!A->isInherited()) {
  751. Attrs.push_back(A);
  752. return;
  753. }
  754. // Attribute inheritance is processed after attribute parsing. To keep the
  755. // order as in the source code, add inherited attributes before non-inherited
  756. // ones.
  757. auto I = Attrs.begin(), E = Attrs.end();
  758. for (; I != E; ++I) {
  759. if (!(*I)->isInherited())
  760. break;
  761. }
  762. Attrs.insert(I, A);
  763. }
  764. const AttrVec &Decl::getAttrs() const {
  765. assert(HasAttrs && "No attrs to get!");
  766. return getASTContext().getDeclAttrs(this);
  767. }
  768. Decl *Decl::castFromDeclContext (const DeclContext *D) {
  769. Decl::Kind DK = D->getDeclKind();
  770. switch(DK) {
  771. #define DECL(NAME, BASE)
  772. #define DECL_CONTEXT(NAME) \
  773. case Decl::NAME: \
  774. return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
  775. #define DECL_CONTEXT_BASE(NAME)
  776. #include "clang/AST/DeclNodes.inc"
  777. default:
  778. #define DECL(NAME, BASE)
  779. #define DECL_CONTEXT_BASE(NAME) \
  780. if (DK >= first##NAME && DK <= last##NAME) \
  781. return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
  782. #include "clang/AST/DeclNodes.inc"
  783. llvm_unreachable("a decl that inherits DeclContext isn't handled");
  784. }
  785. }
  786. DeclContext *Decl::castToDeclContext(const Decl *D) {
  787. Decl::Kind DK = D->getKind();
  788. switch(DK) {
  789. #define DECL(NAME, BASE)
  790. #define DECL_CONTEXT(NAME) \
  791. case Decl::NAME: \
  792. return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
  793. #define DECL_CONTEXT_BASE(NAME)
  794. #include "clang/AST/DeclNodes.inc"
  795. default:
  796. #define DECL(NAME, BASE)
  797. #define DECL_CONTEXT_BASE(NAME) \
  798. if (DK >= first##NAME && DK <= last##NAME) \
  799. return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
  800. #include "clang/AST/DeclNodes.inc"
  801. llvm_unreachable("a decl that inherits DeclContext isn't handled");
  802. }
  803. }
  804. SourceLocation Decl::getBodyRBrace() const {
  805. // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
  806. // FunctionDecl stores EndRangeLoc for this purpose.
  807. if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
  808. const FunctionDecl *Definition;
  809. if (FD->hasBody(Definition))
  810. return Definition->getSourceRange().getEnd();
  811. return {};
  812. }
  813. if (Stmt *Body = getBody())
  814. return Body->getSourceRange().getEnd();
  815. return {};
  816. }
  817. bool Decl::AccessDeclContextCheck() const {
  818. #ifndef NDEBUG
  819. // Suppress this check if any of the following hold:
  820. // 1. this is the translation unit (and thus has no parent)
  821. // 2. this is a template parameter (and thus doesn't belong to its context)
  822. // 3. this is a non-type template parameter
  823. // 4. the context is not a record
  824. // 5. it's invalid
  825. // 6. it's a C++0x static_assert.
  826. // 7. it's a block literal declaration
  827. // 8. it's a temporary with lifetime extended due to being default value.
  828. if (isa<TranslationUnitDecl>(this) || isa<TemplateTypeParmDecl>(this) ||
  829. isa<NonTypeTemplateParmDecl>(this) || !getDeclContext() ||
  830. !isa<CXXRecordDecl>(getDeclContext()) || isInvalidDecl() ||
  831. isa<StaticAssertDecl>(this) || isa<BlockDecl>(this) ||
  832. // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
  833. // as DeclContext (?).
  834. isa<ParmVarDecl>(this) ||
  835. // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
  836. // AS_none as access specifier.
  837. isa<CXXRecordDecl>(this) ||
  838. isa<ClassScopeFunctionSpecializationDecl>(this) ||
  839. isa<LifetimeExtendedTemporaryDecl>(this))
  840. return true;
  841. assert(Access != AS_none &&
  842. "Access specifier is AS_none inside a record decl");
  843. #endif
  844. return true;
  845. }
  846. bool Decl::isInExportDeclContext() const {
  847. const DeclContext *DC = getLexicalDeclContext();
  848. while (DC && !isa<ExportDecl>(DC))
  849. DC = DC->getLexicalParent();
  850. return DC && isa<ExportDecl>(DC);
  851. }
  852. static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
  853. static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
  854. int64_t Decl::getID() const {
  855. return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
  856. }
  857. const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
  858. QualType Ty;
  859. if (const auto *D = dyn_cast<ValueDecl>(this))
  860. Ty = D->getType();
  861. else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
  862. Ty = D->getUnderlyingType();
  863. else
  864. return nullptr;
  865. if (Ty->isFunctionPointerType())
  866. Ty = Ty->castAs<PointerType>()->getPointeeType();
  867. else if (Ty->isFunctionReferenceType())
  868. Ty = Ty->castAs<ReferenceType>()->getPointeeType();
  869. else if (BlocksToo && Ty->isBlockPointerType())
  870. Ty = Ty->castAs<BlockPointerType>()->getPointeeType();
  871. return Ty->getAs<FunctionType>();
  872. }
  873. /// Starting at a given context (a Decl or DeclContext), look for a
  874. /// code context that is not a closure (a lambda, block, etc.).
  875. template <class T> static Decl *getNonClosureContext(T *D) {
  876. if (getKind(D) == Decl::CXXMethod) {
  877. auto *MD = cast<CXXMethodDecl>(D);
  878. if (MD->getOverloadedOperator() == OO_Call &&
  879. MD->getParent()->isLambda())
  880. return getNonClosureContext(MD->getParent()->getParent());
  881. return MD;
  882. }
  883. if (auto *FD = dyn_cast<FunctionDecl>(D))
  884. return FD;
  885. if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
  886. return MD;
  887. if (auto *BD = dyn_cast<BlockDecl>(D))
  888. return getNonClosureContext(BD->getParent());
  889. if (auto *CD = dyn_cast<CapturedDecl>(D))
  890. return getNonClosureContext(CD->getParent());
  891. return nullptr;
  892. }
  893. Decl *Decl::getNonClosureContext() {
  894. return ::getNonClosureContext(this);
  895. }
  896. Decl *DeclContext::getNonClosureAncestor() {
  897. return ::getNonClosureContext(this);
  898. }
  899. //===----------------------------------------------------------------------===//
  900. // DeclContext Implementation
  901. //===----------------------------------------------------------------------===//
  902. DeclContext::DeclContext(Decl::Kind K) {
  903. DeclContextBits.DeclKind = K;
  904. setHasExternalLexicalStorage(false);
  905. setHasExternalVisibleStorage(false);
  906. setNeedToReconcileExternalVisibleStorage(false);
  907. setHasLazyLocalLexicalLookups(false);
  908. setHasLazyExternalLexicalLookups(false);
  909. setUseQualifiedLookup(false);
  910. }
  911. bool DeclContext::classof(const Decl *D) {
  912. switch (D->getKind()) {
  913. #define DECL(NAME, BASE)
  914. #define DECL_CONTEXT(NAME) case Decl::NAME:
  915. #define DECL_CONTEXT_BASE(NAME)
  916. #include "clang/AST/DeclNodes.inc"
  917. return true;
  918. default:
  919. #define DECL(NAME, BASE)
  920. #define DECL_CONTEXT_BASE(NAME) \
  921. if (D->getKind() >= Decl::first##NAME && \
  922. D->getKind() <= Decl::last##NAME) \
  923. return true;
  924. #include "clang/AST/DeclNodes.inc"
  925. return false;
  926. }
  927. }
  928. DeclContext::~DeclContext() = default;
  929. /// Find the parent context of this context that will be
  930. /// used for unqualified name lookup.
  931. ///
  932. /// Generally, the parent lookup context is the semantic context. However, for
  933. /// a friend function the parent lookup context is the lexical context, which
  934. /// is the class in which the friend is declared.
  935. DeclContext *DeclContext::getLookupParent() {
  936. // FIXME: Find a better way to identify friends.
  937. if (isa<FunctionDecl>(this))
  938. if (getParent()->getRedeclContext()->isFileContext() &&
  939. getLexicalParent()->getRedeclContext()->isRecord())
  940. return getLexicalParent();
  941. // A lookup within the call operator of a lambda never looks in the lambda
  942. // class; instead, skip to the context in which that closure type is
  943. // declared.
  944. if (isLambdaCallOperator(this))
  945. return getParent()->getParent();
  946. return getParent();
  947. }
  948. const BlockDecl *DeclContext::getInnermostBlockDecl() const {
  949. const DeclContext *Ctx = this;
  950. do {
  951. if (Ctx->isClosure())
  952. return cast<BlockDecl>(Ctx);
  953. Ctx = Ctx->getParent();
  954. } while (Ctx);
  955. return nullptr;
  956. }
  957. bool DeclContext::isInlineNamespace() const {
  958. return isNamespace() &&
  959. cast<NamespaceDecl>(this)->isInline();
  960. }
  961. bool DeclContext::isStdNamespace() const {
  962. if (!isNamespace())
  963. return false;
  964. const auto *ND = cast<NamespaceDecl>(this);
  965. if (ND->isInline()) {
  966. return ND->getParent()->isStdNamespace();
  967. }
  968. if (!getParent()->getRedeclContext()->isTranslationUnit())
  969. return false;
  970. const IdentifierInfo *II = ND->getIdentifier();
  971. return II && II->isStr("std");
  972. }
  973. bool DeclContext::isDependentContext() const {
  974. if (isFileContext())
  975. return false;
  976. if (isa<ClassTemplatePartialSpecializationDecl>(this))
  977. return true;
  978. if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
  979. if (Record->getDescribedClassTemplate())
  980. return true;
  981. if (Record->isDependentLambda())
  982. return true;
  983. }
  984. if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
  985. if (Function->getDescribedFunctionTemplate())
  986. return true;
  987. // Friend function declarations are dependent if their *lexical*
  988. // context is dependent.
  989. if (cast<Decl>(this)->getFriendObjectKind())
  990. return getLexicalParent()->isDependentContext();
  991. }
  992. // FIXME: A variable template is a dependent context, but is not a
  993. // DeclContext. A context within it (such as a lambda-expression)
  994. // should be considered dependent.
  995. return getParent() && getParent()->isDependentContext();
  996. }
  997. bool DeclContext::isTransparentContext() const {
  998. if (getDeclKind() == Decl::Enum)
  999. return !cast<EnumDecl>(this)->isScoped();
  1000. return getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export;
  1001. }
  1002. static bool isLinkageSpecContext(const DeclContext *DC,
  1003. LinkageSpecDecl::LanguageIDs ID) {
  1004. while (DC->getDeclKind() != Decl::TranslationUnit) {
  1005. if (DC->getDeclKind() == Decl::LinkageSpec)
  1006. return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
  1007. DC = DC->getLexicalParent();
  1008. }
  1009. return false;
  1010. }
  1011. bool DeclContext::isExternCContext() const {
  1012. return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
  1013. }
  1014. const LinkageSpecDecl *DeclContext::getExternCContext() const {
  1015. const DeclContext *DC = this;
  1016. while (DC->getDeclKind() != Decl::TranslationUnit) {
  1017. if (DC->getDeclKind() == Decl::LinkageSpec &&
  1018. cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c)
  1019. return cast<LinkageSpecDecl>(DC);
  1020. DC = DC->getLexicalParent();
  1021. }
  1022. return nullptr;
  1023. }
  1024. bool DeclContext::isExternCXXContext() const {
  1025. return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
  1026. }
  1027. bool DeclContext::Encloses(const DeclContext *DC) const {
  1028. if (getPrimaryContext() != this)
  1029. return getPrimaryContext()->Encloses(DC);
  1030. for (; DC; DC = DC->getParent())
  1031. if (!isa<LinkageSpecDecl>(DC) && !isa<ExportDecl>(DC) &&
  1032. DC->getPrimaryContext() == this)
  1033. return true;
  1034. return false;
  1035. }
  1036. DeclContext *DeclContext::getNonTransparentContext() {
  1037. DeclContext *DC = this;
  1038. while (DC->isTransparentContext()) {
  1039. DC = DC->getParent();
  1040. assert(DC && "All transparent contexts should have a parent!");
  1041. }
  1042. return DC;
  1043. }
  1044. DeclContext *DeclContext::getPrimaryContext() {
  1045. switch (getDeclKind()) {
  1046. case Decl::ExternCContext:
  1047. case Decl::LinkageSpec:
  1048. case Decl::Export:
  1049. case Decl::Block:
  1050. case Decl::Captured:
  1051. case Decl::OMPDeclareReduction:
  1052. case Decl::OMPDeclareMapper:
  1053. case Decl::RequiresExprBody:
  1054. // There is only one DeclContext for these entities.
  1055. return this;
  1056. case Decl::TranslationUnit:
  1057. return static_cast<TranslationUnitDecl *>(this)->getFirstDecl();
  1058. case Decl::Namespace:
  1059. // The original namespace is our primary context.
  1060. return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
  1061. case Decl::ObjCMethod:
  1062. return this;
  1063. case Decl::ObjCInterface:
  1064. if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
  1065. if (auto *Def = OID->getDefinition())
  1066. return Def;
  1067. return this;
  1068. case Decl::ObjCProtocol:
  1069. if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
  1070. if (auto *Def = OPD->getDefinition())
  1071. return Def;
  1072. return this;
  1073. case Decl::ObjCCategory:
  1074. return this;
  1075. case Decl::ObjCImplementation:
  1076. case Decl::ObjCCategoryImpl:
  1077. return this;
  1078. default:
  1079. if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
  1080. // If this is a tag type that has a definition or is currently
  1081. // being defined, that definition is our primary context.
  1082. auto *Tag = cast<TagDecl>(this);
  1083. if (TagDecl *Def = Tag->getDefinition())
  1084. return Def;
  1085. if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
  1086. // Note, TagType::getDecl returns the (partial) definition one exists.
  1087. TagDecl *PossiblePartialDef = TagTy->getDecl();
  1088. if (PossiblePartialDef->isBeingDefined())
  1089. return PossiblePartialDef;
  1090. } else {
  1091. assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
  1092. }
  1093. return Tag;
  1094. }
  1095. assert(getDeclKind() >= Decl::firstFunction &&
  1096. getDeclKind() <= Decl::lastFunction &&
  1097. "Unknown DeclContext kind");
  1098. return this;
  1099. }
  1100. }
  1101. template <typename T>
  1102. void collectAllContextsImpl(T *Self, SmallVectorImpl<DeclContext *> &Contexts) {
  1103. for (T *D = Self->getMostRecentDecl(); D; D = D->getPreviousDecl())
  1104. Contexts.push_back(D);
  1105. std::reverse(Contexts.begin(), Contexts.end());
  1106. }
  1107. void DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts) {
  1108. Contexts.clear();
  1109. Decl::Kind Kind = getDeclKind();
  1110. if (Kind == Decl::TranslationUnit)
  1111. collectAllContextsImpl(static_cast<TranslationUnitDecl *>(this), Contexts);
  1112. else if (Kind == Decl::Namespace)
  1113. collectAllContextsImpl(static_cast<NamespaceDecl *>(this), Contexts);
  1114. else
  1115. Contexts.push_back(this);
  1116. }
  1117. std::pair<Decl *, Decl *>
  1118. DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
  1119. bool FieldsAlreadyLoaded) {
  1120. // Build up a chain of declarations via the Decl::NextInContextAndBits field.
  1121. Decl *FirstNewDecl = nullptr;
  1122. Decl *PrevDecl = nullptr;
  1123. for (auto *D : Decls) {
  1124. if (FieldsAlreadyLoaded && isa<FieldDecl>(D))
  1125. continue;
  1126. if (PrevDecl)
  1127. PrevDecl->NextInContextAndBits.setPointer(D);
  1128. else
  1129. FirstNewDecl = D;
  1130. PrevDecl = D;
  1131. }
  1132. return std::make_pair(FirstNewDecl, PrevDecl);
  1133. }
  1134. /// We have just acquired external visible storage, and we already have
  1135. /// built a lookup map. For every name in the map, pull in the new names from
  1136. /// the external storage.
  1137. void DeclContext::reconcileExternalVisibleStorage() const {
  1138. assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
  1139. setNeedToReconcileExternalVisibleStorage(false);
  1140. for (auto &Lookup : *LookupPtr)
  1141. Lookup.second.setHasExternalDecls();
  1142. }
  1143. /// Load the declarations within this lexical storage from an
  1144. /// external source.
  1145. /// \return \c true if any declarations were added.
  1146. bool
  1147. DeclContext::LoadLexicalDeclsFromExternalStorage() const {
  1148. ExternalASTSource *Source = getParentASTContext().getExternalSource();
  1149. assert(hasExternalLexicalStorage() && Source && "No external storage?");
  1150. // Notify that we have a DeclContext that is initializing.
  1151. ExternalASTSource::Deserializing ADeclContext(Source);
  1152. // Load the external declarations, if any.
  1153. SmallVector<Decl*, 64> Decls;
  1154. setHasExternalLexicalStorage(false);
  1155. Source->FindExternalLexicalDecls(this, Decls);
  1156. if (Decls.empty())
  1157. return false;
  1158. // We may have already loaded just the fields of this record, in which case
  1159. // we need to ignore them.
  1160. bool FieldsAlreadyLoaded = false;
  1161. if (const auto *RD = dyn_cast<RecordDecl>(this))
  1162. FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
  1163. // Splice the newly-read declarations into the beginning of the list
  1164. // of declarations.
  1165. Decl *ExternalFirst, *ExternalLast;
  1166. std::tie(ExternalFirst, ExternalLast) =
  1167. BuildDeclChain(Decls, FieldsAlreadyLoaded);
  1168. ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
  1169. FirstDecl = ExternalFirst;
  1170. if (!LastDecl)
  1171. LastDecl = ExternalLast;
  1172. return true;
  1173. }
  1174. DeclContext::lookup_result
  1175. ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
  1176. DeclarationName Name) {
  1177. ASTContext &Context = DC->getParentASTContext();
  1178. StoredDeclsMap *Map;
  1179. if (!(Map = DC->LookupPtr))
  1180. Map = DC->CreateStoredDeclsMap(Context);
  1181. if (DC->hasNeedToReconcileExternalVisibleStorage())
  1182. DC->reconcileExternalVisibleStorage();
  1183. (*Map)[Name].removeExternalDecls();
  1184. return DeclContext::lookup_result();
  1185. }
  1186. DeclContext::lookup_result
  1187. ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
  1188. DeclarationName Name,
  1189. ArrayRef<NamedDecl*> Decls) {
  1190. ASTContext &Context = DC->getParentASTContext();
  1191. StoredDeclsMap *Map;
  1192. if (!(Map = DC->LookupPtr))
  1193. Map = DC->CreateStoredDeclsMap(Context);
  1194. if (DC->hasNeedToReconcileExternalVisibleStorage())
  1195. DC->reconcileExternalVisibleStorage();
  1196. StoredDeclsList &List = (*Map)[Name];
  1197. List.replaceExternalDecls(Decls);
  1198. return List.getLookupResult();
  1199. }
  1200. DeclContext::decl_iterator DeclContext::decls_begin() const {
  1201. if (hasExternalLexicalStorage())
  1202. LoadLexicalDeclsFromExternalStorage();
  1203. return decl_iterator(FirstDecl);
  1204. }
  1205. bool DeclContext::decls_empty() const {
  1206. if (hasExternalLexicalStorage())
  1207. LoadLexicalDeclsFromExternalStorage();
  1208. return !FirstDecl;
  1209. }
  1210. bool DeclContext::containsDecl(Decl *D) const {
  1211. return (D->getLexicalDeclContext() == this &&
  1212. (D->NextInContextAndBits.getPointer() || D == LastDecl));
  1213. }
  1214. bool DeclContext::containsDeclAndLoad(Decl *D) const {
  1215. if (hasExternalLexicalStorage())
  1216. LoadLexicalDeclsFromExternalStorage();
  1217. return containsDecl(D);
  1218. }
  1219. /// shouldBeHidden - Determine whether a declaration which was declared
  1220. /// within its semantic context should be invisible to qualified name lookup.
  1221. static bool shouldBeHidden(NamedDecl *D) {
  1222. // Skip unnamed declarations.
  1223. if (!D->getDeclName())
  1224. return true;
  1225. // Skip entities that can't be found by name lookup into a particular
  1226. // context.
  1227. if ((D->getIdentifierNamespace() == 0 && !isa<UsingDirectiveDecl>(D)) ||
  1228. D->isTemplateParameter())
  1229. return true;
  1230. // Skip friends and local extern declarations unless they're the first
  1231. // declaration of the entity.
  1232. if ((D->isLocalExternDecl() || D->getFriendObjectKind()) &&
  1233. D != D->getCanonicalDecl())
  1234. return true;
  1235. // Skip template specializations.
  1236. // FIXME: This feels like a hack. Should DeclarationName support
  1237. // template-ids, or is there a better way to keep specializations
  1238. // from being visible?
  1239. if (isa<ClassTemplateSpecializationDecl>(D))
  1240. return true;
  1241. if (auto *FD = dyn_cast<FunctionDecl>(D))
  1242. if (FD->isFunctionTemplateSpecialization())
  1243. return true;
  1244. // Hide destructors that are invalid. There should always be one destructor,
  1245. // but if it is an invalid decl, another one is created. We need to hide the
  1246. // invalid one from places that expect exactly one destructor, like the
  1247. // serialization code.
  1248. if (isa<CXXDestructorDecl>(D) && D->isInvalidDecl())
  1249. return true;
  1250. return false;
  1251. }
  1252. void DeclContext::removeDecl(Decl *D) {
  1253. assert(D->getLexicalDeclContext() == this &&
  1254. "decl being removed from non-lexical context");
  1255. assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
  1256. "decl is not in decls list");
  1257. // Remove D from the decl chain. This is O(n) but hopefully rare.
  1258. if (D == FirstDecl) {
  1259. if (D == LastDecl)
  1260. FirstDecl = LastDecl = nullptr;
  1261. else
  1262. FirstDecl = D->NextInContextAndBits.getPointer();
  1263. } else {
  1264. for (Decl *I = FirstDecl; true; I = I->NextInContextAndBits.getPointer()) {
  1265. assert(I && "decl not found in linked list");
  1266. if (I->NextInContextAndBits.getPointer() == D) {
  1267. I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
  1268. if (D == LastDecl) LastDecl = I;
  1269. break;
  1270. }
  1271. }
  1272. }
  1273. // Mark that D is no longer in the decl chain.
  1274. D->NextInContextAndBits.setPointer(nullptr);
  1275. // Remove D from the lookup table if necessary.
  1276. if (isa<NamedDecl>(D)) {
  1277. auto *ND = cast<NamedDecl>(D);
  1278. // Do not try to remove the declaration if that is invisible to qualified
  1279. // lookup. E.g. template specializations are skipped.
  1280. if (shouldBeHidden(ND))
  1281. return;
  1282. // Remove only decls that have a name
  1283. if (!ND->getDeclName())
  1284. return;
  1285. auto *DC = D->getDeclContext();
  1286. do {
  1287. StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
  1288. if (Map) {
  1289. StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
  1290. assert(Pos != Map->end() && "no lookup entry for decl");
  1291. Pos->second.remove(ND);
  1292. }
  1293. } while (DC->isTransparentContext() && (DC = DC->getParent()));
  1294. }
  1295. }
  1296. void DeclContext::addHiddenDecl(Decl *D) {
  1297. assert(D->getLexicalDeclContext() == this &&
  1298. "Decl inserted into wrong lexical context");
  1299. assert(!D->getNextDeclInContext() && D != LastDecl &&
  1300. "Decl already inserted into a DeclContext");
  1301. if (FirstDecl) {
  1302. LastDecl->NextInContextAndBits.setPointer(D);
  1303. LastDecl = D;
  1304. } else {
  1305. FirstDecl = LastDecl = D;
  1306. }
  1307. // Notify a C++ record declaration that we've added a member, so it can
  1308. // update its class-specific state.
  1309. if (auto *Record = dyn_cast<CXXRecordDecl>(this))
  1310. Record->addedMember(D);
  1311. // If this is a newly-created (not de-serialized) import declaration, wire
  1312. // it in to the list of local import declarations.
  1313. if (!D->isFromASTFile()) {
  1314. if (auto *Import = dyn_cast<ImportDecl>(D))
  1315. D->getASTContext().addedLocalImportDecl(Import);
  1316. }
  1317. }
  1318. void DeclContext::addDecl(Decl *D) {
  1319. addHiddenDecl(D);
  1320. if (auto *ND = dyn_cast<NamedDecl>(D))
  1321. ND->getDeclContext()->getPrimaryContext()->
  1322. makeDeclVisibleInContextWithFlags(ND, false, true);
  1323. }
  1324. void DeclContext::addDeclInternal(Decl *D) {
  1325. addHiddenDecl(D);
  1326. if (auto *ND = dyn_cast<NamedDecl>(D))
  1327. ND->getDeclContext()->getPrimaryContext()->
  1328. makeDeclVisibleInContextWithFlags(ND, true, true);
  1329. }
  1330. /// buildLookup - Build the lookup data structure with all of the
  1331. /// declarations in this DeclContext (and any other contexts linked
  1332. /// to it or transparent contexts nested within it) and return it.
  1333. ///
  1334. /// Note that the produced map may miss out declarations from an
  1335. /// external source. If it does, those entries will be marked with
  1336. /// the 'hasExternalDecls' flag.
  1337. StoredDeclsMap *DeclContext::buildLookup() {
  1338. assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
  1339. if (!hasLazyLocalLexicalLookups() &&
  1340. !hasLazyExternalLexicalLookups())
  1341. return LookupPtr;
  1342. SmallVector<DeclContext *, 2> Contexts;
  1343. collectAllContexts(Contexts);
  1344. if (hasLazyExternalLexicalLookups()) {
  1345. setHasLazyExternalLexicalLookups(false);
  1346. for (auto *DC : Contexts) {
  1347. if (DC->hasExternalLexicalStorage()) {
  1348. bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
  1349. setHasLazyLocalLexicalLookups(
  1350. hasLazyLocalLexicalLookups() | LoadedDecls );
  1351. }
  1352. }
  1353. if (!hasLazyLocalLexicalLookups())
  1354. return LookupPtr;
  1355. }
  1356. for (auto *DC : Contexts)
  1357. buildLookupImpl(DC, hasExternalVisibleStorage());
  1358. // We no longer have any lazy decls.
  1359. setHasLazyLocalLexicalLookups(false);
  1360. return LookupPtr;
  1361. }
  1362. /// buildLookupImpl - Build part of the lookup data structure for the
  1363. /// declarations contained within DCtx, which will either be this
  1364. /// DeclContext, a DeclContext linked to it, or a transparent context
  1365. /// nested within it.
  1366. void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
  1367. for (auto *D : DCtx->noload_decls()) {
  1368. // Insert this declaration into the lookup structure, but only if
  1369. // it's semantically within its decl context. Any other decls which
  1370. // should be found in this context are added eagerly.
  1371. //
  1372. // If it's from an AST file, don't add it now. It'll get handled by
  1373. // FindExternalVisibleDeclsByName if needed. Exception: if we're not
  1374. // in C++, we do not track external visible decls for the TU, so in
  1375. // that case we need to collect them all here.
  1376. if (auto *ND = dyn_cast<NamedDecl>(D))
  1377. if (ND->getDeclContext() == DCtx && !shouldBeHidden(ND) &&
  1378. (!ND->isFromASTFile() ||
  1379. (isTranslationUnit() &&
  1380. !getParentASTContext().getLangOpts().CPlusPlus)))
  1381. makeDeclVisibleInContextImpl(ND, Internal);
  1382. // If this declaration is itself a transparent declaration context
  1383. // or inline namespace, add the members of this declaration of that
  1384. // context (recursively).
  1385. if (auto *InnerCtx = dyn_cast<DeclContext>(D))
  1386. if (InnerCtx->isTransparentContext() || InnerCtx->isInlineNamespace())
  1387. buildLookupImpl(InnerCtx, Internal);
  1388. }
  1389. }
  1390. DeclContext::lookup_result
  1391. DeclContext::lookup(DeclarationName Name) const {
  1392. // For transparent DeclContext, we should lookup in their enclosing context.
  1393. if (getDeclKind() == Decl::LinkageSpec || getDeclKind() == Decl::Export)
  1394. return getParent()->lookup(Name);
  1395. const DeclContext *PrimaryContext = getPrimaryContext();
  1396. if (PrimaryContext != this)
  1397. return PrimaryContext->lookup(Name);
  1398. // If we have an external source, ensure that any later redeclarations of this
  1399. // context have been loaded, since they may add names to the result of this
  1400. // lookup (or add external visible storage).
  1401. ExternalASTSource *Source = getParentASTContext().getExternalSource();
  1402. if (Source)
  1403. (void)cast<Decl>(this)->getMostRecentDecl();
  1404. if (hasExternalVisibleStorage()) {
  1405. assert(Source && "external visible storage but no external source?");
  1406. if (hasNeedToReconcileExternalVisibleStorage())
  1407. reconcileExternalVisibleStorage();
  1408. StoredDeclsMap *Map = LookupPtr;
  1409. if (hasLazyLocalLexicalLookups() ||
  1410. hasLazyExternalLexicalLookups())
  1411. // FIXME: Make buildLookup const?
  1412. Map = const_cast<DeclContext*>(this)->buildLookup();
  1413. if (!Map)
  1414. Map = CreateStoredDeclsMap(getParentASTContext());
  1415. // If we have a lookup result with no external decls, we are done.
  1416. std::pair<StoredDeclsMap::iterator, bool> R =
  1417. Map->insert(std::make_pair(Name, StoredDeclsList()));
  1418. if (!R.second && !R.first->second.hasExternalDecls())
  1419. return R.first->second.getLookupResult();
  1420. if (Source->FindExternalVisibleDeclsByName(this, Name) || !R.second) {
  1421. if (StoredDeclsMap *Map = LookupPtr) {
  1422. StoredDeclsMap::iterator I = Map->find(Name);
  1423. if (I != Map->end())
  1424. return I->second.getLookupResult();
  1425. }
  1426. }
  1427. return {};
  1428. }
  1429. StoredDeclsMap *Map = LookupPtr;
  1430. if (hasLazyLocalLexicalLookups() ||
  1431. hasLazyExternalLexicalLookups())
  1432. Map = const_cast<DeclContext*>(this)->buildLookup();
  1433. if (!Map)
  1434. return {};
  1435. StoredDeclsMap::iterator I = Map->find(Name);
  1436. if (I == Map->end())
  1437. return {};
  1438. return I->second.getLookupResult();
  1439. }
  1440. DeclContext::lookup_result
  1441. DeclContext::noload_lookup(DeclarationName Name) {
  1442. assert(getDeclKind() != Decl::LinkageSpec &&
  1443. getDeclKind() != Decl::Export &&
  1444. "should not perform lookups into transparent contexts");
  1445. DeclContext *PrimaryContext = getPrimaryContext();
  1446. if (PrimaryContext != this)
  1447. return PrimaryContext->noload_lookup(Name);
  1448. loadLazyLocalLexicalLookups();
  1449. StoredDeclsMap *Map = LookupPtr;
  1450. if (!Map)
  1451. return {};
  1452. StoredDeclsMap::iterator I = Map->find(Name);
  1453. return I != Map->end() ? I->second.getLookupResult()
  1454. : lookup_result();
  1455. }
  1456. // If we have any lazy lexical declarations not in our lookup map, add them
  1457. // now. Don't import any external declarations, not even if we know we have
  1458. // some missing from the external visible lookups.
  1459. void DeclContext::loadLazyLocalLexicalLookups() {
  1460. if (hasLazyLocalLexicalLookups()) {
  1461. SmallVector<DeclContext *, 2> Contexts;
  1462. collectAllContexts(Contexts);
  1463. for (auto *Context : Contexts)
  1464. buildLookupImpl(Context, hasExternalVisibleStorage());
  1465. setHasLazyLocalLexicalLookups(false);
  1466. }
  1467. }
  1468. void DeclContext::localUncachedLookup(DeclarationName Name,
  1469. SmallVectorImpl<NamedDecl *> &Results) {
  1470. Results.clear();
  1471. // If there's no external storage, just perform a normal lookup and copy
  1472. // the results.
  1473. if (!hasExternalVisibleStorage() && !hasExternalLexicalStorage() && Name) {
  1474. lookup_result LookupResults = lookup(Name);
  1475. Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
  1476. return;
  1477. }
  1478. // If we have a lookup table, check there first. Maybe we'll get lucky.
  1479. // FIXME: Should we be checking these flags on the primary context?
  1480. if (Name && !hasLazyLocalLexicalLookups() &&
  1481. !hasLazyExternalLexicalLookups()) {
  1482. if (StoredDeclsMap *Map = LookupPtr) {
  1483. StoredDeclsMap::iterator Pos = Map->find(Name);
  1484. if (Pos != Map->end()) {
  1485. Results.insert(Results.end(),
  1486. Pos->second.getLookupResult().begin(),
  1487. Pos->second.getLookupResult().end());
  1488. return;
  1489. }
  1490. }
  1491. }
  1492. // Slow case: grovel through the declarations in our chain looking for
  1493. // matches.
  1494. // FIXME: If we have lazy external declarations, this will not find them!
  1495. // FIXME: Should we CollectAllContexts and walk them all here?
  1496. for (Decl *D = FirstDecl; D; D = D->getNextDeclInContext()) {
  1497. if (auto *ND = dyn_cast<NamedDecl>(D))
  1498. if (ND->getDeclName() == Name)
  1499. Results.push_back(ND);
  1500. }
  1501. }
  1502. DeclContext *DeclContext::getRedeclContext() {
  1503. DeclContext *Ctx = this;
  1504. // In C, a record type is the redeclaration context for its fields only. If
  1505. // we arrive at a record context after skipping anything else, we should skip
  1506. // the record as well. Currently, this means skipping enumerations because
  1507. // they're the only transparent context that can exist within a struct or
  1508. // union.
  1509. bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
  1510. !getParentASTContext().getLangOpts().CPlusPlus;
  1511. // Skip through contexts to get to the redeclaration context. Transparent
  1512. // contexts are always skipped.
  1513. while ((SkipRecords && Ctx->isRecord()) || Ctx->isTransparentContext())
  1514. Ctx = Ctx->getParent();
  1515. return Ctx;
  1516. }
  1517. DeclContext *DeclContext::getEnclosingNamespaceContext() {
  1518. DeclContext *Ctx = this;
  1519. // Skip through non-namespace, non-translation-unit contexts.
  1520. while (!Ctx->isFileContext())
  1521. Ctx = Ctx->getParent();
  1522. return Ctx->getPrimaryContext();
  1523. }
  1524. RecordDecl *DeclContext::getOuterLexicalRecordContext() {
  1525. // Loop until we find a non-record context.
  1526. RecordDecl *OutermostRD = nullptr;
  1527. DeclContext *DC = this;
  1528. while (DC->isRecord()) {
  1529. OutermostRD = cast<RecordDecl>(DC);
  1530. DC = DC->getLexicalParent();
  1531. }
  1532. return OutermostRD;
  1533. }
  1534. bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
  1535. // For non-file contexts, this is equivalent to Equals.
  1536. if (!isFileContext())
  1537. return O->Equals(this);
  1538. do {
  1539. if (O->Equals(this))
  1540. return true;
  1541. const auto *NS = dyn_cast<NamespaceDecl>(O);
  1542. if (!NS || !NS->isInline())
  1543. break;
  1544. O = NS->getParent();
  1545. } while (O);
  1546. return false;
  1547. }
  1548. void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
  1549. DeclContext *PrimaryDC = this->getPrimaryContext();
  1550. DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
  1551. // If the decl is being added outside of its semantic decl context, we
  1552. // need to ensure that we eagerly build the lookup information for it.
  1553. PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
  1554. }
  1555. void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
  1556. bool Recoverable) {
  1557. assert(this == getPrimaryContext() && "expected a primary DC");
  1558. if (!isLookupContext()) {
  1559. if (isTransparentContext())
  1560. getParent()->getPrimaryContext()
  1561. ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
  1562. return;
  1563. }
  1564. // Skip declarations which should be invisible to name lookup.
  1565. if (shouldBeHidden(D))
  1566. return;
  1567. // If we already have a lookup data structure, perform the insertion into
  1568. // it. If we might have externally-stored decls with this name, look them
  1569. // up and perform the insertion. If this decl was declared outside its
  1570. // semantic context, buildLookup won't add it, so add it now.
  1571. //
  1572. // FIXME: As a performance hack, don't add such decls into the translation
  1573. // unit unless we're in C++, since qualified lookup into the TU is never
  1574. // performed.
  1575. if (LookupPtr || hasExternalVisibleStorage() ||
  1576. ((!Recoverable || D->getDeclContext() != D->getLexicalDeclContext()) &&
  1577. (getParentASTContext().getLangOpts().CPlusPlus ||
  1578. !isTranslationUnit()))) {
  1579. // If we have lazily omitted any decls, they might have the same name as
  1580. // the decl which we are adding, so build a full lookup table before adding
  1581. // this decl.
  1582. buildLookup();
  1583. makeDeclVisibleInContextImpl(D, Internal);
  1584. } else {
  1585. setHasLazyLocalLexicalLookups(true);
  1586. }
  1587. // If we are a transparent context or inline namespace, insert into our
  1588. // parent context, too. This operation is recursive.
  1589. if (isTransparentContext() || isInlineNamespace())
  1590. getParent()->getPrimaryContext()->
  1591. makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
  1592. auto *DCAsDecl = cast<Decl>(this);
  1593. // Notify that a decl was made visible unless we are a Tag being defined.
  1594. if (!(isa<TagDecl>(DCAsDecl) && cast<TagDecl>(DCAsDecl)->isBeingDefined()))
  1595. if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
  1596. L->AddedVisibleDecl(this, D);
  1597. }
  1598. void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
  1599. // Find or create the stored declaration map.
  1600. StoredDeclsMap *Map = LookupPtr;
  1601. if (!Map) {
  1602. ASTContext *C = &getParentASTContext();
  1603. Map = CreateStoredDeclsMap(*C);
  1604. }
  1605. // If there is an external AST source, load any declarations it knows about
  1606. // with this declaration's name.
  1607. // If the lookup table contains an entry about this name it means that we
  1608. // have already checked the external source.
  1609. if (!Internal)
  1610. if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
  1611. if (hasExternalVisibleStorage() &&
  1612. Map->find(D->getDeclName()) == Map->end())
  1613. Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
  1614. // Insert this declaration into the map.
  1615. StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
  1616. if (Internal) {
  1617. // If this is being added as part of loading an external declaration,
  1618. // this may not be the only external declaration with this name.
  1619. // In this case, we never try to replace an existing declaration; we'll
  1620. // handle that when we finalize the list of declarations for this name.
  1621. DeclNameEntries.setHasExternalDecls();
  1622. DeclNameEntries.prependDeclNoReplace(D);
  1623. return;
  1624. }
  1625. DeclNameEntries.addOrReplaceDecl(D);
  1626. }
  1627. UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
  1628. return cast<UsingDirectiveDecl>(*I);
  1629. }
  1630. /// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
  1631. /// this context.
  1632. DeclContext::udir_range DeclContext::using_directives() const {
  1633. // FIXME: Use something more efficient than normal lookup for using
  1634. // directives. In C++, using directives are looked up more than anything else.
  1635. lookup_result Result = lookup(UsingDirectiveDecl::getName());
  1636. return udir_range(Result.begin(), Result.end());
  1637. }
  1638. //===----------------------------------------------------------------------===//
  1639. // Creation and Destruction of StoredDeclsMaps. //
  1640. //===----------------------------------------------------------------------===//
  1641. StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
  1642. assert(!LookupPtr && "context already has a decls map");
  1643. assert(getPrimaryContext() == this &&
  1644. "creating decls map on non-primary context");
  1645. StoredDeclsMap *M;
  1646. bool Dependent = isDependentContext();
  1647. if (Dependent)
  1648. M = new DependentStoredDeclsMap();
  1649. else
  1650. M = new StoredDeclsMap();
  1651. M->Previous = C.LastSDM;
  1652. C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
  1653. LookupPtr = M;
  1654. return M;
  1655. }
  1656. void ASTContext::ReleaseDeclContextMaps() {
  1657. // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
  1658. // pointer because the subclass doesn't add anything that needs to
  1659. // be deleted.
  1660. StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
  1661. LastSDM.setPointer(nullptr);
  1662. }
  1663. void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
  1664. while (Map) {
  1665. // Advance the iteration before we invalidate memory.
  1666. llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
  1667. if (Dependent)
  1668. delete static_cast<DependentStoredDeclsMap*>(Map);
  1669. else
  1670. delete Map;
  1671. Map = Next.getPointer();
  1672. Dependent = Next.getInt();
  1673. }
  1674. }
  1675. DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
  1676. DeclContext *Parent,
  1677. const PartialDiagnostic &PDiag) {
  1678. assert(Parent->isDependentContext()
  1679. && "cannot iterate dependent diagnostics of non-dependent context");
  1680. Parent = Parent->getPrimaryContext();
  1681. if (!Parent->LookupPtr)
  1682. Parent->CreateStoredDeclsMap(C);
  1683. auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
  1684. // Allocate the copy of the PartialDiagnostic via the ASTContext's
  1685. // BumpPtrAllocator, rather than the ASTContext itself.
  1686. DiagnosticStorage *DiagStorage = nullptr;
  1687. if (PDiag.hasStorage())
  1688. DiagStorage = new (C) DiagnosticStorage;
  1689. auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
  1690. // TODO: Maybe we shouldn't reverse the order during insertion.
  1691. DD->NextDiagnostic = Map->FirstDiagnostic;
  1692. Map->FirstDiagnostic = DD;
  1693. return DD;
  1694. }