DeclBase.cpp 51 KB

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