DeclBase.cpp 59 KB

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