DeclBase.cpp 61 KB

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