DeclBase.cpp 56 KB

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