DeclBase.cpp 64 KB

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