DeclBase.cpp 52 KB

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