ASTContext.h 133 KB

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