ASTReaderDecl.cpp 161 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315
  1. //===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file implements the ASTReader::ReadDeclRecord method, which is the
  11. // entrypoint for loading a decl.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "ASTCommon.h"
  15. #include "ASTReaderInternals.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/Attr.h"
  18. #include "clang/AST/AttrIterator.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclBase.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclFriend.h"
  23. #include "clang/AST/DeclObjC.h"
  24. #include "clang/AST/DeclOpenMP.h"
  25. #include "clang/AST/DeclTemplate.h"
  26. #include "clang/AST/DeclVisitor.h"
  27. #include "clang/AST/DeclarationName.h"
  28. #include "clang/AST/Expr.h"
  29. #include "clang/AST/ExternalASTSource.h"
  30. #include "clang/AST/LambdaCapture.h"
  31. #include "clang/AST/NestedNameSpecifier.h"
  32. #include "clang/AST/Redeclarable.h"
  33. #include "clang/AST/Stmt.h"
  34. #include "clang/AST/TemplateBase.h"
  35. #include "clang/AST/Type.h"
  36. #include "clang/AST/UnresolvedSet.h"
  37. #include "clang/Basic/AttrKinds.h"
  38. #include "clang/Basic/ExceptionSpecificationType.h"
  39. #include "clang/Basic/IdentifierTable.h"
  40. #include "clang/Basic/LLVM.h"
  41. #include "clang/Basic/Lambda.h"
  42. #include "clang/Basic/LangOptions.h"
  43. #include "clang/Basic/Linkage.h"
  44. #include "clang/Basic/Module.h"
  45. #include "clang/Basic/PragmaKinds.h"
  46. #include "clang/Basic/SourceLocation.h"
  47. #include "clang/Basic/Specifiers.h"
  48. #include "clang/Sema/IdentifierResolver.h"
  49. #include "clang/Sema/SemaDiagnostic.h"
  50. #include "clang/Serialization/ASTBitCodes.h"
  51. #include "clang/Serialization/ASTReader.h"
  52. #include "clang/Serialization/ContinuousRangeMap.h"
  53. #include "clang/Serialization/Module.h"
  54. #include "llvm/ADT/DenseMap.h"
  55. #include "llvm/ADT/FoldingSet.h"
  56. #include "llvm/ADT/STLExtras.h"
  57. #include "llvm/ADT/SmallPtrSet.h"
  58. #include "llvm/ADT/SmallVector.h"
  59. #include "llvm/ADT/iterator_range.h"
  60. #include "llvm/Bitcode/BitstreamReader.h"
  61. #include "llvm/Support/Casting.h"
  62. #include "llvm/Support/ErrorHandling.h"
  63. #include "llvm/Support/SaveAndRestore.h"
  64. #include <algorithm>
  65. #include <cassert>
  66. #include <cstdint>
  67. #include <cstring>
  68. #include <string>
  69. #include <utility>
  70. using namespace clang;
  71. using namespace serialization;
  72. //===----------------------------------------------------------------------===//
  73. // Declaration deserialization
  74. //===----------------------------------------------------------------------===//
  75. namespace clang {
  76. class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
  77. ASTReader &Reader;
  78. ASTRecordReader &Record;
  79. ASTReader::RecordLocation Loc;
  80. const DeclID ThisDeclID;
  81. const SourceLocation ThisDeclLoc;
  82. using RecordData = ASTReader::RecordData;
  83. TypeID TypeIDForTypeDecl = 0;
  84. unsigned AnonymousDeclNumber;
  85. GlobalDeclID NamedDeclForTagDecl = 0;
  86. IdentifierInfo *TypedefNameForLinkage = nullptr;
  87. bool HasPendingBody = false;
  88. ///\brief A flag to carry the information for a decl from the entity is
  89. /// used. We use it to delay the marking of the canonical decl as used until
  90. /// the entire declaration is deserialized and merged.
  91. bool IsDeclMarkedUsed = false;
  92. uint64_t GetCurrentCursorOffset();
  93. uint64_t ReadLocalOffset() {
  94. uint64_t LocalOffset = Record.readInt();
  95. assert(LocalOffset < Loc.Offset && "offset point after current record");
  96. return LocalOffset ? Loc.Offset - LocalOffset : 0;
  97. }
  98. uint64_t ReadGlobalOffset() {
  99. uint64_t Local = ReadLocalOffset();
  100. return Local ? Record.getGlobalBitOffset(Local) : 0;
  101. }
  102. SourceLocation ReadSourceLocation() {
  103. return Record.readSourceLocation();
  104. }
  105. SourceRange ReadSourceRange() {
  106. return Record.readSourceRange();
  107. }
  108. TypeSourceInfo *GetTypeSourceInfo() {
  109. return Record.getTypeSourceInfo();
  110. }
  111. serialization::DeclID ReadDeclID() {
  112. return Record.readDeclID();
  113. }
  114. std::string ReadString() {
  115. return Record.readString();
  116. }
  117. void ReadDeclIDList(SmallVectorImpl<DeclID> &IDs) {
  118. for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
  119. IDs.push_back(ReadDeclID());
  120. }
  121. Decl *ReadDecl() {
  122. return Record.readDecl();
  123. }
  124. template<typename T>
  125. T *ReadDeclAs() {
  126. return Record.readDeclAs<T>();
  127. }
  128. void ReadQualifierInfo(QualifierInfo &Info) {
  129. Record.readQualifierInfo(Info);
  130. }
  131. void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name) {
  132. Record.readDeclarationNameLoc(DNLoc, Name);
  133. }
  134. serialization::SubmoduleID readSubmoduleID() {
  135. if (Record.getIdx() == Record.size())
  136. return 0;
  137. return Record.getGlobalSubmoduleID(Record.readInt());
  138. }
  139. Module *readModule() {
  140. return Record.getSubmodule(readSubmoduleID());
  141. }
  142. void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
  143. void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
  144. const CXXRecordDecl *D);
  145. void MergeDefinitionData(CXXRecordDecl *D,
  146. struct CXXRecordDecl::DefinitionData &&NewDD);
  147. void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
  148. void MergeDefinitionData(ObjCInterfaceDecl *D,
  149. struct ObjCInterfaceDecl::DefinitionData &&NewDD);
  150. void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
  151. void MergeDefinitionData(ObjCProtocolDecl *D,
  152. struct ObjCProtocolDecl::DefinitionData &&NewDD);
  153. static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
  154. DeclContext *DC,
  155. unsigned Index);
  156. static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
  157. unsigned Index, NamedDecl *D);
  158. /// Results from loading a RedeclarableDecl.
  159. class RedeclarableResult {
  160. Decl *MergeWith;
  161. GlobalDeclID FirstID;
  162. bool IsKeyDecl;
  163. public:
  164. RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
  165. : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
  166. /// \brief Retrieve the first ID.
  167. GlobalDeclID getFirstID() const { return FirstID; }
  168. /// \brief Is this declaration a key declaration?
  169. bool isKeyDecl() const { return IsKeyDecl; }
  170. /// \brief Get a known declaration that this should be merged with, if
  171. /// any.
  172. Decl *getKnownMergeTarget() const { return MergeWith; }
  173. };
  174. /// \brief Class used to capture the result of searching for an existing
  175. /// declaration of a specific kind and name, along with the ability
  176. /// to update the place where this result was found (the declaration
  177. /// chain hanging off an identifier or the DeclContext we searched in)
  178. /// if requested.
  179. class FindExistingResult {
  180. ASTReader &Reader;
  181. NamedDecl *New = nullptr;
  182. NamedDecl *Existing = nullptr;
  183. bool AddResult = false;
  184. unsigned AnonymousDeclNumber = 0;
  185. IdentifierInfo *TypedefNameForLinkage = nullptr;
  186. public:
  187. FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
  188. FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
  189. unsigned AnonymousDeclNumber,
  190. IdentifierInfo *TypedefNameForLinkage)
  191. : Reader(Reader), New(New), Existing(Existing), AddResult(true),
  192. AnonymousDeclNumber(AnonymousDeclNumber),
  193. TypedefNameForLinkage(TypedefNameForLinkage) {}
  194. FindExistingResult(FindExistingResult &&Other)
  195. : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
  196. AddResult(Other.AddResult),
  197. AnonymousDeclNumber(Other.AnonymousDeclNumber),
  198. TypedefNameForLinkage(Other.TypedefNameForLinkage) {
  199. Other.AddResult = false;
  200. }
  201. FindExistingResult &operator=(FindExistingResult &&) = delete;
  202. ~FindExistingResult();
  203. /// \brief Suppress the addition of this result into the known set of
  204. /// names.
  205. void suppress() { AddResult = false; }
  206. operator NamedDecl*() const { return Existing; }
  207. template<typename T>
  208. operator T*() const { return dyn_cast_or_null<T>(Existing); }
  209. };
  210. static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
  211. DeclContext *DC);
  212. FindExistingResult findExisting(NamedDecl *D);
  213. public:
  214. ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
  215. ASTReader::RecordLocation Loc,
  216. DeclID thisDeclID, SourceLocation ThisDeclLoc)
  217. : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
  218. ThisDeclLoc(ThisDeclLoc) {}
  219. template <typename T> static
  220. void AddLazySpecializations(T *D,
  221. SmallVectorImpl<serialization::DeclID>& IDs) {
  222. if (IDs.empty())
  223. return;
  224. // FIXME: We should avoid this pattern of getting the ASTContext.
  225. ASTContext &C = D->getASTContext();
  226. auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
  227. if (auto &Old = LazySpecializations) {
  228. IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
  229. llvm::sort(IDs.begin(), IDs.end());
  230. IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
  231. }
  232. auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
  233. *Result = IDs.size();
  234. std::copy(IDs.begin(), IDs.end(), Result + 1);
  235. LazySpecializations = Result;
  236. }
  237. template <typename DeclT>
  238. static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
  239. static Decl *getMostRecentDeclImpl(...);
  240. static Decl *getMostRecentDecl(Decl *D);
  241. template <typename DeclT>
  242. static void attachPreviousDeclImpl(ASTReader &Reader,
  243. Redeclarable<DeclT> *D, Decl *Previous,
  244. Decl *Canon);
  245. static void attachPreviousDeclImpl(ASTReader &Reader, ...);
  246. static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
  247. Decl *Canon);
  248. template <typename DeclT>
  249. static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
  250. static void attachLatestDeclImpl(...);
  251. static void attachLatestDecl(Decl *D, Decl *latest);
  252. template <typename DeclT>
  253. static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
  254. static void markIncompleteDeclChainImpl(...);
  255. /// \brief Determine whether this declaration has a pending body.
  256. bool hasPendingBody() const { return HasPendingBody; }
  257. void ReadFunctionDefinition(FunctionDecl *FD);
  258. void Visit(Decl *D);
  259. void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
  260. static void setNextObjCCategory(ObjCCategoryDecl *Cat,
  261. ObjCCategoryDecl *Next) {
  262. Cat->NextClassCategory = Next;
  263. }
  264. void VisitDecl(Decl *D);
  265. void VisitPragmaCommentDecl(PragmaCommentDecl *D);
  266. void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
  267. void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
  268. void VisitNamedDecl(NamedDecl *ND);
  269. void VisitLabelDecl(LabelDecl *LD);
  270. void VisitNamespaceDecl(NamespaceDecl *D);
  271. void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
  272. void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
  273. void VisitTypeDecl(TypeDecl *TD);
  274. RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
  275. void VisitTypedefDecl(TypedefDecl *TD);
  276. void VisitTypeAliasDecl(TypeAliasDecl *TD);
  277. void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
  278. RedeclarableResult VisitTagDecl(TagDecl *TD);
  279. void VisitEnumDecl(EnumDecl *ED);
  280. RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
  281. void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
  282. RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
  283. void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
  284. RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
  285. ClassTemplateSpecializationDecl *D);
  286. void VisitClassTemplateSpecializationDecl(
  287. ClassTemplateSpecializationDecl *D) {
  288. VisitClassTemplateSpecializationDeclImpl(D);
  289. }
  290. void VisitClassTemplatePartialSpecializationDecl(
  291. ClassTemplatePartialSpecializationDecl *D);
  292. void VisitClassScopeFunctionSpecializationDecl(
  293. ClassScopeFunctionSpecializationDecl *D);
  294. RedeclarableResult
  295. VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
  296. void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
  297. VisitVarTemplateSpecializationDeclImpl(D);
  298. }
  299. void VisitVarTemplatePartialSpecializationDecl(
  300. VarTemplatePartialSpecializationDecl *D);
  301. void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
  302. void VisitValueDecl(ValueDecl *VD);
  303. void VisitEnumConstantDecl(EnumConstantDecl *ECD);
  304. void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
  305. void VisitDeclaratorDecl(DeclaratorDecl *DD);
  306. void VisitFunctionDecl(FunctionDecl *FD);
  307. void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
  308. void VisitCXXMethodDecl(CXXMethodDecl *D);
  309. void VisitCXXConstructorDecl(CXXConstructorDecl *D);
  310. void VisitCXXDestructorDecl(CXXDestructorDecl *D);
  311. void VisitCXXConversionDecl(CXXConversionDecl *D);
  312. void VisitFieldDecl(FieldDecl *FD);
  313. void VisitMSPropertyDecl(MSPropertyDecl *FD);
  314. void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
  315. RedeclarableResult VisitVarDeclImpl(VarDecl *D);
  316. void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
  317. void VisitImplicitParamDecl(ImplicitParamDecl *PD);
  318. void VisitParmVarDecl(ParmVarDecl *PD);
  319. void VisitDecompositionDecl(DecompositionDecl *DD);
  320. void VisitBindingDecl(BindingDecl *BD);
  321. void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
  322. DeclID VisitTemplateDecl(TemplateDecl *D);
  323. RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
  324. void VisitClassTemplateDecl(ClassTemplateDecl *D);
  325. void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
  326. void VisitVarTemplateDecl(VarTemplateDecl *D);
  327. void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
  328. void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
  329. void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
  330. void VisitUsingDecl(UsingDecl *D);
  331. void VisitUsingPackDecl(UsingPackDecl *D);
  332. void VisitUsingShadowDecl(UsingShadowDecl *D);
  333. void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
  334. void VisitLinkageSpecDecl(LinkageSpecDecl *D);
  335. void VisitExportDecl(ExportDecl *D);
  336. void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
  337. void VisitImportDecl(ImportDecl *D);
  338. void VisitAccessSpecDecl(AccessSpecDecl *D);
  339. void VisitFriendDecl(FriendDecl *D);
  340. void VisitFriendTemplateDecl(FriendTemplateDecl *D);
  341. void VisitStaticAssertDecl(StaticAssertDecl *D);
  342. void VisitBlockDecl(BlockDecl *BD);
  343. void VisitCapturedDecl(CapturedDecl *CD);
  344. void VisitEmptyDecl(EmptyDecl *D);
  345. std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
  346. template<typename T>
  347. RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
  348. template<typename T>
  349. void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
  350. DeclID TemplatePatternID = 0);
  351. template<typename T>
  352. void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
  353. RedeclarableResult &Redecl,
  354. DeclID TemplatePatternID = 0);
  355. template<typename T>
  356. void mergeMergeable(Mergeable<T> *D);
  357. void mergeTemplatePattern(RedeclarableTemplateDecl *D,
  358. RedeclarableTemplateDecl *Existing,
  359. DeclID DsID, bool IsKeyDecl);
  360. ObjCTypeParamList *ReadObjCTypeParamList();
  361. // FIXME: Reorder according to DeclNodes.td?
  362. void VisitObjCMethodDecl(ObjCMethodDecl *D);
  363. void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
  364. void VisitObjCContainerDecl(ObjCContainerDecl *D);
  365. void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
  366. void VisitObjCIvarDecl(ObjCIvarDecl *D);
  367. void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
  368. void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
  369. void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
  370. void VisitObjCImplDecl(ObjCImplDecl *D);
  371. void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
  372. void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
  373. void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
  374. void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
  375. void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
  376. void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
  377. void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
  378. void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
  379. };
  380. } // namespace clang
  381. namespace {
  382. /// Iterator over the redeclarations of a declaration that have already
  383. /// been merged into the same redeclaration chain.
  384. template<typename DeclT>
  385. class MergedRedeclIterator {
  386. DeclT *Start;
  387. DeclT *Canonical = nullptr;
  388. DeclT *Current = nullptr;
  389. public:
  390. MergedRedeclIterator() = default;
  391. MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
  392. DeclT *operator*() { return Current; }
  393. MergedRedeclIterator &operator++() {
  394. if (Current->isFirstDecl()) {
  395. Canonical = Current;
  396. Current = Current->getMostRecentDecl();
  397. } else
  398. Current = Current->getPreviousDecl();
  399. // If we started in the merged portion, we'll reach our start position
  400. // eventually. Otherwise, we'll never reach it, but the second declaration
  401. // we reached was the canonical declaration, so stop when we see that one
  402. // again.
  403. if (Current == Start || Current == Canonical)
  404. Current = nullptr;
  405. return *this;
  406. }
  407. friend bool operator!=(const MergedRedeclIterator &A,
  408. const MergedRedeclIterator &B) {
  409. return A.Current != B.Current;
  410. }
  411. };
  412. } // namespace
  413. template <typename DeclT>
  414. static llvm::iterator_range<MergedRedeclIterator<DeclT>>
  415. merged_redecls(DeclT *D) {
  416. return llvm::make_range(MergedRedeclIterator<DeclT>(D),
  417. MergedRedeclIterator<DeclT>());
  418. }
  419. uint64_t ASTDeclReader::GetCurrentCursorOffset() {
  420. return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
  421. }
  422. void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
  423. if (Record.readInt())
  424. Reader.DefinitionSource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
  425. if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
  426. CD->NumCtorInitializers = Record.readInt();
  427. if (CD->NumCtorInitializers)
  428. CD->CtorInitializers = ReadGlobalOffset();
  429. }
  430. // Store the offset of the body so we can lazily load it later.
  431. Reader.PendingBodies[FD] = GetCurrentCursorOffset();
  432. HasPendingBody = true;
  433. }
  434. void ASTDeclReader::Visit(Decl *D) {
  435. DeclVisitor<ASTDeclReader, void>::Visit(D);
  436. // At this point we have deserialized and merged the decl and it is safe to
  437. // update its canonical decl to signal that the entire entity is used.
  438. D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
  439. IsDeclMarkedUsed = false;
  440. if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
  441. if (DD->DeclInfo) {
  442. auto *Info = DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
  443. Info->TInfo = GetTypeSourceInfo();
  444. }
  445. else {
  446. DD->DeclInfo = GetTypeSourceInfo();
  447. }
  448. }
  449. if (auto *TD = dyn_cast<TypeDecl>(D)) {
  450. // We have a fully initialized TypeDecl. Read its type now.
  451. TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
  452. // If this is a tag declaration with a typedef name for linkage, it's safe
  453. // to load that typedef now.
  454. if (NamedDeclForTagDecl)
  455. cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
  456. cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
  457. } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
  458. // if we have a fully initialized TypeDecl, we can safely read its type now.
  459. ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
  460. } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  461. // FunctionDecl's body was written last after all other Stmts/Exprs.
  462. // We only read it if FD doesn't already have a body (e.g., from another
  463. // module).
  464. // FIXME: Can we diagnose ODR violations somehow?
  465. if (Record.readInt())
  466. ReadFunctionDefinition(FD);
  467. }
  468. }
  469. void ASTDeclReader::VisitDecl(Decl *D) {
  470. if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
  471. isa<ParmVarDecl>(D)) {
  472. // We don't want to deserialize the DeclContext of a template
  473. // parameter or of a parameter of a function template immediately. These
  474. // entities might be used in the formulation of its DeclContext (for
  475. // example, a function parameter can be used in decltype() in trailing
  476. // return type of the function). Use the translation unit DeclContext as a
  477. // placeholder.
  478. GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID();
  479. GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID();
  480. if (!LexicalDCIDForTemplateParmDecl)
  481. LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
  482. Reader.addPendingDeclContextInfo(D,
  483. SemaDCIDForTemplateParmDecl,
  484. LexicalDCIDForTemplateParmDecl);
  485. D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
  486. } else {
  487. auto *SemaDC = ReadDeclAs<DeclContext>();
  488. auto *LexicalDC = ReadDeclAs<DeclContext>();
  489. if (!LexicalDC)
  490. LexicalDC = SemaDC;
  491. DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
  492. // Avoid calling setLexicalDeclContext() directly because it uses
  493. // Decl::getASTContext() internally which is unsafe during derialization.
  494. D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
  495. Reader.getContext());
  496. }
  497. D->setLocation(ThisDeclLoc);
  498. D->setInvalidDecl(Record.readInt());
  499. if (Record.readInt()) { // hasAttrs
  500. AttrVec Attrs;
  501. Record.readAttributes(Attrs);
  502. // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
  503. // internally which is unsafe during derialization.
  504. D->setAttrsImpl(Attrs, Reader.getContext());
  505. }
  506. D->setImplicit(Record.readInt());
  507. D->Used = Record.readInt();
  508. IsDeclMarkedUsed |= D->Used;
  509. D->setReferenced(Record.readInt());
  510. D->setTopLevelDeclInObjCContainer(Record.readInt());
  511. D->setAccess((AccessSpecifier)Record.readInt());
  512. D->FromASTFile = true;
  513. bool ModulePrivate = Record.readInt();
  514. // Determine whether this declaration is part of a (sub)module. If so, it
  515. // may not yet be visible.
  516. if (unsigned SubmoduleID = readSubmoduleID()) {
  517. // Store the owning submodule ID in the declaration.
  518. D->setModuleOwnershipKind(
  519. ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
  520. : Decl::ModuleOwnershipKind::VisibleWhenImported);
  521. D->setOwningModuleID(SubmoduleID);
  522. if (ModulePrivate) {
  523. // Module-private declarations are never visible, so there is no work to
  524. // do.
  525. } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
  526. // If local visibility is being tracked, this declaration will become
  527. // hidden and visible as the owning module does.
  528. } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
  529. // Mark the declaration as visible when its owning module becomes visible.
  530. if (Owner->NameVisibility == Module::AllVisible)
  531. D->setVisibleDespiteOwningModule();
  532. else
  533. Reader.HiddenNamesMap[Owner].push_back(D);
  534. }
  535. } else if (ModulePrivate) {
  536. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  537. }
  538. }
  539. void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
  540. VisitDecl(D);
  541. D->setLocation(ReadSourceLocation());
  542. D->CommentKind = (PragmaMSCommentKind)Record.readInt();
  543. std::string Arg = ReadString();
  544. memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
  545. D->getTrailingObjects<char>()[Arg.size()] = '\0';
  546. }
  547. void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
  548. VisitDecl(D);
  549. D->setLocation(ReadSourceLocation());
  550. std::string Name = ReadString();
  551. memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
  552. D->getTrailingObjects<char>()[Name.size()] = '\0';
  553. D->ValueStart = Name.size() + 1;
  554. std::string Value = ReadString();
  555. memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
  556. Value.size());
  557. D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
  558. }
  559. void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
  560. llvm_unreachable("Translation units are not serialized");
  561. }
  562. void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
  563. VisitDecl(ND);
  564. ND->setDeclName(Record.readDeclarationName());
  565. AnonymousDeclNumber = Record.readInt();
  566. }
  567. void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
  568. VisitNamedDecl(TD);
  569. TD->setLocStart(ReadSourceLocation());
  570. // Delay type reading until after we have fully initialized the decl.
  571. TypeIDForTypeDecl = Record.getGlobalTypeID(Record.readInt());
  572. }
  573. ASTDeclReader::RedeclarableResult
  574. ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
  575. RedeclarableResult Redecl = VisitRedeclarable(TD);
  576. VisitTypeDecl(TD);
  577. TypeSourceInfo *TInfo = GetTypeSourceInfo();
  578. if (Record.readInt()) { // isModed
  579. QualType modedT = Record.readType();
  580. TD->setModedTypeSourceInfo(TInfo, modedT);
  581. } else
  582. TD->setTypeSourceInfo(TInfo);
  583. // Read and discard the declaration for which this is a typedef name for
  584. // linkage, if it exists. We cannot rely on our type to pull in this decl,
  585. // because it might have been merged with a type from another module and
  586. // thus might not refer to our version of the declaration.
  587. ReadDecl();
  588. return Redecl;
  589. }
  590. void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
  591. RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
  592. mergeRedeclarable(TD, Redecl);
  593. }
  594. void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
  595. RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
  596. if (auto *Template = ReadDeclAs<TypeAliasTemplateDecl>())
  597. // Merged when we merge the template.
  598. TD->setDescribedAliasTemplate(Template);
  599. else
  600. mergeRedeclarable(TD, Redecl);
  601. }
  602. ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
  603. RedeclarableResult Redecl = VisitRedeclarable(TD);
  604. VisitTypeDecl(TD);
  605. TD->IdentifierNamespace = Record.readInt();
  606. TD->setTagKind((TagDecl::TagKind)Record.readInt());
  607. if (!isa<CXXRecordDecl>(TD))
  608. TD->setCompleteDefinition(Record.readInt());
  609. TD->setEmbeddedInDeclarator(Record.readInt());
  610. TD->setFreeStanding(Record.readInt());
  611. TD->setCompleteDefinitionRequired(Record.readInt());
  612. TD->setBraceRange(ReadSourceRange());
  613. switch (Record.readInt()) {
  614. case 0:
  615. break;
  616. case 1: { // ExtInfo
  617. auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
  618. ReadQualifierInfo(*Info);
  619. TD->TypedefNameDeclOrQualifier = Info;
  620. break;
  621. }
  622. case 2: // TypedefNameForAnonDecl
  623. NamedDeclForTagDecl = ReadDeclID();
  624. TypedefNameForLinkage = Record.getIdentifierInfo();
  625. break;
  626. default:
  627. llvm_unreachable("unexpected tag info kind");
  628. }
  629. if (!isa<CXXRecordDecl>(TD))
  630. mergeRedeclarable(TD, Redecl);
  631. return Redecl;
  632. }
  633. void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
  634. VisitTagDecl(ED);
  635. if (TypeSourceInfo *TI = GetTypeSourceInfo())
  636. ED->setIntegerTypeSourceInfo(TI);
  637. else
  638. ED->setIntegerType(Record.readType());
  639. ED->setPromotionType(Record.readType());
  640. ED->setNumPositiveBits(Record.readInt());
  641. ED->setNumNegativeBits(Record.readInt());
  642. ED->IsScoped = Record.readInt();
  643. ED->IsScopedUsingClassTag = Record.readInt();
  644. ED->IsFixed = Record.readInt();
  645. // If this is a definition subject to the ODR, and we already have a
  646. // definition, merge this one into it.
  647. if (ED->IsCompleteDefinition &&
  648. Reader.getContext().getLangOpts().Modules &&
  649. Reader.getContext().getLangOpts().CPlusPlus) {
  650. EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
  651. if (!OldDef) {
  652. // This is the first time we've seen an imported definition. Look for a
  653. // local definition before deciding that we are the first definition.
  654. for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
  655. if (!D->isFromASTFile() && D->isCompleteDefinition()) {
  656. OldDef = D;
  657. break;
  658. }
  659. }
  660. }
  661. if (OldDef) {
  662. Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
  663. ED->IsCompleteDefinition = false;
  664. Reader.mergeDefinitionVisibility(OldDef, ED);
  665. } else {
  666. OldDef = ED;
  667. }
  668. }
  669. if (auto *InstED = ReadDeclAs<EnumDecl>()) {
  670. auto TSK = (TemplateSpecializationKind)Record.readInt();
  671. SourceLocation POI = ReadSourceLocation();
  672. ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
  673. ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
  674. }
  675. }
  676. ASTDeclReader::RedeclarableResult
  677. ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
  678. RedeclarableResult Redecl = VisitTagDecl(RD);
  679. RD->setHasFlexibleArrayMember(Record.readInt());
  680. RD->setAnonymousStructOrUnion(Record.readInt());
  681. RD->setHasObjectMember(Record.readInt());
  682. RD->setHasVolatileMember(Record.readInt());
  683. RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
  684. RD->setNonTrivialToPrimitiveCopy(Record.readInt());
  685. RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
  686. RD->setParamDestroyedInCallee(Record.readInt());
  687. RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
  688. return Redecl;
  689. }
  690. void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
  691. VisitNamedDecl(VD);
  692. VD->setType(Record.readType());
  693. }
  694. void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
  695. VisitValueDecl(ECD);
  696. if (Record.readInt())
  697. ECD->setInitExpr(Record.readExpr());
  698. ECD->setInitVal(Record.readAPSInt());
  699. mergeMergeable(ECD);
  700. }
  701. void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
  702. VisitValueDecl(DD);
  703. DD->setInnerLocStart(ReadSourceLocation());
  704. if (Record.readInt()) { // hasExtInfo
  705. auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
  706. ReadQualifierInfo(*Info);
  707. DD->DeclInfo = Info;
  708. }
  709. }
  710. void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
  711. RedeclarableResult Redecl = VisitRedeclarable(FD);
  712. VisitDeclaratorDecl(FD);
  713. ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName());
  714. FD->IdentifierNamespace = Record.readInt();
  715. // FunctionDecl's body is handled last at ASTDeclReader::Visit,
  716. // after everything else is read.
  717. FD->SClass = (StorageClass)Record.readInt();
  718. FD->IsInline = Record.readInt();
  719. FD->IsInlineSpecified = Record.readInt();
  720. FD->IsExplicitSpecified = Record.readInt();
  721. FD->IsVirtualAsWritten = Record.readInt();
  722. FD->IsPure = Record.readInt();
  723. FD->HasInheritedPrototype = Record.readInt();
  724. FD->HasWrittenPrototype = Record.readInt();
  725. FD->IsDeleted = Record.readInt();
  726. FD->IsTrivial = Record.readInt();
  727. FD->IsTrivialForCall = Record.readInt();
  728. FD->IsDefaulted = Record.readInt();
  729. FD->IsExplicitlyDefaulted = Record.readInt();
  730. FD->HasImplicitReturnZero = Record.readInt();
  731. FD->IsConstexpr = Record.readInt();
  732. FD->UsesSEHTry = Record.readInt();
  733. FD->HasSkippedBody = Record.readInt();
  734. FD->IsMultiVersion = Record.readInt();
  735. FD->IsLateTemplateParsed = Record.readInt();
  736. FD->setCachedLinkage(Linkage(Record.readInt()));
  737. FD->EndRangeLoc = ReadSourceLocation();
  738. FD->ODRHash = Record.readInt();
  739. FD->HasODRHash = true;
  740. switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
  741. case FunctionDecl::TK_NonTemplate:
  742. mergeRedeclarable(FD, Redecl);
  743. break;
  744. case FunctionDecl::TK_FunctionTemplate:
  745. // Merged when we merge the template.
  746. FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>());
  747. break;
  748. case FunctionDecl::TK_MemberSpecialization: {
  749. auto *InstFD = ReadDeclAs<FunctionDecl>();
  750. auto TSK = (TemplateSpecializationKind)Record.readInt();
  751. SourceLocation POI = ReadSourceLocation();
  752. FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
  753. FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
  754. mergeRedeclarable(FD, Redecl);
  755. break;
  756. }
  757. case FunctionDecl::TK_FunctionTemplateSpecialization: {
  758. auto *Template = ReadDeclAs<FunctionTemplateDecl>();
  759. auto TSK = (TemplateSpecializationKind)Record.readInt();
  760. // Template arguments.
  761. SmallVector<TemplateArgument, 8> TemplArgs;
  762. Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
  763. // Template args as written.
  764. SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
  765. SourceLocation LAngleLoc, RAngleLoc;
  766. bool HasTemplateArgumentsAsWritten = Record.readInt();
  767. if (HasTemplateArgumentsAsWritten) {
  768. unsigned NumTemplateArgLocs = Record.readInt();
  769. TemplArgLocs.reserve(NumTemplateArgLocs);
  770. for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
  771. TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
  772. LAngleLoc = ReadSourceLocation();
  773. RAngleLoc = ReadSourceLocation();
  774. }
  775. SourceLocation POI = ReadSourceLocation();
  776. ASTContext &C = Reader.getContext();
  777. TemplateArgumentList *TemplArgList
  778. = TemplateArgumentList::CreateCopy(C, TemplArgs);
  779. TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
  780. for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
  781. TemplArgsInfo.addArgument(TemplArgLocs[i]);
  782. FunctionTemplateSpecializationInfo *FTInfo
  783. = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
  784. TemplArgList,
  785. HasTemplateArgumentsAsWritten ? &TemplArgsInfo
  786. : nullptr,
  787. POI);
  788. FD->TemplateOrSpecialization = FTInfo;
  789. if (FD->isCanonicalDecl()) { // if canonical add to template's set.
  790. // The template that contains the specializations set. It's not safe to
  791. // use getCanonicalDecl on Template since it may still be initializing.
  792. auto *CanonTemplate = ReadDeclAs<FunctionTemplateDecl>();
  793. // Get the InsertPos by FindNodeOrInsertPos() instead of calling
  794. // InsertNode(FTInfo) directly to avoid the getASTContext() call in
  795. // FunctionTemplateSpecializationInfo's Profile().
  796. // We avoid getASTContext because a decl in the parent hierarchy may
  797. // be initializing.
  798. llvm::FoldingSetNodeID ID;
  799. FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
  800. void *InsertPos = nullptr;
  801. FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
  802. FunctionTemplateSpecializationInfo *ExistingInfo =
  803. CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
  804. if (InsertPos)
  805. CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
  806. else {
  807. assert(Reader.getContext().getLangOpts().Modules &&
  808. "already deserialized this template specialization");
  809. mergeRedeclarable(FD, ExistingInfo->Function, Redecl);
  810. }
  811. }
  812. break;
  813. }
  814. case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
  815. // Templates.
  816. UnresolvedSet<8> TemplDecls;
  817. unsigned NumTemplates = Record.readInt();
  818. while (NumTemplates--)
  819. TemplDecls.addDecl(ReadDeclAs<NamedDecl>());
  820. // Templates args.
  821. TemplateArgumentListInfo TemplArgs;
  822. unsigned NumArgs = Record.readInt();
  823. while (NumArgs--)
  824. TemplArgs.addArgument(Record.readTemplateArgumentLoc());
  825. TemplArgs.setLAngleLoc(ReadSourceLocation());
  826. TemplArgs.setRAngleLoc(ReadSourceLocation());
  827. FD->setDependentTemplateSpecialization(Reader.getContext(),
  828. TemplDecls, TemplArgs);
  829. // These are not merged; we don't need to merge redeclarations of dependent
  830. // template friends.
  831. break;
  832. }
  833. }
  834. // Read in the parameters.
  835. unsigned NumParams = Record.readInt();
  836. SmallVector<ParmVarDecl *, 16> Params;
  837. Params.reserve(NumParams);
  838. for (unsigned I = 0; I != NumParams; ++I)
  839. Params.push_back(ReadDeclAs<ParmVarDecl>());
  840. FD->setParams(Reader.getContext(), Params);
  841. }
  842. void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
  843. VisitNamedDecl(MD);
  844. if (Record.readInt()) {
  845. // Load the body on-demand. Most clients won't care, because method
  846. // definitions rarely show up in headers.
  847. Reader.PendingBodies[MD] = GetCurrentCursorOffset();
  848. HasPendingBody = true;
  849. MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>());
  850. MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>());
  851. }
  852. MD->setInstanceMethod(Record.readInt());
  853. MD->setVariadic(Record.readInt());
  854. MD->setPropertyAccessor(Record.readInt());
  855. MD->setDefined(Record.readInt());
  856. MD->IsOverriding = Record.readInt();
  857. MD->HasSkippedBody = Record.readInt();
  858. MD->IsRedeclaration = Record.readInt();
  859. MD->HasRedeclaration = Record.readInt();
  860. if (MD->HasRedeclaration)
  861. Reader.getContext().setObjCMethodRedeclaration(MD,
  862. ReadDeclAs<ObjCMethodDecl>());
  863. MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
  864. MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
  865. MD->SetRelatedResultType(Record.readInt());
  866. MD->setReturnType(Record.readType());
  867. MD->setReturnTypeSourceInfo(GetTypeSourceInfo());
  868. MD->DeclEndLoc = ReadSourceLocation();
  869. unsigned NumParams = Record.readInt();
  870. SmallVector<ParmVarDecl *, 16> Params;
  871. Params.reserve(NumParams);
  872. for (unsigned I = 0; I != NumParams; ++I)
  873. Params.push_back(ReadDeclAs<ParmVarDecl>());
  874. MD->SelLocsKind = Record.readInt();
  875. unsigned NumStoredSelLocs = Record.readInt();
  876. SmallVector<SourceLocation, 16> SelLocs;
  877. SelLocs.reserve(NumStoredSelLocs);
  878. for (unsigned i = 0; i != NumStoredSelLocs; ++i)
  879. SelLocs.push_back(ReadSourceLocation());
  880. MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
  881. }
  882. void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
  883. VisitTypedefNameDecl(D);
  884. D->Variance = Record.readInt();
  885. D->Index = Record.readInt();
  886. D->VarianceLoc = ReadSourceLocation();
  887. D->ColonLoc = ReadSourceLocation();
  888. }
  889. void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
  890. VisitNamedDecl(CD);
  891. CD->setAtStartLoc(ReadSourceLocation());
  892. CD->setAtEndRange(ReadSourceRange());
  893. }
  894. ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
  895. unsigned numParams = Record.readInt();
  896. if (numParams == 0)
  897. return nullptr;
  898. SmallVector<ObjCTypeParamDecl *, 4> typeParams;
  899. typeParams.reserve(numParams);
  900. for (unsigned i = 0; i != numParams; ++i) {
  901. auto *typeParam = ReadDeclAs<ObjCTypeParamDecl>();
  902. if (!typeParam)
  903. return nullptr;
  904. typeParams.push_back(typeParam);
  905. }
  906. SourceLocation lAngleLoc = ReadSourceLocation();
  907. SourceLocation rAngleLoc = ReadSourceLocation();
  908. return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
  909. typeParams, rAngleLoc);
  910. }
  911. void ASTDeclReader::ReadObjCDefinitionData(
  912. struct ObjCInterfaceDecl::DefinitionData &Data) {
  913. // Read the superclass.
  914. Data.SuperClassTInfo = GetTypeSourceInfo();
  915. Data.EndLoc = ReadSourceLocation();
  916. Data.HasDesignatedInitializers = Record.readInt();
  917. // Read the directly referenced protocols and their SourceLocations.
  918. unsigned NumProtocols = Record.readInt();
  919. SmallVector<ObjCProtocolDecl *, 16> Protocols;
  920. Protocols.reserve(NumProtocols);
  921. for (unsigned I = 0; I != NumProtocols; ++I)
  922. Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
  923. SmallVector<SourceLocation, 16> ProtoLocs;
  924. ProtoLocs.reserve(NumProtocols);
  925. for (unsigned I = 0; I != NumProtocols; ++I)
  926. ProtoLocs.push_back(ReadSourceLocation());
  927. Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
  928. Reader.getContext());
  929. // Read the transitive closure of protocols referenced by this class.
  930. NumProtocols = Record.readInt();
  931. Protocols.clear();
  932. Protocols.reserve(NumProtocols);
  933. for (unsigned I = 0; I != NumProtocols; ++I)
  934. Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
  935. Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
  936. Reader.getContext());
  937. }
  938. void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
  939. struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
  940. // FIXME: odr checking?
  941. }
  942. void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
  943. RedeclarableResult Redecl = VisitRedeclarable(ID);
  944. VisitObjCContainerDecl(ID);
  945. TypeIDForTypeDecl = Record.getGlobalTypeID(Record.readInt());
  946. mergeRedeclarable(ID, Redecl);
  947. ID->TypeParamList = ReadObjCTypeParamList();
  948. if (Record.readInt()) {
  949. // Read the definition.
  950. ID->allocateDefinitionData();
  951. ReadObjCDefinitionData(ID->data());
  952. ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
  953. if (Canon->Data.getPointer()) {
  954. // If we already have a definition, keep the definition invariant and
  955. // merge the data.
  956. MergeDefinitionData(Canon, std::move(ID->data()));
  957. ID->Data = Canon->Data;
  958. } else {
  959. // Set the definition data of the canonical declaration, so other
  960. // redeclarations will see it.
  961. ID->getCanonicalDecl()->Data = ID->Data;
  962. // We will rebuild this list lazily.
  963. ID->setIvarList(nullptr);
  964. }
  965. // Note that we have deserialized a definition.
  966. Reader.PendingDefinitions.insert(ID);
  967. // Note that we've loaded this Objective-C class.
  968. Reader.ObjCClassesLoaded.push_back(ID);
  969. } else {
  970. ID->Data = ID->getCanonicalDecl()->Data;
  971. }
  972. }
  973. void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
  974. VisitFieldDecl(IVD);
  975. IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
  976. // This field will be built lazily.
  977. IVD->setNextIvar(nullptr);
  978. bool synth = Record.readInt();
  979. IVD->setSynthesize(synth);
  980. }
  981. void ASTDeclReader::ReadObjCDefinitionData(
  982. struct ObjCProtocolDecl::DefinitionData &Data) {
  983. unsigned NumProtoRefs = Record.readInt();
  984. SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
  985. ProtoRefs.reserve(NumProtoRefs);
  986. for (unsigned I = 0; I != NumProtoRefs; ++I)
  987. ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
  988. SmallVector<SourceLocation, 16> ProtoLocs;
  989. ProtoLocs.reserve(NumProtoRefs);
  990. for (unsigned I = 0; I != NumProtoRefs; ++I)
  991. ProtoLocs.push_back(ReadSourceLocation());
  992. Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
  993. ProtoLocs.data(), Reader.getContext());
  994. }
  995. void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
  996. struct ObjCProtocolDecl::DefinitionData &&NewDD) {
  997. // FIXME: odr checking?
  998. }
  999. void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
  1000. RedeclarableResult Redecl = VisitRedeclarable(PD);
  1001. VisitObjCContainerDecl(PD);
  1002. mergeRedeclarable(PD, Redecl);
  1003. if (Record.readInt()) {
  1004. // Read the definition.
  1005. PD->allocateDefinitionData();
  1006. ReadObjCDefinitionData(PD->data());
  1007. ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
  1008. if (Canon->Data.getPointer()) {
  1009. // If we already have a definition, keep the definition invariant and
  1010. // merge the data.
  1011. MergeDefinitionData(Canon, std::move(PD->data()));
  1012. PD->Data = Canon->Data;
  1013. } else {
  1014. // Set the definition data of the canonical declaration, so other
  1015. // redeclarations will see it.
  1016. PD->getCanonicalDecl()->Data = PD->Data;
  1017. }
  1018. // Note that we have deserialized a definition.
  1019. Reader.PendingDefinitions.insert(PD);
  1020. } else {
  1021. PD->Data = PD->getCanonicalDecl()->Data;
  1022. }
  1023. }
  1024. void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
  1025. VisitFieldDecl(FD);
  1026. }
  1027. void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
  1028. VisitObjCContainerDecl(CD);
  1029. CD->setCategoryNameLoc(ReadSourceLocation());
  1030. CD->setIvarLBraceLoc(ReadSourceLocation());
  1031. CD->setIvarRBraceLoc(ReadSourceLocation());
  1032. // Note that this category has been deserialized. We do this before
  1033. // deserializing the interface declaration, so that it will consider this
  1034. /// category.
  1035. Reader.CategoriesDeserialized.insert(CD);
  1036. CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>();
  1037. CD->TypeParamList = ReadObjCTypeParamList();
  1038. unsigned NumProtoRefs = Record.readInt();
  1039. SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
  1040. ProtoRefs.reserve(NumProtoRefs);
  1041. for (unsigned I = 0; I != NumProtoRefs; ++I)
  1042. ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
  1043. SmallVector<SourceLocation, 16> ProtoLocs;
  1044. ProtoLocs.reserve(NumProtoRefs);
  1045. for (unsigned I = 0; I != NumProtoRefs; ++I)
  1046. ProtoLocs.push_back(ReadSourceLocation());
  1047. CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
  1048. Reader.getContext());
  1049. // Protocols in the class extension belong to the class.
  1050. if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
  1051. CD->ClassInterface->mergeClassExtensionProtocolList(
  1052. (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
  1053. Reader.getContext());
  1054. }
  1055. void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
  1056. VisitNamedDecl(CAD);
  1057. CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
  1058. }
  1059. void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
  1060. VisitNamedDecl(D);
  1061. D->setAtLoc(ReadSourceLocation());
  1062. D->setLParenLoc(ReadSourceLocation());
  1063. QualType T = Record.readType();
  1064. TypeSourceInfo *TSI = GetTypeSourceInfo();
  1065. D->setType(T, TSI);
  1066. D->setPropertyAttributes(
  1067. (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
  1068. D->setPropertyAttributesAsWritten(
  1069. (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
  1070. D->setPropertyImplementation(
  1071. (ObjCPropertyDecl::PropertyControl)Record.readInt());
  1072. DeclarationName GetterName = Record.readDeclarationName();
  1073. SourceLocation GetterLoc = ReadSourceLocation();
  1074. D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
  1075. DeclarationName SetterName = Record.readDeclarationName();
  1076. SourceLocation SetterLoc = ReadSourceLocation();
  1077. D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
  1078. D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
  1079. D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
  1080. D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>());
  1081. }
  1082. void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
  1083. VisitObjCContainerDecl(D);
  1084. D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
  1085. }
  1086. void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
  1087. VisitObjCImplDecl(D);
  1088. D->CategoryNameLoc = ReadSourceLocation();
  1089. }
  1090. void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
  1091. VisitObjCImplDecl(D);
  1092. D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>());
  1093. D->SuperLoc = ReadSourceLocation();
  1094. D->setIvarLBraceLoc(ReadSourceLocation());
  1095. D->setIvarRBraceLoc(ReadSourceLocation());
  1096. D->setHasNonZeroConstructors(Record.readInt());
  1097. D->setHasDestructors(Record.readInt());
  1098. D->NumIvarInitializers = Record.readInt();
  1099. if (D->NumIvarInitializers)
  1100. D->IvarInitializers = ReadGlobalOffset();
  1101. }
  1102. void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
  1103. VisitDecl(D);
  1104. D->setAtLoc(ReadSourceLocation());
  1105. D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>());
  1106. D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>();
  1107. D->IvarLoc = ReadSourceLocation();
  1108. D->setGetterCXXConstructor(Record.readExpr());
  1109. D->setSetterCXXAssignment(Record.readExpr());
  1110. }
  1111. void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
  1112. VisitDeclaratorDecl(FD);
  1113. FD->Mutable = Record.readInt();
  1114. if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
  1115. FD->InitStorage.setInt(ISK);
  1116. FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
  1117. ? Record.readType().getAsOpaquePtr()
  1118. : Record.readExpr());
  1119. }
  1120. if (auto *BW = Record.readExpr())
  1121. FD->setBitWidth(BW);
  1122. if (!FD->getDeclName()) {
  1123. if (auto *Tmpl = ReadDeclAs<FieldDecl>())
  1124. Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
  1125. }
  1126. mergeMergeable(FD);
  1127. }
  1128. void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
  1129. VisitDeclaratorDecl(PD);
  1130. PD->GetterId = Record.getIdentifierInfo();
  1131. PD->SetterId = Record.getIdentifierInfo();
  1132. }
  1133. void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
  1134. VisitValueDecl(FD);
  1135. FD->ChainingSize = Record.readInt();
  1136. assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
  1137. FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
  1138. for (unsigned I = 0; I != FD->ChainingSize; ++I)
  1139. FD->Chaining[I] = ReadDeclAs<NamedDecl>();
  1140. mergeMergeable(FD);
  1141. }
  1142. ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
  1143. RedeclarableResult Redecl = VisitRedeclarable(VD);
  1144. VisitDeclaratorDecl(VD);
  1145. VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
  1146. VD->VarDeclBits.TSCSpec = Record.readInt();
  1147. VD->VarDeclBits.InitStyle = Record.readInt();
  1148. if (!isa<ParmVarDecl>(VD)) {
  1149. VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
  1150. Record.readInt();
  1151. VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
  1152. VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
  1153. VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
  1154. VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
  1155. VD->NonParmVarDeclBits.ARCPseudoStrong = Record.readInt();
  1156. VD->NonParmVarDeclBits.IsInline = Record.readInt();
  1157. VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
  1158. VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
  1159. VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
  1160. VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
  1161. VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
  1162. }
  1163. auto VarLinkage = Linkage(Record.readInt());
  1164. VD->setCachedLinkage(VarLinkage);
  1165. // Reconstruct the one piece of the IdentifierNamespace that we need.
  1166. if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
  1167. VD->getLexicalDeclContext()->isFunctionOrMethod())
  1168. VD->setLocalExternDecl();
  1169. if (uint64_t Val = Record.readInt()) {
  1170. VD->setInit(Record.readExpr());
  1171. if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
  1172. EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
  1173. Eval->CheckedICE = true;
  1174. Eval->IsICE = Val == 3;
  1175. }
  1176. }
  1177. if (VD->getStorageDuration() == SD_Static && Record.readInt())
  1178. Reader.DefinitionSource[VD] = Loc.F->Kind == ModuleKind::MK_MainFile;
  1179. enum VarKind {
  1180. VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
  1181. };
  1182. switch ((VarKind)Record.readInt()) {
  1183. case VarNotTemplate:
  1184. // Only true variables (not parameters or implicit parameters) can be
  1185. // merged; the other kinds are not really redeclarable at all.
  1186. if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
  1187. !isa<VarTemplateSpecializationDecl>(VD))
  1188. mergeRedeclarable(VD, Redecl);
  1189. break;
  1190. case VarTemplate:
  1191. // Merged when we merge the template.
  1192. VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>());
  1193. break;
  1194. case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
  1195. auto *Tmpl = ReadDeclAs<VarDecl>();
  1196. auto TSK = (TemplateSpecializationKind)Record.readInt();
  1197. SourceLocation POI = ReadSourceLocation();
  1198. Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
  1199. mergeRedeclarable(VD, Redecl);
  1200. break;
  1201. }
  1202. }
  1203. return Redecl;
  1204. }
  1205. void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
  1206. VisitVarDecl(PD);
  1207. }
  1208. void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
  1209. VisitVarDecl(PD);
  1210. unsigned isObjCMethodParam = Record.readInt();
  1211. unsigned scopeDepth = Record.readInt();
  1212. unsigned scopeIndex = Record.readInt();
  1213. unsigned declQualifier = Record.readInt();
  1214. if (isObjCMethodParam) {
  1215. assert(scopeDepth == 0);
  1216. PD->setObjCMethodScopeInfo(scopeIndex);
  1217. PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
  1218. } else {
  1219. PD->setScopeInfo(scopeDepth, scopeIndex);
  1220. }
  1221. PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
  1222. PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
  1223. if (Record.readInt()) // hasUninstantiatedDefaultArg.
  1224. PD->setUninstantiatedDefaultArg(Record.readExpr());
  1225. // FIXME: If this is a redeclaration of a function from another module, handle
  1226. // inheritance of default arguments.
  1227. }
  1228. void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
  1229. VisitVarDecl(DD);
  1230. auto **BDs = DD->getTrailingObjects<BindingDecl *>();
  1231. for (unsigned I = 0; I != DD->NumBindings; ++I)
  1232. BDs[I] = ReadDeclAs<BindingDecl>();
  1233. }
  1234. void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
  1235. VisitValueDecl(BD);
  1236. BD->Binding = Record.readExpr();
  1237. }
  1238. void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
  1239. VisitDecl(AD);
  1240. AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
  1241. AD->setRParenLoc(ReadSourceLocation());
  1242. }
  1243. void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
  1244. VisitDecl(BD);
  1245. BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
  1246. BD->setSignatureAsWritten(GetTypeSourceInfo());
  1247. unsigned NumParams = Record.readInt();
  1248. SmallVector<ParmVarDecl *, 16> Params;
  1249. Params.reserve(NumParams);
  1250. for (unsigned I = 0; I != NumParams; ++I)
  1251. Params.push_back(ReadDeclAs<ParmVarDecl>());
  1252. BD->setParams(Params);
  1253. BD->setIsVariadic(Record.readInt());
  1254. BD->setBlockMissingReturnType(Record.readInt());
  1255. BD->setIsConversionFromLambda(Record.readInt());
  1256. bool capturesCXXThis = Record.readInt();
  1257. unsigned numCaptures = Record.readInt();
  1258. SmallVector<BlockDecl::Capture, 16> captures;
  1259. captures.reserve(numCaptures);
  1260. for (unsigned i = 0; i != numCaptures; ++i) {
  1261. auto *decl = ReadDeclAs<VarDecl>();
  1262. unsigned flags = Record.readInt();
  1263. bool byRef = (flags & 1);
  1264. bool nested = (flags & 2);
  1265. Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
  1266. captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
  1267. }
  1268. BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
  1269. }
  1270. void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
  1271. VisitDecl(CD);
  1272. unsigned ContextParamPos = Record.readInt();
  1273. CD->setNothrow(Record.readInt() != 0);
  1274. // Body is set by VisitCapturedStmt.
  1275. for (unsigned I = 0; I < CD->NumParams; ++I) {
  1276. if (I != ContextParamPos)
  1277. CD->setParam(I, ReadDeclAs<ImplicitParamDecl>());
  1278. else
  1279. CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>());
  1280. }
  1281. }
  1282. void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
  1283. VisitDecl(D);
  1284. D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
  1285. D->setExternLoc(ReadSourceLocation());
  1286. D->setRBraceLoc(ReadSourceLocation());
  1287. }
  1288. void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
  1289. VisitDecl(D);
  1290. D->RBraceLoc = ReadSourceLocation();
  1291. }
  1292. void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
  1293. VisitNamedDecl(D);
  1294. D->setLocStart(ReadSourceLocation());
  1295. }
  1296. void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
  1297. RedeclarableResult Redecl = VisitRedeclarable(D);
  1298. VisitNamedDecl(D);
  1299. D->setInline(Record.readInt());
  1300. D->LocStart = ReadSourceLocation();
  1301. D->RBraceLoc = ReadSourceLocation();
  1302. // Defer loading the anonymous namespace until we've finished merging
  1303. // this namespace; loading it might load a later declaration of the
  1304. // same namespace, and we have an invariant that older declarations
  1305. // get merged before newer ones try to merge.
  1306. GlobalDeclID AnonNamespace = 0;
  1307. if (Redecl.getFirstID() == ThisDeclID) {
  1308. AnonNamespace = ReadDeclID();
  1309. } else {
  1310. // Link this namespace back to the first declaration, which has already
  1311. // been deserialized.
  1312. D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
  1313. }
  1314. mergeRedeclarable(D, Redecl);
  1315. if (AnonNamespace) {
  1316. // Each module has its own anonymous namespace, which is disjoint from
  1317. // any other module's anonymous namespaces, so don't attach the anonymous
  1318. // namespace at all.
  1319. auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
  1320. if (!Record.isModule())
  1321. D->setAnonymousNamespace(Anon);
  1322. }
  1323. }
  1324. void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
  1325. RedeclarableResult Redecl = VisitRedeclarable(D);
  1326. VisitNamedDecl(D);
  1327. D->NamespaceLoc = ReadSourceLocation();
  1328. D->IdentLoc = ReadSourceLocation();
  1329. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1330. D->Namespace = ReadDeclAs<NamedDecl>();
  1331. mergeRedeclarable(D, Redecl);
  1332. }
  1333. void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
  1334. VisitNamedDecl(D);
  1335. D->setUsingLoc(ReadSourceLocation());
  1336. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1337. ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
  1338. D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>());
  1339. D->setTypename(Record.readInt());
  1340. if (auto *Pattern = ReadDeclAs<NamedDecl>())
  1341. Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
  1342. mergeMergeable(D);
  1343. }
  1344. void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
  1345. VisitNamedDecl(D);
  1346. D->InstantiatedFrom = ReadDeclAs<NamedDecl>();
  1347. auto **Expansions = D->getTrailingObjects<NamedDecl *>();
  1348. for (unsigned I = 0; I != D->NumExpansions; ++I)
  1349. Expansions[I] = ReadDeclAs<NamedDecl>();
  1350. mergeMergeable(D);
  1351. }
  1352. void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
  1353. RedeclarableResult Redecl = VisitRedeclarable(D);
  1354. VisitNamedDecl(D);
  1355. D->Underlying = ReadDeclAs<NamedDecl>();
  1356. D->IdentifierNamespace = Record.readInt();
  1357. D->UsingOrNextShadow = ReadDeclAs<NamedDecl>();
  1358. auto *Pattern = ReadDeclAs<UsingShadowDecl>();
  1359. if (Pattern)
  1360. Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
  1361. mergeRedeclarable(D, Redecl);
  1362. }
  1363. void ASTDeclReader::VisitConstructorUsingShadowDecl(
  1364. ConstructorUsingShadowDecl *D) {
  1365. VisitUsingShadowDecl(D);
  1366. D->NominatedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
  1367. D->ConstructedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
  1368. D->IsVirtual = Record.readInt();
  1369. }
  1370. void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
  1371. VisitNamedDecl(D);
  1372. D->UsingLoc = ReadSourceLocation();
  1373. D->NamespaceLoc = ReadSourceLocation();
  1374. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1375. D->NominatedNamespace = ReadDeclAs<NamedDecl>();
  1376. D->CommonAncestor = ReadDeclAs<DeclContext>();
  1377. }
  1378. void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
  1379. VisitValueDecl(D);
  1380. D->setUsingLoc(ReadSourceLocation());
  1381. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1382. ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
  1383. D->EllipsisLoc = ReadSourceLocation();
  1384. mergeMergeable(D);
  1385. }
  1386. void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
  1387. UnresolvedUsingTypenameDecl *D) {
  1388. VisitTypeDecl(D);
  1389. D->TypenameLocation = ReadSourceLocation();
  1390. D->QualifierLoc = Record.readNestedNameSpecifierLoc();
  1391. D->EllipsisLoc = ReadSourceLocation();
  1392. mergeMergeable(D);
  1393. }
  1394. void ASTDeclReader::ReadCXXDefinitionData(
  1395. struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
  1396. // Note: the caller has deserialized the IsLambda bit already.
  1397. Data.UserDeclaredConstructor = Record.readInt();
  1398. Data.UserDeclaredSpecialMembers = Record.readInt();
  1399. Data.Aggregate = Record.readInt();
  1400. Data.PlainOldData = Record.readInt();
  1401. Data.Empty = Record.readInt();
  1402. Data.Polymorphic = Record.readInt();
  1403. Data.Abstract = Record.readInt();
  1404. Data.IsStandardLayout = Record.readInt();
  1405. Data.IsCXX11StandardLayout = Record.readInt();
  1406. Data.HasBasesWithFields = Record.readInt();
  1407. Data.HasBasesWithNonStaticDataMembers = Record.readInt();
  1408. Data.HasPrivateFields = Record.readInt();
  1409. Data.HasProtectedFields = Record.readInt();
  1410. Data.HasPublicFields = Record.readInt();
  1411. Data.HasMutableFields = Record.readInt();
  1412. Data.HasVariantMembers = Record.readInt();
  1413. Data.HasOnlyCMembers = Record.readInt();
  1414. Data.HasInClassInitializer = Record.readInt();
  1415. Data.HasUninitializedReferenceMember = Record.readInt();
  1416. Data.HasUninitializedFields = Record.readInt();
  1417. Data.HasInheritedConstructor = Record.readInt();
  1418. Data.HasInheritedAssignment = Record.readInt();
  1419. Data.NeedOverloadResolutionForCopyConstructor = Record.readInt();
  1420. Data.NeedOverloadResolutionForMoveConstructor = Record.readInt();
  1421. Data.NeedOverloadResolutionForMoveAssignment = Record.readInt();
  1422. Data.NeedOverloadResolutionForDestructor = Record.readInt();
  1423. Data.DefaultedCopyConstructorIsDeleted = Record.readInt();
  1424. Data.DefaultedMoveConstructorIsDeleted = Record.readInt();
  1425. Data.DefaultedMoveAssignmentIsDeleted = Record.readInt();
  1426. Data.DefaultedDestructorIsDeleted = Record.readInt();
  1427. Data.HasTrivialSpecialMembers = Record.readInt();
  1428. Data.HasTrivialSpecialMembersForCall = Record.readInt();
  1429. Data.DeclaredNonTrivialSpecialMembers = Record.readInt();
  1430. Data.DeclaredNonTrivialSpecialMembersForCall = Record.readInt();
  1431. Data.HasIrrelevantDestructor = Record.readInt();
  1432. Data.HasConstexprNonCopyMoveConstructor = Record.readInt();
  1433. Data.HasDefaultedDefaultConstructor = Record.readInt();
  1434. Data.DefaultedDefaultConstructorIsConstexpr = Record.readInt();
  1435. Data.HasConstexprDefaultConstructor = Record.readInt();
  1436. Data.HasNonLiteralTypeFieldsOrBases = Record.readInt();
  1437. Data.ComputedVisibleConversions = Record.readInt();
  1438. Data.UserProvidedDefaultConstructor = Record.readInt();
  1439. Data.DeclaredSpecialMembers = Record.readInt();
  1440. Data.ImplicitCopyConstructorCanHaveConstParamForVBase = Record.readInt();
  1441. Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase = Record.readInt();
  1442. Data.ImplicitCopyAssignmentHasConstParam = Record.readInt();
  1443. Data.HasDeclaredCopyConstructorWithConstParam = Record.readInt();
  1444. Data.HasDeclaredCopyAssignmentWithConstParam = Record.readInt();
  1445. Data.ODRHash = Record.readInt();
  1446. Data.HasODRHash = true;
  1447. if (Record.readInt())
  1448. Reader.DefinitionSource[D] = Loc.F->Kind == ModuleKind::MK_MainFile;
  1449. Data.NumBases = Record.readInt();
  1450. if (Data.NumBases)
  1451. Data.Bases = ReadGlobalOffset();
  1452. Data.NumVBases = Record.readInt();
  1453. if (Data.NumVBases)
  1454. Data.VBases = ReadGlobalOffset();
  1455. Record.readUnresolvedSet(Data.Conversions);
  1456. Record.readUnresolvedSet(Data.VisibleConversions);
  1457. assert(Data.Definition && "Data.Definition should be already set!");
  1458. Data.FirstFriend = ReadDeclID();
  1459. if (Data.IsLambda) {
  1460. using Capture = LambdaCapture;
  1461. auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
  1462. Lambda.Dependent = Record.readInt();
  1463. Lambda.IsGenericLambda = Record.readInt();
  1464. Lambda.CaptureDefault = Record.readInt();
  1465. Lambda.NumCaptures = Record.readInt();
  1466. Lambda.NumExplicitCaptures = Record.readInt();
  1467. Lambda.ManglingNumber = Record.readInt();
  1468. Lambda.ContextDecl = ReadDeclID();
  1469. Lambda.Captures = (Capture *)Reader.getContext().Allocate(
  1470. sizeof(Capture) * Lambda.NumCaptures);
  1471. Capture *ToCapture = Lambda.Captures;
  1472. Lambda.MethodTyInfo = GetTypeSourceInfo();
  1473. for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
  1474. SourceLocation Loc = ReadSourceLocation();
  1475. bool IsImplicit = Record.readInt();
  1476. auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
  1477. switch (Kind) {
  1478. case LCK_StarThis:
  1479. case LCK_This:
  1480. case LCK_VLAType:
  1481. *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
  1482. break;
  1483. case LCK_ByCopy:
  1484. case LCK_ByRef:
  1485. auto *Var = ReadDeclAs<VarDecl>();
  1486. SourceLocation EllipsisLoc = ReadSourceLocation();
  1487. *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
  1488. break;
  1489. }
  1490. }
  1491. }
  1492. }
  1493. void ASTDeclReader::MergeDefinitionData(
  1494. CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
  1495. assert(D->DefinitionData &&
  1496. "merging class definition into non-definition");
  1497. auto &DD = *D->DefinitionData;
  1498. if (DD.Definition != MergeDD.Definition) {
  1499. // Track that we merged the definitions.
  1500. Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
  1501. DD.Definition));
  1502. Reader.PendingDefinitions.erase(MergeDD.Definition);
  1503. MergeDD.Definition->IsCompleteDefinition = false;
  1504. Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
  1505. assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
  1506. "already loaded pending lookups for merged definition");
  1507. }
  1508. auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
  1509. if (PFDI != Reader.PendingFakeDefinitionData.end() &&
  1510. PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
  1511. // We faked up this definition data because we found a class for which we'd
  1512. // not yet loaded the definition. Replace it with the real thing now.
  1513. assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
  1514. PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
  1515. // Don't change which declaration is the definition; that is required
  1516. // to be invariant once we select it.
  1517. auto *Def = DD.Definition;
  1518. DD = std::move(MergeDD);
  1519. DD.Definition = Def;
  1520. return;
  1521. }
  1522. // FIXME: Move this out into a .def file?
  1523. bool DetectedOdrViolation = false;
  1524. #define OR_FIELD(Field) DD.Field |= MergeDD.Field;
  1525. #define MATCH_FIELD(Field) \
  1526. DetectedOdrViolation |= DD.Field != MergeDD.Field; \
  1527. OR_FIELD(Field)
  1528. MATCH_FIELD(UserDeclaredConstructor)
  1529. MATCH_FIELD(UserDeclaredSpecialMembers)
  1530. MATCH_FIELD(Aggregate)
  1531. MATCH_FIELD(PlainOldData)
  1532. MATCH_FIELD(Empty)
  1533. MATCH_FIELD(Polymorphic)
  1534. MATCH_FIELD(Abstract)
  1535. MATCH_FIELD(IsStandardLayout)
  1536. MATCH_FIELD(IsCXX11StandardLayout)
  1537. MATCH_FIELD(HasBasesWithFields)
  1538. MATCH_FIELD(HasBasesWithNonStaticDataMembers)
  1539. MATCH_FIELD(HasPrivateFields)
  1540. MATCH_FIELD(HasProtectedFields)
  1541. MATCH_FIELD(HasPublicFields)
  1542. MATCH_FIELD(HasMutableFields)
  1543. MATCH_FIELD(HasVariantMembers)
  1544. MATCH_FIELD(HasOnlyCMembers)
  1545. MATCH_FIELD(HasInClassInitializer)
  1546. MATCH_FIELD(HasUninitializedReferenceMember)
  1547. MATCH_FIELD(HasUninitializedFields)
  1548. MATCH_FIELD(HasInheritedConstructor)
  1549. MATCH_FIELD(HasInheritedAssignment)
  1550. MATCH_FIELD(NeedOverloadResolutionForCopyConstructor)
  1551. MATCH_FIELD(NeedOverloadResolutionForMoveConstructor)
  1552. MATCH_FIELD(NeedOverloadResolutionForMoveAssignment)
  1553. MATCH_FIELD(NeedOverloadResolutionForDestructor)
  1554. MATCH_FIELD(DefaultedCopyConstructorIsDeleted)
  1555. MATCH_FIELD(DefaultedMoveConstructorIsDeleted)
  1556. MATCH_FIELD(DefaultedMoveAssignmentIsDeleted)
  1557. MATCH_FIELD(DefaultedDestructorIsDeleted)
  1558. OR_FIELD(HasTrivialSpecialMembers)
  1559. OR_FIELD(HasTrivialSpecialMembersForCall)
  1560. OR_FIELD(DeclaredNonTrivialSpecialMembers)
  1561. OR_FIELD(DeclaredNonTrivialSpecialMembersForCall)
  1562. MATCH_FIELD(HasIrrelevantDestructor)
  1563. OR_FIELD(HasConstexprNonCopyMoveConstructor)
  1564. OR_FIELD(HasDefaultedDefaultConstructor)
  1565. MATCH_FIELD(DefaultedDefaultConstructorIsConstexpr)
  1566. OR_FIELD(HasConstexprDefaultConstructor)
  1567. MATCH_FIELD(HasNonLiteralTypeFieldsOrBases)
  1568. // ComputedVisibleConversions is handled below.
  1569. MATCH_FIELD(UserProvidedDefaultConstructor)
  1570. OR_FIELD(DeclaredSpecialMembers)
  1571. MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForVBase)
  1572. MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForNonVBase)
  1573. MATCH_FIELD(ImplicitCopyAssignmentHasConstParam)
  1574. OR_FIELD(HasDeclaredCopyConstructorWithConstParam)
  1575. OR_FIELD(HasDeclaredCopyAssignmentWithConstParam)
  1576. MATCH_FIELD(IsLambda)
  1577. #undef OR_FIELD
  1578. #undef MATCH_FIELD
  1579. if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
  1580. DetectedOdrViolation = true;
  1581. // FIXME: Issue a diagnostic if the base classes don't match when we come
  1582. // to lazily load them.
  1583. // FIXME: Issue a diagnostic if the list of conversion functions doesn't
  1584. // match when we come to lazily load them.
  1585. if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
  1586. DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
  1587. DD.ComputedVisibleConversions = true;
  1588. }
  1589. // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
  1590. // lazily load it.
  1591. if (DD.IsLambda) {
  1592. // FIXME: ODR-checking for merging lambdas (this happens, for instance,
  1593. // when they occur within the body of a function template specialization).
  1594. }
  1595. if (D->getODRHash() != MergeDD.ODRHash) {
  1596. DetectedOdrViolation = true;
  1597. }
  1598. if (DetectedOdrViolation)
  1599. Reader.PendingOdrMergeFailures[DD.Definition].push_back(
  1600. {MergeDD.Definition, &MergeDD});
  1601. }
  1602. void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
  1603. struct CXXRecordDecl::DefinitionData *DD;
  1604. ASTContext &C = Reader.getContext();
  1605. // Determine whether this is a lambda closure type, so that we can
  1606. // allocate the appropriate DefinitionData structure.
  1607. bool IsLambda = Record.readInt();
  1608. if (IsLambda)
  1609. DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
  1610. LCD_None);
  1611. else
  1612. DD = new (C) struct CXXRecordDecl::DefinitionData(D);
  1613. CXXRecordDecl *Canon = D->getCanonicalDecl();
  1614. // Set decl definition data before reading it, so that during deserialization
  1615. // when we read CXXRecordDecl, it already has definition data and we don't
  1616. // set fake one.
  1617. if (!Canon->DefinitionData)
  1618. Canon->DefinitionData = DD;
  1619. D->DefinitionData = Canon->DefinitionData;
  1620. ReadCXXDefinitionData(*DD, D);
  1621. // We might already have a different definition for this record. This can
  1622. // happen either because we're reading an update record, or because we've
  1623. // already done some merging. Either way, just merge into it.
  1624. if (Canon->DefinitionData != DD) {
  1625. MergeDefinitionData(Canon, std::move(*DD));
  1626. return;
  1627. }
  1628. // Mark this declaration as being a definition.
  1629. D->IsCompleteDefinition = true;
  1630. // If this is not the first declaration or is an update record, we can have
  1631. // other redeclarations already. Make a note that we need to propagate the
  1632. // DefinitionData pointer onto them.
  1633. if (Update || Canon != D)
  1634. Reader.PendingDefinitions.insert(D);
  1635. }
  1636. ASTDeclReader::RedeclarableResult
  1637. ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
  1638. RedeclarableResult Redecl = VisitRecordDeclImpl(D);
  1639. ASTContext &C = Reader.getContext();
  1640. enum CXXRecKind {
  1641. CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
  1642. };
  1643. switch ((CXXRecKind)Record.readInt()) {
  1644. case CXXRecNotTemplate:
  1645. // Merged when we merge the folding set entry in the primary template.
  1646. if (!isa<ClassTemplateSpecializationDecl>(D))
  1647. mergeRedeclarable(D, Redecl);
  1648. break;
  1649. case CXXRecTemplate: {
  1650. // Merged when we merge the template.
  1651. auto *Template = ReadDeclAs<ClassTemplateDecl>();
  1652. D->TemplateOrInstantiation = Template;
  1653. if (!Template->getTemplatedDecl()) {
  1654. // We've not actually loaded the ClassTemplateDecl yet, because we're
  1655. // currently being loaded as its pattern. Rely on it to set up our
  1656. // TypeForDecl (see VisitClassTemplateDecl).
  1657. //
  1658. // Beware: we do not yet know our canonical declaration, and may still
  1659. // get merged once the surrounding class template has got off the ground.
  1660. TypeIDForTypeDecl = 0;
  1661. }
  1662. break;
  1663. }
  1664. case CXXRecMemberSpecialization: {
  1665. auto *RD = ReadDeclAs<CXXRecordDecl>();
  1666. auto TSK = (TemplateSpecializationKind)Record.readInt();
  1667. SourceLocation POI = ReadSourceLocation();
  1668. MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
  1669. MSI->setPointOfInstantiation(POI);
  1670. D->TemplateOrInstantiation = MSI;
  1671. mergeRedeclarable(D, Redecl);
  1672. break;
  1673. }
  1674. }
  1675. bool WasDefinition = Record.readInt();
  1676. if (WasDefinition)
  1677. ReadCXXRecordDefinition(D, /*Update*/false);
  1678. else
  1679. // Propagate DefinitionData pointer from the canonical declaration.
  1680. D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
  1681. // Lazily load the key function to avoid deserializing every method so we can
  1682. // compute it.
  1683. if (WasDefinition) {
  1684. DeclID KeyFn = ReadDeclID();
  1685. if (KeyFn && D->IsCompleteDefinition)
  1686. // FIXME: This is wrong for the ARM ABI, where some other module may have
  1687. // made this function no longer be a key function. We need an update
  1688. // record or similar for that case.
  1689. C.KeyFunctions[D] = KeyFn;
  1690. }
  1691. return Redecl;
  1692. }
  1693. void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
  1694. VisitFunctionDecl(D);
  1695. D->IsCopyDeductionCandidate = Record.readInt();
  1696. }
  1697. void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
  1698. VisitFunctionDecl(D);
  1699. unsigned NumOverridenMethods = Record.readInt();
  1700. if (D->isCanonicalDecl()) {
  1701. while (NumOverridenMethods--) {
  1702. // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
  1703. // MD may be initializing.
  1704. if (auto *MD = ReadDeclAs<CXXMethodDecl>())
  1705. Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
  1706. }
  1707. } else {
  1708. // We don't care about which declarations this used to override; we get
  1709. // the relevant information from the canonical declaration.
  1710. Record.skipInts(NumOverridenMethods);
  1711. }
  1712. }
  1713. void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
  1714. // We need the inherited constructor information to merge the declaration,
  1715. // so we have to read it before we call VisitCXXMethodDecl.
  1716. if (D->isInheritingConstructor()) {
  1717. auto *Shadow = ReadDeclAs<ConstructorUsingShadowDecl>();
  1718. auto *Ctor = ReadDeclAs<CXXConstructorDecl>();
  1719. *D->getTrailingObjects<InheritedConstructor>() =
  1720. InheritedConstructor(Shadow, Ctor);
  1721. }
  1722. VisitCXXMethodDecl(D);
  1723. }
  1724. void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
  1725. VisitCXXMethodDecl(D);
  1726. if (auto *OperatorDelete = ReadDeclAs<FunctionDecl>()) {
  1727. CXXDestructorDecl *Canon = D->getCanonicalDecl();
  1728. auto *ThisArg = Record.readExpr();
  1729. // FIXME: Check consistency if we have an old and new operator delete.
  1730. if (!Canon->OperatorDelete) {
  1731. Canon->OperatorDelete = OperatorDelete;
  1732. Canon->OperatorDeleteThisArg = ThisArg;
  1733. }
  1734. }
  1735. }
  1736. void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
  1737. VisitCXXMethodDecl(D);
  1738. }
  1739. void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
  1740. VisitDecl(D);
  1741. D->ImportedAndComplete.setPointer(readModule());
  1742. D->ImportedAndComplete.setInt(Record.readInt());
  1743. auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
  1744. for (unsigned I = 0, N = Record.back(); I != N; ++I)
  1745. StoredLocs[I] = ReadSourceLocation();
  1746. Record.skipInts(1); // The number of stored source locations.
  1747. }
  1748. void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
  1749. VisitDecl(D);
  1750. D->setColonLoc(ReadSourceLocation());
  1751. }
  1752. void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
  1753. VisitDecl(D);
  1754. if (Record.readInt()) // hasFriendDecl
  1755. D->Friend = ReadDeclAs<NamedDecl>();
  1756. else
  1757. D->Friend = GetTypeSourceInfo();
  1758. for (unsigned i = 0; i != D->NumTPLists; ++i)
  1759. D->getTrailingObjects<TemplateParameterList *>()[i] =
  1760. Record.readTemplateParameterList();
  1761. D->NextFriend = ReadDeclID();
  1762. D->UnsupportedFriend = (Record.readInt() != 0);
  1763. D->FriendLoc = ReadSourceLocation();
  1764. }
  1765. void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
  1766. VisitDecl(D);
  1767. unsigned NumParams = Record.readInt();
  1768. D->NumParams = NumParams;
  1769. D->Params = new TemplateParameterList*[NumParams];
  1770. for (unsigned i = 0; i != NumParams; ++i)
  1771. D->Params[i] = Record.readTemplateParameterList();
  1772. if (Record.readInt()) // HasFriendDecl
  1773. D->Friend = ReadDeclAs<NamedDecl>();
  1774. else
  1775. D->Friend = GetTypeSourceInfo();
  1776. D->FriendLoc = ReadSourceLocation();
  1777. }
  1778. DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
  1779. VisitNamedDecl(D);
  1780. DeclID PatternID = ReadDeclID();
  1781. auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
  1782. TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
  1783. // FIXME handle associated constraints
  1784. D->init(TemplatedDecl, TemplateParams);
  1785. return PatternID;
  1786. }
  1787. ASTDeclReader::RedeclarableResult
  1788. ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
  1789. RedeclarableResult Redecl = VisitRedeclarable(D);
  1790. // Make sure we've allocated the Common pointer first. We do this before
  1791. // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
  1792. RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
  1793. if (!CanonD->Common) {
  1794. CanonD->Common = CanonD->newCommon(Reader.getContext());
  1795. Reader.PendingDefinitions.insert(CanonD);
  1796. }
  1797. D->Common = CanonD->Common;
  1798. // If this is the first declaration of the template, fill in the information
  1799. // for the 'common' pointer.
  1800. if (ThisDeclID == Redecl.getFirstID()) {
  1801. if (auto *RTD = ReadDeclAs<RedeclarableTemplateDecl>()) {
  1802. assert(RTD->getKind() == D->getKind() &&
  1803. "InstantiatedFromMemberTemplate kind mismatch");
  1804. D->setInstantiatedFromMemberTemplate(RTD);
  1805. if (Record.readInt())
  1806. D->setMemberSpecialization();
  1807. }
  1808. }
  1809. DeclID PatternID = VisitTemplateDecl(D);
  1810. D->IdentifierNamespace = Record.readInt();
  1811. mergeRedeclarable(D, Redecl, PatternID);
  1812. // If we merged the template with a prior declaration chain, merge the common
  1813. // pointer.
  1814. // FIXME: Actually merge here, don't just overwrite.
  1815. D->Common = D->getCanonicalDecl()->Common;
  1816. return Redecl;
  1817. }
  1818. void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
  1819. RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
  1820. if (ThisDeclID == Redecl.getFirstID()) {
  1821. // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
  1822. // the specializations.
  1823. SmallVector<serialization::DeclID, 32> SpecIDs;
  1824. ReadDeclIDList(SpecIDs);
  1825. ASTDeclReader::AddLazySpecializations(D, SpecIDs);
  1826. }
  1827. if (D->getTemplatedDecl()->TemplateOrInstantiation) {
  1828. // We were loaded before our templated declaration was. We've not set up
  1829. // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
  1830. // it now.
  1831. Reader.getContext().getInjectedClassNameType(
  1832. D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
  1833. }
  1834. }
  1835. void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
  1836. llvm_unreachable("BuiltinTemplates are not serialized");
  1837. }
  1838. /// TODO: Unify with ClassTemplateDecl version?
  1839. /// May require unifying ClassTemplateDecl and
  1840. /// VarTemplateDecl beyond TemplateDecl...
  1841. void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
  1842. RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
  1843. if (ThisDeclID == Redecl.getFirstID()) {
  1844. // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
  1845. // the specializations.
  1846. SmallVector<serialization::DeclID, 32> SpecIDs;
  1847. ReadDeclIDList(SpecIDs);
  1848. ASTDeclReader::AddLazySpecializations(D, SpecIDs);
  1849. }
  1850. }
  1851. ASTDeclReader::RedeclarableResult
  1852. ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
  1853. ClassTemplateSpecializationDecl *D) {
  1854. RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
  1855. ASTContext &C = Reader.getContext();
  1856. if (Decl *InstD = ReadDecl()) {
  1857. if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
  1858. D->SpecializedTemplate = CTD;
  1859. } else {
  1860. SmallVector<TemplateArgument, 8> TemplArgs;
  1861. Record.readTemplateArgumentList(TemplArgs);
  1862. TemplateArgumentList *ArgList
  1863. = TemplateArgumentList::CreateCopy(C, TemplArgs);
  1864. auto *PS =
  1865. new (C) ClassTemplateSpecializationDecl::
  1866. SpecializedPartialSpecialization();
  1867. PS->PartialSpecialization
  1868. = cast<ClassTemplatePartialSpecializationDecl>(InstD);
  1869. PS->TemplateArgs = ArgList;
  1870. D->SpecializedTemplate = PS;
  1871. }
  1872. }
  1873. SmallVector<TemplateArgument, 8> TemplArgs;
  1874. Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
  1875. D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
  1876. D->PointOfInstantiation = ReadSourceLocation();
  1877. D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
  1878. bool writtenAsCanonicalDecl = Record.readInt();
  1879. if (writtenAsCanonicalDecl) {
  1880. auto *CanonPattern = ReadDeclAs<ClassTemplateDecl>();
  1881. if (D->isCanonicalDecl()) { // It's kept in the folding set.
  1882. // Set this as, or find, the canonical declaration for this specialization
  1883. ClassTemplateSpecializationDecl *CanonSpec;
  1884. if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
  1885. CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
  1886. .GetOrInsertNode(Partial);
  1887. } else {
  1888. CanonSpec =
  1889. CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
  1890. }
  1891. // If there was already a canonical specialization, merge into it.
  1892. if (CanonSpec != D) {
  1893. mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
  1894. // This declaration might be a definition. Merge with any existing
  1895. // definition.
  1896. if (auto *DDD = D->DefinitionData) {
  1897. if (CanonSpec->DefinitionData)
  1898. MergeDefinitionData(CanonSpec, std::move(*DDD));
  1899. else
  1900. CanonSpec->DefinitionData = D->DefinitionData;
  1901. }
  1902. D->DefinitionData = CanonSpec->DefinitionData;
  1903. }
  1904. }
  1905. }
  1906. // Explicit info.
  1907. if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
  1908. auto *ExplicitInfo =
  1909. new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
  1910. ExplicitInfo->TypeAsWritten = TyInfo;
  1911. ExplicitInfo->ExternLoc = ReadSourceLocation();
  1912. ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
  1913. D->ExplicitInfo = ExplicitInfo;
  1914. }
  1915. return Redecl;
  1916. }
  1917. void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
  1918. ClassTemplatePartialSpecializationDecl *D) {
  1919. RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
  1920. D->TemplateParams = Record.readTemplateParameterList();
  1921. D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
  1922. // These are read/set from/to the first declaration.
  1923. if (ThisDeclID == Redecl.getFirstID()) {
  1924. D->InstantiatedFromMember.setPointer(
  1925. ReadDeclAs<ClassTemplatePartialSpecializationDecl>());
  1926. D->InstantiatedFromMember.setInt(Record.readInt());
  1927. }
  1928. }
  1929. void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
  1930. ClassScopeFunctionSpecializationDecl *D) {
  1931. VisitDecl(D);
  1932. D->Specialization = ReadDeclAs<CXXMethodDecl>();
  1933. }
  1934. void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
  1935. RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
  1936. if (ThisDeclID == Redecl.getFirstID()) {
  1937. // This FunctionTemplateDecl owns a CommonPtr; read it.
  1938. SmallVector<serialization::DeclID, 32> SpecIDs;
  1939. ReadDeclIDList(SpecIDs);
  1940. ASTDeclReader::AddLazySpecializations(D, SpecIDs);
  1941. }
  1942. }
  1943. /// TODO: Unify with ClassTemplateSpecializationDecl version?
  1944. /// May require unifying ClassTemplate(Partial)SpecializationDecl and
  1945. /// VarTemplate(Partial)SpecializationDecl with a new data
  1946. /// structure Template(Partial)SpecializationDecl, and
  1947. /// using Template(Partial)SpecializationDecl as input type.
  1948. ASTDeclReader::RedeclarableResult
  1949. ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
  1950. VarTemplateSpecializationDecl *D) {
  1951. RedeclarableResult Redecl = VisitVarDeclImpl(D);
  1952. ASTContext &C = Reader.getContext();
  1953. if (Decl *InstD = ReadDecl()) {
  1954. if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
  1955. D->SpecializedTemplate = VTD;
  1956. } else {
  1957. SmallVector<TemplateArgument, 8> TemplArgs;
  1958. Record.readTemplateArgumentList(TemplArgs);
  1959. TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
  1960. C, TemplArgs);
  1961. auto *PS =
  1962. new (C)
  1963. VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
  1964. PS->PartialSpecialization =
  1965. cast<VarTemplatePartialSpecializationDecl>(InstD);
  1966. PS->TemplateArgs = ArgList;
  1967. D->SpecializedTemplate = PS;
  1968. }
  1969. }
  1970. // Explicit info.
  1971. if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
  1972. auto *ExplicitInfo =
  1973. new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
  1974. ExplicitInfo->TypeAsWritten = TyInfo;
  1975. ExplicitInfo->ExternLoc = ReadSourceLocation();
  1976. ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
  1977. D->ExplicitInfo = ExplicitInfo;
  1978. }
  1979. SmallVector<TemplateArgument, 8> TemplArgs;
  1980. Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
  1981. D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
  1982. D->PointOfInstantiation = ReadSourceLocation();
  1983. D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
  1984. D->IsCompleteDefinition = Record.readInt();
  1985. bool writtenAsCanonicalDecl = Record.readInt();
  1986. if (writtenAsCanonicalDecl) {
  1987. auto *CanonPattern = ReadDeclAs<VarTemplateDecl>();
  1988. if (D->isCanonicalDecl()) { // It's kept in the folding set.
  1989. // FIXME: If it's already present, merge it.
  1990. if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
  1991. CanonPattern->getCommonPtr()->PartialSpecializations
  1992. .GetOrInsertNode(Partial);
  1993. } else {
  1994. CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
  1995. }
  1996. }
  1997. }
  1998. return Redecl;
  1999. }
  2000. /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
  2001. /// May require unifying ClassTemplate(Partial)SpecializationDecl and
  2002. /// VarTemplate(Partial)SpecializationDecl with a new data
  2003. /// structure Template(Partial)SpecializationDecl, and
  2004. /// using Template(Partial)SpecializationDecl as input type.
  2005. void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
  2006. VarTemplatePartialSpecializationDecl *D) {
  2007. RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
  2008. D->TemplateParams = Record.readTemplateParameterList();
  2009. D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
  2010. // These are read/set from/to the first declaration.
  2011. if (ThisDeclID == Redecl.getFirstID()) {
  2012. D->InstantiatedFromMember.setPointer(
  2013. ReadDeclAs<VarTemplatePartialSpecializationDecl>());
  2014. D->InstantiatedFromMember.setInt(Record.readInt());
  2015. }
  2016. }
  2017. void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
  2018. VisitTypeDecl(D);
  2019. D->setDeclaredWithTypename(Record.readInt());
  2020. if (Record.readInt())
  2021. D->setDefaultArgument(GetTypeSourceInfo());
  2022. }
  2023. void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
  2024. VisitDeclaratorDecl(D);
  2025. // TemplateParmPosition.
  2026. D->setDepth(Record.readInt());
  2027. D->setPosition(Record.readInt());
  2028. if (D->isExpandedParameterPack()) {
  2029. auto TypesAndInfos =
  2030. D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
  2031. for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
  2032. new (&TypesAndInfos[I].first) QualType(Record.readType());
  2033. TypesAndInfos[I].second = GetTypeSourceInfo();
  2034. }
  2035. } else {
  2036. // Rest of NonTypeTemplateParmDecl.
  2037. D->ParameterPack = Record.readInt();
  2038. if (Record.readInt())
  2039. D->setDefaultArgument(Record.readExpr());
  2040. }
  2041. }
  2042. void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
  2043. VisitTemplateDecl(D);
  2044. // TemplateParmPosition.
  2045. D->setDepth(Record.readInt());
  2046. D->setPosition(Record.readInt());
  2047. if (D->isExpandedParameterPack()) {
  2048. auto **Data = D->getTrailingObjects<TemplateParameterList *>();
  2049. for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
  2050. I != N; ++I)
  2051. Data[I] = Record.readTemplateParameterList();
  2052. } else {
  2053. // Rest of TemplateTemplateParmDecl.
  2054. D->ParameterPack = Record.readInt();
  2055. if (Record.readInt())
  2056. D->setDefaultArgument(Reader.getContext(),
  2057. Record.readTemplateArgumentLoc());
  2058. }
  2059. }
  2060. void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
  2061. VisitRedeclarableTemplateDecl(D);
  2062. }
  2063. void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
  2064. VisitDecl(D);
  2065. D->AssertExprAndFailed.setPointer(Record.readExpr());
  2066. D->AssertExprAndFailed.setInt(Record.readInt());
  2067. D->Message = cast_or_null<StringLiteral>(Record.readExpr());
  2068. D->RParenLoc = ReadSourceLocation();
  2069. }
  2070. void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
  2071. VisitDecl(D);
  2072. }
  2073. std::pair<uint64_t, uint64_t>
  2074. ASTDeclReader::VisitDeclContext(DeclContext *DC) {
  2075. uint64_t LexicalOffset = ReadLocalOffset();
  2076. uint64_t VisibleOffset = ReadLocalOffset();
  2077. return std::make_pair(LexicalOffset, VisibleOffset);
  2078. }
  2079. template <typename T>
  2080. ASTDeclReader::RedeclarableResult
  2081. ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
  2082. DeclID FirstDeclID = ReadDeclID();
  2083. Decl *MergeWith = nullptr;
  2084. bool IsKeyDecl = ThisDeclID == FirstDeclID;
  2085. bool IsFirstLocalDecl = false;
  2086. uint64_t RedeclOffset = 0;
  2087. // 0 indicates that this declaration was the only declaration of its entity,
  2088. // and is used for space optimization.
  2089. if (FirstDeclID == 0) {
  2090. FirstDeclID = ThisDeclID;
  2091. IsKeyDecl = true;
  2092. IsFirstLocalDecl = true;
  2093. } else if (unsigned N = Record.readInt()) {
  2094. // This declaration was the first local declaration, but may have imported
  2095. // other declarations.
  2096. IsKeyDecl = N == 1;
  2097. IsFirstLocalDecl = true;
  2098. // We have some declarations that must be before us in our redeclaration
  2099. // chain. Read them now, and remember that we ought to merge with one of
  2100. // them.
  2101. // FIXME: Provide a known merge target to the second and subsequent such
  2102. // declaration.
  2103. for (unsigned I = 0; I != N - 1; ++I)
  2104. MergeWith = ReadDecl();
  2105. RedeclOffset = ReadLocalOffset();
  2106. } else {
  2107. // This declaration was not the first local declaration. Read the first
  2108. // local declaration now, to trigger the import of other redeclarations.
  2109. (void)ReadDecl();
  2110. }
  2111. auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
  2112. if (FirstDecl != D) {
  2113. // We delay loading of the redeclaration chain to avoid deeply nested calls.
  2114. // We temporarily set the first (canonical) declaration as the previous one
  2115. // which is the one that matters and mark the real previous DeclID to be
  2116. // loaded & attached later on.
  2117. D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
  2118. D->First = FirstDecl->getCanonicalDecl();
  2119. }
  2120. auto *DAsT = static_cast<T *>(D);
  2121. // Note that we need to load local redeclarations of this decl and build a
  2122. // decl chain for them. This must happen *after* we perform the preloading
  2123. // above; this ensures that the redeclaration chain is built in the correct
  2124. // order.
  2125. if (IsFirstLocalDecl)
  2126. Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
  2127. return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
  2128. }
  2129. /// \brief Attempts to merge the given declaration (D) with another declaration
  2130. /// of the same entity.
  2131. template<typename T>
  2132. void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
  2133. RedeclarableResult &Redecl,
  2134. DeclID TemplatePatternID) {
  2135. // If modules are not available, there is no reason to perform this merge.
  2136. if (!Reader.getContext().getLangOpts().Modules)
  2137. return;
  2138. // If we're not the canonical declaration, we don't need to merge.
  2139. if (!DBase->isFirstDecl())
  2140. return;
  2141. auto *D = static_cast<T *>(DBase);
  2142. if (auto *Existing = Redecl.getKnownMergeTarget())
  2143. // We already know of an existing declaration we should merge with.
  2144. mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
  2145. else if (FindExistingResult ExistingRes = findExisting(D))
  2146. if (T *Existing = ExistingRes)
  2147. mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
  2148. }
  2149. /// \brief "Cast" to type T, asserting if we don't have an implicit conversion.
  2150. /// We use this to put code in a template that will only be valid for certain
  2151. /// instantiations.
  2152. template<typename T> static T assert_cast(T t) { return t; }
  2153. template<typename T> static T assert_cast(...) {
  2154. llvm_unreachable("bad assert_cast");
  2155. }
  2156. /// \brief Merge together the pattern declarations from two template
  2157. /// declarations.
  2158. void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
  2159. RedeclarableTemplateDecl *Existing,
  2160. DeclID DsID, bool IsKeyDecl) {
  2161. auto *DPattern = D->getTemplatedDecl();
  2162. auto *ExistingPattern = Existing->getTemplatedDecl();
  2163. RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
  2164. DPattern->getCanonicalDecl()->getGlobalID(),
  2165. IsKeyDecl);
  2166. if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
  2167. // Merge with any existing definition.
  2168. // FIXME: This is duplicated in several places. Refactor.
  2169. auto *ExistingClass =
  2170. cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
  2171. if (auto *DDD = DClass->DefinitionData) {
  2172. if (ExistingClass->DefinitionData) {
  2173. MergeDefinitionData(ExistingClass, std::move(*DDD));
  2174. } else {
  2175. ExistingClass->DefinitionData = DClass->DefinitionData;
  2176. // We may have skipped this before because we thought that DClass
  2177. // was the canonical declaration.
  2178. Reader.PendingDefinitions.insert(DClass);
  2179. }
  2180. }
  2181. DClass->DefinitionData = ExistingClass->DefinitionData;
  2182. return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
  2183. Result);
  2184. }
  2185. if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
  2186. return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
  2187. Result);
  2188. if (auto *DVar = dyn_cast<VarDecl>(DPattern))
  2189. return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
  2190. if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
  2191. return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
  2192. Result);
  2193. llvm_unreachable("merged an unknown kind of redeclarable template");
  2194. }
  2195. /// \brief Attempts to merge the given declaration (D) with another declaration
  2196. /// of the same entity.
  2197. template<typename T>
  2198. void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
  2199. RedeclarableResult &Redecl,
  2200. DeclID TemplatePatternID) {
  2201. auto *D = static_cast<T *>(DBase);
  2202. T *ExistingCanon = Existing->getCanonicalDecl();
  2203. T *DCanon = D->getCanonicalDecl();
  2204. if (ExistingCanon != DCanon) {
  2205. assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
  2206. "already merged this declaration");
  2207. // Have our redeclaration link point back at the canonical declaration
  2208. // of the existing declaration, so that this declaration has the
  2209. // appropriate canonical declaration.
  2210. D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
  2211. D->First = ExistingCanon;
  2212. ExistingCanon->Used |= D->Used;
  2213. D->Used = false;
  2214. // When we merge a namespace, update its pointer to the first namespace.
  2215. // We cannot have loaded any redeclarations of this declaration yet, so
  2216. // there's nothing else that needs to be updated.
  2217. if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
  2218. Namespace->AnonOrFirstNamespaceAndInline.setPointer(
  2219. assert_cast<NamespaceDecl*>(ExistingCanon));
  2220. // When we merge a template, merge its pattern.
  2221. if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
  2222. mergeTemplatePattern(
  2223. DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
  2224. TemplatePatternID, Redecl.isKeyDecl());
  2225. // If this declaration is a key declaration, make a note of that.
  2226. if (Redecl.isKeyDecl())
  2227. Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
  2228. }
  2229. }
  2230. /// \brief Attempts to merge the given declaration (D) with another declaration
  2231. /// of the same entity, for the case where the entity is not actually
  2232. /// redeclarable. This happens, for instance, when merging the fields of
  2233. /// identical class definitions from two different modules.
  2234. template<typename T>
  2235. void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
  2236. // If modules are not available, there is no reason to perform this merge.
  2237. if (!Reader.getContext().getLangOpts().Modules)
  2238. return;
  2239. // ODR-based merging is only performed in C++. In C, identically-named things
  2240. // in different translation units are not redeclarations (but may still have
  2241. // compatible types).
  2242. if (!Reader.getContext().getLangOpts().CPlusPlus)
  2243. return;
  2244. if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
  2245. if (T *Existing = ExistingRes)
  2246. Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
  2247. Existing->getCanonicalDecl());
  2248. }
  2249. void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
  2250. VisitDecl(D);
  2251. unsigned NumVars = D->varlist_size();
  2252. SmallVector<Expr *, 16> Vars;
  2253. Vars.reserve(NumVars);
  2254. for (unsigned i = 0; i != NumVars; ++i) {
  2255. Vars.push_back(Record.readExpr());
  2256. }
  2257. D->setVars(Vars);
  2258. }
  2259. void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
  2260. VisitValueDecl(D);
  2261. D->setLocation(ReadSourceLocation());
  2262. D->setCombiner(Record.readExpr());
  2263. D->setInitializer(
  2264. Record.readExpr(),
  2265. static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt()));
  2266. D->PrevDeclInScope = ReadDeclID();
  2267. }
  2268. void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
  2269. VisitVarDecl(D);
  2270. }
  2271. //===----------------------------------------------------------------------===//
  2272. // Attribute Reading
  2273. //===----------------------------------------------------------------------===//
  2274. /// \brief Reads attributes from the current stream position.
  2275. void ASTReader::ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs) {
  2276. for (unsigned i = 0, e = Record.readInt(); i != e; ++i) {
  2277. Attr *New = nullptr;
  2278. auto Kind = (attr::Kind)Record.readInt();
  2279. SourceRange Range = Record.readSourceRange();
  2280. ASTContext &Context = getContext();
  2281. #include "clang/Serialization/AttrPCHRead.inc"
  2282. assert(New && "Unable to decode attribute?");
  2283. Attrs.push_back(New);
  2284. }
  2285. }
  2286. //===----------------------------------------------------------------------===//
  2287. // ASTReader Implementation
  2288. //===----------------------------------------------------------------------===//
  2289. /// \brief Note that we have loaded the declaration with the given
  2290. /// Index.
  2291. ///
  2292. /// This routine notes that this declaration has already been loaded,
  2293. /// so that future GetDecl calls will return this declaration rather
  2294. /// than trying to load a new declaration.
  2295. inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
  2296. assert(!DeclsLoaded[Index] && "Decl loaded twice?");
  2297. DeclsLoaded[Index] = D;
  2298. }
  2299. /// \brief Determine whether the consumer will be interested in seeing
  2300. /// this declaration (via HandleTopLevelDecl).
  2301. ///
  2302. /// This routine should return true for anything that might affect
  2303. /// code generation, e.g., inline function definitions, Objective-C
  2304. /// declarations with metadata, etc.
  2305. static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
  2306. // An ObjCMethodDecl is never considered as "interesting" because its
  2307. // implementation container always is.
  2308. // An ImportDecl or VarDecl imported from a module map module will get
  2309. // emitted when we import the relevant module.
  2310. if (isa<ImportDecl>(D) || isa<VarDecl>(D)) {
  2311. auto *M = D->getImportedOwningModule();
  2312. if (M && M->Kind == Module::ModuleMapModule &&
  2313. Ctx.DeclMustBeEmitted(D))
  2314. return false;
  2315. }
  2316. if (isa<FileScopeAsmDecl>(D) ||
  2317. isa<ObjCProtocolDecl>(D) ||
  2318. isa<ObjCImplDecl>(D) ||
  2319. isa<ImportDecl>(D) ||
  2320. isa<PragmaCommentDecl>(D) ||
  2321. isa<PragmaDetectMismatchDecl>(D))
  2322. return true;
  2323. if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D))
  2324. return !D->getDeclContext()->isFunctionOrMethod();
  2325. if (const auto *Var = dyn_cast<VarDecl>(D))
  2326. return Var->isFileVarDecl() &&
  2327. Var->isThisDeclarationADefinition() == VarDecl::Definition;
  2328. if (const auto *Func = dyn_cast<FunctionDecl>(D))
  2329. return Func->doesThisDeclarationHaveABody() || HasBody;
  2330. if (auto *ES = D->getASTContext().getExternalSource())
  2331. if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
  2332. return true;
  2333. return false;
  2334. }
  2335. /// \brief Get the correct cursor and offset for loading a declaration.
  2336. ASTReader::RecordLocation
  2337. ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
  2338. GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
  2339. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  2340. ModuleFile *M = I->second;
  2341. const DeclOffset &DOffs =
  2342. M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
  2343. Loc = TranslateSourceLocation(*M, DOffs.getLocation());
  2344. return RecordLocation(M, DOffs.BitOffset);
  2345. }
  2346. ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
  2347. auto I = GlobalBitOffsetsMap.find(GlobalOffset);
  2348. assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
  2349. return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
  2350. }
  2351. uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
  2352. return LocalOffset + M.GlobalBitOffset;
  2353. }
  2354. static bool isSameTemplateParameterList(const TemplateParameterList *X,
  2355. const TemplateParameterList *Y);
  2356. /// \brief Determine whether two template parameters are similar enough
  2357. /// that they may be used in declarations of the same template.
  2358. static bool isSameTemplateParameter(const NamedDecl *X,
  2359. const NamedDecl *Y) {
  2360. if (X->getKind() != Y->getKind())
  2361. return false;
  2362. if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
  2363. const auto *TY = cast<TemplateTypeParmDecl>(Y);
  2364. return TX->isParameterPack() == TY->isParameterPack();
  2365. }
  2366. if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
  2367. const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
  2368. return TX->isParameterPack() == TY->isParameterPack() &&
  2369. TX->getASTContext().hasSameType(TX->getType(), TY->getType());
  2370. }
  2371. const auto *TX = cast<TemplateTemplateParmDecl>(X);
  2372. const auto *TY = cast<TemplateTemplateParmDecl>(Y);
  2373. return TX->isParameterPack() == TY->isParameterPack() &&
  2374. isSameTemplateParameterList(TX->getTemplateParameters(),
  2375. TY->getTemplateParameters());
  2376. }
  2377. static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
  2378. if (auto *NS = X->getAsNamespace())
  2379. return NS;
  2380. if (auto *NAS = X->getAsNamespaceAlias())
  2381. return NAS->getNamespace();
  2382. return nullptr;
  2383. }
  2384. static bool isSameQualifier(const NestedNameSpecifier *X,
  2385. const NestedNameSpecifier *Y) {
  2386. if (auto *NSX = getNamespace(X)) {
  2387. auto *NSY = getNamespace(Y);
  2388. if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
  2389. return false;
  2390. } else if (X->getKind() != Y->getKind())
  2391. return false;
  2392. // FIXME: For namespaces and types, we're permitted to check that the entity
  2393. // is named via the same tokens. We should probably do so.
  2394. switch (X->getKind()) {
  2395. case NestedNameSpecifier::Identifier:
  2396. if (X->getAsIdentifier() != Y->getAsIdentifier())
  2397. return false;
  2398. break;
  2399. case NestedNameSpecifier::Namespace:
  2400. case NestedNameSpecifier::NamespaceAlias:
  2401. // We've already checked that we named the same namespace.
  2402. break;
  2403. case NestedNameSpecifier::TypeSpec:
  2404. case NestedNameSpecifier::TypeSpecWithTemplate:
  2405. if (X->getAsType()->getCanonicalTypeInternal() !=
  2406. Y->getAsType()->getCanonicalTypeInternal())
  2407. return false;
  2408. break;
  2409. case NestedNameSpecifier::Global:
  2410. case NestedNameSpecifier::Super:
  2411. return true;
  2412. }
  2413. // Recurse into earlier portion of NNS, if any.
  2414. auto *PX = X->getPrefix();
  2415. auto *PY = Y->getPrefix();
  2416. if (PX && PY)
  2417. return isSameQualifier(PX, PY);
  2418. return !PX && !PY;
  2419. }
  2420. /// \brief Determine whether two template parameter lists are similar enough
  2421. /// that they may be used in declarations of the same template.
  2422. static bool isSameTemplateParameterList(const TemplateParameterList *X,
  2423. const TemplateParameterList *Y) {
  2424. if (X->size() != Y->size())
  2425. return false;
  2426. for (unsigned I = 0, N = X->size(); I != N; ++I)
  2427. if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
  2428. return false;
  2429. return true;
  2430. }
  2431. /// Determine whether the attributes we can overload on are identical for A and
  2432. /// B. Will ignore any overloadable attrs represented in the type of A and B.
  2433. static bool hasSameOverloadableAttrs(const FunctionDecl *A,
  2434. const FunctionDecl *B) {
  2435. // Note that pass_object_size attributes are represented in the function's
  2436. // ExtParameterInfo, so we don't need to check them here.
  2437. SmallVector<const EnableIfAttr *, 4> AEnableIfs;
  2438. // Since this is an equality check, we can ignore that enable_if attrs show up
  2439. // in reverse order.
  2440. for (const auto *EIA : A->specific_attrs<EnableIfAttr>())
  2441. AEnableIfs.push_back(EIA);
  2442. SmallVector<const EnableIfAttr *, 4> BEnableIfs;
  2443. for (const auto *EIA : B->specific_attrs<EnableIfAttr>())
  2444. BEnableIfs.push_back(EIA);
  2445. // Two very common cases: either we have 0 enable_if attrs, or we have an
  2446. // unequal number of enable_if attrs.
  2447. if (AEnableIfs.empty() && BEnableIfs.empty())
  2448. return true;
  2449. if (AEnableIfs.size() != BEnableIfs.size())
  2450. return false;
  2451. llvm::FoldingSetNodeID Cand1ID, Cand2ID;
  2452. for (unsigned I = 0, E = AEnableIfs.size(); I != E; ++I) {
  2453. Cand1ID.clear();
  2454. Cand2ID.clear();
  2455. AEnableIfs[I]->getCond()->Profile(Cand1ID, A->getASTContext(), true);
  2456. BEnableIfs[I]->getCond()->Profile(Cand2ID, B->getASTContext(), true);
  2457. if (Cand1ID != Cand2ID)
  2458. return false;
  2459. }
  2460. return true;
  2461. }
  2462. /// \brief Determine whether the two declarations refer to the same entity.
  2463. static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
  2464. assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
  2465. if (X == Y)
  2466. return true;
  2467. // Must be in the same context.
  2468. if (!X->getDeclContext()->getRedeclContext()->Equals(
  2469. Y->getDeclContext()->getRedeclContext()))
  2470. return false;
  2471. // Two typedefs refer to the same entity if they have the same underlying
  2472. // type.
  2473. if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
  2474. if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
  2475. return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
  2476. TypedefY->getUnderlyingType());
  2477. // Must have the same kind.
  2478. if (X->getKind() != Y->getKind())
  2479. return false;
  2480. // Objective-C classes and protocols with the same name always match.
  2481. if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
  2482. return true;
  2483. if (isa<ClassTemplateSpecializationDecl>(X)) {
  2484. // No need to handle these here: we merge them when adding them to the
  2485. // template.
  2486. return false;
  2487. }
  2488. // Compatible tags match.
  2489. if (const auto *TagX = dyn_cast<TagDecl>(X)) {
  2490. const auto *TagY = cast<TagDecl>(Y);
  2491. return (TagX->getTagKind() == TagY->getTagKind()) ||
  2492. ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
  2493. TagX->getTagKind() == TTK_Interface) &&
  2494. (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
  2495. TagY->getTagKind() == TTK_Interface));
  2496. }
  2497. // Functions with the same type and linkage match.
  2498. // FIXME: This needs to cope with merging of prototyped/non-prototyped
  2499. // functions, etc.
  2500. if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
  2501. const auto *FuncY = cast<FunctionDecl>(Y);
  2502. if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
  2503. const auto *CtorY = cast<CXXConstructorDecl>(Y);
  2504. if (CtorX->getInheritedConstructor() &&
  2505. !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
  2506. CtorY->getInheritedConstructor().getConstructor()))
  2507. return false;
  2508. }
  2509. if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
  2510. return false;
  2511. // Multiversioned functions with different feature strings are represented
  2512. // as separate declarations.
  2513. if (FuncX->isMultiVersion()) {
  2514. const auto *TAX = FuncX->getAttr<TargetAttr>();
  2515. const auto *TAY = FuncY->getAttr<TargetAttr>();
  2516. assert(TAX && TAY && "Multiversion Function without target attribute");
  2517. if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
  2518. return false;
  2519. }
  2520. ASTContext &C = FuncX->getASTContext();
  2521. if (!C.hasSameType(FuncX->getType(), FuncY->getType())) {
  2522. // We can get functions with different types on the redecl chain in C++17
  2523. // if they have differing exception specifications and at least one of
  2524. // the excpetion specs is unresolved.
  2525. // FIXME: Do we need to check for C++14 deduced return types here too?
  2526. auto *XFPT = FuncX->getType()->getAs<FunctionProtoType>();
  2527. auto *YFPT = FuncY->getType()->getAs<FunctionProtoType>();
  2528. if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
  2529. (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
  2530. isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
  2531. C.hasSameFunctionTypeIgnoringExceptionSpec(FuncX->getType(),
  2532. FuncY->getType()))
  2533. return true;
  2534. return false;
  2535. }
  2536. return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
  2537. hasSameOverloadableAttrs(FuncX, FuncY);
  2538. }
  2539. // Variables with the same type and linkage match.
  2540. if (const auto *VarX = dyn_cast<VarDecl>(X)) {
  2541. const auto *VarY = cast<VarDecl>(Y);
  2542. if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
  2543. ASTContext &C = VarX->getASTContext();
  2544. if (C.hasSameType(VarX->getType(), VarY->getType()))
  2545. return true;
  2546. // We can get decls with different types on the redecl chain. Eg.
  2547. // template <typename T> struct S { static T Var[]; }; // #1
  2548. // template <typename T> T S<T>::Var[sizeof(T)]; // #2
  2549. // Only? happens when completing an incomplete array type. In this case
  2550. // when comparing #1 and #2 we should go through their element type.
  2551. const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
  2552. const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
  2553. if (!VarXTy || !VarYTy)
  2554. return false;
  2555. if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
  2556. return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
  2557. }
  2558. return false;
  2559. }
  2560. // Namespaces with the same name and inlinedness match.
  2561. if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
  2562. const auto *NamespaceY = cast<NamespaceDecl>(Y);
  2563. return NamespaceX->isInline() == NamespaceY->isInline();
  2564. }
  2565. // Identical template names and kinds match if their template parameter lists
  2566. // and patterns match.
  2567. if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
  2568. const auto *TemplateY = cast<TemplateDecl>(Y);
  2569. return isSameEntity(TemplateX->getTemplatedDecl(),
  2570. TemplateY->getTemplatedDecl()) &&
  2571. isSameTemplateParameterList(TemplateX->getTemplateParameters(),
  2572. TemplateY->getTemplateParameters());
  2573. }
  2574. // Fields with the same name and the same type match.
  2575. if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
  2576. const auto *FDY = cast<FieldDecl>(Y);
  2577. // FIXME: Also check the bitwidth is odr-equivalent, if any.
  2578. return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
  2579. }
  2580. // Indirect fields with the same target field match.
  2581. if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
  2582. const auto *IFDY = cast<IndirectFieldDecl>(Y);
  2583. return IFDX->getAnonField()->getCanonicalDecl() ==
  2584. IFDY->getAnonField()->getCanonicalDecl();
  2585. }
  2586. // Enumerators with the same name match.
  2587. if (isa<EnumConstantDecl>(X))
  2588. // FIXME: Also check the value is odr-equivalent.
  2589. return true;
  2590. // Using shadow declarations with the same target match.
  2591. if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
  2592. const auto *USY = cast<UsingShadowDecl>(Y);
  2593. return USX->getTargetDecl() == USY->getTargetDecl();
  2594. }
  2595. // Using declarations with the same qualifier match. (We already know that
  2596. // the name matches.)
  2597. if (const auto *UX = dyn_cast<UsingDecl>(X)) {
  2598. const auto *UY = cast<UsingDecl>(Y);
  2599. return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
  2600. UX->hasTypename() == UY->hasTypename() &&
  2601. UX->isAccessDeclaration() == UY->isAccessDeclaration();
  2602. }
  2603. if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
  2604. const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
  2605. return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
  2606. UX->isAccessDeclaration() == UY->isAccessDeclaration();
  2607. }
  2608. if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
  2609. return isSameQualifier(
  2610. UX->getQualifier(),
  2611. cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
  2612. // Namespace alias definitions with the same target match.
  2613. if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
  2614. const auto *NAY = cast<NamespaceAliasDecl>(Y);
  2615. return NAX->getNamespace()->Equals(NAY->getNamespace());
  2616. }
  2617. return false;
  2618. }
  2619. /// Find the context in which we should search for previous declarations when
  2620. /// looking for declarations to merge.
  2621. DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
  2622. DeclContext *DC) {
  2623. if (auto *ND = dyn_cast<NamespaceDecl>(DC))
  2624. return ND->getOriginalNamespace();
  2625. if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
  2626. // Try to dig out the definition.
  2627. auto *DD = RD->DefinitionData;
  2628. if (!DD)
  2629. DD = RD->getCanonicalDecl()->DefinitionData;
  2630. // If there's no definition yet, then DC's definition is added by an update
  2631. // record, but we've not yet loaded that update record. In this case, we
  2632. // commit to DC being the canonical definition now, and will fix this when
  2633. // we load the update record.
  2634. if (!DD) {
  2635. DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
  2636. RD->IsCompleteDefinition = true;
  2637. RD->DefinitionData = DD;
  2638. RD->getCanonicalDecl()->DefinitionData = DD;
  2639. // Track that we did this horrible thing so that we can fix it later.
  2640. Reader.PendingFakeDefinitionData.insert(
  2641. std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
  2642. }
  2643. return DD->Definition;
  2644. }
  2645. if (auto *ED = dyn_cast<EnumDecl>(DC))
  2646. return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
  2647. : nullptr;
  2648. // We can see the TU here only if we have no Sema object. In that case,
  2649. // there's no TU scope to look in, so using the DC alone is sufficient.
  2650. if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
  2651. return TU;
  2652. return nullptr;
  2653. }
  2654. ASTDeclReader::FindExistingResult::~FindExistingResult() {
  2655. // Record that we had a typedef name for linkage whether or not we merge
  2656. // with that declaration.
  2657. if (TypedefNameForLinkage) {
  2658. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  2659. Reader.ImportedTypedefNamesForLinkage.insert(
  2660. std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
  2661. return;
  2662. }
  2663. if (!AddResult || Existing)
  2664. return;
  2665. DeclarationName Name = New->getDeclName();
  2666. DeclContext *DC = New->getDeclContext()->getRedeclContext();
  2667. if (needsAnonymousDeclarationNumber(New)) {
  2668. setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
  2669. AnonymousDeclNumber, New);
  2670. } else if (DC->isTranslationUnit() &&
  2671. !Reader.getContext().getLangOpts().CPlusPlus) {
  2672. if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
  2673. Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
  2674. .push_back(New);
  2675. } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
  2676. // Add the declaration to its redeclaration context so later merging
  2677. // lookups will find it.
  2678. MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
  2679. }
  2680. }
  2681. /// Find the declaration that should be merged into, given the declaration found
  2682. /// by name lookup. If we're merging an anonymous declaration within a typedef,
  2683. /// we need a matching typedef, and we merge with the type inside it.
  2684. static NamedDecl *getDeclForMerging(NamedDecl *Found,
  2685. bool IsTypedefNameForLinkage) {
  2686. if (!IsTypedefNameForLinkage)
  2687. return Found;
  2688. // If we found a typedef declaration that gives a name to some other
  2689. // declaration, then we want that inner declaration. Declarations from
  2690. // AST files are handled via ImportedTypedefNamesForLinkage.
  2691. if (Found->isFromASTFile())
  2692. return nullptr;
  2693. if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
  2694. return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
  2695. return nullptr;
  2696. }
  2697. NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
  2698. DeclContext *DC,
  2699. unsigned Index) {
  2700. // If the lexical context has been merged, look into the now-canonical
  2701. // definition.
  2702. if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
  2703. DC = Merged;
  2704. // If we've seen this before, return the canonical declaration.
  2705. auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
  2706. if (Index < Previous.size() && Previous[Index])
  2707. return Previous[Index];
  2708. // If this is the first time, but we have parsed a declaration of the context,
  2709. // build the anonymous declaration list from the parsed declaration.
  2710. if (!cast<Decl>(DC)->isFromASTFile()) {
  2711. numberAnonymousDeclsWithin(DC, [&](NamedDecl *ND, unsigned Number) {
  2712. if (Previous.size() == Number)
  2713. Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
  2714. else
  2715. Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
  2716. });
  2717. }
  2718. return Index < Previous.size() ? Previous[Index] : nullptr;
  2719. }
  2720. void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
  2721. DeclContext *DC, unsigned Index,
  2722. NamedDecl *D) {
  2723. if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
  2724. DC = Merged;
  2725. auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
  2726. if (Index >= Previous.size())
  2727. Previous.resize(Index + 1);
  2728. if (!Previous[Index])
  2729. Previous[Index] = D;
  2730. }
  2731. ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
  2732. DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
  2733. : D->getDeclName();
  2734. if (!Name && !needsAnonymousDeclarationNumber(D)) {
  2735. // Don't bother trying to find unnamed declarations that are in
  2736. // unmergeable contexts.
  2737. FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
  2738. AnonymousDeclNumber, TypedefNameForLinkage);
  2739. Result.suppress();
  2740. return Result;
  2741. }
  2742. DeclContext *DC = D->getDeclContext()->getRedeclContext();
  2743. if (TypedefNameForLinkage) {
  2744. auto It = Reader.ImportedTypedefNamesForLinkage.find(
  2745. std::make_pair(DC, TypedefNameForLinkage));
  2746. if (It != Reader.ImportedTypedefNamesForLinkage.end())
  2747. if (isSameEntity(It->second, D))
  2748. return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
  2749. TypedefNameForLinkage);
  2750. // Go on to check in other places in case an existing typedef name
  2751. // was not imported.
  2752. }
  2753. if (needsAnonymousDeclarationNumber(D)) {
  2754. // This is an anonymous declaration that we may need to merge. Look it up
  2755. // in its context by number.
  2756. if (auto *Existing = getAnonymousDeclForMerging(
  2757. Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
  2758. if (isSameEntity(Existing, D))
  2759. return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
  2760. TypedefNameForLinkage);
  2761. } else if (DC->isTranslationUnit() &&
  2762. !Reader.getContext().getLangOpts().CPlusPlus) {
  2763. IdentifierResolver &IdResolver = Reader.getIdResolver();
  2764. // Temporarily consider the identifier to be up-to-date. We don't want to
  2765. // cause additional lookups here.
  2766. class UpToDateIdentifierRAII {
  2767. IdentifierInfo *II;
  2768. bool WasOutToDate = false;
  2769. public:
  2770. explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
  2771. if (II) {
  2772. WasOutToDate = II->isOutOfDate();
  2773. if (WasOutToDate)
  2774. II->setOutOfDate(false);
  2775. }
  2776. }
  2777. ~UpToDateIdentifierRAII() {
  2778. if (WasOutToDate)
  2779. II->setOutOfDate(true);
  2780. }
  2781. } UpToDate(Name.getAsIdentifierInfo());
  2782. for (IdentifierResolver::iterator I = IdResolver.begin(Name),
  2783. IEnd = IdResolver.end();
  2784. I != IEnd; ++I) {
  2785. if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
  2786. if (isSameEntity(Existing, D))
  2787. return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
  2788. TypedefNameForLinkage);
  2789. }
  2790. } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
  2791. DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
  2792. for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
  2793. if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
  2794. if (isSameEntity(Existing, D))
  2795. return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
  2796. TypedefNameForLinkage);
  2797. }
  2798. } else {
  2799. // Not in a mergeable context.
  2800. return FindExistingResult(Reader);
  2801. }
  2802. // If this declaration is from a merged context, make a note that we need to
  2803. // check that the canonical definition of that context contains the decl.
  2804. //
  2805. // FIXME: We should do something similar if we merge two definitions of the
  2806. // same template specialization into the same CXXRecordDecl.
  2807. auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
  2808. if (MergedDCIt != Reader.MergedDeclContexts.end() &&
  2809. MergedDCIt->second == D->getDeclContext())
  2810. Reader.PendingOdrMergeChecks.push_back(D);
  2811. return FindExistingResult(Reader, D, /*Existing=*/nullptr,
  2812. AnonymousDeclNumber, TypedefNameForLinkage);
  2813. }
  2814. template<typename DeclT>
  2815. Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
  2816. return D->RedeclLink.getLatestNotUpdated();
  2817. }
  2818. Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
  2819. llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
  2820. }
  2821. Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
  2822. assert(D);
  2823. switch (D->getKind()) {
  2824. #define ABSTRACT_DECL(TYPE)
  2825. #define DECL(TYPE, BASE) \
  2826. case Decl::TYPE: \
  2827. return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
  2828. #include "clang/AST/DeclNodes.inc"
  2829. }
  2830. llvm_unreachable("unknown decl kind");
  2831. }
  2832. Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
  2833. return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
  2834. }
  2835. template<typename DeclT>
  2836. void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
  2837. Redeclarable<DeclT> *D,
  2838. Decl *Previous, Decl *Canon) {
  2839. D->RedeclLink.setPrevious(cast<DeclT>(Previous));
  2840. D->First = cast<DeclT>(Previous)->First;
  2841. }
  2842. namespace clang {
  2843. template<>
  2844. void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
  2845. Redeclarable<VarDecl> *D,
  2846. Decl *Previous, Decl *Canon) {
  2847. auto *VD = static_cast<VarDecl *>(D);
  2848. auto *PrevVD = cast<VarDecl>(Previous);
  2849. D->RedeclLink.setPrevious(PrevVD);
  2850. D->First = PrevVD->First;
  2851. // We should keep at most one definition on the chain.
  2852. // FIXME: Cache the definition once we've found it. Building a chain with
  2853. // N definitions currently takes O(N^2) time here.
  2854. if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
  2855. for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
  2856. if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
  2857. Reader.mergeDefinitionVisibility(CurD, VD);
  2858. VD->demoteThisDefinitionToDeclaration();
  2859. break;
  2860. }
  2861. }
  2862. }
  2863. }
  2864. template<>
  2865. void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
  2866. Redeclarable<FunctionDecl> *D,
  2867. Decl *Previous, Decl *Canon) {
  2868. auto *FD = static_cast<FunctionDecl *>(D);
  2869. auto *PrevFD = cast<FunctionDecl>(Previous);
  2870. FD->RedeclLink.setPrevious(PrevFD);
  2871. FD->First = PrevFD->First;
  2872. // If the previous declaration is an inline function declaration, then this
  2873. // declaration is too.
  2874. if (PrevFD->IsInline != FD->IsInline) {
  2875. // FIXME: [dcl.fct.spec]p4:
  2876. // If a function with external linkage is declared inline in one
  2877. // translation unit, it shall be declared inline in all translation
  2878. // units in which it appears.
  2879. //
  2880. // Be careful of this case:
  2881. //
  2882. // module A:
  2883. // template<typename T> struct X { void f(); };
  2884. // template<typename T> inline void X<T>::f() {}
  2885. //
  2886. // module B instantiates the declaration of X<int>::f
  2887. // module C instantiates the definition of X<int>::f
  2888. //
  2889. // If module B and C are merged, we do not have a violation of this rule.
  2890. FD->IsInline = true;
  2891. }
  2892. // If we need to propagate an exception specification along the redecl
  2893. // chain, make a note of that so that we can do so later.
  2894. auto *FPT = FD->getType()->getAs<FunctionProtoType>();
  2895. auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
  2896. if (FPT && PrevFPT) {
  2897. bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
  2898. bool WasUnresolved =
  2899. isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
  2900. if (IsUnresolved != WasUnresolved)
  2901. Reader.PendingExceptionSpecUpdates.insert(
  2902. std::make_pair(Canon, IsUnresolved ? PrevFD : FD));
  2903. }
  2904. }
  2905. } // namespace clang
  2906. void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
  2907. llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
  2908. }
  2909. /// Inherit the default template argument from \p From to \p To. Returns
  2910. /// \c false if there is no default template for \p From.
  2911. template <typename ParmDecl>
  2912. static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
  2913. Decl *ToD) {
  2914. auto *To = cast<ParmDecl>(ToD);
  2915. if (!From->hasDefaultArgument())
  2916. return false;
  2917. To->setInheritedDefaultArgument(Context, From);
  2918. return true;
  2919. }
  2920. static void inheritDefaultTemplateArguments(ASTContext &Context,
  2921. TemplateDecl *From,
  2922. TemplateDecl *To) {
  2923. auto *FromTP = From->getTemplateParameters();
  2924. auto *ToTP = To->getTemplateParameters();
  2925. assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
  2926. for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
  2927. NamedDecl *FromParam = FromTP->getParam(N - I - 1);
  2928. if (FromParam->isParameterPack())
  2929. continue;
  2930. NamedDecl *ToParam = ToTP->getParam(N - I - 1);
  2931. if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) {
  2932. if (!inheritDefaultTemplateArgument(Context, FTTP, ToParam))
  2933. break;
  2934. } else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) {
  2935. if (!inheritDefaultTemplateArgument(Context, FNTTP, ToParam))
  2936. break;
  2937. } else {
  2938. if (!inheritDefaultTemplateArgument(
  2939. Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam))
  2940. break;
  2941. }
  2942. }
  2943. }
  2944. void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
  2945. Decl *Previous, Decl *Canon) {
  2946. assert(D && Previous);
  2947. switch (D->getKind()) {
  2948. #define ABSTRACT_DECL(TYPE)
  2949. #define DECL(TYPE, BASE) \
  2950. case Decl::TYPE: \
  2951. attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
  2952. break;
  2953. #include "clang/AST/DeclNodes.inc"
  2954. }
  2955. // If the declaration was visible in one module, a redeclaration of it in
  2956. // another module remains visible even if it wouldn't be visible by itself.
  2957. //
  2958. // FIXME: In this case, the declaration should only be visible if a module
  2959. // that makes it visible has been imported.
  2960. D->IdentifierNamespace |=
  2961. Previous->IdentifierNamespace &
  2962. (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
  2963. // If the declaration declares a template, it may inherit default arguments
  2964. // from the previous declaration.
  2965. if (auto *TD = dyn_cast<TemplateDecl>(D))
  2966. inheritDefaultTemplateArguments(Reader.getContext(),
  2967. cast<TemplateDecl>(Previous), TD);
  2968. }
  2969. template<typename DeclT>
  2970. void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
  2971. D->RedeclLink.setLatest(cast<DeclT>(Latest));
  2972. }
  2973. void ASTDeclReader::attachLatestDeclImpl(...) {
  2974. llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
  2975. }
  2976. void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
  2977. assert(D && Latest);
  2978. switch (D->getKind()) {
  2979. #define ABSTRACT_DECL(TYPE)
  2980. #define DECL(TYPE, BASE) \
  2981. case Decl::TYPE: \
  2982. attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
  2983. break;
  2984. #include "clang/AST/DeclNodes.inc"
  2985. }
  2986. }
  2987. template<typename DeclT>
  2988. void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
  2989. D->RedeclLink.markIncomplete();
  2990. }
  2991. void ASTDeclReader::markIncompleteDeclChainImpl(...) {
  2992. llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
  2993. }
  2994. void ASTReader::markIncompleteDeclChain(Decl *D) {
  2995. switch (D->getKind()) {
  2996. #define ABSTRACT_DECL(TYPE)
  2997. #define DECL(TYPE, BASE) \
  2998. case Decl::TYPE: \
  2999. ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
  3000. break;
  3001. #include "clang/AST/DeclNodes.inc"
  3002. }
  3003. }
  3004. /// \brief Read the declaration at the given offset from the AST file.
  3005. Decl *ASTReader::ReadDeclRecord(DeclID ID) {
  3006. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  3007. SourceLocation DeclLoc;
  3008. RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
  3009. llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
  3010. // Keep track of where we are in the stream, then jump back there
  3011. // after reading this declaration.
  3012. SavedStreamPosition SavedPosition(DeclsCursor);
  3013. ReadingKindTracker ReadingKind(Read_Decl, *this);
  3014. // Note that we are loading a declaration record.
  3015. Deserializing ADecl(this);
  3016. DeclsCursor.JumpToBit(Loc.Offset);
  3017. ASTRecordReader Record(*this, *Loc.F);
  3018. ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
  3019. unsigned Code = DeclsCursor.ReadCode();
  3020. ASTContext &Context = getContext();
  3021. Decl *D = nullptr;
  3022. switch ((DeclCode)Record.readRecord(DeclsCursor, Code)) {
  3023. case DECL_CONTEXT_LEXICAL:
  3024. case DECL_CONTEXT_VISIBLE:
  3025. llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
  3026. case DECL_TYPEDEF:
  3027. D = TypedefDecl::CreateDeserialized(Context, ID);
  3028. break;
  3029. case DECL_TYPEALIAS:
  3030. D = TypeAliasDecl::CreateDeserialized(Context, ID);
  3031. break;
  3032. case DECL_ENUM:
  3033. D = EnumDecl::CreateDeserialized(Context, ID);
  3034. break;
  3035. case DECL_RECORD:
  3036. D = RecordDecl::CreateDeserialized(Context, ID);
  3037. break;
  3038. case DECL_ENUM_CONSTANT:
  3039. D = EnumConstantDecl::CreateDeserialized(Context, ID);
  3040. break;
  3041. case DECL_FUNCTION:
  3042. D = FunctionDecl::CreateDeserialized(Context, ID);
  3043. break;
  3044. case DECL_LINKAGE_SPEC:
  3045. D = LinkageSpecDecl::CreateDeserialized(Context, ID);
  3046. break;
  3047. case DECL_EXPORT:
  3048. D = ExportDecl::CreateDeserialized(Context, ID);
  3049. break;
  3050. case DECL_LABEL:
  3051. D = LabelDecl::CreateDeserialized(Context, ID);
  3052. break;
  3053. case DECL_NAMESPACE:
  3054. D = NamespaceDecl::CreateDeserialized(Context, ID);
  3055. break;
  3056. case DECL_NAMESPACE_ALIAS:
  3057. D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
  3058. break;
  3059. case DECL_USING:
  3060. D = UsingDecl::CreateDeserialized(Context, ID);
  3061. break;
  3062. case DECL_USING_PACK:
  3063. D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
  3064. break;
  3065. case DECL_USING_SHADOW:
  3066. D = UsingShadowDecl::CreateDeserialized(Context, ID);
  3067. break;
  3068. case DECL_CONSTRUCTOR_USING_SHADOW:
  3069. D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
  3070. break;
  3071. case DECL_USING_DIRECTIVE:
  3072. D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
  3073. break;
  3074. case DECL_UNRESOLVED_USING_VALUE:
  3075. D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
  3076. break;
  3077. case DECL_UNRESOLVED_USING_TYPENAME:
  3078. D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
  3079. break;
  3080. case DECL_CXX_RECORD:
  3081. D = CXXRecordDecl::CreateDeserialized(Context, ID);
  3082. break;
  3083. case DECL_CXX_DEDUCTION_GUIDE:
  3084. D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
  3085. break;
  3086. case DECL_CXX_METHOD:
  3087. D = CXXMethodDecl::CreateDeserialized(Context, ID);
  3088. break;
  3089. case DECL_CXX_CONSTRUCTOR:
  3090. D = CXXConstructorDecl::CreateDeserialized(Context, ID, false);
  3091. break;
  3092. case DECL_CXX_INHERITED_CONSTRUCTOR:
  3093. D = CXXConstructorDecl::CreateDeserialized(Context, ID, true);
  3094. break;
  3095. case DECL_CXX_DESTRUCTOR:
  3096. D = CXXDestructorDecl::CreateDeserialized(Context, ID);
  3097. break;
  3098. case DECL_CXX_CONVERSION:
  3099. D = CXXConversionDecl::CreateDeserialized(Context, ID);
  3100. break;
  3101. case DECL_ACCESS_SPEC:
  3102. D = AccessSpecDecl::CreateDeserialized(Context, ID);
  3103. break;
  3104. case DECL_FRIEND:
  3105. D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
  3106. break;
  3107. case DECL_FRIEND_TEMPLATE:
  3108. D = FriendTemplateDecl::CreateDeserialized(Context, ID);
  3109. break;
  3110. case DECL_CLASS_TEMPLATE:
  3111. D = ClassTemplateDecl::CreateDeserialized(Context, ID);
  3112. break;
  3113. case DECL_CLASS_TEMPLATE_SPECIALIZATION:
  3114. D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
  3115. break;
  3116. case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
  3117. D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
  3118. break;
  3119. case DECL_VAR_TEMPLATE:
  3120. D = VarTemplateDecl::CreateDeserialized(Context, ID);
  3121. break;
  3122. case DECL_VAR_TEMPLATE_SPECIALIZATION:
  3123. D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
  3124. break;
  3125. case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
  3126. D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
  3127. break;
  3128. case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
  3129. D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
  3130. break;
  3131. case DECL_FUNCTION_TEMPLATE:
  3132. D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
  3133. break;
  3134. case DECL_TEMPLATE_TYPE_PARM:
  3135. D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
  3136. break;
  3137. case DECL_NON_TYPE_TEMPLATE_PARM:
  3138. D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
  3139. break;
  3140. case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
  3141. D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
  3142. Record.readInt());
  3143. break;
  3144. case DECL_TEMPLATE_TEMPLATE_PARM:
  3145. D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
  3146. break;
  3147. case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
  3148. D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
  3149. Record.readInt());
  3150. break;
  3151. case DECL_TYPE_ALIAS_TEMPLATE:
  3152. D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
  3153. break;
  3154. case DECL_STATIC_ASSERT:
  3155. D = StaticAssertDecl::CreateDeserialized(Context, ID);
  3156. break;
  3157. case DECL_OBJC_METHOD:
  3158. D = ObjCMethodDecl::CreateDeserialized(Context, ID);
  3159. break;
  3160. case DECL_OBJC_INTERFACE:
  3161. D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
  3162. break;
  3163. case DECL_OBJC_IVAR:
  3164. D = ObjCIvarDecl::CreateDeserialized(Context, ID);
  3165. break;
  3166. case DECL_OBJC_PROTOCOL:
  3167. D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
  3168. break;
  3169. case DECL_OBJC_AT_DEFS_FIELD:
  3170. D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
  3171. break;
  3172. case DECL_OBJC_CATEGORY:
  3173. D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
  3174. break;
  3175. case DECL_OBJC_CATEGORY_IMPL:
  3176. D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
  3177. break;
  3178. case DECL_OBJC_IMPLEMENTATION:
  3179. D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
  3180. break;
  3181. case DECL_OBJC_COMPATIBLE_ALIAS:
  3182. D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
  3183. break;
  3184. case DECL_OBJC_PROPERTY:
  3185. D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
  3186. break;
  3187. case DECL_OBJC_PROPERTY_IMPL:
  3188. D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
  3189. break;
  3190. case DECL_FIELD:
  3191. D = FieldDecl::CreateDeserialized(Context, ID);
  3192. break;
  3193. case DECL_INDIRECTFIELD:
  3194. D = IndirectFieldDecl::CreateDeserialized(Context, ID);
  3195. break;
  3196. case DECL_VAR:
  3197. D = VarDecl::CreateDeserialized(Context, ID);
  3198. break;
  3199. case DECL_IMPLICIT_PARAM:
  3200. D = ImplicitParamDecl::CreateDeserialized(Context, ID);
  3201. break;
  3202. case DECL_PARM_VAR:
  3203. D = ParmVarDecl::CreateDeserialized(Context, ID);
  3204. break;
  3205. case DECL_DECOMPOSITION:
  3206. D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
  3207. break;
  3208. case DECL_BINDING:
  3209. D = BindingDecl::CreateDeserialized(Context, ID);
  3210. break;
  3211. case DECL_FILE_SCOPE_ASM:
  3212. D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
  3213. break;
  3214. case DECL_BLOCK:
  3215. D = BlockDecl::CreateDeserialized(Context, ID);
  3216. break;
  3217. case DECL_MS_PROPERTY:
  3218. D = MSPropertyDecl::CreateDeserialized(Context, ID);
  3219. break;
  3220. case DECL_CAPTURED:
  3221. D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
  3222. break;
  3223. case DECL_CXX_BASE_SPECIFIERS:
  3224. Error("attempt to read a C++ base-specifier record as a declaration");
  3225. return nullptr;
  3226. case DECL_CXX_CTOR_INITIALIZERS:
  3227. Error("attempt to read a C++ ctor initializer record as a declaration");
  3228. return nullptr;
  3229. case DECL_IMPORT:
  3230. // Note: last entry of the ImportDecl record is the number of stored source
  3231. // locations.
  3232. D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
  3233. break;
  3234. case DECL_OMP_THREADPRIVATE:
  3235. D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
  3236. break;
  3237. case DECL_OMP_DECLARE_REDUCTION:
  3238. D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
  3239. break;
  3240. case DECL_OMP_CAPTUREDEXPR:
  3241. D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
  3242. break;
  3243. case DECL_PRAGMA_COMMENT:
  3244. D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
  3245. break;
  3246. case DECL_PRAGMA_DETECT_MISMATCH:
  3247. D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
  3248. Record.readInt());
  3249. break;
  3250. case DECL_EMPTY:
  3251. D = EmptyDecl::CreateDeserialized(Context, ID);
  3252. break;
  3253. case DECL_OBJC_TYPE_PARAM:
  3254. D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
  3255. break;
  3256. }
  3257. assert(D && "Unknown declaration reading AST file");
  3258. LoadedDecl(Index, D);
  3259. // Set the DeclContext before doing any deserialization, to make sure internal
  3260. // calls to Decl::getASTContext() by Decl's methods will find the
  3261. // TranslationUnitDecl without crashing.
  3262. D->setDeclContext(Context.getTranslationUnitDecl());
  3263. Reader.Visit(D);
  3264. // If this declaration is also a declaration context, get the
  3265. // offsets for its tables of lexical and visible declarations.
  3266. if (auto *DC = dyn_cast<DeclContext>(D)) {
  3267. std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
  3268. if (Offsets.first &&
  3269. ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
  3270. return nullptr;
  3271. if (Offsets.second &&
  3272. ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
  3273. return nullptr;
  3274. }
  3275. assert(Record.getIdx() == Record.size());
  3276. // Load any relevant update records.
  3277. PendingUpdateRecords.push_back(
  3278. PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
  3279. // Load the categories after recursive loading is finished.
  3280. if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
  3281. // If we already have a definition when deserializing the ObjCInterfaceDecl,
  3282. // we put the Decl in PendingDefinitions so we can pull the categories here.
  3283. if (Class->isThisDeclarationADefinition() ||
  3284. PendingDefinitions.count(Class))
  3285. loadObjCCategories(ID, Class);
  3286. // If we have deserialized a declaration that has a definition the
  3287. // AST consumer might need to know about, queue it.
  3288. // We don't pass it to the consumer immediately because we may be in recursive
  3289. // loading, and some declarations may still be initializing.
  3290. PotentiallyInterestingDecls.push_back(
  3291. InterestingDecl(D, Reader.hasPendingBody()));
  3292. return D;
  3293. }
  3294. void ASTReader::PassInterestingDeclsToConsumer() {
  3295. assert(Consumer);
  3296. if (PassingDeclsToConsumer)
  3297. return;
  3298. // Guard variable to avoid recursively redoing the process of passing
  3299. // decls to consumer.
  3300. SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
  3301. true);
  3302. // Ensure that we've loaded all potentially-interesting declarations
  3303. // that need to be eagerly loaded.
  3304. for (auto ID : EagerlyDeserializedDecls)
  3305. GetDecl(ID);
  3306. EagerlyDeserializedDecls.clear();
  3307. while (!PotentiallyInterestingDecls.empty()) {
  3308. InterestingDecl D = PotentiallyInterestingDecls.front();
  3309. PotentiallyInterestingDecls.pop_front();
  3310. if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
  3311. PassInterestingDeclToConsumer(D.getDecl());
  3312. }
  3313. }
  3314. void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
  3315. // The declaration may have been modified by files later in the chain.
  3316. // If this is the case, read the record containing the updates from each file
  3317. // and pass it to ASTDeclReader to make the modifications.
  3318. serialization::GlobalDeclID ID = Record.ID;
  3319. Decl *D = Record.D;
  3320. ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
  3321. DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
  3322. SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
  3323. if (UpdI != DeclUpdateOffsets.end()) {
  3324. auto UpdateOffsets = std::move(UpdI->second);
  3325. DeclUpdateOffsets.erase(UpdI);
  3326. // Check if this decl was interesting to the consumer. If we just loaded
  3327. // the declaration, then we know it was interesting and we skip the call
  3328. // to isConsumerInterestedIn because it is unsafe to call in the
  3329. // current ASTReader state.
  3330. bool WasInteresting =
  3331. Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
  3332. for (auto &FileAndOffset : UpdateOffsets) {
  3333. ModuleFile *F = FileAndOffset.first;
  3334. uint64_t Offset = FileAndOffset.second;
  3335. llvm::BitstreamCursor &Cursor = F->DeclsCursor;
  3336. SavedStreamPosition SavedPosition(Cursor);
  3337. Cursor.JumpToBit(Offset);
  3338. unsigned Code = Cursor.ReadCode();
  3339. ASTRecordReader Record(*this, *F);
  3340. unsigned RecCode = Record.readRecord(Cursor, Code);
  3341. (void)RecCode;
  3342. assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
  3343. ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
  3344. SourceLocation());
  3345. Reader.UpdateDecl(D, PendingLazySpecializationIDs);
  3346. // We might have made this declaration interesting. If so, remember that
  3347. // we need to hand it off to the consumer.
  3348. if (!WasInteresting &&
  3349. isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
  3350. PotentiallyInterestingDecls.push_back(
  3351. InterestingDecl(D, Reader.hasPendingBody()));
  3352. WasInteresting = true;
  3353. }
  3354. }
  3355. }
  3356. // Add the lazy specializations to the template.
  3357. assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
  3358. isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
  3359. "Must not have pending specializations");
  3360. if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
  3361. ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
  3362. else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
  3363. ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
  3364. else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
  3365. ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
  3366. PendingLazySpecializationIDs.clear();
  3367. // Load the pending visible updates for this decl context, if it has any.
  3368. auto I = PendingVisibleUpdates.find(ID);
  3369. if (I != PendingVisibleUpdates.end()) {
  3370. auto VisibleUpdates = std::move(I->second);
  3371. PendingVisibleUpdates.erase(I);
  3372. auto *DC = cast<DeclContext>(D)->getPrimaryContext();
  3373. for (const auto &Update : VisibleUpdates)
  3374. Lookups[DC].Table.add(
  3375. Update.Mod, Update.Data,
  3376. reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
  3377. DC->setHasExternalVisibleStorage(true);
  3378. }
  3379. }
  3380. void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
  3381. // Attach FirstLocal to the end of the decl chain.
  3382. Decl *CanonDecl = FirstLocal->getCanonicalDecl();
  3383. if (FirstLocal != CanonDecl) {
  3384. Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
  3385. ASTDeclReader::attachPreviousDecl(
  3386. *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
  3387. CanonDecl);
  3388. }
  3389. if (!LocalOffset) {
  3390. ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
  3391. return;
  3392. }
  3393. // Load the list of other redeclarations from this module file.
  3394. ModuleFile *M = getOwningModuleFile(FirstLocal);
  3395. assert(M && "imported decl from no module file");
  3396. llvm::BitstreamCursor &Cursor = M->DeclsCursor;
  3397. SavedStreamPosition SavedPosition(Cursor);
  3398. Cursor.JumpToBit(LocalOffset);
  3399. RecordData Record;
  3400. unsigned Code = Cursor.ReadCode();
  3401. unsigned RecCode = Cursor.readRecord(Code, Record);
  3402. (void)RecCode;
  3403. assert(RecCode == LOCAL_REDECLARATIONS && "expected LOCAL_REDECLARATIONS record!");
  3404. // FIXME: We have several different dispatches on decl kind here; maybe
  3405. // we should instead generate one loop per kind and dispatch up-front?
  3406. Decl *MostRecent = FirstLocal;
  3407. for (unsigned I = 0, N = Record.size(); I != N; ++I) {
  3408. auto *D = GetLocalDecl(*M, Record[N - I - 1]);
  3409. ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
  3410. MostRecent = D;
  3411. }
  3412. ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
  3413. }
  3414. namespace {
  3415. /// \brief Given an ObjC interface, goes through the modules and links to the
  3416. /// interface all the categories for it.
  3417. class ObjCCategoriesVisitor {
  3418. ASTReader &Reader;
  3419. ObjCInterfaceDecl *Interface;
  3420. llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
  3421. ObjCCategoryDecl *Tail = nullptr;
  3422. llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
  3423. serialization::GlobalDeclID InterfaceID;
  3424. unsigned PreviousGeneration;
  3425. void add(ObjCCategoryDecl *Cat) {
  3426. // Only process each category once.
  3427. if (!Deserialized.erase(Cat))
  3428. return;
  3429. // Check for duplicate categories.
  3430. if (Cat->getDeclName()) {
  3431. ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
  3432. if (Existing &&
  3433. Reader.getOwningModuleFile(Existing)
  3434. != Reader.getOwningModuleFile(Cat)) {
  3435. // FIXME: We should not warn for duplicates in diamond:
  3436. //
  3437. // MT //
  3438. // / \ //
  3439. // ML MR //
  3440. // \ / //
  3441. // MB //
  3442. //
  3443. // If there are duplicates in ML/MR, there will be warning when
  3444. // creating MB *and* when importing MB. We should not warn when
  3445. // importing.
  3446. Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
  3447. << Interface->getDeclName() << Cat->getDeclName();
  3448. Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
  3449. } else if (!Existing) {
  3450. // Record this category.
  3451. Existing = Cat;
  3452. }
  3453. }
  3454. // Add this category to the end of the chain.
  3455. if (Tail)
  3456. ASTDeclReader::setNextObjCCategory(Tail, Cat);
  3457. else
  3458. Interface->setCategoryListRaw(Cat);
  3459. Tail = Cat;
  3460. }
  3461. public:
  3462. ObjCCategoriesVisitor(ASTReader &Reader,
  3463. ObjCInterfaceDecl *Interface,
  3464. llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
  3465. serialization::GlobalDeclID InterfaceID,
  3466. unsigned PreviousGeneration)
  3467. : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
  3468. InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
  3469. // Populate the name -> category map with the set of known categories.
  3470. for (auto *Cat : Interface->known_categories()) {
  3471. if (Cat->getDeclName())
  3472. NameCategoryMap[Cat->getDeclName()] = Cat;
  3473. // Keep track of the tail of the category list.
  3474. Tail = Cat;
  3475. }
  3476. }
  3477. bool operator()(ModuleFile &M) {
  3478. // If we've loaded all of the category information we care about from
  3479. // this module file, we're done.
  3480. if (M.Generation <= PreviousGeneration)
  3481. return true;
  3482. // Map global ID of the definition down to the local ID used in this
  3483. // module file. If there is no such mapping, we'll find nothing here
  3484. // (or in any module it imports).
  3485. DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
  3486. if (!LocalID)
  3487. return true;
  3488. // Perform a binary search to find the local redeclarations for this
  3489. // declaration (if any).
  3490. const ObjCCategoriesInfo Compare = { LocalID, 0 };
  3491. const ObjCCategoriesInfo *Result
  3492. = std::lower_bound(M.ObjCCategoriesMap,
  3493. M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
  3494. Compare);
  3495. if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
  3496. Result->DefinitionID != LocalID) {
  3497. // We didn't find anything. If the class definition is in this module
  3498. // file, then the module files it depends on cannot have any categories,
  3499. // so suppress further lookup.
  3500. return Reader.isDeclIDFromModule(InterfaceID, M);
  3501. }
  3502. // We found something. Dig out all of the categories.
  3503. unsigned Offset = Result->Offset;
  3504. unsigned N = M.ObjCCategories[Offset];
  3505. M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
  3506. for (unsigned I = 0; I != N; ++I)
  3507. add(cast_or_null<ObjCCategoryDecl>(
  3508. Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
  3509. return true;
  3510. }
  3511. };
  3512. } // namespace
  3513. void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
  3514. ObjCInterfaceDecl *D,
  3515. unsigned PreviousGeneration) {
  3516. ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
  3517. PreviousGeneration);
  3518. ModuleMgr.visit(Visitor);
  3519. }
  3520. template<typename DeclT, typename Fn>
  3521. static void forAllLaterRedecls(DeclT *D, Fn F) {
  3522. F(D);
  3523. // Check whether we've already merged D into its redeclaration chain.
  3524. // MostRecent may or may not be nullptr if D has not been merged. If
  3525. // not, walk the merged redecl chain and see if it's there.
  3526. auto *MostRecent = D->getMostRecentDecl();
  3527. bool Found = false;
  3528. for (auto *Redecl = MostRecent; Redecl && !Found;
  3529. Redecl = Redecl->getPreviousDecl())
  3530. Found = (Redecl == D);
  3531. // If this declaration is merged, apply the functor to all later decls.
  3532. if (Found) {
  3533. for (auto *Redecl = MostRecent; Redecl != D;
  3534. Redecl = Redecl->getPreviousDecl())
  3535. F(Redecl);
  3536. }
  3537. }
  3538. void ASTDeclReader::UpdateDecl(Decl *D,
  3539. llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
  3540. while (Record.getIdx() < Record.size()) {
  3541. switch ((DeclUpdateKind)Record.readInt()) {
  3542. case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
  3543. auto *RD = cast<CXXRecordDecl>(D);
  3544. // FIXME: If we also have an update record for instantiating the
  3545. // definition of D, we need that to happen before we get here.
  3546. Decl *MD = Record.readDecl();
  3547. assert(MD && "couldn't read decl from update record");
  3548. // FIXME: We should call addHiddenDecl instead, to add the member
  3549. // to its DeclContext.
  3550. RD->addedMember(MD);
  3551. break;
  3552. }
  3553. case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
  3554. // It will be added to the template's lazy specialization set.
  3555. PendingLazySpecializationIDs.push_back(ReadDeclID());
  3556. break;
  3557. case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
  3558. auto *Anon = ReadDeclAs<NamespaceDecl>();
  3559. // Each module has its own anonymous namespace, which is disjoint from
  3560. // any other module's anonymous namespaces, so don't attach the anonymous
  3561. // namespace at all.
  3562. if (!Record.isModule()) {
  3563. if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
  3564. TU->setAnonymousNamespace(Anon);
  3565. else
  3566. cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
  3567. }
  3568. break;
  3569. }
  3570. case UPD_CXX_ADDED_VAR_DEFINITION: {
  3571. auto *VD = cast<VarDecl>(D);
  3572. VD->NonParmVarDeclBits.IsInline = Record.readInt();
  3573. VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
  3574. uint64_t Val = Record.readInt();
  3575. if (Val && !VD->getInit()) {
  3576. VD->setInit(Record.readExpr());
  3577. if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
  3578. EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
  3579. Eval->CheckedICE = true;
  3580. Eval->IsICE = Val == 3;
  3581. }
  3582. }
  3583. break;
  3584. }
  3585. case UPD_CXX_POINT_OF_INSTANTIATION: {
  3586. SourceLocation POI = Record.readSourceLocation();
  3587. if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
  3588. VTSD->setPointOfInstantiation(POI);
  3589. } else if (auto *VD = dyn_cast<VarDecl>(D)) {
  3590. VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
  3591. } else {
  3592. auto *FD = cast<FunctionDecl>(D);
  3593. if (auto *FTSInfo = FD->TemplateOrSpecialization
  3594. .dyn_cast<FunctionTemplateSpecializationInfo *>())
  3595. FTSInfo->setPointOfInstantiation(POI);
  3596. else
  3597. FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
  3598. ->setPointOfInstantiation(POI);
  3599. }
  3600. break;
  3601. }
  3602. case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
  3603. auto *Param = cast<ParmVarDecl>(D);
  3604. // We have to read the default argument regardless of whether we use it
  3605. // so that hypothetical further update records aren't messed up.
  3606. // TODO: Add a function to skip over the next expr record.
  3607. auto *DefaultArg = Record.readExpr();
  3608. // Only apply the update if the parameter still has an uninstantiated
  3609. // default argument.
  3610. if (Param->hasUninstantiatedDefaultArg())
  3611. Param->setDefaultArg(DefaultArg);
  3612. break;
  3613. }
  3614. case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
  3615. auto *FD = cast<FieldDecl>(D);
  3616. auto *DefaultInit = Record.readExpr();
  3617. // Only apply the update if the field still has an uninstantiated
  3618. // default member initializer.
  3619. if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
  3620. if (DefaultInit)
  3621. FD->setInClassInitializer(DefaultInit);
  3622. else
  3623. // Instantiation failed. We can get here if we serialized an AST for
  3624. // an invalid program.
  3625. FD->removeInClassInitializer();
  3626. }
  3627. break;
  3628. }
  3629. case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
  3630. auto *FD = cast<FunctionDecl>(D);
  3631. if (Reader.PendingBodies[FD]) {
  3632. // FIXME: Maybe check for ODR violations.
  3633. // It's safe to stop now because this update record is always last.
  3634. return;
  3635. }
  3636. if (Record.readInt()) {
  3637. // Maintain AST consistency: any later redeclarations of this function
  3638. // are inline if this one is. (We might have merged another declaration
  3639. // into this one.)
  3640. forAllLaterRedecls(FD, [](FunctionDecl *FD) {
  3641. FD->setImplicitlyInline();
  3642. });
  3643. }
  3644. FD->setInnerLocStart(ReadSourceLocation());
  3645. ReadFunctionDefinition(FD);
  3646. assert(Record.getIdx() == Record.size() && "lazy body must be last");
  3647. break;
  3648. }
  3649. case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
  3650. auto *RD = cast<CXXRecordDecl>(D);
  3651. auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
  3652. bool HadRealDefinition =
  3653. OldDD && (OldDD->Definition != RD ||
  3654. !Reader.PendingFakeDefinitionData.count(OldDD));
  3655. RD->setParamDestroyedInCallee(Record.readInt());
  3656. RD->setArgPassingRestrictions(
  3657. (RecordDecl::ArgPassingKind)Record.readInt());
  3658. ReadCXXRecordDefinition(RD, /*Update*/true);
  3659. // Visible update is handled separately.
  3660. uint64_t LexicalOffset = ReadLocalOffset();
  3661. if (!HadRealDefinition && LexicalOffset) {
  3662. Record.readLexicalDeclContextStorage(LexicalOffset, RD);
  3663. Reader.PendingFakeDefinitionData.erase(OldDD);
  3664. }
  3665. auto TSK = (TemplateSpecializationKind)Record.readInt();
  3666. SourceLocation POI = ReadSourceLocation();
  3667. if (MemberSpecializationInfo *MSInfo =
  3668. RD->getMemberSpecializationInfo()) {
  3669. MSInfo->setTemplateSpecializationKind(TSK);
  3670. MSInfo->setPointOfInstantiation(POI);
  3671. } else {
  3672. auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
  3673. Spec->setTemplateSpecializationKind(TSK);
  3674. Spec->setPointOfInstantiation(POI);
  3675. if (Record.readInt()) {
  3676. auto *PartialSpec =
  3677. ReadDeclAs<ClassTemplatePartialSpecializationDecl>();
  3678. SmallVector<TemplateArgument, 8> TemplArgs;
  3679. Record.readTemplateArgumentList(TemplArgs);
  3680. auto *TemplArgList = TemplateArgumentList::CreateCopy(
  3681. Reader.getContext(), TemplArgs);
  3682. // FIXME: If we already have a partial specialization set,
  3683. // check that it matches.
  3684. if (!Spec->getSpecializedTemplateOrPartial()
  3685. .is<ClassTemplatePartialSpecializationDecl *>())
  3686. Spec->setInstantiationOf(PartialSpec, TemplArgList);
  3687. }
  3688. }
  3689. RD->setTagKind((TagTypeKind)Record.readInt());
  3690. RD->setLocation(ReadSourceLocation());
  3691. RD->setLocStart(ReadSourceLocation());
  3692. RD->setBraceRange(ReadSourceRange());
  3693. if (Record.readInt()) {
  3694. AttrVec Attrs;
  3695. Record.readAttributes(Attrs);
  3696. // If the declaration already has attributes, we assume that some other
  3697. // AST file already loaded them.
  3698. if (!D->hasAttrs())
  3699. D->setAttrsImpl(Attrs, Reader.getContext());
  3700. }
  3701. break;
  3702. }
  3703. case UPD_CXX_RESOLVED_DTOR_DELETE: {
  3704. // Set the 'operator delete' directly to avoid emitting another update
  3705. // record.
  3706. auto *Del = ReadDeclAs<FunctionDecl>();
  3707. auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
  3708. auto *ThisArg = Record.readExpr();
  3709. // FIXME: Check consistency if we have an old and new operator delete.
  3710. if (!First->OperatorDelete) {
  3711. First->OperatorDelete = Del;
  3712. First->OperatorDeleteThisArg = ThisArg;
  3713. }
  3714. break;
  3715. }
  3716. case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
  3717. FunctionProtoType::ExceptionSpecInfo ESI;
  3718. SmallVector<QualType, 8> ExceptionStorage;
  3719. Record.readExceptionSpec(ExceptionStorage, ESI);
  3720. // Update this declaration's exception specification, if needed.
  3721. auto *FD = cast<FunctionDecl>(D);
  3722. auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  3723. // FIXME: If the exception specification is already present, check that it
  3724. // matches.
  3725. if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
  3726. FD->setType(Reader.getContext().getFunctionType(
  3727. FPT->getReturnType(), FPT->getParamTypes(),
  3728. FPT->getExtProtoInfo().withExceptionSpec(ESI)));
  3729. // When we get to the end of deserializing, see if there are other decls
  3730. // that we need to propagate this exception specification onto.
  3731. Reader.PendingExceptionSpecUpdates.insert(
  3732. std::make_pair(FD->getCanonicalDecl(), FD));
  3733. }
  3734. break;
  3735. }
  3736. case UPD_CXX_DEDUCED_RETURN_TYPE: {
  3737. // FIXME: Also do this when merging redecls.
  3738. QualType DeducedResultType = Record.readType();
  3739. for (auto *Redecl : merged_redecls(D)) {
  3740. // FIXME: If the return type is already deduced, check that it matches.
  3741. auto *FD = cast<FunctionDecl>(Redecl);
  3742. Reader.getContext().adjustDeducedFunctionResultType(FD,
  3743. DeducedResultType);
  3744. }
  3745. break;
  3746. }
  3747. case UPD_DECL_MARKED_USED:
  3748. // Maintain AST consistency: any later redeclarations are used too.
  3749. D->markUsed(Reader.getContext());
  3750. break;
  3751. case UPD_MANGLING_NUMBER:
  3752. Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
  3753. Record.readInt());
  3754. break;
  3755. case UPD_STATIC_LOCAL_NUMBER:
  3756. Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
  3757. Record.readInt());
  3758. break;
  3759. case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
  3760. D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(Reader.getContext(),
  3761. ReadSourceRange()));
  3762. break;
  3763. case UPD_DECL_EXPORTED: {
  3764. unsigned SubmoduleID = readSubmoduleID();
  3765. auto *Exported = cast<NamedDecl>(D);
  3766. if (auto *TD = dyn_cast<TagDecl>(Exported))
  3767. Exported = TD->getDefinition();
  3768. Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
  3769. if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
  3770. Reader.getContext().mergeDefinitionIntoModule(cast<NamedDecl>(Exported),
  3771. Owner);
  3772. Reader.PendingMergedDefinitionsToDeduplicate.insert(
  3773. cast<NamedDecl>(Exported));
  3774. } else if (Owner && Owner->NameVisibility != Module::AllVisible) {
  3775. // If Owner is made visible at some later point, make this declaration
  3776. // visible too.
  3777. Reader.HiddenNamesMap[Owner].push_back(Exported);
  3778. } else {
  3779. // The declaration is now visible.
  3780. Exported->setVisibleDespiteOwningModule();
  3781. }
  3782. break;
  3783. }
  3784. case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
  3785. case UPD_ADDED_ATTR_TO_RECORD:
  3786. AttrVec Attrs;
  3787. Record.readAttributes(Attrs);
  3788. assert(Attrs.size() == 1);
  3789. D->addAttr(Attrs[0]);
  3790. break;
  3791. }
  3792. }
  3793. }