DeclBase.cpp 60 KB

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