DeclBase.cpp 61 KB

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