ASTContext.h 136 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ASTContext.h - Context to hold long-lived AST nodes ------*- 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. /// \file
  15. /// Defines the clang::ASTContext interface.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #ifndef LLVM_CLANG_AST_ASTCONTEXT_H
  19. #define LLVM_CLANG_AST_ASTCONTEXT_H
  20. #include "clang/AST/ASTFwd.h"
  21. #include "clang/AST/CanonicalType.h"
  22. #include "clang/AST/CommentCommandTraits.h"
  23. #include "clang/AST/ComparisonCategories.h"
  24. #include "clang/AST/Decl.h"
  25. #include "clang/AST/DeclarationName.h"
  26. #include "clang/AST/ExternalASTSource.h"
  27. #include "clang/AST/NestedNameSpecifier.h"
  28. #include "clang/AST/PrettyPrinter.h"
  29. #include "clang/AST/RawCommentList.h"
  30. #include "clang/AST/TemplateName.h"
  31. #include "clang/Basic/IdentifierTable.h"
  32. #include "clang/Basic/LLVM.h"
  33. #include "clang/Basic/LangOptions.h"
  34. #include "clang/Basic/NoSanitizeList.h"
  35. #include "clang/Basic/PartialDiagnostic.h"
  36. #include "clang/Basic/ProfileList.h"
  37. #include "clang/Basic/SourceLocation.h"
  38. #include "clang/Basic/XRayLists.h"
  39. #include "llvm/ADT/DenseMap.h"
  40. #include "llvm/ADT/DenseSet.h"
  41. #include "llvm/ADT/FoldingSet.h"
  42. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  43. #include "llvm/ADT/MapVector.h"
  44. #include "llvm/ADT/PointerIntPair.h"
  45. #include "llvm/ADT/PointerUnion.h"
  46. #include "llvm/ADT/SmallVector.h"
  47. #include "llvm/ADT/StringMap.h"
  48. #include "llvm/ADT/StringRef.h"
  49. #include "llvm/ADT/TinyPtrVector.h"
  50. #include "llvm/Support/TypeSize.h"
  51. #include <optional>
  52. namespace llvm {
  53. class APFixedPoint;
  54. class FixedPointSemantics;
  55. struct fltSemantics;
  56. template <typename T, unsigned N> class SmallPtrSet;
  57. } // namespace llvm
  58. namespace clang {
  59. class APValue;
  60. class ASTMutationListener;
  61. class ASTRecordLayout;
  62. class AtomicExpr;
  63. class BlockExpr;
  64. class BuiltinTemplateDecl;
  65. class CharUnits;
  66. class ConceptDecl;
  67. class CXXABI;
  68. class CXXConstructorDecl;
  69. class CXXMethodDecl;
  70. class CXXRecordDecl;
  71. class DiagnosticsEngine;
  72. class ParentMapContext;
  73. class DynTypedNodeList;
  74. class Expr;
  75. enum class FloatModeKind;
  76. class GlobalDecl;
  77. class MangleContext;
  78. class MangleNumberingContext;
  79. class MemberSpecializationInfo;
  80. class Module;
  81. struct MSGuidDeclParts;
  82. class ObjCCategoryDecl;
  83. class ObjCCategoryImplDecl;
  84. class ObjCContainerDecl;
  85. class ObjCImplDecl;
  86. class ObjCImplementationDecl;
  87. class ObjCInterfaceDecl;
  88. class ObjCIvarDecl;
  89. class ObjCMethodDecl;
  90. class ObjCPropertyDecl;
  91. class ObjCPropertyImplDecl;
  92. class ObjCProtocolDecl;
  93. class ObjCTypeParamDecl;
  94. class OMPTraitInfo;
  95. struct ParsedTargetAttr;
  96. class Preprocessor;
  97. class StoredDeclsMap;
  98. class TargetAttr;
  99. class TargetInfo;
  100. class TemplateDecl;
  101. class TemplateParameterList;
  102. class TemplateTemplateParmDecl;
  103. class TemplateTypeParmDecl;
  104. class TypeConstraint;
  105. class UnresolvedSetIterator;
  106. class UsingShadowDecl;
  107. class VarTemplateDecl;
  108. class VTableContextBase;
  109. struct BlockVarCopyInit;
  110. namespace Builtin {
  111. class Context;
  112. } // namespace Builtin
  113. enum BuiltinTemplateKind : int;
  114. enum OpenCLTypeKind : uint8_t;
  115. namespace comments {
  116. class FullComment;
  117. } // namespace comments
  118. namespace interp {
  119. class Context;
  120. } // namespace interp
  121. namespace serialization {
  122. template <class> class AbstractTypeReader;
  123. } // namespace serialization
  124. enum class AlignRequirementKind {
  125. /// The alignment was not explicit in code.
  126. None,
  127. /// The alignment comes from an alignment attribute on a typedef.
  128. RequiredByTypedef,
  129. /// The alignment comes from an alignment attribute on a record type.
  130. RequiredByRecord,
  131. /// The alignment comes from an alignment attribute on a enum type.
  132. RequiredByEnum,
  133. };
  134. struct TypeInfo {
  135. uint64_t Width = 0;
  136. unsigned Align = 0;
  137. AlignRequirementKind AlignRequirement;
  138. TypeInfo() : AlignRequirement(AlignRequirementKind::None) {}
  139. TypeInfo(uint64_t Width, unsigned Align,
  140. AlignRequirementKind AlignRequirement)
  141. : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
  142. bool isAlignRequired() {
  143. return AlignRequirement != AlignRequirementKind::None;
  144. }
  145. };
  146. struct TypeInfoChars {
  147. CharUnits Width;
  148. CharUnits Align;
  149. AlignRequirementKind AlignRequirement;
  150. TypeInfoChars() : AlignRequirement(AlignRequirementKind::None) {}
  151. TypeInfoChars(CharUnits Width, CharUnits Align,
  152. AlignRequirementKind AlignRequirement)
  153. : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
  154. bool isAlignRequired() {
  155. return AlignRequirement != AlignRequirementKind::None;
  156. }
  157. };
  158. /// Holds long-lived AST nodes (such as types and decls) that can be
  159. /// referred to throughout the semantic analysis of a file.
  160. class ASTContext : public RefCountedBase<ASTContext> {
  161. friend class NestedNameSpecifier;
  162. mutable SmallVector<Type *, 0> Types;
  163. mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
  164. mutable llvm::FoldingSet<ComplexType> ComplexTypes;
  165. mutable llvm::FoldingSet<PointerType> PointerTypes{GeneralTypesLog2InitSize};
  166. mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
  167. mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
  168. mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
  169. mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
  170. mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
  171. mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
  172. ConstantArrayTypes;
  173. mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
  174. mutable std::vector<VariableArrayType*> VariableArrayTypes;
  175. mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
  176. mutable llvm::FoldingSet<DependentSizedExtVectorType>
  177. DependentSizedExtVectorTypes;
  178. mutable llvm::FoldingSet<DependentAddressSpaceType>
  179. DependentAddressSpaceTypes;
  180. mutable llvm::FoldingSet<VectorType> VectorTypes;
  181. mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
  182. mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes;
  183. mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes;
  184. mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
  185. mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
  186. FunctionProtoTypes;
  187. mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
  188. mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
  189. mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
  190. mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
  191. mutable llvm::FoldingSet<SubstTemplateTypeParmType>
  192. SubstTemplateTypeParmTypes;
  193. mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
  194. SubstTemplateTypeParmPackTypes;
  195. mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
  196. TemplateSpecializationTypes;
  197. mutable llvm::FoldingSet<ParenType> ParenTypes{GeneralTypesLog2InitSize};
  198. mutable llvm::FoldingSet<UsingType> UsingTypes;
  199. mutable llvm::FoldingSet<TypedefType> TypedefTypes;
  200. mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes{
  201. GeneralTypesLog2InitSize};
  202. mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
  203. mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
  204. ASTContext&>
  205. DependentTemplateSpecializationTypes;
  206. llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
  207. mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
  208. mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
  209. mutable llvm::FoldingSet<DependentUnaryTransformType>
  210. DependentUnaryTransformTypes;
  211. mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes;
  212. mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
  213. DeducedTemplateSpecializationTypes;
  214. mutable llvm::FoldingSet<AtomicType> AtomicTypes;
  215. mutable llvm::FoldingSet<AttributedType> AttributedTypes;
  216. mutable llvm::FoldingSet<PipeType> PipeTypes;
  217. mutable llvm::FoldingSet<BitIntType> BitIntTypes;
  218. mutable llvm::FoldingSet<DependentBitIntType> DependentBitIntTypes;
  219. llvm::FoldingSet<BTFTagAttributedType> BTFTagAttributedTypes;
  220. mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
  221. mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
  222. mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
  223. SubstTemplateTemplateParms;
  224. mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
  225. ASTContext&>
  226. SubstTemplateTemplateParmPacks;
  227. /// The set of nested name specifiers.
  228. ///
  229. /// This set is managed by the NestedNameSpecifier class.
  230. mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
  231. mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
  232. /// A cache mapping from RecordDecls to ASTRecordLayouts.
  233. ///
  234. /// This is lazily created. This is intentionally not serialized.
  235. mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
  236. ASTRecordLayouts;
  237. mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
  238. ObjCLayouts;
  239. /// A cache from types to size and alignment information.
  240. using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
  241. mutable TypeInfoMap MemoizedTypeInfo;
  242. /// A cache from types to unadjusted alignment information. Only ARM and
  243. /// AArch64 targets need this information, keeping it separate prevents
  244. /// imposing overhead on TypeInfo size.
  245. using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
  246. mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
  247. /// A cache mapping from CXXRecordDecls to key functions.
  248. llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
  249. /// Mapping from ObjCContainers to their ObjCImplementations.
  250. llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
  251. /// Mapping from ObjCMethod to its duplicate declaration in the same
  252. /// interface.
  253. llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
  254. /// Mapping from __block VarDecls to BlockVarCopyInit.
  255. llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
  256. /// Mapping from GUIDs to the corresponding MSGuidDecl.
  257. mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;
  258. /// Mapping from APValues to the corresponding UnnamedGlobalConstantDecl.
  259. mutable llvm::FoldingSet<UnnamedGlobalConstantDecl>
  260. UnnamedGlobalConstantDecls;
  261. /// Mapping from APValues to the corresponding TemplateParamObjects.
  262. mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls;
  263. /// A cache mapping a string value to a StringLiteral object with the same
  264. /// value.
  265. ///
  266. /// This is lazily created. This is intentionally not serialized.
  267. mutable llvm::StringMap<StringLiteral *> StringLiteralCache;
  268. /// MD5 hash of CUID. It is calculated when first used and cached by this
  269. /// data member.
  270. mutable std::string CUIDHash;
  271. /// Representation of a "canonical" template template parameter that
  272. /// is used in canonical template names.
  273. class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
  274. TemplateTemplateParmDecl *Parm;
  275. public:
  276. CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
  277. : Parm(Parm) {}
  278. TemplateTemplateParmDecl *getParam() const { return Parm; }
  279. void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) {
  280. Profile(ID, C, Parm);
  281. }
  282. static void Profile(llvm::FoldingSetNodeID &ID,
  283. const ASTContext &C,
  284. TemplateTemplateParmDecl *Parm);
  285. };
  286. mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
  287. const ASTContext&>
  288. CanonTemplateTemplateParms;
  289. TemplateTemplateParmDecl *
  290. getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
  291. /// The typedef for the __int128_t type.
  292. mutable TypedefDecl *Int128Decl = nullptr;
  293. /// The typedef for the __uint128_t type.
  294. mutable TypedefDecl *UInt128Decl = nullptr;
  295. /// The typedef for the target specific predefined
  296. /// __builtin_va_list type.
  297. mutable TypedefDecl *BuiltinVaListDecl = nullptr;
  298. /// The typedef for the predefined \c __builtin_ms_va_list type.
  299. mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
  300. /// The typedef for the predefined \c id type.
  301. mutable TypedefDecl *ObjCIdDecl = nullptr;
  302. /// The typedef for the predefined \c SEL type.
  303. mutable TypedefDecl *ObjCSelDecl = nullptr;
  304. /// The typedef for the predefined \c Class type.
  305. mutable TypedefDecl *ObjCClassDecl = nullptr;
  306. /// The typedef for the predefined \c Protocol class in Objective-C.
  307. mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
  308. /// The typedef for the predefined 'BOOL' type.
  309. mutable TypedefDecl *BOOLDecl = nullptr;
  310. // Typedefs which may be provided defining the structure of Objective-C
  311. // pseudo-builtins
  312. QualType ObjCIdRedefinitionType;
  313. QualType ObjCClassRedefinitionType;
  314. QualType ObjCSelRedefinitionType;
  315. /// The identifier 'bool'.
  316. mutable IdentifierInfo *BoolName = nullptr;
  317. /// The identifier 'NSObject'.
  318. mutable IdentifierInfo *NSObjectName = nullptr;
  319. /// The identifier 'NSCopying'.
  320. IdentifierInfo *NSCopyingName = nullptr;
  321. /// The identifier '__make_integer_seq'.
  322. mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
  323. /// The identifier '__type_pack_element'.
  324. mutable IdentifierInfo *TypePackElementName = nullptr;
  325. QualType ObjCConstantStringType;
  326. mutable RecordDecl *CFConstantStringTagDecl = nullptr;
  327. mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
  328. mutable QualType ObjCSuperType;
  329. QualType ObjCNSStringType;
  330. /// The typedef declaration for the Objective-C "instancetype" type.
  331. TypedefDecl *ObjCInstanceTypeDecl = nullptr;
  332. /// The type for the C FILE type.
  333. TypeDecl *FILEDecl = nullptr;
  334. /// The type for the C jmp_buf type.
  335. TypeDecl *jmp_bufDecl = nullptr;
  336. /// The type for the C sigjmp_buf type.
  337. TypeDecl *sigjmp_bufDecl = nullptr;
  338. /// The type for the C ucontext_t type.
  339. TypeDecl *ucontext_tDecl = nullptr;
  340. /// Type for the Block descriptor for Blocks CodeGen.
  341. ///
  342. /// Since this is only used for generation of debug info, it is not
  343. /// serialized.
  344. mutable RecordDecl *BlockDescriptorType = nullptr;
  345. /// Type for the Block descriptor for Blocks CodeGen.
  346. ///
  347. /// Since this is only used for generation of debug info, it is not
  348. /// serialized.
  349. mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
  350. /// Declaration for the CUDA cudaConfigureCall function.
  351. FunctionDecl *cudaConfigureCallDecl = nullptr;
  352. /// Keeps track of all declaration attributes.
  353. ///
  354. /// Since so few decls have attrs, we keep them in a hash map instead of
  355. /// wasting space in the Decl class.
  356. llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
  357. /// A mapping from non-redeclarable declarations in modules that were
  358. /// merged with other declarations to the canonical declaration that they were
  359. /// merged into.
  360. llvm::DenseMap<Decl*, Decl*> MergedDecls;
  361. /// A mapping from a defining declaration to a list of modules (other
  362. /// than the owning module of the declaration) that contain merged
  363. /// definitions of that entity.
  364. llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
  365. /// Initializers for a module, in order. Each Decl will be either
  366. /// something that has a semantic effect on startup (such as a variable with
  367. /// a non-constant initializer), or an ImportDecl (which recursively triggers
  368. /// initialization of another module).
  369. struct PerModuleInitializers {
  370. llvm::SmallVector<Decl*, 4> Initializers;
  371. llvm::SmallVector<uint32_t, 4> LazyInitializers;
  372. void resolve(ASTContext &Ctx);
  373. };
  374. llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
  375. /// For module code-gen cases, this is the top-level module we are building.
  376. Module *TopLevelModule = nullptr;
  377. static constexpr unsigned ConstantArrayTypesLog2InitSize = 8;
  378. static constexpr unsigned GeneralTypesLog2InitSize = 9;
  379. static constexpr unsigned FunctionProtoTypesLog2InitSize = 12;
  380. ASTContext &this_() { return *this; }
  381. public:
  382. /// A type synonym for the TemplateOrInstantiation mapping.
  383. using TemplateOrSpecializationInfo =
  384. llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
  385. private:
  386. friend class ASTDeclReader;
  387. friend class ASTReader;
  388. friend class ASTWriter;
  389. template <class> friend class serialization::AbstractTypeReader;
  390. friend class CXXRecordDecl;
  391. friend class IncrementalParser;
  392. /// A mapping to contain the template or declaration that
  393. /// a variable declaration describes or was instantiated from,
  394. /// respectively.
  395. ///
  396. /// For non-templates, this value will be NULL. For variable
  397. /// declarations that describe a variable template, this will be a
  398. /// pointer to a VarTemplateDecl. For static data members
  399. /// of class template specializations, this will be the
  400. /// MemberSpecializationInfo referring to the member variable that was
  401. /// instantiated or specialized. Thus, the mapping will keep track of
  402. /// the static data member templates from which static data members of
  403. /// class template specializations were instantiated.
  404. ///
  405. /// Given the following example:
  406. ///
  407. /// \code
  408. /// template<typename T>
  409. /// struct X {
  410. /// static T value;
  411. /// };
  412. ///
  413. /// template<typename T>
  414. /// T X<T>::value = T(17);
  415. ///
  416. /// int *x = &X<int>::value;
  417. /// \endcode
  418. ///
  419. /// This mapping will contain an entry that maps from the VarDecl for
  420. /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
  421. /// class template X) and will be marked TSK_ImplicitInstantiation.
  422. llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
  423. TemplateOrInstantiation;
  424. /// Keeps track of the declaration from which a using declaration was
  425. /// created during instantiation.
  426. ///
  427. /// The source and target declarations are always a UsingDecl, an
  428. /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
  429. ///
  430. /// For example:
  431. /// \code
  432. /// template<typename T>
  433. /// struct A {
  434. /// void f();
  435. /// };
  436. ///
  437. /// template<typename T>
  438. /// struct B : A<T> {
  439. /// using A<T>::f;
  440. /// };
  441. ///
  442. /// template struct B<int>;
  443. /// \endcode
  444. ///
  445. /// This mapping will contain an entry that maps from the UsingDecl in
  446. /// B<int> to the UnresolvedUsingDecl in B<T>.
  447. llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
  448. /// Like InstantiatedFromUsingDecl, but for using-enum-declarations. Maps
  449. /// from the instantiated using-enum to the templated decl from whence it
  450. /// came.
  451. /// Note that using-enum-declarations cannot be dependent and
  452. /// thus will never be instantiated from an "unresolved"
  453. /// version thereof (as with using-declarations), so each mapping is from
  454. /// a (resolved) UsingEnumDecl to a (resolved) UsingEnumDecl.
  455. llvm::DenseMap<UsingEnumDecl *, UsingEnumDecl *>
  456. InstantiatedFromUsingEnumDecl;
  457. /// Simlarly maps instantiated UsingShadowDecls to their origin.
  458. llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
  459. InstantiatedFromUsingShadowDecl;
  460. llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
  461. /// Mapping that stores the methods overridden by a given C++
  462. /// member function.
  463. ///
  464. /// Since most C++ member functions aren't virtual and therefore
  465. /// don't override anything, we store the overridden functions in
  466. /// this map on the side rather than within the CXXMethodDecl structure.
  467. using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
  468. llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
  469. /// Mapping from each declaration context to its corresponding
  470. /// mangling numbering context (used for constructs like lambdas which
  471. /// need to be consistently numbered for the mangler).
  472. llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
  473. MangleNumberingContexts;
  474. llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
  475. ExtraMangleNumberingContexts;
  476. /// Side-table of mangling numbers for declarations which rarely
  477. /// need them (like static local vars).
  478. llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
  479. llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
  480. /// Mapping the associated device lambda mangling number if present.
  481. mutable llvm::DenseMap<const CXXRecordDecl *, unsigned>
  482. DeviceLambdaManglingNumbers;
  483. /// Mapping that stores parameterIndex values for ParmVarDecls when
  484. /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
  485. using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
  486. ParameterIndexTable ParamIndices;
  487. ImportDecl *FirstLocalImport = nullptr;
  488. ImportDecl *LastLocalImport = nullptr;
  489. TranslationUnitDecl *TUDecl = nullptr;
  490. mutable ExternCContextDecl *ExternCContext = nullptr;
  491. mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
  492. mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
  493. /// The associated SourceManager object.
  494. SourceManager &SourceMgr;
  495. /// The language options used to create the AST associated with
  496. /// this ASTContext object.
  497. LangOptions &LangOpts;
  498. /// NoSanitizeList object that is used by sanitizers to decide which
  499. /// entities should not be instrumented.
  500. std::unique_ptr<NoSanitizeList> NoSanitizeL;
  501. /// Function filtering mechanism to determine whether a given function
  502. /// should be imbued with the XRay "always" or "never" attributes.
  503. std::unique_ptr<XRayFunctionFilter> XRayFilter;
  504. /// ProfileList object that is used by the profile instrumentation
  505. /// to decide which entities should be instrumented.
  506. std::unique_ptr<ProfileList> ProfList;
  507. /// The allocator used to create AST objects.
  508. ///
  509. /// AST objects are never destructed; rather, all memory associated with the
  510. /// AST objects will be released when the ASTContext itself is destroyed.
  511. mutable llvm::BumpPtrAllocator BumpAlloc;
  512. /// Allocator for partial diagnostics.
  513. PartialDiagnostic::DiagStorageAllocator DiagAllocator;
  514. /// The current C++ ABI.
  515. std::unique_ptr<CXXABI> ABI;
  516. CXXABI *createCXXABI(const TargetInfo &T);
  517. /// Address space map mangling must be used with language specific
  518. /// address spaces (e.g. OpenCL/CUDA)
  519. bool AddrSpaceMapMangling;
  520. const TargetInfo *Target = nullptr;
  521. const TargetInfo *AuxTarget = nullptr;
  522. clang::PrintingPolicy PrintingPolicy;
  523. std::unique_ptr<interp::Context> InterpContext;
  524. std::unique_ptr<ParentMapContext> ParentMapCtx;
  525. /// Keeps track of the deallocated DeclListNodes for future reuse.
  526. DeclListNode *ListNodeFreeList = nullptr;
  527. public:
  528. IdentifierTable &Idents;
  529. SelectorTable &Selectors;
  530. Builtin::Context &BuiltinInfo;
  531. const TranslationUnitKind TUKind;
  532. mutable DeclarationNameTable DeclarationNames;
  533. IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
  534. ASTMutationListener *Listener = nullptr;
  535. /// Returns the clang bytecode interpreter context.
  536. interp::Context &getInterpContext();
  537. struct CUDAConstantEvalContext {
  538. /// Do not allow wrong-sided variables in constant expressions.
  539. bool NoWrongSidedVars = false;
  540. } CUDAConstantEvalCtx;
  541. struct CUDAConstantEvalContextRAII {
  542. ASTContext &Ctx;
  543. CUDAConstantEvalContext SavedCtx;
  544. CUDAConstantEvalContextRAII(ASTContext &Ctx_, bool NoWrongSidedVars)
  545. : Ctx(Ctx_), SavedCtx(Ctx_.CUDAConstantEvalCtx) {
  546. Ctx_.CUDAConstantEvalCtx.NoWrongSidedVars = NoWrongSidedVars;
  547. }
  548. ~CUDAConstantEvalContextRAII() { Ctx.CUDAConstantEvalCtx = SavedCtx; }
  549. };
  550. /// Returns the dynamic AST node parent map context.
  551. ParentMapContext &getParentMapContext();
  552. // A traversal scope limits the parts of the AST visible to certain analyses.
  553. // RecursiveASTVisitor only visits specified children of TranslationUnitDecl.
  554. // getParents() will only observe reachable parent edges.
  555. //
  556. // The scope is defined by a set of "top-level" declarations which will be
  557. // visible under the TranslationUnitDecl.
  558. // Initially, it is the entire TU, represented by {getTranslationUnitDecl()}.
  559. //
  560. // After setTraversalScope({foo, bar}), the exposed AST looks like:
  561. // TranslationUnitDecl
  562. // - foo
  563. // - ...
  564. // - bar
  565. // - ...
  566. // All other siblings of foo and bar are pruned from the tree.
  567. // (However they are still accessible via TranslationUnitDecl->decls())
  568. //
  569. // Changing the scope clears the parent cache, which is expensive to rebuild.
  570. std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
  571. void setTraversalScope(const std::vector<Decl *> &);
  572. /// Forwards to get node parents from the ParentMapContext. New callers should
  573. /// use ParentMapContext::getParents() directly.
  574. template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node);
  575. const clang::PrintingPolicy &getPrintingPolicy() const {
  576. return PrintingPolicy;
  577. }
  578. void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
  579. PrintingPolicy = Policy;
  580. }
  581. SourceManager& getSourceManager() { return SourceMgr; }
  582. const SourceManager& getSourceManager() const { return SourceMgr; }
  583. // Cleans up some of the data structures. This allows us to do cleanup
  584. // normally done in the destructor earlier. Renders much of the ASTContext
  585. // unusable, mostly the actual AST nodes, so should be called when we no
  586. // longer need access to the AST.
  587. void cleanup();
  588. llvm::BumpPtrAllocator &getAllocator() const {
  589. return BumpAlloc;
  590. }
  591. void *Allocate(size_t Size, unsigned Align = 8) const {
  592. return BumpAlloc.Allocate(Size, Align);
  593. }
  594. template <typename T> T *Allocate(size_t Num = 1) const {
  595. return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
  596. }
  597. void Deallocate(void *Ptr) const {}
  598. /// Allocates a \c DeclListNode or returns one from the \c ListNodeFreeList
  599. /// pool.
  600. DeclListNode *AllocateDeclListNode(clang::NamedDecl *ND) {
  601. if (DeclListNode *Alloc = ListNodeFreeList) {
  602. ListNodeFreeList = Alloc->Rest.dyn_cast<DeclListNode*>();
  603. Alloc->D = ND;
  604. Alloc->Rest = nullptr;
  605. return Alloc;
  606. }
  607. return new (*this) DeclListNode(ND);
  608. }
  609. /// Deallcates a \c DeclListNode by returning it to the \c ListNodeFreeList
  610. /// pool.
  611. void DeallocateDeclListNode(DeclListNode *N) {
  612. N->Rest = ListNodeFreeList;
  613. ListNodeFreeList = N;
  614. }
  615. /// Return the total amount of physical memory allocated for representing
  616. /// AST nodes and type information.
  617. size_t getASTAllocatedMemory() const {
  618. return BumpAlloc.getTotalMemory();
  619. }
  620. /// Return the total memory used for various side tables.
  621. size_t getSideTableAllocatedMemory() const;
  622. PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() {
  623. return DiagAllocator;
  624. }
  625. const TargetInfo &getTargetInfo() const { return *Target; }
  626. const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
  627. /// getIntTypeForBitwidth -
  628. /// sets integer QualTy according to specified details:
  629. /// bitwidth, signed/unsigned.
  630. /// Returns empty type if there is no appropriate target types.
  631. QualType getIntTypeForBitwidth(unsigned DestWidth,
  632. unsigned Signed) const;
  633. /// getRealTypeForBitwidth -
  634. /// sets floating point QualTy according to specified bitwidth.
  635. /// Returns empty type if there is no appropriate target types.
  636. QualType getRealTypeForBitwidth(unsigned DestWidth,
  637. FloatModeKind ExplicitType) const;
  638. bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
  639. const LangOptions& getLangOpts() const { return LangOpts; }
  640. // If this condition is false, typo correction must be performed eagerly
  641. // rather than delayed in many places, as it makes use of dependent types.
  642. // the condition is false for clang's C-only codepath, as it doesn't support
  643. // dependent types yet.
  644. bool isDependenceAllowed() const {
  645. return LangOpts.CPlusPlus || LangOpts.RecoveryAST;
  646. }
  647. const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; }
  648. const XRayFunctionFilter &getXRayFilter() const {
  649. return *XRayFilter;
  650. }
  651. const ProfileList &getProfileList() const { return *ProfList; }
  652. DiagnosticsEngine &getDiagnostics() const;
  653. FullSourceLoc getFullLoc(SourceLocation Loc) const {
  654. return FullSourceLoc(Loc,SourceMgr);
  655. }
  656. /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden
  657. /// at compile time with `-fc++-abi=`. If this is not provided, we instead use
  658. /// the default ABI set by the target.
  659. TargetCXXABI::Kind getCXXABIKind() const;
  660. /// All comments in this translation unit.
  661. RawCommentList Comments;
  662. /// True if comments are already loaded from ExternalASTSource.
  663. mutable bool CommentsLoaded = false;
  664. /// Mapping from declaration to directly attached comment.
  665. ///
  666. /// Raw comments are owned by Comments list. This mapping is populated
  667. /// lazily.
  668. mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;
  669. /// Mapping from canonical declaration to the first redeclaration in chain
  670. /// that has a comment attached.
  671. ///
  672. /// Raw comments are owned by Comments list. This mapping is populated
  673. /// lazily.
  674. mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments;
  675. /// Keeps track of redeclaration chains that don't have any comment attached.
  676. /// Mapping from canonical declaration to redeclaration chain that has no
  677. /// comments attached to any redeclaration. Specifically it's mapping to
  678. /// the last redeclaration we've checked.
  679. ///
  680. /// Shall not contain declarations that have comments attached to any
  681. /// redeclaration in their chain.
  682. mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains;
  683. /// Mapping from declarations to parsed comments attached to any
  684. /// redeclaration.
  685. mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
  686. /// Attaches \p Comment to \p OriginalD and to its redeclaration chain
  687. /// and removes the redeclaration chain from the set of commentless chains.
  688. ///
  689. /// Don't do anything if a comment has already been attached to \p OriginalD
  690. /// or its redeclaration chain.
  691. void cacheRawCommentForDecl(const Decl &OriginalD,
  692. const RawComment &Comment) const;
  693. /// \returns searches \p CommentsInFile for doc comment for \p D.
  694. ///
  695. /// \p RepresentativeLocForDecl is used as a location for searching doc
  696. /// comments. \p CommentsInFile is a mapping offset -> comment of files in the
  697. /// same file where \p RepresentativeLocForDecl is.
  698. RawComment *getRawCommentForDeclNoCacheImpl(
  699. const Decl *D, const SourceLocation RepresentativeLocForDecl,
  700. const std::map<unsigned, RawComment *> &CommentsInFile) const;
  701. /// Return the documentation comment attached to a given declaration,
  702. /// without looking into cache.
  703. RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
  704. public:
  705. void addComment(const RawComment &RC);
  706. /// Return the documentation comment attached to a given declaration.
  707. /// Returns nullptr if no comment is attached.
  708. ///
  709. /// \param OriginalDecl if not nullptr, is set to declaration AST node that
  710. /// had the comment, if the comment we found comes from a redeclaration.
  711. const RawComment *
  712. getRawCommentForAnyRedecl(const Decl *D,
  713. const Decl **OriginalDecl = nullptr) const;
  714. /// Searches existing comments for doc comments that should be attached to \p
  715. /// Decls. If any doc comment is found, it is parsed.
  716. ///
  717. /// Requirement: All \p Decls are in the same file.
  718. ///
  719. /// If the last comment in the file is already attached we assume
  720. /// there are not comments left to be attached to \p Decls.
  721. void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
  722. const Preprocessor *PP);
  723. /// Return parsed documentation comment attached to a given declaration.
  724. /// Returns nullptr if no comment is attached.
  725. ///
  726. /// \param PP the Preprocessor used with this TU. Could be nullptr if
  727. /// preprocessor is not available.
  728. comments::FullComment *getCommentForDecl(const Decl *D,
  729. const Preprocessor *PP) const;
  730. /// Return parsed documentation comment attached to a given declaration.
  731. /// Returns nullptr if no comment is attached. Does not look at any
  732. /// redeclarations of the declaration.
  733. comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
  734. comments::FullComment *cloneFullComment(comments::FullComment *FC,
  735. const Decl *D) const;
  736. private:
  737. mutable comments::CommandTraits CommentCommandTraits;
  738. /// Iterator that visits import declarations.
  739. class import_iterator {
  740. ImportDecl *Import = nullptr;
  741. public:
  742. using value_type = ImportDecl *;
  743. using reference = ImportDecl *;
  744. using pointer = ImportDecl *;
  745. using difference_type = int;
  746. using iterator_category = std::forward_iterator_tag;
  747. import_iterator() = default;
  748. explicit import_iterator(ImportDecl *Import) : Import(Import) {}
  749. reference operator*() const { return Import; }
  750. pointer operator->() const { return Import; }
  751. import_iterator &operator++() {
  752. Import = ASTContext::getNextLocalImport(Import);
  753. return *this;
  754. }
  755. import_iterator operator++(int) {
  756. import_iterator Other(*this);
  757. ++(*this);
  758. return Other;
  759. }
  760. friend bool operator==(import_iterator X, import_iterator Y) {
  761. return X.Import == Y.Import;
  762. }
  763. friend bool operator!=(import_iterator X, import_iterator Y) {
  764. return X.Import != Y.Import;
  765. }
  766. };
  767. public:
  768. comments::CommandTraits &getCommentCommandTraits() const {
  769. return CommentCommandTraits;
  770. }
  771. /// Retrieve the attributes for the given declaration.
  772. AttrVec& getDeclAttrs(const Decl *D);
  773. /// Erase the attributes corresponding to the given declaration.
  774. void eraseDeclAttrs(const Decl *D);
  775. /// If this variable is an instantiated static data member of a
  776. /// class template specialization, returns the templated static data member
  777. /// from which it was instantiated.
  778. // FIXME: Remove ?
  779. MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
  780. const VarDecl *Var);
  781. /// Note that the static data member \p Inst is an instantiation of
  782. /// the static data member template \p Tmpl of a class template.
  783. void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
  784. TemplateSpecializationKind TSK,
  785. SourceLocation PointOfInstantiation = SourceLocation());
  786. TemplateOrSpecializationInfo
  787. getTemplateOrSpecializationInfo(const VarDecl *Var);
  788. void setTemplateOrSpecializationInfo(VarDecl *Inst,
  789. TemplateOrSpecializationInfo TSI);
  790. /// If the given using decl \p Inst is an instantiation of
  791. /// another (possibly unresolved) using decl, return it.
  792. NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
  793. /// Remember that the using decl \p Inst is an instantiation
  794. /// of the using decl \p Pattern of a class template.
  795. void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
  796. /// If the given using-enum decl \p Inst is an instantiation of
  797. /// another using-enum decl, return it.
  798. UsingEnumDecl *getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst);
  799. /// Remember that the using enum decl \p Inst is an instantiation
  800. /// of the using enum decl \p Pattern of a class template.
  801. void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
  802. UsingEnumDecl *Pattern);
  803. UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
  804. void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
  805. UsingShadowDecl *Pattern);
  806. FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
  807. void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
  808. // Access to the set of methods overridden by the given C++ method.
  809. using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
  810. overridden_cxx_method_iterator
  811. overridden_methods_begin(const CXXMethodDecl *Method) const;
  812. overridden_cxx_method_iterator
  813. overridden_methods_end(const CXXMethodDecl *Method) const;
  814. unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
  815. using overridden_method_range =
  816. llvm::iterator_range<overridden_cxx_method_iterator>;
  817. overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
  818. /// Note that the given C++ \p Method overrides the given \p
  819. /// Overridden method.
  820. void addOverriddenMethod(const CXXMethodDecl *Method,
  821. const CXXMethodDecl *Overridden);
  822. /// Return C++ or ObjC overridden methods for the given \p Method.
  823. ///
  824. /// An ObjC method is considered to override any method in the class's
  825. /// base classes, its protocols, or its categories' protocols, that has
  826. /// the same selector and is of the same kind (class or instance).
  827. /// A method in an implementation is not considered as overriding the same
  828. /// method in the interface or its categories.
  829. void getOverriddenMethods(
  830. const NamedDecl *Method,
  831. SmallVectorImpl<const NamedDecl *> &Overridden) const;
  832. /// Notify the AST context that a new import declaration has been
  833. /// parsed or implicitly created within this translation unit.
  834. void addedLocalImportDecl(ImportDecl *Import);
  835. static ImportDecl *getNextLocalImport(ImportDecl *Import) {
  836. return Import->getNextLocalImport();
  837. }
  838. using import_range = llvm::iterator_range<import_iterator>;
  839. import_range local_imports() const {
  840. return import_range(import_iterator(FirstLocalImport), import_iterator());
  841. }
  842. Decl *getPrimaryMergedDecl(Decl *D) {
  843. Decl *Result = MergedDecls.lookup(D);
  844. return Result ? Result : D;
  845. }
  846. void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
  847. MergedDecls[D] = Primary;
  848. }
  849. /// Note that the definition \p ND has been merged into module \p M,
  850. /// and should be visible whenever \p M is visible.
  851. void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
  852. bool NotifyListeners = true);
  853. /// Clean up the merged definition list. Call this if you might have
  854. /// added duplicates into the list.
  855. void deduplicateMergedDefinitonsFor(NamedDecl *ND);
  856. /// Get the additional modules in which the definition \p Def has
  857. /// been merged.
  858. ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
  859. /// Add a declaration to the list of declarations that are initialized
  860. /// for a module. This will typically be a global variable (with internal
  861. /// linkage) that runs module initializers, such as the iostream initializer,
  862. /// or an ImportDecl nominating another module that has initializers.
  863. void addModuleInitializer(Module *M, Decl *Init);
  864. void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
  865. /// Get the initializations to perform when importing a module, if any.
  866. ArrayRef<Decl*> getModuleInitializers(Module *M);
  867. /// Set the (C++20) module we are building.
  868. void setModuleForCodeGen(Module *M) { TopLevelModule = M; }
  869. /// Get module under construction, nullptr if this is not a C++20 module.
  870. Module *getModuleForCodeGen() const { return TopLevelModule; }
  871. TranslationUnitDecl *getTranslationUnitDecl() const {
  872. return TUDecl->getMostRecentDecl();
  873. }
  874. void addTranslationUnitDecl() {
  875. assert(!TUDecl || TUKind == TU_Incremental);
  876. TranslationUnitDecl *NewTUDecl = TranslationUnitDecl::Create(*this);
  877. if (TraversalScope.empty() || TraversalScope.back() == TUDecl)
  878. TraversalScope = {NewTUDecl};
  879. if (TUDecl)
  880. NewTUDecl->setPreviousDecl(TUDecl);
  881. TUDecl = NewTUDecl;
  882. }
  883. ExternCContextDecl *getExternCContextDecl() const;
  884. BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
  885. BuiltinTemplateDecl *getTypePackElementDecl() const;
  886. // Builtin Types.
  887. CanQualType VoidTy;
  888. CanQualType BoolTy;
  889. CanQualType CharTy;
  890. CanQualType WCharTy; // [C++ 3.9.1p5].
  891. CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
  892. CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
  893. CanQualType Char8Ty; // [C++20 proposal]
  894. CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
  895. CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
  896. CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
  897. CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
  898. CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
  899. CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty, Ibm128Ty;
  900. CanQualType ShortAccumTy, AccumTy,
  901. LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
  902. CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
  903. CanQualType ShortFractTy, FractTy, LongFractTy;
  904. CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
  905. CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
  906. CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
  907. SatUnsignedLongAccumTy;
  908. CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
  909. CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
  910. SatUnsignedLongFractTy;
  911. CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
  912. CanQualType BFloat16Ty;
  913. CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
  914. CanQualType VoidPtrTy, NullPtrTy;
  915. CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
  916. CanQualType BuiltinFnTy;
  917. CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
  918. CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
  919. CanQualType ObjCBuiltinBoolTy;
  920. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  921. CanQualType SingletonId;
  922. #include "clang/Basic/OpenCLImageTypes.def"
  923. CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
  924. CanQualType OCLQueueTy, OCLReserveIDTy;
  925. CanQualType IncompleteMatrixIdxTy;
  926. CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy;
  927. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  928. CanQualType Id##Ty;
  929. #include "clang/Basic/OpenCLExtensionTypes.def"
  930. #define SVE_TYPE(Name, Id, SingletonId) \
  931. CanQualType SingletonId;
  932. #include "clang/Basic/AArch64SVEACLETypes.def"
  933. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  934. CanQualType Id##Ty;
  935. #include "clang/Basic/PPCTypes.def"
  936. #define RVV_TYPE(Name, Id, SingletonId) \
  937. CanQualType SingletonId;
  938. #include "clang/Basic/RISCVVTypes.def"
  939. // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
  940. mutable QualType AutoDeductTy; // Deduction against 'auto'.
  941. mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
  942. // Decl used to help define __builtin_va_list for some targets.
  943. // The decl is built when constructing 'BuiltinVaListDecl'.
  944. mutable Decl *VaListTagDecl = nullptr;
  945. // Implicitly-declared type 'struct _GUID'.
  946. mutable TagDecl *MSGuidTagDecl = nullptr;
  947. /// Keep track of CUDA/HIP device-side variables ODR-used by host code.
  948. llvm::DenseSet<const VarDecl *> CUDADeviceVarODRUsedByHost;
  949. /// Keep track of CUDA/HIP external kernels or device variables ODR-used by
  950. /// host code.
  951. llvm::DenseSet<const ValueDecl *> CUDAExternalDeviceDeclODRUsedByHost;
  952. ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
  953. SelectorTable &sels, Builtin::Context &builtins,
  954. TranslationUnitKind TUKind);
  955. ASTContext(const ASTContext &) = delete;
  956. ASTContext &operator=(const ASTContext &) = delete;
  957. ~ASTContext();
  958. /// Attach an external AST source to the AST context.
  959. ///
  960. /// The external AST source provides the ability to load parts of
  961. /// the abstract syntax tree as needed from some external storage,
  962. /// e.g., a precompiled header.
  963. void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
  964. /// Retrieve a pointer to the external AST source associated
  965. /// with this AST context, if any.
  966. ExternalASTSource *getExternalSource() const {
  967. return ExternalSource.get();
  968. }
  969. /// Attach an AST mutation listener to the AST context.
  970. ///
  971. /// The AST mutation listener provides the ability to track modifications to
  972. /// the abstract syntax tree entities committed after they were initially
  973. /// created.
  974. void setASTMutationListener(ASTMutationListener *Listener) {
  975. this->Listener = Listener;
  976. }
  977. /// Retrieve a pointer to the AST mutation listener associated
  978. /// with this AST context, if any.
  979. ASTMutationListener *getASTMutationListener() const { return Listener; }
  980. void PrintStats() const;
  981. const SmallVectorImpl<Type *>& getTypes() const { return Types; }
  982. BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
  983. const IdentifierInfo *II) const;
  984. /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
  985. /// declaration.
  986. RecordDecl *buildImplicitRecord(StringRef Name,
  987. RecordDecl::TagKind TK = TTK_Struct) const;
  988. /// Create a new implicit TU-level typedef declaration.
  989. TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
  990. /// Retrieve the declaration for the 128-bit signed integer type.
  991. TypedefDecl *getInt128Decl() const;
  992. /// Retrieve the declaration for the 128-bit unsigned integer type.
  993. TypedefDecl *getUInt128Decl() const;
  994. //===--------------------------------------------------------------------===//
  995. // Type Constructors
  996. //===--------------------------------------------------------------------===//
  997. private:
  998. /// Return a type with extended qualifiers.
  999. QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
  1000. QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
  1001. QualType getPipeType(QualType T, bool ReadOnly) const;
  1002. public:
  1003. /// Return the uniqued reference to the type for an address space
  1004. /// qualified type with the specified type and address space.
  1005. ///
  1006. /// The resulting type has a union of the qualifiers from T and the address
  1007. /// space. If T already has an address space specifier, it is silently
  1008. /// replaced.
  1009. QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
  1010. /// Remove any existing address space on the type and returns the type
  1011. /// with qualifiers intact (or that's the idea anyway)
  1012. ///
  1013. /// The return type should be T with all prior qualifiers minus the address
  1014. /// space.
  1015. QualType removeAddrSpaceQualType(QualType T) const;
  1016. /// Apply Objective-C protocol qualifiers to the given type.
  1017. /// \param allowOnPointerType specifies if we can apply protocol
  1018. /// qualifiers on ObjCObjectPointerType. It can be set to true when
  1019. /// constructing the canonical type of a Objective-C type parameter.
  1020. QualType applyObjCProtocolQualifiers(QualType type,
  1021. ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
  1022. bool allowOnPointerType = false) const;
  1023. /// Return the uniqued reference to the type for an Objective-C
  1024. /// gc-qualified type.
  1025. ///
  1026. /// The resulting type has a union of the qualifiers from T and the gc
  1027. /// attribute.
  1028. QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
  1029. /// Remove the existing address space on the type if it is a pointer size
  1030. /// address space and return the type with qualifiers intact.
  1031. QualType removePtrSizeAddrSpace(QualType T) const;
  1032. /// Return the uniqued reference to the type for a \c restrict
  1033. /// qualified type.
  1034. ///
  1035. /// The resulting type has a union of the qualifiers from \p T and
  1036. /// \c restrict.
  1037. QualType getRestrictType(QualType T) const {
  1038. return T.withFastQualifiers(Qualifiers::Restrict);
  1039. }
  1040. /// Return the uniqued reference to the type for a \c volatile
  1041. /// qualified type.
  1042. ///
  1043. /// The resulting type has a union of the qualifiers from \p T and
  1044. /// \c volatile.
  1045. QualType getVolatileType(QualType T) const {
  1046. return T.withFastQualifiers(Qualifiers::Volatile);
  1047. }
  1048. /// Return the uniqued reference to the type for a \c const
  1049. /// qualified type.
  1050. ///
  1051. /// The resulting type has a union of the qualifiers from \p T and \c const.
  1052. ///
  1053. /// It can be reasonably expected that this will always be equivalent to
  1054. /// calling T.withConst().
  1055. QualType getConstType(QualType T) const { return T.withConst(); }
  1056. /// Change the ExtInfo on a function type.
  1057. const FunctionType *adjustFunctionType(const FunctionType *Fn,
  1058. FunctionType::ExtInfo EInfo);
  1059. /// Adjust the given function result type.
  1060. CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
  1061. /// Change the result type of a function type once it is deduced.
  1062. void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
  1063. /// Get a function type and produce the equivalent function type with the
  1064. /// specified exception specification. Type sugar that can be present on a
  1065. /// declaration of a function with an exception specification is permitted
  1066. /// and preserved. Other type sugar (for instance, typedefs) is not.
  1067. QualType getFunctionTypeWithExceptionSpec(
  1068. QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI) const;
  1069. /// Determine whether two function types are the same, ignoring
  1070. /// exception specifications in cases where they're part of the type.
  1071. bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const;
  1072. /// Change the exception specification on a function once it is
  1073. /// delay-parsed, instantiated, or computed.
  1074. void adjustExceptionSpec(FunctionDecl *FD,
  1075. const FunctionProtoType::ExceptionSpecInfo &ESI,
  1076. bool AsWritten = false);
  1077. /// Get a function type and produce the equivalent function type where
  1078. /// pointer size address spaces in the return type and parameter tyeps are
  1079. /// replaced with the default address space.
  1080. QualType getFunctionTypeWithoutPtrSizes(QualType T);
  1081. /// Determine whether two function types are the same, ignoring pointer sizes
  1082. /// in the return type and parameter types.
  1083. bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U);
  1084. /// Return the uniqued reference to the type for a complex
  1085. /// number with the specified element type.
  1086. QualType getComplexType(QualType T) const;
  1087. CanQualType getComplexType(CanQualType T) const {
  1088. return CanQualType::CreateUnsafe(getComplexType((QualType) T));
  1089. }
  1090. /// Return the uniqued reference to the type for a pointer to
  1091. /// the specified type.
  1092. QualType getPointerType(QualType T) const;
  1093. CanQualType getPointerType(CanQualType T) const {
  1094. return CanQualType::CreateUnsafe(getPointerType((QualType) T));
  1095. }
  1096. /// Return the uniqued reference to a type adjusted from the original
  1097. /// type to a new type.
  1098. QualType getAdjustedType(QualType Orig, QualType New) const;
  1099. CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
  1100. return CanQualType::CreateUnsafe(
  1101. getAdjustedType((QualType)Orig, (QualType)New));
  1102. }
  1103. /// Return the uniqued reference to the decayed version of the given
  1104. /// type. Can only be called on array and function types which decay to
  1105. /// pointer types.
  1106. QualType getDecayedType(QualType T) const;
  1107. CanQualType getDecayedType(CanQualType T) const {
  1108. return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
  1109. }
  1110. /// Return the uniqued reference to a specified decay from the original
  1111. /// type to the decayed type.
  1112. QualType getDecayedType(QualType Orig, QualType Decayed) const;
  1113. /// Return the uniqued reference to the atomic type for the specified
  1114. /// type.
  1115. QualType getAtomicType(QualType T) const;
  1116. /// Return the uniqued reference to the type for a block of the
  1117. /// specified type.
  1118. QualType getBlockPointerType(QualType T) const;
  1119. /// Gets the struct used to keep track of the descriptor for pointer to
  1120. /// blocks.
  1121. QualType getBlockDescriptorType() const;
  1122. /// Return a read_only pipe type for the specified type.
  1123. QualType getReadPipeType(QualType T) const;
  1124. /// Return a write_only pipe type for the specified type.
  1125. QualType getWritePipeType(QualType T) const;
  1126. /// Return a bit-precise integer type with the specified signedness and bit
  1127. /// count.
  1128. QualType getBitIntType(bool Unsigned, unsigned NumBits) const;
  1129. /// Return a dependent bit-precise integer type with the specified signedness
  1130. /// and bit count.
  1131. QualType getDependentBitIntType(bool Unsigned, Expr *BitsExpr) const;
  1132. /// Gets the struct used to keep track of the extended descriptor for
  1133. /// pointer to blocks.
  1134. QualType getBlockDescriptorExtendedType() const;
  1135. /// Map an AST Type to an OpenCLTypeKind enum value.
  1136. OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
  1137. /// Get address space for OpenCL type.
  1138. LangAS getOpenCLTypeAddrSpace(const Type *T) const;
  1139. /// Returns default address space based on OpenCL version and enabled features
  1140. inline LangAS getDefaultOpenCLPointeeAddrSpace() {
  1141. return LangOpts.OpenCLGenericAddressSpace ? LangAS::opencl_generic
  1142. : LangAS::opencl_private;
  1143. }
  1144. void setcudaConfigureCallDecl(FunctionDecl *FD) {
  1145. cudaConfigureCallDecl = FD;
  1146. }
  1147. FunctionDecl *getcudaConfigureCallDecl() {
  1148. return cudaConfigureCallDecl;
  1149. }
  1150. /// Returns true iff we need copy/dispose helpers for the given type.
  1151. bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
  1152. /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
  1153. /// is set to false in this case. If HasByrefExtendedLayout returns true,
  1154. /// byref variable has extended lifetime.
  1155. bool getByrefLifetime(QualType Ty,
  1156. Qualifiers::ObjCLifetime &Lifetime,
  1157. bool &HasByrefExtendedLayout) const;
  1158. /// Return the uniqued reference to the type for an lvalue reference
  1159. /// to the specified type.
  1160. QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
  1161. const;
  1162. /// Return the uniqued reference to the type for an rvalue reference
  1163. /// to the specified type.
  1164. QualType getRValueReferenceType(QualType T) const;
  1165. /// Return the uniqued reference to the type for a member pointer to
  1166. /// the specified type in the specified class.
  1167. ///
  1168. /// The class \p Cls is a \c Type because it could be a dependent name.
  1169. QualType getMemberPointerType(QualType T, const Type *Cls) const;
  1170. /// Return a non-unique reference to the type for a variable array of
  1171. /// the specified element type.
  1172. QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
  1173. ArrayType::ArraySizeModifier ASM,
  1174. unsigned IndexTypeQuals,
  1175. SourceRange Brackets) const;
  1176. /// Return a non-unique reference to the type for a dependently-sized
  1177. /// array of the specified element type.
  1178. ///
  1179. /// FIXME: We will need these to be uniqued, or at least comparable, at some
  1180. /// point.
  1181. QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
  1182. ArrayType::ArraySizeModifier ASM,
  1183. unsigned IndexTypeQuals,
  1184. SourceRange Brackets) const;
  1185. /// Return a unique reference to the type for an incomplete array of
  1186. /// the specified element type.
  1187. QualType getIncompleteArrayType(QualType EltTy,
  1188. ArrayType::ArraySizeModifier ASM,
  1189. unsigned IndexTypeQuals) const;
  1190. /// Return the unique reference to the type for a constant array of
  1191. /// the specified element type.
  1192. QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
  1193. const Expr *SizeExpr,
  1194. ArrayType::ArraySizeModifier ASM,
  1195. unsigned IndexTypeQuals) const;
  1196. /// Return a type for a constant array for a string literal of the
  1197. /// specified element type and length.
  1198. QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const;
  1199. /// Returns a vla type where known sizes are replaced with [*].
  1200. QualType getVariableArrayDecayedType(QualType Ty) const;
  1201. // Convenience struct to return information about a builtin vector type.
  1202. struct BuiltinVectorTypeInfo {
  1203. QualType ElementType;
  1204. llvm::ElementCount EC;
  1205. unsigned NumVectors;
  1206. BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC,
  1207. unsigned NumVectors)
  1208. : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {}
  1209. };
  1210. /// Returns the element type, element count and number of vectors
  1211. /// (in case of tuple) for a builtin vector type.
  1212. BuiltinVectorTypeInfo
  1213. getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const;
  1214. /// Return the unique reference to a scalable vector type of the specified
  1215. /// element type and scalable number of elements.
  1216. ///
  1217. /// \pre \p EltTy must be a built-in type.
  1218. QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const;
  1219. /// Return the unique reference to a vector type of the specified
  1220. /// element type and size.
  1221. ///
  1222. /// \pre \p VectorType must be a built-in type.
  1223. QualType getVectorType(QualType VectorType, unsigned NumElts,
  1224. VectorType::VectorKind VecKind) const;
  1225. /// Return the unique reference to the type for a dependently sized vector of
  1226. /// the specified element type.
  1227. QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
  1228. SourceLocation AttrLoc,
  1229. VectorType::VectorKind VecKind) const;
  1230. /// Return the unique reference to an extended vector type
  1231. /// of the specified element type and size.
  1232. ///
  1233. /// \pre \p VectorType must be a built-in type.
  1234. QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
  1235. /// \pre Return a non-unique reference to the type for a dependently-sized
  1236. /// vector of the specified element type.
  1237. ///
  1238. /// FIXME: We will need these to be uniqued, or at least comparable, at some
  1239. /// point.
  1240. QualType getDependentSizedExtVectorType(QualType VectorType,
  1241. Expr *SizeExpr,
  1242. SourceLocation AttrLoc) const;
  1243. /// Return the unique reference to the matrix type of the specified element
  1244. /// type and size
  1245. ///
  1246. /// \pre \p ElementType must be a valid matrix element type (see
  1247. /// MatrixType::isValidElementType).
  1248. QualType getConstantMatrixType(QualType ElementType, unsigned NumRows,
  1249. unsigned NumColumns) const;
  1250. /// Return the unique reference to the matrix type of the specified element
  1251. /// type and size
  1252. QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
  1253. Expr *ColumnExpr,
  1254. SourceLocation AttrLoc) const;
  1255. QualType getDependentAddressSpaceType(QualType PointeeType,
  1256. Expr *AddrSpaceExpr,
  1257. SourceLocation AttrLoc) const;
  1258. /// Return a K&R style C function type like 'int()'.
  1259. QualType getFunctionNoProtoType(QualType ResultTy,
  1260. const FunctionType::ExtInfo &Info) const;
  1261. QualType getFunctionNoProtoType(QualType ResultTy) const {
  1262. return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
  1263. }
  1264. /// Return a normal function type with a typed argument list.
  1265. QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
  1266. const FunctionProtoType::ExtProtoInfo &EPI) const {
  1267. return getFunctionTypeInternal(ResultTy, Args, EPI, false);
  1268. }
  1269. QualType adjustStringLiteralBaseType(QualType StrLTy) const;
  1270. private:
  1271. /// Return a normal function type with a typed argument list.
  1272. QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
  1273. const FunctionProtoType::ExtProtoInfo &EPI,
  1274. bool OnlyWantCanonical) const;
  1275. QualType
  1276. getAutoTypeInternal(QualType DeducedType, AutoTypeKeyword Keyword,
  1277. bool IsDependent, bool IsPack = false,
  1278. ConceptDecl *TypeConstraintConcept = nullptr,
  1279. ArrayRef<TemplateArgument> TypeConstraintArgs = {},
  1280. bool IsCanon = false) const;
  1281. public:
  1282. /// Return the unique reference to the type for the specified type
  1283. /// declaration.
  1284. QualType getTypeDeclType(const TypeDecl *Decl,
  1285. const TypeDecl *PrevDecl = nullptr) const {
  1286. assert(Decl && "Passed null for Decl param");
  1287. if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
  1288. if (PrevDecl) {
  1289. assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl");
  1290. Decl->TypeForDecl = PrevDecl->TypeForDecl;
  1291. return QualType(PrevDecl->TypeForDecl, 0);
  1292. }
  1293. return getTypeDeclTypeSlow(Decl);
  1294. }
  1295. QualType getUsingType(const UsingShadowDecl *Found,
  1296. QualType Underlying) const;
  1297. /// Return the unique reference to the type for the specified
  1298. /// typedef-name decl.
  1299. QualType getTypedefType(const TypedefNameDecl *Decl,
  1300. QualType Underlying = QualType()) const;
  1301. QualType getRecordType(const RecordDecl *Decl) const;
  1302. QualType getEnumType(const EnumDecl *Decl) const;
  1303. QualType
  1304. getUnresolvedUsingType(const UnresolvedUsingTypenameDecl *Decl) const;
  1305. QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
  1306. QualType getAttributedType(attr::Kind attrKind, QualType modifiedType,
  1307. QualType equivalentType) const;
  1308. QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
  1309. QualType Wrapped);
  1310. QualType
  1311. getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl,
  1312. unsigned Index,
  1313. std::optional<unsigned> PackIndex) const;
  1314. QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
  1315. unsigned Index, bool Final,
  1316. const TemplateArgument &ArgPack);
  1317. QualType
  1318. getTemplateTypeParmType(unsigned Depth, unsigned Index,
  1319. bool ParameterPack,
  1320. TemplateTypeParmDecl *ParmDecl = nullptr) const;
  1321. QualType getTemplateSpecializationType(TemplateName T,
  1322. ArrayRef<TemplateArgument> Args,
  1323. QualType Canon = QualType()) const;
  1324. QualType
  1325. getCanonicalTemplateSpecializationType(TemplateName T,
  1326. ArrayRef<TemplateArgument> Args) const;
  1327. QualType getTemplateSpecializationType(TemplateName T,
  1328. ArrayRef<TemplateArgumentLoc> Args,
  1329. QualType Canon = QualType()) const;
  1330. TypeSourceInfo *
  1331. getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
  1332. const TemplateArgumentListInfo &Args,
  1333. QualType Canon = QualType()) const;
  1334. QualType getParenType(QualType NamedType) const;
  1335. QualType getMacroQualifiedType(QualType UnderlyingTy,
  1336. const IdentifierInfo *MacroII) const;
  1337. QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
  1338. NestedNameSpecifier *NNS, QualType NamedType,
  1339. TagDecl *OwnedTagDecl = nullptr) const;
  1340. QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
  1341. NestedNameSpecifier *NNS,
  1342. const IdentifierInfo *Name,
  1343. QualType Canon = QualType()) const;
  1344. QualType getDependentTemplateSpecializationType(
  1345. ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
  1346. const IdentifierInfo *Name, ArrayRef<TemplateArgumentLoc> Args) const;
  1347. QualType getDependentTemplateSpecializationType(
  1348. ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
  1349. const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
  1350. TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
  1351. /// Get a template argument list with one argument per template parameter
  1352. /// in a template parameter list, such as for the injected class name of
  1353. /// a class template.
  1354. void getInjectedTemplateArgs(const TemplateParameterList *Params,
  1355. SmallVectorImpl<TemplateArgument> &Args);
  1356. /// Form a pack expansion type with the given pattern.
  1357. /// \param NumExpansions The number of expansions for the pack, if known.
  1358. /// \param ExpectPackInType If \c false, we should not expect \p Pattern to
  1359. /// contain an unexpanded pack. This only makes sense if the pack
  1360. /// expansion is used in a context where the arity is inferred from
  1361. /// elsewhere, such as if the pattern contains a placeholder type or
  1362. /// if this is the canonical type of another pack expansion type.
  1363. QualType getPackExpansionType(QualType Pattern,
  1364. std::optional<unsigned> NumExpansions,
  1365. bool ExpectPackInType = true);
  1366. QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
  1367. ObjCInterfaceDecl *PrevDecl = nullptr) const;
  1368. /// Legacy interface: cannot provide type arguments or __kindof.
  1369. QualType getObjCObjectType(QualType Base,
  1370. ObjCProtocolDecl * const *Protocols,
  1371. unsigned NumProtocols) const;
  1372. QualType getObjCObjectType(QualType Base,
  1373. ArrayRef<QualType> typeArgs,
  1374. ArrayRef<ObjCProtocolDecl *> protocols,
  1375. bool isKindOf) const;
  1376. QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
  1377. ArrayRef<ObjCProtocolDecl *> protocols) const;
  1378. void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
  1379. ObjCTypeParamDecl *New) const;
  1380. bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
  1381. /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
  1382. /// QT's qualified-id protocol list adopt all protocols in IDecl's list
  1383. /// of protocols.
  1384. bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
  1385. ObjCInterfaceDecl *IDecl);
  1386. /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
  1387. QualType getObjCObjectPointerType(QualType OIT) const;
  1388. /// C2x feature and GCC extension.
  1389. QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const;
  1390. QualType getTypeOfType(QualType QT, TypeOfKind Kind) const;
  1391. QualType getReferenceQualifiedType(const Expr *e) const;
  1392. /// C++11 decltype.
  1393. QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
  1394. /// Unary type transforms
  1395. QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
  1396. UnaryTransformType::UTTKind UKind) const;
  1397. /// C++11 deduced auto type.
  1398. QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
  1399. bool IsDependent, bool IsPack = false,
  1400. ConceptDecl *TypeConstraintConcept = nullptr,
  1401. ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
  1402. /// C++11 deduction pattern for 'auto' type.
  1403. QualType getAutoDeductType() const;
  1404. /// C++11 deduction pattern for 'auto &&' type.
  1405. QualType getAutoRRefDeductType() const;
  1406. /// C++17 deduced class template specialization type.
  1407. QualType getDeducedTemplateSpecializationType(TemplateName Template,
  1408. QualType DeducedType,
  1409. bool IsDependent) const;
  1410. /// Return the unique reference to the type for the specified TagDecl
  1411. /// (struct/union/class/enum) decl.
  1412. QualType getTagDeclType(const TagDecl *Decl) const;
  1413. /// Return the unique type for "size_t" (C99 7.17), defined in
  1414. /// <stddef.h>.
  1415. ///
  1416. /// The sizeof operator requires this (C99 6.5.3.4p4).
  1417. CanQualType getSizeType() const;
  1418. /// Return the unique signed counterpart of
  1419. /// the integer type corresponding to size_t.
  1420. CanQualType getSignedSizeType() const;
  1421. /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
  1422. /// <stdint.h>.
  1423. CanQualType getIntMaxType() const;
  1424. /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
  1425. /// <stdint.h>.
  1426. CanQualType getUIntMaxType() const;
  1427. /// Return the unique wchar_t type available in C++ (and available as
  1428. /// __wchar_t as a Microsoft extension).
  1429. QualType getWCharType() const { return WCharTy; }
  1430. /// Return the type of wide characters. In C++, this returns the
  1431. /// unique wchar_t type. In C99, this returns a type compatible with the type
  1432. /// defined in <stddef.h> as defined by the target.
  1433. QualType getWideCharType() const { return WideCharTy; }
  1434. /// Return the type of "signed wchar_t".
  1435. ///
  1436. /// Used when in C++, as a GCC extension.
  1437. QualType getSignedWCharType() const;
  1438. /// Return the type of "unsigned wchar_t".
  1439. ///
  1440. /// Used when in C++, as a GCC extension.
  1441. QualType getUnsignedWCharType() const;
  1442. /// In C99, this returns a type compatible with the type
  1443. /// defined in <stddef.h> as defined by the target.
  1444. QualType getWIntType() const { return WIntTy; }
  1445. /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
  1446. /// as defined by the target.
  1447. QualType getIntPtrType() const;
  1448. /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
  1449. /// as defined by the target.
  1450. QualType getUIntPtrType() const;
  1451. /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
  1452. /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
  1453. QualType getPointerDiffType() const;
  1454. /// Return the unique unsigned counterpart of "ptrdiff_t"
  1455. /// integer type. The standard (C11 7.21.6.1p7) refers to this type
  1456. /// in the definition of %tu format specifier.
  1457. QualType getUnsignedPointerDiffType() const;
  1458. /// Return the unique type for "pid_t" defined in
  1459. /// <sys/types.h>. We need this to compute the correct type for vfork().
  1460. QualType getProcessIDType() const;
  1461. /// Return the C structure type used to represent constant CFStrings.
  1462. QualType getCFConstantStringType() const;
  1463. /// Returns the C struct type for objc_super
  1464. QualType getObjCSuperType() const;
  1465. void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
  1466. /// Get the structure type used to representation CFStrings, or NULL
  1467. /// if it hasn't yet been built.
  1468. QualType getRawCFConstantStringType() const {
  1469. if (CFConstantStringTypeDecl)
  1470. return getTypedefType(CFConstantStringTypeDecl);
  1471. return QualType();
  1472. }
  1473. void setCFConstantStringType(QualType T);
  1474. TypedefDecl *getCFConstantStringDecl() const;
  1475. RecordDecl *getCFConstantStringTagDecl() const;
  1476. // This setter/getter represents the ObjC type for an NSConstantString.
  1477. void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
  1478. QualType getObjCConstantStringInterface() const {
  1479. return ObjCConstantStringType;
  1480. }
  1481. QualType getObjCNSStringType() const {
  1482. return ObjCNSStringType;
  1483. }
  1484. void setObjCNSStringType(QualType T) {
  1485. ObjCNSStringType = T;
  1486. }
  1487. /// Retrieve the type that \c id has been defined to, which may be
  1488. /// different from the built-in \c id if \c id has been typedef'd.
  1489. QualType getObjCIdRedefinitionType() const {
  1490. if (ObjCIdRedefinitionType.isNull())
  1491. return getObjCIdType();
  1492. return ObjCIdRedefinitionType;
  1493. }
  1494. /// Set the user-written type that redefines \c id.
  1495. void setObjCIdRedefinitionType(QualType RedefType) {
  1496. ObjCIdRedefinitionType = RedefType;
  1497. }
  1498. /// Retrieve the type that \c Class has been defined to, which may be
  1499. /// different from the built-in \c Class if \c Class has been typedef'd.
  1500. QualType getObjCClassRedefinitionType() const {
  1501. if (ObjCClassRedefinitionType.isNull())
  1502. return getObjCClassType();
  1503. return ObjCClassRedefinitionType;
  1504. }
  1505. /// Set the user-written type that redefines 'SEL'.
  1506. void setObjCClassRedefinitionType(QualType RedefType) {
  1507. ObjCClassRedefinitionType = RedefType;
  1508. }
  1509. /// Retrieve the type that 'SEL' has been defined to, which may be
  1510. /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
  1511. QualType getObjCSelRedefinitionType() const {
  1512. if (ObjCSelRedefinitionType.isNull())
  1513. return getObjCSelType();
  1514. return ObjCSelRedefinitionType;
  1515. }
  1516. /// Set the user-written type that redefines 'SEL'.
  1517. void setObjCSelRedefinitionType(QualType RedefType) {
  1518. ObjCSelRedefinitionType = RedefType;
  1519. }
  1520. /// Retrieve the identifier 'NSObject'.
  1521. IdentifierInfo *getNSObjectName() const {
  1522. if (!NSObjectName) {
  1523. NSObjectName = &Idents.get("NSObject");
  1524. }
  1525. return NSObjectName;
  1526. }
  1527. /// Retrieve the identifier 'NSCopying'.
  1528. IdentifierInfo *getNSCopyingName() {
  1529. if (!NSCopyingName) {
  1530. NSCopyingName = &Idents.get("NSCopying");
  1531. }
  1532. return NSCopyingName;
  1533. }
  1534. CanQualType getNSUIntegerType() const;
  1535. CanQualType getNSIntegerType() const;
  1536. /// Retrieve the identifier 'bool'.
  1537. IdentifierInfo *getBoolName() const {
  1538. if (!BoolName)
  1539. BoolName = &Idents.get("bool");
  1540. return BoolName;
  1541. }
  1542. IdentifierInfo *getMakeIntegerSeqName() const {
  1543. if (!MakeIntegerSeqName)
  1544. MakeIntegerSeqName = &Idents.get("__make_integer_seq");
  1545. return MakeIntegerSeqName;
  1546. }
  1547. IdentifierInfo *getTypePackElementName() const {
  1548. if (!TypePackElementName)
  1549. TypePackElementName = &Idents.get("__type_pack_element");
  1550. return TypePackElementName;
  1551. }
  1552. /// Retrieve the Objective-C "instancetype" type, if already known;
  1553. /// otherwise, returns a NULL type;
  1554. QualType getObjCInstanceType() {
  1555. return getTypeDeclType(getObjCInstanceTypeDecl());
  1556. }
  1557. /// Retrieve the typedef declaration corresponding to the Objective-C
  1558. /// "instancetype" type.
  1559. TypedefDecl *getObjCInstanceTypeDecl();
  1560. /// Set the type for the C FILE type.
  1561. void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
  1562. /// Retrieve the C FILE type.
  1563. QualType getFILEType() const {
  1564. if (FILEDecl)
  1565. return getTypeDeclType(FILEDecl);
  1566. return QualType();
  1567. }
  1568. /// Set the type for the C jmp_buf type.
  1569. void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
  1570. this->jmp_bufDecl = jmp_bufDecl;
  1571. }
  1572. /// Retrieve the C jmp_buf type.
  1573. QualType getjmp_bufType() const {
  1574. if (jmp_bufDecl)
  1575. return getTypeDeclType(jmp_bufDecl);
  1576. return QualType();
  1577. }
  1578. /// Set the type for the C sigjmp_buf type.
  1579. void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
  1580. this->sigjmp_bufDecl = sigjmp_bufDecl;
  1581. }
  1582. /// Retrieve the C sigjmp_buf type.
  1583. QualType getsigjmp_bufType() const {
  1584. if (sigjmp_bufDecl)
  1585. return getTypeDeclType(sigjmp_bufDecl);
  1586. return QualType();
  1587. }
  1588. /// Set the type for the C ucontext_t type.
  1589. void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
  1590. this->ucontext_tDecl = ucontext_tDecl;
  1591. }
  1592. /// Retrieve the C ucontext_t type.
  1593. QualType getucontext_tType() const {
  1594. if (ucontext_tDecl)
  1595. return getTypeDeclType(ucontext_tDecl);
  1596. return QualType();
  1597. }
  1598. /// The result type of logical operations, '<', '>', '!=', etc.
  1599. QualType getLogicalOperationType() const {
  1600. return getLangOpts().CPlusPlus ? BoolTy : IntTy;
  1601. }
  1602. /// Emit the Objective-CC type encoding for the given type \p T into
  1603. /// \p S.
  1604. ///
  1605. /// If \p Field is specified then record field names are also encoded.
  1606. void getObjCEncodingForType(QualType T, std::string &S,
  1607. const FieldDecl *Field=nullptr,
  1608. QualType *NotEncodedT=nullptr) const;
  1609. /// Emit the Objective-C property type encoding for the given
  1610. /// type \p T into \p S.
  1611. void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
  1612. void getLegacyIntegralTypeEncoding(QualType &t) const;
  1613. /// Put the string version of the type qualifiers \p QT into \p S.
  1614. void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
  1615. std::string &S) const;
  1616. /// Emit the encoded type for the function \p Decl into \p S.
  1617. ///
  1618. /// This is in the same format as Objective-C method encodings.
  1619. ///
  1620. /// \returns true if an error occurred (e.g., because one of the parameter
  1621. /// types is incomplete), false otherwise.
  1622. std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
  1623. /// Emit the encoded type for the method declaration \p Decl into
  1624. /// \p S.
  1625. std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
  1626. bool Extended = false) const;
  1627. /// Return the encoded type for this block declaration.
  1628. std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
  1629. /// getObjCEncodingForPropertyDecl - Return the encoded type for
  1630. /// this method declaration. If non-NULL, Container must be either
  1631. /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
  1632. /// only be NULL when getting encodings for protocol properties.
  1633. std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
  1634. const Decl *Container) const;
  1635. bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
  1636. ObjCProtocolDecl *rProto) const;
  1637. ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
  1638. const ObjCPropertyDecl *PD,
  1639. const Decl *Container) const;
  1640. /// Return the size of type \p T for Objective-C encoding purpose,
  1641. /// in characters.
  1642. CharUnits getObjCEncodingTypeSize(QualType T) const;
  1643. /// Retrieve the typedef corresponding to the predefined \c id type
  1644. /// in Objective-C.
  1645. TypedefDecl *getObjCIdDecl() const;
  1646. /// Represents the Objective-CC \c id type.
  1647. ///
  1648. /// This is set up lazily, by Sema. \c id is always a (typedef for a)
  1649. /// pointer type, a pointer to a struct.
  1650. QualType getObjCIdType() const {
  1651. return getTypeDeclType(getObjCIdDecl());
  1652. }
  1653. /// Retrieve the typedef corresponding to the predefined 'SEL' type
  1654. /// in Objective-C.
  1655. TypedefDecl *getObjCSelDecl() const;
  1656. /// Retrieve the type that corresponds to the predefined Objective-C
  1657. /// 'SEL' type.
  1658. QualType getObjCSelType() const {
  1659. return getTypeDeclType(getObjCSelDecl());
  1660. }
  1661. /// Retrieve the typedef declaration corresponding to the predefined
  1662. /// Objective-C 'Class' type.
  1663. TypedefDecl *getObjCClassDecl() const;
  1664. /// Represents the Objective-C \c Class type.
  1665. ///
  1666. /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
  1667. /// pointer type, a pointer to a struct.
  1668. QualType getObjCClassType() const {
  1669. return getTypeDeclType(getObjCClassDecl());
  1670. }
  1671. /// Retrieve the Objective-C class declaration corresponding to
  1672. /// the predefined \c Protocol class.
  1673. ObjCInterfaceDecl *getObjCProtocolDecl() const;
  1674. /// Retrieve declaration of 'BOOL' typedef
  1675. TypedefDecl *getBOOLDecl() const {
  1676. return BOOLDecl;
  1677. }
  1678. /// Save declaration of 'BOOL' typedef
  1679. void setBOOLDecl(TypedefDecl *TD) {
  1680. BOOLDecl = TD;
  1681. }
  1682. /// type of 'BOOL' type.
  1683. QualType getBOOLType() const {
  1684. return getTypeDeclType(getBOOLDecl());
  1685. }
  1686. /// Retrieve the type of the Objective-C \c Protocol class.
  1687. QualType getObjCProtoType() const {
  1688. return getObjCInterfaceType(getObjCProtocolDecl());
  1689. }
  1690. /// Retrieve the C type declaration corresponding to the predefined
  1691. /// \c __builtin_va_list type.
  1692. TypedefDecl *getBuiltinVaListDecl() const;
  1693. /// Retrieve the type of the \c __builtin_va_list type.
  1694. QualType getBuiltinVaListType() const {
  1695. return getTypeDeclType(getBuiltinVaListDecl());
  1696. }
  1697. /// Retrieve the C type declaration corresponding to the predefined
  1698. /// \c __va_list_tag type used to help define the \c __builtin_va_list type
  1699. /// for some targets.
  1700. Decl *getVaListTagDecl() const;
  1701. /// Retrieve the C type declaration corresponding to the predefined
  1702. /// \c __builtin_ms_va_list type.
  1703. TypedefDecl *getBuiltinMSVaListDecl() const;
  1704. /// Retrieve the type of the \c __builtin_ms_va_list type.
  1705. QualType getBuiltinMSVaListType() const {
  1706. return getTypeDeclType(getBuiltinMSVaListDecl());
  1707. }
  1708. /// Retrieve the implicitly-predeclared 'struct _GUID' declaration.
  1709. TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; }
  1710. /// Retrieve the implicitly-predeclared 'struct _GUID' type.
  1711. QualType getMSGuidType() const {
  1712. assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled");
  1713. return getTagDeclType(MSGuidTagDecl);
  1714. }
  1715. /// Return whether a declaration to a builtin is allowed to be
  1716. /// overloaded/redeclared.
  1717. bool canBuiltinBeRedeclared(const FunctionDecl *) const;
  1718. /// Return a type with additional \c const, \c volatile, or
  1719. /// \c restrict qualifiers.
  1720. QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
  1721. return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
  1722. }
  1723. /// Un-split a SplitQualType.
  1724. QualType getQualifiedType(SplitQualType split) const {
  1725. return getQualifiedType(split.Ty, split.Quals);
  1726. }
  1727. /// Return a type with additional qualifiers.
  1728. QualType getQualifiedType(QualType T, Qualifiers Qs) const {
  1729. if (!Qs.hasNonFastQualifiers())
  1730. return T.withFastQualifiers(Qs.getFastQualifiers());
  1731. QualifierCollector Qc(Qs);
  1732. const Type *Ptr = Qc.strip(T);
  1733. return getExtQualType(Ptr, Qc);
  1734. }
  1735. /// Return a type with additional qualifiers.
  1736. QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
  1737. if (!Qs.hasNonFastQualifiers())
  1738. return QualType(T, Qs.getFastQualifiers());
  1739. return getExtQualType(T, Qs);
  1740. }
  1741. /// Return a type with the given lifetime qualifier.
  1742. ///
  1743. /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
  1744. QualType getLifetimeQualifiedType(QualType type,
  1745. Qualifiers::ObjCLifetime lifetime) {
  1746. assert(type.getObjCLifetime() == Qualifiers::OCL_None);
  1747. assert(lifetime != Qualifiers::OCL_None);
  1748. Qualifiers qs;
  1749. qs.addObjCLifetime(lifetime);
  1750. return getQualifiedType(type, qs);
  1751. }
  1752. /// getUnqualifiedObjCPointerType - Returns version of
  1753. /// Objective-C pointer type with lifetime qualifier removed.
  1754. QualType getUnqualifiedObjCPointerType(QualType type) const {
  1755. if (!type.getTypePtr()->isObjCObjectPointerType() ||
  1756. !type.getQualifiers().hasObjCLifetime())
  1757. return type;
  1758. Qualifiers Qs = type.getQualifiers();
  1759. Qs.removeObjCLifetime();
  1760. return getQualifiedType(type.getUnqualifiedType(), Qs);
  1761. }
  1762. unsigned char getFixedPointScale(QualType Ty) const;
  1763. unsigned char getFixedPointIBits(QualType Ty) const;
  1764. llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
  1765. llvm::APFixedPoint getFixedPointMax(QualType Ty) const;
  1766. llvm::APFixedPoint getFixedPointMin(QualType Ty) const;
  1767. DeclarationNameInfo getNameForTemplate(TemplateName Name,
  1768. SourceLocation NameLoc) const;
  1769. TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
  1770. UnresolvedSetIterator End) const;
  1771. TemplateName getAssumedTemplateName(DeclarationName Name) const;
  1772. TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
  1773. bool TemplateKeyword,
  1774. TemplateName Template) const;
  1775. TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
  1776. const IdentifierInfo *Name) const;
  1777. TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
  1778. OverloadedOperatorKind Operator) const;
  1779. TemplateName
  1780. getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl,
  1781. unsigned Index,
  1782. std::optional<unsigned> PackIndex) const;
  1783. TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack,
  1784. Decl *AssociatedDecl,
  1785. unsigned Index,
  1786. bool Final) const;
  1787. enum GetBuiltinTypeError {
  1788. /// No error
  1789. GE_None,
  1790. /// Missing a type
  1791. GE_Missing_type,
  1792. /// Missing a type from <stdio.h>
  1793. GE_Missing_stdio,
  1794. /// Missing a type from <setjmp.h>
  1795. GE_Missing_setjmp,
  1796. /// Missing a type from <ucontext.h>
  1797. GE_Missing_ucontext
  1798. };
  1799. QualType DecodeTypeStr(const char *&Str, const ASTContext &Context,
  1800. ASTContext::GetBuiltinTypeError &Error,
  1801. bool &RequireICE, bool AllowTypeModifiers) const;
  1802. /// Return the type for the specified builtin.
  1803. ///
  1804. /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
  1805. /// arguments to the builtin that are required to be integer constant
  1806. /// expressions.
  1807. QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
  1808. unsigned *IntegerConstantArgs = nullptr) const;
  1809. /// Types and expressions required to build C++2a three-way comparisons
  1810. /// using operator<=>, including the values return by builtin <=> operators.
  1811. ComparisonCategories CompCategories;
  1812. private:
  1813. CanQualType getFromTargetType(unsigned Type) const;
  1814. TypeInfo getTypeInfoImpl(const Type *T) const;
  1815. //===--------------------------------------------------------------------===//
  1816. // Type Predicates.
  1817. //===--------------------------------------------------------------------===//
  1818. public:
  1819. /// Return one of the GCNone, Weak or Strong Objective-C garbage
  1820. /// collection attributes.
  1821. Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
  1822. /// Return true if the given vector types are of the same unqualified
  1823. /// type or if they are equivalent to the same GCC vector type.
  1824. ///
  1825. /// \note This ignores whether they are target-specific (AltiVec or Neon)
  1826. /// types.
  1827. bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
  1828. /// Return true if the given types are an SVE builtin and a VectorType that
  1829. /// is a fixed-length representation of the SVE builtin for a specific
  1830. /// vector-length.
  1831. bool areCompatibleSveTypes(QualType FirstType, QualType SecondType);
  1832. /// Return true if the given vector types are lax-compatible SVE vector types,
  1833. /// false otherwise.
  1834. bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType);
  1835. /// Return true if the type has been explicitly qualified with ObjC ownership.
  1836. /// A type may be implicitly qualified with ownership under ObjC ARC, and in
  1837. /// some cases the compiler treats these differently.
  1838. bool hasDirectOwnershipQualifier(QualType Ty) const;
  1839. /// Return true if this is an \c NSObject object with its \c NSObject
  1840. /// attribute set.
  1841. static bool isObjCNSObjectType(QualType Ty) {
  1842. return Ty->isObjCNSObjectType();
  1843. }
  1844. //===--------------------------------------------------------------------===//
  1845. // Type Sizing and Analysis
  1846. //===--------------------------------------------------------------------===//
  1847. /// Return the APFloat 'semantics' for the specified scalar floating
  1848. /// point type.
  1849. const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
  1850. /// Get the size and alignment of the specified complete type in bits.
  1851. TypeInfo getTypeInfo(const Type *T) const;
  1852. TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
  1853. /// Get default simd alignment of the specified complete type in bits.
  1854. unsigned getOpenMPDefaultSimdAlign(QualType T) const;
  1855. /// Return the size of the specified (complete) type \p T, in bits.
  1856. uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
  1857. uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
  1858. /// Return the size of the character type, in bits.
  1859. uint64_t getCharWidth() const {
  1860. return getTypeSize(CharTy);
  1861. }
  1862. /// Convert a size in bits to a size in characters.
  1863. CharUnits toCharUnitsFromBits(int64_t BitSize) const;
  1864. /// Convert a size in characters to a size in bits.
  1865. int64_t toBits(CharUnits CharSize) const;
  1866. /// Return the size of the specified (complete) type \p T, in
  1867. /// characters.
  1868. CharUnits getTypeSizeInChars(QualType T) const;
  1869. CharUnits getTypeSizeInChars(const Type *T) const;
  1870. std::optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
  1871. if (Ty->isIncompleteType() || Ty->isDependentType())
  1872. return std::nullopt;
  1873. return getTypeSizeInChars(Ty);
  1874. }
  1875. std::optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
  1876. return getTypeSizeInCharsIfKnown(QualType(Ty, 0));
  1877. }
  1878. /// Return the ABI-specified alignment of a (complete) type \p T, in
  1879. /// bits.
  1880. unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
  1881. unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
  1882. /// Return the ABI-specified natural alignment of a (complete) type \p T,
  1883. /// before alignment adjustments, in bits.
  1884. ///
  1885. /// This alignment is curently used only by ARM and AArch64 when passing
  1886. /// arguments of a composite type.
  1887. unsigned getTypeUnadjustedAlign(QualType T) const {
  1888. return getTypeUnadjustedAlign(T.getTypePtr());
  1889. }
  1890. unsigned getTypeUnadjustedAlign(const Type *T) const;
  1891. /// Return the alignment of a type, in bits, or 0 if
  1892. /// the type is incomplete and we cannot determine the alignment (for
  1893. /// example, from alignment attributes). The returned alignment is the
  1894. /// Preferred alignment if NeedsPreferredAlignment is true, otherwise is the
  1895. /// ABI alignment.
  1896. unsigned getTypeAlignIfKnown(QualType T,
  1897. bool NeedsPreferredAlignment = false) const;
  1898. /// Return the ABI-specified alignment of a (complete) type \p T, in
  1899. /// characters.
  1900. CharUnits getTypeAlignInChars(QualType T) const;
  1901. CharUnits getTypeAlignInChars(const Type *T) const;
  1902. /// Return the PreferredAlignment of a (complete) type \p T, in
  1903. /// characters.
  1904. CharUnits getPreferredTypeAlignInChars(QualType T) const {
  1905. return toCharUnitsFromBits(getPreferredTypeAlign(T));
  1906. }
  1907. /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
  1908. /// in characters, before alignment adjustments. This method does not work on
  1909. /// incomplete types.
  1910. CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
  1911. CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
  1912. // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
  1913. // type is a record, its data size is returned.
  1914. TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const;
  1915. TypeInfoChars getTypeInfoInChars(const Type *T) const;
  1916. TypeInfoChars getTypeInfoInChars(QualType T) const;
  1917. /// Determine if the alignment the type has was required using an
  1918. /// alignment attribute.
  1919. bool isAlignmentRequired(const Type *T) const;
  1920. bool isAlignmentRequired(QualType T) const;
  1921. /// More type predicates useful for type checking/promotion
  1922. bool isPromotableIntegerType(QualType T) const; // C99 6.3.1.1p2
  1923. /// Return the "preferred" alignment of the specified type \p T for
  1924. /// the current target, in bits.
  1925. ///
  1926. /// This can be different than the ABI alignment in cases where it is
  1927. /// beneficial for performance or backwards compatibility preserving to
  1928. /// overalign a data type. (Note: despite the name, the preferred alignment
  1929. /// is ABI-impacting, and not an optimization.)
  1930. unsigned getPreferredTypeAlign(QualType T) const {
  1931. return getPreferredTypeAlign(T.getTypePtr());
  1932. }
  1933. unsigned getPreferredTypeAlign(const Type *T) const;
  1934. /// Return the default alignment for __attribute__((aligned)) on
  1935. /// this target, to be used if no alignment value is specified.
  1936. unsigned getTargetDefaultAlignForAttributeAligned() const;
  1937. /// Return the alignment in bits that should be given to a
  1938. /// global variable with type \p T.
  1939. unsigned getAlignOfGlobalVar(QualType T) const;
  1940. /// Return the alignment in characters that should be given to a
  1941. /// global variable with type \p T.
  1942. CharUnits getAlignOfGlobalVarInChars(QualType T) const;
  1943. /// Return a conservative estimate of the alignment of the specified
  1944. /// decl \p D.
  1945. ///
  1946. /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
  1947. /// alignment.
  1948. ///
  1949. /// If \p ForAlignof, references are treated like their underlying type
  1950. /// and large arrays don't get any special treatment. If not \p ForAlignof
  1951. /// it computes the value expected by CodeGen: references are treated like
  1952. /// pointers and large arrays get extra alignment.
  1953. CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
  1954. /// Return the alignment (in bytes) of the thrown exception object. This is
  1955. /// only meaningful for targets that allocate C++ exceptions in a system
  1956. /// runtime, such as those using the Itanium C++ ABI.
  1957. CharUnits getExnObjectAlignment() const;
  1958. /// Get or compute information about the layout of the specified
  1959. /// record (struct/union/class) \p D, which indicates its size and field
  1960. /// position information.
  1961. const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
  1962. /// Get or compute information about the layout of the specified
  1963. /// Objective-C interface.
  1964. const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
  1965. const;
  1966. void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
  1967. bool Simple = false) const;
  1968. /// Get or compute information about the layout of the specified
  1969. /// Objective-C implementation.
  1970. ///
  1971. /// This may differ from the interface if synthesized ivars are present.
  1972. const ASTRecordLayout &
  1973. getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
  1974. /// Get our current best idea for the key function of the
  1975. /// given record decl, or nullptr if there isn't one.
  1976. ///
  1977. /// The key function is, according to the Itanium C++ ABI section 5.2.3:
  1978. /// ...the first non-pure virtual function that is not inline at the
  1979. /// point of class definition.
  1980. ///
  1981. /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
  1982. /// virtual functions that are defined 'inline', which means that
  1983. /// the result of this computation can change.
  1984. const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
  1985. /// Observe that the given method cannot be a key function.
  1986. /// Checks the key-function cache for the method's class and clears it
  1987. /// if matches the given declaration.
  1988. ///
  1989. /// This is used in ABIs where out-of-line definitions marked
  1990. /// inline are not considered to be key functions.
  1991. ///
  1992. /// \param method should be the declaration from the class definition
  1993. void setNonKeyFunction(const CXXMethodDecl *method);
  1994. /// Loading virtual member pointers using the virtual inheritance model
  1995. /// always results in an adjustment using the vbtable even if the index is
  1996. /// zero.
  1997. ///
  1998. /// This is usually OK because the first slot in the vbtable points
  1999. /// backwards to the top of the MDC. However, the MDC might be reusing a
  2000. /// vbptr from an nv-base. In this case, the first slot in the vbtable
  2001. /// points to the start of the nv-base which introduced the vbptr and *not*
  2002. /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
  2003. CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
  2004. /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
  2005. uint64_t getFieldOffset(const ValueDecl *FD) const;
  2006. /// Get the offset of an ObjCIvarDecl in bits.
  2007. uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
  2008. const ObjCImplementationDecl *ID,
  2009. const ObjCIvarDecl *Ivar) const;
  2010. /// Find the 'this' offset for the member path in a pointer-to-member
  2011. /// APValue.
  2012. CharUnits getMemberPointerPathAdjustment(const APValue &MP) const;
  2013. bool isNearlyEmpty(const CXXRecordDecl *RD) const;
  2014. VTableContextBase *getVTableContext();
  2015. /// If \p T is null pointer, assume the target in ASTContext.
  2016. MangleContext *createMangleContext(const TargetInfo *T = nullptr);
  2017. /// Creates a device mangle context to correctly mangle lambdas in a mixed
  2018. /// architecture compile by setting the lambda mangling number source to the
  2019. /// DeviceLambdaManglingNumber. Currently this asserts that the TargetInfo
  2020. /// (from the AuxTargetInfo) is a an itanium target.
  2021. MangleContext *createDeviceMangleContext(const TargetInfo &T);
  2022. void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
  2023. SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
  2024. unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
  2025. void CollectInheritedProtocols(const Decl *CDecl,
  2026. llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
  2027. /// Return true if the specified type has unique object representations
  2028. /// according to (C++17 [meta.unary.prop]p9)
  2029. bool hasUniqueObjectRepresentations(QualType Ty) const;
  2030. //===--------------------------------------------------------------------===//
  2031. // Type Operators
  2032. //===--------------------------------------------------------------------===//
  2033. /// Return the canonical (structural) type corresponding to the
  2034. /// specified potentially non-canonical type \p T.
  2035. ///
  2036. /// The non-canonical version of a type may have many "decorated" versions of
  2037. /// types. Decorators can include typedefs, 'typeof' operators, etc. The
  2038. /// returned type is guaranteed to be free of any of these, allowing two
  2039. /// canonical types to be compared for exact equality with a simple pointer
  2040. /// comparison.
  2041. CanQualType getCanonicalType(QualType T) const {
  2042. return CanQualType::CreateUnsafe(T.getCanonicalType());
  2043. }
  2044. const Type *getCanonicalType(const Type *T) const {
  2045. return T->getCanonicalTypeInternal().getTypePtr();
  2046. }
  2047. /// Return the canonical parameter type corresponding to the specific
  2048. /// potentially non-canonical one.
  2049. ///
  2050. /// Qualifiers are stripped off, functions are turned into function
  2051. /// pointers, and arrays decay one level into pointers.
  2052. CanQualType getCanonicalParamType(QualType T) const;
  2053. /// Determine whether the given types \p T1 and \p T2 are equivalent.
  2054. bool hasSameType(QualType T1, QualType T2) const {
  2055. return getCanonicalType(T1) == getCanonicalType(T2);
  2056. }
  2057. bool hasSameType(const Type *T1, const Type *T2) const {
  2058. return getCanonicalType(T1) == getCanonicalType(T2);
  2059. }
  2060. /// Determine whether the given expressions \p X and \p Y are equivalent.
  2061. bool hasSameExpr(const Expr *X, const Expr *Y) const;
  2062. /// Return this type as a completely-unqualified array type,
  2063. /// capturing the qualifiers in \p Quals.
  2064. ///
  2065. /// This will remove the minimal amount of sugaring from the types, similar
  2066. /// to the behavior of QualType::getUnqualifiedType().
  2067. ///
  2068. /// \param T is the qualified type, which may be an ArrayType
  2069. ///
  2070. /// \param Quals will receive the full set of qualifiers that were
  2071. /// applied to the array.
  2072. ///
  2073. /// \returns if this is an array type, the completely unqualified array type
  2074. /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
  2075. QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
  2076. /// Determine whether the given types are equivalent after
  2077. /// cvr-qualifiers have been removed.
  2078. bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
  2079. return getCanonicalType(T1).getTypePtr() ==
  2080. getCanonicalType(T2).getTypePtr();
  2081. }
  2082. bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
  2083. bool IsParam) const {
  2084. auto SubTnullability = SubT->getNullability();
  2085. auto SuperTnullability = SuperT->getNullability();
  2086. if (SubTnullability.has_value() == SuperTnullability.has_value()) {
  2087. // Neither has nullability; return true
  2088. if (!SubTnullability)
  2089. return true;
  2090. // Both have nullability qualifier.
  2091. if (*SubTnullability == *SuperTnullability ||
  2092. *SubTnullability == NullabilityKind::Unspecified ||
  2093. *SuperTnullability == NullabilityKind::Unspecified)
  2094. return true;
  2095. if (IsParam) {
  2096. // Ok for the superclass method parameter to be "nonnull" and the subclass
  2097. // method parameter to be "nullable"
  2098. return (*SuperTnullability == NullabilityKind::NonNull &&
  2099. *SubTnullability == NullabilityKind::Nullable);
  2100. }
  2101. // For the return type, it's okay for the superclass method to specify
  2102. // "nullable" and the subclass method specify "nonnull"
  2103. return (*SuperTnullability == NullabilityKind::Nullable &&
  2104. *SubTnullability == NullabilityKind::NonNull);
  2105. }
  2106. return true;
  2107. }
  2108. bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
  2109. const ObjCMethodDecl *MethodImp);
  2110. bool UnwrapSimilarTypes(QualType &T1, QualType &T2,
  2111. bool AllowPiMismatch = true);
  2112. void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2,
  2113. bool AllowPiMismatch = true);
  2114. /// Determine if two types are similar, according to the C++ rules. That is,
  2115. /// determine if they are the same other than qualifiers on the initial
  2116. /// sequence of pointer / pointer-to-member / array (and in Clang, object
  2117. /// pointer) types and their element types.
  2118. ///
  2119. /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
  2120. /// those qualifiers are also ignored in the 'similarity' check.
  2121. bool hasSimilarType(QualType T1, QualType T2);
  2122. /// Determine if two types are similar, ignoring only CVR qualifiers.
  2123. bool hasCvrSimilarType(QualType T1, QualType T2);
  2124. /// Retrieves the "canonical" nested name specifier for a
  2125. /// given nested name specifier.
  2126. ///
  2127. /// The canonical nested name specifier is a nested name specifier
  2128. /// that uniquely identifies a type or namespace within the type
  2129. /// system. For example, given:
  2130. ///
  2131. /// \code
  2132. /// namespace N {
  2133. /// struct S {
  2134. /// template<typename T> struct X { typename T* type; };
  2135. /// };
  2136. /// }
  2137. ///
  2138. /// template<typename T> struct Y {
  2139. /// typename N::S::X<T>::type member;
  2140. /// };
  2141. /// \endcode
  2142. ///
  2143. /// Here, the nested-name-specifier for N::S::X<T>:: will be
  2144. /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
  2145. /// by declarations in the type system and the canonical type for
  2146. /// the template type parameter 'T' is template-param-0-0.
  2147. NestedNameSpecifier *
  2148. getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
  2149. /// Retrieves the default calling convention for the current target.
  2150. CallingConv getDefaultCallingConvention(bool IsVariadic,
  2151. bool IsCXXMethod,
  2152. bool IsBuiltin = false) const;
  2153. /// Retrieves the "canonical" template name that refers to a
  2154. /// given template.
  2155. ///
  2156. /// The canonical template name is the simplest expression that can
  2157. /// be used to refer to a given template. For most templates, this
  2158. /// expression is just the template declaration itself. For example,
  2159. /// the template std::vector can be referred to via a variety of
  2160. /// names---std::vector, \::std::vector, vector (if vector is in
  2161. /// scope), etc.---but all of these names map down to the same
  2162. /// TemplateDecl, which is used to form the canonical template name.
  2163. ///
  2164. /// Dependent template names are more interesting. Here, the
  2165. /// template name could be something like T::template apply or
  2166. /// std::allocator<T>::template rebind, where the nested name
  2167. /// specifier itself is dependent. In this case, the canonical
  2168. /// template name uses the shortest form of the dependent
  2169. /// nested-name-specifier, which itself contains all canonical
  2170. /// types, values, and templates.
  2171. TemplateName getCanonicalTemplateName(const TemplateName &Name) const;
  2172. /// Determine whether the given template names refer to the same
  2173. /// template.
  2174. bool hasSameTemplateName(const TemplateName &X, const TemplateName &Y) const;
  2175. /// Determine whether two Friend functions are different because constraints
  2176. /// that refer to an enclosing template, according to [temp.friend] p9.
  2177. bool FriendsDifferByConstraints(const FunctionDecl *X,
  2178. const FunctionDecl *Y) const;
  2179. /// Determine whether the two declarations refer to the same entity.
  2180. bool isSameEntity(const NamedDecl *X, const NamedDecl *Y) const;
  2181. /// Determine whether two template parameter lists are similar enough
  2182. /// that they may be used in declarations of the same template.
  2183. bool isSameTemplateParameterList(const TemplateParameterList *X,
  2184. const TemplateParameterList *Y) const;
  2185. /// Determine whether two template parameters are similar enough
  2186. /// that they may be used in declarations of the same template.
  2187. bool isSameTemplateParameter(const NamedDecl *X, const NamedDecl *Y) const;
  2188. /// Determine whether two 'requires' expressions are similar enough that they
  2189. /// may be used in re-declarations.
  2190. ///
  2191. /// Use of 'requires' isn't mandatory, works with constraints expressed in
  2192. /// other ways too.
  2193. bool isSameConstraintExpr(const Expr *XCE, const Expr *YCE) const;
  2194. /// Determine whether two type contraint are similar enough that they could
  2195. /// used in declarations of the same template.
  2196. bool isSameTypeConstraint(const TypeConstraint *XTC,
  2197. const TypeConstraint *YTC) const;
  2198. /// Determine whether two default template arguments are similar enough
  2199. /// that they may be used in declarations of the same template.
  2200. bool isSameDefaultTemplateArgument(const NamedDecl *X,
  2201. const NamedDecl *Y) const;
  2202. /// Retrieve the "canonical" template argument.
  2203. ///
  2204. /// The canonical template argument is the simplest template argument
  2205. /// (which may be a type, value, expression, or declaration) that
  2206. /// expresses the value of the argument.
  2207. TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
  2208. const;
  2209. /// Type Query functions. If the type is an instance of the specified class,
  2210. /// return the Type pointer for the underlying maximally pretty type. This
  2211. /// is a member of ASTContext because this may need to do some amount of
  2212. /// canonicalization, e.g. to move type qualifiers into the element type.
  2213. const ArrayType *getAsArrayType(QualType T) const;
  2214. const ConstantArrayType *getAsConstantArrayType(QualType T) const {
  2215. return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
  2216. }
  2217. const VariableArrayType *getAsVariableArrayType(QualType T) const {
  2218. return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
  2219. }
  2220. const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
  2221. return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
  2222. }
  2223. const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
  2224. const {
  2225. return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
  2226. }
  2227. /// Return the innermost element type of an array type.
  2228. ///
  2229. /// For example, will return "int" for int[m][n]
  2230. QualType getBaseElementType(const ArrayType *VAT) const;
  2231. /// Return the innermost element type of a type (which needn't
  2232. /// actually be an array type).
  2233. QualType getBaseElementType(QualType QT) const;
  2234. /// Return number of constant array elements.
  2235. uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
  2236. /// Return number of elements initialized in an ArrayInitLoopExpr.
  2237. uint64_t
  2238. getArrayInitLoopExprElementCount(const ArrayInitLoopExpr *AILE) const;
  2239. /// Perform adjustment on the parameter type of a function.
  2240. ///
  2241. /// This routine adjusts the given parameter type @p T to the actual
  2242. /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
  2243. /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
  2244. QualType getAdjustedParameterType(QualType T) const;
  2245. /// Retrieve the parameter type as adjusted for use in the signature
  2246. /// of a function, decaying array and function types and removing top-level
  2247. /// cv-qualifiers.
  2248. QualType getSignatureParameterType(QualType T) const;
  2249. QualType getExceptionObjectType(QualType T) const;
  2250. /// Return the properly qualified result of decaying the specified
  2251. /// array type to a pointer.
  2252. ///
  2253. /// This operation is non-trivial when handling typedefs etc. The canonical
  2254. /// type of \p T must be an array type, this returns a pointer to a properly
  2255. /// qualified element of the array.
  2256. ///
  2257. /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
  2258. QualType getArrayDecayedType(QualType T) const;
  2259. /// Return the type that \p PromotableType will promote to: C99
  2260. /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
  2261. QualType getPromotedIntegerType(QualType PromotableType) const;
  2262. /// Recurses in pointer/array types until it finds an Objective-C
  2263. /// retainable type and returns its ownership.
  2264. Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
  2265. /// Whether this is a promotable bitfield reference according
  2266. /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
  2267. ///
  2268. /// \returns the type this bit-field will promote to, or NULL if no
  2269. /// promotion occurs.
  2270. QualType isPromotableBitField(Expr *E) const;
  2271. /// Return the highest ranked integer type, see C99 6.3.1.8p1.
  2272. ///
  2273. /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
  2274. /// \p LHS < \p RHS, return -1.
  2275. int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
  2276. /// Compare the rank of the two specified floating point types,
  2277. /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
  2278. ///
  2279. /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
  2280. /// \p LHS < \p RHS, return -1.
  2281. int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
  2282. /// Compare the rank of two floating point types as above, but compare equal
  2283. /// if both types have the same floating-point semantics on the target (i.e.
  2284. /// long double and double on AArch64 will return 0).
  2285. int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
  2286. unsigned getTargetAddressSpace(LangAS AS) const;
  2287. LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
  2288. /// Get target-dependent integer value for null pointer which is used for
  2289. /// constant folding.
  2290. uint64_t getTargetNullPointerValue(QualType QT) const;
  2291. bool addressSpaceMapManglingFor(LangAS AS) const {
  2292. return AddrSpaceMapMangling || isTargetAddressSpace(AS);
  2293. }
  2294. // Merges two exception specifications, such that the resulting
  2295. // exception spec is the union of both. For example, if either
  2296. // of them can throw something, the result can throw it as well.
  2297. FunctionProtoType::ExceptionSpecInfo
  2298. mergeExceptionSpecs(FunctionProtoType::ExceptionSpecInfo ESI1,
  2299. FunctionProtoType::ExceptionSpecInfo ESI2,
  2300. SmallVectorImpl<QualType> &ExceptionTypeStorage,
  2301. bool AcceptDependent);
  2302. // For two "same" types, return a type which has
  2303. // the common sugar between them. If Unqualified is true,
  2304. // both types need only be the same unqualified type.
  2305. // The result will drop the qualifiers which do not occur
  2306. // in both types.
  2307. QualType getCommonSugaredType(QualType X, QualType Y,
  2308. bool Unqualified = false);
  2309. private:
  2310. // Helper for integer ordering
  2311. unsigned getIntegerRank(const Type *T) const;
  2312. public:
  2313. //===--------------------------------------------------------------------===//
  2314. // Type Compatibility Predicates
  2315. //===--------------------------------------------------------------------===//
  2316. /// Compatibility predicates used to check assignment expressions.
  2317. bool typesAreCompatible(QualType T1, QualType T2,
  2318. bool CompareUnqualified = false); // C99 6.2.7p1
  2319. bool propertyTypesAreCompatible(QualType, QualType);
  2320. bool typesAreBlockPointerCompatible(QualType, QualType);
  2321. bool isObjCIdType(QualType T) const {
  2322. if (const auto *ET = dyn_cast<ElaboratedType>(T))
  2323. T = ET->getNamedType();
  2324. return T == getObjCIdType();
  2325. }
  2326. bool isObjCClassType(QualType T) const {
  2327. if (const auto *ET = dyn_cast<ElaboratedType>(T))
  2328. T = ET->getNamedType();
  2329. return T == getObjCClassType();
  2330. }
  2331. bool isObjCSelType(QualType T) const {
  2332. if (const auto *ET = dyn_cast<ElaboratedType>(T))
  2333. T = ET->getNamedType();
  2334. return T == getObjCSelType();
  2335. }
  2336. bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS,
  2337. const ObjCObjectPointerType *RHS,
  2338. bool ForCompare);
  2339. bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS,
  2340. const ObjCObjectPointerType *RHS);
  2341. // Check the safety of assignment from LHS to RHS
  2342. bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
  2343. const ObjCObjectPointerType *RHSOPT);
  2344. bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
  2345. const ObjCObjectType *RHS);
  2346. bool canAssignObjCInterfacesInBlockPointer(
  2347. const ObjCObjectPointerType *LHSOPT,
  2348. const ObjCObjectPointerType *RHSOPT,
  2349. bool BlockReturnType);
  2350. bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
  2351. QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
  2352. const ObjCObjectPointerType *RHSOPT);
  2353. bool canBindObjCObjectType(QualType To, QualType From);
  2354. // Functions for calculating composite types
  2355. QualType mergeTypes(QualType, QualType, bool OfBlockPointer = false,
  2356. bool Unqualified = false, bool BlockReturnType = false,
  2357. bool IsConditionalOperator = false);
  2358. QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer = false,
  2359. bool Unqualified = false, bool AllowCXX = false,
  2360. bool IsConditionalOperator = false);
  2361. QualType mergeFunctionParameterTypes(QualType, QualType,
  2362. bool OfBlockPointer = false,
  2363. bool Unqualified = false);
  2364. QualType mergeTransparentUnionType(QualType, QualType,
  2365. bool OfBlockPointer=false,
  2366. bool Unqualified = false);
  2367. QualType mergeObjCGCQualifiers(QualType, QualType);
  2368. /// This function merges the ExtParameterInfo lists of two functions. It
  2369. /// returns true if the lists are compatible. The merged list is returned in
  2370. /// NewParamInfos.
  2371. ///
  2372. /// \param FirstFnType The type of the first function.
  2373. ///
  2374. /// \param SecondFnType The type of the second function.
  2375. ///
  2376. /// \param CanUseFirst This flag is set to true if the first function's
  2377. /// ExtParameterInfo list can be used as the composite list of
  2378. /// ExtParameterInfo.
  2379. ///
  2380. /// \param CanUseSecond This flag is set to true if the second function's
  2381. /// ExtParameterInfo list can be used as the composite list of
  2382. /// ExtParameterInfo.
  2383. ///
  2384. /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
  2385. /// empty if none of the flags are set.
  2386. ///
  2387. bool mergeExtParameterInfo(
  2388. const FunctionProtoType *FirstFnType,
  2389. const FunctionProtoType *SecondFnType,
  2390. bool &CanUseFirst, bool &CanUseSecond,
  2391. SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
  2392. void ResetObjCLayout(const ObjCContainerDecl *CD);
  2393. //===--------------------------------------------------------------------===//
  2394. // Integer Predicates
  2395. //===--------------------------------------------------------------------===//
  2396. // The width of an integer, as defined in C99 6.2.6.2. This is the number
  2397. // of bits in an integer type excluding any padding bits.
  2398. unsigned getIntWidth(QualType T) const;
  2399. // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
  2400. // unsigned integer type. This method takes a signed type, and returns the
  2401. // corresponding unsigned integer type.
  2402. // With the introduction of fixed point types in ISO N1169, this method also
  2403. // accepts fixed point types and returns the corresponding unsigned type for
  2404. // a given fixed point type.
  2405. QualType getCorrespondingUnsignedType(QualType T) const;
  2406. // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
  2407. // unsigned integer type. This method takes an unsigned type, and returns the
  2408. // corresponding signed integer type.
  2409. // With the introduction of fixed point types in ISO N1169, this method also
  2410. // accepts fixed point types and returns the corresponding signed type for
  2411. // a given fixed point type.
  2412. QualType getCorrespondingSignedType(QualType T) const;
  2413. // Per ISO N1169, this method accepts fixed point types and returns the
  2414. // corresponding saturated type for a given fixed point type.
  2415. QualType getCorrespondingSaturatedType(QualType Ty) const;
  2416. // This method accepts fixed point types and returns the corresponding signed
  2417. // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
  2418. // fixed point types because there are unsigned integer types like bool and
  2419. // char8_t that don't have signed equivalents.
  2420. QualType getCorrespondingSignedFixedPointType(QualType Ty) const;
  2421. //===--------------------------------------------------------------------===//
  2422. // Integer Values
  2423. //===--------------------------------------------------------------------===//
  2424. /// Make an APSInt of the appropriate width and signedness for the
  2425. /// given \p Value and integer \p Type.
  2426. llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
  2427. // If Type is a signed integer type larger than 64 bits, we need to be sure
  2428. // to sign extend Res appropriately.
  2429. llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
  2430. Res = Value;
  2431. unsigned Width = getIntWidth(Type);
  2432. if (Width != Res.getBitWidth())
  2433. return Res.extOrTrunc(Width);
  2434. return Res;
  2435. }
  2436. bool isSentinelNullExpr(const Expr *E);
  2437. /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
  2438. /// none exists.
  2439. ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
  2440. /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
  2441. /// none exists.
  2442. ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
  2443. /// Return true if there is at least one \@implementation in the TU.
  2444. bool AnyObjCImplementation() {
  2445. return !ObjCImpls.empty();
  2446. }
  2447. /// Set the implementation of ObjCInterfaceDecl.
  2448. void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
  2449. ObjCImplementationDecl *ImplD);
  2450. /// Set the implementation of ObjCCategoryDecl.
  2451. void setObjCImplementation(ObjCCategoryDecl *CatD,
  2452. ObjCCategoryImplDecl *ImplD);
  2453. /// Get the duplicate declaration of a ObjCMethod in the same
  2454. /// interface, or null if none exists.
  2455. const ObjCMethodDecl *
  2456. getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
  2457. void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
  2458. const ObjCMethodDecl *Redecl);
  2459. /// Returns the Objective-C interface that \p ND belongs to if it is
  2460. /// an Objective-C method/property/ivar etc. that is part of an interface,
  2461. /// otherwise returns null.
  2462. const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
  2463. /// Set the copy initialization expression of a block var decl. \p CanThrow
  2464. /// indicates whether the copy expression can throw or not.
  2465. void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
  2466. /// Get the copy initialization expression of the VarDecl \p VD, or
  2467. /// nullptr if none exists.
  2468. BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
  2469. /// Allocate an uninitialized TypeSourceInfo.
  2470. ///
  2471. /// The caller should initialize the memory held by TypeSourceInfo using
  2472. /// the TypeLoc wrappers.
  2473. ///
  2474. /// \param T the type that will be the basis for type source info. This type
  2475. /// should refer to how the declarator was written in source code, not to
  2476. /// what type semantic analysis resolved the declarator to.
  2477. ///
  2478. /// \param Size the size of the type info to create, or 0 if the size
  2479. /// should be calculated based on the type.
  2480. TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
  2481. /// Allocate a TypeSourceInfo where all locations have been
  2482. /// initialized to a given location, which defaults to the empty
  2483. /// location.
  2484. TypeSourceInfo *
  2485. getTrivialTypeSourceInfo(QualType T,
  2486. SourceLocation Loc = SourceLocation()) const;
  2487. /// Add a deallocation callback that will be invoked when the
  2488. /// ASTContext is destroyed.
  2489. ///
  2490. /// \param Callback A callback function that will be invoked on destruction.
  2491. ///
  2492. /// \param Data Pointer data that will be provided to the callback function
  2493. /// when it is called.
  2494. void AddDeallocation(void (*Callback)(void *), void *Data) const;
  2495. /// If T isn't trivially destructible, calls AddDeallocation to register it
  2496. /// for destruction.
  2497. template <typename T> void addDestruction(T *Ptr) const {
  2498. if (!std::is_trivially_destructible<T>::value) {
  2499. auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
  2500. AddDeallocation(DestroyPtr, Ptr);
  2501. }
  2502. }
  2503. GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
  2504. GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
  2505. /// Determines if the decl can be CodeGen'ed or deserialized from PCH
  2506. /// lazily, only when used; this is only relevant for function or file scoped
  2507. /// var definitions.
  2508. ///
  2509. /// \returns true if the function/var must be CodeGen'ed/deserialized even if
  2510. /// it is not used.
  2511. bool DeclMustBeEmitted(const Decl *D);
  2512. /// Visits all versions of a multiversioned function with the passed
  2513. /// predicate.
  2514. void forEachMultiversionedFunctionVersion(
  2515. const FunctionDecl *FD,
  2516. llvm::function_ref<void(FunctionDecl *)> Pred) const;
  2517. const CXXConstructorDecl *
  2518. getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
  2519. void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
  2520. CXXConstructorDecl *CD);
  2521. void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
  2522. TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
  2523. void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
  2524. DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
  2525. void setManglingNumber(const NamedDecl *ND, unsigned Number);
  2526. unsigned getManglingNumber(const NamedDecl *ND,
  2527. bool ForAuxTarget = false) const;
  2528. void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
  2529. unsigned getStaticLocalNumber(const VarDecl *VD) const;
  2530. /// Retrieve the context for computing mangling numbers in the given
  2531. /// DeclContext.
  2532. MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
  2533. enum NeedExtraManglingDecl_t { NeedExtraManglingDecl };
  2534. MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t,
  2535. const Decl *D);
  2536. std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
  2537. /// Used by ParmVarDecl to store on the side the
  2538. /// index of the parameter when it exceeds the size of the normal bitfield.
  2539. void setParameterIndex(const ParmVarDecl *D, unsigned index);
  2540. /// Used by ParmVarDecl to retrieve on the side the
  2541. /// index of the parameter when it exceeds the size of the normal bitfield.
  2542. unsigned getParameterIndex(const ParmVarDecl *D) const;
  2543. /// Return a string representing the human readable name for the specified
  2544. /// function declaration or file name. Used by SourceLocExpr and
  2545. /// PredefinedExpr to cache evaluated results.
  2546. StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const;
  2547. /// Return a declaration for the global GUID object representing the given
  2548. /// GUID value.
  2549. MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const;
  2550. /// Return a declaration for a uniquified anonymous global constant
  2551. /// corresponding to a given APValue.
  2552. UnnamedGlobalConstantDecl *
  2553. getUnnamedGlobalConstantDecl(QualType Ty, const APValue &Value) const;
  2554. /// Return the template parameter object of the given type with the given
  2555. /// value.
  2556. TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T,
  2557. const APValue &V) const;
  2558. /// Parses the target attributes passed in, and returns only the ones that are
  2559. /// valid feature names.
  2560. ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
  2561. std::vector<std::string>
  2562. filterFunctionTargetVersionAttrs(const TargetVersionAttr *TV) const;
  2563. void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  2564. const FunctionDecl *) const;
  2565. void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
  2566. GlobalDecl GD) const;
  2567. //===--------------------------------------------------------------------===//
  2568. // Statistics
  2569. //===--------------------------------------------------------------------===//
  2570. /// The number of implicitly-declared default constructors.
  2571. unsigned NumImplicitDefaultConstructors = 0;
  2572. /// The number of implicitly-declared default constructors for
  2573. /// which declarations were built.
  2574. unsigned NumImplicitDefaultConstructorsDeclared = 0;
  2575. /// The number of implicitly-declared copy constructors.
  2576. unsigned NumImplicitCopyConstructors = 0;
  2577. /// The number of implicitly-declared copy constructors for
  2578. /// which declarations were built.
  2579. unsigned NumImplicitCopyConstructorsDeclared = 0;
  2580. /// The number of implicitly-declared move constructors.
  2581. unsigned NumImplicitMoveConstructors = 0;
  2582. /// The number of implicitly-declared move constructors for
  2583. /// which declarations were built.
  2584. unsigned NumImplicitMoveConstructorsDeclared = 0;
  2585. /// The number of implicitly-declared copy assignment operators.
  2586. unsigned NumImplicitCopyAssignmentOperators = 0;
  2587. /// The number of implicitly-declared copy assignment operators for
  2588. /// which declarations were built.
  2589. unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0;
  2590. /// The number of implicitly-declared move assignment operators.
  2591. unsigned NumImplicitMoveAssignmentOperators = 0;
  2592. /// The number of implicitly-declared move assignment operators for
  2593. /// which declarations were built.
  2594. unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0;
  2595. /// The number of implicitly-declared destructors.
  2596. unsigned NumImplicitDestructors = 0;
  2597. /// The number of implicitly-declared destructors for which
  2598. /// declarations were built.
  2599. unsigned NumImplicitDestructorsDeclared = 0;
  2600. public:
  2601. /// Initialize built-in types.
  2602. ///
  2603. /// This routine may only be invoked once for a given ASTContext object.
  2604. /// It is normally invoked after ASTContext construction.
  2605. ///
  2606. /// \param Target The target
  2607. void InitBuiltinTypes(const TargetInfo &Target,
  2608. const TargetInfo *AuxTarget = nullptr);
  2609. private:
  2610. void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
  2611. class ObjCEncOptions {
  2612. unsigned Bits;
  2613. ObjCEncOptions(unsigned Bits) : Bits(Bits) {}
  2614. public:
  2615. ObjCEncOptions() : Bits(0) {}
  2616. ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {}
  2617. #define OPT_LIST(V) \
  2618. V(ExpandPointedToStructures, 0) \
  2619. V(ExpandStructures, 1) \
  2620. V(IsOutermostType, 2) \
  2621. V(EncodingProperty, 3) \
  2622. V(IsStructField, 4) \
  2623. V(EncodeBlockParameters, 5) \
  2624. V(EncodeClassNames, 6) \
  2625. #define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
  2626. OPT_LIST(V)
  2627. #undef V
  2628. #define V(N,I) bool N() const { return Bits & 1 << I; }
  2629. OPT_LIST(V)
  2630. #undef V
  2631. #undef OPT_LIST
  2632. [[nodiscard]] ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const {
  2633. return Bits & Mask.Bits;
  2634. }
  2635. [[nodiscard]] ObjCEncOptions forComponentType() const {
  2636. ObjCEncOptions Mask = ObjCEncOptions()
  2637. .setIsOutermostType()
  2638. .setIsStructField();
  2639. return Bits & ~Mask.Bits;
  2640. }
  2641. };
  2642. // Return the Objective-C type encoding for a given type.
  2643. void getObjCEncodingForTypeImpl(QualType t, std::string &S,
  2644. ObjCEncOptions Options,
  2645. const FieldDecl *Field,
  2646. QualType *NotEncodedT = nullptr) const;
  2647. // Adds the encoding of the structure's members.
  2648. void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
  2649. const FieldDecl *Field,
  2650. bool includeVBases = true,
  2651. QualType *NotEncodedT=nullptr) const;
  2652. public:
  2653. // Adds the encoding of a method parameter or return type.
  2654. void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
  2655. QualType T, std::string& S,
  2656. bool Extended) const;
  2657. /// Returns true if this is an inline-initialized static data member
  2658. /// which is treated as a definition for MSVC compatibility.
  2659. bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
  2660. enum class InlineVariableDefinitionKind {
  2661. /// Not an inline variable.
  2662. None,
  2663. /// Weak definition of inline variable.
  2664. Weak,
  2665. /// Weak for now, might become strong later in this TU.
  2666. WeakUnknown,
  2667. /// Strong definition.
  2668. Strong
  2669. };
  2670. /// Determine whether a definition of this inline variable should
  2671. /// be treated as a weak or strong definition. For compatibility with
  2672. /// C++14 and before, for a constexpr static data member, if there is an
  2673. /// out-of-line declaration of the member, we may promote it from weak to
  2674. /// strong.
  2675. InlineVariableDefinitionKind
  2676. getInlineVariableDefinitionKind(const VarDecl *VD) const;
  2677. private:
  2678. friend class DeclarationNameTable;
  2679. friend class DeclContext;
  2680. const ASTRecordLayout &
  2681. getObjCLayout(const ObjCInterfaceDecl *D,
  2682. const ObjCImplementationDecl *Impl) const;
  2683. /// A set of deallocations that should be performed when the
  2684. /// ASTContext is destroyed.
  2685. // FIXME: We really should have a better mechanism in the ASTContext to
  2686. // manage running destructors for types which do variable sized allocation
  2687. // within the AST. In some places we thread the AST bump pointer allocator
  2688. // into the datastructures which avoids this mess during deallocation but is
  2689. // wasteful of memory, and here we require a lot of error prone book keeping
  2690. // in order to track and run destructors while we're tearing things down.
  2691. using DeallocationFunctionsAndArguments =
  2692. llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
  2693. mutable DeallocationFunctionsAndArguments Deallocations;
  2694. // FIXME: This currently contains the set of StoredDeclMaps used
  2695. // by DeclContext objects. This probably should not be in ASTContext,
  2696. // but we include it here so that ASTContext can quickly deallocate them.
  2697. llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
  2698. std::vector<Decl *> TraversalScope;
  2699. std::unique_ptr<VTableContextBase> VTContext;
  2700. void ReleaseDeclContextMaps();
  2701. public:
  2702. enum PragmaSectionFlag : unsigned {
  2703. PSF_None = 0,
  2704. PSF_Read = 0x1,
  2705. PSF_Write = 0x2,
  2706. PSF_Execute = 0x4,
  2707. PSF_Implicit = 0x8,
  2708. PSF_ZeroInit = 0x10,
  2709. PSF_Invalid = 0x80000000U,
  2710. };
  2711. struct SectionInfo {
  2712. NamedDecl *Decl;
  2713. SourceLocation PragmaSectionLocation;
  2714. int SectionFlags;
  2715. SectionInfo() = default;
  2716. SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation,
  2717. int SectionFlags)
  2718. : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
  2719. SectionFlags(SectionFlags) {}
  2720. };
  2721. llvm::StringMap<SectionInfo> SectionInfos;
  2722. /// Return a new OMPTraitInfo object owned by this context.
  2723. OMPTraitInfo &getNewOMPTraitInfo();
  2724. /// Whether a C++ static variable or CUDA/HIP kernel may be externalized.
  2725. bool mayExternalize(const Decl *D) const;
  2726. /// Whether a C++ static variable or CUDA/HIP kernel should be externalized.
  2727. bool shouldExternalize(const Decl *D) const;
  2728. StringRef getCUIDHash() const;
  2729. private:
  2730. /// All OMPTraitInfo objects live in this collection, one per
  2731. /// `pragma omp [begin] declare variant` directive.
  2732. SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector;
  2733. };
  2734. /// Insertion operator for diagnostics.
  2735. const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
  2736. const ASTContext::SectionInfo &Section);
  2737. /// Utility function for constructing a nullary selector.
  2738. inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
  2739. IdentifierInfo* II = &Ctx.Idents.get(name);
  2740. return Ctx.Selectors.getSelector(0, &II);
  2741. }
  2742. /// Utility function for constructing an unary selector.
  2743. inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
  2744. IdentifierInfo* II = &Ctx.Idents.get(name);
  2745. return Ctx.Selectors.getSelector(1, &II);
  2746. }
  2747. } // namespace clang
  2748. // operator new and delete aren't allowed inside namespaces.
  2749. /// Placement new for using the ASTContext's allocator.
  2750. ///
  2751. /// This placement form of operator new uses the ASTContext's allocator for
  2752. /// obtaining memory.
  2753. ///
  2754. /// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
  2755. /// Any changes here need to also be made there.
  2756. ///
  2757. /// We intentionally avoid using a nothrow specification here so that the calls
  2758. /// to this operator will not perform a null check on the result -- the
  2759. /// underlying allocator never returns null pointers.
  2760. ///
  2761. /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
  2762. /// @code
  2763. /// // Default alignment (8)
  2764. /// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
  2765. /// // Specific alignment
  2766. /// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
  2767. /// @endcode
  2768. /// Memory allocated through this placement new operator does not need to be
  2769. /// explicitly freed, as ASTContext will free all of this memory when it gets
  2770. /// destroyed. Please note that you cannot use delete on the pointer.
  2771. ///
  2772. /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
  2773. /// @param C The ASTContext that provides the allocator.
  2774. /// @param Alignment The alignment of the allocated memory (if the underlying
  2775. /// allocator supports it).
  2776. /// @return The allocated memory. Could be nullptr.
  2777. inline void *operator new(size_t Bytes, const clang::ASTContext &C,
  2778. size_t Alignment /* = 8 */) {
  2779. return C.Allocate(Bytes, Alignment);
  2780. }
  2781. /// Placement delete companion to the new above.
  2782. ///
  2783. /// This operator is just a companion to the new above. There is no way of
  2784. /// invoking it directly; see the new operator for more details. This operator
  2785. /// is called implicitly by the compiler if a placement new expression using
  2786. /// the ASTContext throws in the object constructor.
  2787. inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
  2788. C.Deallocate(Ptr);
  2789. }
  2790. /// This placement form of operator new[] uses the ASTContext's allocator for
  2791. /// obtaining memory.
  2792. ///
  2793. /// We intentionally avoid using a nothrow specification here so that the calls
  2794. /// to this operator will not perform a null check on the result -- the
  2795. /// underlying allocator never returns null pointers.
  2796. ///
  2797. /// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
  2798. /// @code
  2799. /// // Default alignment (8)
  2800. /// char *data = new (Context) char[10];
  2801. /// // Specific alignment
  2802. /// char *data = new (Context, 4) char[10];
  2803. /// @endcode
  2804. /// Memory allocated through this placement new[] operator does not need to be
  2805. /// explicitly freed, as ASTContext will free all of this memory when it gets
  2806. /// destroyed. Please note that you cannot use delete on the pointer.
  2807. ///
  2808. /// @param Bytes The number of bytes to allocate. Calculated by the compiler.
  2809. /// @param C The ASTContext that provides the allocator.
  2810. /// @param Alignment The alignment of the allocated memory (if the underlying
  2811. /// allocator supports it).
  2812. /// @return The allocated memory. Could be nullptr.
  2813. inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
  2814. size_t Alignment /* = 8 */) {
  2815. return C.Allocate(Bytes, Alignment);
  2816. }
  2817. /// Placement delete[] companion to the new[] above.
  2818. ///
  2819. /// This operator is just a companion to the new[] above. There is no way of
  2820. /// invoking it directly; see the new[] operator for more details. This operator
  2821. /// is called implicitly by the compiler if a placement new[] expression using
  2822. /// the ASTContext throws in the object constructor.
  2823. inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
  2824. C.Deallocate(Ptr);
  2825. }
  2826. /// Create the representation of a LazyGenerationalUpdatePtr.
  2827. template <typename Owner, typename T,
  2828. void (clang::ExternalASTSource::*Update)(Owner)>
  2829. typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
  2830. clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
  2831. const clang::ASTContext &Ctx, T Value) {
  2832. // Note, this is implemented here so that ExternalASTSource.h doesn't need to
  2833. // include ASTContext.h. We explicitly instantiate it for all relevant types
  2834. // in ASTContext.cpp.
  2835. if (auto *Source = Ctx.getExternalSource())
  2836. return new (Ctx) LazyData(Source, Value);
  2837. return Value;
  2838. }
  2839. #endif // LLVM_CLANG_AST_ASTCONTEXT_H
  2840. #ifdef __GNUC__
  2841. #pragma GCC diagnostic pop
  2842. #endif