ASTReaderDecl.cpp 170 KB

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