DeclBase.cpp 58 KB

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