DeclBase.cpp 61 KB

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