DeclBase.h 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the Decl and DeclContext interfaces.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_CLANG_AST_DECLBASE_H
  18. #define LLVM_CLANG_AST_DECLBASE_H
  19. #include "clang/AST/ASTDumperUtils.h"
  20. #include "clang/AST/AttrIterator.h"
  21. #include "clang/AST/DeclarationName.h"
  22. #include "clang/Basic/IdentifierTable.h"
  23. #include "clang/Basic/LLVM.h"
  24. #include "clang/Basic/SourceLocation.h"
  25. #include "clang/Basic/Specifiers.h"
  26. #include "llvm/ADT/ArrayRef.h"
  27. #include "llvm/ADT/PointerIntPair.h"
  28. #include "llvm/ADT/PointerUnion.h"
  29. #include "llvm/ADT/iterator.h"
  30. #include "llvm/ADT/iterator_range.h"
  31. #include "llvm/Support/Casting.h"
  32. #include "llvm/Support/Compiler.h"
  33. #include "llvm/Support/PrettyStackTrace.h"
  34. #include "llvm/Support/VersionTuple.h"
  35. #include <algorithm>
  36. #include <cassert>
  37. #include <cstddef>
  38. #include <iterator>
  39. #include <string>
  40. #include <type_traits>
  41. #include <utility>
  42. namespace clang {
  43. class ASTContext;
  44. class ASTMutationListener;
  45. class Attr;
  46. class BlockDecl;
  47. class DeclContext;
  48. class ExternalSourceSymbolAttr;
  49. class FunctionDecl;
  50. class FunctionType;
  51. class IdentifierInfo;
  52. enum Linkage : unsigned char;
  53. class LinkageSpecDecl;
  54. class Module;
  55. class NamedDecl;
  56. class ObjCContainerDecl;
  57. class ObjCMethodDecl;
  58. struct PrintingPolicy;
  59. class RecordDecl;
  60. class SourceManager;
  61. class Stmt;
  62. class StoredDeclsMap;
  63. class TemplateDecl;
  64. class TemplateParameterList;
  65. class TranslationUnitDecl;
  66. class UsingDirectiveDecl;
  67. /// Captures the result of checking the availability of a
  68. /// declaration.
  69. enum AvailabilityResult {
  70. AR_Available = 0,
  71. AR_NotYetIntroduced,
  72. AR_Deprecated,
  73. AR_Unavailable
  74. };
  75. /// Decl - This represents one declaration (or definition), e.g. a variable,
  76. /// typedef, function, struct, etc.
  77. ///
  78. /// Note: There are objects tacked on before the *beginning* of Decl
  79. /// (and its subclasses) in its Decl::operator new(). Proper alignment
  80. /// of all subclasses (not requiring more than the alignment of Decl) is
  81. /// asserted in DeclBase.cpp.
  82. class alignas(8) Decl {
  83. public:
  84. /// Lists the kind of concrete classes of Decl.
  85. enum Kind {
  86. #define DECL(DERIVED, BASE) DERIVED,
  87. #define ABSTRACT_DECL(DECL)
  88. #define DECL_RANGE(BASE, START, END) \
  89. first##BASE = START, last##BASE = END,
  90. #define LAST_DECL_RANGE(BASE, START, END) \
  91. first##BASE = START, last##BASE = END
  92. #include "clang/AST/DeclNodes.inc"
  93. };
  94. /// A placeholder type used to construct an empty shell of a
  95. /// decl-derived type that will be filled in later (e.g., by some
  96. /// deserialization method).
  97. struct EmptyShell {};
  98. /// IdentifierNamespace - The different namespaces in which
  99. /// declarations may appear. According to C99 6.2.3, there are
  100. /// four namespaces, labels, tags, members and ordinary
  101. /// identifiers. C++ describes lookup completely differently:
  102. /// certain lookups merely "ignore" certain kinds of declarations,
  103. /// usually based on whether the declaration is of a type, etc.
  104. ///
  105. /// These are meant as bitmasks, so that searches in
  106. /// C++ can look into the "tag" namespace during ordinary lookup.
  107. ///
  108. /// Decl currently provides 15 bits of IDNS bits.
  109. enum IdentifierNamespace {
  110. /// Labels, declared with 'x:' and referenced with 'goto x'.
  111. IDNS_Label = 0x0001,
  112. /// Tags, declared with 'struct foo;' and referenced with
  113. /// 'struct foo'. All tags are also types. This is what
  114. /// elaborated-type-specifiers look for in C.
  115. /// This also contains names that conflict with tags in the
  116. /// same scope but that are otherwise ordinary names (non-type
  117. /// template parameters and indirect field declarations).
  118. IDNS_Tag = 0x0002,
  119. /// Types, declared with 'struct foo', typedefs, etc.
  120. /// This is what elaborated-type-specifiers look for in C++,
  121. /// but note that it's ill-formed to find a non-tag.
  122. IDNS_Type = 0x0004,
  123. /// Members, declared with object declarations within tag
  124. /// definitions. In C, these can only be found by "qualified"
  125. /// lookup in member expressions. In C++, they're found by
  126. /// normal lookup.
  127. IDNS_Member = 0x0008,
  128. /// Namespaces, declared with 'namespace foo {}'.
  129. /// Lookup for nested-name-specifiers find these.
  130. IDNS_Namespace = 0x0010,
  131. /// Ordinary names. In C, everything that's not a label, tag,
  132. /// member, or function-local extern ends up here.
  133. IDNS_Ordinary = 0x0020,
  134. /// Objective C \@protocol.
  135. IDNS_ObjCProtocol = 0x0040,
  136. /// This declaration is a friend function. A friend function
  137. /// declaration is always in this namespace but may also be in
  138. /// IDNS_Ordinary if it was previously declared.
  139. IDNS_OrdinaryFriend = 0x0080,
  140. /// This declaration is a friend class. A friend class
  141. /// declaration is always in this namespace but may also be in
  142. /// IDNS_Tag|IDNS_Type if it was previously declared.
  143. IDNS_TagFriend = 0x0100,
  144. /// This declaration is a using declaration. A using declaration
  145. /// *introduces* a number of other declarations into the current
  146. /// scope, and those declarations use the IDNS of their targets,
  147. /// but the actual using declarations go in this namespace.
  148. IDNS_Using = 0x0200,
  149. /// This declaration is a C++ operator declared in a non-class
  150. /// context. All such operators are also in IDNS_Ordinary.
  151. /// C++ lexical operator lookup looks for these.
  152. IDNS_NonMemberOperator = 0x0400,
  153. /// This declaration is a function-local extern declaration of a
  154. /// variable or function. This may also be IDNS_Ordinary if it
  155. /// has been declared outside any function. These act mostly like
  156. /// invisible friend declarations, but are also visible to unqualified
  157. /// lookup within the scope of the declaring function.
  158. IDNS_LocalExtern = 0x0800,
  159. /// This declaration is an OpenMP user defined reduction construction.
  160. IDNS_OMPReduction = 0x1000,
  161. /// This declaration is an OpenMP user defined mapper.
  162. IDNS_OMPMapper = 0x2000,
  163. };
  164. /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
  165. /// parameter types in method declarations. Other than remembering
  166. /// them and mangling them into the method's signature string, these
  167. /// are ignored by the compiler; they are consumed by certain
  168. /// remote-messaging frameworks.
  169. ///
  170. /// in, inout, and out are mutually exclusive and apply only to
  171. /// method parameters. bycopy and byref are mutually exclusive and
  172. /// apply only to method parameters (?). oneway applies only to
  173. /// results. All of these expect their corresponding parameter to
  174. /// have a particular type. None of this is currently enforced by
  175. /// clang.
  176. ///
  177. /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
  178. enum ObjCDeclQualifier {
  179. OBJC_TQ_None = 0x0,
  180. OBJC_TQ_In = 0x1,
  181. OBJC_TQ_Inout = 0x2,
  182. OBJC_TQ_Out = 0x4,
  183. OBJC_TQ_Bycopy = 0x8,
  184. OBJC_TQ_Byref = 0x10,
  185. OBJC_TQ_Oneway = 0x20,
  186. /// The nullability qualifier is set when the nullability of the
  187. /// result or parameter was expressed via a context-sensitive
  188. /// keyword.
  189. OBJC_TQ_CSNullability = 0x40
  190. };
  191. /// The kind of ownership a declaration has, for visibility purposes.
  192. /// This enumeration is designed such that higher values represent higher
  193. /// levels of name hiding.
  194. enum class ModuleOwnershipKind : unsigned {
  195. /// This declaration is not owned by a module.
  196. Unowned,
  197. /// This declaration has an owning module, but is globally visible
  198. /// (typically because its owning module is visible and we know that
  199. /// modules cannot later become hidden in this compilation).
  200. /// After serialization and deserialization, this will be converted
  201. /// to VisibleWhenImported.
  202. Visible,
  203. /// This declaration has an owning module, and is visible when that
  204. /// module is imported.
  205. VisibleWhenImported,
  206. /// This declaration has an owning module, but is only visible to
  207. /// lookups that occur within that module.
  208. ModulePrivate
  209. };
  210. protected:
  211. /// The next declaration within the same lexical
  212. /// DeclContext. These pointers form the linked list that is
  213. /// traversed via DeclContext's decls_begin()/decls_end().
  214. ///
  215. /// The extra two bits are used for the ModuleOwnershipKind.
  216. llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
  217. private:
  218. friend class DeclContext;
  219. struct MultipleDC {
  220. DeclContext *SemanticDC;
  221. DeclContext *LexicalDC;
  222. };
  223. /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
  224. /// For declarations that don't contain C++ scope specifiers, it contains
  225. /// the DeclContext where the Decl was declared.
  226. /// For declarations with C++ scope specifiers, it contains a MultipleDC*
  227. /// with the context where it semantically belongs (SemanticDC) and the
  228. /// context where it was lexically declared (LexicalDC).
  229. /// e.g.:
  230. ///
  231. /// namespace A {
  232. /// void f(); // SemanticDC == LexicalDC == 'namespace A'
  233. /// }
  234. /// void A::f(); // SemanticDC == namespace 'A'
  235. /// // LexicalDC == global namespace
  236. llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
  237. bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
  238. bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
  239. MultipleDC *getMultipleDC() const {
  240. return DeclCtx.get<MultipleDC*>();
  241. }
  242. DeclContext *getSemanticDC() const {
  243. return DeclCtx.get<DeclContext*>();
  244. }
  245. /// Loc - The location of this decl.
  246. SourceLocation Loc;
  247. /// DeclKind - This indicates which class this is.
  248. unsigned DeclKind : 7;
  249. /// InvalidDecl - This indicates a semantic error occurred.
  250. unsigned InvalidDecl : 1;
  251. /// HasAttrs - This indicates whether the decl has attributes or not.
  252. unsigned HasAttrs : 1;
  253. /// Implicit - Whether this declaration was implicitly generated by
  254. /// the implementation rather than explicitly written by the user.
  255. unsigned Implicit : 1;
  256. /// Whether this declaration was "used", meaning that a definition is
  257. /// required.
  258. unsigned Used : 1;
  259. /// Whether this declaration was "referenced".
  260. /// The difference with 'Used' is whether the reference appears in a
  261. /// evaluated context or not, e.g. functions used in uninstantiated templates
  262. /// are regarded as "referenced" but not "used".
  263. unsigned Referenced : 1;
  264. /// Whether this declaration is a top-level declaration (function,
  265. /// global variable, etc.) that is lexically inside an objc container
  266. /// definition.
  267. unsigned TopLevelDeclInObjCContainer : 1;
  268. /// Whether statistic collection is enabled.
  269. static bool StatisticsEnabled;
  270. protected:
  271. friend class ASTDeclReader;
  272. friend class ASTDeclWriter;
  273. friend class ASTNodeImporter;
  274. friend class ASTReader;
  275. friend class CXXClassMemberWrapper;
  276. friend class LinkageComputer;
  277. template<typename decl_type> friend class Redeclarable;
  278. /// Access - Used by C++ decls for the access specifier.
  279. // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
  280. unsigned Access : 2;
  281. /// Whether this declaration was loaded from an AST file.
  282. unsigned FromASTFile : 1;
  283. /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
  284. unsigned IdentifierNamespace : 14;
  285. /// If 0, we have not computed the linkage of this declaration.
  286. /// Otherwise, it is the linkage + 1.
  287. mutable unsigned CacheValidAndLinkage : 3;
  288. /// Allocate memory for a deserialized declaration.
  289. ///
  290. /// This routine must be used to allocate memory for any declaration that is
  291. /// deserialized from a module file.
  292. ///
  293. /// \param Size The size of the allocated object.
  294. /// \param Ctx The context in which we will allocate memory.
  295. /// \param ID The global ID of the deserialized declaration.
  296. /// \param Extra The amount of extra space to allocate after the object.
  297. void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
  298. std::size_t Extra = 0);
  299. /// Allocate memory for a non-deserialized declaration.
  300. void *operator new(std::size_t Size, const ASTContext &Ctx,
  301. DeclContext *Parent, std::size_t Extra = 0);
  302. private:
  303. bool AccessDeclContextCheck() const;
  304. /// Get the module ownership kind to use for a local lexical child of \p DC,
  305. /// which may be either a local or (rarely) an imported declaration.
  306. static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
  307. if (DC) {
  308. auto *D = cast<Decl>(DC);
  309. auto MOK = D->getModuleOwnershipKind();
  310. if (MOK != ModuleOwnershipKind::Unowned &&
  311. (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
  312. return MOK;
  313. // If D is not local and we have no local module storage, then we don't
  314. // need to track module ownership at all.
  315. }
  316. return ModuleOwnershipKind::Unowned;
  317. }
  318. public:
  319. Decl() = delete;
  320. Decl(const Decl&) = delete;
  321. Decl(Decl &&) = delete;
  322. Decl &operator=(const Decl&) = delete;
  323. Decl &operator=(Decl&&) = delete;
  324. protected:
  325. Decl(Kind DK, DeclContext *DC, SourceLocation L)
  326. : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
  327. DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
  328. Implicit(false), Used(false), Referenced(false),
  329. TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
  330. IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
  331. CacheValidAndLinkage(0) {
  332. if (StatisticsEnabled) add(DK);
  333. }
  334. Decl(Kind DK, EmptyShell Empty)
  335. : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
  336. Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
  337. Access(AS_none), FromASTFile(0),
  338. IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
  339. CacheValidAndLinkage(0) {
  340. if (StatisticsEnabled) add(DK);
  341. }
  342. virtual ~Decl();
  343. /// Update a potentially out-of-date declaration.
  344. void updateOutOfDate(IdentifierInfo &II) const;
  345. Linkage getCachedLinkage() const {
  346. return Linkage(CacheValidAndLinkage - 1);
  347. }
  348. void setCachedLinkage(Linkage L) const {
  349. CacheValidAndLinkage = L + 1;
  350. }
  351. bool hasCachedLinkage() const {
  352. return CacheValidAndLinkage;
  353. }
  354. public:
  355. /// Source range that this declaration covers.
  356. virtual SourceRange getSourceRange() const LLVM_READONLY {
  357. return SourceRange(getLocation(), getLocation());
  358. }
  359. SourceLocation getBeginLoc() const LLVM_READONLY {
  360. return getSourceRange().getBegin();
  361. }
  362. SourceLocation getEndLoc() const LLVM_READONLY {
  363. return getSourceRange().getEnd();
  364. }
  365. SourceLocation getLocation() const { return Loc; }
  366. void setLocation(SourceLocation L) { Loc = L; }
  367. Kind getKind() const { return static_cast<Kind>(DeclKind); }
  368. const char *getDeclKindName() const;
  369. Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
  370. const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
  371. DeclContext *getDeclContext() {
  372. if (isInSemaDC())
  373. return getSemanticDC();
  374. return getMultipleDC()->SemanticDC;
  375. }
  376. const DeclContext *getDeclContext() const {
  377. return const_cast<Decl*>(this)->getDeclContext();
  378. }
  379. /// Find the innermost non-closure ancestor of this declaration,
  380. /// walking up through blocks, lambdas, etc. If that ancestor is
  381. /// not a code context (!isFunctionOrMethod()), returns null.
  382. ///
  383. /// A declaration may be its own non-closure context.
  384. Decl *getNonClosureContext();
  385. const Decl *getNonClosureContext() const {
  386. return const_cast<Decl*>(this)->getNonClosureContext();
  387. }
  388. TranslationUnitDecl *getTranslationUnitDecl();
  389. const TranslationUnitDecl *getTranslationUnitDecl() const {
  390. return const_cast<Decl*>(this)->getTranslationUnitDecl();
  391. }
  392. bool isInAnonymousNamespace() const;
  393. bool isInStdNamespace() const;
  394. ASTContext &getASTContext() const LLVM_READONLY;
  395. /// Helper to get the language options from the ASTContext.
  396. /// Defined out of line to avoid depending on ASTContext.h.
  397. const LangOptions &getLangOpts() const LLVM_READONLY;
  398. void setAccess(AccessSpecifier AS) {
  399. Access = AS;
  400. assert(AccessDeclContextCheck());
  401. }
  402. AccessSpecifier getAccess() const {
  403. assert(AccessDeclContextCheck());
  404. return AccessSpecifier(Access);
  405. }
  406. /// Retrieve the access specifier for this declaration, even though
  407. /// it may not yet have been properly set.
  408. AccessSpecifier getAccessUnsafe() const {
  409. return AccessSpecifier(Access);
  410. }
  411. bool hasAttrs() const { return HasAttrs; }
  412. void setAttrs(const AttrVec& Attrs) {
  413. return setAttrsImpl(Attrs, getASTContext());
  414. }
  415. AttrVec &getAttrs() {
  416. return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
  417. }
  418. const AttrVec &getAttrs() const;
  419. void dropAttrs();
  420. void addAttr(Attr *A);
  421. using attr_iterator = AttrVec::const_iterator;
  422. using attr_range = llvm::iterator_range<attr_iterator>;
  423. attr_range attrs() const {
  424. return attr_range(attr_begin(), attr_end());
  425. }
  426. attr_iterator attr_begin() const {
  427. return hasAttrs() ? getAttrs().begin() : nullptr;
  428. }
  429. attr_iterator attr_end() const {
  430. return hasAttrs() ? getAttrs().end() : nullptr;
  431. }
  432. template <typename T>
  433. void dropAttr() {
  434. if (!HasAttrs) return;
  435. AttrVec &Vec = getAttrs();
  436. llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); });
  437. if (Vec.empty())
  438. HasAttrs = false;
  439. }
  440. template <typename T>
  441. llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
  442. return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
  443. }
  444. template <typename T>
  445. specific_attr_iterator<T> specific_attr_begin() const {
  446. return specific_attr_iterator<T>(attr_begin());
  447. }
  448. template <typename T>
  449. specific_attr_iterator<T> specific_attr_end() const {
  450. return specific_attr_iterator<T>(attr_end());
  451. }
  452. template<typename T> T *getAttr() const {
  453. return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
  454. }
  455. template<typename T> bool hasAttr() const {
  456. return hasAttrs() && hasSpecificAttr<T>(getAttrs());
  457. }
  458. /// getMaxAlignment - return the maximum alignment specified by attributes
  459. /// on this decl, 0 if there are none.
  460. unsigned getMaxAlignment() const;
  461. /// setInvalidDecl - Indicates the Decl had a semantic error. This
  462. /// allows for graceful error recovery.
  463. void setInvalidDecl(bool Invalid = true);
  464. bool isInvalidDecl() const { return (bool) InvalidDecl; }
  465. /// isImplicit - Indicates whether the declaration was implicitly
  466. /// generated by the implementation. If false, this declaration
  467. /// was written explicitly in the source code.
  468. bool isImplicit() const { return Implicit; }
  469. void setImplicit(bool I = true) { Implicit = I; }
  470. /// Whether *any* (re-)declaration of the entity was used, meaning that
  471. /// a definition is required.
  472. ///
  473. /// \param CheckUsedAttr When true, also consider the "used" attribute
  474. /// (in addition to the "used" bit set by \c setUsed()) when determining
  475. /// whether the function is used.
  476. bool isUsed(bool CheckUsedAttr = true) const;
  477. /// Set whether the declaration is used, in the sense of odr-use.
  478. ///
  479. /// This should only be used immediately after creating a declaration.
  480. /// It intentionally doesn't notify any listeners.
  481. void setIsUsed() { getCanonicalDecl()->Used = true; }
  482. /// Mark the declaration used, in the sense of odr-use.
  483. ///
  484. /// This notifies any mutation listeners in addition to setting a bit
  485. /// indicating the declaration is used.
  486. void markUsed(ASTContext &C);
  487. /// Whether any declaration of this entity was referenced.
  488. bool isReferenced() const;
  489. /// Whether this declaration was referenced. This should not be relied
  490. /// upon for anything other than debugging.
  491. bool isThisDeclarationReferenced() const { return Referenced; }
  492. void setReferenced(bool R = true) { Referenced = R; }
  493. /// Whether this declaration is a top-level declaration (function,
  494. /// global variable, etc.) that is lexically inside an objc container
  495. /// definition.
  496. bool isTopLevelDeclInObjCContainer() const {
  497. return TopLevelDeclInObjCContainer;
  498. }
  499. void setTopLevelDeclInObjCContainer(bool V = true) {
  500. TopLevelDeclInObjCContainer = V;
  501. }
  502. /// Looks on this and related declarations for an applicable
  503. /// external source symbol attribute.
  504. ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
  505. /// Whether this declaration was marked as being private to the
  506. /// module in which it was defined.
  507. bool isModulePrivate() const {
  508. return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
  509. }
  510. /// Whether this declaration was exported in a lexical context.
  511. /// e.g.:
  512. ///
  513. /// export namespace A {
  514. /// void f1(); // isInExportDeclContext() == true
  515. /// }
  516. /// void A::f1(); // isInExportDeclContext() == false
  517. ///
  518. /// namespace B {
  519. /// void f2(); // isInExportDeclContext() == false
  520. /// }
  521. /// export void B::f2(); // isInExportDeclContext() == true
  522. bool isInExportDeclContext() const;
  523. /// Return true if this declaration has an attribute which acts as
  524. /// definition of the entity, such as 'alias' or 'ifunc'.
  525. bool hasDefiningAttr() const;
  526. /// Return this declaration's defining attribute if it has one.
  527. const Attr *getDefiningAttr() const;
  528. protected:
  529. /// Specify that this declaration was marked as being private
  530. /// to the module in which it was defined.
  531. void setModulePrivate() {
  532. // The module-private specifier has no effect on unowned declarations.
  533. // FIXME: We should track this in some way for source fidelity.
  534. if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
  535. return;
  536. setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
  537. }
  538. public:
  539. /// Set the FromASTFile flag. This indicates that this declaration
  540. /// was deserialized and not parsed from source code and enables
  541. /// features such as module ownership information.
  542. void setFromASTFile() {
  543. FromASTFile = true;
  544. }
  545. /// Set the owning module ID. This may only be called for
  546. /// deserialized Decls.
  547. void setOwningModuleID(unsigned ID) {
  548. assert(isFromASTFile() && "Only works on a deserialized declaration");
  549. *((unsigned*)this - 2) = ID;
  550. }
  551. public:
  552. /// Determine the availability of the given declaration.
  553. ///
  554. /// This routine will determine the most restrictive availability of
  555. /// the given declaration (e.g., preferring 'unavailable' to
  556. /// 'deprecated').
  557. ///
  558. /// \param Message If non-NULL and the result is not \c
  559. /// AR_Available, will be set to a (possibly empty) message
  560. /// describing why the declaration has not been introduced, is
  561. /// deprecated, or is unavailable.
  562. ///
  563. /// \param EnclosingVersion The version to compare with. If empty, assume the
  564. /// deployment target version.
  565. ///
  566. /// \param RealizedPlatform If non-NULL and the availability result is found
  567. /// in an available attribute it will set to the platform which is written in
  568. /// the available attribute.
  569. AvailabilityResult
  570. getAvailability(std::string *Message = nullptr,
  571. VersionTuple EnclosingVersion = VersionTuple(),
  572. StringRef *RealizedPlatform = nullptr) const;
  573. /// Retrieve the version of the target platform in which this
  574. /// declaration was introduced.
  575. ///
  576. /// \returns An empty version tuple if this declaration has no 'introduced'
  577. /// availability attributes, or the version tuple that's specified in the
  578. /// attribute otherwise.
  579. VersionTuple getVersionIntroduced() const;
  580. /// Determine whether this declaration is marked 'deprecated'.
  581. ///
  582. /// \param Message If non-NULL and the declaration is deprecated,
  583. /// this will be set to the message describing why the declaration
  584. /// was deprecated (which may be empty).
  585. bool isDeprecated(std::string *Message = nullptr) const {
  586. return getAvailability(Message) == AR_Deprecated;
  587. }
  588. /// Determine whether this declaration is marked 'unavailable'.
  589. ///
  590. /// \param Message If non-NULL and the declaration is unavailable,
  591. /// this will be set to the message describing why the declaration
  592. /// was made unavailable (which may be empty).
  593. bool isUnavailable(std::string *Message = nullptr) const {
  594. return getAvailability(Message) == AR_Unavailable;
  595. }
  596. /// Determine whether this is a weak-imported symbol.
  597. ///
  598. /// Weak-imported symbols are typically marked with the
  599. /// 'weak_import' attribute, but may also be marked with an
  600. /// 'availability' attribute where we're targing a platform prior to
  601. /// the introduction of this feature.
  602. bool isWeakImported() const;
  603. /// Determines whether this symbol can be weak-imported,
  604. /// e.g., whether it would be well-formed to add the weak_import
  605. /// attribute.
  606. ///
  607. /// \param IsDefinition Set to \c true to indicate that this
  608. /// declaration cannot be weak-imported because it has a definition.
  609. bool canBeWeakImported(bool &IsDefinition) const;
  610. /// Determine whether this declaration came from an AST file (such as
  611. /// a precompiled header or module) rather than having been parsed.
  612. bool isFromASTFile() const { return FromASTFile; }
  613. /// Retrieve the global declaration ID associated with this
  614. /// declaration, which specifies where this Decl was loaded from.
  615. unsigned getGlobalID() const {
  616. if (isFromASTFile())
  617. return *((const unsigned*)this - 1);
  618. return 0;
  619. }
  620. /// Retrieve the global ID of the module that owns this particular
  621. /// declaration.
  622. unsigned getOwningModuleID() const {
  623. if (isFromASTFile())
  624. return *((const unsigned*)this - 2);
  625. return 0;
  626. }
  627. private:
  628. Module *getOwningModuleSlow() const;
  629. protected:
  630. bool hasLocalOwningModuleStorage() const;
  631. public:
  632. /// Get the imported owning module, if this decl is from an imported
  633. /// (non-local) module.
  634. Module *getImportedOwningModule() const {
  635. if (!isFromASTFile() || !hasOwningModule())
  636. return nullptr;
  637. return getOwningModuleSlow();
  638. }
  639. /// Get the local owning module, if known. Returns nullptr if owner is
  640. /// not yet known or declaration is not from a module.
  641. Module *getLocalOwningModule() const {
  642. if (isFromASTFile() || !hasOwningModule())
  643. return nullptr;
  644. assert(hasLocalOwningModuleStorage() &&
  645. "owned local decl but no local module storage");
  646. return reinterpret_cast<Module *const *>(this)[-1];
  647. }
  648. void setLocalOwningModule(Module *M) {
  649. assert(!isFromASTFile() && hasOwningModule() &&
  650. hasLocalOwningModuleStorage() &&
  651. "should not have a cached owning module");
  652. reinterpret_cast<Module **>(this)[-1] = M;
  653. }
  654. /// Is this declaration owned by some module?
  655. bool hasOwningModule() const {
  656. return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
  657. }
  658. /// Get the module that owns this declaration (for visibility purposes).
  659. Module *getOwningModule() const {
  660. return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
  661. }
  662. /// Get the module that owns this declaration for linkage purposes.
  663. /// There only ever is such a module under the C++ Modules TS.
  664. ///
  665. /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
  666. /// all declarations in a global module fragment are unowned.
  667. Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
  668. /// Determine whether this declaration is definitely visible to name lookup,
  669. /// independent of whether the owning module is visible.
  670. /// Note: The declaration may be visible even if this returns \c false if the
  671. /// owning module is visible within the query context. This is a low-level
  672. /// helper function; most code should be calling Sema::isVisible() instead.
  673. bool isUnconditionallyVisible() const {
  674. return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
  675. }
  676. /// Set that this declaration is globally visible, even if it came from a
  677. /// module that is not visible.
  678. void setVisibleDespiteOwningModule() {
  679. if (!isUnconditionallyVisible())
  680. setModuleOwnershipKind(ModuleOwnershipKind::Visible);
  681. }
  682. /// Get the kind of module ownership for this declaration.
  683. ModuleOwnershipKind getModuleOwnershipKind() const {
  684. return NextInContextAndBits.getInt();
  685. }
  686. /// Set whether this declaration is hidden from name lookup.
  687. void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
  688. assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&
  689. MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&
  690. !hasLocalOwningModuleStorage()) &&
  691. "no storage available for owning module for this declaration");
  692. NextInContextAndBits.setInt(MOK);
  693. }
  694. unsigned getIdentifierNamespace() const {
  695. return IdentifierNamespace;
  696. }
  697. bool isInIdentifierNamespace(unsigned NS) const {
  698. return getIdentifierNamespace() & NS;
  699. }
  700. static unsigned getIdentifierNamespaceForKind(Kind DK);
  701. bool hasTagIdentifierNamespace() const {
  702. return isTagIdentifierNamespace(getIdentifierNamespace());
  703. }
  704. static bool isTagIdentifierNamespace(unsigned NS) {
  705. // TagDecls have Tag and Type set and may also have TagFriend.
  706. return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
  707. }
  708. /// getLexicalDeclContext - The declaration context where this Decl was
  709. /// lexically declared (LexicalDC). May be different from
  710. /// getDeclContext() (SemanticDC).
  711. /// e.g.:
  712. ///
  713. /// namespace A {
  714. /// void f(); // SemanticDC == LexicalDC == 'namespace A'
  715. /// }
  716. /// void A::f(); // SemanticDC == namespace 'A'
  717. /// // LexicalDC == global namespace
  718. DeclContext *getLexicalDeclContext() {
  719. if (isInSemaDC())
  720. return getSemanticDC();
  721. return getMultipleDC()->LexicalDC;
  722. }
  723. const DeclContext *getLexicalDeclContext() const {
  724. return const_cast<Decl*>(this)->getLexicalDeclContext();
  725. }
  726. /// Determine whether this declaration is declared out of line (outside its
  727. /// semantic context).
  728. virtual bool isOutOfLine() const;
  729. /// setDeclContext - Set both the semantic and lexical DeclContext
  730. /// to DC.
  731. void setDeclContext(DeclContext *DC);
  732. void setLexicalDeclContext(DeclContext *DC);
  733. /// Determine whether this declaration is a templated entity (whether it is
  734. // within the scope of a template parameter).
  735. bool isTemplated() const;
  736. /// Determine the number of levels of template parameter surrounding this
  737. /// declaration.
  738. unsigned getTemplateDepth() const;
  739. /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
  740. /// scoped decl is defined outside the current function or method. This is
  741. /// roughly global variables and functions, but also handles enums (which
  742. /// could be defined inside or outside a function etc).
  743. bool isDefinedOutsideFunctionOrMethod() const {
  744. return getParentFunctionOrMethod() == nullptr;
  745. }
  746. /// Determine whether a substitution into this declaration would occur as
  747. /// part of a substitution into a dependent local scope. Such a substitution
  748. /// transitively substitutes into all constructs nested within this
  749. /// declaration.
  750. ///
  751. /// This recognizes non-defining declarations as well as members of local
  752. /// classes and lambdas:
  753. /// \code
  754. /// template<typename T> void foo() { void bar(); }
  755. /// template<typename T> void foo2() { class ABC { void bar(); }; }
  756. /// template<typename T> inline int x = [](){ return 0; }();
  757. /// \endcode
  758. bool isInLocalScopeForInstantiation() const;
  759. /// If this decl is defined inside a function/method/block it returns
  760. /// the corresponding DeclContext, otherwise it returns null.
  761. const DeclContext *getParentFunctionOrMethod() const;
  762. DeclContext *getParentFunctionOrMethod() {
  763. return const_cast<DeclContext*>(
  764. const_cast<const Decl*>(this)->getParentFunctionOrMethod());
  765. }
  766. /// Retrieves the "canonical" declaration of the given declaration.
  767. virtual Decl *getCanonicalDecl() { return this; }
  768. const Decl *getCanonicalDecl() const {
  769. return const_cast<Decl*>(this)->getCanonicalDecl();
  770. }
  771. /// Whether this particular Decl is a canonical one.
  772. bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
  773. protected:
  774. /// Returns the next redeclaration or itself if this is the only decl.
  775. ///
  776. /// Decl subclasses that can be redeclared should override this method so that
  777. /// Decl::redecl_iterator can iterate over them.
  778. virtual Decl *getNextRedeclarationImpl() { return this; }
  779. /// Implementation of getPreviousDecl(), to be overridden by any
  780. /// subclass that has a redeclaration chain.
  781. virtual Decl *getPreviousDeclImpl() { return nullptr; }
  782. /// Implementation of getMostRecentDecl(), to be overridden by any
  783. /// subclass that has a redeclaration chain.
  784. virtual Decl *getMostRecentDeclImpl() { return this; }
  785. public:
  786. /// Iterates through all the redeclarations of the same decl.
  787. class redecl_iterator {
  788. /// Current - The current declaration.
  789. Decl *Current = nullptr;
  790. Decl *Starter;
  791. public:
  792. using value_type = Decl *;
  793. using reference = const value_type &;
  794. using pointer = const value_type *;
  795. using iterator_category = std::forward_iterator_tag;
  796. using difference_type = std::ptrdiff_t;
  797. redecl_iterator() = default;
  798. explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
  799. reference operator*() const { return Current; }
  800. value_type operator->() const { return Current; }
  801. redecl_iterator& operator++() {
  802. assert(Current && "Advancing while iterator has reached end");
  803. // Get either previous decl or latest decl.
  804. Decl *Next = Current->getNextRedeclarationImpl();
  805. assert(Next && "Should return next redeclaration or itself, never null!");
  806. Current = (Next != Starter) ? Next : nullptr;
  807. return *this;
  808. }
  809. redecl_iterator operator++(int) {
  810. redecl_iterator tmp(*this);
  811. ++(*this);
  812. return tmp;
  813. }
  814. friend bool operator==(redecl_iterator x, redecl_iterator y) {
  815. return x.Current == y.Current;
  816. }
  817. friend bool operator!=(redecl_iterator x, redecl_iterator y) {
  818. return x.Current != y.Current;
  819. }
  820. };
  821. using redecl_range = llvm::iterator_range<redecl_iterator>;
  822. /// Returns an iterator range for all the redeclarations of the same
  823. /// decl. It will iterate at least once (when this decl is the only one).
  824. redecl_range redecls() const {
  825. return redecl_range(redecls_begin(), redecls_end());
  826. }
  827. redecl_iterator redecls_begin() const {
  828. return redecl_iterator(const_cast<Decl *>(this));
  829. }
  830. redecl_iterator redecls_end() const { return redecl_iterator(); }
  831. /// Retrieve the previous declaration that declares the same entity
  832. /// as this declaration, or NULL if there is no previous declaration.
  833. Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
  834. /// Retrieve the previous declaration that declares the same entity
  835. /// as this declaration, or NULL if there is no previous declaration.
  836. const Decl *getPreviousDecl() const {
  837. return const_cast<Decl *>(this)->getPreviousDeclImpl();
  838. }
  839. /// True if this is the first declaration in its redeclaration chain.
  840. bool isFirstDecl() const {
  841. return getPreviousDecl() == nullptr;
  842. }
  843. /// Retrieve the most recent declaration that declares the same entity
  844. /// as this declaration (which may be this declaration).
  845. Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
  846. /// Retrieve the most recent declaration that declares the same entity
  847. /// as this declaration (which may be this declaration).
  848. const Decl *getMostRecentDecl() const {
  849. return const_cast<Decl *>(this)->getMostRecentDeclImpl();
  850. }
  851. /// getBody - If this Decl represents a declaration for a body of code,
  852. /// such as a function or method definition, this method returns the
  853. /// top-level Stmt* of that body. Otherwise this method returns null.
  854. virtual Stmt* getBody() const { return nullptr; }
  855. /// Returns true if this \c Decl represents a declaration for a body of
  856. /// code, such as a function or method definition.
  857. /// Note that \c hasBody can also return true if any redeclaration of this
  858. /// \c Decl represents a declaration for a body of code.
  859. virtual bool hasBody() const { return getBody() != nullptr; }
  860. /// getBodyRBrace - Gets the right brace of the body, if a body exists.
  861. /// This works whether the body is a CompoundStmt or a CXXTryStmt.
  862. SourceLocation getBodyRBrace() const;
  863. // global temp stats (until we have a per-module visitor)
  864. static void add(Kind k);
  865. static void EnableStatistics();
  866. static void PrintStats();
  867. /// isTemplateParameter - Determines whether this declaration is a
  868. /// template parameter.
  869. bool isTemplateParameter() const;
  870. /// isTemplateParameter - Determines whether this declaration is a
  871. /// template parameter pack.
  872. bool isTemplateParameterPack() const;
  873. /// Whether this declaration is a parameter pack.
  874. bool isParameterPack() const;
  875. /// returns true if this declaration is a template
  876. bool isTemplateDecl() const;
  877. /// Whether this declaration is a function or function template.
  878. bool isFunctionOrFunctionTemplate() const {
  879. return (DeclKind >= Decl::firstFunction &&
  880. DeclKind <= Decl::lastFunction) ||
  881. DeclKind == FunctionTemplate;
  882. }
  883. /// If this is a declaration that describes some template, this
  884. /// method returns that template declaration.
  885. ///
  886. /// Note that this returns nullptr for partial specializations, because they
  887. /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
  888. /// those cases.
  889. TemplateDecl *getDescribedTemplate() const;
  890. /// If this is a declaration that describes some template or partial
  891. /// specialization, this returns the corresponding template parameter list.
  892. const TemplateParameterList *getDescribedTemplateParams() const;
  893. /// Returns the function itself, or the templated function if this is a
  894. /// function template.
  895. FunctionDecl *getAsFunction() LLVM_READONLY;
  896. const FunctionDecl *getAsFunction() const {
  897. return const_cast<Decl *>(this)->getAsFunction();
  898. }
  899. /// Changes the namespace of this declaration to reflect that it's
  900. /// a function-local extern declaration.
  901. ///
  902. /// These declarations appear in the lexical context of the extern
  903. /// declaration, but in the semantic context of the enclosing namespace
  904. /// scope.
  905. void setLocalExternDecl() {
  906. Decl *Prev = getPreviousDecl();
  907. IdentifierNamespace &= ~IDNS_Ordinary;
  908. // It's OK for the declaration to still have the "invisible friend" flag or
  909. // the "conflicts with tag declarations in this scope" flag for the outer
  910. // scope.
  911. assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&
  912. "namespace is not ordinary");
  913. IdentifierNamespace |= IDNS_LocalExtern;
  914. if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
  915. IdentifierNamespace |= IDNS_Ordinary;
  916. }
  917. /// Determine whether this is a block-scope declaration with linkage.
  918. /// This will either be a local variable declaration declared 'extern', or a
  919. /// local function declaration.
  920. bool isLocalExternDecl() {
  921. return IdentifierNamespace & IDNS_LocalExtern;
  922. }
  923. /// Changes the namespace of this declaration to reflect that it's
  924. /// the object of a friend declaration.
  925. ///
  926. /// These declarations appear in the lexical context of the friending
  927. /// class, but in the semantic context of the actual entity. This property
  928. /// applies only to a specific decl object; other redeclarations of the
  929. /// same entity may not (and probably don't) share this property.
  930. void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
  931. unsigned OldNS = IdentifierNamespace;
  932. assert((OldNS & (IDNS_Tag | IDNS_Ordinary |
  933. IDNS_TagFriend | IDNS_OrdinaryFriend |
  934. IDNS_LocalExtern | IDNS_NonMemberOperator)) &&
  935. "namespace includes neither ordinary nor tag");
  936. assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |
  937. IDNS_TagFriend | IDNS_OrdinaryFriend |
  938. IDNS_LocalExtern | IDNS_NonMemberOperator)) &&
  939. "namespace includes other than ordinary or tag");
  940. Decl *Prev = getPreviousDecl();
  941. IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
  942. if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
  943. IdentifierNamespace |= IDNS_TagFriend;
  944. if (PerformFriendInjection ||
  945. (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
  946. IdentifierNamespace |= IDNS_Tag | IDNS_Type;
  947. }
  948. if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
  949. IDNS_LocalExtern | IDNS_NonMemberOperator)) {
  950. IdentifierNamespace |= IDNS_OrdinaryFriend;
  951. if (PerformFriendInjection ||
  952. (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
  953. IdentifierNamespace |= IDNS_Ordinary;
  954. }
  955. }
  956. enum FriendObjectKind {
  957. FOK_None, ///< Not a friend object.
  958. FOK_Declared, ///< A friend of a previously-declared entity.
  959. FOK_Undeclared ///< A friend of a previously-undeclared entity.
  960. };
  961. /// Determines whether this declaration is the object of a
  962. /// friend declaration and, if so, what kind.
  963. ///
  964. /// There is currently no direct way to find the associated FriendDecl.
  965. FriendObjectKind getFriendObjectKind() const {
  966. unsigned mask =
  967. (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
  968. if (!mask) return FOK_None;
  969. return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
  970. : FOK_Undeclared);
  971. }
  972. /// Specifies that this declaration is a C++ overloaded non-member.
  973. void setNonMemberOperator() {
  974. assert(getKind() == Function || getKind() == FunctionTemplate);
  975. assert((IdentifierNamespace & IDNS_Ordinary) &&
  976. "visible non-member operators should be in ordinary namespace");
  977. IdentifierNamespace |= IDNS_NonMemberOperator;
  978. }
  979. static bool classofKind(Kind K) { return true; }
  980. static DeclContext *castToDeclContext(const Decl *);
  981. static Decl *castFromDeclContext(const DeclContext *);
  982. void print(raw_ostream &Out, unsigned Indentation = 0,
  983. bool PrintInstantiation = false) const;
  984. void print(raw_ostream &Out, const PrintingPolicy &Policy,
  985. unsigned Indentation = 0, bool PrintInstantiation = false) const;
  986. static void printGroup(Decl** Begin, unsigned NumDecls,
  987. raw_ostream &Out, const PrintingPolicy &Policy,
  988. unsigned Indentation = 0);
  989. // Debuggers don't usually respect default arguments.
  990. void dump() const;
  991. // Same as dump(), but forces color printing.
  992. void dumpColor() const;
  993. void dump(raw_ostream &Out, bool Deserialize = false,
  994. ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
  995. /// \return Unique reproducible object identifier
  996. int64_t getID() const;
  997. /// Looks through the Decl's underlying type to extract a FunctionType
  998. /// when possible. Will return null if the type underlying the Decl does not
  999. /// have a FunctionType.
  1000. const FunctionType *getFunctionType(bool BlocksToo = true) const;
  1001. private:
  1002. void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
  1003. void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
  1004. ASTContext &Ctx);
  1005. protected:
  1006. ASTMutationListener *getASTMutationListener() const;
  1007. };
  1008. /// Determine whether two declarations declare the same entity.
  1009. inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
  1010. if (!D1 || !D2)
  1011. return false;
  1012. if (D1 == D2)
  1013. return true;
  1014. return D1->getCanonicalDecl() == D2->getCanonicalDecl();
  1015. }
  1016. /// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
  1017. /// doing something to a specific decl.
  1018. class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
  1019. const Decl *TheDecl;
  1020. SourceLocation Loc;
  1021. SourceManager &SM;
  1022. const char *Message;
  1023. public:
  1024. PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
  1025. SourceManager &sm, const char *Msg)
  1026. : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
  1027. void print(raw_ostream &OS) const override;
  1028. };
  1029. } // namespace clang
  1030. // Required to determine the layout of the PointerUnion<NamedDecl*> before
  1031. // seeing the NamedDecl definition being first used in DeclListNode::operator*.
  1032. namespace llvm {
  1033. template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> {
  1034. static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; }
  1035. static inline ::clang::NamedDecl *getFromVoidPointer(void *P) {
  1036. return static_cast<::clang::NamedDecl *>(P);
  1037. }
  1038. static constexpr int NumLowBitsAvailable = 3;
  1039. };
  1040. }
  1041. namespace clang {
  1042. /// A list storing NamedDecls in the lookup tables.
  1043. class DeclListNode {
  1044. friend class ASTContext; // allocate, deallocate nodes.
  1045. friend class StoredDeclsList;
  1046. public:
  1047. using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>;
  1048. class iterator {
  1049. friend class DeclContextLookupResult;
  1050. friend class StoredDeclsList;
  1051. Decls Ptr;
  1052. iterator(Decls Node) : Ptr(Node) { }
  1053. public:
  1054. using difference_type = ptrdiff_t;
  1055. using value_type = NamedDecl*;
  1056. using pointer = void;
  1057. using reference = value_type;
  1058. using iterator_category = std::forward_iterator_tag;
  1059. iterator() = default;
  1060. reference operator*() const {
  1061. assert(Ptr && "dereferencing end() iterator");
  1062. if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
  1063. return CurNode->D;
  1064. return Ptr.get<NamedDecl*>();
  1065. }
  1066. void operator->() const { } // Unsupported.
  1067. bool operator==(const iterator &X) const { return Ptr == X.Ptr; }
  1068. bool operator!=(const iterator &X) const { return Ptr != X.Ptr; }
  1069. inline iterator &operator++() { // ++It
  1070. assert(!Ptr.isNull() && "Advancing empty iterator");
  1071. if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
  1072. Ptr = CurNode->Rest;
  1073. else
  1074. Ptr = nullptr;
  1075. return *this;
  1076. }
  1077. iterator operator++(int) { // It++
  1078. iterator temp = *this;
  1079. ++(*this);
  1080. return temp;
  1081. }
  1082. // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I)
  1083. iterator end() { return iterator(); }
  1084. };
  1085. private:
  1086. NamedDecl *D = nullptr;
  1087. Decls Rest = nullptr;
  1088. DeclListNode(NamedDecl *ND) : D(ND) {}
  1089. };
  1090. /// The results of name lookup within a DeclContext.
  1091. class DeclContextLookupResult {
  1092. using Decls = DeclListNode::Decls;
  1093. /// When in collection form, this is what the Data pointer points to.
  1094. Decls Result;
  1095. public:
  1096. DeclContextLookupResult() = default;
  1097. DeclContextLookupResult(Decls Result) : Result(Result) {}
  1098. using iterator = DeclListNode::iterator;
  1099. using const_iterator = iterator;
  1100. using reference = iterator::reference;
  1101. iterator begin() { return iterator(Result); }
  1102. iterator end() { return iterator(); }
  1103. const_iterator begin() const {
  1104. return const_cast<DeclContextLookupResult*>(this)->begin();
  1105. }
  1106. const_iterator end() const { return iterator(); }
  1107. bool empty() const { return Result.isNull(); }
  1108. bool isSingleResult() const { return Result.dyn_cast<NamedDecl*>(); }
  1109. reference front() const { return *begin(); }
  1110. // Find the first declaration of the given type in the list. Note that this
  1111. // is not in general the earliest-declared declaration, and should only be
  1112. // used when it's not possible for there to be more than one match or where
  1113. // it doesn't matter which one is found.
  1114. template<class T> T *find_first() const {
  1115. for (auto *D : *this)
  1116. if (T *Decl = dyn_cast<T>(D))
  1117. return Decl;
  1118. return nullptr;
  1119. }
  1120. };
  1121. /// DeclContext - This is used only as base class of specific decl types that
  1122. /// can act as declaration contexts. These decls are (only the top classes
  1123. /// that directly derive from DeclContext are mentioned, not their subclasses):
  1124. ///
  1125. /// TranslationUnitDecl
  1126. /// ExternCContext
  1127. /// NamespaceDecl
  1128. /// TagDecl
  1129. /// OMPDeclareReductionDecl
  1130. /// OMPDeclareMapperDecl
  1131. /// FunctionDecl
  1132. /// ObjCMethodDecl
  1133. /// ObjCContainerDecl
  1134. /// LinkageSpecDecl
  1135. /// ExportDecl
  1136. /// BlockDecl
  1137. /// CapturedDecl
  1138. class DeclContext {
  1139. /// For makeDeclVisibleInContextImpl
  1140. friend class ASTDeclReader;
  1141. /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
  1142. /// hasNeedToReconcileExternalVisibleStorage
  1143. friend class ExternalASTSource;
  1144. /// For CreateStoredDeclsMap
  1145. friend class DependentDiagnostic;
  1146. /// For hasNeedToReconcileExternalVisibleStorage,
  1147. /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
  1148. friend class ASTWriter;
  1149. // We use uint64_t in the bit-fields below since some bit-fields
  1150. // cross the unsigned boundary and this breaks the packing.
  1151. /// Stores the bits used by DeclContext.
  1152. /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
  1153. /// methods in DeclContext should be updated appropriately.
  1154. class DeclContextBitfields {
  1155. friend class DeclContext;
  1156. /// DeclKind - This indicates which class this is.
  1157. uint64_t DeclKind : 7;
  1158. /// Whether this declaration context also has some external
  1159. /// storage that contains additional declarations that are lexically
  1160. /// part of this context.
  1161. mutable uint64_t ExternalLexicalStorage : 1;
  1162. /// Whether this declaration context also has some external
  1163. /// storage that contains additional declarations that are visible
  1164. /// in this context.
  1165. mutable uint64_t ExternalVisibleStorage : 1;
  1166. /// Whether this declaration context has had externally visible
  1167. /// storage added since the last lookup. In this case, \c LookupPtr's
  1168. /// invariant may not hold and needs to be fixed before we perform
  1169. /// another lookup.
  1170. mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
  1171. /// If \c true, this context may have local lexical declarations
  1172. /// that are missing from the lookup table.
  1173. mutable uint64_t HasLazyLocalLexicalLookups : 1;
  1174. /// If \c true, the external source may have lexical declarations
  1175. /// that are missing from the lookup table.
  1176. mutable uint64_t HasLazyExternalLexicalLookups : 1;
  1177. /// If \c true, lookups should only return identifier from
  1178. /// DeclContext scope (for example TranslationUnit). Used in
  1179. /// LookupQualifiedName()
  1180. mutable uint64_t UseQualifiedLookup : 1;
  1181. };
  1182. /// Number of bits in DeclContextBitfields.
  1183. enum { NumDeclContextBits = 13 };
  1184. /// Stores the bits used by TagDecl.
  1185. /// If modified NumTagDeclBits and the accessor
  1186. /// methods in TagDecl should be updated appropriately.
  1187. class TagDeclBitfields {
  1188. friend class TagDecl;
  1189. /// For the bits in DeclContextBitfields
  1190. uint64_t : NumDeclContextBits;
  1191. /// The TagKind enum.
  1192. uint64_t TagDeclKind : 3;
  1193. /// True if this is a definition ("struct foo {};"), false if it is a
  1194. /// declaration ("struct foo;"). It is not considered a definition
  1195. /// until the definition has been fully processed.
  1196. uint64_t IsCompleteDefinition : 1;
  1197. /// True if this is currently being defined.
  1198. uint64_t IsBeingDefined : 1;
  1199. /// True if this tag declaration is "embedded" (i.e., defined or declared
  1200. /// for the very first time) in the syntax of a declarator.
  1201. uint64_t IsEmbeddedInDeclarator : 1;
  1202. /// True if this tag is free standing, e.g. "struct foo;".
  1203. uint64_t IsFreeStanding : 1;
  1204. /// Indicates whether it is possible for declarations of this kind
  1205. /// to have an out-of-date definition.
  1206. ///
  1207. /// This option is only enabled when modules are enabled.
  1208. uint64_t MayHaveOutOfDateDef : 1;
  1209. /// Has the full definition of this type been required by a use somewhere in
  1210. /// the TU.
  1211. uint64_t IsCompleteDefinitionRequired : 1;
  1212. };
  1213. /// Number of non-inherited bits in TagDeclBitfields.
  1214. enum { NumTagDeclBits = 9 };
  1215. /// Stores the bits used by EnumDecl.
  1216. /// If modified NumEnumDeclBit and the accessor
  1217. /// methods in EnumDecl should be updated appropriately.
  1218. class EnumDeclBitfields {
  1219. friend class EnumDecl;
  1220. /// For the bits in DeclContextBitfields.
  1221. uint64_t : NumDeclContextBits;
  1222. /// For the bits in TagDeclBitfields.
  1223. uint64_t : NumTagDeclBits;
  1224. /// Width in bits required to store all the non-negative
  1225. /// enumerators of this enum.
  1226. uint64_t NumPositiveBits : 8;
  1227. /// Width in bits required to store all the negative
  1228. /// enumerators of this enum.
  1229. uint64_t NumNegativeBits : 8;
  1230. /// True if this tag declaration is a scoped enumeration. Only
  1231. /// possible in C++11 mode.
  1232. uint64_t IsScoped : 1;
  1233. /// If this tag declaration is a scoped enum,
  1234. /// then this is true if the scoped enum was declared using the class
  1235. /// tag, false if it was declared with the struct tag. No meaning is
  1236. /// associated if this tag declaration is not a scoped enum.
  1237. uint64_t IsScopedUsingClassTag : 1;
  1238. /// True if this is an enumeration with fixed underlying type. Only
  1239. /// possible in C++11, Microsoft extensions, or Objective C mode.
  1240. uint64_t IsFixed : 1;
  1241. /// True if a valid hash is stored in ODRHash.
  1242. uint64_t HasODRHash : 1;
  1243. };
  1244. /// Number of non-inherited bits in EnumDeclBitfields.
  1245. enum { NumEnumDeclBits = 20 };
  1246. /// Stores the bits used by RecordDecl.
  1247. /// If modified NumRecordDeclBits and the accessor
  1248. /// methods in RecordDecl should be updated appropriately.
  1249. class RecordDeclBitfields {
  1250. friend class RecordDecl;
  1251. /// For the bits in DeclContextBitfields.
  1252. uint64_t : NumDeclContextBits;
  1253. /// For the bits in TagDeclBitfields.
  1254. uint64_t : NumTagDeclBits;
  1255. /// This is true if this struct ends with a flexible
  1256. /// array member (e.g. int X[]) or if this union contains a struct that does.
  1257. /// If so, this cannot be contained in arrays or other structs as a member.
  1258. uint64_t HasFlexibleArrayMember : 1;
  1259. /// Whether this is the type of an anonymous struct or union.
  1260. uint64_t AnonymousStructOrUnion : 1;
  1261. /// This is true if this struct has at least one member
  1262. /// containing an Objective-C object pointer type.
  1263. uint64_t HasObjectMember : 1;
  1264. /// This is true if struct has at least one member of
  1265. /// 'volatile' type.
  1266. uint64_t HasVolatileMember : 1;
  1267. /// Whether the field declarations of this record have been loaded
  1268. /// from external storage. To avoid unnecessary deserialization of
  1269. /// methods/nested types we allow deserialization of just the fields
  1270. /// when needed.
  1271. mutable uint64_t LoadedFieldsFromExternalStorage : 1;
  1272. /// Basic properties of non-trivial C structs.
  1273. uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
  1274. uint64_t NonTrivialToPrimitiveCopy : 1;
  1275. uint64_t NonTrivialToPrimitiveDestroy : 1;
  1276. /// The following bits indicate whether this is or contains a C union that
  1277. /// is non-trivial to default-initialize, destruct, or copy. These bits
  1278. /// imply the associated basic non-triviality predicates declared above.
  1279. uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
  1280. uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
  1281. uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
  1282. /// Indicates whether this struct is destroyed in the callee.
  1283. uint64_t ParamDestroyedInCallee : 1;
  1284. /// Represents the way this type is passed to a function.
  1285. uint64_t ArgPassingRestrictions : 2;
  1286. };
  1287. /// Number of non-inherited bits in RecordDeclBitfields.
  1288. enum { NumRecordDeclBits = 14 };
  1289. /// Stores the bits used by OMPDeclareReductionDecl.
  1290. /// If modified NumOMPDeclareReductionDeclBits and the accessor
  1291. /// methods in OMPDeclareReductionDecl should be updated appropriately.
  1292. class OMPDeclareReductionDeclBitfields {
  1293. friend class OMPDeclareReductionDecl;
  1294. /// For the bits in DeclContextBitfields
  1295. uint64_t : NumDeclContextBits;
  1296. /// Kind of initializer,
  1297. /// function call or omp_priv<init_expr> initializtion.
  1298. uint64_t InitializerKind : 2;
  1299. };
  1300. /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
  1301. enum { NumOMPDeclareReductionDeclBits = 2 };
  1302. /// Stores the bits used by FunctionDecl.
  1303. /// If modified NumFunctionDeclBits and the accessor
  1304. /// methods in FunctionDecl and CXXDeductionGuideDecl
  1305. /// (for IsCopyDeductionCandidate) should be updated appropriately.
  1306. class FunctionDeclBitfields {
  1307. friend class FunctionDecl;
  1308. /// For IsCopyDeductionCandidate
  1309. friend class CXXDeductionGuideDecl;
  1310. /// For the bits in DeclContextBitfields.
  1311. uint64_t : NumDeclContextBits;
  1312. uint64_t SClass : 3;
  1313. uint64_t IsInline : 1;
  1314. uint64_t IsInlineSpecified : 1;
  1315. uint64_t IsVirtualAsWritten : 1;
  1316. uint64_t IsPure : 1;
  1317. uint64_t HasInheritedPrototype : 1;
  1318. uint64_t HasWrittenPrototype : 1;
  1319. uint64_t IsDeleted : 1;
  1320. /// Used by CXXMethodDecl
  1321. uint64_t IsTrivial : 1;
  1322. /// This flag indicates whether this function is trivial for the purpose of
  1323. /// calls. This is meaningful only when this function is a copy/move
  1324. /// constructor or a destructor.
  1325. uint64_t IsTrivialForCall : 1;
  1326. uint64_t IsDefaulted : 1;
  1327. uint64_t IsExplicitlyDefaulted : 1;
  1328. uint64_t HasDefaultedFunctionInfo : 1;
  1329. uint64_t HasImplicitReturnZero : 1;
  1330. uint64_t IsLateTemplateParsed : 1;
  1331. /// Kind of contexpr specifier as defined by ConstexprSpecKind.
  1332. uint64_t ConstexprKind : 2;
  1333. uint64_t InstantiationIsPending : 1;
  1334. /// Indicates if the function uses __try.
  1335. uint64_t UsesSEHTry : 1;
  1336. /// Indicates if the function was a definition
  1337. /// but its body was skipped.
  1338. uint64_t HasSkippedBody : 1;
  1339. /// Indicates if the function declaration will
  1340. /// have a body, once we're done parsing it.
  1341. uint64_t WillHaveBody : 1;
  1342. /// Indicates that this function is a multiversioned
  1343. /// function using attribute 'target'.
  1344. uint64_t IsMultiVersion : 1;
  1345. /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
  1346. /// the Deduction Guide is the implicitly generated 'copy
  1347. /// deduction candidate' (is used during overload resolution).
  1348. uint64_t IsCopyDeductionCandidate : 1;
  1349. /// Store the ODRHash after first calculation.
  1350. uint64_t HasODRHash : 1;
  1351. /// Indicates if the function uses Floating Point Constrained Intrinsics
  1352. uint64_t UsesFPIntrin : 1;
  1353. };
  1354. /// Number of non-inherited bits in FunctionDeclBitfields.
  1355. enum { NumFunctionDeclBits = 27 };
  1356. /// Stores the bits used by CXXConstructorDecl. If modified
  1357. /// NumCXXConstructorDeclBits and the accessor
  1358. /// methods in CXXConstructorDecl should be updated appropriately.
  1359. class CXXConstructorDeclBitfields {
  1360. friend class CXXConstructorDecl;
  1361. /// For the bits in DeclContextBitfields.
  1362. uint64_t : NumDeclContextBits;
  1363. /// For the bits in FunctionDeclBitfields.
  1364. uint64_t : NumFunctionDeclBits;
  1365. /// 24 bits to fit in the remaining available space.
  1366. /// Note that this makes CXXConstructorDeclBitfields take
  1367. /// exactly 64 bits and thus the width of NumCtorInitializers
  1368. /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
  1369. /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
  1370. uint64_t NumCtorInitializers : 21;
  1371. uint64_t IsInheritingConstructor : 1;
  1372. /// Whether this constructor has a trail-allocated explicit specifier.
  1373. uint64_t HasTrailingExplicitSpecifier : 1;
  1374. /// If this constructor does't have a trail-allocated explicit specifier.
  1375. /// Whether this constructor is explicit specified.
  1376. uint64_t IsSimpleExplicit : 1;
  1377. };
  1378. /// Number of non-inherited bits in CXXConstructorDeclBitfields.
  1379. enum {
  1380. NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
  1381. };
  1382. /// Stores the bits used by ObjCMethodDecl.
  1383. /// If modified NumObjCMethodDeclBits and the accessor
  1384. /// methods in ObjCMethodDecl should be updated appropriately.
  1385. class ObjCMethodDeclBitfields {
  1386. friend class ObjCMethodDecl;
  1387. /// For the bits in DeclContextBitfields.
  1388. uint64_t : NumDeclContextBits;
  1389. /// The conventional meaning of this method; an ObjCMethodFamily.
  1390. /// This is not serialized; instead, it is computed on demand and
  1391. /// cached.
  1392. mutable uint64_t Family : ObjCMethodFamilyBitWidth;
  1393. /// instance (true) or class (false) method.
  1394. uint64_t IsInstance : 1;
  1395. uint64_t IsVariadic : 1;
  1396. /// True if this method is the getter or setter for an explicit property.
  1397. uint64_t IsPropertyAccessor : 1;
  1398. /// True if this method is a synthesized property accessor stub.
  1399. uint64_t IsSynthesizedAccessorStub : 1;
  1400. /// Method has a definition.
  1401. uint64_t IsDefined : 1;
  1402. /// Method redeclaration in the same interface.
  1403. uint64_t IsRedeclaration : 1;
  1404. /// Is redeclared in the same interface.
  1405. mutable uint64_t HasRedeclaration : 1;
  1406. /// \@required/\@optional
  1407. uint64_t DeclImplementation : 2;
  1408. /// in, inout, etc.
  1409. uint64_t objcDeclQualifier : 7;
  1410. /// Indicates whether this method has a related result type.
  1411. uint64_t RelatedResultType : 1;
  1412. /// Whether the locations of the selector identifiers are in a
  1413. /// "standard" position, a enum SelectorLocationsKind.
  1414. uint64_t SelLocsKind : 2;
  1415. /// Whether this method overrides any other in the class hierarchy.
  1416. ///
  1417. /// A method is said to override any method in the class's
  1418. /// base classes, its protocols, or its categories' protocols, that has
  1419. /// the same selector and is of the same kind (class or instance).
  1420. /// A method in an implementation is not considered as overriding the same
  1421. /// method in the interface or its categories.
  1422. uint64_t IsOverriding : 1;
  1423. /// Indicates if the method was a definition but its body was skipped.
  1424. uint64_t HasSkippedBody : 1;
  1425. };
  1426. /// Number of non-inherited bits in ObjCMethodDeclBitfields.
  1427. enum { NumObjCMethodDeclBits = 24 };
  1428. /// Stores the bits used by ObjCContainerDecl.
  1429. /// If modified NumObjCContainerDeclBits and the accessor
  1430. /// methods in ObjCContainerDecl should be updated appropriately.
  1431. class ObjCContainerDeclBitfields {
  1432. friend class ObjCContainerDecl;
  1433. /// For the bits in DeclContextBitfields
  1434. uint32_t : NumDeclContextBits;
  1435. // Not a bitfield but this saves space.
  1436. // Note that ObjCContainerDeclBitfields is full.
  1437. SourceLocation AtStart;
  1438. };
  1439. /// Number of non-inherited bits in ObjCContainerDeclBitfields.
  1440. /// Note that here we rely on the fact that SourceLocation is 32 bits
  1441. /// wide. We check this with the static_assert in the ctor of DeclContext.
  1442. enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
  1443. /// Stores the bits used by LinkageSpecDecl.
  1444. /// If modified NumLinkageSpecDeclBits and the accessor
  1445. /// methods in LinkageSpecDecl should be updated appropriately.
  1446. class LinkageSpecDeclBitfields {
  1447. friend class LinkageSpecDecl;
  1448. /// For the bits in DeclContextBitfields.
  1449. uint64_t : NumDeclContextBits;
  1450. /// The language for this linkage specification with values
  1451. /// in the enum LinkageSpecDecl::LanguageIDs.
  1452. uint64_t Language : 3;
  1453. /// True if this linkage spec has braces.
  1454. /// This is needed so that hasBraces() returns the correct result while the
  1455. /// linkage spec body is being parsed. Once RBraceLoc has been set this is
  1456. /// not used, so it doesn't need to be serialized.
  1457. uint64_t HasBraces : 1;
  1458. };
  1459. /// Number of non-inherited bits in LinkageSpecDeclBitfields.
  1460. enum { NumLinkageSpecDeclBits = 4 };
  1461. /// Stores the bits used by BlockDecl.
  1462. /// If modified NumBlockDeclBits and the accessor
  1463. /// methods in BlockDecl should be updated appropriately.
  1464. class BlockDeclBitfields {
  1465. friend class BlockDecl;
  1466. /// For the bits in DeclContextBitfields.
  1467. uint64_t : NumDeclContextBits;
  1468. uint64_t IsVariadic : 1;
  1469. uint64_t CapturesCXXThis : 1;
  1470. uint64_t BlockMissingReturnType : 1;
  1471. uint64_t IsConversionFromLambda : 1;
  1472. /// A bit that indicates this block is passed directly to a function as a
  1473. /// non-escaping parameter.
  1474. uint64_t DoesNotEscape : 1;
  1475. /// A bit that indicates whether it's possible to avoid coying this block to
  1476. /// the heap when it initializes or is assigned to a local variable with
  1477. /// automatic storage.
  1478. uint64_t CanAvoidCopyToHeap : 1;
  1479. };
  1480. /// Number of non-inherited bits in BlockDeclBitfields.
  1481. enum { NumBlockDeclBits = 5 };
  1482. /// Pointer to the data structure used to lookup declarations
  1483. /// within this context (or a DependentStoredDeclsMap if this is a
  1484. /// dependent context). We maintain the invariant that, if the map
  1485. /// contains an entry for a DeclarationName (and we haven't lazily
  1486. /// omitted anything), then it contains all relevant entries for that
  1487. /// name (modulo the hasExternalDecls() flag).
  1488. mutable StoredDeclsMap *LookupPtr = nullptr;
  1489. protected:
  1490. /// This anonymous union stores the bits belonging to DeclContext and classes
  1491. /// deriving from it. The goal is to use otherwise wasted
  1492. /// space in DeclContext to store data belonging to derived classes.
  1493. /// The space saved is especially significient when pointers are aligned
  1494. /// to 8 bytes. In this case due to alignment requirements we have a
  1495. /// little less than 8 bytes free in DeclContext which we can use.
  1496. /// We check that none of the classes in this union is larger than
  1497. /// 8 bytes with static_asserts in the ctor of DeclContext.
  1498. union {
  1499. DeclContextBitfields DeclContextBits;
  1500. TagDeclBitfields TagDeclBits;
  1501. EnumDeclBitfields EnumDeclBits;
  1502. RecordDeclBitfields RecordDeclBits;
  1503. OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
  1504. FunctionDeclBitfields FunctionDeclBits;
  1505. CXXConstructorDeclBitfields CXXConstructorDeclBits;
  1506. ObjCMethodDeclBitfields ObjCMethodDeclBits;
  1507. ObjCContainerDeclBitfields ObjCContainerDeclBits;
  1508. LinkageSpecDeclBitfields LinkageSpecDeclBits;
  1509. BlockDeclBitfields BlockDeclBits;
  1510. static_assert(sizeof(DeclContextBitfields) <= 8,
  1511. "DeclContextBitfields is larger than 8 bytes!");
  1512. static_assert(sizeof(TagDeclBitfields) <= 8,
  1513. "TagDeclBitfields is larger than 8 bytes!");
  1514. static_assert(sizeof(EnumDeclBitfields) <= 8,
  1515. "EnumDeclBitfields is larger than 8 bytes!");
  1516. static_assert(sizeof(RecordDeclBitfields) <= 8,
  1517. "RecordDeclBitfields is larger than 8 bytes!");
  1518. static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
  1519. "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
  1520. static_assert(sizeof(FunctionDeclBitfields) <= 8,
  1521. "FunctionDeclBitfields is larger than 8 bytes!");
  1522. static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
  1523. "CXXConstructorDeclBitfields is larger than 8 bytes!");
  1524. static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
  1525. "ObjCMethodDeclBitfields is larger than 8 bytes!");
  1526. static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
  1527. "ObjCContainerDeclBitfields is larger than 8 bytes!");
  1528. static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
  1529. "LinkageSpecDeclBitfields is larger than 8 bytes!");
  1530. static_assert(sizeof(BlockDeclBitfields) <= 8,
  1531. "BlockDeclBitfields is larger than 8 bytes!");
  1532. };
  1533. /// FirstDecl - The first declaration stored within this declaration
  1534. /// context.
  1535. mutable Decl *FirstDecl = nullptr;
  1536. /// LastDecl - The last declaration stored within this declaration
  1537. /// context. FIXME: We could probably cache this value somewhere
  1538. /// outside of the DeclContext, to reduce the size of DeclContext by
  1539. /// another pointer.
  1540. mutable Decl *LastDecl = nullptr;
  1541. /// Build up a chain of declarations.
  1542. ///
  1543. /// \returns the first/last pair of declarations.
  1544. static std::pair<Decl *, Decl *>
  1545. BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
  1546. DeclContext(Decl::Kind K);
  1547. public:
  1548. ~DeclContext();
  1549. Decl::Kind getDeclKind() const {
  1550. return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
  1551. }
  1552. const char *getDeclKindName() const;
  1553. /// getParent - Returns the containing DeclContext.
  1554. DeclContext *getParent() {
  1555. return cast<Decl>(this)->getDeclContext();
  1556. }
  1557. const DeclContext *getParent() const {
  1558. return const_cast<DeclContext*>(this)->getParent();
  1559. }
  1560. /// getLexicalParent - Returns the containing lexical DeclContext. May be
  1561. /// different from getParent, e.g.:
  1562. ///
  1563. /// namespace A {
  1564. /// struct S;
  1565. /// }
  1566. /// struct A::S {}; // getParent() == namespace 'A'
  1567. /// // getLexicalParent() == translation unit
  1568. ///
  1569. DeclContext *getLexicalParent() {
  1570. return cast<Decl>(this)->getLexicalDeclContext();
  1571. }
  1572. const DeclContext *getLexicalParent() const {
  1573. return const_cast<DeclContext*>(this)->getLexicalParent();
  1574. }
  1575. DeclContext *getLookupParent();
  1576. const DeclContext *getLookupParent() const {
  1577. return const_cast<DeclContext*>(this)->getLookupParent();
  1578. }
  1579. ASTContext &getParentASTContext() const {
  1580. return cast<Decl>(this)->getASTContext();
  1581. }
  1582. bool isClosure() const { return getDeclKind() == Decl::Block; }
  1583. /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
  1584. /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
  1585. const BlockDecl *getInnermostBlockDecl() const;
  1586. bool isObjCContainer() const {
  1587. switch (getDeclKind()) {
  1588. case Decl::ObjCCategory:
  1589. case Decl::ObjCCategoryImpl:
  1590. case Decl::ObjCImplementation:
  1591. case Decl::ObjCInterface:
  1592. case Decl::ObjCProtocol:
  1593. return true;
  1594. default:
  1595. return false;
  1596. }
  1597. }
  1598. bool isFunctionOrMethod() const {
  1599. switch (getDeclKind()) {
  1600. case Decl::Block:
  1601. case Decl::Captured:
  1602. case Decl::ObjCMethod:
  1603. return true;
  1604. default:
  1605. return getDeclKind() >= Decl::firstFunction &&
  1606. getDeclKind() <= Decl::lastFunction;
  1607. }
  1608. }
  1609. /// Test whether the context supports looking up names.
  1610. bool isLookupContext() const {
  1611. return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
  1612. getDeclKind() != Decl::Export;
  1613. }
  1614. bool isFileContext() const {
  1615. return getDeclKind() == Decl::TranslationUnit ||
  1616. getDeclKind() == Decl::Namespace;
  1617. }
  1618. bool isTranslationUnit() const {
  1619. return getDeclKind() == Decl::TranslationUnit;
  1620. }
  1621. bool isRecord() const {
  1622. return getDeclKind() >= Decl::firstRecord &&
  1623. getDeclKind() <= Decl::lastRecord;
  1624. }
  1625. bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
  1626. bool isStdNamespace() const;
  1627. bool isInlineNamespace() const;
  1628. /// Determines whether this context is dependent on a
  1629. /// template parameter.
  1630. bool isDependentContext() const;
  1631. /// isTransparentContext - Determines whether this context is a
  1632. /// "transparent" context, meaning that the members declared in this
  1633. /// context are semantically declared in the nearest enclosing
  1634. /// non-transparent (opaque) context but are lexically declared in
  1635. /// this context. For example, consider the enumerators of an
  1636. /// enumeration type:
  1637. /// @code
  1638. /// enum E {
  1639. /// Val1
  1640. /// };
  1641. /// @endcode
  1642. /// Here, E is a transparent context, so its enumerator (Val1) will
  1643. /// appear (semantically) that it is in the same context of E.
  1644. /// Examples of transparent contexts include: enumerations (except for
  1645. /// C++0x scoped enums), and C++ linkage specifications.
  1646. bool isTransparentContext() const;
  1647. /// Determines whether this context or some of its ancestors is a
  1648. /// linkage specification context that specifies C linkage.
  1649. bool isExternCContext() const;
  1650. /// Retrieve the nearest enclosing C linkage specification context.
  1651. const LinkageSpecDecl *getExternCContext() const;
  1652. /// Determines whether this context or some of its ancestors is a
  1653. /// linkage specification context that specifies C++ linkage.
  1654. bool isExternCXXContext() const;
  1655. /// Determine whether this declaration context is equivalent
  1656. /// to the declaration context DC.
  1657. bool Equals(const DeclContext *DC) const {
  1658. return DC && this->getPrimaryContext() == DC->getPrimaryContext();
  1659. }
  1660. /// Determine whether this declaration context encloses the
  1661. /// declaration context DC.
  1662. bool Encloses(const DeclContext *DC) const;
  1663. /// Find the nearest non-closure ancestor of this context,
  1664. /// i.e. the innermost semantic parent of this context which is not
  1665. /// a closure. A context may be its own non-closure ancestor.
  1666. Decl *getNonClosureAncestor();
  1667. const Decl *getNonClosureAncestor() const {
  1668. return const_cast<DeclContext*>(this)->getNonClosureAncestor();
  1669. }
  1670. // Retrieve the nearest context that is not a transparent context.
  1671. DeclContext *getNonTransparentContext();
  1672. const DeclContext *getNonTransparentContext() const {
  1673. return const_cast<DeclContext *>(this)->getNonTransparentContext();
  1674. }
  1675. /// getPrimaryContext - There may be many different
  1676. /// declarations of the same entity (including forward declarations
  1677. /// of classes, multiple definitions of namespaces, etc.), each with
  1678. /// a different set of declarations. This routine returns the
  1679. /// "primary" DeclContext structure, which will contain the
  1680. /// information needed to perform name lookup into this context.
  1681. DeclContext *getPrimaryContext();
  1682. const DeclContext *getPrimaryContext() const {
  1683. return const_cast<DeclContext*>(this)->getPrimaryContext();
  1684. }
  1685. /// getRedeclContext - Retrieve the context in which an entity conflicts with
  1686. /// other entities of the same name, or where it is a redeclaration if the
  1687. /// two entities are compatible. This skips through transparent contexts.
  1688. DeclContext *getRedeclContext();
  1689. const DeclContext *getRedeclContext() const {
  1690. return const_cast<DeclContext *>(this)->getRedeclContext();
  1691. }
  1692. /// Retrieve the nearest enclosing namespace context.
  1693. DeclContext *getEnclosingNamespaceContext();
  1694. const DeclContext *getEnclosingNamespaceContext() const {
  1695. return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
  1696. }
  1697. /// Retrieve the outermost lexically enclosing record context.
  1698. RecordDecl *getOuterLexicalRecordContext();
  1699. const RecordDecl *getOuterLexicalRecordContext() const {
  1700. return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
  1701. }
  1702. /// Test if this context is part of the enclosing namespace set of
  1703. /// the context NS, as defined in C++0x [namespace.def]p9. If either context
  1704. /// isn't a namespace, this is equivalent to Equals().
  1705. ///
  1706. /// The enclosing namespace set of a namespace is the namespace and, if it is
  1707. /// inline, its enclosing namespace, recursively.
  1708. bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
  1709. /// Collects all of the declaration contexts that are semantically
  1710. /// connected to this declaration context.
  1711. ///
  1712. /// For declaration contexts that have multiple semantically connected but
  1713. /// syntactically distinct contexts, such as C++ namespaces, this routine
  1714. /// retrieves the complete set of such declaration contexts in source order.
  1715. /// For example, given:
  1716. ///
  1717. /// \code
  1718. /// namespace N {
  1719. /// int x;
  1720. /// }
  1721. /// namespace N {
  1722. /// int y;
  1723. /// }
  1724. /// \endcode
  1725. ///
  1726. /// The \c Contexts parameter will contain both definitions of N.
  1727. ///
  1728. /// \param Contexts Will be cleared and set to the set of declaration
  1729. /// contexts that are semanticaly connected to this declaration context,
  1730. /// in source order, including this context (which may be the only result,
  1731. /// for non-namespace contexts).
  1732. void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
  1733. /// decl_iterator - Iterates through the declarations stored
  1734. /// within this context.
  1735. class decl_iterator {
  1736. /// Current - The current declaration.
  1737. Decl *Current = nullptr;
  1738. public:
  1739. using value_type = Decl *;
  1740. using reference = const value_type &;
  1741. using pointer = const value_type *;
  1742. using iterator_category = std::forward_iterator_tag;
  1743. using difference_type = std::ptrdiff_t;
  1744. decl_iterator() = default;
  1745. explicit decl_iterator(Decl *C) : Current(C) {}
  1746. reference operator*() const { return Current; }
  1747. // This doesn't meet the iterator requirements, but it's convenient
  1748. value_type operator->() const { return Current; }
  1749. decl_iterator& operator++() {
  1750. Current = Current->getNextDeclInContext();
  1751. return *this;
  1752. }
  1753. decl_iterator operator++(int) {
  1754. decl_iterator tmp(*this);
  1755. ++(*this);
  1756. return tmp;
  1757. }
  1758. friend bool operator==(decl_iterator x, decl_iterator y) {
  1759. return x.Current == y.Current;
  1760. }
  1761. friend bool operator!=(decl_iterator x, decl_iterator y) {
  1762. return x.Current != y.Current;
  1763. }
  1764. };
  1765. using decl_range = llvm::iterator_range<decl_iterator>;
  1766. /// decls_begin/decls_end - Iterate over the declarations stored in
  1767. /// this context.
  1768. decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
  1769. decl_iterator decls_begin() const;
  1770. decl_iterator decls_end() const { return decl_iterator(); }
  1771. bool decls_empty() const;
  1772. /// noload_decls_begin/end - Iterate over the declarations stored in this
  1773. /// context that are currently loaded; don't attempt to retrieve anything
  1774. /// from an external source.
  1775. decl_range noload_decls() const {
  1776. return decl_range(noload_decls_begin(), noload_decls_end());
  1777. }
  1778. decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
  1779. decl_iterator noload_decls_end() const { return decl_iterator(); }
  1780. /// specific_decl_iterator - Iterates over a subrange of
  1781. /// declarations stored in a DeclContext, providing only those that
  1782. /// are of type SpecificDecl (or a class derived from it). This
  1783. /// iterator is used, for example, to provide iteration over just
  1784. /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
  1785. template<typename SpecificDecl>
  1786. class specific_decl_iterator {
  1787. /// Current - The current, underlying declaration iterator, which
  1788. /// will either be NULL or will point to a declaration of
  1789. /// type SpecificDecl.
  1790. DeclContext::decl_iterator Current;
  1791. /// SkipToNextDecl - Advances the current position up to the next
  1792. /// declaration of type SpecificDecl that also meets the criteria
  1793. /// required by Acceptable.
  1794. void SkipToNextDecl() {
  1795. while (*Current && !isa<SpecificDecl>(*Current))
  1796. ++Current;
  1797. }
  1798. public:
  1799. using value_type = SpecificDecl *;
  1800. // TODO: Add reference and pointer types (with some appropriate proxy type)
  1801. // if we ever have a need for them.
  1802. using reference = void;
  1803. using pointer = void;
  1804. using difference_type =
  1805. std::iterator_traits<DeclContext::decl_iterator>::difference_type;
  1806. using iterator_category = std::forward_iterator_tag;
  1807. specific_decl_iterator() = default;
  1808. /// specific_decl_iterator - Construct a new iterator over a
  1809. /// subset of the declarations the range [C,
  1810. /// end-of-declarations). If A is non-NULL, it is a pointer to a
  1811. /// member function of SpecificDecl that should return true for
  1812. /// all of the SpecificDecl instances that will be in the subset
  1813. /// of iterators. For example, if you want Objective-C instance
  1814. /// methods, SpecificDecl will be ObjCMethodDecl and A will be
  1815. /// &ObjCMethodDecl::isInstanceMethod.
  1816. explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
  1817. SkipToNextDecl();
  1818. }
  1819. value_type operator*() const { return cast<SpecificDecl>(*Current); }
  1820. // This doesn't meet the iterator requirements, but it's convenient
  1821. value_type operator->() const { return **this; }
  1822. specific_decl_iterator& operator++() {
  1823. ++Current;
  1824. SkipToNextDecl();
  1825. return *this;
  1826. }
  1827. specific_decl_iterator operator++(int) {
  1828. specific_decl_iterator tmp(*this);
  1829. ++(*this);
  1830. return tmp;
  1831. }
  1832. friend bool operator==(const specific_decl_iterator& x,
  1833. const specific_decl_iterator& y) {
  1834. return x.Current == y.Current;
  1835. }
  1836. friend bool operator!=(const specific_decl_iterator& x,
  1837. const specific_decl_iterator& y) {
  1838. return x.Current != y.Current;
  1839. }
  1840. };
  1841. /// Iterates over a filtered subrange of declarations stored
  1842. /// in a DeclContext.
  1843. ///
  1844. /// This iterator visits only those declarations that are of type
  1845. /// SpecificDecl (or a class derived from it) and that meet some
  1846. /// additional run-time criteria. This iterator is used, for
  1847. /// example, to provide access to the instance methods within an
  1848. /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
  1849. /// Acceptable = ObjCMethodDecl::isInstanceMethod).
  1850. template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
  1851. class filtered_decl_iterator {
  1852. /// Current - The current, underlying declaration iterator, which
  1853. /// will either be NULL or will point to a declaration of
  1854. /// type SpecificDecl.
  1855. DeclContext::decl_iterator Current;
  1856. /// SkipToNextDecl - Advances the current position up to the next
  1857. /// declaration of type SpecificDecl that also meets the criteria
  1858. /// required by Acceptable.
  1859. void SkipToNextDecl() {
  1860. while (*Current &&
  1861. (!isa<SpecificDecl>(*Current) ||
  1862. (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
  1863. ++Current;
  1864. }
  1865. public:
  1866. using value_type = SpecificDecl *;
  1867. // TODO: Add reference and pointer types (with some appropriate proxy type)
  1868. // if we ever have a need for them.
  1869. using reference = void;
  1870. using pointer = void;
  1871. using difference_type =
  1872. std::iterator_traits<DeclContext::decl_iterator>::difference_type;
  1873. using iterator_category = std::forward_iterator_tag;
  1874. filtered_decl_iterator() = default;
  1875. /// filtered_decl_iterator - Construct a new iterator over a
  1876. /// subset of the declarations the range [C,
  1877. /// end-of-declarations). If A is non-NULL, it is a pointer to a
  1878. /// member function of SpecificDecl that should return true for
  1879. /// all of the SpecificDecl instances that will be in the subset
  1880. /// of iterators. For example, if you want Objective-C instance
  1881. /// methods, SpecificDecl will be ObjCMethodDecl and A will be
  1882. /// &ObjCMethodDecl::isInstanceMethod.
  1883. explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
  1884. SkipToNextDecl();
  1885. }
  1886. value_type operator*() const { return cast<SpecificDecl>(*Current); }
  1887. value_type operator->() const { return cast<SpecificDecl>(*Current); }
  1888. filtered_decl_iterator& operator++() {
  1889. ++Current;
  1890. SkipToNextDecl();
  1891. return *this;
  1892. }
  1893. filtered_decl_iterator operator++(int) {
  1894. filtered_decl_iterator tmp(*this);
  1895. ++(*this);
  1896. return tmp;
  1897. }
  1898. friend bool operator==(const filtered_decl_iterator& x,
  1899. const filtered_decl_iterator& y) {
  1900. return x.Current == y.Current;
  1901. }
  1902. friend bool operator!=(const filtered_decl_iterator& x,
  1903. const filtered_decl_iterator& y) {
  1904. return x.Current != y.Current;
  1905. }
  1906. };
  1907. /// Add the declaration D into this context.
  1908. ///
  1909. /// This routine should be invoked when the declaration D has first
  1910. /// been declared, to place D into the context where it was
  1911. /// (lexically) defined. Every declaration must be added to one
  1912. /// (and only one!) context, where it can be visited via
  1913. /// [decls_begin(), decls_end()). Once a declaration has been added
  1914. /// to its lexical context, the corresponding DeclContext owns the
  1915. /// declaration.
  1916. ///
  1917. /// If D is also a NamedDecl, it will be made visible within its
  1918. /// semantic context via makeDeclVisibleInContext.
  1919. void addDecl(Decl *D);
  1920. /// Add the declaration D into this context, but suppress
  1921. /// searches for external declarations with the same name.
  1922. ///
  1923. /// Although analogous in function to addDecl, this removes an
  1924. /// important check. This is only useful if the Decl is being
  1925. /// added in response to an external search; in all other cases,
  1926. /// addDecl() is the right function to use.
  1927. /// See the ASTImporter for use cases.
  1928. void addDeclInternal(Decl *D);
  1929. /// Add the declaration D to this context without modifying
  1930. /// any lookup tables.
  1931. ///
  1932. /// This is useful for some operations in dependent contexts where
  1933. /// the semantic context might not be dependent; this basically
  1934. /// only happens with friends.
  1935. void addHiddenDecl(Decl *D);
  1936. /// Removes a declaration from this context.
  1937. void removeDecl(Decl *D);
  1938. /// Checks whether a declaration is in this context.
  1939. bool containsDecl(Decl *D) const;
  1940. /// Checks whether a declaration is in this context.
  1941. /// This also loads the Decls from the external source before the check.
  1942. bool containsDeclAndLoad(Decl *D) const;
  1943. using lookup_result = DeclContextLookupResult;
  1944. using lookup_iterator = lookup_result::iterator;
  1945. /// lookup - Find the declarations (if any) with the given Name in
  1946. /// this context. Returns a range of iterators that contains all of
  1947. /// the declarations with this name, with object, function, member,
  1948. /// and enumerator names preceding any tag name. Note that this
  1949. /// routine will not look into parent contexts.
  1950. lookup_result lookup(DeclarationName Name) const;
  1951. /// Find the declarations with the given name that are visible
  1952. /// within this context; don't attempt to retrieve anything from an
  1953. /// external source.
  1954. lookup_result noload_lookup(DeclarationName Name);
  1955. /// A simplistic name lookup mechanism that performs name lookup
  1956. /// into this declaration context without consulting the external source.
  1957. ///
  1958. /// This function should almost never be used, because it subverts the
  1959. /// usual relationship between a DeclContext and the external source.
  1960. /// See the ASTImporter for the (few, but important) use cases.
  1961. ///
  1962. /// FIXME: This is very inefficient; replace uses of it with uses of
  1963. /// noload_lookup.
  1964. void localUncachedLookup(DeclarationName Name,
  1965. SmallVectorImpl<NamedDecl *> &Results);
  1966. /// Makes a declaration visible within this context.
  1967. ///
  1968. /// This routine makes the declaration D visible to name lookup
  1969. /// within this context and, if this is a transparent context,
  1970. /// within its parent contexts up to the first enclosing
  1971. /// non-transparent context. Making a declaration visible within a
  1972. /// context does not transfer ownership of a declaration, and a
  1973. /// declaration can be visible in many contexts that aren't its
  1974. /// lexical context.
  1975. ///
  1976. /// If D is a redeclaration of an existing declaration that is
  1977. /// visible from this context, as determined by
  1978. /// NamedDecl::declarationReplaces, the previous declaration will be
  1979. /// replaced with D.
  1980. void makeDeclVisibleInContext(NamedDecl *D);
  1981. /// all_lookups_iterator - An iterator that provides a view over the results
  1982. /// of looking up every possible name.
  1983. class all_lookups_iterator;
  1984. using lookups_range = llvm::iterator_range<all_lookups_iterator>;
  1985. lookups_range lookups() const;
  1986. // Like lookups(), but avoids loading external declarations.
  1987. // If PreserveInternalState, avoids building lookup data structures too.
  1988. lookups_range noload_lookups(bool PreserveInternalState) const;
  1989. /// Iterators over all possible lookups within this context.
  1990. all_lookups_iterator lookups_begin() const;
  1991. all_lookups_iterator lookups_end() const;
  1992. /// Iterators over all possible lookups within this context that are
  1993. /// currently loaded; don't attempt to retrieve anything from an external
  1994. /// source.
  1995. all_lookups_iterator noload_lookups_begin() const;
  1996. all_lookups_iterator noload_lookups_end() const;
  1997. struct udir_iterator;
  1998. using udir_iterator_base =
  1999. llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
  2000. typename lookup_iterator::iterator_category,
  2001. UsingDirectiveDecl *>;
  2002. struct udir_iterator : udir_iterator_base {
  2003. udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
  2004. UsingDirectiveDecl *operator*() const;
  2005. };
  2006. using udir_range = llvm::iterator_range<udir_iterator>;
  2007. udir_range using_directives() const;
  2008. // These are all defined in DependentDiagnostic.h.
  2009. class ddiag_iterator;
  2010. using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
  2011. inline ddiag_range ddiags() const;
  2012. // Low-level accessors
  2013. /// Mark that there are external lexical declarations that we need
  2014. /// to include in our lookup table (and that are not available as external
  2015. /// visible lookups). These extra lookup results will be found by walking
  2016. /// the lexical declarations of this context. This should be used only if
  2017. /// setHasExternalLexicalStorage() has been called on any decl context for
  2018. /// which this is the primary context.
  2019. void setMustBuildLookupTable() {
  2020. assert(this == getPrimaryContext() &&
  2021. "should only be called on primary context");
  2022. DeclContextBits.HasLazyExternalLexicalLookups = true;
  2023. }
  2024. /// Retrieve the internal representation of the lookup structure.
  2025. /// This may omit some names if we are lazily building the structure.
  2026. StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
  2027. /// Ensure the lookup structure is fully-built and return it.
  2028. StoredDeclsMap *buildLookup();
  2029. /// Whether this DeclContext has external storage containing
  2030. /// additional declarations that are lexically in this context.
  2031. bool hasExternalLexicalStorage() const {
  2032. return DeclContextBits.ExternalLexicalStorage;
  2033. }
  2034. /// State whether this DeclContext has external storage for
  2035. /// declarations lexically in this context.
  2036. void setHasExternalLexicalStorage(bool ES = true) const {
  2037. DeclContextBits.ExternalLexicalStorage = ES;
  2038. }
  2039. /// Whether this DeclContext has external storage containing
  2040. /// additional declarations that are visible in this context.
  2041. bool hasExternalVisibleStorage() const {
  2042. return DeclContextBits.ExternalVisibleStorage;
  2043. }
  2044. /// State whether this DeclContext has external storage for
  2045. /// declarations visible in this context.
  2046. void setHasExternalVisibleStorage(bool ES = true) const {
  2047. DeclContextBits.ExternalVisibleStorage = ES;
  2048. if (ES && LookupPtr)
  2049. DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
  2050. }
  2051. /// Determine whether the given declaration is stored in the list of
  2052. /// declarations lexically within this context.
  2053. bool isDeclInLexicalTraversal(const Decl *D) const {
  2054. return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
  2055. D == LastDecl);
  2056. }
  2057. bool setUseQualifiedLookup(bool use = true) const {
  2058. bool old_value = DeclContextBits.UseQualifiedLookup;
  2059. DeclContextBits.UseQualifiedLookup = use;
  2060. return old_value;
  2061. }
  2062. bool shouldUseQualifiedLookup() const {
  2063. return DeclContextBits.UseQualifiedLookup;
  2064. }
  2065. static bool classof(const Decl *D);
  2066. static bool classof(const DeclContext *D) { return true; }
  2067. void dumpDeclContext() const;
  2068. void dumpLookups() const;
  2069. void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
  2070. bool Deserialize = false) const;
  2071. private:
  2072. /// Whether this declaration context has had externally visible
  2073. /// storage added since the last lookup. In this case, \c LookupPtr's
  2074. /// invariant may not hold and needs to be fixed before we perform
  2075. /// another lookup.
  2076. bool hasNeedToReconcileExternalVisibleStorage() const {
  2077. return DeclContextBits.NeedToReconcileExternalVisibleStorage;
  2078. }
  2079. /// State that this declaration context has had externally visible
  2080. /// storage added since the last lookup. In this case, \c LookupPtr's
  2081. /// invariant may not hold and needs to be fixed before we perform
  2082. /// another lookup.
  2083. void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
  2084. DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
  2085. }
  2086. /// If \c true, this context may have local lexical declarations
  2087. /// that are missing from the lookup table.
  2088. bool hasLazyLocalLexicalLookups() const {
  2089. return DeclContextBits.HasLazyLocalLexicalLookups;
  2090. }
  2091. /// If \c true, this context may have local lexical declarations
  2092. /// that are missing from the lookup table.
  2093. void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
  2094. DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
  2095. }
  2096. /// If \c true, the external source may have lexical declarations
  2097. /// that are missing from the lookup table.
  2098. bool hasLazyExternalLexicalLookups() const {
  2099. return DeclContextBits.HasLazyExternalLexicalLookups;
  2100. }
  2101. /// If \c true, the external source may have lexical declarations
  2102. /// that are missing from the lookup table.
  2103. void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
  2104. DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
  2105. }
  2106. void reconcileExternalVisibleStorage() const;
  2107. bool LoadLexicalDeclsFromExternalStorage() const;
  2108. /// Makes a declaration visible within this context, but
  2109. /// suppresses searches for external declarations with the same
  2110. /// name.
  2111. ///
  2112. /// Analogous to makeDeclVisibleInContext, but for the exclusive
  2113. /// use of addDeclInternal().
  2114. void makeDeclVisibleInContextInternal(NamedDecl *D);
  2115. StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
  2116. void loadLazyLocalLexicalLookups();
  2117. void buildLookupImpl(DeclContext *DCtx, bool Internal);
  2118. void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
  2119. bool Rediscoverable);
  2120. void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
  2121. };
  2122. inline bool Decl::isTemplateParameter() const {
  2123. return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
  2124. getKind() == TemplateTemplateParm;
  2125. }
  2126. // Specialization selected when ToTy is not a known subclass of DeclContext.
  2127. template <class ToTy,
  2128. bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
  2129. struct cast_convert_decl_context {
  2130. static const ToTy *doit(const DeclContext *Val) {
  2131. return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
  2132. }
  2133. static ToTy *doit(DeclContext *Val) {
  2134. return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
  2135. }
  2136. };
  2137. // Specialization selected when ToTy is a known subclass of DeclContext.
  2138. template <class ToTy>
  2139. struct cast_convert_decl_context<ToTy, true> {
  2140. static const ToTy *doit(const DeclContext *Val) {
  2141. return static_cast<const ToTy*>(Val);
  2142. }
  2143. static ToTy *doit(DeclContext *Val) {
  2144. return static_cast<ToTy*>(Val);
  2145. }
  2146. };
  2147. } // namespace clang
  2148. namespace llvm {
  2149. /// isa<T>(DeclContext*)
  2150. template <typename To>
  2151. struct isa_impl<To, ::clang::DeclContext> {
  2152. static bool doit(const ::clang::DeclContext &Val) {
  2153. return To::classofKind(Val.getDeclKind());
  2154. }
  2155. };
  2156. /// cast<T>(DeclContext*)
  2157. template<class ToTy>
  2158. struct cast_convert_val<ToTy,
  2159. const ::clang::DeclContext,const ::clang::DeclContext> {
  2160. static const ToTy &doit(const ::clang::DeclContext &Val) {
  2161. return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
  2162. }
  2163. };
  2164. template<class ToTy>
  2165. struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
  2166. static ToTy &doit(::clang::DeclContext &Val) {
  2167. return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
  2168. }
  2169. };
  2170. template<class ToTy>
  2171. struct cast_convert_val<ToTy,
  2172. const ::clang::DeclContext*, const ::clang::DeclContext*> {
  2173. static const ToTy *doit(const ::clang::DeclContext *Val) {
  2174. return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
  2175. }
  2176. };
  2177. template<class ToTy>
  2178. struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
  2179. static ToTy *doit(::clang::DeclContext *Val) {
  2180. return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
  2181. }
  2182. };
  2183. /// Implement cast_convert_val for Decl -> DeclContext conversions.
  2184. template<class FromTy>
  2185. struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
  2186. static ::clang::DeclContext &doit(const FromTy &Val) {
  2187. return *FromTy::castToDeclContext(&Val);
  2188. }
  2189. };
  2190. template<class FromTy>
  2191. struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
  2192. static ::clang::DeclContext *doit(const FromTy *Val) {
  2193. return FromTy::castToDeclContext(Val);
  2194. }
  2195. };
  2196. template<class FromTy>
  2197. struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
  2198. static const ::clang::DeclContext &doit(const FromTy &Val) {
  2199. return *FromTy::castToDeclContext(&Val);
  2200. }
  2201. };
  2202. template<class FromTy>
  2203. struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
  2204. static const ::clang::DeclContext *doit(const FromTy *Val) {
  2205. return FromTy::castToDeclContext(Val);
  2206. }
  2207. };
  2208. } // namespace llvm
  2209. #endif // LLVM_CLANG_AST_DECLBASE_H
  2210. #ifdef __GNUC__
  2211. #pragma GCC diagnostic pop
  2212. #endif