DeclBase.cpp 56 KB

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