ASTReaderDecl.cpp 166 KB

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