ASTReader.cpp 397 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388
  1. //===- ASTReader.cpp - AST File Reader ------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the ASTReader class, which reads AST files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "ASTCommon.h"
  13. #include "ASTReaderInternals.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/ASTStructuralEquivalence.h"
  18. #include "clang/AST/ASTUnresolvedSet.h"
  19. #include "clang/AST/AbstractTypeReader.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclBase.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/DeclFriend.h"
  24. #include "clang/AST/DeclGroup.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/AST/DeclTemplate.h"
  27. #include "clang/AST/DeclarationName.h"
  28. #include "clang/AST/Expr.h"
  29. #include "clang/AST/ExprCXX.h"
  30. #include "clang/AST/ExternalASTSource.h"
  31. #include "clang/AST/NestedNameSpecifier.h"
  32. #include "clang/AST/ODRDiagsEmitter.h"
  33. #include "clang/AST/ODRHash.h"
  34. #include "clang/AST/OpenMPClause.h"
  35. #include "clang/AST/RawCommentList.h"
  36. #include "clang/AST/TemplateBase.h"
  37. #include "clang/AST/TemplateName.h"
  38. #include "clang/AST/Type.h"
  39. #include "clang/AST/TypeLoc.h"
  40. #include "clang/AST/TypeLocVisitor.h"
  41. #include "clang/AST/UnresolvedSet.h"
  42. #include "clang/Basic/CommentOptions.h"
  43. #include "clang/Basic/Diagnostic.h"
  44. #include "clang/Basic/DiagnosticError.h"
  45. #include "clang/Basic/DiagnosticOptions.h"
  46. #include "clang/Basic/DiagnosticSema.h"
  47. #include "clang/Basic/ExceptionSpecificationType.h"
  48. #include "clang/Basic/FileManager.h"
  49. #include "clang/Basic/FileSystemOptions.h"
  50. #include "clang/Basic/IdentifierTable.h"
  51. #include "clang/Basic/LLVM.h"
  52. #include "clang/Basic/LangOptions.h"
  53. #include "clang/Basic/Module.h"
  54. #include "clang/Basic/ObjCRuntime.h"
  55. #include "clang/Basic/OpenMPKinds.h"
  56. #include "clang/Basic/OperatorKinds.h"
  57. #include "clang/Basic/PragmaKinds.h"
  58. #include "clang/Basic/Sanitizers.h"
  59. #include "clang/Basic/SourceLocation.h"
  60. #include "clang/Basic/SourceManager.h"
  61. #include "clang/Basic/SourceManagerInternals.h"
  62. #include "clang/Basic/Specifiers.h"
  63. #include "clang/Basic/TargetInfo.h"
  64. #include "clang/Basic/TargetOptions.h"
  65. #include "clang/Basic/TokenKinds.h"
  66. #include "clang/Basic/Version.h"
  67. #include "clang/Lex/HeaderSearch.h"
  68. #include "clang/Lex/HeaderSearchOptions.h"
  69. #include "clang/Lex/MacroInfo.h"
  70. #include "clang/Lex/ModuleMap.h"
  71. #include "clang/Lex/PreprocessingRecord.h"
  72. #include "clang/Lex/Preprocessor.h"
  73. #include "clang/Lex/PreprocessorOptions.h"
  74. #include "clang/Lex/Token.h"
  75. #include "clang/Sema/ObjCMethodList.h"
  76. #include "clang/Sema/Scope.h"
  77. #include "clang/Sema/Sema.h"
  78. #include "clang/Sema/Weak.h"
  79. #include "clang/Serialization/ASTBitCodes.h"
  80. #include "clang/Serialization/ASTDeserializationListener.h"
  81. #include "clang/Serialization/ASTRecordReader.h"
  82. #include "clang/Serialization/ContinuousRangeMap.h"
  83. #include "clang/Serialization/GlobalModuleIndex.h"
  84. #include "clang/Serialization/InMemoryModuleCache.h"
  85. #include "clang/Serialization/ModuleFile.h"
  86. #include "clang/Serialization/ModuleFileExtension.h"
  87. #include "clang/Serialization/ModuleManager.h"
  88. #include "clang/Serialization/PCHContainerOperations.h"
  89. #include "clang/Serialization/SerializationDiagnostic.h"
  90. #include "llvm/ADT/APFloat.h"
  91. #include "llvm/ADT/APInt.h"
  92. #include "llvm/ADT/APSInt.h"
  93. #include "llvm/ADT/ArrayRef.h"
  94. #include "llvm/ADT/DenseMap.h"
  95. #include "llvm/ADT/FloatingPointMode.h"
  96. #include "llvm/ADT/FoldingSet.h"
  97. #include "llvm/ADT/Hashing.h"
  98. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  99. #include "llvm/ADT/STLExtras.h"
  100. #include "llvm/ADT/ScopeExit.h"
  101. #include "llvm/ADT/SmallPtrSet.h"
  102. #include "llvm/ADT/SmallString.h"
  103. #include "llvm/ADT/SmallVector.h"
  104. #include "llvm/ADT/StringExtras.h"
  105. #include "llvm/ADT/StringMap.h"
  106. #include "llvm/ADT/StringRef.h"
  107. #include "llvm/ADT/Triple.h"
  108. #include "llvm/ADT/iterator_range.h"
  109. #include "llvm/Bitstream/BitstreamReader.h"
  110. #include "llvm/Support/Casting.h"
  111. #include "llvm/Support/Compiler.h"
  112. #include "llvm/Support/Compression.h"
  113. #include "llvm/Support/DJB.h"
  114. #include "llvm/Support/Endian.h"
  115. #include "llvm/Support/Error.h"
  116. #include "llvm/Support/ErrorHandling.h"
  117. #include "llvm/Support/FileSystem.h"
  118. #include "llvm/Support/LEB128.h"
  119. #include "llvm/Support/MemoryBuffer.h"
  120. #include "llvm/Support/Path.h"
  121. #include "llvm/Support/SaveAndRestore.h"
  122. #include "llvm/Support/TimeProfiler.h"
  123. #include "llvm/Support/Timer.h"
  124. #include "llvm/Support/VersionTuple.h"
  125. #include "llvm/Support/raw_ostream.h"
  126. #include <algorithm>
  127. #include <cassert>
  128. #include <cstddef>
  129. #include <cstdint>
  130. #include <cstdio>
  131. #include <ctime>
  132. #include <iterator>
  133. #include <limits>
  134. #include <map>
  135. #include <memory>
  136. #include <optional>
  137. #include <string>
  138. #include <system_error>
  139. #include <tuple>
  140. #include <utility>
  141. #include <vector>
  142. using namespace clang;
  143. using namespace clang::serialization;
  144. using namespace clang::serialization::reader;
  145. using llvm::BitstreamCursor;
  146. //===----------------------------------------------------------------------===//
  147. // ChainedASTReaderListener implementation
  148. //===----------------------------------------------------------------------===//
  149. bool
  150. ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
  151. return First->ReadFullVersionInformation(FullVersion) ||
  152. Second->ReadFullVersionInformation(FullVersion);
  153. }
  154. void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
  155. First->ReadModuleName(ModuleName);
  156. Second->ReadModuleName(ModuleName);
  157. }
  158. void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
  159. First->ReadModuleMapFile(ModuleMapPath);
  160. Second->ReadModuleMapFile(ModuleMapPath);
  161. }
  162. bool
  163. ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
  164. bool Complain,
  165. bool AllowCompatibleDifferences) {
  166. return First->ReadLanguageOptions(LangOpts, Complain,
  167. AllowCompatibleDifferences) ||
  168. Second->ReadLanguageOptions(LangOpts, Complain,
  169. AllowCompatibleDifferences);
  170. }
  171. bool ChainedASTReaderListener::ReadTargetOptions(
  172. const TargetOptions &TargetOpts, bool Complain,
  173. bool AllowCompatibleDifferences) {
  174. return First->ReadTargetOptions(TargetOpts, Complain,
  175. AllowCompatibleDifferences) ||
  176. Second->ReadTargetOptions(TargetOpts, Complain,
  177. AllowCompatibleDifferences);
  178. }
  179. bool ChainedASTReaderListener::ReadDiagnosticOptions(
  180. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  181. return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
  182. Second->ReadDiagnosticOptions(DiagOpts, Complain);
  183. }
  184. bool
  185. ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
  186. bool Complain) {
  187. return First->ReadFileSystemOptions(FSOpts, Complain) ||
  188. Second->ReadFileSystemOptions(FSOpts, Complain);
  189. }
  190. bool ChainedASTReaderListener::ReadHeaderSearchOptions(
  191. const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
  192. bool Complain) {
  193. return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  194. Complain) ||
  195. Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  196. Complain);
  197. }
  198. bool ChainedASTReaderListener::ReadPreprocessorOptions(
  199. const PreprocessorOptions &PPOpts, bool Complain,
  200. std::string &SuggestedPredefines) {
  201. return First->ReadPreprocessorOptions(PPOpts, Complain,
  202. SuggestedPredefines) ||
  203. Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
  204. }
  205. void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
  206. unsigned Value) {
  207. First->ReadCounter(M, Value);
  208. Second->ReadCounter(M, Value);
  209. }
  210. bool ChainedASTReaderListener::needsInputFileVisitation() {
  211. return First->needsInputFileVisitation() ||
  212. Second->needsInputFileVisitation();
  213. }
  214. bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
  215. return First->needsSystemInputFileVisitation() ||
  216. Second->needsSystemInputFileVisitation();
  217. }
  218. void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
  219. ModuleKind Kind) {
  220. First->visitModuleFile(Filename, Kind);
  221. Second->visitModuleFile(Filename, Kind);
  222. }
  223. bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
  224. bool isSystem,
  225. bool isOverridden,
  226. bool isExplicitModule) {
  227. bool Continue = false;
  228. if (First->needsInputFileVisitation() &&
  229. (!isSystem || First->needsSystemInputFileVisitation()))
  230. Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
  231. isExplicitModule);
  232. if (Second->needsInputFileVisitation() &&
  233. (!isSystem || Second->needsSystemInputFileVisitation()))
  234. Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
  235. isExplicitModule);
  236. return Continue;
  237. }
  238. void ChainedASTReaderListener::readModuleFileExtension(
  239. const ModuleFileExtensionMetadata &Metadata) {
  240. First->readModuleFileExtension(Metadata);
  241. Second->readModuleFileExtension(Metadata);
  242. }
  243. //===----------------------------------------------------------------------===//
  244. // PCH validator implementation
  245. //===----------------------------------------------------------------------===//
  246. ASTReaderListener::~ASTReaderListener() = default;
  247. /// Compare the given set of language options against an existing set of
  248. /// language options.
  249. ///
  250. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  251. /// \param AllowCompatibleDifferences If true, differences between compatible
  252. /// language options will be permitted.
  253. ///
  254. /// \returns true if the languagae options mis-match, false otherwise.
  255. static bool checkLanguageOptions(const LangOptions &LangOpts,
  256. const LangOptions &ExistingLangOpts,
  257. DiagnosticsEngine *Diags,
  258. bool AllowCompatibleDifferences = true) {
  259. #define LANGOPT(Name, Bits, Default, Description) \
  260. if (ExistingLangOpts.Name != LangOpts.Name) { \
  261. if (Diags) \
  262. Diags->Report(diag::err_pch_langopt_mismatch) \
  263. << Description << LangOpts.Name << ExistingLangOpts.Name; \
  264. return true; \
  265. }
  266. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  267. if (ExistingLangOpts.Name != LangOpts.Name) { \
  268. if (Diags) \
  269. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  270. << Description; \
  271. return true; \
  272. }
  273. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  274. if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
  275. if (Diags) \
  276. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  277. << Description; \
  278. return true; \
  279. }
  280. #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
  281. if (!AllowCompatibleDifferences) \
  282. LANGOPT(Name, Bits, Default, Description)
  283. #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
  284. if (!AllowCompatibleDifferences) \
  285. ENUM_LANGOPT(Name, Bits, Default, Description)
  286. #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
  287. if (!AllowCompatibleDifferences) \
  288. VALUE_LANGOPT(Name, Bits, Default, Description)
  289. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  290. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  291. #define BENIGN_VALUE_LANGOPT(Name, Bits, Default, Description)
  292. #include "clang/Basic/LangOptions.def"
  293. if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
  294. if (Diags)
  295. Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
  296. return true;
  297. }
  298. if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
  299. if (Diags)
  300. Diags->Report(diag::err_pch_langopt_value_mismatch)
  301. << "target Objective-C runtime";
  302. return true;
  303. }
  304. if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
  305. LangOpts.CommentOpts.BlockCommandNames) {
  306. if (Diags)
  307. Diags->Report(diag::err_pch_langopt_value_mismatch)
  308. << "block command names";
  309. return true;
  310. }
  311. // Sanitizer feature mismatches are treated as compatible differences. If
  312. // compatible differences aren't allowed, we still only want to check for
  313. // mismatches of non-modular sanitizers (the only ones which can affect AST
  314. // generation).
  315. if (!AllowCompatibleDifferences) {
  316. SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
  317. SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
  318. SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
  319. ExistingSanitizers.clear(ModularSanitizers);
  320. ImportedSanitizers.clear(ModularSanitizers);
  321. if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
  322. const std::string Flag = "-fsanitize=";
  323. if (Diags) {
  324. #define SANITIZER(NAME, ID) \
  325. { \
  326. bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
  327. bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
  328. if (InExistingModule != InImportedModule) \
  329. Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
  330. << InExistingModule << (Flag + NAME); \
  331. }
  332. #include "clang/Basic/Sanitizers.def"
  333. }
  334. return true;
  335. }
  336. }
  337. return false;
  338. }
  339. /// Compare the given set of target options against an existing set of
  340. /// target options.
  341. ///
  342. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  343. ///
  344. /// \returns true if the target options mis-match, false otherwise.
  345. static bool checkTargetOptions(const TargetOptions &TargetOpts,
  346. const TargetOptions &ExistingTargetOpts,
  347. DiagnosticsEngine *Diags,
  348. bool AllowCompatibleDifferences = true) {
  349. #define CHECK_TARGET_OPT(Field, Name) \
  350. if (TargetOpts.Field != ExistingTargetOpts.Field) { \
  351. if (Diags) \
  352. Diags->Report(diag::err_pch_targetopt_mismatch) \
  353. << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
  354. return true; \
  355. }
  356. // The triple and ABI must match exactly.
  357. CHECK_TARGET_OPT(Triple, "target");
  358. CHECK_TARGET_OPT(ABI, "target ABI");
  359. // We can tolerate different CPUs in many cases, notably when one CPU
  360. // supports a strict superset of another. When allowing compatible
  361. // differences skip this check.
  362. if (!AllowCompatibleDifferences) {
  363. CHECK_TARGET_OPT(CPU, "target CPU");
  364. CHECK_TARGET_OPT(TuneCPU, "tune CPU");
  365. }
  366. #undef CHECK_TARGET_OPT
  367. // Compare feature sets.
  368. SmallVector<StringRef, 4> ExistingFeatures(
  369. ExistingTargetOpts.FeaturesAsWritten.begin(),
  370. ExistingTargetOpts.FeaturesAsWritten.end());
  371. SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
  372. TargetOpts.FeaturesAsWritten.end());
  373. llvm::sort(ExistingFeatures);
  374. llvm::sort(ReadFeatures);
  375. // We compute the set difference in both directions explicitly so that we can
  376. // diagnose the differences differently.
  377. SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
  378. std::set_difference(
  379. ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
  380. ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
  381. std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
  382. ExistingFeatures.begin(), ExistingFeatures.end(),
  383. std::back_inserter(UnmatchedReadFeatures));
  384. // If we are allowing compatible differences and the read feature set is
  385. // a strict subset of the existing feature set, there is nothing to diagnose.
  386. if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
  387. return false;
  388. if (Diags) {
  389. for (StringRef Feature : UnmatchedReadFeatures)
  390. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  391. << /* is-existing-feature */ false << Feature;
  392. for (StringRef Feature : UnmatchedExistingFeatures)
  393. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  394. << /* is-existing-feature */ true << Feature;
  395. }
  396. return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
  397. }
  398. bool
  399. PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
  400. bool Complain,
  401. bool AllowCompatibleDifferences) {
  402. const LangOptions &ExistingLangOpts = PP.getLangOpts();
  403. return checkLanguageOptions(LangOpts, ExistingLangOpts,
  404. Complain ? &Reader.Diags : nullptr,
  405. AllowCompatibleDifferences);
  406. }
  407. bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
  408. bool Complain,
  409. bool AllowCompatibleDifferences) {
  410. const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
  411. return checkTargetOptions(TargetOpts, ExistingTargetOpts,
  412. Complain ? &Reader.Diags : nullptr,
  413. AllowCompatibleDifferences);
  414. }
  415. namespace {
  416. using MacroDefinitionsMap =
  417. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
  418. using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
  419. } // namespace
  420. static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
  421. DiagnosticsEngine &Diags,
  422. bool Complain) {
  423. using Level = DiagnosticsEngine::Level;
  424. // Check current mappings for new -Werror mappings, and the stored mappings
  425. // for cases that were explicitly mapped to *not* be errors that are now
  426. // errors because of options like -Werror.
  427. DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
  428. for (DiagnosticsEngine *MappingSource : MappingSources) {
  429. for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
  430. diag::kind DiagID = DiagIDMappingPair.first;
  431. Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
  432. if (CurLevel < DiagnosticsEngine::Error)
  433. continue; // not significant
  434. Level StoredLevel =
  435. StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
  436. if (StoredLevel < DiagnosticsEngine::Error) {
  437. if (Complain)
  438. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
  439. Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
  440. return true;
  441. }
  442. }
  443. }
  444. return false;
  445. }
  446. static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
  447. diag::Severity Ext = Diags.getExtensionHandlingBehavior();
  448. if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
  449. return true;
  450. return Ext >= diag::Severity::Error;
  451. }
  452. static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
  453. DiagnosticsEngine &Diags,
  454. bool IsSystem, bool Complain) {
  455. // Top-level options
  456. if (IsSystem) {
  457. if (Diags.getSuppressSystemWarnings())
  458. return false;
  459. // If -Wsystem-headers was not enabled before, be conservative
  460. if (StoredDiags.getSuppressSystemWarnings()) {
  461. if (Complain)
  462. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
  463. return true;
  464. }
  465. }
  466. if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
  467. if (Complain)
  468. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
  469. return true;
  470. }
  471. if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
  472. !StoredDiags.getEnableAllWarnings()) {
  473. if (Complain)
  474. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
  475. return true;
  476. }
  477. if (isExtHandlingFromDiagsError(Diags) &&
  478. !isExtHandlingFromDiagsError(StoredDiags)) {
  479. if (Complain)
  480. Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
  481. return true;
  482. }
  483. return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
  484. }
  485. /// Return the top import module if it is implicit, nullptr otherwise.
  486. static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
  487. Preprocessor &PP) {
  488. // If the original import came from a file explicitly generated by the user,
  489. // don't check the diagnostic mappings.
  490. // FIXME: currently this is approximated by checking whether this is not a
  491. // module import of an implicitly-loaded module file.
  492. // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
  493. // the transitive closure of its imports, since unrelated modules cannot be
  494. // imported until after this module finishes validation.
  495. ModuleFile *TopImport = &*ModuleMgr.rbegin();
  496. while (!TopImport->ImportedBy.empty())
  497. TopImport = TopImport->ImportedBy[0];
  498. if (TopImport->Kind != MK_ImplicitModule)
  499. return nullptr;
  500. StringRef ModuleName = TopImport->ModuleName;
  501. assert(!ModuleName.empty() && "diagnostic options read before module name");
  502. Module *M =
  503. PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
  504. assert(M && "missing module");
  505. return M;
  506. }
  507. bool PCHValidator::ReadDiagnosticOptions(
  508. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  509. DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
  510. IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
  511. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
  512. new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
  513. // This should never fail, because we would have processed these options
  514. // before writing them to an ASTFile.
  515. ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
  516. ModuleManager &ModuleMgr = Reader.getModuleManager();
  517. assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
  518. Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
  519. if (!TopM)
  520. return false;
  521. // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
  522. // contains the union of their flags.
  523. return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
  524. Complain);
  525. }
  526. /// Collect the macro definitions provided by the given preprocessor
  527. /// options.
  528. static void
  529. collectMacroDefinitions(const PreprocessorOptions &PPOpts,
  530. MacroDefinitionsMap &Macros,
  531. SmallVectorImpl<StringRef> *MacroNames = nullptr) {
  532. for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
  533. StringRef Macro = PPOpts.Macros[I].first;
  534. bool IsUndef = PPOpts.Macros[I].second;
  535. std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
  536. StringRef MacroName = MacroPair.first;
  537. StringRef MacroBody = MacroPair.second;
  538. // For an #undef'd macro, we only care about the name.
  539. if (IsUndef) {
  540. if (MacroNames && !Macros.count(MacroName))
  541. MacroNames->push_back(MacroName);
  542. Macros[MacroName] = std::make_pair("", true);
  543. continue;
  544. }
  545. // For a #define'd macro, figure out the actual definition.
  546. if (MacroName.size() == Macro.size())
  547. MacroBody = "1";
  548. else {
  549. // Note: GCC drops anything following an end-of-line character.
  550. StringRef::size_type End = MacroBody.find_first_of("\n\r");
  551. MacroBody = MacroBody.substr(0, End);
  552. }
  553. if (MacroNames && !Macros.count(MacroName))
  554. MacroNames->push_back(MacroName);
  555. Macros[MacroName] = std::make_pair(MacroBody, false);
  556. }
  557. }
  558. enum OptionValidation {
  559. OptionValidateNone,
  560. OptionValidateContradictions,
  561. OptionValidateStrictMatches,
  562. };
  563. /// Check the preprocessor options deserialized from the control block
  564. /// against the preprocessor options in an existing preprocessor.
  565. ///
  566. /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
  567. /// \param Validation If set to OptionValidateNone, ignore differences in
  568. /// preprocessor options. If set to OptionValidateContradictions,
  569. /// require that options passed both in the AST file and on the command
  570. /// line (-D or -U) match, but tolerate options missing in one or the
  571. /// other. If set to OptionValidateContradictions, require that there
  572. /// are no differences in the options between the two.
  573. static bool checkPreprocessorOptions(
  574. const PreprocessorOptions &PPOpts,
  575. const PreprocessorOptions &ExistingPPOpts, DiagnosticsEngine *Diags,
  576. FileManager &FileMgr, std::string &SuggestedPredefines,
  577. const LangOptions &LangOpts,
  578. OptionValidation Validation = OptionValidateContradictions) {
  579. // Check macro definitions.
  580. MacroDefinitionsMap ASTFileMacros;
  581. collectMacroDefinitions(PPOpts, ASTFileMacros);
  582. MacroDefinitionsMap ExistingMacros;
  583. SmallVector<StringRef, 4> ExistingMacroNames;
  584. collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
  585. for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
  586. // Dig out the macro definition in the existing preprocessor options.
  587. StringRef MacroName = ExistingMacroNames[I];
  588. std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
  589. // Check whether we know anything about this macro name or not.
  590. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
  591. ASTFileMacros.find(MacroName);
  592. if (Validation == OptionValidateNone || Known == ASTFileMacros.end()) {
  593. if (Validation == OptionValidateStrictMatches) {
  594. // If strict matches are requested, don't tolerate any extra defines on
  595. // the command line that are missing in the AST file.
  596. if (Diags) {
  597. Diags->Report(diag::err_pch_macro_def_undef) << MacroName << true;
  598. }
  599. return true;
  600. }
  601. // FIXME: Check whether this identifier was referenced anywhere in the
  602. // AST file. If so, we should reject the AST file. Unfortunately, this
  603. // information isn't in the control block. What shall we do about it?
  604. if (Existing.second) {
  605. SuggestedPredefines += "#undef ";
  606. SuggestedPredefines += MacroName.str();
  607. SuggestedPredefines += '\n';
  608. } else {
  609. SuggestedPredefines += "#define ";
  610. SuggestedPredefines += MacroName.str();
  611. SuggestedPredefines += ' ';
  612. SuggestedPredefines += Existing.first.str();
  613. SuggestedPredefines += '\n';
  614. }
  615. continue;
  616. }
  617. // If the macro was defined in one but undef'd in the other, we have a
  618. // conflict.
  619. if (Existing.second != Known->second.second) {
  620. if (Diags) {
  621. Diags->Report(diag::err_pch_macro_def_undef)
  622. << MacroName << Known->second.second;
  623. }
  624. return true;
  625. }
  626. // If the macro was #undef'd in both, or if the macro bodies are identical,
  627. // it's fine.
  628. if (Existing.second || Existing.first == Known->second.first) {
  629. ASTFileMacros.erase(Known);
  630. continue;
  631. }
  632. // The macro bodies differ; complain.
  633. if (Diags) {
  634. Diags->Report(diag::err_pch_macro_def_conflict)
  635. << MacroName << Known->second.first << Existing.first;
  636. }
  637. return true;
  638. }
  639. if (Validation == OptionValidateStrictMatches) {
  640. // If strict matches are requested, don't tolerate any extra defines in
  641. // the AST file that are missing on the command line.
  642. for (const auto &MacroName : ASTFileMacros.keys()) {
  643. if (Diags) {
  644. Diags->Report(diag::err_pch_macro_def_undef) << MacroName << false;
  645. }
  646. return true;
  647. }
  648. }
  649. // Check whether we're using predefines.
  650. if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines &&
  651. Validation != OptionValidateNone) {
  652. if (Diags) {
  653. Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
  654. }
  655. return true;
  656. }
  657. // Detailed record is important since it is used for the module cache hash.
  658. if (LangOpts.Modules &&
  659. PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord &&
  660. Validation != OptionValidateNone) {
  661. if (Diags) {
  662. Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
  663. }
  664. return true;
  665. }
  666. // Compute the #include and #include_macros lines we need.
  667. for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
  668. StringRef File = ExistingPPOpts.Includes[I];
  669. if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
  670. !ExistingPPOpts.PCHThroughHeader.empty()) {
  671. // In case the through header is an include, we must add all the includes
  672. // to the predefines so the start point can be determined.
  673. SuggestedPredefines += "#include \"";
  674. SuggestedPredefines += File;
  675. SuggestedPredefines += "\"\n";
  676. continue;
  677. }
  678. if (File == ExistingPPOpts.ImplicitPCHInclude)
  679. continue;
  680. if (llvm::is_contained(PPOpts.Includes, File))
  681. continue;
  682. SuggestedPredefines += "#include \"";
  683. SuggestedPredefines += File;
  684. SuggestedPredefines += "\"\n";
  685. }
  686. for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
  687. StringRef File = ExistingPPOpts.MacroIncludes[I];
  688. if (llvm::is_contained(PPOpts.MacroIncludes, File))
  689. continue;
  690. SuggestedPredefines += "#__include_macros \"";
  691. SuggestedPredefines += File;
  692. SuggestedPredefines += "\"\n##\n";
  693. }
  694. return false;
  695. }
  696. bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  697. bool Complain,
  698. std::string &SuggestedPredefines) {
  699. const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
  700. return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
  701. Complain? &Reader.Diags : nullptr,
  702. PP.getFileManager(),
  703. SuggestedPredefines,
  704. PP.getLangOpts());
  705. }
  706. bool SimpleASTReaderListener::ReadPreprocessorOptions(
  707. const PreprocessorOptions &PPOpts,
  708. bool Complain,
  709. std::string &SuggestedPredefines) {
  710. return checkPreprocessorOptions(PPOpts, PP.getPreprocessorOpts(), nullptr,
  711. PP.getFileManager(), SuggestedPredefines,
  712. PP.getLangOpts(), OptionValidateNone);
  713. }
  714. /// Check the header search options deserialized from the control block
  715. /// against the header search options in an existing preprocessor.
  716. ///
  717. /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
  718. static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  719. StringRef SpecificModuleCachePath,
  720. StringRef ExistingModuleCachePath,
  721. DiagnosticsEngine *Diags,
  722. const LangOptions &LangOpts,
  723. const PreprocessorOptions &PPOpts) {
  724. if (LangOpts.Modules) {
  725. if (SpecificModuleCachePath != ExistingModuleCachePath &&
  726. !PPOpts.AllowPCHWithDifferentModulesCachePath) {
  727. if (Diags)
  728. Diags->Report(diag::err_pch_modulecache_mismatch)
  729. << SpecificModuleCachePath << ExistingModuleCachePath;
  730. return true;
  731. }
  732. }
  733. return false;
  734. }
  735. bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  736. StringRef SpecificModuleCachePath,
  737. bool Complain) {
  738. return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  739. PP.getHeaderSearchInfo().getModuleCachePath(),
  740. Complain ? &Reader.Diags : nullptr,
  741. PP.getLangOpts(), PP.getPreprocessorOpts());
  742. }
  743. void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
  744. PP.setCounterValue(Value);
  745. }
  746. //===----------------------------------------------------------------------===//
  747. // AST reader implementation
  748. //===----------------------------------------------------------------------===//
  749. static uint64_t readULEB(const unsigned char *&P) {
  750. unsigned Length = 0;
  751. const char *Error = nullptr;
  752. uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
  753. if (Error)
  754. llvm::report_fatal_error(Error);
  755. P += Length;
  756. return Val;
  757. }
  758. /// Read ULEB-encoded key length and data length.
  759. static std::pair<unsigned, unsigned>
  760. readULEBKeyDataLength(const unsigned char *&P) {
  761. unsigned KeyLen = readULEB(P);
  762. if ((unsigned)KeyLen != KeyLen)
  763. llvm::report_fatal_error("key too large");
  764. unsigned DataLen = readULEB(P);
  765. if ((unsigned)DataLen != DataLen)
  766. llvm::report_fatal_error("data too large");
  767. return std::make_pair(KeyLen, DataLen);
  768. }
  769. void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
  770. bool TakeOwnership) {
  771. DeserializationListener = Listener;
  772. OwnsDeserializationListener = TakeOwnership;
  773. }
  774. unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
  775. return serialization::ComputeHash(Sel);
  776. }
  777. std::pair<unsigned, unsigned>
  778. ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
  779. return readULEBKeyDataLength(d);
  780. }
  781. ASTSelectorLookupTrait::internal_key_type
  782. ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
  783. using namespace llvm::support;
  784. SelectorTable &SelTable = Reader.getContext().Selectors;
  785. unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
  786. IdentifierInfo *FirstII = Reader.getLocalIdentifier(
  787. F, endian::readNext<uint32_t, little, unaligned>(d));
  788. if (N == 0)
  789. return SelTable.getNullarySelector(FirstII);
  790. else if (N == 1)
  791. return SelTable.getUnarySelector(FirstII);
  792. SmallVector<IdentifierInfo *, 16> Args;
  793. Args.push_back(FirstII);
  794. for (unsigned I = 1; I != N; ++I)
  795. Args.push_back(Reader.getLocalIdentifier(
  796. F, endian::readNext<uint32_t, little, unaligned>(d)));
  797. return SelTable.getSelector(N, Args.data());
  798. }
  799. ASTSelectorLookupTrait::data_type
  800. ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
  801. unsigned DataLen) {
  802. using namespace llvm::support;
  803. data_type Result;
  804. Result.ID = Reader.getGlobalSelectorID(
  805. F, endian::readNext<uint32_t, little, unaligned>(d));
  806. unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
  807. unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
  808. Result.InstanceBits = FullInstanceBits & 0x3;
  809. Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
  810. Result.FactoryBits = FullFactoryBits & 0x3;
  811. Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
  812. unsigned NumInstanceMethods = FullInstanceBits >> 3;
  813. unsigned NumFactoryMethods = FullFactoryBits >> 3;
  814. // Load instance methods
  815. for (unsigned I = 0; I != NumInstanceMethods; ++I) {
  816. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  817. F, endian::readNext<uint32_t, little, unaligned>(d)))
  818. Result.Instance.push_back(Method);
  819. }
  820. // Load factory methods
  821. for (unsigned I = 0; I != NumFactoryMethods; ++I) {
  822. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  823. F, endian::readNext<uint32_t, little, unaligned>(d)))
  824. Result.Factory.push_back(Method);
  825. }
  826. return Result;
  827. }
  828. unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
  829. return llvm::djbHash(a);
  830. }
  831. std::pair<unsigned, unsigned>
  832. ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
  833. return readULEBKeyDataLength(d);
  834. }
  835. ASTIdentifierLookupTraitBase::internal_key_type
  836. ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
  837. assert(n >= 2 && d[n-1] == '\0');
  838. return StringRef((const char*) d, n-1);
  839. }
  840. /// Whether the given identifier is "interesting".
  841. static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
  842. bool IsModule) {
  843. return II.hadMacroDefinition() || II.isPoisoned() ||
  844. (!IsModule && II.getObjCOrBuiltinID()) ||
  845. II.hasRevertedTokenIDToIdentifier() ||
  846. (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
  847. II.getFETokenInfo());
  848. }
  849. static bool readBit(unsigned &Bits) {
  850. bool Value = Bits & 0x1;
  851. Bits >>= 1;
  852. return Value;
  853. }
  854. IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
  855. using namespace llvm::support;
  856. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  857. return Reader.getGlobalIdentifierID(F, RawID >> 1);
  858. }
  859. static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
  860. if (!II.isFromAST()) {
  861. II.setIsFromAST();
  862. bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
  863. if (isInterestingIdentifier(Reader, II, IsModule))
  864. II.setChangedSinceDeserialization();
  865. }
  866. }
  867. IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
  868. const unsigned char* d,
  869. unsigned DataLen) {
  870. using namespace llvm::support;
  871. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  872. bool IsInteresting = RawID & 0x01;
  873. // Wipe out the "is interesting" bit.
  874. RawID = RawID >> 1;
  875. // Build the IdentifierInfo and link the identifier ID with it.
  876. IdentifierInfo *II = KnownII;
  877. if (!II) {
  878. II = &Reader.getIdentifierTable().getOwn(k);
  879. KnownII = II;
  880. }
  881. markIdentifierFromAST(Reader, *II);
  882. Reader.markIdentifierUpToDate(II);
  883. IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
  884. if (!IsInteresting) {
  885. // For uninteresting identifiers, there's nothing else to do. Just notify
  886. // the reader that we've finished loading this identifier.
  887. Reader.SetIdentifierInfo(ID, II);
  888. return II;
  889. }
  890. unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
  891. unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
  892. bool CPlusPlusOperatorKeyword = readBit(Bits);
  893. bool HasRevertedTokenIDToIdentifier = readBit(Bits);
  894. bool Poisoned = readBit(Bits);
  895. bool ExtensionToken = readBit(Bits);
  896. bool HadMacroDefinition = readBit(Bits);
  897. assert(Bits == 0 && "Extra bits in the identifier?");
  898. DataLen -= 8;
  899. // Set or check the various bits in the IdentifierInfo structure.
  900. // Token IDs are read-only.
  901. if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
  902. II->revertTokenIDToIdentifier();
  903. if (!F.isModule())
  904. II->setObjCOrBuiltinID(ObjCOrBuiltinID);
  905. assert(II->isExtensionToken() == ExtensionToken &&
  906. "Incorrect extension token flag");
  907. (void)ExtensionToken;
  908. if (Poisoned)
  909. II->setIsPoisoned(true);
  910. assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
  911. "Incorrect C++ operator keyword flag");
  912. (void)CPlusPlusOperatorKeyword;
  913. // If this identifier is a macro, deserialize the macro
  914. // definition.
  915. if (HadMacroDefinition) {
  916. uint32_t MacroDirectivesOffset =
  917. endian::readNext<uint32_t, little, unaligned>(d);
  918. DataLen -= 4;
  919. Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
  920. }
  921. Reader.SetIdentifierInfo(ID, II);
  922. // Read all of the declarations visible at global scope with this
  923. // name.
  924. if (DataLen > 0) {
  925. SmallVector<uint32_t, 4> DeclIDs;
  926. for (; DataLen > 0; DataLen -= 4)
  927. DeclIDs.push_back(Reader.getGlobalDeclID(
  928. F, endian::readNext<uint32_t, little, unaligned>(d)));
  929. Reader.SetGloballyVisibleDecls(II, DeclIDs);
  930. }
  931. return II;
  932. }
  933. DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
  934. : Kind(Name.getNameKind()) {
  935. switch (Kind) {
  936. case DeclarationName::Identifier:
  937. Data = (uint64_t)Name.getAsIdentifierInfo();
  938. break;
  939. case DeclarationName::ObjCZeroArgSelector:
  940. case DeclarationName::ObjCOneArgSelector:
  941. case DeclarationName::ObjCMultiArgSelector:
  942. Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
  943. break;
  944. case DeclarationName::CXXOperatorName:
  945. Data = Name.getCXXOverloadedOperator();
  946. break;
  947. case DeclarationName::CXXLiteralOperatorName:
  948. Data = (uint64_t)Name.getCXXLiteralIdentifier();
  949. break;
  950. case DeclarationName::CXXDeductionGuideName:
  951. Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
  952. ->getDeclName().getAsIdentifierInfo();
  953. break;
  954. case DeclarationName::CXXConstructorName:
  955. case DeclarationName::CXXDestructorName:
  956. case DeclarationName::CXXConversionFunctionName:
  957. case DeclarationName::CXXUsingDirective:
  958. Data = 0;
  959. break;
  960. }
  961. }
  962. unsigned DeclarationNameKey::getHash() const {
  963. llvm::FoldingSetNodeID ID;
  964. ID.AddInteger(Kind);
  965. switch (Kind) {
  966. case DeclarationName::Identifier:
  967. case DeclarationName::CXXLiteralOperatorName:
  968. case DeclarationName::CXXDeductionGuideName:
  969. ID.AddString(((IdentifierInfo*)Data)->getName());
  970. break;
  971. case DeclarationName::ObjCZeroArgSelector:
  972. case DeclarationName::ObjCOneArgSelector:
  973. case DeclarationName::ObjCMultiArgSelector:
  974. ID.AddInteger(serialization::ComputeHash(Selector(Data)));
  975. break;
  976. case DeclarationName::CXXOperatorName:
  977. ID.AddInteger((OverloadedOperatorKind)Data);
  978. break;
  979. case DeclarationName::CXXConstructorName:
  980. case DeclarationName::CXXDestructorName:
  981. case DeclarationName::CXXConversionFunctionName:
  982. case DeclarationName::CXXUsingDirective:
  983. break;
  984. }
  985. return ID.ComputeHash();
  986. }
  987. ModuleFile *
  988. ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
  989. using namespace llvm::support;
  990. uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
  991. return Reader.getLocalModuleFile(F, ModuleFileID);
  992. }
  993. std::pair<unsigned, unsigned>
  994. ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
  995. return readULEBKeyDataLength(d);
  996. }
  997. ASTDeclContextNameLookupTrait::internal_key_type
  998. ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
  999. using namespace llvm::support;
  1000. auto Kind = (DeclarationName::NameKind)*d++;
  1001. uint64_t Data;
  1002. switch (Kind) {
  1003. case DeclarationName::Identifier:
  1004. case DeclarationName::CXXLiteralOperatorName:
  1005. case DeclarationName::CXXDeductionGuideName:
  1006. Data = (uint64_t)Reader.getLocalIdentifier(
  1007. F, endian::readNext<uint32_t, little, unaligned>(d));
  1008. break;
  1009. case DeclarationName::ObjCZeroArgSelector:
  1010. case DeclarationName::ObjCOneArgSelector:
  1011. case DeclarationName::ObjCMultiArgSelector:
  1012. Data =
  1013. (uint64_t)Reader.getLocalSelector(
  1014. F, endian::readNext<uint32_t, little, unaligned>(
  1015. d)).getAsOpaquePtr();
  1016. break;
  1017. case DeclarationName::CXXOperatorName:
  1018. Data = *d++; // OverloadedOperatorKind
  1019. break;
  1020. case DeclarationName::CXXConstructorName:
  1021. case DeclarationName::CXXDestructorName:
  1022. case DeclarationName::CXXConversionFunctionName:
  1023. case DeclarationName::CXXUsingDirective:
  1024. Data = 0;
  1025. break;
  1026. }
  1027. return DeclarationNameKey(Kind, Data);
  1028. }
  1029. void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
  1030. const unsigned char *d,
  1031. unsigned DataLen,
  1032. data_type_builder &Val) {
  1033. using namespace llvm::support;
  1034. for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
  1035. uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
  1036. Val.insert(Reader.getGlobalDeclID(F, LocalID));
  1037. }
  1038. }
  1039. bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
  1040. BitstreamCursor &Cursor,
  1041. uint64_t Offset,
  1042. DeclContext *DC) {
  1043. assert(Offset != 0);
  1044. SavedStreamPosition SavedPosition(Cursor);
  1045. if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
  1046. Error(std::move(Err));
  1047. return true;
  1048. }
  1049. RecordData Record;
  1050. StringRef Blob;
  1051. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  1052. if (!MaybeCode) {
  1053. Error(MaybeCode.takeError());
  1054. return true;
  1055. }
  1056. unsigned Code = MaybeCode.get();
  1057. Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
  1058. if (!MaybeRecCode) {
  1059. Error(MaybeRecCode.takeError());
  1060. return true;
  1061. }
  1062. unsigned RecCode = MaybeRecCode.get();
  1063. if (RecCode != DECL_CONTEXT_LEXICAL) {
  1064. Error("Expected lexical block");
  1065. return true;
  1066. }
  1067. assert(!isa<TranslationUnitDecl>(DC) &&
  1068. "expected a TU_UPDATE_LEXICAL record for TU");
  1069. // If we are handling a C++ class template instantiation, we can see multiple
  1070. // lexical updates for the same record. It's important that we select only one
  1071. // of them, so that field numbering works properly. Just pick the first one we
  1072. // see.
  1073. auto &Lex = LexicalDecls[DC];
  1074. if (!Lex.first) {
  1075. Lex = std::make_pair(
  1076. &M, llvm::ArrayRef(
  1077. reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
  1078. Blob.data()),
  1079. Blob.size() / 4));
  1080. }
  1081. DC->setHasExternalLexicalStorage(true);
  1082. return false;
  1083. }
  1084. bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
  1085. BitstreamCursor &Cursor,
  1086. uint64_t Offset,
  1087. DeclID ID) {
  1088. assert(Offset != 0);
  1089. SavedStreamPosition SavedPosition(Cursor);
  1090. if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
  1091. Error(std::move(Err));
  1092. return true;
  1093. }
  1094. RecordData Record;
  1095. StringRef Blob;
  1096. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  1097. if (!MaybeCode) {
  1098. Error(MaybeCode.takeError());
  1099. return true;
  1100. }
  1101. unsigned Code = MaybeCode.get();
  1102. Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
  1103. if (!MaybeRecCode) {
  1104. Error(MaybeRecCode.takeError());
  1105. return true;
  1106. }
  1107. unsigned RecCode = MaybeRecCode.get();
  1108. if (RecCode != DECL_CONTEXT_VISIBLE) {
  1109. Error("Expected visible lookup table block");
  1110. return true;
  1111. }
  1112. // We can't safely determine the primary context yet, so delay attaching the
  1113. // lookup table until we're done with recursive deserialization.
  1114. auto *Data = (const unsigned char*)Blob.data();
  1115. PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
  1116. return false;
  1117. }
  1118. void ASTReader::Error(StringRef Msg) const {
  1119. Error(diag::err_fe_pch_malformed, Msg);
  1120. if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
  1121. !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
  1122. Diag(diag::note_module_cache_path)
  1123. << PP.getHeaderSearchInfo().getModuleCachePath();
  1124. }
  1125. }
  1126. void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
  1127. StringRef Arg3) const {
  1128. if (Diags.isDiagnosticInFlight())
  1129. Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
  1130. else
  1131. Diag(DiagID) << Arg1 << Arg2 << Arg3;
  1132. }
  1133. void ASTReader::Error(llvm::Error &&Err) const {
  1134. llvm::Error RemainingErr =
  1135. handleErrors(std::move(Err), [this](const DiagnosticError &E) {
  1136. auto Diag = E.getDiagnostic().second;
  1137. // Ideally we'd just emit it, but have to handle a possible in-flight
  1138. // diagnostic. Note that the location is currently ignored as well.
  1139. auto NumArgs = Diag.getStorage()->NumDiagArgs;
  1140. assert(NumArgs <= 3 && "Can only have up to 3 arguments");
  1141. StringRef Arg1, Arg2, Arg3;
  1142. switch (NumArgs) {
  1143. case 3:
  1144. Arg3 = Diag.getStringArg(2);
  1145. [[fallthrough]];
  1146. case 2:
  1147. Arg2 = Diag.getStringArg(1);
  1148. [[fallthrough]];
  1149. case 1:
  1150. Arg1 = Diag.getStringArg(0);
  1151. }
  1152. Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
  1153. });
  1154. if (RemainingErr)
  1155. Error(toString(std::move(RemainingErr)));
  1156. }
  1157. //===----------------------------------------------------------------------===//
  1158. // Source Manager Deserialization
  1159. //===----------------------------------------------------------------------===//
  1160. /// Read the line table in the source manager block.
  1161. void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
  1162. unsigned Idx = 0;
  1163. LineTableInfo &LineTable = SourceMgr.getLineTable();
  1164. // Parse the file names
  1165. std::map<int, int> FileIDs;
  1166. FileIDs[-1] = -1; // For unspecified filenames.
  1167. for (unsigned I = 0; Record[Idx]; ++I) {
  1168. // Extract the file name
  1169. auto Filename = ReadPath(F, Record, Idx);
  1170. FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
  1171. }
  1172. ++Idx;
  1173. // Parse the line entries
  1174. std::vector<LineEntry> Entries;
  1175. while (Idx < Record.size()) {
  1176. FileID FID = ReadFileID(F, Record, Idx);
  1177. // Extract the line entries
  1178. unsigned NumEntries = Record[Idx++];
  1179. assert(NumEntries && "no line entries for file ID");
  1180. Entries.clear();
  1181. Entries.reserve(NumEntries);
  1182. for (unsigned I = 0; I != NumEntries; ++I) {
  1183. unsigned FileOffset = Record[Idx++];
  1184. unsigned LineNo = Record[Idx++];
  1185. int FilenameID = FileIDs[Record[Idx++]];
  1186. SrcMgr::CharacteristicKind FileKind
  1187. = (SrcMgr::CharacteristicKind)Record[Idx++];
  1188. unsigned IncludeOffset = Record[Idx++];
  1189. Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
  1190. FileKind, IncludeOffset));
  1191. }
  1192. LineTable.AddEntry(FID, Entries);
  1193. }
  1194. }
  1195. /// Read a source manager block
  1196. llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
  1197. using namespace SrcMgr;
  1198. BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
  1199. // Set the source-location entry cursor to the current position in
  1200. // the stream. This cursor will be used to read the contents of the
  1201. // source manager block initially, and then lazily read
  1202. // source-location entries as needed.
  1203. SLocEntryCursor = F.Stream;
  1204. // The stream itself is going to skip over the source manager block.
  1205. if (llvm::Error Err = F.Stream.SkipBlock())
  1206. return Err;
  1207. // Enter the source manager block.
  1208. if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
  1209. return Err;
  1210. F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
  1211. RecordData Record;
  1212. while (true) {
  1213. Expected<llvm::BitstreamEntry> MaybeE =
  1214. SLocEntryCursor.advanceSkippingSubblocks();
  1215. if (!MaybeE)
  1216. return MaybeE.takeError();
  1217. llvm::BitstreamEntry E = MaybeE.get();
  1218. switch (E.Kind) {
  1219. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1220. case llvm::BitstreamEntry::Error:
  1221. return llvm::createStringError(std::errc::illegal_byte_sequence,
  1222. "malformed block record in AST file");
  1223. case llvm::BitstreamEntry::EndBlock:
  1224. return llvm::Error::success();
  1225. case llvm::BitstreamEntry::Record:
  1226. // The interesting case.
  1227. break;
  1228. }
  1229. // Read a record.
  1230. Record.clear();
  1231. StringRef Blob;
  1232. Expected<unsigned> MaybeRecord =
  1233. SLocEntryCursor.readRecord(E.ID, Record, &Blob);
  1234. if (!MaybeRecord)
  1235. return MaybeRecord.takeError();
  1236. switch (MaybeRecord.get()) {
  1237. default: // Default behavior: ignore.
  1238. break;
  1239. case SM_SLOC_FILE_ENTRY:
  1240. case SM_SLOC_BUFFER_ENTRY:
  1241. case SM_SLOC_EXPANSION_ENTRY:
  1242. // Once we hit one of the source location entries, we're done.
  1243. return llvm::Error::success();
  1244. }
  1245. }
  1246. }
  1247. bool ASTReader::ReadSLocEntry(int ID) {
  1248. if (ID == 0)
  1249. return false;
  1250. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1251. Error("source location entry ID out-of-range for AST file");
  1252. return true;
  1253. }
  1254. // Local helper to read the (possibly-compressed) buffer data following the
  1255. // entry record.
  1256. auto ReadBuffer = [this](
  1257. BitstreamCursor &SLocEntryCursor,
  1258. StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
  1259. RecordData Record;
  1260. StringRef Blob;
  1261. Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
  1262. if (!MaybeCode) {
  1263. Error(MaybeCode.takeError());
  1264. return nullptr;
  1265. }
  1266. unsigned Code = MaybeCode.get();
  1267. Expected<unsigned> MaybeRecCode =
  1268. SLocEntryCursor.readRecord(Code, Record, &Blob);
  1269. if (!MaybeRecCode) {
  1270. Error(MaybeRecCode.takeError());
  1271. return nullptr;
  1272. }
  1273. unsigned RecCode = MaybeRecCode.get();
  1274. if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
  1275. // Inspect the first byte to differentiate zlib (\x78) and zstd
  1276. // (little-endian 0xFD2FB528).
  1277. const llvm::compression::Format F =
  1278. Blob.size() > 0 && Blob.data()[0] == 0x78
  1279. ? llvm::compression::Format::Zlib
  1280. : llvm::compression::Format::Zstd;
  1281. if (const char *Reason = llvm::compression::getReasonIfUnsupported(F)) {
  1282. Error(Reason);
  1283. return nullptr;
  1284. }
  1285. SmallVector<uint8_t, 0> Decompressed;
  1286. if (llvm::Error E = llvm::compression::decompress(
  1287. F, llvm::arrayRefFromStringRef(Blob), Decompressed, Record[0])) {
  1288. Error("could not decompress embedded file contents: " +
  1289. llvm::toString(std::move(E)));
  1290. return nullptr;
  1291. }
  1292. return llvm::MemoryBuffer::getMemBufferCopy(
  1293. llvm::toStringRef(Decompressed), Name);
  1294. } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
  1295. return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
  1296. } else {
  1297. Error("AST record has invalid code");
  1298. return nullptr;
  1299. }
  1300. };
  1301. ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
  1302. if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
  1303. F->SLocEntryOffsetsBase +
  1304. F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
  1305. Error(std::move(Err));
  1306. return true;
  1307. }
  1308. BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
  1309. SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
  1310. ++NumSLocEntriesRead;
  1311. Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
  1312. if (!MaybeEntry) {
  1313. Error(MaybeEntry.takeError());
  1314. return true;
  1315. }
  1316. llvm::BitstreamEntry Entry = MaybeEntry.get();
  1317. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1318. Error("incorrectly-formatted source location entry in AST file");
  1319. return true;
  1320. }
  1321. RecordData Record;
  1322. StringRef Blob;
  1323. Expected<unsigned> MaybeSLOC =
  1324. SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
  1325. if (!MaybeSLOC) {
  1326. Error(MaybeSLOC.takeError());
  1327. return true;
  1328. }
  1329. switch (MaybeSLOC.get()) {
  1330. default:
  1331. Error("incorrectly-formatted source location entry in AST file");
  1332. return true;
  1333. case SM_SLOC_FILE_ENTRY: {
  1334. // We will detect whether a file changed and return 'Failure' for it, but
  1335. // we will also try to fail gracefully by setting up the SLocEntry.
  1336. unsigned InputID = Record[4];
  1337. InputFile IF = getInputFile(*F, InputID);
  1338. OptionalFileEntryRef File = IF.getFile();
  1339. bool OverriddenBuffer = IF.isOverridden();
  1340. // Note that we only check if a File was returned. If it was out-of-date
  1341. // we have complained but we will continue creating a FileID to recover
  1342. // gracefully.
  1343. if (!File)
  1344. return true;
  1345. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1346. if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
  1347. // This is the module's main file.
  1348. IncludeLoc = getImportLocation(F);
  1349. }
  1350. SrcMgr::CharacteristicKind
  1351. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1352. FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
  1353. BaseOffset + Record[0]);
  1354. SrcMgr::FileInfo &FileInfo =
  1355. const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
  1356. FileInfo.NumCreatedFIDs = Record[5];
  1357. if (Record[3])
  1358. FileInfo.setHasLineDirectives();
  1359. unsigned NumFileDecls = Record[7];
  1360. if (NumFileDecls && ContextObj) {
  1361. const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
  1362. assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
  1363. FileDeclIDs[FID] =
  1364. FileDeclsInfo(F, llvm::ArrayRef(FirstDecl, NumFileDecls));
  1365. }
  1366. const SrcMgr::ContentCache &ContentCache =
  1367. SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
  1368. if (OverriddenBuffer && !ContentCache.BufferOverridden &&
  1369. ContentCache.ContentsEntry == ContentCache.OrigEntry &&
  1370. !ContentCache.getBufferIfLoaded()) {
  1371. auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
  1372. if (!Buffer)
  1373. return true;
  1374. SourceMgr.overrideFileContents(*File, std::move(Buffer));
  1375. }
  1376. break;
  1377. }
  1378. case SM_SLOC_BUFFER_ENTRY: {
  1379. const char *Name = Blob.data();
  1380. unsigned Offset = Record[0];
  1381. SrcMgr::CharacteristicKind
  1382. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1383. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1384. if (IncludeLoc.isInvalid() && F->isModule()) {
  1385. IncludeLoc = getImportLocation(F);
  1386. }
  1387. auto Buffer = ReadBuffer(SLocEntryCursor, Name);
  1388. if (!Buffer)
  1389. return true;
  1390. SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
  1391. BaseOffset + Offset, IncludeLoc);
  1392. break;
  1393. }
  1394. case SM_SLOC_EXPANSION_ENTRY: {
  1395. LocSeq::State Seq;
  1396. SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1], Seq);
  1397. SourceLocation ExpansionBegin = ReadSourceLocation(*F, Record[2], Seq);
  1398. SourceLocation ExpansionEnd = ReadSourceLocation(*F, Record[3], Seq);
  1399. SourceMgr.createExpansionLoc(SpellingLoc, ExpansionBegin, ExpansionEnd,
  1400. Record[5], Record[4], ID,
  1401. BaseOffset + Record[0]);
  1402. break;
  1403. }
  1404. }
  1405. return false;
  1406. }
  1407. std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
  1408. if (ID == 0)
  1409. return std::make_pair(SourceLocation(), "");
  1410. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1411. Error("source location entry ID out-of-range for AST file");
  1412. return std::make_pair(SourceLocation(), "");
  1413. }
  1414. // Find which module file this entry lands in.
  1415. ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
  1416. if (!M->isModule())
  1417. return std::make_pair(SourceLocation(), "");
  1418. // FIXME: Can we map this down to a particular submodule? That would be
  1419. // ideal.
  1420. return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
  1421. }
  1422. /// Find the location where the module F is imported.
  1423. SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
  1424. if (F->ImportLoc.isValid())
  1425. return F->ImportLoc;
  1426. // Otherwise we have a PCH. It's considered to be "imported" at the first
  1427. // location of its includer.
  1428. if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
  1429. // Main file is the importer.
  1430. assert(SourceMgr.getMainFileID().isValid() && "missing main file");
  1431. return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  1432. }
  1433. return F->ImportedBy[0]->FirstLoc;
  1434. }
  1435. /// Enter a subblock of the specified BlockID with the specified cursor. Read
  1436. /// the abbreviations that are at the top of the block and then leave the cursor
  1437. /// pointing into the block.
  1438. llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
  1439. unsigned BlockID,
  1440. uint64_t *StartOfBlockOffset) {
  1441. if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
  1442. return Err;
  1443. if (StartOfBlockOffset)
  1444. *StartOfBlockOffset = Cursor.GetCurrentBitNo();
  1445. while (true) {
  1446. uint64_t Offset = Cursor.GetCurrentBitNo();
  1447. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  1448. if (!MaybeCode)
  1449. return MaybeCode.takeError();
  1450. unsigned Code = MaybeCode.get();
  1451. // We expect all abbrevs to be at the start of the block.
  1452. if (Code != llvm::bitc::DEFINE_ABBREV) {
  1453. if (llvm::Error Err = Cursor.JumpToBit(Offset))
  1454. return Err;
  1455. return llvm::Error::success();
  1456. }
  1457. if (llvm::Error Err = Cursor.ReadAbbrevRecord())
  1458. return Err;
  1459. }
  1460. }
  1461. Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
  1462. unsigned &Idx) {
  1463. Token Tok;
  1464. Tok.startToken();
  1465. Tok.setLocation(ReadSourceLocation(F, Record, Idx));
  1466. Tok.setKind((tok::TokenKind)Record[Idx++]);
  1467. Tok.setFlag((Token::TokenFlags)Record[Idx++]);
  1468. if (Tok.isAnnotation()) {
  1469. Tok.setAnnotationEndLoc(ReadSourceLocation(F, Record, Idx));
  1470. switch (Tok.getKind()) {
  1471. case tok::annot_pragma_loop_hint: {
  1472. auto *Info = new (PP.getPreprocessorAllocator()) PragmaLoopHintInfo;
  1473. Info->PragmaName = ReadToken(F, Record, Idx);
  1474. Info->Option = ReadToken(F, Record, Idx);
  1475. unsigned NumTokens = Record[Idx++];
  1476. SmallVector<Token, 4> Toks;
  1477. Toks.reserve(NumTokens);
  1478. for (unsigned I = 0; I < NumTokens; ++I)
  1479. Toks.push_back(ReadToken(F, Record, Idx));
  1480. Info->Toks = llvm::ArrayRef(Toks).copy(PP.getPreprocessorAllocator());
  1481. Tok.setAnnotationValue(static_cast<void *>(Info));
  1482. break;
  1483. }
  1484. // Some annotation tokens do not use the PtrData field.
  1485. case tok::annot_pragma_openmp:
  1486. case tok::annot_pragma_openmp_end:
  1487. case tok::annot_pragma_unused:
  1488. break;
  1489. default:
  1490. llvm_unreachable("missing deserialization code for annotation token");
  1491. }
  1492. } else {
  1493. Tok.setLength(Record[Idx++]);
  1494. if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
  1495. Tok.setIdentifierInfo(II);
  1496. }
  1497. return Tok;
  1498. }
  1499. MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
  1500. BitstreamCursor &Stream = F.MacroCursor;
  1501. // Keep track of where we are in the stream, then jump back there
  1502. // after reading this macro.
  1503. SavedStreamPosition SavedPosition(Stream);
  1504. if (llvm::Error Err = Stream.JumpToBit(Offset)) {
  1505. // FIXME this drops errors on the floor.
  1506. consumeError(std::move(Err));
  1507. return nullptr;
  1508. }
  1509. RecordData Record;
  1510. SmallVector<IdentifierInfo*, 16> MacroParams;
  1511. MacroInfo *Macro = nullptr;
  1512. llvm::MutableArrayRef<Token> MacroTokens;
  1513. while (true) {
  1514. // Advance to the next record, but if we get to the end of the block, don't
  1515. // pop it (removing all the abbreviations from the cursor) since we want to
  1516. // be able to reseek within the block and read entries.
  1517. unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
  1518. Expected<llvm::BitstreamEntry> MaybeEntry =
  1519. Stream.advanceSkippingSubblocks(Flags);
  1520. if (!MaybeEntry) {
  1521. Error(MaybeEntry.takeError());
  1522. return Macro;
  1523. }
  1524. llvm::BitstreamEntry Entry = MaybeEntry.get();
  1525. switch (Entry.Kind) {
  1526. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1527. case llvm::BitstreamEntry::Error:
  1528. Error("malformed block record in AST file");
  1529. return Macro;
  1530. case llvm::BitstreamEntry::EndBlock:
  1531. return Macro;
  1532. case llvm::BitstreamEntry::Record:
  1533. // The interesting case.
  1534. break;
  1535. }
  1536. // Read a record.
  1537. Record.clear();
  1538. PreprocessorRecordTypes RecType;
  1539. if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
  1540. RecType = (PreprocessorRecordTypes)MaybeRecType.get();
  1541. else {
  1542. Error(MaybeRecType.takeError());
  1543. return Macro;
  1544. }
  1545. switch (RecType) {
  1546. case PP_MODULE_MACRO:
  1547. case PP_MACRO_DIRECTIVE_HISTORY:
  1548. return Macro;
  1549. case PP_MACRO_OBJECT_LIKE:
  1550. case PP_MACRO_FUNCTION_LIKE: {
  1551. // If we already have a macro, that means that we've hit the end
  1552. // of the definition of the macro we were looking for. We're
  1553. // done.
  1554. if (Macro)
  1555. return Macro;
  1556. unsigned NextIndex = 1; // Skip identifier ID.
  1557. SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
  1558. MacroInfo *MI = PP.AllocateMacroInfo(Loc);
  1559. MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
  1560. MI->setIsUsed(Record[NextIndex++]);
  1561. MI->setUsedForHeaderGuard(Record[NextIndex++]);
  1562. MacroTokens = MI->allocateTokens(Record[NextIndex++],
  1563. PP.getPreprocessorAllocator());
  1564. if (RecType == PP_MACRO_FUNCTION_LIKE) {
  1565. // Decode function-like macro info.
  1566. bool isC99VarArgs = Record[NextIndex++];
  1567. bool isGNUVarArgs = Record[NextIndex++];
  1568. bool hasCommaPasting = Record[NextIndex++];
  1569. MacroParams.clear();
  1570. unsigned NumArgs = Record[NextIndex++];
  1571. for (unsigned i = 0; i != NumArgs; ++i)
  1572. MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
  1573. // Install function-like macro info.
  1574. MI->setIsFunctionLike();
  1575. if (isC99VarArgs) MI->setIsC99Varargs();
  1576. if (isGNUVarArgs) MI->setIsGNUVarargs();
  1577. if (hasCommaPasting) MI->setHasCommaPasting();
  1578. MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
  1579. }
  1580. // Remember that we saw this macro last so that we add the tokens that
  1581. // form its body to it.
  1582. Macro = MI;
  1583. if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
  1584. Record[NextIndex]) {
  1585. // We have a macro definition. Register the association
  1586. PreprocessedEntityID
  1587. GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
  1588. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  1589. PreprocessingRecord::PPEntityID PPID =
  1590. PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
  1591. MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
  1592. PPRec.getPreprocessedEntity(PPID));
  1593. if (PPDef)
  1594. PPRec.RegisterMacroDefinition(Macro, PPDef);
  1595. }
  1596. ++NumMacrosRead;
  1597. break;
  1598. }
  1599. case PP_TOKEN: {
  1600. // If we see a TOKEN before a PP_MACRO_*, then the file is
  1601. // erroneous, just pretend we didn't see this.
  1602. if (!Macro) break;
  1603. if (MacroTokens.empty()) {
  1604. Error("unexpected number of macro tokens for a macro in AST file");
  1605. return Macro;
  1606. }
  1607. unsigned Idx = 0;
  1608. MacroTokens[0] = ReadToken(F, Record, Idx);
  1609. MacroTokens = MacroTokens.drop_front();
  1610. break;
  1611. }
  1612. }
  1613. }
  1614. }
  1615. PreprocessedEntityID
  1616. ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
  1617. unsigned LocalID) const {
  1618. if (!M.ModuleOffsetMap.empty())
  1619. ReadModuleOffsetMap(M);
  1620. ContinuousRangeMap<uint32_t, int, 2>::const_iterator
  1621. I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
  1622. assert(I != M.PreprocessedEntityRemap.end()
  1623. && "Invalid index into preprocessed entity index remap");
  1624. return LocalID + I->second;
  1625. }
  1626. unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
  1627. return llvm::hash_combine(ikey.Size, ikey.ModTime);
  1628. }
  1629. HeaderFileInfoTrait::internal_key_type
  1630. HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
  1631. internal_key_type ikey = {FE->getSize(),
  1632. M.HasTimestamps ? FE->getModificationTime() : 0,
  1633. FE->getName(), /*Imported*/ false};
  1634. return ikey;
  1635. }
  1636. bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
  1637. if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
  1638. return false;
  1639. if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
  1640. return true;
  1641. // Determine whether the actual files are equivalent.
  1642. FileManager &FileMgr = Reader.getFileManager();
  1643. auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
  1644. if (!Key.Imported) {
  1645. if (auto File = FileMgr.getFile(Key.Filename))
  1646. return *File;
  1647. return nullptr;
  1648. }
  1649. std::string Resolved = std::string(Key.Filename);
  1650. Reader.ResolveImportedPath(M, Resolved);
  1651. if (auto File = FileMgr.getFile(Resolved))
  1652. return *File;
  1653. return nullptr;
  1654. };
  1655. const FileEntry *FEA = GetFile(a);
  1656. const FileEntry *FEB = GetFile(b);
  1657. return FEA && FEA == FEB;
  1658. }
  1659. std::pair<unsigned, unsigned>
  1660. HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
  1661. return readULEBKeyDataLength(d);
  1662. }
  1663. HeaderFileInfoTrait::internal_key_type
  1664. HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
  1665. using namespace llvm::support;
  1666. internal_key_type ikey;
  1667. ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
  1668. ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
  1669. ikey.Filename = (const char *)d;
  1670. ikey.Imported = true;
  1671. return ikey;
  1672. }
  1673. HeaderFileInfoTrait::data_type
  1674. HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
  1675. unsigned DataLen) {
  1676. using namespace llvm::support;
  1677. const unsigned char *End = d + DataLen;
  1678. HeaderFileInfo HFI;
  1679. unsigned Flags = *d++;
  1680. // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
  1681. HFI.isImport |= (Flags >> 5) & 0x01;
  1682. HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
  1683. HFI.DirInfo = (Flags >> 1) & 0x07;
  1684. HFI.IndexHeaderMapHeader = Flags & 0x01;
  1685. HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
  1686. M, endian::readNext<uint32_t, little, unaligned>(d));
  1687. if (unsigned FrameworkOffset =
  1688. endian::readNext<uint32_t, little, unaligned>(d)) {
  1689. // The framework offset is 1 greater than the actual offset,
  1690. // since 0 is used as an indicator for "no framework name".
  1691. StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
  1692. HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
  1693. }
  1694. assert((End - d) % 4 == 0 &&
  1695. "Wrong data length in HeaderFileInfo deserialization");
  1696. while (d != End) {
  1697. uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
  1698. auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 7);
  1699. LocalSMID >>= 3;
  1700. // This header is part of a module. Associate it with the module to enable
  1701. // implicit module import.
  1702. SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
  1703. Module *Mod = Reader.getSubmodule(GlobalSMID);
  1704. FileManager &FileMgr = Reader.getFileManager();
  1705. ModuleMap &ModMap =
  1706. Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1707. std::string Filename = std::string(key.Filename);
  1708. if (key.Imported)
  1709. Reader.ResolveImportedPath(M, Filename);
  1710. // FIXME: NameAsWritten
  1711. Module::Header H = {std::string(key.Filename), "",
  1712. FileMgr.getOptionalFileRef(Filename)};
  1713. ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
  1714. HFI.isModuleHeader |= ModuleMap::isModular(HeaderRole);
  1715. }
  1716. // This HeaderFileInfo was externally loaded.
  1717. HFI.External = true;
  1718. HFI.IsValid = true;
  1719. return HFI;
  1720. }
  1721. void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
  1722. uint32_t MacroDirectivesOffset) {
  1723. assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
  1724. PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
  1725. }
  1726. void ASTReader::ReadDefinedMacros() {
  1727. // Note that we are loading defined macros.
  1728. Deserializing Macros(this);
  1729. for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
  1730. BitstreamCursor &MacroCursor = I.MacroCursor;
  1731. // If there was no preprocessor block, skip this file.
  1732. if (MacroCursor.getBitcodeBytes().empty())
  1733. continue;
  1734. BitstreamCursor Cursor = MacroCursor;
  1735. if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
  1736. Error(std::move(Err));
  1737. return;
  1738. }
  1739. RecordData Record;
  1740. while (true) {
  1741. Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
  1742. if (!MaybeE) {
  1743. Error(MaybeE.takeError());
  1744. return;
  1745. }
  1746. llvm::BitstreamEntry E = MaybeE.get();
  1747. switch (E.Kind) {
  1748. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1749. case llvm::BitstreamEntry::Error:
  1750. Error("malformed block record in AST file");
  1751. return;
  1752. case llvm::BitstreamEntry::EndBlock:
  1753. goto NextCursor;
  1754. case llvm::BitstreamEntry::Record: {
  1755. Record.clear();
  1756. Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
  1757. if (!MaybeRecord) {
  1758. Error(MaybeRecord.takeError());
  1759. return;
  1760. }
  1761. switch (MaybeRecord.get()) {
  1762. default: // Default behavior: ignore.
  1763. break;
  1764. case PP_MACRO_OBJECT_LIKE:
  1765. case PP_MACRO_FUNCTION_LIKE: {
  1766. IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
  1767. if (II->isOutOfDate())
  1768. updateOutOfDateIdentifier(*II);
  1769. break;
  1770. }
  1771. case PP_TOKEN:
  1772. // Ignore tokens.
  1773. break;
  1774. }
  1775. break;
  1776. }
  1777. }
  1778. }
  1779. NextCursor: ;
  1780. }
  1781. }
  1782. namespace {
  1783. /// Visitor class used to look up identifirs in an AST file.
  1784. class IdentifierLookupVisitor {
  1785. StringRef Name;
  1786. unsigned NameHash;
  1787. unsigned PriorGeneration;
  1788. unsigned &NumIdentifierLookups;
  1789. unsigned &NumIdentifierLookupHits;
  1790. IdentifierInfo *Found = nullptr;
  1791. public:
  1792. IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
  1793. unsigned &NumIdentifierLookups,
  1794. unsigned &NumIdentifierLookupHits)
  1795. : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
  1796. PriorGeneration(PriorGeneration),
  1797. NumIdentifierLookups(NumIdentifierLookups),
  1798. NumIdentifierLookupHits(NumIdentifierLookupHits) {}
  1799. bool operator()(ModuleFile &M) {
  1800. // If we've already searched this module file, skip it now.
  1801. if (M.Generation <= PriorGeneration)
  1802. return true;
  1803. ASTIdentifierLookupTable *IdTable
  1804. = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
  1805. if (!IdTable)
  1806. return false;
  1807. ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
  1808. Found);
  1809. ++NumIdentifierLookups;
  1810. ASTIdentifierLookupTable::iterator Pos =
  1811. IdTable->find_hashed(Name, NameHash, &Trait);
  1812. if (Pos == IdTable->end())
  1813. return false;
  1814. // Dereferencing the iterator has the effect of building the
  1815. // IdentifierInfo node and populating it with the various
  1816. // declarations it needs.
  1817. ++NumIdentifierLookupHits;
  1818. Found = *Pos;
  1819. return true;
  1820. }
  1821. // Retrieve the identifier info found within the module
  1822. // files.
  1823. IdentifierInfo *getIdentifierInfo() const { return Found; }
  1824. };
  1825. } // namespace
  1826. void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
  1827. // Note that we are loading an identifier.
  1828. Deserializing AnIdentifier(this);
  1829. unsigned PriorGeneration = 0;
  1830. if (getContext().getLangOpts().Modules)
  1831. PriorGeneration = IdentifierGeneration[&II];
  1832. // If there is a global index, look there first to determine which modules
  1833. // provably do not have any results for this identifier.
  1834. GlobalModuleIndex::HitSet Hits;
  1835. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  1836. if (!loadGlobalIndex()) {
  1837. if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
  1838. HitsPtr = &Hits;
  1839. }
  1840. }
  1841. IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
  1842. NumIdentifierLookups,
  1843. NumIdentifierLookupHits);
  1844. ModuleMgr.visit(Visitor, HitsPtr);
  1845. markIdentifierUpToDate(&II);
  1846. }
  1847. void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
  1848. if (!II)
  1849. return;
  1850. II->setOutOfDate(false);
  1851. // Update the generation for this identifier.
  1852. if (getContext().getLangOpts().Modules)
  1853. IdentifierGeneration[II] = getGeneration();
  1854. }
  1855. void ASTReader::resolvePendingMacro(IdentifierInfo *II,
  1856. const PendingMacroInfo &PMInfo) {
  1857. ModuleFile &M = *PMInfo.M;
  1858. BitstreamCursor &Cursor = M.MacroCursor;
  1859. SavedStreamPosition SavedPosition(Cursor);
  1860. if (llvm::Error Err =
  1861. Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
  1862. Error(std::move(Err));
  1863. return;
  1864. }
  1865. struct ModuleMacroRecord {
  1866. SubmoduleID SubModID;
  1867. MacroInfo *MI;
  1868. SmallVector<SubmoduleID, 8> Overrides;
  1869. };
  1870. llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
  1871. // We expect to see a sequence of PP_MODULE_MACRO records listing exported
  1872. // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
  1873. // macro histroy.
  1874. RecordData Record;
  1875. while (true) {
  1876. Expected<llvm::BitstreamEntry> MaybeEntry =
  1877. Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  1878. if (!MaybeEntry) {
  1879. Error(MaybeEntry.takeError());
  1880. return;
  1881. }
  1882. llvm::BitstreamEntry Entry = MaybeEntry.get();
  1883. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1884. Error("malformed block record in AST file");
  1885. return;
  1886. }
  1887. Record.clear();
  1888. Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
  1889. if (!MaybePP) {
  1890. Error(MaybePP.takeError());
  1891. return;
  1892. }
  1893. switch ((PreprocessorRecordTypes)MaybePP.get()) {
  1894. case PP_MACRO_DIRECTIVE_HISTORY:
  1895. break;
  1896. case PP_MODULE_MACRO: {
  1897. ModuleMacros.push_back(ModuleMacroRecord());
  1898. auto &Info = ModuleMacros.back();
  1899. Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
  1900. Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
  1901. for (int I = 2, N = Record.size(); I != N; ++I)
  1902. Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
  1903. continue;
  1904. }
  1905. default:
  1906. Error("malformed block record in AST file");
  1907. return;
  1908. }
  1909. // We found the macro directive history; that's the last record
  1910. // for this macro.
  1911. break;
  1912. }
  1913. // Module macros are listed in reverse dependency order.
  1914. {
  1915. std::reverse(ModuleMacros.begin(), ModuleMacros.end());
  1916. llvm::SmallVector<ModuleMacro*, 8> Overrides;
  1917. for (auto &MMR : ModuleMacros) {
  1918. Overrides.clear();
  1919. for (unsigned ModID : MMR.Overrides) {
  1920. Module *Mod = getSubmodule(ModID);
  1921. auto *Macro = PP.getModuleMacro(Mod, II);
  1922. assert(Macro && "missing definition for overridden macro");
  1923. Overrides.push_back(Macro);
  1924. }
  1925. bool Inserted = false;
  1926. Module *Owner = getSubmodule(MMR.SubModID);
  1927. PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
  1928. }
  1929. }
  1930. // Don't read the directive history for a module; we don't have anywhere
  1931. // to put it.
  1932. if (M.isModule())
  1933. return;
  1934. // Deserialize the macro directives history in reverse source-order.
  1935. MacroDirective *Latest = nullptr, *Earliest = nullptr;
  1936. unsigned Idx = 0, N = Record.size();
  1937. while (Idx < N) {
  1938. MacroDirective *MD = nullptr;
  1939. SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
  1940. MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
  1941. switch (K) {
  1942. case MacroDirective::MD_Define: {
  1943. MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
  1944. MD = PP.AllocateDefMacroDirective(MI, Loc);
  1945. break;
  1946. }
  1947. case MacroDirective::MD_Undefine:
  1948. MD = PP.AllocateUndefMacroDirective(Loc);
  1949. break;
  1950. case MacroDirective::MD_Visibility:
  1951. bool isPublic = Record[Idx++];
  1952. MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
  1953. break;
  1954. }
  1955. if (!Latest)
  1956. Latest = MD;
  1957. if (Earliest)
  1958. Earliest->setPrevious(MD);
  1959. Earliest = MD;
  1960. }
  1961. if (Latest)
  1962. PP.setLoadedMacroDirective(II, Earliest, Latest);
  1963. }
  1964. bool ASTReader::shouldDisableValidationForFile(
  1965. const serialization::ModuleFile &M) const {
  1966. if (DisableValidationKind == DisableValidationForModuleKind::None)
  1967. return false;
  1968. // If a PCH is loaded and validation is disabled for PCH then disable
  1969. // validation for the PCH and the modules it loads.
  1970. ModuleKind K = CurrentDeserializingModuleKind.value_or(M.Kind);
  1971. switch (K) {
  1972. case MK_MainFile:
  1973. case MK_Preamble:
  1974. case MK_PCH:
  1975. return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
  1976. case MK_ImplicitModule:
  1977. case MK_ExplicitModule:
  1978. case MK_PrebuiltModule:
  1979. return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
  1980. }
  1981. return false;
  1982. }
  1983. InputFileInfo ASTReader::getInputFileInfo(ModuleFile &F, unsigned ID) {
  1984. // If this ID is bogus, just return an empty input file.
  1985. if (ID == 0 || ID > F.InputFileInfosLoaded.size())
  1986. return InputFileInfo();
  1987. // If we've already loaded this input file, return it.
  1988. if (!F.InputFileInfosLoaded[ID - 1].Filename.empty())
  1989. return F.InputFileInfosLoaded[ID - 1];
  1990. // Go find this input file.
  1991. BitstreamCursor &Cursor = F.InputFilesCursor;
  1992. SavedStreamPosition SavedPosition(Cursor);
  1993. if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
  1994. // FIXME this drops errors on the floor.
  1995. consumeError(std::move(Err));
  1996. }
  1997. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  1998. if (!MaybeCode) {
  1999. // FIXME this drops errors on the floor.
  2000. consumeError(MaybeCode.takeError());
  2001. }
  2002. unsigned Code = MaybeCode.get();
  2003. RecordData Record;
  2004. StringRef Blob;
  2005. if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
  2006. assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
  2007. "invalid record type for input file");
  2008. else {
  2009. // FIXME this drops errors on the floor.
  2010. consumeError(Maybe.takeError());
  2011. }
  2012. assert(Record[0] == ID && "Bogus stored ID or offset");
  2013. InputFileInfo R;
  2014. R.StoredSize = static_cast<off_t>(Record[1]);
  2015. R.StoredTime = static_cast<time_t>(Record[2]);
  2016. R.Overridden = static_cast<bool>(Record[3]);
  2017. R.Transient = static_cast<bool>(Record[4]);
  2018. R.TopLevelModuleMap = static_cast<bool>(Record[5]);
  2019. R.Filename = std::string(Blob);
  2020. ResolveImportedPath(F, R.Filename);
  2021. Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
  2022. if (!MaybeEntry) // FIXME this drops errors on the floor.
  2023. consumeError(MaybeEntry.takeError());
  2024. llvm::BitstreamEntry Entry = MaybeEntry.get();
  2025. assert(Entry.Kind == llvm::BitstreamEntry::Record &&
  2026. "expected record type for input file hash");
  2027. Record.clear();
  2028. if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
  2029. assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
  2030. "invalid record type for input file hash");
  2031. else {
  2032. // FIXME this drops errors on the floor.
  2033. consumeError(Maybe.takeError());
  2034. }
  2035. R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
  2036. static_cast<uint64_t>(Record[0]);
  2037. // Note that we've loaded this input file info.
  2038. F.InputFileInfosLoaded[ID - 1] = R;
  2039. return R;
  2040. }
  2041. static unsigned moduleKindForDiagnostic(ModuleKind Kind);
  2042. InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
  2043. // If this ID is bogus, just return an empty input file.
  2044. if (ID == 0 || ID > F.InputFilesLoaded.size())
  2045. return InputFile();
  2046. // If we've already loaded this input file, return it.
  2047. if (F.InputFilesLoaded[ID-1].getFile())
  2048. return F.InputFilesLoaded[ID-1];
  2049. if (F.InputFilesLoaded[ID-1].isNotFound())
  2050. return InputFile();
  2051. // Go find this input file.
  2052. BitstreamCursor &Cursor = F.InputFilesCursor;
  2053. SavedStreamPosition SavedPosition(Cursor);
  2054. if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
  2055. // FIXME this drops errors on the floor.
  2056. consumeError(std::move(Err));
  2057. }
  2058. InputFileInfo FI = getInputFileInfo(F, ID);
  2059. off_t StoredSize = FI.StoredSize;
  2060. time_t StoredTime = FI.StoredTime;
  2061. bool Overridden = FI.Overridden;
  2062. bool Transient = FI.Transient;
  2063. StringRef Filename = FI.Filename;
  2064. uint64_t StoredContentHash = FI.ContentHash;
  2065. OptionalFileEntryRefDegradesToFileEntryPtr File = OptionalFileEntryRef(
  2066. expectedToOptional(FileMgr.getFileRef(Filename, /*OpenFile=*/false)));
  2067. // For an overridden file, create a virtual file with the stored
  2068. // size/timestamp.
  2069. if ((Overridden || Transient) && !File)
  2070. File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
  2071. if (!File) {
  2072. if (Complain) {
  2073. std::string ErrorStr = "could not find file '";
  2074. ErrorStr += Filename;
  2075. ErrorStr += "' referenced by AST file '";
  2076. ErrorStr += F.FileName;
  2077. ErrorStr += "'";
  2078. Error(ErrorStr);
  2079. }
  2080. // Record that we didn't find the file.
  2081. F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
  2082. return InputFile();
  2083. }
  2084. // Check if there was a request to override the contents of the file
  2085. // that was part of the precompiled header. Overriding such a file
  2086. // can lead to problems when lexing using the source locations from the
  2087. // PCH.
  2088. SourceManager &SM = getSourceManager();
  2089. // FIXME: Reject if the overrides are different.
  2090. if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
  2091. if (Complain)
  2092. Error(diag::err_fe_pch_file_overridden, Filename);
  2093. // After emitting the diagnostic, bypass the overriding file to recover
  2094. // (this creates a separate FileEntry).
  2095. File = SM.bypassFileContentsOverride(*File);
  2096. if (!File) {
  2097. F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
  2098. return InputFile();
  2099. }
  2100. }
  2101. struct Change {
  2102. enum ModificationKind {
  2103. Size,
  2104. ModTime,
  2105. Content,
  2106. None,
  2107. } Kind;
  2108. std::optional<int64_t> Old = std::nullopt;
  2109. std::optional<int64_t> New = std::nullopt;
  2110. };
  2111. auto HasInputFileChanged = [&]() {
  2112. if (StoredSize != File->getSize())
  2113. return Change{Change::Size, StoredSize, File->getSize()};
  2114. if (!shouldDisableValidationForFile(F) && StoredTime &&
  2115. StoredTime != File->getModificationTime()) {
  2116. Change MTimeChange = {Change::ModTime, StoredTime,
  2117. File->getModificationTime()};
  2118. // In case the modification time changes but not the content,
  2119. // accept the cached file as legit.
  2120. if (ValidateASTInputFilesContent &&
  2121. StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
  2122. auto MemBuffOrError = FileMgr.getBufferForFile(File);
  2123. if (!MemBuffOrError) {
  2124. if (!Complain)
  2125. return MTimeChange;
  2126. std::string ErrorStr = "could not get buffer for file '";
  2127. ErrorStr += File->getName();
  2128. ErrorStr += "'";
  2129. Error(ErrorStr);
  2130. return MTimeChange;
  2131. }
  2132. // FIXME: hash_value is not guaranteed to be stable!
  2133. auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
  2134. if (StoredContentHash == static_cast<uint64_t>(ContentHash))
  2135. return Change{Change::None};
  2136. return Change{Change::Content};
  2137. }
  2138. return MTimeChange;
  2139. }
  2140. return Change{Change::None};
  2141. };
  2142. bool IsOutOfDate = false;
  2143. auto FileChange = HasInputFileChanged();
  2144. // For an overridden file, there is nothing to validate.
  2145. if (!Overridden && FileChange.Kind != Change::None) {
  2146. if (Complain && !Diags.isDiagnosticInFlight()) {
  2147. // Build a list of the PCH imports that got us here (in reverse).
  2148. SmallVector<ModuleFile *, 4> ImportStack(1, &F);
  2149. while (!ImportStack.back()->ImportedBy.empty())
  2150. ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
  2151. // The top-level PCH is stale.
  2152. StringRef TopLevelPCHName(ImportStack.back()->FileName);
  2153. Diag(diag::err_fe_ast_file_modified)
  2154. << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
  2155. << TopLevelPCHName << FileChange.Kind
  2156. << (FileChange.Old && FileChange.New)
  2157. << llvm::itostr(FileChange.Old.value_or(0))
  2158. << llvm::itostr(FileChange.New.value_or(0));
  2159. // Print the import stack.
  2160. if (ImportStack.size() > 1) {
  2161. Diag(diag::note_pch_required_by)
  2162. << Filename << ImportStack[0]->FileName;
  2163. for (unsigned I = 1; I < ImportStack.size(); ++I)
  2164. Diag(diag::note_pch_required_by)
  2165. << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
  2166. }
  2167. Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
  2168. }
  2169. IsOutOfDate = true;
  2170. }
  2171. // FIXME: If the file is overridden and we've already opened it,
  2172. // issue an error (or split it into a separate FileEntry).
  2173. InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
  2174. // Note that we've loaded this input file.
  2175. F.InputFilesLoaded[ID-1] = IF;
  2176. return IF;
  2177. }
  2178. /// If we are loading a relocatable PCH or module file, and the filename
  2179. /// is not an absolute path, add the system or module root to the beginning of
  2180. /// the file name.
  2181. void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
  2182. // Resolve relative to the base directory, if we have one.
  2183. if (!M.BaseDirectory.empty())
  2184. return ResolveImportedPath(Filename, M.BaseDirectory);
  2185. }
  2186. void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
  2187. if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
  2188. return;
  2189. SmallString<128> Buffer;
  2190. llvm::sys::path::append(Buffer, Prefix, Filename);
  2191. Filename.assign(Buffer.begin(), Buffer.end());
  2192. }
  2193. static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
  2194. switch (ARR) {
  2195. case ASTReader::Failure: return true;
  2196. case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
  2197. case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
  2198. case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
  2199. case ASTReader::ConfigurationMismatch:
  2200. return !(Caps & ASTReader::ARR_ConfigurationMismatch);
  2201. case ASTReader::HadErrors: return true;
  2202. case ASTReader::Success: return false;
  2203. }
  2204. llvm_unreachable("unknown ASTReadResult");
  2205. }
  2206. ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
  2207. BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
  2208. bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
  2209. std::string &SuggestedPredefines) {
  2210. if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
  2211. // FIXME this drops errors on the floor.
  2212. consumeError(std::move(Err));
  2213. return Failure;
  2214. }
  2215. // Read all of the records in the options block.
  2216. RecordData Record;
  2217. ASTReadResult Result = Success;
  2218. while (true) {
  2219. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  2220. if (!MaybeEntry) {
  2221. // FIXME this drops errors on the floor.
  2222. consumeError(MaybeEntry.takeError());
  2223. return Failure;
  2224. }
  2225. llvm::BitstreamEntry Entry = MaybeEntry.get();
  2226. switch (Entry.Kind) {
  2227. case llvm::BitstreamEntry::Error:
  2228. case llvm::BitstreamEntry::SubBlock:
  2229. return Failure;
  2230. case llvm::BitstreamEntry::EndBlock:
  2231. return Result;
  2232. case llvm::BitstreamEntry::Record:
  2233. // The interesting case.
  2234. break;
  2235. }
  2236. // Read and process a record.
  2237. Record.clear();
  2238. Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
  2239. if (!MaybeRecordType) {
  2240. // FIXME this drops errors on the floor.
  2241. consumeError(MaybeRecordType.takeError());
  2242. return Failure;
  2243. }
  2244. switch ((OptionsRecordTypes)MaybeRecordType.get()) {
  2245. case LANGUAGE_OPTIONS: {
  2246. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2247. if (ParseLanguageOptions(Record, Complain, Listener,
  2248. AllowCompatibleConfigurationMismatch))
  2249. Result = ConfigurationMismatch;
  2250. break;
  2251. }
  2252. case TARGET_OPTIONS: {
  2253. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2254. if (ParseTargetOptions(Record, Complain, Listener,
  2255. AllowCompatibleConfigurationMismatch))
  2256. Result = ConfigurationMismatch;
  2257. break;
  2258. }
  2259. case FILE_SYSTEM_OPTIONS: {
  2260. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2261. if (!AllowCompatibleConfigurationMismatch &&
  2262. ParseFileSystemOptions(Record, Complain, Listener))
  2263. Result = ConfigurationMismatch;
  2264. break;
  2265. }
  2266. case HEADER_SEARCH_OPTIONS: {
  2267. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2268. if (!AllowCompatibleConfigurationMismatch &&
  2269. ParseHeaderSearchOptions(Record, Complain, Listener))
  2270. Result = ConfigurationMismatch;
  2271. break;
  2272. }
  2273. case PREPROCESSOR_OPTIONS:
  2274. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2275. if (!AllowCompatibleConfigurationMismatch &&
  2276. ParsePreprocessorOptions(Record, Complain, Listener,
  2277. SuggestedPredefines))
  2278. Result = ConfigurationMismatch;
  2279. break;
  2280. }
  2281. }
  2282. }
  2283. ASTReader::ASTReadResult
  2284. ASTReader::ReadControlBlock(ModuleFile &F,
  2285. SmallVectorImpl<ImportedModule> &Loaded,
  2286. const ModuleFile *ImportedBy,
  2287. unsigned ClientLoadCapabilities) {
  2288. BitstreamCursor &Stream = F.Stream;
  2289. if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
  2290. Error(std::move(Err));
  2291. return Failure;
  2292. }
  2293. // Lambda to read the unhashed control block the first time it's called.
  2294. //
  2295. // For PCM files, the unhashed control block cannot be read until after the
  2296. // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
  2297. // need to look ahead before reading the IMPORTS record. For consistency,
  2298. // this block is always read somehow (see BitstreamEntry::EndBlock).
  2299. bool HasReadUnhashedControlBlock = false;
  2300. auto readUnhashedControlBlockOnce = [&]() {
  2301. if (!HasReadUnhashedControlBlock) {
  2302. HasReadUnhashedControlBlock = true;
  2303. if (ASTReadResult Result =
  2304. readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
  2305. return Result;
  2306. }
  2307. return Success;
  2308. };
  2309. bool DisableValidation = shouldDisableValidationForFile(F);
  2310. // Read all of the records and blocks in the control block.
  2311. RecordData Record;
  2312. unsigned NumInputs = 0;
  2313. unsigned NumUserInputs = 0;
  2314. StringRef BaseDirectoryAsWritten;
  2315. while (true) {
  2316. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  2317. if (!MaybeEntry) {
  2318. Error(MaybeEntry.takeError());
  2319. return Failure;
  2320. }
  2321. llvm::BitstreamEntry Entry = MaybeEntry.get();
  2322. switch (Entry.Kind) {
  2323. case llvm::BitstreamEntry::Error:
  2324. Error("malformed block record in AST file");
  2325. return Failure;
  2326. case llvm::BitstreamEntry::EndBlock: {
  2327. // Validate the module before returning. This call catches an AST with
  2328. // no module name and no imports.
  2329. if (ASTReadResult Result = readUnhashedControlBlockOnce())
  2330. return Result;
  2331. // Validate input files.
  2332. const HeaderSearchOptions &HSOpts =
  2333. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  2334. // All user input files reside at the index range [0, NumUserInputs), and
  2335. // system input files reside at [NumUserInputs, NumInputs). For explicitly
  2336. // loaded module files, ignore missing inputs.
  2337. if (!DisableValidation && F.Kind != MK_ExplicitModule &&
  2338. F.Kind != MK_PrebuiltModule) {
  2339. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
  2340. // If we are reading a module, we will create a verification timestamp,
  2341. // so we verify all input files. Otherwise, verify only user input
  2342. // files.
  2343. unsigned N = ValidateSystemInputs ? NumInputs : NumUserInputs;
  2344. if (HSOpts.ModulesValidateOncePerBuildSession &&
  2345. F.InputFilesValidationTimestamp > HSOpts.BuildSessionTimestamp &&
  2346. F.Kind == MK_ImplicitModule)
  2347. N = NumUserInputs;
  2348. for (unsigned I = 0; I < N; ++I) {
  2349. InputFile IF = getInputFile(F, I+1, Complain);
  2350. if (!IF.getFile() || IF.isOutOfDate())
  2351. return OutOfDate;
  2352. }
  2353. }
  2354. if (Listener)
  2355. Listener->visitModuleFile(F.FileName, F.Kind);
  2356. if (Listener && Listener->needsInputFileVisitation()) {
  2357. unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
  2358. : NumUserInputs;
  2359. for (unsigned I = 0; I < N; ++I) {
  2360. bool IsSystem = I >= NumUserInputs;
  2361. InputFileInfo FI = getInputFileInfo(F, I + 1);
  2362. Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
  2363. F.Kind == MK_ExplicitModule ||
  2364. F.Kind == MK_PrebuiltModule);
  2365. }
  2366. }
  2367. return Success;
  2368. }
  2369. case llvm::BitstreamEntry::SubBlock:
  2370. switch (Entry.ID) {
  2371. case INPUT_FILES_BLOCK_ID:
  2372. F.InputFilesCursor = Stream;
  2373. if (llvm::Error Err = Stream.SkipBlock()) {
  2374. Error(std::move(Err));
  2375. return Failure;
  2376. }
  2377. if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
  2378. Error("malformed block record in AST file");
  2379. return Failure;
  2380. }
  2381. continue;
  2382. case OPTIONS_BLOCK_ID:
  2383. // If we're reading the first module for this group, check its options
  2384. // are compatible with ours. For modules it imports, no further checking
  2385. // is required, because we checked them when we built it.
  2386. if (Listener && !ImportedBy) {
  2387. // Should we allow the configuration of the module file to differ from
  2388. // the configuration of the current translation unit in a compatible
  2389. // way?
  2390. //
  2391. // FIXME: Allow this for files explicitly specified with -include-pch.
  2392. bool AllowCompatibleConfigurationMismatch =
  2393. F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
  2394. ASTReadResult Result =
  2395. ReadOptionsBlock(Stream, ClientLoadCapabilities,
  2396. AllowCompatibleConfigurationMismatch, *Listener,
  2397. SuggestedPredefines);
  2398. if (Result == Failure) {
  2399. Error("malformed block record in AST file");
  2400. return Result;
  2401. }
  2402. if (DisableValidation ||
  2403. (AllowConfigurationMismatch && Result == ConfigurationMismatch))
  2404. Result = Success;
  2405. // If we can't load the module, exit early since we likely
  2406. // will rebuild the module anyway. The stream may be in the
  2407. // middle of a block.
  2408. if (Result != Success)
  2409. return Result;
  2410. } else if (llvm::Error Err = Stream.SkipBlock()) {
  2411. Error(std::move(Err));
  2412. return Failure;
  2413. }
  2414. continue;
  2415. default:
  2416. if (llvm::Error Err = Stream.SkipBlock()) {
  2417. Error(std::move(Err));
  2418. return Failure;
  2419. }
  2420. continue;
  2421. }
  2422. case llvm::BitstreamEntry::Record:
  2423. // The interesting case.
  2424. break;
  2425. }
  2426. // Read and process a record.
  2427. Record.clear();
  2428. StringRef Blob;
  2429. Expected<unsigned> MaybeRecordType =
  2430. Stream.readRecord(Entry.ID, Record, &Blob);
  2431. if (!MaybeRecordType) {
  2432. Error(MaybeRecordType.takeError());
  2433. return Failure;
  2434. }
  2435. switch ((ControlRecordTypes)MaybeRecordType.get()) {
  2436. case METADATA: {
  2437. if (Record[0] != VERSION_MAJOR && !DisableValidation) {
  2438. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  2439. Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
  2440. : diag::err_pch_version_too_new);
  2441. return VersionMismatch;
  2442. }
  2443. bool hasErrors = Record[6];
  2444. if (hasErrors && !DisableValidation) {
  2445. // If requested by the caller and the module hasn't already been read
  2446. // or compiled, mark modules on error as out-of-date.
  2447. if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
  2448. canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  2449. return OutOfDate;
  2450. if (!AllowASTWithCompilerErrors) {
  2451. Diag(diag::err_pch_with_compiler_errors);
  2452. return HadErrors;
  2453. }
  2454. }
  2455. if (hasErrors) {
  2456. Diags.ErrorOccurred = true;
  2457. Diags.UncompilableErrorOccurred = true;
  2458. Diags.UnrecoverableErrorOccurred = true;
  2459. }
  2460. F.RelocatablePCH = Record[4];
  2461. // Relative paths in a relocatable PCH are relative to our sysroot.
  2462. if (F.RelocatablePCH)
  2463. F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
  2464. F.HasTimestamps = Record[5];
  2465. const std::string &CurBranch = getClangFullRepositoryVersion();
  2466. StringRef ASTBranch = Blob;
  2467. if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
  2468. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  2469. Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
  2470. return VersionMismatch;
  2471. }
  2472. break;
  2473. }
  2474. case IMPORTS: {
  2475. // Validate the AST before processing any imports (otherwise, untangling
  2476. // them can be error-prone and expensive). A module will have a name and
  2477. // will already have been validated, but this catches the PCH case.
  2478. if (ASTReadResult Result = readUnhashedControlBlockOnce())
  2479. return Result;
  2480. // Load each of the imported PCH files.
  2481. unsigned Idx = 0, N = Record.size();
  2482. while (Idx < N) {
  2483. // Read information about the AST file.
  2484. ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
  2485. // The import location will be the local one for now; we will adjust
  2486. // all import locations of module imports after the global source
  2487. // location info are setup, in ReadAST.
  2488. SourceLocation ImportLoc =
  2489. ReadUntranslatedSourceLocation(Record[Idx++]);
  2490. off_t StoredSize = (off_t)Record[Idx++];
  2491. time_t StoredModTime = (time_t)Record[Idx++];
  2492. auto FirstSignatureByte = Record.begin() + Idx;
  2493. ASTFileSignature StoredSignature = ASTFileSignature::create(
  2494. FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
  2495. Idx += ASTFileSignature::size;
  2496. std::string ImportedName = ReadString(Record, Idx);
  2497. std::string ImportedFile;
  2498. // For prebuilt and explicit modules first consult the file map for
  2499. // an override. Note that here we don't search prebuilt module
  2500. // directories, only the explicit name to file mappings. Also, we will
  2501. // still verify the size/signature making sure it is essentially the
  2502. // same file but perhaps in a different location.
  2503. if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
  2504. ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
  2505. ImportedName, /*FileMapOnly*/ true);
  2506. if (ImportedFile.empty())
  2507. // Use BaseDirectoryAsWritten to ensure we use the same path in the
  2508. // ModuleCache as when writing.
  2509. ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
  2510. else
  2511. SkipPath(Record, Idx);
  2512. // If our client can't cope with us being out of date, we can't cope with
  2513. // our dependency being missing.
  2514. unsigned Capabilities = ClientLoadCapabilities;
  2515. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2516. Capabilities &= ~ARR_Missing;
  2517. // Load the AST file.
  2518. auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
  2519. Loaded, StoredSize, StoredModTime,
  2520. StoredSignature, Capabilities);
  2521. // If we diagnosed a problem, produce a backtrace.
  2522. bool recompilingFinalized =
  2523. Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
  2524. getModuleManager().getModuleCache().isPCMFinal(F.FileName);
  2525. if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
  2526. Diag(diag::note_module_file_imported_by)
  2527. << F.FileName << !F.ModuleName.empty() << F.ModuleName;
  2528. if (recompilingFinalized)
  2529. Diag(diag::note_module_file_conflict);
  2530. switch (Result) {
  2531. case Failure: return Failure;
  2532. // If we have to ignore the dependency, we'll have to ignore this too.
  2533. case Missing:
  2534. case OutOfDate: return OutOfDate;
  2535. case VersionMismatch: return VersionMismatch;
  2536. case ConfigurationMismatch: return ConfigurationMismatch;
  2537. case HadErrors: return HadErrors;
  2538. case Success: break;
  2539. }
  2540. }
  2541. break;
  2542. }
  2543. case ORIGINAL_FILE:
  2544. F.OriginalSourceFileID = FileID::get(Record[0]);
  2545. F.ActualOriginalSourceFileName = std::string(Blob);
  2546. F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
  2547. ResolveImportedPath(F, F.OriginalSourceFileName);
  2548. break;
  2549. case ORIGINAL_FILE_ID:
  2550. F.OriginalSourceFileID = FileID::get(Record[0]);
  2551. break;
  2552. case MODULE_NAME:
  2553. F.ModuleName = std::string(Blob);
  2554. Diag(diag::remark_module_import)
  2555. << F.ModuleName << F.FileName << (ImportedBy ? true : false)
  2556. << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
  2557. if (Listener)
  2558. Listener->ReadModuleName(F.ModuleName);
  2559. // Validate the AST as soon as we have a name so we can exit early on
  2560. // failure.
  2561. if (ASTReadResult Result = readUnhashedControlBlockOnce())
  2562. return Result;
  2563. break;
  2564. case MODULE_DIRECTORY: {
  2565. // Save the BaseDirectory as written in the PCM for computing the module
  2566. // filename for the ModuleCache.
  2567. BaseDirectoryAsWritten = Blob;
  2568. assert(!F.ModuleName.empty() &&
  2569. "MODULE_DIRECTORY found before MODULE_NAME");
  2570. // If we've already loaded a module map file covering this module, we may
  2571. // have a better path for it (relative to the current build).
  2572. Module *M = PP.getHeaderSearchInfo().lookupModule(
  2573. F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
  2574. /*AllowExtraModuleMapSearch*/ true);
  2575. if (M && M->Directory) {
  2576. // If we're implicitly loading a module, the base directory can't
  2577. // change between the build and use.
  2578. // Don't emit module relocation error if we have -fno-validate-pch
  2579. if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
  2580. DisableValidationForModuleKind::Module) &&
  2581. F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
  2582. auto BuildDir = PP.getFileManager().getDirectory(Blob);
  2583. if (!BuildDir || *BuildDir != M->Directory) {
  2584. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  2585. Diag(diag::err_imported_module_relocated)
  2586. << F.ModuleName << Blob << M->Directory->getName();
  2587. return OutOfDate;
  2588. }
  2589. }
  2590. F.BaseDirectory = std::string(M->Directory->getName());
  2591. } else {
  2592. F.BaseDirectory = std::string(Blob);
  2593. }
  2594. break;
  2595. }
  2596. case MODULE_MAP_FILE:
  2597. if (ASTReadResult Result =
  2598. ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
  2599. return Result;
  2600. break;
  2601. case INPUT_FILE_OFFSETS:
  2602. NumInputs = Record[0];
  2603. NumUserInputs = Record[1];
  2604. F.InputFileOffsets =
  2605. (const llvm::support::unaligned_uint64_t *)Blob.data();
  2606. F.InputFilesLoaded.resize(NumInputs);
  2607. F.InputFileInfosLoaded.resize(NumInputs);
  2608. F.NumUserInputFiles = NumUserInputs;
  2609. break;
  2610. }
  2611. }
  2612. }
  2613. void ASTReader::readIncludedFiles(ModuleFile &F, StringRef Blob,
  2614. Preprocessor &PP) {
  2615. using namespace llvm::support;
  2616. const unsigned char *D = (const unsigned char *)Blob.data();
  2617. unsigned FileCount = endian::readNext<uint32_t, little, unaligned>(D);
  2618. for (unsigned I = 0; I < FileCount; ++I) {
  2619. size_t ID = endian::readNext<uint32_t, little, unaligned>(D);
  2620. InputFileInfo IFI = getInputFileInfo(F, ID);
  2621. if (llvm::ErrorOr<const FileEntry *> File =
  2622. PP.getFileManager().getFile(IFI.Filename))
  2623. PP.getIncludedFiles().insert(*File);
  2624. }
  2625. }
  2626. llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
  2627. unsigned ClientLoadCapabilities) {
  2628. BitstreamCursor &Stream = F.Stream;
  2629. if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
  2630. return Err;
  2631. F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
  2632. // Read all of the records and blocks for the AST file.
  2633. RecordData Record;
  2634. while (true) {
  2635. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  2636. if (!MaybeEntry)
  2637. return MaybeEntry.takeError();
  2638. llvm::BitstreamEntry Entry = MaybeEntry.get();
  2639. switch (Entry.Kind) {
  2640. case llvm::BitstreamEntry::Error:
  2641. return llvm::createStringError(
  2642. std::errc::illegal_byte_sequence,
  2643. "error at end of module block in AST file");
  2644. case llvm::BitstreamEntry::EndBlock:
  2645. // Outside of C++, we do not store a lookup map for the translation unit.
  2646. // Instead, mark it as needing a lookup map to be built if this module
  2647. // contains any declarations lexically within it (which it always does!).
  2648. // This usually has no cost, since we very rarely need the lookup map for
  2649. // the translation unit outside C++.
  2650. if (ASTContext *Ctx = ContextObj) {
  2651. DeclContext *DC = Ctx->getTranslationUnitDecl();
  2652. if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
  2653. DC->setMustBuildLookupTable();
  2654. }
  2655. return llvm::Error::success();
  2656. case llvm::BitstreamEntry::SubBlock:
  2657. switch (Entry.ID) {
  2658. case DECLTYPES_BLOCK_ID:
  2659. // We lazily load the decls block, but we want to set up the
  2660. // DeclsCursor cursor to point into it. Clone our current bitcode
  2661. // cursor to it, enter the block and read the abbrevs in that block.
  2662. // With the main cursor, we just skip over it.
  2663. F.DeclsCursor = Stream;
  2664. if (llvm::Error Err = Stream.SkipBlock())
  2665. return Err;
  2666. if (llvm::Error Err = ReadBlockAbbrevs(
  2667. F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))
  2668. return Err;
  2669. break;
  2670. case PREPROCESSOR_BLOCK_ID:
  2671. F.MacroCursor = Stream;
  2672. if (!PP.getExternalSource())
  2673. PP.setExternalSource(this);
  2674. if (llvm::Error Err = Stream.SkipBlock())
  2675. return Err;
  2676. if (llvm::Error Err =
  2677. ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
  2678. return Err;
  2679. F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
  2680. break;
  2681. case PREPROCESSOR_DETAIL_BLOCK_ID:
  2682. F.PreprocessorDetailCursor = Stream;
  2683. if (llvm::Error Err = Stream.SkipBlock()) {
  2684. return Err;
  2685. }
  2686. if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
  2687. PREPROCESSOR_DETAIL_BLOCK_ID))
  2688. return Err;
  2689. F.PreprocessorDetailStartOffset
  2690. = F.PreprocessorDetailCursor.GetCurrentBitNo();
  2691. if (!PP.getPreprocessingRecord())
  2692. PP.createPreprocessingRecord();
  2693. if (!PP.getPreprocessingRecord()->getExternalSource())
  2694. PP.getPreprocessingRecord()->SetExternalSource(*this);
  2695. break;
  2696. case SOURCE_MANAGER_BLOCK_ID:
  2697. if (llvm::Error Err = ReadSourceManagerBlock(F))
  2698. return Err;
  2699. break;
  2700. case SUBMODULE_BLOCK_ID:
  2701. if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
  2702. return Err;
  2703. break;
  2704. case COMMENTS_BLOCK_ID: {
  2705. BitstreamCursor C = Stream;
  2706. if (llvm::Error Err = Stream.SkipBlock())
  2707. return Err;
  2708. if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
  2709. return Err;
  2710. CommentsCursors.push_back(std::make_pair(C, &F));
  2711. break;
  2712. }
  2713. default:
  2714. if (llvm::Error Err = Stream.SkipBlock())
  2715. return Err;
  2716. break;
  2717. }
  2718. continue;
  2719. case llvm::BitstreamEntry::Record:
  2720. // The interesting case.
  2721. break;
  2722. }
  2723. // Read and process a record.
  2724. Record.clear();
  2725. StringRef Blob;
  2726. Expected<unsigned> MaybeRecordType =
  2727. Stream.readRecord(Entry.ID, Record, &Blob);
  2728. if (!MaybeRecordType)
  2729. return MaybeRecordType.takeError();
  2730. ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
  2731. // If we're not loading an AST context, we don't care about most records.
  2732. if (!ContextObj) {
  2733. switch (RecordType) {
  2734. case IDENTIFIER_TABLE:
  2735. case IDENTIFIER_OFFSET:
  2736. case INTERESTING_IDENTIFIERS:
  2737. case STATISTICS:
  2738. case PP_ASSUME_NONNULL_LOC:
  2739. case PP_CONDITIONAL_STACK:
  2740. case PP_COUNTER_VALUE:
  2741. case SOURCE_LOCATION_OFFSETS:
  2742. case MODULE_OFFSET_MAP:
  2743. case SOURCE_MANAGER_LINE_TABLE:
  2744. case SOURCE_LOCATION_PRELOADS:
  2745. case PPD_ENTITIES_OFFSETS:
  2746. case HEADER_SEARCH_TABLE:
  2747. case IMPORTED_MODULES:
  2748. case MACRO_OFFSET:
  2749. break;
  2750. default:
  2751. continue;
  2752. }
  2753. }
  2754. switch (RecordType) {
  2755. default: // Default behavior: ignore.
  2756. break;
  2757. case TYPE_OFFSET: {
  2758. if (F.LocalNumTypes != 0)
  2759. return llvm::createStringError(
  2760. std::errc::illegal_byte_sequence,
  2761. "duplicate TYPE_OFFSET record in AST file");
  2762. F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
  2763. F.LocalNumTypes = Record[0];
  2764. unsigned LocalBaseTypeIndex = Record[1];
  2765. F.BaseTypeIndex = getTotalNumTypes();
  2766. if (F.LocalNumTypes > 0) {
  2767. // Introduce the global -> local mapping for types within this module.
  2768. GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
  2769. // Introduce the local -> global mapping for types within this module.
  2770. F.TypeRemap.insertOrReplace(
  2771. std::make_pair(LocalBaseTypeIndex,
  2772. F.BaseTypeIndex - LocalBaseTypeIndex));
  2773. TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
  2774. }
  2775. break;
  2776. }
  2777. case DECL_OFFSET: {
  2778. if (F.LocalNumDecls != 0)
  2779. return llvm::createStringError(
  2780. std::errc::illegal_byte_sequence,
  2781. "duplicate DECL_OFFSET record in AST file");
  2782. F.DeclOffsets = (const DeclOffset *)Blob.data();
  2783. F.LocalNumDecls = Record[0];
  2784. unsigned LocalBaseDeclID = Record[1];
  2785. F.BaseDeclID = getTotalNumDecls();
  2786. if (F.LocalNumDecls > 0) {
  2787. // Introduce the global -> local mapping for declarations within this
  2788. // module.
  2789. GlobalDeclMap.insert(
  2790. std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
  2791. // Introduce the local -> global mapping for declarations within this
  2792. // module.
  2793. F.DeclRemap.insertOrReplace(
  2794. std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
  2795. // Introduce the global -> local mapping for declarations within this
  2796. // module.
  2797. F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
  2798. DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
  2799. }
  2800. break;
  2801. }
  2802. case TU_UPDATE_LEXICAL: {
  2803. DeclContext *TU = ContextObj->getTranslationUnitDecl();
  2804. LexicalContents Contents(
  2805. reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
  2806. Blob.data()),
  2807. static_cast<unsigned int>(Blob.size() / 4));
  2808. TULexicalDecls.push_back(std::make_pair(&F, Contents));
  2809. TU->setHasExternalLexicalStorage(true);
  2810. break;
  2811. }
  2812. case UPDATE_VISIBLE: {
  2813. unsigned Idx = 0;
  2814. serialization::DeclID ID = ReadDeclID(F, Record, Idx);
  2815. auto *Data = (const unsigned char*)Blob.data();
  2816. PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
  2817. // If we've already loaded the decl, perform the updates when we finish
  2818. // loading this block.
  2819. if (Decl *D = GetExistingDecl(ID))
  2820. PendingUpdateRecords.push_back(
  2821. PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
  2822. break;
  2823. }
  2824. case IDENTIFIER_TABLE:
  2825. F.IdentifierTableData =
  2826. reinterpret_cast<const unsigned char *>(Blob.data());
  2827. if (Record[0]) {
  2828. F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
  2829. F.IdentifierTableData + Record[0],
  2830. F.IdentifierTableData + sizeof(uint32_t),
  2831. F.IdentifierTableData,
  2832. ASTIdentifierLookupTrait(*this, F));
  2833. PP.getIdentifierTable().setExternalIdentifierLookup(this);
  2834. }
  2835. break;
  2836. case IDENTIFIER_OFFSET: {
  2837. if (F.LocalNumIdentifiers != 0)
  2838. return llvm::createStringError(
  2839. std::errc::illegal_byte_sequence,
  2840. "duplicate IDENTIFIER_OFFSET record in AST file");
  2841. F.IdentifierOffsets = (const uint32_t *)Blob.data();
  2842. F.LocalNumIdentifiers = Record[0];
  2843. unsigned LocalBaseIdentifierID = Record[1];
  2844. F.BaseIdentifierID = getTotalNumIdentifiers();
  2845. if (F.LocalNumIdentifiers > 0) {
  2846. // Introduce the global -> local mapping for identifiers within this
  2847. // module.
  2848. GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
  2849. &F));
  2850. // Introduce the local -> global mapping for identifiers within this
  2851. // module.
  2852. F.IdentifierRemap.insertOrReplace(
  2853. std::make_pair(LocalBaseIdentifierID,
  2854. F.BaseIdentifierID - LocalBaseIdentifierID));
  2855. IdentifiersLoaded.resize(IdentifiersLoaded.size()
  2856. + F.LocalNumIdentifiers);
  2857. }
  2858. break;
  2859. }
  2860. case INTERESTING_IDENTIFIERS:
  2861. F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
  2862. break;
  2863. case EAGERLY_DESERIALIZED_DECLS:
  2864. // FIXME: Skip reading this record if our ASTConsumer doesn't care
  2865. // about "interesting" decls (for instance, if we're building a module).
  2866. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2867. EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2868. break;
  2869. case MODULAR_CODEGEN_DECLS:
  2870. // FIXME: Skip reading this record if our ASTConsumer doesn't care about
  2871. // them (ie: if we're not codegenerating this module).
  2872. if (F.Kind == MK_MainFile ||
  2873. getContext().getLangOpts().BuildingPCHWithObjectFile)
  2874. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2875. EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2876. break;
  2877. case SPECIAL_TYPES:
  2878. if (SpecialTypes.empty()) {
  2879. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2880. SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
  2881. break;
  2882. }
  2883. if (SpecialTypes.size() != Record.size())
  2884. return llvm::createStringError(std::errc::illegal_byte_sequence,
  2885. "invalid special-types record");
  2886. for (unsigned I = 0, N = Record.size(); I != N; ++I) {
  2887. serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
  2888. if (!SpecialTypes[I])
  2889. SpecialTypes[I] = ID;
  2890. // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
  2891. // merge step?
  2892. }
  2893. break;
  2894. case STATISTICS:
  2895. TotalNumStatements += Record[0];
  2896. TotalNumMacros += Record[1];
  2897. TotalLexicalDeclContexts += Record[2];
  2898. TotalVisibleDeclContexts += Record[3];
  2899. break;
  2900. case UNUSED_FILESCOPED_DECLS:
  2901. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2902. UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2903. break;
  2904. case DELEGATING_CTORS:
  2905. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2906. DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
  2907. break;
  2908. case WEAK_UNDECLARED_IDENTIFIERS:
  2909. if (Record.size() % 3 != 0)
  2910. return llvm::createStringError(std::errc::illegal_byte_sequence,
  2911. "invalid weak identifiers record");
  2912. // FIXME: Ignore weak undeclared identifiers from non-original PCH
  2913. // files. This isn't the way to do it :)
  2914. WeakUndeclaredIdentifiers.clear();
  2915. // Translate the weak, undeclared identifiers into global IDs.
  2916. for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
  2917. WeakUndeclaredIdentifiers.push_back(
  2918. getGlobalIdentifierID(F, Record[I++]));
  2919. WeakUndeclaredIdentifiers.push_back(
  2920. getGlobalIdentifierID(F, Record[I++]));
  2921. WeakUndeclaredIdentifiers.push_back(
  2922. ReadSourceLocation(F, Record, I).getRawEncoding());
  2923. }
  2924. break;
  2925. case SELECTOR_OFFSETS: {
  2926. F.SelectorOffsets = (const uint32_t *)Blob.data();
  2927. F.LocalNumSelectors = Record[0];
  2928. unsigned LocalBaseSelectorID = Record[1];
  2929. F.BaseSelectorID = getTotalNumSelectors();
  2930. if (F.LocalNumSelectors > 0) {
  2931. // Introduce the global -> local mapping for selectors within this
  2932. // module.
  2933. GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
  2934. // Introduce the local -> global mapping for selectors within this
  2935. // module.
  2936. F.SelectorRemap.insertOrReplace(
  2937. std::make_pair(LocalBaseSelectorID,
  2938. F.BaseSelectorID - LocalBaseSelectorID));
  2939. SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
  2940. }
  2941. break;
  2942. }
  2943. case METHOD_POOL:
  2944. F.SelectorLookupTableData = (const unsigned char *)Blob.data();
  2945. if (Record[0])
  2946. F.SelectorLookupTable
  2947. = ASTSelectorLookupTable::Create(
  2948. F.SelectorLookupTableData + Record[0],
  2949. F.SelectorLookupTableData,
  2950. ASTSelectorLookupTrait(*this, F));
  2951. TotalNumMethodPoolEntries += Record[1];
  2952. break;
  2953. case REFERENCED_SELECTOR_POOL:
  2954. if (!Record.empty()) {
  2955. for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
  2956. ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
  2957. Record[Idx++]));
  2958. ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
  2959. getRawEncoding());
  2960. }
  2961. }
  2962. break;
  2963. case PP_ASSUME_NONNULL_LOC: {
  2964. unsigned Idx = 0;
  2965. if (!Record.empty())
  2966. PP.setPreambleRecordedPragmaAssumeNonNullLoc(
  2967. ReadSourceLocation(F, Record, Idx));
  2968. break;
  2969. }
  2970. case PP_CONDITIONAL_STACK:
  2971. if (!Record.empty()) {
  2972. unsigned Idx = 0, End = Record.size() - 1;
  2973. bool ReachedEOFWhileSkipping = Record[Idx++];
  2974. std::optional<Preprocessor::PreambleSkipInfo> SkipInfo;
  2975. if (ReachedEOFWhileSkipping) {
  2976. SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
  2977. SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
  2978. bool FoundNonSkipPortion = Record[Idx++];
  2979. bool FoundElse = Record[Idx++];
  2980. SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
  2981. SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
  2982. FoundElse, ElseLoc);
  2983. }
  2984. SmallVector<PPConditionalInfo, 4> ConditionalStack;
  2985. while (Idx < End) {
  2986. auto Loc = ReadSourceLocation(F, Record, Idx);
  2987. bool WasSkipping = Record[Idx++];
  2988. bool FoundNonSkip = Record[Idx++];
  2989. bool FoundElse = Record[Idx++];
  2990. ConditionalStack.push_back(
  2991. {Loc, WasSkipping, FoundNonSkip, FoundElse});
  2992. }
  2993. PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
  2994. }
  2995. break;
  2996. case PP_COUNTER_VALUE:
  2997. if (!Record.empty() && Listener)
  2998. Listener->ReadCounter(F, Record[0]);
  2999. break;
  3000. case FILE_SORTED_DECLS:
  3001. F.FileSortedDecls = (const DeclID *)Blob.data();
  3002. F.NumFileSortedDecls = Record[0];
  3003. break;
  3004. case SOURCE_LOCATION_OFFSETS: {
  3005. F.SLocEntryOffsets = (const uint32_t *)Blob.data();
  3006. F.LocalNumSLocEntries = Record[0];
  3007. SourceLocation::UIntTy SLocSpaceSize = Record[1];
  3008. F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
  3009. std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
  3010. SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
  3011. SLocSpaceSize);
  3012. if (!F.SLocEntryBaseID) {
  3013. if (!Diags.isDiagnosticInFlight()) {
  3014. Diags.Report(SourceLocation(), diag::remark_sloc_usage);
  3015. SourceMgr.noteSLocAddressSpaceUsage(Diags);
  3016. }
  3017. return llvm::createStringError(std::errc::invalid_argument,
  3018. "ran out of source locations");
  3019. }
  3020. // Make our entry in the range map. BaseID is negative and growing, so
  3021. // we invert it. Because we invert it, though, we need the other end of
  3022. // the range.
  3023. unsigned RangeStart =
  3024. unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
  3025. GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
  3026. F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
  3027. // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
  3028. assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
  3029. GlobalSLocOffsetMap.insert(
  3030. std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
  3031. - SLocSpaceSize,&F));
  3032. // Initialize the remapping table.
  3033. // Invalid stays invalid.
  3034. F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
  3035. // This module. Base was 2 when being compiled.
  3036. F.SLocRemap.insertOrReplace(std::make_pair(
  3037. 2U, static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2)));
  3038. TotalNumSLocEntries += F.LocalNumSLocEntries;
  3039. break;
  3040. }
  3041. case MODULE_OFFSET_MAP:
  3042. F.ModuleOffsetMap = Blob;
  3043. break;
  3044. case SOURCE_MANAGER_LINE_TABLE:
  3045. ParseLineTable(F, Record);
  3046. break;
  3047. case SOURCE_LOCATION_PRELOADS: {
  3048. // Need to transform from the local view (1-based IDs) to the global view,
  3049. // which is based off F.SLocEntryBaseID.
  3050. if (!F.PreloadSLocEntries.empty())
  3051. return llvm::createStringError(
  3052. std::errc::illegal_byte_sequence,
  3053. "Multiple SOURCE_LOCATION_PRELOADS records in AST file");
  3054. F.PreloadSLocEntries.swap(Record);
  3055. break;
  3056. }
  3057. case EXT_VECTOR_DECLS:
  3058. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3059. ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
  3060. break;
  3061. case VTABLE_USES:
  3062. if (Record.size() % 3 != 0)
  3063. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3064. "Invalid VTABLE_USES record");
  3065. // Later tables overwrite earlier ones.
  3066. // FIXME: Modules will have some trouble with this. This is clearly not
  3067. // the right way to do this.
  3068. VTableUses.clear();
  3069. for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
  3070. VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
  3071. VTableUses.push_back(
  3072. ReadSourceLocation(F, Record, Idx).getRawEncoding());
  3073. VTableUses.push_back(Record[Idx++]);
  3074. }
  3075. break;
  3076. case PENDING_IMPLICIT_INSTANTIATIONS:
  3077. if (PendingInstantiations.size() % 2 != 0)
  3078. return llvm::createStringError(
  3079. std::errc::illegal_byte_sequence,
  3080. "Invalid existing PendingInstantiations");
  3081. if (Record.size() % 2 != 0)
  3082. return llvm::createStringError(
  3083. std::errc::illegal_byte_sequence,
  3084. "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
  3085. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  3086. PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
  3087. PendingInstantiations.push_back(
  3088. ReadSourceLocation(F, Record, I).getRawEncoding());
  3089. }
  3090. break;
  3091. case SEMA_DECL_REFS:
  3092. if (Record.size() != 3)
  3093. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3094. "Invalid SEMA_DECL_REFS block");
  3095. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3096. SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  3097. break;
  3098. case PPD_ENTITIES_OFFSETS: {
  3099. F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
  3100. assert(Blob.size() % sizeof(PPEntityOffset) == 0);
  3101. F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
  3102. unsigned LocalBasePreprocessedEntityID = Record[0];
  3103. unsigned StartingID;
  3104. if (!PP.getPreprocessingRecord())
  3105. PP.createPreprocessingRecord();
  3106. if (!PP.getPreprocessingRecord()->getExternalSource())
  3107. PP.getPreprocessingRecord()->SetExternalSource(*this);
  3108. StartingID
  3109. = PP.getPreprocessingRecord()
  3110. ->allocateLoadedEntities(F.NumPreprocessedEntities);
  3111. F.BasePreprocessedEntityID = StartingID;
  3112. if (F.NumPreprocessedEntities > 0) {
  3113. // Introduce the global -> local mapping for preprocessed entities in
  3114. // this module.
  3115. GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
  3116. // Introduce the local -> global mapping for preprocessed entities in
  3117. // this module.
  3118. F.PreprocessedEntityRemap.insertOrReplace(
  3119. std::make_pair(LocalBasePreprocessedEntityID,
  3120. F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
  3121. }
  3122. break;
  3123. }
  3124. case PPD_SKIPPED_RANGES: {
  3125. F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
  3126. assert(Blob.size() % sizeof(PPSkippedRange) == 0);
  3127. F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
  3128. if (!PP.getPreprocessingRecord())
  3129. PP.createPreprocessingRecord();
  3130. if (!PP.getPreprocessingRecord()->getExternalSource())
  3131. PP.getPreprocessingRecord()->SetExternalSource(*this);
  3132. F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
  3133. ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
  3134. if (F.NumPreprocessedSkippedRanges > 0)
  3135. GlobalSkippedRangeMap.insert(
  3136. std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
  3137. break;
  3138. }
  3139. case DECL_UPDATE_OFFSETS:
  3140. if (Record.size() % 2 != 0)
  3141. return llvm::createStringError(
  3142. std::errc::illegal_byte_sequence,
  3143. "invalid DECL_UPDATE_OFFSETS block in AST file");
  3144. for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
  3145. GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
  3146. DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
  3147. // If we've already loaded the decl, perform the updates when we finish
  3148. // loading this block.
  3149. if (Decl *D = GetExistingDecl(ID))
  3150. PendingUpdateRecords.push_back(
  3151. PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
  3152. }
  3153. break;
  3154. case OBJC_CATEGORIES_MAP:
  3155. if (F.LocalNumObjCCategoriesInMap != 0)
  3156. return llvm::createStringError(
  3157. std::errc::illegal_byte_sequence,
  3158. "duplicate OBJC_CATEGORIES_MAP record in AST file");
  3159. F.LocalNumObjCCategoriesInMap = Record[0];
  3160. F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
  3161. break;
  3162. case OBJC_CATEGORIES:
  3163. F.ObjCCategories.swap(Record);
  3164. break;
  3165. case CUDA_SPECIAL_DECL_REFS:
  3166. // Later tables overwrite earlier ones.
  3167. // FIXME: Modules will have trouble with this.
  3168. CUDASpecialDeclRefs.clear();
  3169. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3170. CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  3171. break;
  3172. case HEADER_SEARCH_TABLE:
  3173. F.HeaderFileInfoTableData = Blob.data();
  3174. F.LocalNumHeaderFileInfos = Record[1];
  3175. if (Record[0]) {
  3176. F.HeaderFileInfoTable
  3177. = HeaderFileInfoLookupTable::Create(
  3178. (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
  3179. (const unsigned char *)F.HeaderFileInfoTableData,
  3180. HeaderFileInfoTrait(*this, F,
  3181. &PP.getHeaderSearchInfo(),
  3182. Blob.data() + Record[2]));
  3183. PP.getHeaderSearchInfo().SetExternalSource(this);
  3184. if (!PP.getHeaderSearchInfo().getExternalLookup())
  3185. PP.getHeaderSearchInfo().SetExternalLookup(this);
  3186. }
  3187. break;
  3188. case FP_PRAGMA_OPTIONS:
  3189. // Later tables overwrite earlier ones.
  3190. FPPragmaOptions.swap(Record);
  3191. break;
  3192. case OPENCL_EXTENSIONS:
  3193. for (unsigned I = 0, E = Record.size(); I != E; ) {
  3194. auto Name = ReadString(Record, I);
  3195. auto &OptInfo = OpenCLExtensions.OptMap[Name];
  3196. OptInfo.Supported = Record[I++] != 0;
  3197. OptInfo.Enabled = Record[I++] != 0;
  3198. OptInfo.WithPragma = Record[I++] != 0;
  3199. OptInfo.Avail = Record[I++];
  3200. OptInfo.Core = Record[I++];
  3201. OptInfo.Opt = Record[I++];
  3202. }
  3203. break;
  3204. case TENTATIVE_DEFINITIONS:
  3205. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3206. TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
  3207. break;
  3208. case KNOWN_NAMESPACES:
  3209. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3210. KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
  3211. break;
  3212. case UNDEFINED_BUT_USED:
  3213. if (UndefinedButUsed.size() % 2 != 0)
  3214. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3215. "Invalid existing UndefinedButUsed");
  3216. if (Record.size() % 2 != 0)
  3217. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3218. "invalid undefined-but-used record");
  3219. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  3220. UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
  3221. UndefinedButUsed.push_back(
  3222. ReadSourceLocation(F, Record, I).getRawEncoding());
  3223. }
  3224. break;
  3225. case DELETE_EXPRS_TO_ANALYZE:
  3226. for (unsigned I = 0, N = Record.size(); I != N;) {
  3227. DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
  3228. const uint64_t Count = Record[I++];
  3229. DelayedDeleteExprs.push_back(Count);
  3230. for (uint64_t C = 0; C < Count; ++C) {
  3231. DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
  3232. bool IsArrayForm = Record[I++] == 1;
  3233. DelayedDeleteExprs.push_back(IsArrayForm);
  3234. }
  3235. }
  3236. break;
  3237. case IMPORTED_MODULES:
  3238. if (!F.isModule()) {
  3239. // If we aren't loading a module (which has its own exports), make
  3240. // all of the imported modules visible.
  3241. // FIXME: Deal with macros-only imports.
  3242. for (unsigned I = 0, N = Record.size(); I != N; /**/) {
  3243. unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
  3244. SourceLocation Loc = ReadSourceLocation(F, Record, I);
  3245. if (GlobalID) {
  3246. ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
  3247. if (DeserializationListener)
  3248. DeserializationListener->ModuleImportRead(GlobalID, Loc);
  3249. }
  3250. }
  3251. }
  3252. break;
  3253. case MACRO_OFFSET: {
  3254. if (F.LocalNumMacros != 0)
  3255. return llvm::createStringError(
  3256. std::errc::illegal_byte_sequence,
  3257. "duplicate MACRO_OFFSET record in AST file");
  3258. F.MacroOffsets = (const uint32_t *)Blob.data();
  3259. F.LocalNumMacros = Record[0];
  3260. unsigned LocalBaseMacroID = Record[1];
  3261. F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset;
  3262. F.BaseMacroID = getTotalNumMacros();
  3263. if (F.LocalNumMacros > 0) {
  3264. // Introduce the global -> local mapping for macros within this module.
  3265. GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
  3266. // Introduce the local -> global mapping for macros within this module.
  3267. F.MacroRemap.insertOrReplace(
  3268. std::make_pair(LocalBaseMacroID,
  3269. F.BaseMacroID - LocalBaseMacroID));
  3270. MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
  3271. }
  3272. break;
  3273. }
  3274. case PP_INCLUDED_FILES:
  3275. readIncludedFiles(F, Blob, PP);
  3276. break;
  3277. case LATE_PARSED_TEMPLATE:
  3278. LateParsedTemplates.emplace_back(
  3279. std::piecewise_construct, std::forward_as_tuple(&F),
  3280. std::forward_as_tuple(Record.begin(), Record.end()));
  3281. break;
  3282. case OPTIMIZE_PRAGMA_OPTIONS:
  3283. if (Record.size() != 1)
  3284. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3285. "invalid pragma optimize record");
  3286. OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
  3287. break;
  3288. case MSSTRUCT_PRAGMA_OPTIONS:
  3289. if (Record.size() != 1)
  3290. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3291. "invalid pragma ms_struct record");
  3292. PragmaMSStructState = Record[0];
  3293. break;
  3294. case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
  3295. if (Record.size() != 2)
  3296. return llvm::createStringError(
  3297. std::errc::illegal_byte_sequence,
  3298. "invalid pragma pointers to members record");
  3299. PragmaMSPointersToMembersState = Record[0];
  3300. PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
  3301. break;
  3302. case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
  3303. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3304. UnusedLocalTypedefNameCandidates.push_back(
  3305. getGlobalDeclID(F, Record[I]));
  3306. break;
  3307. case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
  3308. if (Record.size() != 1)
  3309. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3310. "invalid cuda pragma options record");
  3311. ForceCUDAHostDeviceDepth = Record[0];
  3312. break;
  3313. case ALIGN_PACK_PRAGMA_OPTIONS: {
  3314. if (Record.size() < 3)
  3315. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3316. "invalid pragma pack record");
  3317. PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
  3318. PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
  3319. unsigned NumStackEntries = Record[2];
  3320. unsigned Idx = 3;
  3321. // Reset the stack when importing a new module.
  3322. PragmaAlignPackStack.clear();
  3323. for (unsigned I = 0; I < NumStackEntries; ++I) {
  3324. PragmaAlignPackStackEntry Entry;
  3325. Entry.Value = ReadAlignPackInfo(Record[Idx++]);
  3326. Entry.Location = ReadSourceLocation(F, Record[Idx++]);
  3327. Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
  3328. PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
  3329. Entry.SlotLabel = PragmaAlignPackStrings.back();
  3330. PragmaAlignPackStack.push_back(Entry);
  3331. }
  3332. break;
  3333. }
  3334. case FLOAT_CONTROL_PRAGMA_OPTIONS: {
  3335. if (Record.size() < 3)
  3336. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3337. "invalid pragma float control record");
  3338. FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
  3339. FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
  3340. unsigned NumStackEntries = Record[2];
  3341. unsigned Idx = 3;
  3342. // Reset the stack when importing a new module.
  3343. FpPragmaStack.clear();
  3344. for (unsigned I = 0; I < NumStackEntries; ++I) {
  3345. FpPragmaStackEntry Entry;
  3346. Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
  3347. Entry.Location = ReadSourceLocation(F, Record[Idx++]);
  3348. Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
  3349. FpPragmaStrings.push_back(ReadString(Record, Idx));
  3350. Entry.SlotLabel = FpPragmaStrings.back();
  3351. FpPragmaStack.push_back(Entry);
  3352. }
  3353. break;
  3354. }
  3355. case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
  3356. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3357. DeclsToCheckForDeferredDiags.insert(getGlobalDeclID(F, Record[I]));
  3358. break;
  3359. }
  3360. }
  3361. }
  3362. void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
  3363. assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
  3364. // Additional remapping information.
  3365. const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
  3366. const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
  3367. F.ModuleOffsetMap = StringRef();
  3368. // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
  3369. if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
  3370. F.SLocRemap.insert(std::make_pair(0U, 0));
  3371. F.SLocRemap.insert(std::make_pair(2U, 1));
  3372. }
  3373. // Continuous range maps we may be updating in our module.
  3374. using SLocRemapBuilder =
  3375. ContinuousRangeMap<SourceLocation::UIntTy, SourceLocation::IntTy,
  3376. 2>::Builder;
  3377. using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
  3378. SLocRemapBuilder SLocRemap(F.SLocRemap);
  3379. RemapBuilder IdentifierRemap(F.IdentifierRemap);
  3380. RemapBuilder MacroRemap(F.MacroRemap);
  3381. RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
  3382. RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
  3383. RemapBuilder SelectorRemap(F.SelectorRemap);
  3384. RemapBuilder DeclRemap(F.DeclRemap);
  3385. RemapBuilder TypeRemap(F.TypeRemap);
  3386. while (Data < DataEnd) {
  3387. // FIXME: Looking up dependency modules by filename is horrible. Let's
  3388. // start fixing this with prebuilt, explicit and implicit modules and see
  3389. // how it goes...
  3390. using namespace llvm::support;
  3391. ModuleKind Kind = static_cast<ModuleKind>(
  3392. endian::readNext<uint8_t, little, unaligned>(Data));
  3393. uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
  3394. StringRef Name = StringRef((const char*)Data, Len);
  3395. Data += Len;
  3396. ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||
  3397. Kind == MK_ImplicitModule
  3398. ? ModuleMgr.lookupByModuleName(Name)
  3399. : ModuleMgr.lookupByFileName(Name));
  3400. if (!OM) {
  3401. std::string Msg =
  3402. "SourceLocation remap refers to unknown module, cannot find ";
  3403. Msg.append(std::string(Name));
  3404. Error(Msg);
  3405. return;
  3406. }
  3407. SourceLocation::UIntTy SLocOffset =
  3408. endian::readNext<uint32_t, little, unaligned>(Data);
  3409. uint32_t IdentifierIDOffset =
  3410. endian::readNext<uint32_t, little, unaligned>(Data);
  3411. uint32_t MacroIDOffset =
  3412. endian::readNext<uint32_t, little, unaligned>(Data);
  3413. uint32_t PreprocessedEntityIDOffset =
  3414. endian::readNext<uint32_t, little, unaligned>(Data);
  3415. uint32_t SubmoduleIDOffset =
  3416. endian::readNext<uint32_t, little, unaligned>(Data);
  3417. uint32_t SelectorIDOffset =
  3418. endian::readNext<uint32_t, little, unaligned>(Data);
  3419. uint32_t DeclIDOffset =
  3420. endian::readNext<uint32_t, little, unaligned>(Data);
  3421. uint32_t TypeIndexOffset =
  3422. endian::readNext<uint32_t, little, unaligned>(Data);
  3423. auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
  3424. RemapBuilder &Remap) {
  3425. constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
  3426. if (Offset != None)
  3427. Remap.insert(std::make_pair(Offset,
  3428. static_cast<int>(BaseOffset - Offset)));
  3429. };
  3430. constexpr SourceLocation::UIntTy SLocNone =
  3431. std::numeric_limits<SourceLocation::UIntTy>::max();
  3432. if (SLocOffset != SLocNone)
  3433. SLocRemap.insert(std::make_pair(
  3434. SLocOffset, static_cast<SourceLocation::IntTy>(
  3435. OM->SLocEntryBaseOffset - SLocOffset)));
  3436. mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
  3437. mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
  3438. mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
  3439. PreprocessedEntityRemap);
  3440. mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
  3441. mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
  3442. mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
  3443. mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
  3444. // Global -> local mappings.
  3445. F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
  3446. }
  3447. }
  3448. ASTReader::ASTReadResult
  3449. ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
  3450. const ModuleFile *ImportedBy,
  3451. unsigned ClientLoadCapabilities) {
  3452. unsigned Idx = 0;
  3453. F.ModuleMapPath = ReadPath(F, Record, Idx);
  3454. // Try to resolve ModuleName in the current header search context and
  3455. // verify that it is found in the same module map file as we saved. If the
  3456. // top-level AST file is a main file, skip this check because there is no
  3457. // usable header search context.
  3458. assert(!F.ModuleName.empty() &&
  3459. "MODULE_NAME should come before MODULE_MAP_FILE");
  3460. if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
  3461. // An implicitly-loaded module file should have its module listed in some
  3462. // module map file that we've already loaded.
  3463. Module *M =
  3464. PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
  3465. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  3466. OptionalFileEntryRef ModMap =
  3467. M ? Map.getModuleMapFileForUniquing(M) : std::nullopt;
  3468. // Don't emit module relocation error if we have -fno-validate-pch
  3469. if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
  3470. DisableValidationForModuleKind::Module) &&
  3471. !ModMap) {
  3472. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
  3473. if (auto ASTFE = M ? M->getASTFile() : std::nullopt) {
  3474. // This module was defined by an imported (explicit) module.
  3475. Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
  3476. << ASTFE->getName();
  3477. } else {
  3478. // This module was built with a different module map.
  3479. Diag(diag::err_imported_module_not_found)
  3480. << F.ModuleName << F.FileName
  3481. << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
  3482. << !ImportedBy;
  3483. // In case it was imported by a PCH, there's a chance the user is
  3484. // just missing to include the search path to the directory containing
  3485. // the modulemap.
  3486. if (ImportedBy && ImportedBy->Kind == MK_PCH)
  3487. Diag(diag::note_imported_by_pch_module_not_found)
  3488. << llvm::sys::path::parent_path(F.ModuleMapPath);
  3489. }
  3490. }
  3491. return OutOfDate;
  3492. }
  3493. assert(M && M->Name == F.ModuleName && "found module with different name");
  3494. // Check the primary module map file.
  3495. auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
  3496. if (!StoredModMap || *StoredModMap != ModMap) {
  3497. assert(ModMap && "found module is missing module map file");
  3498. assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
  3499. "top-level import should be verified");
  3500. bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
  3501. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  3502. Diag(diag::err_imported_module_modmap_changed)
  3503. << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
  3504. << ModMap->getName() << F.ModuleMapPath << NotImported;
  3505. return OutOfDate;
  3506. }
  3507. llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
  3508. for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
  3509. // FIXME: we should use input files rather than storing names.
  3510. std::string Filename = ReadPath(F, Record, Idx);
  3511. auto SF = FileMgr.getFile(Filename, false, false);
  3512. if (!SF) {
  3513. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  3514. Error("could not find file '" + Filename +"' referenced by AST file");
  3515. return OutOfDate;
  3516. }
  3517. AdditionalStoredMaps.insert(*SF);
  3518. }
  3519. // Check any additional module map files (e.g. module.private.modulemap)
  3520. // that are not in the pcm.
  3521. if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
  3522. for (const FileEntry *ModMap : *AdditionalModuleMaps) {
  3523. // Remove files that match
  3524. // Note: SmallPtrSet::erase is really remove
  3525. if (!AdditionalStoredMaps.erase(ModMap)) {
  3526. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  3527. Diag(diag::err_module_different_modmap)
  3528. << F.ModuleName << /*new*/0 << ModMap->getName();
  3529. return OutOfDate;
  3530. }
  3531. }
  3532. }
  3533. // Check any additional module map files that are in the pcm, but not
  3534. // found in header search. Cases that match are already removed.
  3535. for (const FileEntry *ModMap : AdditionalStoredMaps) {
  3536. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  3537. Diag(diag::err_module_different_modmap)
  3538. << F.ModuleName << /*not new*/1 << ModMap->getName();
  3539. return OutOfDate;
  3540. }
  3541. }
  3542. if (Listener)
  3543. Listener->ReadModuleMapFile(F.ModuleMapPath);
  3544. return Success;
  3545. }
  3546. /// Move the given method to the back of the global list of methods.
  3547. static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
  3548. // Find the entry for this selector in the method pool.
  3549. Sema::GlobalMethodPool::iterator Known
  3550. = S.MethodPool.find(Method->getSelector());
  3551. if (Known == S.MethodPool.end())
  3552. return;
  3553. // Retrieve the appropriate method list.
  3554. ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
  3555. : Known->second.second;
  3556. bool Found = false;
  3557. for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
  3558. if (!Found) {
  3559. if (List->getMethod() == Method) {
  3560. Found = true;
  3561. } else {
  3562. // Keep searching.
  3563. continue;
  3564. }
  3565. }
  3566. if (List->getNext())
  3567. List->setMethod(List->getNext()->getMethod());
  3568. else
  3569. List->setMethod(Method);
  3570. }
  3571. }
  3572. void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
  3573. assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
  3574. for (Decl *D : Names) {
  3575. bool wasHidden = !D->isUnconditionallyVisible();
  3576. D->setVisibleDespiteOwningModule();
  3577. if (wasHidden && SemaObj) {
  3578. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
  3579. moveMethodToBackOfGlobalList(*SemaObj, Method);
  3580. }
  3581. }
  3582. }
  3583. }
  3584. void ASTReader::makeModuleVisible(Module *Mod,
  3585. Module::NameVisibilityKind NameVisibility,
  3586. SourceLocation ImportLoc) {
  3587. llvm::SmallPtrSet<Module *, 4> Visited;
  3588. SmallVector<Module *, 4> Stack;
  3589. Stack.push_back(Mod);
  3590. while (!Stack.empty()) {
  3591. Mod = Stack.pop_back_val();
  3592. if (NameVisibility <= Mod->NameVisibility) {
  3593. // This module already has this level of visibility (or greater), so
  3594. // there is nothing more to do.
  3595. continue;
  3596. }
  3597. if (Mod->isUnimportable()) {
  3598. // Modules that aren't importable cannot be made visible.
  3599. continue;
  3600. }
  3601. // Update the module's name visibility.
  3602. Mod->NameVisibility = NameVisibility;
  3603. // If we've already deserialized any names from this module,
  3604. // mark them as visible.
  3605. HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
  3606. if (Hidden != HiddenNamesMap.end()) {
  3607. auto HiddenNames = std::move(*Hidden);
  3608. HiddenNamesMap.erase(Hidden);
  3609. makeNamesVisible(HiddenNames.second, HiddenNames.first);
  3610. assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
  3611. "making names visible added hidden names");
  3612. }
  3613. // Push any exported modules onto the stack to be marked as visible.
  3614. SmallVector<Module *, 16> Exports;
  3615. Mod->getExportedModules(Exports);
  3616. for (SmallVectorImpl<Module *>::iterator
  3617. I = Exports.begin(), E = Exports.end(); I != E; ++I) {
  3618. Module *Exported = *I;
  3619. if (Visited.insert(Exported).second)
  3620. Stack.push_back(Exported);
  3621. }
  3622. }
  3623. }
  3624. /// We've merged the definition \p MergedDef into the existing definition
  3625. /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
  3626. /// visible.
  3627. void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
  3628. NamedDecl *MergedDef) {
  3629. if (!Def->isUnconditionallyVisible()) {
  3630. // If MergedDef is visible or becomes visible, make the definition visible.
  3631. if (MergedDef->isUnconditionallyVisible())
  3632. Def->setVisibleDespiteOwningModule();
  3633. else {
  3634. getContext().mergeDefinitionIntoModule(
  3635. Def, MergedDef->getImportedOwningModule(),
  3636. /*NotifyListeners*/ false);
  3637. PendingMergedDefinitionsToDeduplicate.insert(Def);
  3638. }
  3639. }
  3640. }
  3641. bool ASTReader::loadGlobalIndex() {
  3642. if (GlobalIndex)
  3643. return false;
  3644. if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
  3645. !PP.getLangOpts().Modules)
  3646. return true;
  3647. // Try to load the global index.
  3648. TriedLoadingGlobalIndex = true;
  3649. StringRef ModuleCachePath
  3650. = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
  3651. std::pair<GlobalModuleIndex *, llvm::Error> Result =
  3652. GlobalModuleIndex::readIndex(ModuleCachePath);
  3653. if (llvm::Error Err = std::move(Result.second)) {
  3654. assert(!Result.first);
  3655. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  3656. return true;
  3657. }
  3658. GlobalIndex.reset(Result.first);
  3659. ModuleMgr.setGlobalIndex(GlobalIndex.get());
  3660. return false;
  3661. }
  3662. bool ASTReader::isGlobalIndexUnavailable() const {
  3663. return PP.getLangOpts().Modules && UseGlobalIndex &&
  3664. !hasGlobalIndex() && TriedLoadingGlobalIndex;
  3665. }
  3666. static void updateModuleTimestamp(ModuleFile &MF) {
  3667. // Overwrite the timestamp file contents so that file's mtime changes.
  3668. std::string TimestampFilename = MF.getTimestampFilename();
  3669. std::error_code EC;
  3670. llvm::raw_fd_ostream OS(TimestampFilename, EC,
  3671. llvm::sys::fs::OF_TextWithCRLF);
  3672. if (EC)
  3673. return;
  3674. OS << "Timestamp file\n";
  3675. OS.close();
  3676. OS.clear_error(); // Avoid triggering a fatal error.
  3677. }
  3678. /// Given a cursor at the start of an AST file, scan ahead and drop the
  3679. /// cursor into the start of the given block ID, returning false on success and
  3680. /// true on failure.
  3681. static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
  3682. while (true) {
  3683. Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
  3684. if (!MaybeEntry) {
  3685. // FIXME this drops errors on the floor.
  3686. consumeError(MaybeEntry.takeError());
  3687. return true;
  3688. }
  3689. llvm::BitstreamEntry Entry = MaybeEntry.get();
  3690. switch (Entry.Kind) {
  3691. case llvm::BitstreamEntry::Error:
  3692. case llvm::BitstreamEntry::EndBlock:
  3693. return true;
  3694. case llvm::BitstreamEntry::Record:
  3695. // Ignore top-level records.
  3696. if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
  3697. break;
  3698. else {
  3699. // FIXME this drops errors on the floor.
  3700. consumeError(Skipped.takeError());
  3701. return true;
  3702. }
  3703. case llvm::BitstreamEntry::SubBlock:
  3704. if (Entry.ID == BlockID) {
  3705. if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
  3706. // FIXME this drops the error on the floor.
  3707. consumeError(std::move(Err));
  3708. return true;
  3709. }
  3710. // Found it!
  3711. return false;
  3712. }
  3713. if (llvm::Error Err = Cursor.SkipBlock()) {
  3714. // FIXME this drops the error on the floor.
  3715. consumeError(std::move(Err));
  3716. return true;
  3717. }
  3718. }
  3719. }
  3720. }
  3721. ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
  3722. ModuleKind Type,
  3723. SourceLocation ImportLoc,
  3724. unsigned ClientLoadCapabilities,
  3725. SmallVectorImpl<ImportedSubmodule> *Imported) {
  3726. llvm::TimeTraceScope scope("ReadAST", FileName);
  3727. llvm::SaveAndRestore SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
  3728. llvm::SaveAndRestore<std::optional<ModuleKind>> SetCurModuleKindRAII(
  3729. CurrentDeserializingModuleKind, Type);
  3730. // Defer any pending actions until we get to the end of reading the AST file.
  3731. Deserializing AnASTFile(this);
  3732. // Bump the generation number.
  3733. unsigned PreviousGeneration = 0;
  3734. if (ContextObj)
  3735. PreviousGeneration = incrementGeneration(*ContextObj);
  3736. unsigned NumModules = ModuleMgr.size();
  3737. SmallVector<ImportedModule, 4> Loaded;
  3738. if (ASTReadResult ReadResult =
  3739. ReadASTCore(FileName, Type, ImportLoc,
  3740. /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
  3741. ClientLoadCapabilities)) {
  3742. ModuleMgr.removeModules(ModuleMgr.begin() + NumModules);
  3743. // If we find that any modules are unusable, the global index is going
  3744. // to be out-of-date. Just remove it.
  3745. GlobalIndex.reset();
  3746. ModuleMgr.setGlobalIndex(nullptr);
  3747. return ReadResult;
  3748. }
  3749. // Here comes stuff that we only do once the entire chain is loaded. Do *not*
  3750. // remove modules from this point. Various fields are updated during reading
  3751. // the AST block and removing the modules would result in dangling pointers.
  3752. // They are generally only incidentally dereferenced, ie. a binary search
  3753. // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
  3754. // be dereferenced but it wouldn't actually be used.
  3755. // Load the AST blocks of all of the modules that we loaded. We can still
  3756. // hit errors parsing the ASTs at this point.
  3757. for (ImportedModule &M : Loaded) {
  3758. ModuleFile &F = *M.Mod;
  3759. llvm::TimeTraceScope Scope2("Read Loaded AST", F.ModuleName);
  3760. // Read the AST block.
  3761. if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
  3762. Error(std::move(Err));
  3763. return Failure;
  3764. }
  3765. // The AST block should always have a definition for the main module.
  3766. if (F.isModule() && !F.DidReadTopLevelSubmodule) {
  3767. Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
  3768. return Failure;
  3769. }
  3770. // Read the extension blocks.
  3771. while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
  3772. if (llvm::Error Err = ReadExtensionBlock(F)) {
  3773. Error(std::move(Err));
  3774. return Failure;
  3775. }
  3776. }
  3777. // Once read, set the ModuleFile bit base offset and update the size in
  3778. // bits of all files we've seen.
  3779. F.GlobalBitOffset = TotalModulesSizeInBits;
  3780. TotalModulesSizeInBits += F.SizeInBits;
  3781. GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
  3782. }
  3783. // Preload source locations and interesting indentifiers.
  3784. for (ImportedModule &M : Loaded) {
  3785. ModuleFile &F = *M.Mod;
  3786. // Preload SLocEntries.
  3787. for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
  3788. int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
  3789. // Load it through the SourceManager and don't call ReadSLocEntry()
  3790. // directly because the entry may have already been loaded in which case
  3791. // calling ReadSLocEntry() directly would trigger an assertion in
  3792. // SourceManager.
  3793. SourceMgr.getLoadedSLocEntryByID(Index);
  3794. }
  3795. // Map the original source file ID into the ID space of the current
  3796. // compilation.
  3797. if (F.OriginalSourceFileID.isValid())
  3798. F.OriginalSourceFileID = TranslateFileID(F, F.OriginalSourceFileID);
  3799. // Preload all the pending interesting identifiers by marking them out of
  3800. // date.
  3801. for (auto Offset : F.PreloadIdentifierOffsets) {
  3802. const unsigned char *Data = F.IdentifierTableData + Offset;
  3803. ASTIdentifierLookupTrait Trait(*this, F);
  3804. auto KeyDataLen = Trait.ReadKeyDataLength(Data);
  3805. auto Key = Trait.ReadKey(Data, KeyDataLen.first);
  3806. auto &II = PP.getIdentifierTable().getOwn(Key);
  3807. II.setOutOfDate(true);
  3808. // Mark this identifier as being from an AST file so that we can track
  3809. // whether we need to serialize it.
  3810. markIdentifierFromAST(*this, II);
  3811. // Associate the ID with the identifier so that the writer can reuse it.
  3812. auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
  3813. SetIdentifierInfo(ID, &II);
  3814. }
  3815. }
  3816. // Setup the import locations and notify the module manager that we've
  3817. // committed to these module files.
  3818. for (ImportedModule &M : Loaded) {
  3819. ModuleFile &F = *M.Mod;
  3820. ModuleMgr.moduleFileAccepted(&F);
  3821. // Set the import location.
  3822. F.DirectImportLoc = ImportLoc;
  3823. // FIXME: We assume that locations from PCH / preamble do not need
  3824. // any translation.
  3825. if (!M.ImportedBy)
  3826. F.ImportLoc = M.ImportLoc;
  3827. else
  3828. F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
  3829. }
  3830. if (!PP.getLangOpts().CPlusPlus ||
  3831. (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
  3832. Type != MK_PrebuiltModule)) {
  3833. // Mark all of the identifiers in the identifier table as being out of date,
  3834. // so that various accessors know to check the loaded modules when the
  3835. // identifier is used.
  3836. //
  3837. // For C++ modules, we don't need information on many identifiers (just
  3838. // those that provide macros or are poisoned), so we mark all of
  3839. // the interesting ones via PreloadIdentifierOffsets.
  3840. for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
  3841. IdEnd = PP.getIdentifierTable().end();
  3842. Id != IdEnd; ++Id)
  3843. Id->second->setOutOfDate(true);
  3844. }
  3845. // Mark selectors as out of date.
  3846. for (auto Sel : SelectorGeneration)
  3847. SelectorOutOfDate[Sel.first] = true;
  3848. // Resolve any unresolved module exports.
  3849. for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
  3850. UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
  3851. SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
  3852. Module *ResolvedMod = getSubmodule(GlobalID);
  3853. switch (Unresolved.Kind) {
  3854. case UnresolvedModuleRef::Conflict:
  3855. if (ResolvedMod) {
  3856. Module::Conflict Conflict;
  3857. Conflict.Other = ResolvedMod;
  3858. Conflict.Message = Unresolved.String.str();
  3859. Unresolved.Mod->Conflicts.push_back(Conflict);
  3860. }
  3861. continue;
  3862. case UnresolvedModuleRef::Import:
  3863. if (ResolvedMod)
  3864. Unresolved.Mod->Imports.insert(ResolvedMod);
  3865. continue;
  3866. case UnresolvedModuleRef::Affecting:
  3867. if (ResolvedMod)
  3868. Unresolved.Mod->AffectingClangModules.insert(ResolvedMod);
  3869. continue;
  3870. case UnresolvedModuleRef::Export:
  3871. if (ResolvedMod || Unresolved.IsWildcard)
  3872. Unresolved.Mod->Exports.push_back(
  3873. Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
  3874. continue;
  3875. }
  3876. }
  3877. UnresolvedModuleRefs.clear();
  3878. if (Imported)
  3879. Imported->append(ImportedModules.begin(),
  3880. ImportedModules.end());
  3881. // FIXME: How do we load the 'use'd modules? They may not be submodules.
  3882. // Might be unnecessary as use declarations are only used to build the
  3883. // module itself.
  3884. if (ContextObj)
  3885. InitializeContext();
  3886. if (SemaObj)
  3887. UpdateSema();
  3888. if (DeserializationListener)
  3889. DeserializationListener->ReaderInitialized(this);
  3890. ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
  3891. if (PrimaryModule.OriginalSourceFileID.isValid()) {
  3892. // If this AST file is a precompiled preamble, then set the
  3893. // preamble file ID of the source manager to the file source file
  3894. // from which the preamble was built.
  3895. if (Type == MK_Preamble) {
  3896. SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
  3897. } else if (Type == MK_MainFile) {
  3898. SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
  3899. }
  3900. }
  3901. // For any Objective-C class definitions we have already loaded, make sure
  3902. // that we load any additional categories.
  3903. if (ContextObj) {
  3904. for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
  3905. loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
  3906. ObjCClassesLoaded[I],
  3907. PreviousGeneration);
  3908. }
  3909. }
  3910. if (PP.getHeaderSearchInfo()
  3911. .getHeaderSearchOpts()
  3912. .ModulesValidateOncePerBuildSession) {
  3913. // Now we are certain that the module and all modules it depends on are
  3914. // up to date. Create or update timestamp files for modules that are
  3915. // located in the module cache (not for PCH files that could be anywhere
  3916. // in the filesystem).
  3917. for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
  3918. ImportedModule &M = Loaded[I];
  3919. if (M.Mod->Kind == MK_ImplicitModule) {
  3920. updateModuleTimestamp(*M.Mod);
  3921. }
  3922. }
  3923. }
  3924. return Success;
  3925. }
  3926. static ASTFileSignature readASTFileSignature(StringRef PCH);
  3927. /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
  3928. static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
  3929. // FIXME checking magic headers is done in other places such as
  3930. // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
  3931. // always done the same. Unify it all with a helper.
  3932. if (!Stream.canSkipToPos(4))
  3933. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3934. "file too small to contain AST file magic");
  3935. for (unsigned C : {'C', 'P', 'C', 'H'})
  3936. if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
  3937. if (Res.get() != C)
  3938. return llvm::createStringError(
  3939. std::errc::illegal_byte_sequence,
  3940. "file doesn't start with AST file magic");
  3941. } else
  3942. return Res.takeError();
  3943. return llvm::Error::success();
  3944. }
  3945. static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
  3946. switch (Kind) {
  3947. case MK_PCH:
  3948. return 0; // PCH
  3949. case MK_ImplicitModule:
  3950. case MK_ExplicitModule:
  3951. case MK_PrebuiltModule:
  3952. return 1; // module
  3953. case MK_MainFile:
  3954. case MK_Preamble:
  3955. return 2; // main source file
  3956. }
  3957. llvm_unreachable("unknown module kind");
  3958. }
  3959. ASTReader::ASTReadResult
  3960. ASTReader::ReadASTCore(StringRef FileName,
  3961. ModuleKind Type,
  3962. SourceLocation ImportLoc,
  3963. ModuleFile *ImportedBy,
  3964. SmallVectorImpl<ImportedModule> &Loaded,
  3965. off_t ExpectedSize, time_t ExpectedModTime,
  3966. ASTFileSignature ExpectedSignature,
  3967. unsigned ClientLoadCapabilities) {
  3968. ModuleFile *M;
  3969. std::string ErrorStr;
  3970. ModuleManager::AddModuleResult AddResult
  3971. = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
  3972. getGeneration(), ExpectedSize, ExpectedModTime,
  3973. ExpectedSignature, readASTFileSignature,
  3974. M, ErrorStr);
  3975. switch (AddResult) {
  3976. case ModuleManager::AlreadyLoaded:
  3977. Diag(diag::remark_module_import)
  3978. << M->ModuleName << M->FileName << (ImportedBy ? true : false)
  3979. << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
  3980. return Success;
  3981. case ModuleManager::NewlyLoaded:
  3982. // Load module file below.
  3983. break;
  3984. case ModuleManager::Missing:
  3985. // The module file was missing; if the client can handle that, return
  3986. // it.
  3987. if (ClientLoadCapabilities & ARR_Missing)
  3988. return Missing;
  3989. // Otherwise, return an error.
  3990. Diag(diag::err_ast_file_not_found)
  3991. << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
  3992. << ErrorStr;
  3993. return Failure;
  3994. case ModuleManager::OutOfDate:
  3995. // We couldn't load the module file because it is out-of-date. If the
  3996. // client can handle out-of-date, return it.
  3997. if (ClientLoadCapabilities & ARR_OutOfDate)
  3998. return OutOfDate;
  3999. // Otherwise, return an error.
  4000. Diag(diag::err_ast_file_out_of_date)
  4001. << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
  4002. << ErrorStr;
  4003. return Failure;
  4004. }
  4005. assert(M && "Missing module file");
  4006. bool ShouldFinalizePCM = false;
  4007. auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
  4008. auto &MC = getModuleManager().getModuleCache();
  4009. if (ShouldFinalizePCM)
  4010. MC.finalizePCM(FileName);
  4011. else
  4012. MC.tryToDropPCM(FileName);
  4013. });
  4014. ModuleFile &F = *M;
  4015. BitstreamCursor &Stream = F.Stream;
  4016. Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
  4017. F.SizeInBits = F.Buffer->getBufferSize() * 8;
  4018. // Sniff for the signature.
  4019. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  4020. Diag(diag::err_ast_file_invalid)
  4021. << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
  4022. return Failure;
  4023. }
  4024. // This is used for compatibility with older PCH formats.
  4025. bool HaveReadControlBlock = false;
  4026. while (true) {
  4027. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4028. if (!MaybeEntry) {
  4029. Error(MaybeEntry.takeError());
  4030. return Failure;
  4031. }
  4032. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4033. switch (Entry.Kind) {
  4034. case llvm::BitstreamEntry::Error:
  4035. case llvm::BitstreamEntry::Record:
  4036. case llvm::BitstreamEntry::EndBlock:
  4037. Error("invalid record at top-level of AST file");
  4038. return Failure;
  4039. case llvm::BitstreamEntry::SubBlock:
  4040. break;
  4041. }
  4042. switch (Entry.ID) {
  4043. case CONTROL_BLOCK_ID:
  4044. HaveReadControlBlock = true;
  4045. switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
  4046. case Success:
  4047. // Check that we didn't try to load a non-module AST file as a module.
  4048. //
  4049. // FIXME: Should we also perform the converse check? Loading a module as
  4050. // a PCH file sort of works, but it's a bit wonky.
  4051. if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
  4052. Type == MK_PrebuiltModule) &&
  4053. F.ModuleName.empty()) {
  4054. auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
  4055. if (Result != OutOfDate ||
  4056. (ClientLoadCapabilities & ARR_OutOfDate) == 0)
  4057. Diag(diag::err_module_file_not_module) << FileName;
  4058. return Result;
  4059. }
  4060. break;
  4061. case Failure: return Failure;
  4062. case Missing: return Missing;
  4063. case OutOfDate: return OutOfDate;
  4064. case VersionMismatch: return VersionMismatch;
  4065. case ConfigurationMismatch: return ConfigurationMismatch;
  4066. case HadErrors: return HadErrors;
  4067. }
  4068. break;
  4069. case AST_BLOCK_ID:
  4070. if (!HaveReadControlBlock) {
  4071. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  4072. Diag(diag::err_pch_version_too_old);
  4073. return VersionMismatch;
  4074. }
  4075. // Record that we've loaded this module.
  4076. Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
  4077. ShouldFinalizePCM = true;
  4078. return Success;
  4079. case UNHASHED_CONTROL_BLOCK_ID:
  4080. // This block is handled using look-ahead during ReadControlBlock. We
  4081. // shouldn't get here!
  4082. Error("malformed block record in AST file");
  4083. return Failure;
  4084. default:
  4085. if (llvm::Error Err = Stream.SkipBlock()) {
  4086. Error(std::move(Err));
  4087. return Failure;
  4088. }
  4089. break;
  4090. }
  4091. }
  4092. llvm_unreachable("unexpected break; expected return");
  4093. }
  4094. ASTReader::ASTReadResult
  4095. ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
  4096. unsigned ClientLoadCapabilities) {
  4097. const HeaderSearchOptions &HSOpts =
  4098. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  4099. bool AllowCompatibleConfigurationMismatch =
  4100. F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
  4101. bool DisableValidation = shouldDisableValidationForFile(F);
  4102. ASTReadResult Result = readUnhashedControlBlockImpl(
  4103. &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
  4104. Listener.get(),
  4105. WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
  4106. // If F was directly imported by another module, it's implicitly validated by
  4107. // the importing module.
  4108. if (DisableValidation || WasImportedBy ||
  4109. (AllowConfigurationMismatch && Result == ConfigurationMismatch))
  4110. return Success;
  4111. if (Result == Failure) {
  4112. Error("malformed block record in AST file");
  4113. return Failure;
  4114. }
  4115. if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
  4116. // If this module has already been finalized in the ModuleCache, we're stuck
  4117. // with it; we can only load a single version of each module.
  4118. //
  4119. // This can happen when a module is imported in two contexts: in one, as a
  4120. // user module; in another, as a system module (due to an import from
  4121. // another module marked with the [system] flag). It usually indicates a
  4122. // bug in the module map: this module should also be marked with [system].
  4123. //
  4124. // If -Wno-system-headers (the default), and the first import is as a
  4125. // system module, then validation will fail during the as-user import,
  4126. // since -Werror flags won't have been validated. However, it's reasonable
  4127. // to treat this consistently as a system module.
  4128. //
  4129. // If -Wsystem-headers, the PCM on disk was built with
  4130. // -Wno-system-headers, and the first import is as a user module, then
  4131. // validation will fail during the as-system import since the PCM on disk
  4132. // doesn't guarantee that -Werror was respected. However, the -Werror
  4133. // flags were checked during the initial as-user import.
  4134. if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
  4135. Diag(diag::warn_module_system_bit_conflict) << F.FileName;
  4136. return Success;
  4137. }
  4138. }
  4139. return Result;
  4140. }
  4141. ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
  4142. ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
  4143. bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
  4144. bool ValidateDiagnosticOptions) {
  4145. // Initialize a stream.
  4146. BitstreamCursor Stream(StreamData);
  4147. // Sniff for the signature.
  4148. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  4149. // FIXME this drops the error on the floor.
  4150. consumeError(std::move(Err));
  4151. return Failure;
  4152. }
  4153. // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
  4154. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
  4155. return Failure;
  4156. // Read all of the records in the options block.
  4157. RecordData Record;
  4158. ASTReadResult Result = Success;
  4159. while (true) {
  4160. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4161. if (!MaybeEntry) {
  4162. // FIXME this drops the error on the floor.
  4163. consumeError(MaybeEntry.takeError());
  4164. return Failure;
  4165. }
  4166. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4167. switch (Entry.Kind) {
  4168. case llvm::BitstreamEntry::Error:
  4169. case llvm::BitstreamEntry::SubBlock:
  4170. return Failure;
  4171. case llvm::BitstreamEntry::EndBlock:
  4172. return Result;
  4173. case llvm::BitstreamEntry::Record:
  4174. // The interesting case.
  4175. break;
  4176. }
  4177. // Read and process a record.
  4178. Record.clear();
  4179. StringRef Blob;
  4180. Expected<unsigned> MaybeRecordType =
  4181. Stream.readRecord(Entry.ID, Record, &Blob);
  4182. if (!MaybeRecordType) {
  4183. // FIXME this drops the error.
  4184. return Failure;
  4185. }
  4186. switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
  4187. case SIGNATURE:
  4188. if (F)
  4189. F->Signature = ASTFileSignature::create(Record.begin(), Record.end());
  4190. break;
  4191. case AST_BLOCK_HASH:
  4192. if (F)
  4193. F->ASTBlockHash =
  4194. ASTFileSignature::create(Record.begin(), Record.end());
  4195. break;
  4196. case DIAGNOSTIC_OPTIONS: {
  4197. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
  4198. if (Listener && ValidateDiagnosticOptions &&
  4199. !AllowCompatibleConfigurationMismatch &&
  4200. ParseDiagnosticOptions(Record, Complain, *Listener))
  4201. Result = OutOfDate; // Don't return early. Read the signature.
  4202. break;
  4203. }
  4204. case HEADER_SEARCH_PATHS: {
  4205. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  4206. if (!AllowCompatibleConfigurationMismatch &&
  4207. ParseHeaderSearchPaths(Record, Complain, *Listener))
  4208. Result = ConfigurationMismatch;
  4209. break;
  4210. }
  4211. case DIAG_PRAGMA_MAPPINGS:
  4212. if (!F)
  4213. break;
  4214. if (F->PragmaDiagMappings.empty())
  4215. F->PragmaDiagMappings.swap(Record);
  4216. else
  4217. F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
  4218. Record.begin(), Record.end());
  4219. break;
  4220. case HEADER_SEARCH_ENTRY_USAGE:
  4221. if (!F)
  4222. break;
  4223. unsigned Count = Record[0];
  4224. const char *Byte = Blob.data();
  4225. F->SearchPathUsage = llvm::BitVector(Count, false);
  4226. for (unsigned I = 0; I < Count; ++Byte)
  4227. for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
  4228. if (*Byte & (1 << Bit))
  4229. F->SearchPathUsage[I] = true;
  4230. break;
  4231. }
  4232. }
  4233. }
  4234. /// Parse a record and blob containing module file extension metadata.
  4235. static bool parseModuleFileExtensionMetadata(
  4236. const SmallVectorImpl<uint64_t> &Record,
  4237. StringRef Blob,
  4238. ModuleFileExtensionMetadata &Metadata) {
  4239. if (Record.size() < 4) return true;
  4240. Metadata.MajorVersion = Record[0];
  4241. Metadata.MinorVersion = Record[1];
  4242. unsigned BlockNameLen = Record[2];
  4243. unsigned UserInfoLen = Record[3];
  4244. if (BlockNameLen + UserInfoLen > Blob.size()) return true;
  4245. Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
  4246. Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
  4247. Blob.data() + BlockNameLen + UserInfoLen);
  4248. return false;
  4249. }
  4250. llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
  4251. BitstreamCursor &Stream = F.Stream;
  4252. RecordData Record;
  4253. while (true) {
  4254. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4255. if (!MaybeEntry)
  4256. return MaybeEntry.takeError();
  4257. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4258. switch (Entry.Kind) {
  4259. case llvm::BitstreamEntry::SubBlock:
  4260. if (llvm::Error Err = Stream.SkipBlock())
  4261. return Err;
  4262. continue;
  4263. case llvm::BitstreamEntry::EndBlock:
  4264. return llvm::Error::success();
  4265. case llvm::BitstreamEntry::Error:
  4266. return llvm::createStringError(std::errc::illegal_byte_sequence,
  4267. "malformed block record in AST file");
  4268. case llvm::BitstreamEntry::Record:
  4269. break;
  4270. }
  4271. Record.clear();
  4272. StringRef Blob;
  4273. Expected<unsigned> MaybeRecCode =
  4274. Stream.readRecord(Entry.ID, Record, &Blob);
  4275. if (!MaybeRecCode)
  4276. return MaybeRecCode.takeError();
  4277. switch (MaybeRecCode.get()) {
  4278. case EXTENSION_METADATA: {
  4279. ModuleFileExtensionMetadata Metadata;
  4280. if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
  4281. return llvm::createStringError(
  4282. std::errc::illegal_byte_sequence,
  4283. "malformed EXTENSION_METADATA in AST file");
  4284. // Find a module file extension with this block name.
  4285. auto Known = ModuleFileExtensions.find(Metadata.BlockName);
  4286. if (Known == ModuleFileExtensions.end()) break;
  4287. // Form a reader.
  4288. if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
  4289. F, Stream)) {
  4290. F.ExtensionReaders.push_back(std::move(Reader));
  4291. }
  4292. break;
  4293. }
  4294. }
  4295. }
  4296. return llvm::Error::success();
  4297. }
  4298. void ASTReader::InitializeContext() {
  4299. assert(ContextObj && "no context to initialize");
  4300. ASTContext &Context = *ContextObj;
  4301. // If there's a listener, notify them that we "read" the translation unit.
  4302. if (DeserializationListener)
  4303. DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
  4304. Context.getTranslationUnitDecl());
  4305. // FIXME: Find a better way to deal with collisions between these
  4306. // built-in types. Right now, we just ignore the problem.
  4307. // Load the special types.
  4308. if (SpecialTypes.size() >= NumSpecialTypeIDs) {
  4309. if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
  4310. if (!Context.CFConstantStringTypeDecl)
  4311. Context.setCFConstantStringType(GetType(String));
  4312. }
  4313. if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
  4314. QualType FileType = GetType(File);
  4315. if (FileType.isNull()) {
  4316. Error("FILE type is NULL");
  4317. return;
  4318. }
  4319. if (!Context.FILEDecl) {
  4320. if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
  4321. Context.setFILEDecl(Typedef->getDecl());
  4322. else {
  4323. const TagType *Tag = FileType->getAs<TagType>();
  4324. if (!Tag) {
  4325. Error("Invalid FILE type in AST file");
  4326. return;
  4327. }
  4328. Context.setFILEDecl(Tag->getDecl());
  4329. }
  4330. }
  4331. }
  4332. if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
  4333. QualType Jmp_bufType = GetType(Jmp_buf);
  4334. if (Jmp_bufType.isNull()) {
  4335. Error("jmp_buf type is NULL");
  4336. return;
  4337. }
  4338. if (!Context.jmp_bufDecl) {
  4339. if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
  4340. Context.setjmp_bufDecl(Typedef->getDecl());
  4341. else {
  4342. const TagType *Tag = Jmp_bufType->getAs<TagType>();
  4343. if (!Tag) {
  4344. Error("Invalid jmp_buf type in AST file");
  4345. return;
  4346. }
  4347. Context.setjmp_bufDecl(Tag->getDecl());
  4348. }
  4349. }
  4350. }
  4351. if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
  4352. QualType Sigjmp_bufType = GetType(Sigjmp_buf);
  4353. if (Sigjmp_bufType.isNull()) {
  4354. Error("sigjmp_buf type is NULL");
  4355. return;
  4356. }
  4357. if (!Context.sigjmp_bufDecl) {
  4358. if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
  4359. Context.setsigjmp_bufDecl(Typedef->getDecl());
  4360. else {
  4361. const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
  4362. assert(Tag && "Invalid sigjmp_buf type in AST file");
  4363. Context.setsigjmp_bufDecl(Tag->getDecl());
  4364. }
  4365. }
  4366. }
  4367. if (unsigned ObjCIdRedef
  4368. = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
  4369. if (Context.ObjCIdRedefinitionType.isNull())
  4370. Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
  4371. }
  4372. if (unsigned ObjCClassRedef
  4373. = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
  4374. if (Context.ObjCClassRedefinitionType.isNull())
  4375. Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
  4376. }
  4377. if (unsigned ObjCSelRedef
  4378. = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
  4379. if (Context.ObjCSelRedefinitionType.isNull())
  4380. Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
  4381. }
  4382. if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
  4383. QualType Ucontext_tType = GetType(Ucontext_t);
  4384. if (Ucontext_tType.isNull()) {
  4385. Error("ucontext_t type is NULL");
  4386. return;
  4387. }
  4388. if (!Context.ucontext_tDecl) {
  4389. if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
  4390. Context.setucontext_tDecl(Typedef->getDecl());
  4391. else {
  4392. const TagType *Tag = Ucontext_tType->getAs<TagType>();
  4393. assert(Tag && "Invalid ucontext_t type in AST file");
  4394. Context.setucontext_tDecl(Tag->getDecl());
  4395. }
  4396. }
  4397. }
  4398. }
  4399. ReadPragmaDiagnosticMappings(Context.getDiagnostics());
  4400. // If there were any CUDA special declarations, deserialize them.
  4401. if (!CUDASpecialDeclRefs.empty()) {
  4402. assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
  4403. Context.setcudaConfigureCallDecl(
  4404. cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
  4405. }
  4406. // Re-export any modules that were imported by a non-module AST file.
  4407. // FIXME: This does not make macro-only imports visible again.
  4408. for (auto &Import : ImportedModules) {
  4409. if (Module *Imported = getSubmodule(Import.ID)) {
  4410. makeModuleVisible(Imported, Module::AllVisible,
  4411. /*ImportLoc=*/Import.ImportLoc);
  4412. if (Import.ImportLoc.isValid())
  4413. PP.makeModuleVisible(Imported, Import.ImportLoc);
  4414. // This updates visibility for Preprocessor only. For Sema, which can be
  4415. // nullptr here, we do the same later, in UpdateSema().
  4416. }
  4417. }
  4418. }
  4419. void ASTReader::finalizeForWriting() {
  4420. // Nothing to do for now.
  4421. }
  4422. /// Reads and return the signature record from \p PCH's control block, or
  4423. /// else returns 0.
  4424. static ASTFileSignature readASTFileSignature(StringRef PCH) {
  4425. BitstreamCursor Stream(PCH);
  4426. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  4427. // FIXME this drops the error on the floor.
  4428. consumeError(std::move(Err));
  4429. return ASTFileSignature();
  4430. }
  4431. // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
  4432. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
  4433. return ASTFileSignature();
  4434. // Scan for SIGNATURE inside the diagnostic options block.
  4435. ASTReader::RecordData Record;
  4436. while (true) {
  4437. Expected<llvm::BitstreamEntry> MaybeEntry =
  4438. Stream.advanceSkippingSubblocks();
  4439. if (!MaybeEntry) {
  4440. // FIXME this drops the error on the floor.
  4441. consumeError(MaybeEntry.takeError());
  4442. return ASTFileSignature();
  4443. }
  4444. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4445. if (Entry.Kind != llvm::BitstreamEntry::Record)
  4446. return ASTFileSignature();
  4447. Record.clear();
  4448. StringRef Blob;
  4449. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
  4450. if (!MaybeRecord) {
  4451. // FIXME this drops the error on the floor.
  4452. consumeError(MaybeRecord.takeError());
  4453. return ASTFileSignature();
  4454. }
  4455. if (SIGNATURE == MaybeRecord.get())
  4456. return ASTFileSignature::create(Record.begin(),
  4457. Record.begin() + ASTFileSignature::size);
  4458. }
  4459. }
  4460. /// Retrieve the name of the original source file name
  4461. /// directly from the AST file, without actually loading the AST
  4462. /// file.
  4463. std::string ASTReader::getOriginalSourceFile(
  4464. const std::string &ASTFileName, FileManager &FileMgr,
  4465. const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
  4466. // Open the AST file.
  4467. auto Buffer = FileMgr.getBufferForFile(ASTFileName, /*IsVolatile=*/false,
  4468. /*RequiresNullTerminator=*/false);
  4469. if (!Buffer) {
  4470. Diags.Report(diag::err_fe_unable_to_read_pch_file)
  4471. << ASTFileName << Buffer.getError().message();
  4472. return std::string();
  4473. }
  4474. // Initialize the stream
  4475. BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
  4476. // Sniff for the signature.
  4477. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  4478. Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
  4479. return std::string();
  4480. }
  4481. // Scan for the CONTROL_BLOCK_ID block.
  4482. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
  4483. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  4484. return std::string();
  4485. }
  4486. // Scan for ORIGINAL_FILE inside the control block.
  4487. RecordData Record;
  4488. while (true) {
  4489. Expected<llvm::BitstreamEntry> MaybeEntry =
  4490. Stream.advanceSkippingSubblocks();
  4491. if (!MaybeEntry) {
  4492. // FIXME this drops errors on the floor.
  4493. consumeError(MaybeEntry.takeError());
  4494. return std::string();
  4495. }
  4496. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4497. if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
  4498. return std::string();
  4499. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  4500. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  4501. return std::string();
  4502. }
  4503. Record.clear();
  4504. StringRef Blob;
  4505. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
  4506. if (!MaybeRecord) {
  4507. // FIXME this drops the errors on the floor.
  4508. consumeError(MaybeRecord.takeError());
  4509. return std::string();
  4510. }
  4511. if (ORIGINAL_FILE == MaybeRecord.get())
  4512. return Blob.str();
  4513. }
  4514. }
  4515. namespace {
  4516. class SimplePCHValidator : public ASTReaderListener {
  4517. const LangOptions &ExistingLangOpts;
  4518. const TargetOptions &ExistingTargetOpts;
  4519. const PreprocessorOptions &ExistingPPOpts;
  4520. std::string ExistingModuleCachePath;
  4521. FileManager &FileMgr;
  4522. bool StrictOptionMatches;
  4523. public:
  4524. SimplePCHValidator(const LangOptions &ExistingLangOpts,
  4525. const TargetOptions &ExistingTargetOpts,
  4526. const PreprocessorOptions &ExistingPPOpts,
  4527. StringRef ExistingModuleCachePath, FileManager &FileMgr,
  4528. bool StrictOptionMatches)
  4529. : ExistingLangOpts(ExistingLangOpts),
  4530. ExistingTargetOpts(ExistingTargetOpts),
  4531. ExistingPPOpts(ExistingPPOpts),
  4532. ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr),
  4533. StrictOptionMatches(StrictOptionMatches) {}
  4534. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  4535. bool AllowCompatibleDifferences) override {
  4536. return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
  4537. AllowCompatibleDifferences);
  4538. }
  4539. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  4540. bool AllowCompatibleDifferences) override {
  4541. return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
  4542. AllowCompatibleDifferences);
  4543. }
  4544. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  4545. StringRef SpecificModuleCachePath,
  4546. bool Complain) override {
  4547. return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  4548. ExistingModuleCachePath, nullptr,
  4549. ExistingLangOpts, ExistingPPOpts);
  4550. }
  4551. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  4552. bool Complain,
  4553. std::string &SuggestedPredefines) override {
  4554. return checkPreprocessorOptions(
  4555. PPOpts, ExistingPPOpts, /*Diags=*/nullptr, FileMgr,
  4556. SuggestedPredefines, ExistingLangOpts,
  4557. StrictOptionMatches ? OptionValidateStrictMatches
  4558. : OptionValidateContradictions);
  4559. }
  4560. };
  4561. } // namespace
  4562. bool ASTReader::readASTFileControlBlock(
  4563. StringRef Filename, FileManager &FileMgr,
  4564. const InMemoryModuleCache &ModuleCache,
  4565. const PCHContainerReader &PCHContainerRdr, bool FindModuleFileExtensions,
  4566. ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
  4567. // Open the AST file.
  4568. std::unique_ptr<llvm::MemoryBuffer> OwnedBuffer;
  4569. llvm::MemoryBuffer *Buffer = ModuleCache.lookupPCM(Filename);
  4570. if (!Buffer) {
  4571. // FIXME: We should add the pcm to the InMemoryModuleCache if it could be
  4572. // read again later, but we do not have the context here to determine if it
  4573. // is safe to change the result of InMemoryModuleCache::getPCMState().
  4574. // FIXME: This allows use of the VFS; we do not allow use of the
  4575. // VFS when actually loading a module.
  4576. auto BufferOrErr = FileMgr.getBufferForFile(Filename);
  4577. if (!BufferOrErr)
  4578. return true;
  4579. OwnedBuffer = std::move(*BufferOrErr);
  4580. Buffer = OwnedBuffer.get();
  4581. }
  4582. // Initialize the stream
  4583. StringRef Bytes = PCHContainerRdr.ExtractPCH(*Buffer);
  4584. BitstreamCursor Stream(Bytes);
  4585. // Sniff for the signature.
  4586. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  4587. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  4588. return true;
  4589. }
  4590. // Scan for the CONTROL_BLOCK_ID block.
  4591. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
  4592. return true;
  4593. bool NeedsInputFiles = Listener.needsInputFileVisitation();
  4594. bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
  4595. bool NeedsImports = Listener.needsImportVisitation();
  4596. BitstreamCursor InputFilesCursor;
  4597. RecordData Record;
  4598. std::string ModuleDir;
  4599. bool DoneWithControlBlock = false;
  4600. while (!DoneWithControlBlock) {
  4601. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4602. if (!MaybeEntry) {
  4603. // FIXME this drops the error on the floor.
  4604. consumeError(MaybeEntry.takeError());
  4605. return true;
  4606. }
  4607. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4608. switch (Entry.Kind) {
  4609. case llvm::BitstreamEntry::SubBlock: {
  4610. switch (Entry.ID) {
  4611. case OPTIONS_BLOCK_ID: {
  4612. std::string IgnoredSuggestedPredefines;
  4613. if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
  4614. /*AllowCompatibleConfigurationMismatch*/ false,
  4615. Listener, IgnoredSuggestedPredefines) != Success)
  4616. return true;
  4617. break;
  4618. }
  4619. case INPUT_FILES_BLOCK_ID:
  4620. InputFilesCursor = Stream;
  4621. if (llvm::Error Err = Stream.SkipBlock()) {
  4622. // FIXME this drops the error on the floor.
  4623. consumeError(std::move(Err));
  4624. return true;
  4625. }
  4626. if (NeedsInputFiles &&
  4627. ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
  4628. return true;
  4629. break;
  4630. default:
  4631. if (llvm::Error Err = Stream.SkipBlock()) {
  4632. // FIXME this drops the error on the floor.
  4633. consumeError(std::move(Err));
  4634. return true;
  4635. }
  4636. break;
  4637. }
  4638. continue;
  4639. }
  4640. case llvm::BitstreamEntry::EndBlock:
  4641. DoneWithControlBlock = true;
  4642. break;
  4643. case llvm::BitstreamEntry::Error:
  4644. return true;
  4645. case llvm::BitstreamEntry::Record:
  4646. break;
  4647. }
  4648. if (DoneWithControlBlock) break;
  4649. Record.clear();
  4650. StringRef Blob;
  4651. Expected<unsigned> MaybeRecCode =
  4652. Stream.readRecord(Entry.ID, Record, &Blob);
  4653. if (!MaybeRecCode) {
  4654. // FIXME this drops the error.
  4655. return Failure;
  4656. }
  4657. switch ((ControlRecordTypes)MaybeRecCode.get()) {
  4658. case METADATA:
  4659. if (Record[0] != VERSION_MAJOR)
  4660. return true;
  4661. if (Listener.ReadFullVersionInformation(Blob))
  4662. return true;
  4663. break;
  4664. case MODULE_NAME:
  4665. Listener.ReadModuleName(Blob);
  4666. break;
  4667. case MODULE_DIRECTORY:
  4668. ModuleDir = std::string(Blob);
  4669. break;
  4670. case MODULE_MAP_FILE: {
  4671. unsigned Idx = 0;
  4672. auto Path = ReadString(Record, Idx);
  4673. ResolveImportedPath(Path, ModuleDir);
  4674. Listener.ReadModuleMapFile(Path);
  4675. break;
  4676. }
  4677. case INPUT_FILE_OFFSETS: {
  4678. if (!NeedsInputFiles)
  4679. break;
  4680. unsigned NumInputFiles = Record[0];
  4681. unsigned NumUserFiles = Record[1];
  4682. const llvm::support::unaligned_uint64_t *InputFileOffs =
  4683. (const llvm::support::unaligned_uint64_t *)Blob.data();
  4684. for (unsigned I = 0; I != NumInputFiles; ++I) {
  4685. // Go find this input file.
  4686. bool isSystemFile = I >= NumUserFiles;
  4687. if (isSystemFile && !NeedsSystemInputFiles)
  4688. break; // the rest are system input files
  4689. BitstreamCursor &Cursor = InputFilesCursor;
  4690. SavedStreamPosition SavedPosition(Cursor);
  4691. if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
  4692. // FIXME this drops errors on the floor.
  4693. consumeError(std::move(Err));
  4694. }
  4695. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  4696. if (!MaybeCode) {
  4697. // FIXME this drops errors on the floor.
  4698. consumeError(MaybeCode.takeError());
  4699. }
  4700. unsigned Code = MaybeCode.get();
  4701. RecordData Record;
  4702. StringRef Blob;
  4703. bool shouldContinue = false;
  4704. Expected<unsigned> MaybeRecordType =
  4705. Cursor.readRecord(Code, Record, &Blob);
  4706. if (!MaybeRecordType) {
  4707. // FIXME this drops errors on the floor.
  4708. consumeError(MaybeRecordType.takeError());
  4709. }
  4710. switch ((InputFileRecordTypes)MaybeRecordType.get()) {
  4711. case INPUT_FILE_HASH:
  4712. break;
  4713. case INPUT_FILE:
  4714. bool Overridden = static_cast<bool>(Record[3]);
  4715. std::string Filename = std::string(Blob);
  4716. ResolveImportedPath(Filename, ModuleDir);
  4717. shouldContinue = Listener.visitInputFile(
  4718. Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
  4719. break;
  4720. }
  4721. if (!shouldContinue)
  4722. break;
  4723. }
  4724. break;
  4725. }
  4726. case IMPORTS: {
  4727. if (!NeedsImports)
  4728. break;
  4729. unsigned Idx = 0, N = Record.size();
  4730. while (Idx < N) {
  4731. // Read information about the AST file.
  4732. Idx +=
  4733. 1 + 1 + 1 + 1 +
  4734. ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature
  4735. std::string ModuleName = ReadString(Record, Idx);
  4736. std::string Filename = ReadString(Record, Idx);
  4737. ResolveImportedPath(Filename, ModuleDir);
  4738. Listener.visitImport(ModuleName, Filename);
  4739. }
  4740. break;
  4741. }
  4742. default:
  4743. // No other validation to perform.
  4744. break;
  4745. }
  4746. }
  4747. // Look for module file extension blocks, if requested.
  4748. if (FindModuleFileExtensions) {
  4749. BitstreamCursor SavedStream = Stream;
  4750. while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
  4751. bool DoneWithExtensionBlock = false;
  4752. while (!DoneWithExtensionBlock) {
  4753. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4754. if (!MaybeEntry) {
  4755. // FIXME this drops the error.
  4756. return true;
  4757. }
  4758. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4759. switch (Entry.Kind) {
  4760. case llvm::BitstreamEntry::SubBlock:
  4761. if (llvm::Error Err = Stream.SkipBlock()) {
  4762. // FIXME this drops the error on the floor.
  4763. consumeError(std::move(Err));
  4764. return true;
  4765. }
  4766. continue;
  4767. case llvm::BitstreamEntry::EndBlock:
  4768. DoneWithExtensionBlock = true;
  4769. continue;
  4770. case llvm::BitstreamEntry::Error:
  4771. return true;
  4772. case llvm::BitstreamEntry::Record:
  4773. break;
  4774. }
  4775. Record.clear();
  4776. StringRef Blob;
  4777. Expected<unsigned> MaybeRecCode =
  4778. Stream.readRecord(Entry.ID, Record, &Blob);
  4779. if (!MaybeRecCode) {
  4780. // FIXME this drops the error.
  4781. return true;
  4782. }
  4783. switch (MaybeRecCode.get()) {
  4784. case EXTENSION_METADATA: {
  4785. ModuleFileExtensionMetadata Metadata;
  4786. if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
  4787. return true;
  4788. Listener.readModuleFileExtension(Metadata);
  4789. break;
  4790. }
  4791. }
  4792. }
  4793. }
  4794. Stream = SavedStream;
  4795. }
  4796. // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
  4797. if (readUnhashedControlBlockImpl(
  4798. nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
  4799. /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
  4800. ValidateDiagnosticOptions) != Success)
  4801. return true;
  4802. return false;
  4803. }
  4804. bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
  4805. const InMemoryModuleCache &ModuleCache,
  4806. const PCHContainerReader &PCHContainerRdr,
  4807. const LangOptions &LangOpts,
  4808. const TargetOptions &TargetOpts,
  4809. const PreprocessorOptions &PPOpts,
  4810. StringRef ExistingModuleCachePath,
  4811. bool RequireStrictOptionMatches) {
  4812. SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
  4813. ExistingModuleCachePath, FileMgr,
  4814. RequireStrictOptionMatches);
  4815. return !readASTFileControlBlock(Filename, FileMgr, ModuleCache,
  4816. PCHContainerRdr,
  4817. /*FindModuleFileExtensions=*/false, validator,
  4818. /*ValidateDiagnosticOptions=*/true);
  4819. }
  4820. llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
  4821. unsigned ClientLoadCapabilities) {
  4822. // Enter the submodule block.
  4823. if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
  4824. return Err;
  4825. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  4826. bool First = true;
  4827. Module *CurrentModule = nullptr;
  4828. RecordData Record;
  4829. while (true) {
  4830. Expected<llvm::BitstreamEntry> MaybeEntry =
  4831. F.Stream.advanceSkippingSubblocks();
  4832. if (!MaybeEntry)
  4833. return MaybeEntry.takeError();
  4834. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4835. switch (Entry.Kind) {
  4836. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  4837. case llvm::BitstreamEntry::Error:
  4838. return llvm::createStringError(std::errc::illegal_byte_sequence,
  4839. "malformed block record in AST file");
  4840. case llvm::BitstreamEntry::EndBlock:
  4841. return llvm::Error::success();
  4842. case llvm::BitstreamEntry::Record:
  4843. // The interesting case.
  4844. break;
  4845. }
  4846. // Read a record.
  4847. StringRef Blob;
  4848. Record.clear();
  4849. Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
  4850. if (!MaybeKind)
  4851. return MaybeKind.takeError();
  4852. unsigned Kind = MaybeKind.get();
  4853. if ((Kind == SUBMODULE_METADATA) != First)
  4854. return llvm::createStringError(
  4855. std::errc::illegal_byte_sequence,
  4856. "submodule metadata record should be at beginning of block");
  4857. First = false;
  4858. // Submodule information is only valid if we have a current module.
  4859. // FIXME: Should we error on these cases?
  4860. if (!CurrentModule && Kind != SUBMODULE_METADATA &&
  4861. Kind != SUBMODULE_DEFINITION)
  4862. continue;
  4863. switch (Kind) {
  4864. default: // Default behavior: ignore.
  4865. break;
  4866. case SUBMODULE_DEFINITION: {
  4867. if (Record.size() < 12)
  4868. return llvm::createStringError(std::errc::illegal_byte_sequence,
  4869. "malformed module definition");
  4870. StringRef Name = Blob;
  4871. unsigned Idx = 0;
  4872. SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
  4873. SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
  4874. Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
  4875. bool IsFramework = Record[Idx++];
  4876. bool IsExplicit = Record[Idx++];
  4877. bool IsSystem = Record[Idx++];
  4878. bool IsExternC = Record[Idx++];
  4879. bool InferSubmodules = Record[Idx++];
  4880. bool InferExplicitSubmodules = Record[Idx++];
  4881. bool InferExportWildcard = Record[Idx++];
  4882. bool ConfigMacrosExhaustive = Record[Idx++];
  4883. bool ModuleMapIsPrivate = Record[Idx++];
  4884. Module *ParentModule = nullptr;
  4885. if (Parent)
  4886. ParentModule = getSubmodule(Parent);
  4887. // Retrieve this (sub)module from the module map, creating it if
  4888. // necessary.
  4889. CurrentModule =
  4890. ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
  4891. .first;
  4892. // FIXME: set the definition loc for CurrentModule, or call
  4893. // ModMap.setInferredModuleAllowedBy()
  4894. SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
  4895. if (GlobalIndex >= SubmodulesLoaded.size() ||
  4896. SubmodulesLoaded[GlobalIndex])
  4897. return llvm::createStringError(std::errc::invalid_argument,
  4898. "too many submodules");
  4899. if (!ParentModule) {
  4900. if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
  4901. // Don't emit module relocation error if we have -fno-validate-pch
  4902. if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
  4903. DisableValidationForModuleKind::Module) &&
  4904. CurFile != F.File) {
  4905. auto ConflictError =
  4906. PartialDiagnostic(diag::err_module_file_conflict,
  4907. ContextObj->DiagAllocator)
  4908. << CurrentModule->getTopLevelModuleName() << CurFile->getName()
  4909. << F.File->getName();
  4910. return DiagnosticError::create(CurrentImportLoc, ConflictError);
  4911. }
  4912. }
  4913. F.DidReadTopLevelSubmodule = true;
  4914. CurrentModule->setASTFile(F.File);
  4915. CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
  4916. }
  4917. CurrentModule->Kind = Kind;
  4918. CurrentModule->Signature = F.Signature;
  4919. CurrentModule->IsFromModuleFile = true;
  4920. CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
  4921. CurrentModule->IsExternC = IsExternC;
  4922. CurrentModule->InferSubmodules = InferSubmodules;
  4923. CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
  4924. CurrentModule->InferExportWildcard = InferExportWildcard;
  4925. CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
  4926. CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
  4927. if (DeserializationListener)
  4928. DeserializationListener->ModuleRead(GlobalID, CurrentModule);
  4929. SubmodulesLoaded[GlobalIndex] = CurrentModule;
  4930. // Clear out data that will be replaced by what is in the module file.
  4931. CurrentModule->LinkLibraries.clear();
  4932. CurrentModule->ConfigMacros.clear();
  4933. CurrentModule->UnresolvedConflicts.clear();
  4934. CurrentModule->Conflicts.clear();
  4935. // The module is available unless it's missing a requirement; relevant
  4936. // requirements will be (re-)added by SUBMODULE_REQUIRES records.
  4937. // Missing headers that were present when the module was built do not
  4938. // make it unavailable -- if we got this far, this must be an explicitly
  4939. // imported module file.
  4940. CurrentModule->Requirements.clear();
  4941. CurrentModule->MissingHeaders.clear();
  4942. CurrentModule->IsUnimportable =
  4943. ParentModule && ParentModule->IsUnimportable;
  4944. CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
  4945. break;
  4946. }
  4947. case SUBMODULE_UMBRELLA_HEADER: {
  4948. // FIXME: This doesn't work for framework modules as `Filename` is the
  4949. // name as written in the module file and does not include
  4950. // `Headers/`, so this path will never exist.
  4951. std::string Filename = std::string(Blob);
  4952. ResolveImportedPath(F, Filename);
  4953. if (auto Umbrella = PP.getFileManager().getOptionalFileRef(Filename)) {
  4954. if (!CurrentModule->getUmbrellaHeader()) {
  4955. // FIXME: NameAsWritten
  4956. ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
  4957. }
  4958. // Note that it's too late at this point to return out of date if the
  4959. // name from the PCM doesn't match up with the one in the module map,
  4960. // but also quite unlikely since we will have already checked the
  4961. // modification time and size of the module map file itself.
  4962. }
  4963. break;
  4964. }
  4965. case SUBMODULE_HEADER:
  4966. case SUBMODULE_EXCLUDED_HEADER:
  4967. case SUBMODULE_PRIVATE_HEADER:
  4968. // We lazily associate headers with their modules via the HeaderInfo table.
  4969. // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
  4970. // of complete filenames or remove it entirely.
  4971. break;
  4972. case SUBMODULE_TEXTUAL_HEADER:
  4973. case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
  4974. // FIXME: Textual headers are not marked in the HeaderInfo table. Load
  4975. // them here.
  4976. break;
  4977. case SUBMODULE_TOPHEADER: {
  4978. std::string HeaderName(Blob);
  4979. ResolveImportedPath(F, HeaderName);
  4980. CurrentModule->addTopHeaderFilename(HeaderName);
  4981. break;
  4982. }
  4983. case SUBMODULE_UMBRELLA_DIR: {
  4984. // See comments in SUBMODULE_UMBRELLA_HEADER
  4985. std::string Dirname = std::string(Blob);
  4986. ResolveImportedPath(F, Dirname);
  4987. if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
  4988. if (!CurrentModule->getUmbrellaDir()) {
  4989. // FIXME: NameAsWritten
  4990. ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
  4991. }
  4992. }
  4993. break;
  4994. }
  4995. case SUBMODULE_METADATA: {
  4996. F.BaseSubmoduleID = getTotalNumSubmodules();
  4997. F.LocalNumSubmodules = Record[0];
  4998. unsigned LocalBaseSubmoduleID = Record[1];
  4999. if (F.LocalNumSubmodules > 0) {
  5000. // Introduce the global -> local mapping for submodules within this
  5001. // module.
  5002. GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
  5003. // Introduce the local -> global mapping for submodules within this
  5004. // module.
  5005. F.SubmoduleRemap.insertOrReplace(
  5006. std::make_pair(LocalBaseSubmoduleID,
  5007. F.BaseSubmoduleID - LocalBaseSubmoduleID));
  5008. SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
  5009. }
  5010. break;
  5011. }
  5012. case SUBMODULE_IMPORTS:
  5013. for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
  5014. UnresolvedModuleRef Unresolved;
  5015. Unresolved.File = &F;
  5016. Unresolved.Mod = CurrentModule;
  5017. Unresolved.ID = Record[Idx];
  5018. Unresolved.Kind = UnresolvedModuleRef::Import;
  5019. Unresolved.IsWildcard = false;
  5020. UnresolvedModuleRefs.push_back(Unresolved);
  5021. }
  5022. break;
  5023. case SUBMODULE_AFFECTING_MODULES:
  5024. for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
  5025. UnresolvedModuleRef Unresolved;
  5026. Unresolved.File = &F;
  5027. Unresolved.Mod = CurrentModule;
  5028. Unresolved.ID = Record[Idx];
  5029. Unresolved.Kind = UnresolvedModuleRef::Affecting;
  5030. Unresolved.IsWildcard = false;
  5031. UnresolvedModuleRefs.push_back(Unresolved);
  5032. }
  5033. break;
  5034. case SUBMODULE_EXPORTS:
  5035. for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
  5036. UnresolvedModuleRef Unresolved;
  5037. Unresolved.File = &F;
  5038. Unresolved.Mod = CurrentModule;
  5039. Unresolved.ID = Record[Idx];
  5040. Unresolved.Kind = UnresolvedModuleRef::Export;
  5041. Unresolved.IsWildcard = Record[Idx + 1];
  5042. UnresolvedModuleRefs.push_back(Unresolved);
  5043. }
  5044. // Once we've loaded the set of exports, there's no reason to keep
  5045. // the parsed, unresolved exports around.
  5046. CurrentModule->UnresolvedExports.clear();
  5047. break;
  5048. case SUBMODULE_REQUIRES:
  5049. CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
  5050. PP.getTargetInfo());
  5051. break;
  5052. case SUBMODULE_LINK_LIBRARY:
  5053. ModMap.resolveLinkAsDependencies(CurrentModule);
  5054. CurrentModule->LinkLibraries.push_back(
  5055. Module::LinkLibrary(std::string(Blob), Record[0]));
  5056. break;
  5057. case SUBMODULE_CONFIG_MACRO:
  5058. CurrentModule->ConfigMacros.push_back(Blob.str());
  5059. break;
  5060. case SUBMODULE_CONFLICT: {
  5061. UnresolvedModuleRef Unresolved;
  5062. Unresolved.File = &F;
  5063. Unresolved.Mod = CurrentModule;
  5064. Unresolved.ID = Record[0];
  5065. Unresolved.Kind = UnresolvedModuleRef::Conflict;
  5066. Unresolved.IsWildcard = false;
  5067. Unresolved.String = Blob;
  5068. UnresolvedModuleRefs.push_back(Unresolved);
  5069. break;
  5070. }
  5071. case SUBMODULE_INITIALIZERS: {
  5072. if (!ContextObj)
  5073. break;
  5074. SmallVector<uint32_t, 16> Inits;
  5075. for (auto &ID : Record)
  5076. Inits.push_back(getGlobalDeclID(F, ID));
  5077. ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
  5078. break;
  5079. }
  5080. case SUBMODULE_EXPORT_AS:
  5081. CurrentModule->ExportAsModule = Blob.str();
  5082. ModMap.addLinkAsDependency(CurrentModule);
  5083. break;
  5084. }
  5085. }
  5086. }
  5087. /// Parse the record that corresponds to a LangOptions data
  5088. /// structure.
  5089. ///
  5090. /// This routine parses the language options from the AST file and then gives
  5091. /// them to the AST listener if one is set.
  5092. ///
  5093. /// \returns true if the listener deems the file unacceptable, false otherwise.
  5094. bool ASTReader::ParseLanguageOptions(const RecordData &Record,
  5095. bool Complain,
  5096. ASTReaderListener &Listener,
  5097. bool AllowCompatibleDifferences) {
  5098. LangOptions LangOpts;
  5099. unsigned Idx = 0;
  5100. #define LANGOPT(Name, Bits, Default, Description) \
  5101. LangOpts.Name = Record[Idx++];
  5102. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  5103. LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
  5104. #include "clang/Basic/LangOptions.def"
  5105. #define SANITIZER(NAME, ID) \
  5106. LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
  5107. #include "clang/Basic/Sanitizers.def"
  5108. for (unsigned N = Record[Idx++]; N; --N)
  5109. LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
  5110. ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
  5111. VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
  5112. LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
  5113. LangOpts.CurrentModule = ReadString(Record, Idx);
  5114. // Comment options.
  5115. for (unsigned N = Record[Idx++]; N; --N) {
  5116. LangOpts.CommentOpts.BlockCommandNames.push_back(
  5117. ReadString(Record, Idx));
  5118. }
  5119. LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
  5120. // OpenMP offloading options.
  5121. for (unsigned N = Record[Idx++]; N; --N) {
  5122. LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
  5123. }
  5124. LangOpts.OMPHostIRFile = ReadString(Record, Idx);
  5125. return Listener.ReadLanguageOptions(LangOpts, Complain,
  5126. AllowCompatibleDifferences);
  5127. }
  5128. bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
  5129. ASTReaderListener &Listener,
  5130. bool AllowCompatibleDifferences) {
  5131. unsigned Idx = 0;
  5132. TargetOptions TargetOpts;
  5133. TargetOpts.Triple = ReadString(Record, Idx);
  5134. TargetOpts.CPU = ReadString(Record, Idx);
  5135. TargetOpts.TuneCPU = ReadString(Record, Idx);
  5136. TargetOpts.ABI = ReadString(Record, Idx);
  5137. for (unsigned N = Record[Idx++]; N; --N) {
  5138. TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
  5139. }
  5140. for (unsigned N = Record[Idx++]; N; --N) {
  5141. TargetOpts.Features.push_back(ReadString(Record, Idx));
  5142. }
  5143. return Listener.ReadTargetOptions(TargetOpts, Complain,
  5144. AllowCompatibleDifferences);
  5145. }
  5146. bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
  5147. ASTReaderListener &Listener) {
  5148. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
  5149. unsigned Idx = 0;
  5150. #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
  5151. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  5152. DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
  5153. #include "clang/Basic/DiagnosticOptions.def"
  5154. for (unsigned N = Record[Idx++]; N; --N)
  5155. DiagOpts->Warnings.push_back(ReadString(Record, Idx));
  5156. for (unsigned N = Record[Idx++]; N; --N)
  5157. DiagOpts->Remarks.push_back(ReadString(Record, Idx));
  5158. return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
  5159. }
  5160. bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
  5161. ASTReaderListener &Listener) {
  5162. FileSystemOptions FSOpts;
  5163. unsigned Idx = 0;
  5164. FSOpts.WorkingDir = ReadString(Record, Idx);
  5165. return Listener.ReadFileSystemOptions(FSOpts, Complain);
  5166. }
  5167. bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
  5168. bool Complain,
  5169. ASTReaderListener &Listener) {
  5170. HeaderSearchOptions HSOpts;
  5171. unsigned Idx = 0;
  5172. HSOpts.Sysroot = ReadString(Record, Idx);
  5173. HSOpts.ResourceDir = ReadString(Record, Idx);
  5174. HSOpts.ModuleCachePath = ReadString(Record, Idx);
  5175. HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
  5176. HSOpts.DisableModuleHash = Record[Idx++];
  5177. HSOpts.ImplicitModuleMaps = Record[Idx++];
  5178. HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
  5179. HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
  5180. HSOpts.UseBuiltinIncludes = Record[Idx++];
  5181. HSOpts.UseStandardSystemIncludes = Record[Idx++];
  5182. HSOpts.UseStandardCXXIncludes = Record[Idx++];
  5183. HSOpts.UseLibcxx = Record[Idx++];
  5184. std::string SpecificModuleCachePath = ReadString(Record, Idx);
  5185. return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  5186. Complain);
  5187. }
  5188. bool ASTReader::ParseHeaderSearchPaths(const RecordData &Record, bool Complain,
  5189. ASTReaderListener &Listener) {
  5190. HeaderSearchOptions HSOpts;
  5191. unsigned Idx = 0;
  5192. // Include entries.
  5193. for (unsigned N = Record[Idx++]; N; --N) {
  5194. std::string Path = ReadString(Record, Idx);
  5195. frontend::IncludeDirGroup Group
  5196. = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
  5197. bool IsFramework = Record[Idx++];
  5198. bool IgnoreSysRoot = Record[Idx++];
  5199. HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
  5200. IgnoreSysRoot);
  5201. }
  5202. // System header prefixes.
  5203. for (unsigned N = Record[Idx++]; N; --N) {
  5204. std::string Prefix = ReadString(Record, Idx);
  5205. bool IsSystemHeader = Record[Idx++];
  5206. HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
  5207. }
  5208. // VFS overlay files.
  5209. for (unsigned N = Record[Idx++]; N; --N) {
  5210. std::string VFSOverlayFile = ReadString(Record, Idx);
  5211. HSOpts.VFSOverlayFiles.emplace_back(std::move(VFSOverlayFile));
  5212. }
  5213. return Listener.ReadHeaderSearchPaths(HSOpts, Complain);
  5214. }
  5215. bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
  5216. bool Complain,
  5217. ASTReaderListener &Listener,
  5218. std::string &SuggestedPredefines) {
  5219. PreprocessorOptions PPOpts;
  5220. unsigned Idx = 0;
  5221. // Macro definitions/undefs
  5222. for (unsigned N = Record[Idx++]; N; --N) {
  5223. std::string Macro = ReadString(Record, Idx);
  5224. bool IsUndef = Record[Idx++];
  5225. PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
  5226. }
  5227. // Includes
  5228. for (unsigned N = Record[Idx++]; N; --N) {
  5229. PPOpts.Includes.push_back(ReadString(Record, Idx));
  5230. }
  5231. // Macro Includes
  5232. for (unsigned N = Record[Idx++]; N; --N) {
  5233. PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
  5234. }
  5235. PPOpts.UsePredefines = Record[Idx++];
  5236. PPOpts.DetailedRecord = Record[Idx++];
  5237. PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
  5238. PPOpts.ObjCXXARCStandardLibrary =
  5239. static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
  5240. SuggestedPredefines.clear();
  5241. return Listener.ReadPreprocessorOptions(PPOpts, Complain,
  5242. SuggestedPredefines);
  5243. }
  5244. std::pair<ModuleFile *, unsigned>
  5245. ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
  5246. GlobalPreprocessedEntityMapType::iterator
  5247. I = GlobalPreprocessedEntityMap.find(GlobalIndex);
  5248. assert(I != GlobalPreprocessedEntityMap.end() &&
  5249. "Corrupted global preprocessed entity map");
  5250. ModuleFile *M = I->second;
  5251. unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
  5252. return std::make_pair(M, LocalIndex);
  5253. }
  5254. llvm::iterator_range<PreprocessingRecord::iterator>
  5255. ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
  5256. if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
  5257. return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
  5258. Mod.NumPreprocessedEntities);
  5259. return llvm::make_range(PreprocessingRecord::iterator(),
  5260. PreprocessingRecord::iterator());
  5261. }
  5262. bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
  5263. unsigned int ClientLoadCapabilities) {
  5264. return ClientLoadCapabilities & ARR_OutOfDate &&
  5265. !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
  5266. }
  5267. llvm::iterator_range<ASTReader::ModuleDeclIterator>
  5268. ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
  5269. return llvm::make_range(
  5270. ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
  5271. ModuleDeclIterator(this, &Mod,
  5272. Mod.FileSortedDecls + Mod.NumFileSortedDecls));
  5273. }
  5274. SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
  5275. auto I = GlobalSkippedRangeMap.find(GlobalIndex);
  5276. assert(I != GlobalSkippedRangeMap.end() &&
  5277. "Corrupted global skipped range map");
  5278. ModuleFile *M = I->second;
  5279. unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
  5280. assert(LocalIndex < M->NumPreprocessedSkippedRanges);
  5281. PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
  5282. SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
  5283. TranslateSourceLocation(*M, RawRange.getEnd()));
  5284. assert(Range.isValid());
  5285. return Range;
  5286. }
  5287. PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
  5288. PreprocessedEntityID PPID = Index+1;
  5289. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  5290. ModuleFile &M = *PPInfo.first;
  5291. unsigned LocalIndex = PPInfo.second;
  5292. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  5293. if (!PP.getPreprocessingRecord()) {
  5294. Error("no preprocessing record");
  5295. return nullptr;
  5296. }
  5297. SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
  5298. if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
  5299. M.MacroOffsetsBase + PPOffs.BitOffset)) {
  5300. Error(std::move(Err));
  5301. return nullptr;
  5302. }
  5303. Expected<llvm::BitstreamEntry> MaybeEntry =
  5304. M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  5305. if (!MaybeEntry) {
  5306. Error(MaybeEntry.takeError());
  5307. return nullptr;
  5308. }
  5309. llvm::BitstreamEntry Entry = MaybeEntry.get();
  5310. if (Entry.Kind != llvm::BitstreamEntry::Record)
  5311. return nullptr;
  5312. // Read the record.
  5313. SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
  5314. TranslateSourceLocation(M, PPOffs.getEnd()));
  5315. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  5316. StringRef Blob;
  5317. RecordData Record;
  5318. Expected<unsigned> MaybeRecType =
  5319. M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
  5320. if (!MaybeRecType) {
  5321. Error(MaybeRecType.takeError());
  5322. return nullptr;
  5323. }
  5324. switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
  5325. case PPD_MACRO_EXPANSION: {
  5326. bool isBuiltin = Record[0];
  5327. IdentifierInfo *Name = nullptr;
  5328. MacroDefinitionRecord *Def = nullptr;
  5329. if (isBuiltin)
  5330. Name = getLocalIdentifier(M, Record[1]);
  5331. else {
  5332. PreprocessedEntityID GlobalID =
  5333. getGlobalPreprocessedEntityID(M, Record[1]);
  5334. Def = cast<MacroDefinitionRecord>(
  5335. PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
  5336. }
  5337. MacroExpansion *ME;
  5338. if (isBuiltin)
  5339. ME = new (PPRec) MacroExpansion(Name, Range);
  5340. else
  5341. ME = new (PPRec) MacroExpansion(Def, Range);
  5342. return ME;
  5343. }
  5344. case PPD_MACRO_DEFINITION: {
  5345. // Decode the identifier info and then check again; if the macro is
  5346. // still defined and associated with the identifier,
  5347. IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
  5348. MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
  5349. if (DeserializationListener)
  5350. DeserializationListener->MacroDefinitionRead(PPID, MD);
  5351. return MD;
  5352. }
  5353. case PPD_INCLUSION_DIRECTIVE: {
  5354. const char *FullFileNameStart = Blob.data() + Record[0];
  5355. StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
  5356. OptionalFileEntryRef File;
  5357. if (!FullFileName.empty())
  5358. File = PP.getFileManager().getOptionalFileRef(FullFileName);
  5359. // FIXME: Stable encoding
  5360. InclusionDirective::InclusionKind Kind
  5361. = static_cast<InclusionDirective::InclusionKind>(Record[2]);
  5362. InclusionDirective *ID
  5363. = new (PPRec) InclusionDirective(PPRec, Kind,
  5364. StringRef(Blob.data(), Record[0]),
  5365. Record[1], Record[3],
  5366. File,
  5367. Range);
  5368. return ID;
  5369. }
  5370. }
  5371. llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
  5372. }
  5373. /// Find the next module that contains entities and return the ID
  5374. /// of the first entry.
  5375. ///
  5376. /// \param SLocMapI points at a chunk of a module that contains no
  5377. /// preprocessed entities or the entities it contains are not the ones we are
  5378. /// looking for.
  5379. PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
  5380. GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
  5381. ++SLocMapI;
  5382. for (GlobalSLocOffsetMapType::const_iterator
  5383. EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
  5384. ModuleFile &M = *SLocMapI->second;
  5385. if (M.NumPreprocessedEntities)
  5386. return M.BasePreprocessedEntityID;
  5387. }
  5388. return getTotalNumPreprocessedEntities();
  5389. }
  5390. namespace {
  5391. struct PPEntityComp {
  5392. const ASTReader &Reader;
  5393. ModuleFile &M;
  5394. PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
  5395. bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
  5396. SourceLocation LHS = getLoc(L);
  5397. SourceLocation RHS = getLoc(R);
  5398. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5399. }
  5400. bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
  5401. SourceLocation LHS = getLoc(L);
  5402. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5403. }
  5404. bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
  5405. SourceLocation RHS = getLoc(R);
  5406. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5407. }
  5408. SourceLocation getLoc(const PPEntityOffset &PPE) const {
  5409. return Reader.TranslateSourceLocation(M, PPE.getBegin());
  5410. }
  5411. };
  5412. } // namespace
  5413. PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
  5414. bool EndsAfter) const {
  5415. if (SourceMgr.isLocalSourceLocation(Loc))
  5416. return getTotalNumPreprocessedEntities();
  5417. GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
  5418. SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
  5419. assert(SLocMapI != GlobalSLocOffsetMap.end() &&
  5420. "Corrupted global sloc offset map");
  5421. if (SLocMapI->second->NumPreprocessedEntities == 0)
  5422. return findNextPreprocessedEntity(SLocMapI);
  5423. ModuleFile &M = *SLocMapI->second;
  5424. using pp_iterator = const PPEntityOffset *;
  5425. pp_iterator pp_begin = M.PreprocessedEntityOffsets;
  5426. pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
  5427. size_t Count = M.NumPreprocessedEntities;
  5428. size_t Half;
  5429. pp_iterator First = pp_begin;
  5430. pp_iterator PPI;
  5431. if (EndsAfter) {
  5432. PPI = std::upper_bound(pp_begin, pp_end, Loc,
  5433. PPEntityComp(*this, M));
  5434. } else {
  5435. // Do a binary search manually instead of using std::lower_bound because
  5436. // The end locations of entities may be unordered (when a macro expansion
  5437. // is inside another macro argument), but for this case it is not important
  5438. // whether we get the first macro expansion or its containing macro.
  5439. while (Count > 0) {
  5440. Half = Count / 2;
  5441. PPI = First;
  5442. std::advance(PPI, Half);
  5443. if (SourceMgr.isBeforeInTranslationUnit(
  5444. TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
  5445. First = PPI;
  5446. ++First;
  5447. Count = Count - Half - 1;
  5448. } else
  5449. Count = Half;
  5450. }
  5451. }
  5452. if (PPI == pp_end)
  5453. return findNextPreprocessedEntity(SLocMapI);
  5454. return M.BasePreprocessedEntityID + (PPI - pp_begin);
  5455. }
  5456. /// Returns a pair of [Begin, End) indices of preallocated
  5457. /// preprocessed entities that \arg Range encompasses.
  5458. std::pair<unsigned, unsigned>
  5459. ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
  5460. if (Range.isInvalid())
  5461. return std::make_pair(0,0);
  5462. assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
  5463. PreprocessedEntityID BeginID =
  5464. findPreprocessedEntity(Range.getBegin(), false);
  5465. PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
  5466. return std::make_pair(BeginID, EndID);
  5467. }
  5468. /// Optionally returns true or false if the preallocated preprocessed
  5469. /// entity with index \arg Index came from file \arg FID.
  5470. std::optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
  5471. FileID FID) {
  5472. if (FID.isInvalid())
  5473. return false;
  5474. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  5475. ModuleFile &M = *PPInfo.first;
  5476. unsigned LocalIndex = PPInfo.second;
  5477. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  5478. SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
  5479. if (Loc.isInvalid())
  5480. return false;
  5481. if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
  5482. return true;
  5483. else
  5484. return false;
  5485. }
  5486. namespace {
  5487. /// Visitor used to search for information about a header file.
  5488. class HeaderFileInfoVisitor {
  5489. const FileEntry *FE;
  5490. std::optional<HeaderFileInfo> HFI;
  5491. public:
  5492. explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
  5493. bool operator()(ModuleFile &M) {
  5494. HeaderFileInfoLookupTable *Table
  5495. = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
  5496. if (!Table)
  5497. return false;
  5498. // Look in the on-disk hash table for an entry for this file name.
  5499. HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
  5500. if (Pos == Table->end())
  5501. return false;
  5502. HFI = *Pos;
  5503. return true;
  5504. }
  5505. std::optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
  5506. };
  5507. } // namespace
  5508. HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
  5509. HeaderFileInfoVisitor Visitor(FE);
  5510. ModuleMgr.visit(Visitor);
  5511. if (std::optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
  5512. return *HFI;
  5513. return HeaderFileInfo();
  5514. }
  5515. void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
  5516. using DiagState = DiagnosticsEngine::DiagState;
  5517. SmallVector<DiagState *, 32> DiagStates;
  5518. for (ModuleFile &F : ModuleMgr) {
  5519. unsigned Idx = 0;
  5520. auto &Record = F.PragmaDiagMappings;
  5521. if (Record.empty())
  5522. continue;
  5523. DiagStates.clear();
  5524. auto ReadDiagState = [&](const DiagState &BasedOn,
  5525. bool IncludeNonPragmaStates) {
  5526. unsigned BackrefID = Record[Idx++];
  5527. if (BackrefID != 0)
  5528. return DiagStates[BackrefID - 1];
  5529. // A new DiagState was created here.
  5530. Diag.DiagStates.push_back(BasedOn);
  5531. DiagState *NewState = &Diag.DiagStates.back();
  5532. DiagStates.push_back(NewState);
  5533. unsigned Size = Record[Idx++];
  5534. assert(Idx + Size * 2 <= Record.size() &&
  5535. "Invalid data, not enough diag/map pairs");
  5536. while (Size--) {
  5537. unsigned DiagID = Record[Idx++];
  5538. DiagnosticMapping NewMapping =
  5539. DiagnosticMapping::deserialize(Record[Idx++]);
  5540. if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
  5541. continue;
  5542. DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
  5543. // If this mapping was specified as a warning but the severity was
  5544. // upgraded due to diagnostic settings, simulate the current diagnostic
  5545. // settings (and use a warning).
  5546. if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
  5547. NewMapping.setSeverity(diag::Severity::Warning);
  5548. NewMapping.setUpgradedFromWarning(false);
  5549. }
  5550. Mapping = NewMapping;
  5551. }
  5552. return NewState;
  5553. };
  5554. // Read the first state.
  5555. DiagState *FirstState;
  5556. if (F.Kind == MK_ImplicitModule) {
  5557. // Implicitly-built modules are reused with different diagnostic
  5558. // settings. Use the initial diagnostic state from Diag to simulate this
  5559. // compilation's diagnostic settings.
  5560. FirstState = Diag.DiagStatesByLoc.FirstDiagState;
  5561. DiagStates.push_back(FirstState);
  5562. // Skip the initial diagnostic state from the serialized module.
  5563. assert(Record[1] == 0 &&
  5564. "Invalid data, unexpected backref in initial state");
  5565. Idx = 3 + Record[2] * 2;
  5566. assert(Idx < Record.size() &&
  5567. "Invalid data, not enough state change pairs in initial state");
  5568. } else if (F.isModule()) {
  5569. // For an explicit module, preserve the flags from the module build
  5570. // command line (-w, -Weverything, -Werror, ...) along with any explicit
  5571. // -Wblah flags.
  5572. unsigned Flags = Record[Idx++];
  5573. DiagState Initial;
  5574. Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
  5575. Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
  5576. Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
  5577. Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
  5578. Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
  5579. Initial.ExtBehavior = (diag::Severity)Flags;
  5580. FirstState = ReadDiagState(Initial, true);
  5581. assert(F.OriginalSourceFileID.isValid());
  5582. // Set up the root buffer of the module to start with the initial
  5583. // diagnostic state of the module itself, to cover files that contain no
  5584. // explicit transitions (for which we did not serialize anything).
  5585. Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
  5586. .StateTransitions.push_back({FirstState, 0});
  5587. } else {
  5588. // For prefix ASTs, start with whatever the user configured on the
  5589. // command line.
  5590. Idx++; // Skip flags.
  5591. FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState, false);
  5592. }
  5593. // Read the state transitions.
  5594. unsigned NumLocations = Record[Idx++];
  5595. while (NumLocations--) {
  5596. assert(Idx < Record.size() &&
  5597. "Invalid data, missing pragma diagnostic states");
  5598. SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
  5599. auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
  5600. assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
  5601. assert(IDAndOffset.second == 0 && "not a start location for a FileID");
  5602. unsigned Transitions = Record[Idx++];
  5603. // Note that we don't need to set up Parent/ParentOffset here, because
  5604. // we won't be changing the diagnostic state within imported FileIDs
  5605. // (other than perhaps appending to the main source file, which has no
  5606. // parent).
  5607. auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
  5608. F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
  5609. for (unsigned I = 0; I != Transitions; ++I) {
  5610. unsigned Offset = Record[Idx++];
  5611. auto *State = ReadDiagState(*FirstState, false);
  5612. F.StateTransitions.push_back({State, Offset});
  5613. }
  5614. }
  5615. // Read the final state.
  5616. assert(Idx < Record.size() &&
  5617. "Invalid data, missing final pragma diagnostic state");
  5618. SourceLocation CurStateLoc =
  5619. ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
  5620. auto *CurState = ReadDiagState(*FirstState, false);
  5621. if (!F.isModule()) {
  5622. Diag.DiagStatesByLoc.CurDiagState = CurState;
  5623. Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
  5624. // Preserve the property that the imaginary root file describes the
  5625. // current state.
  5626. FileID NullFile;
  5627. auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
  5628. if (T.empty())
  5629. T.push_back({CurState, 0});
  5630. else
  5631. T[0].State = CurState;
  5632. }
  5633. // Don't try to read these mappings again.
  5634. Record.clear();
  5635. }
  5636. }
  5637. /// Get the correct cursor and offset for loading a type.
  5638. ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
  5639. GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
  5640. assert(I != GlobalTypeMap.end() && "Corrupted global type map");
  5641. ModuleFile *M = I->second;
  5642. return RecordLocation(
  5643. M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
  5644. M->DeclsBlockStartOffset);
  5645. }
  5646. static std::optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
  5647. switch (code) {
  5648. #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
  5649. case TYPE_##CODE_ID: return Type::CLASS_ID;
  5650. #include "clang/Serialization/TypeBitCodes.def"
  5651. default:
  5652. return std::nullopt;
  5653. }
  5654. }
  5655. /// Read and return the type with the given index..
  5656. ///
  5657. /// The index is the type ID, shifted and minus the number of predefs. This
  5658. /// routine actually reads the record corresponding to the type at the given
  5659. /// location. It is a helper routine for GetType, which deals with reading type
  5660. /// IDs.
  5661. QualType ASTReader::readTypeRecord(unsigned Index) {
  5662. assert(ContextObj && "reading type with no AST context");
  5663. ASTContext &Context = *ContextObj;
  5664. RecordLocation Loc = TypeCursorForIndex(Index);
  5665. BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
  5666. // Keep track of where we are in the stream, then jump back there
  5667. // after reading this type.
  5668. SavedStreamPosition SavedPosition(DeclsCursor);
  5669. ReadingKindTracker ReadingKind(Read_Type, *this);
  5670. // Note that we are loading a type record.
  5671. Deserializing AType(this);
  5672. if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
  5673. Error(std::move(Err));
  5674. return QualType();
  5675. }
  5676. Expected<unsigned> RawCode = DeclsCursor.ReadCode();
  5677. if (!RawCode) {
  5678. Error(RawCode.takeError());
  5679. return QualType();
  5680. }
  5681. ASTRecordReader Record(*this, *Loc.F);
  5682. Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
  5683. if (!Code) {
  5684. Error(Code.takeError());
  5685. return QualType();
  5686. }
  5687. if (Code.get() == TYPE_EXT_QUAL) {
  5688. QualType baseType = Record.readQualType();
  5689. Qualifiers quals = Record.readQualifiers();
  5690. return Context.getQualifiedType(baseType, quals);
  5691. }
  5692. auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
  5693. if (!maybeClass) {
  5694. Error("Unexpected code for type");
  5695. return QualType();
  5696. }
  5697. serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
  5698. return TypeReader.read(*maybeClass);
  5699. }
  5700. namespace clang {
  5701. class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
  5702. using LocSeq = SourceLocationSequence;
  5703. ASTRecordReader &Reader;
  5704. LocSeq *Seq;
  5705. SourceLocation readSourceLocation() { return Reader.readSourceLocation(Seq); }
  5706. SourceRange readSourceRange() { return Reader.readSourceRange(Seq); }
  5707. TypeSourceInfo *GetTypeSourceInfo() {
  5708. return Reader.readTypeSourceInfo();
  5709. }
  5710. NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
  5711. return Reader.readNestedNameSpecifierLoc();
  5712. }
  5713. Attr *ReadAttr() {
  5714. return Reader.readAttr();
  5715. }
  5716. public:
  5717. TypeLocReader(ASTRecordReader &Reader, LocSeq *Seq)
  5718. : Reader(Reader), Seq(Seq) {}
  5719. // We want compile-time assurance that we've enumerated all of
  5720. // these, so unfortunately we have to declare them first, then
  5721. // define them out-of-line.
  5722. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  5723. #define TYPELOC(CLASS, PARENT) \
  5724. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  5725. #include "clang/AST/TypeLocNodes.def"
  5726. void VisitFunctionTypeLoc(FunctionTypeLoc);
  5727. void VisitArrayTypeLoc(ArrayTypeLoc);
  5728. };
  5729. } // namespace clang
  5730. void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  5731. // nothing to do
  5732. }
  5733. void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  5734. TL.setBuiltinLoc(readSourceLocation());
  5735. if (TL.needsExtraLocalData()) {
  5736. TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
  5737. TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
  5738. TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
  5739. TL.setModeAttr(Reader.readInt());
  5740. }
  5741. }
  5742. void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  5743. TL.setNameLoc(readSourceLocation());
  5744. }
  5745. void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
  5746. TL.setStarLoc(readSourceLocation());
  5747. }
  5748. void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  5749. // nothing to do
  5750. }
  5751. void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  5752. // nothing to do
  5753. }
  5754. void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
  5755. TL.setExpansionLoc(readSourceLocation());
  5756. }
  5757. void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  5758. TL.setCaretLoc(readSourceLocation());
  5759. }
  5760. void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  5761. TL.setAmpLoc(readSourceLocation());
  5762. }
  5763. void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  5764. TL.setAmpAmpLoc(readSourceLocation());
  5765. }
  5766. void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  5767. TL.setStarLoc(readSourceLocation());
  5768. TL.setClassTInfo(GetTypeSourceInfo());
  5769. }
  5770. void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  5771. TL.setLBracketLoc(readSourceLocation());
  5772. TL.setRBracketLoc(readSourceLocation());
  5773. if (Reader.readBool())
  5774. TL.setSizeExpr(Reader.readExpr());
  5775. else
  5776. TL.setSizeExpr(nullptr);
  5777. }
  5778. void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  5779. VisitArrayTypeLoc(TL);
  5780. }
  5781. void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  5782. VisitArrayTypeLoc(TL);
  5783. }
  5784. void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  5785. VisitArrayTypeLoc(TL);
  5786. }
  5787. void TypeLocReader::VisitDependentSizedArrayTypeLoc(
  5788. DependentSizedArrayTypeLoc TL) {
  5789. VisitArrayTypeLoc(TL);
  5790. }
  5791. void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
  5792. DependentAddressSpaceTypeLoc TL) {
  5793. TL.setAttrNameLoc(readSourceLocation());
  5794. TL.setAttrOperandParensRange(readSourceRange());
  5795. TL.setAttrExprOperand(Reader.readExpr());
  5796. }
  5797. void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
  5798. DependentSizedExtVectorTypeLoc TL) {
  5799. TL.setNameLoc(readSourceLocation());
  5800. }
  5801. void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
  5802. TL.setNameLoc(readSourceLocation());
  5803. }
  5804. void TypeLocReader::VisitDependentVectorTypeLoc(
  5805. DependentVectorTypeLoc TL) {
  5806. TL.setNameLoc(readSourceLocation());
  5807. }
  5808. void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  5809. TL.setNameLoc(readSourceLocation());
  5810. }
  5811. void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
  5812. TL.setAttrNameLoc(readSourceLocation());
  5813. TL.setAttrOperandParensRange(readSourceRange());
  5814. TL.setAttrRowOperand(Reader.readExpr());
  5815. TL.setAttrColumnOperand(Reader.readExpr());
  5816. }
  5817. void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
  5818. DependentSizedMatrixTypeLoc TL) {
  5819. TL.setAttrNameLoc(readSourceLocation());
  5820. TL.setAttrOperandParensRange(readSourceRange());
  5821. TL.setAttrRowOperand(Reader.readExpr());
  5822. TL.setAttrColumnOperand(Reader.readExpr());
  5823. }
  5824. void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  5825. TL.setLocalRangeBegin(readSourceLocation());
  5826. TL.setLParenLoc(readSourceLocation());
  5827. TL.setRParenLoc(readSourceLocation());
  5828. TL.setExceptionSpecRange(readSourceRange());
  5829. TL.setLocalRangeEnd(readSourceLocation());
  5830. for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
  5831. TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
  5832. }
  5833. }
  5834. void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  5835. VisitFunctionTypeLoc(TL);
  5836. }
  5837. void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  5838. VisitFunctionTypeLoc(TL);
  5839. }
  5840. void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  5841. TL.setNameLoc(readSourceLocation());
  5842. }
  5843. void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
  5844. TL.setNameLoc(readSourceLocation());
  5845. }
  5846. void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  5847. TL.setNameLoc(readSourceLocation());
  5848. }
  5849. void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  5850. TL.setTypeofLoc(readSourceLocation());
  5851. TL.setLParenLoc(readSourceLocation());
  5852. TL.setRParenLoc(readSourceLocation());
  5853. }
  5854. void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  5855. TL.setTypeofLoc(readSourceLocation());
  5856. TL.setLParenLoc(readSourceLocation());
  5857. TL.setRParenLoc(readSourceLocation());
  5858. TL.setUnmodifiedTInfo(GetTypeSourceInfo());
  5859. }
  5860. void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  5861. TL.setDecltypeLoc(readSourceLocation());
  5862. TL.setRParenLoc(readSourceLocation());
  5863. }
  5864. void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  5865. TL.setKWLoc(readSourceLocation());
  5866. TL.setLParenLoc(readSourceLocation());
  5867. TL.setRParenLoc(readSourceLocation());
  5868. TL.setUnderlyingTInfo(GetTypeSourceInfo());
  5869. }
  5870. void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
  5871. TL.setNameLoc(readSourceLocation());
  5872. if (Reader.readBool()) {
  5873. TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
  5874. TL.setTemplateKWLoc(readSourceLocation());
  5875. TL.setConceptNameLoc(readSourceLocation());
  5876. TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
  5877. TL.setLAngleLoc(readSourceLocation());
  5878. TL.setRAngleLoc(readSourceLocation());
  5879. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  5880. TL.setArgLocInfo(
  5881. i, Reader.readTemplateArgumentLocInfo(
  5882. TL.getTypePtr()->getTypeConstraintArguments()[i].getKind()));
  5883. }
  5884. if (Reader.readBool())
  5885. TL.setRParenLoc(readSourceLocation());
  5886. }
  5887. void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
  5888. DeducedTemplateSpecializationTypeLoc TL) {
  5889. TL.setTemplateNameLoc(readSourceLocation());
  5890. }
  5891. void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
  5892. TL.setNameLoc(readSourceLocation());
  5893. }
  5894. void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
  5895. TL.setNameLoc(readSourceLocation());
  5896. }
  5897. void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  5898. TL.setAttr(ReadAttr());
  5899. }
  5900. void TypeLocReader::VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
  5901. // Nothing to do.
  5902. }
  5903. void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  5904. TL.setNameLoc(readSourceLocation());
  5905. }
  5906. void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
  5907. SubstTemplateTypeParmTypeLoc TL) {
  5908. TL.setNameLoc(readSourceLocation());
  5909. }
  5910. void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
  5911. SubstTemplateTypeParmPackTypeLoc TL) {
  5912. TL.setNameLoc(readSourceLocation());
  5913. }
  5914. void TypeLocReader::VisitTemplateSpecializationTypeLoc(
  5915. TemplateSpecializationTypeLoc TL) {
  5916. TL.setTemplateKeywordLoc(readSourceLocation());
  5917. TL.setTemplateNameLoc(readSourceLocation());
  5918. TL.setLAngleLoc(readSourceLocation());
  5919. TL.setRAngleLoc(readSourceLocation());
  5920. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  5921. TL.setArgLocInfo(i,
  5922. Reader.readTemplateArgumentLocInfo(
  5923. TL.getTypePtr()->template_arguments()[i].getKind()));
  5924. }
  5925. void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
  5926. TL.setLParenLoc(readSourceLocation());
  5927. TL.setRParenLoc(readSourceLocation());
  5928. }
  5929. void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  5930. TL.setElaboratedKeywordLoc(readSourceLocation());
  5931. TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
  5932. }
  5933. void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  5934. TL.setNameLoc(readSourceLocation());
  5935. }
  5936. void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  5937. TL.setElaboratedKeywordLoc(readSourceLocation());
  5938. TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
  5939. TL.setNameLoc(readSourceLocation());
  5940. }
  5941. void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
  5942. DependentTemplateSpecializationTypeLoc TL) {
  5943. TL.setElaboratedKeywordLoc(readSourceLocation());
  5944. TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
  5945. TL.setTemplateKeywordLoc(readSourceLocation());
  5946. TL.setTemplateNameLoc(readSourceLocation());
  5947. TL.setLAngleLoc(readSourceLocation());
  5948. TL.setRAngleLoc(readSourceLocation());
  5949. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  5950. TL.setArgLocInfo(I,
  5951. Reader.readTemplateArgumentLocInfo(
  5952. TL.getTypePtr()->template_arguments()[I].getKind()));
  5953. }
  5954. void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  5955. TL.setEllipsisLoc(readSourceLocation());
  5956. }
  5957. void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  5958. TL.setNameLoc(readSourceLocation());
  5959. TL.setNameEndLoc(readSourceLocation());
  5960. }
  5961. void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
  5962. if (TL.getNumProtocols()) {
  5963. TL.setProtocolLAngleLoc(readSourceLocation());
  5964. TL.setProtocolRAngleLoc(readSourceLocation());
  5965. }
  5966. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  5967. TL.setProtocolLoc(i, readSourceLocation());
  5968. }
  5969. void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  5970. TL.setHasBaseTypeAsWritten(Reader.readBool());
  5971. TL.setTypeArgsLAngleLoc(readSourceLocation());
  5972. TL.setTypeArgsRAngleLoc(readSourceLocation());
  5973. for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
  5974. TL.setTypeArgTInfo(i, GetTypeSourceInfo());
  5975. TL.setProtocolLAngleLoc(readSourceLocation());
  5976. TL.setProtocolRAngleLoc(readSourceLocation());
  5977. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  5978. TL.setProtocolLoc(i, readSourceLocation());
  5979. }
  5980. void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  5981. TL.setStarLoc(readSourceLocation());
  5982. }
  5983. void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  5984. TL.setKWLoc(readSourceLocation());
  5985. TL.setLParenLoc(readSourceLocation());
  5986. TL.setRParenLoc(readSourceLocation());
  5987. }
  5988. void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
  5989. TL.setKWLoc(readSourceLocation());
  5990. }
  5991. void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
  5992. TL.setNameLoc(readSourceLocation());
  5993. }
  5994. void TypeLocReader::VisitDependentBitIntTypeLoc(
  5995. clang::DependentBitIntTypeLoc TL) {
  5996. TL.setNameLoc(readSourceLocation());
  5997. }
  5998. void ASTRecordReader::readTypeLoc(TypeLoc TL, LocSeq *ParentSeq) {
  5999. LocSeq::State Seq(ParentSeq);
  6000. TypeLocReader TLR(*this, Seq);
  6001. for (; !TL.isNull(); TL = TL.getNextTypeLoc())
  6002. TLR.Visit(TL);
  6003. }
  6004. TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
  6005. QualType InfoTy = readType();
  6006. if (InfoTy.isNull())
  6007. return nullptr;
  6008. TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
  6009. readTypeLoc(TInfo->getTypeLoc());
  6010. return TInfo;
  6011. }
  6012. QualType ASTReader::GetType(TypeID ID) {
  6013. assert(ContextObj && "reading type with no AST context");
  6014. ASTContext &Context = *ContextObj;
  6015. unsigned FastQuals = ID & Qualifiers::FastMask;
  6016. unsigned Index = ID >> Qualifiers::FastWidth;
  6017. if (Index < NUM_PREDEF_TYPE_IDS) {
  6018. QualType T;
  6019. switch ((PredefinedTypeIDs)Index) {
  6020. case PREDEF_TYPE_NULL_ID:
  6021. return QualType();
  6022. case PREDEF_TYPE_VOID_ID:
  6023. T = Context.VoidTy;
  6024. break;
  6025. case PREDEF_TYPE_BOOL_ID:
  6026. T = Context.BoolTy;
  6027. break;
  6028. case PREDEF_TYPE_CHAR_U_ID:
  6029. case PREDEF_TYPE_CHAR_S_ID:
  6030. // FIXME: Check that the signedness of CharTy is correct!
  6031. T = Context.CharTy;
  6032. break;
  6033. case PREDEF_TYPE_UCHAR_ID:
  6034. T = Context.UnsignedCharTy;
  6035. break;
  6036. case PREDEF_TYPE_USHORT_ID:
  6037. T = Context.UnsignedShortTy;
  6038. break;
  6039. case PREDEF_TYPE_UINT_ID:
  6040. T = Context.UnsignedIntTy;
  6041. break;
  6042. case PREDEF_TYPE_ULONG_ID:
  6043. T = Context.UnsignedLongTy;
  6044. break;
  6045. case PREDEF_TYPE_ULONGLONG_ID:
  6046. T = Context.UnsignedLongLongTy;
  6047. break;
  6048. case PREDEF_TYPE_UINT128_ID:
  6049. T = Context.UnsignedInt128Ty;
  6050. break;
  6051. case PREDEF_TYPE_SCHAR_ID:
  6052. T = Context.SignedCharTy;
  6053. break;
  6054. case PREDEF_TYPE_WCHAR_ID:
  6055. T = Context.WCharTy;
  6056. break;
  6057. case PREDEF_TYPE_SHORT_ID:
  6058. T = Context.ShortTy;
  6059. break;
  6060. case PREDEF_TYPE_INT_ID:
  6061. T = Context.IntTy;
  6062. break;
  6063. case PREDEF_TYPE_LONG_ID:
  6064. T = Context.LongTy;
  6065. break;
  6066. case PREDEF_TYPE_LONGLONG_ID:
  6067. T = Context.LongLongTy;
  6068. break;
  6069. case PREDEF_TYPE_INT128_ID:
  6070. T = Context.Int128Ty;
  6071. break;
  6072. case PREDEF_TYPE_BFLOAT16_ID:
  6073. T = Context.BFloat16Ty;
  6074. break;
  6075. case PREDEF_TYPE_HALF_ID:
  6076. T = Context.HalfTy;
  6077. break;
  6078. case PREDEF_TYPE_FLOAT_ID:
  6079. T = Context.FloatTy;
  6080. break;
  6081. case PREDEF_TYPE_DOUBLE_ID:
  6082. T = Context.DoubleTy;
  6083. break;
  6084. case PREDEF_TYPE_LONGDOUBLE_ID:
  6085. T = Context.LongDoubleTy;
  6086. break;
  6087. case PREDEF_TYPE_SHORT_ACCUM_ID:
  6088. T = Context.ShortAccumTy;
  6089. break;
  6090. case PREDEF_TYPE_ACCUM_ID:
  6091. T = Context.AccumTy;
  6092. break;
  6093. case PREDEF_TYPE_LONG_ACCUM_ID:
  6094. T = Context.LongAccumTy;
  6095. break;
  6096. case PREDEF_TYPE_USHORT_ACCUM_ID:
  6097. T = Context.UnsignedShortAccumTy;
  6098. break;
  6099. case PREDEF_TYPE_UACCUM_ID:
  6100. T = Context.UnsignedAccumTy;
  6101. break;
  6102. case PREDEF_TYPE_ULONG_ACCUM_ID:
  6103. T = Context.UnsignedLongAccumTy;
  6104. break;
  6105. case PREDEF_TYPE_SHORT_FRACT_ID:
  6106. T = Context.ShortFractTy;
  6107. break;
  6108. case PREDEF_TYPE_FRACT_ID:
  6109. T = Context.FractTy;
  6110. break;
  6111. case PREDEF_TYPE_LONG_FRACT_ID:
  6112. T = Context.LongFractTy;
  6113. break;
  6114. case PREDEF_TYPE_USHORT_FRACT_ID:
  6115. T = Context.UnsignedShortFractTy;
  6116. break;
  6117. case PREDEF_TYPE_UFRACT_ID:
  6118. T = Context.UnsignedFractTy;
  6119. break;
  6120. case PREDEF_TYPE_ULONG_FRACT_ID:
  6121. T = Context.UnsignedLongFractTy;
  6122. break;
  6123. case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
  6124. T = Context.SatShortAccumTy;
  6125. break;
  6126. case PREDEF_TYPE_SAT_ACCUM_ID:
  6127. T = Context.SatAccumTy;
  6128. break;
  6129. case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
  6130. T = Context.SatLongAccumTy;
  6131. break;
  6132. case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
  6133. T = Context.SatUnsignedShortAccumTy;
  6134. break;
  6135. case PREDEF_TYPE_SAT_UACCUM_ID:
  6136. T = Context.SatUnsignedAccumTy;
  6137. break;
  6138. case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
  6139. T = Context.SatUnsignedLongAccumTy;
  6140. break;
  6141. case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
  6142. T = Context.SatShortFractTy;
  6143. break;
  6144. case PREDEF_TYPE_SAT_FRACT_ID:
  6145. T = Context.SatFractTy;
  6146. break;
  6147. case PREDEF_TYPE_SAT_LONG_FRACT_ID:
  6148. T = Context.SatLongFractTy;
  6149. break;
  6150. case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
  6151. T = Context.SatUnsignedShortFractTy;
  6152. break;
  6153. case PREDEF_TYPE_SAT_UFRACT_ID:
  6154. T = Context.SatUnsignedFractTy;
  6155. break;
  6156. case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
  6157. T = Context.SatUnsignedLongFractTy;
  6158. break;
  6159. case PREDEF_TYPE_FLOAT16_ID:
  6160. T = Context.Float16Ty;
  6161. break;
  6162. case PREDEF_TYPE_FLOAT128_ID:
  6163. T = Context.Float128Ty;
  6164. break;
  6165. case PREDEF_TYPE_IBM128_ID:
  6166. T = Context.Ibm128Ty;
  6167. break;
  6168. case PREDEF_TYPE_OVERLOAD_ID:
  6169. T = Context.OverloadTy;
  6170. break;
  6171. case PREDEF_TYPE_BOUND_MEMBER:
  6172. T = Context.BoundMemberTy;
  6173. break;
  6174. case PREDEF_TYPE_PSEUDO_OBJECT:
  6175. T = Context.PseudoObjectTy;
  6176. break;
  6177. case PREDEF_TYPE_DEPENDENT_ID:
  6178. T = Context.DependentTy;
  6179. break;
  6180. case PREDEF_TYPE_UNKNOWN_ANY:
  6181. T = Context.UnknownAnyTy;
  6182. break;
  6183. case PREDEF_TYPE_NULLPTR_ID:
  6184. T = Context.NullPtrTy;
  6185. break;
  6186. case PREDEF_TYPE_CHAR8_ID:
  6187. T = Context.Char8Ty;
  6188. break;
  6189. case PREDEF_TYPE_CHAR16_ID:
  6190. T = Context.Char16Ty;
  6191. break;
  6192. case PREDEF_TYPE_CHAR32_ID:
  6193. T = Context.Char32Ty;
  6194. break;
  6195. case PREDEF_TYPE_OBJC_ID:
  6196. T = Context.ObjCBuiltinIdTy;
  6197. break;
  6198. case PREDEF_TYPE_OBJC_CLASS:
  6199. T = Context.ObjCBuiltinClassTy;
  6200. break;
  6201. case PREDEF_TYPE_OBJC_SEL:
  6202. T = Context.ObjCBuiltinSelTy;
  6203. break;
  6204. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6205. case PREDEF_TYPE_##Id##_ID: \
  6206. T = Context.SingletonId; \
  6207. break;
  6208. #include "clang/Basic/OpenCLImageTypes.def"
  6209. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  6210. case PREDEF_TYPE_##Id##_ID: \
  6211. T = Context.Id##Ty; \
  6212. break;
  6213. #include "clang/Basic/OpenCLExtensionTypes.def"
  6214. case PREDEF_TYPE_SAMPLER_ID:
  6215. T = Context.OCLSamplerTy;
  6216. break;
  6217. case PREDEF_TYPE_EVENT_ID:
  6218. T = Context.OCLEventTy;
  6219. break;
  6220. case PREDEF_TYPE_CLK_EVENT_ID:
  6221. T = Context.OCLClkEventTy;
  6222. break;
  6223. case PREDEF_TYPE_QUEUE_ID:
  6224. T = Context.OCLQueueTy;
  6225. break;
  6226. case PREDEF_TYPE_RESERVE_ID_ID:
  6227. T = Context.OCLReserveIDTy;
  6228. break;
  6229. case PREDEF_TYPE_AUTO_DEDUCT:
  6230. T = Context.getAutoDeductType();
  6231. break;
  6232. case PREDEF_TYPE_AUTO_RREF_DEDUCT:
  6233. T = Context.getAutoRRefDeductType();
  6234. break;
  6235. case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
  6236. T = Context.ARCUnbridgedCastTy;
  6237. break;
  6238. case PREDEF_TYPE_BUILTIN_FN:
  6239. T = Context.BuiltinFnTy;
  6240. break;
  6241. case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
  6242. T = Context.IncompleteMatrixIdxTy;
  6243. break;
  6244. case PREDEF_TYPE_OMP_ARRAY_SECTION:
  6245. T = Context.OMPArraySectionTy;
  6246. break;
  6247. case PREDEF_TYPE_OMP_ARRAY_SHAPING:
  6248. T = Context.OMPArraySectionTy;
  6249. break;
  6250. case PREDEF_TYPE_OMP_ITERATOR:
  6251. T = Context.OMPIteratorTy;
  6252. break;
  6253. #define SVE_TYPE(Name, Id, SingletonId) \
  6254. case PREDEF_TYPE_##Id##_ID: \
  6255. T = Context.SingletonId; \
  6256. break;
  6257. #include "clang/Basic/AArch64SVEACLETypes.def"
  6258. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  6259. case PREDEF_TYPE_##Id##_ID: \
  6260. T = Context.Id##Ty; \
  6261. break;
  6262. #include "clang/Basic/PPCTypes.def"
  6263. #define RVV_TYPE(Name, Id, SingletonId) \
  6264. case PREDEF_TYPE_##Id##_ID: \
  6265. T = Context.SingletonId; \
  6266. break;
  6267. #include "clang/Basic/RISCVVTypes.def"
  6268. }
  6269. assert(!T.isNull() && "Unknown predefined type");
  6270. return T.withFastQualifiers(FastQuals);
  6271. }
  6272. Index -= NUM_PREDEF_TYPE_IDS;
  6273. assert(Index < TypesLoaded.size() && "Type index out-of-range");
  6274. if (TypesLoaded[Index].isNull()) {
  6275. TypesLoaded[Index] = readTypeRecord(Index);
  6276. if (TypesLoaded[Index].isNull())
  6277. return QualType();
  6278. TypesLoaded[Index]->setFromAST();
  6279. if (DeserializationListener)
  6280. DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
  6281. TypesLoaded[Index]);
  6282. }
  6283. return TypesLoaded[Index].withFastQualifiers(FastQuals);
  6284. }
  6285. QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
  6286. return GetType(getGlobalTypeID(F, LocalID));
  6287. }
  6288. serialization::TypeID
  6289. ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
  6290. unsigned FastQuals = LocalID & Qualifiers::FastMask;
  6291. unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
  6292. if (LocalIndex < NUM_PREDEF_TYPE_IDS)
  6293. return LocalID;
  6294. if (!F.ModuleOffsetMap.empty())
  6295. ReadModuleOffsetMap(F);
  6296. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6297. = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
  6298. assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
  6299. unsigned GlobalIndex = LocalIndex + I->second;
  6300. return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
  6301. }
  6302. TemplateArgumentLocInfo
  6303. ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
  6304. switch (Kind) {
  6305. case TemplateArgument::Expression:
  6306. return readExpr();
  6307. case TemplateArgument::Type:
  6308. return readTypeSourceInfo();
  6309. case TemplateArgument::Template: {
  6310. NestedNameSpecifierLoc QualifierLoc =
  6311. readNestedNameSpecifierLoc();
  6312. SourceLocation TemplateNameLoc = readSourceLocation();
  6313. return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
  6314. TemplateNameLoc, SourceLocation());
  6315. }
  6316. case TemplateArgument::TemplateExpansion: {
  6317. NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
  6318. SourceLocation TemplateNameLoc = readSourceLocation();
  6319. SourceLocation EllipsisLoc = readSourceLocation();
  6320. return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
  6321. TemplateNameLoc, EllipsisLoc);
  6322. }
  6323. case TemplateArgument::Null:
  6324. case TemplateArgument::Integral:
  6325. case TemplateArgument::Declaration:
  6326. case TemplateArgument::NullPtr:
  6327. case TemplateArgument::Pack:
  6328. // FIXME: Is this right?
  6329. return TemplateArgumentLocInfo();
  6330. }
  6331. llvm_unreachable("unexpected template argument loc");
  6332. }
  6333. TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
  6334. TemplateArgument Arg = readTemplateArgument();
  6335. if (Arg.getKind() == TemplateArgument::Expression) {
  6336. if (readBool()) // bool InfoHasSameExpr.
  6337. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
  6338. }
  6339. return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
  6340. }
  6341. const ASTTemplateArgumentListInfo *
  6342. ASTRecordReader::readASTTemplateArgumentListInfo() {
  6343. SourceLocation LAngleLoc = readSourceLocation();
  6344. SourceLocation RAngleLoc = readSourceLocation();
  6345. unsigned NumArgsAsWritten = readInt();
  6346. TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
  6347. for (unsigned i = 0; i != NumArgsAsWritten; ++i)
  6348. TemplArgsInfo.addArgument(readTemplateArgumentLoc());
  6349. return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
  6350. }
  6351. Decl *ASTReader::GetExternalDecl(uint32_t ID) {
  6352. return GetDecl(ID);
  6353. }
  6354. void ASTReader::CompleteRedeclChain(const Decl *D) {
  6355. if (NumCurrentElementsDeserializing) {
  6356. // We arrange to not care about the complete redeclaration chain while we're
  6357. // deserializing. Just remember that the AST has marked this one as complete
  6358. // but that it's not actually complete yet, so we know we still need to
  6359. // complete it later.
  6360. PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
  6361. return;
  6362. }
  6363. if (!D->getDeclContext()) {
  6364. assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
  6365. return;
  6366. }
  6367. const DeclContext *DC = D->getDeclContext()->getRedeclContext();
  6368. // If this is a named declaration, complete it by looking it up
  6369. // within its context.
  6370. //
  6371. // FIXME: Merging a function definition should merge
  6372. // all mergeable entities within it.
  6373. if (isa<TranslationUnitDecl, NamespaceDecl, RecordDecl, EnumDecl>(DC)) {
  6374. if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
  6375. if (!getContext().getLangOpts().CPlusPlus &&
  6376. isa<TranslationUnitDecl>(DC)) {
  6377. // Outside of C++, we don't have a lookup table for the TU, so update
  6378. // the identifier instead. (For C++ modules, we don't store decls
  6379. // in the serialized identifier table, so we do the lookup in the TU.)
  6380. auto *II = Name.getAsIdentifierInfo();
  6381. assert(II && "non-identifier name in C?");
  6382. if (II->isOutOfDate())
  6383. updateOutOfDateIdentifier(*II);
  6384. } else
  6385. DC->lookup(Name);
  6386. } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
  6387. // Find all declarations of this kind from the relevant context.
  6388. for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
  6389. auto *DC = cast<DeclContext>(DCDecl);
  6390. SmallVector<Decl*, 8> Decls;
  6391. FindExternalLexicalDecls(
  6392. DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
  6393. }
  6394. }
  6395. }
  6396. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
  6397. CTSD->getSpecializedTemplate()->LoadLazySpecializations();
  6398. if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
  6399. VTSD->getSpecializedTemplate()->LoadLazySpecializations();
  6400. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  6401. if (auto *Template = FD->getPrimaryTemplate())
  6402. Template->LoadLazySpecializations();
  6403. }
  6404. }
  6405. CXXCtorInitializer **
  6406. ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
  6407. RecordLocation Loc = getLocalBitOffset(Offset);
  6408. BitstreamCursor &Cursor = Loc.F->DeclsCursor;
  6409. SavedStreamPosition SavedPosition(Cursor);
  6410. if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
  6411. Error(std::move(Err));
  6412. return nullptr;
  6413. }
  6414. ReadingKindTracker ReadingKind(Read_Decl, *this);
  6415. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  6416. if (!MaybeCode) {
  6417. Error(MaybeCode.takeError());
  6418. return nullptr;
  6419. }
  6420. unsigned Code = MaybeCode.get();
  6421. ASTRecordReader Record(*this, *Loc.F);
  6422. Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
  6423. if (!MaybeRecCode) {
  6424. Error(MaybeRecCode.takeError());
  6425. return nullptr;
  6426. }
  6427. if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
  6428. Error("malformed AST file: missing C++ ctor initializers");
  6429. return nullptr;
  6430. }
  6431. return Record.readCXXCtorInitializers();
  6432. }
  6433. CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
  6434. assert(ContextObj && "reading base specifiers with no AST context");
  6435. ASTContext &Context = *ContextObj;
  6436. RecordLocation Loc = getLocalBitOffset(Offset);
  6437. BitstreamCursor &Cursor = Loc.F->DeclsCursor;
  6438. SavedStreamPosition SavedPosition(Cursor);
  6439. if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
  6440. Error(std::move(Err));
  6441. return nullptr;
  6442. }
  6443. ReadingKindTracker ReadingKind(Read_Decl, *this);
  6444. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  6445. if (!MaybeCode) {
  6446. Error(MaybeCode.takeError());
  6447. return nullptr;
  6448. }
  6449. unsigned Code = MaybeCode.get();
  6450. ASTRecordReader Record(*this, *Loc.F);
  6451. Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
  6452. if (!MaybeRecCode) {
  6453. Error(MaybeCode.takeError());
  6454. return nullptr;
  6455. }
  6456. unsigned RecCode = MaybeRecCode.get();
  6457. if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
  6458. Error("malformed AST file: missing C++ base specifiers");
  6459. return nullptr;
  6460. }
  6461. unsigned NumBases = Record.readInt();
  6462. void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
  6463. CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
  6464. for (unsigned I = 0; I != NumBases; ++I)
  6465. Bases[I] = Record.readCXXBaseSpecifier();
  6466. return Bases;
  6467. }
  6468. serialization::DeclID
  6469. ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
  6470. if (LocalID < NUM_PREDEF_DECL_IDS)
  6471. return LocalID;
  6472. if (!F.ModuleOffsetMap.empty())
  6473. ReadModuleOffsetMap(F);
  6474. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6475. = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
  6476. assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
  6477. return LocalID + I->second;
  6478. }
  6479. bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
  6480. ModuleFile &M) const {
  6481. // Predefined decls aren't from any module.
  6482. if (ID < NUM_PREDEF_DECL_IDS)
  6483. return false;
  6484. return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
  6485. ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
  6486. }
  6487. ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
  6488. if (!D->isFromASTFile())
  6489. return nullptr;
  6490. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
  6491. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  6492. return I->second;
  6493. }
  6494. SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
  6495. if (ID < NUM_PREDEF_DECL_IDS)
  6496. return SourceLocation();
  6497. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  6498. if (Index > DeclsLoaded.size()) {
  6499. Error("declaration ID out-of-range for AST file");
  6500. return SourceLocation();
  6501. }
  6502. if (Decl *D = DeclsLoaded[Index])
  6503. return D->getLocation();
  6504. SourceLocation Loc;
  6505. DeclCursorForID(ID, Loc);
  6506. return Loc;
  6507. }
  6508. static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
  6509. switch (ID) {
  6510. case PREDEF_DECL_NULL_ID:
  6511. return nullptr;
  6512. case PREDEF_DECL_TRANSLATION_UNIT_ID:
  6513. return Context.getTranslationUnitDecl();
  6514. case PREDEF_DECL_OBJC_ID_ID:
  6515. return Context.getObjCIdDecl();
  6516. case PREDEF_DECL_OBJC_SEL_ID:
  6517. return Context.getObjCSelDecl();
  6518. case PREDEF_DECL_OBJC_CLASS_ID:
  6519. return Context.getObjCClassDecl();
  6520. case PREDEF_DECL_OBJC_PROTOCOL_ID:
  6521. return Context.getObjCProtocolDecl();
  6522. case PREDEF_DECL_INT_128_ID:
  6523. return Context.getInt128Decl();
  6524. case PREDEF_DECL_UNSIGNED_INT_128_ID:
  6525. return Context.getUInt128Decl();
  6526. case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
  6527. return Context.getObjCInstanceTypeDecl();
  6528. case PREDEF_DECL_BUILTIN_VA_LIST_ID:
  6529. return Context.getBuiltinVaListDecl();
  6530. case PREDEF_DECL_VA_LIST_TAG:
  6531. return Context.getVaListTagDecl();
  6532. case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
  6533. return Context.getBuiltinMSVaListDecl();
  6534. case PREDEF_DECL_BUILTIN_MS_GUID_ID:
  6535. return Context.getMSGuidTagDecl();
  6536. case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
  6537. return Context.getExternCContextDecl();
  6538. case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
  6539. return Context.getMakeIntegerSeqDecl();
  6540. case PREDEF_DECL_CF_CONSTANT_STRING_ID:
  6541. return Context.getCFConstantStringDecl();
  6542. case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
  6543. return Context.getCFConstantStringTagDecl();
  6544. case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
  6545. return Context.getTypePackElementDecl();
  6546. }
  6547. llvm_unreachable("PredefinedDeclIDs unknown enum value");
  6548. }
  6549. Decl *ASTReader::GetExistingDecl(DeclID ID) {
  6550. assert(ContextObj && "reading decl with no AST context");
  6551. if (ID < NUM_PREDEF_DECL_IDS) {
  6552. Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
  6553. if (D) {
  6554. // Track that we have merged the declaration with ID \p ID into the
  6555. // pre-existing predefined declaration \p D.
  6556. auto &Merged = KeyDecls[D->getCanonicalDecl()];
  6557. if (Merged.empty())
  6558. Merged.push_back(ID);
  6559. }
  6560. return D;
  6561. }
  6562. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  6563. if (Index >= DeclsLoaded.size()) {
  6564. assert(0 && "declaration ID out-of-range for AST file");
  6565. Error("declaration ID out-of-range for AST file");
  6566. return nullptr;
  6567. }
  6568. return DeclsLoaded[Index];
  6569. }
  6570. Decl *ASTReader::GetDecl(DeclID ID) {
  6571. if (ID < NUM_PREDEF_DECL_IDS)
  6572. return GetExistingDecl(ID);
  6573. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  6574. if (Index >= DeclsLoaded.size()) {
  6575. assert(0 && "declaration ID out-of-range for AST file");
  6576. Error("declaration ID out-of-range for AST file");
  6577. return nullptr;
  6578. }
  6579. if (!DeclsLoaded[Index]) {
  6580. ReadDeclRecord(ID);
  6581. if (DeserializationListener)
  6582. DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
  6583. }
  6584. return DeclsLoaded[Index];
  6585. }
  6586. DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
  6587. DeclID GlobalID) {
  6588. if (GlobalID < NUM_PREDEF_DECL_IDS)
  6589. return GlobalID;
  6590. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
  6591. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  6592. ModuleFile *Owner = I->second;
  6593. llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
  6594. = M.GlobalToLocalDeclIDs.find(Owner);
  6595. if (Pos == M.GlobalToLocalDeclIDs.end())
  6596. return 0;
  6597. return GlobalID - Owner->BaseDeclID + Pos->second;
  6598. }
  6599. serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
  6600. const RecordData &Record,
  6601. unsigned &Idx) {
  6602. if (Idx >= Record.size()) {
  6603. Error("Corrupted AST file");
  6604. return 0;
  6605. }
  6606. return getGlobalDeclID(F, Record[Idx++]);
  6607. }
  6608. /// Resolve the offset of a statement into a statement.
  6609. ///
  6610. /// This operation will read a new statement from the external
  6611. /// source each time it is called, and is meant to be used via a
  6612. /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
  6613. Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
  6614. // Switch case IDs are per Decl.
  6615. ClearSwitchCaseIDs();
  6616. // Offset here is a global offset across the entire chain.
  6617. RecordLocation Loc = getLocalBitOffset(Offset);
  6618. if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
  6619. Error(std::move(Err));
  6620. return nullptr;
  6621. }
  6622. assert(NumCurrentElementsDeserializing == 0 &&
  6623. "should not be called while already deserializing");
  6624. Deserializing D(this);
  6625. return ReadStmtFromStream(*Loc.F);
  6626. }
  6627. void ASTReader::FindExternalLexicalDecls(
  6628. const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
  6629. SmallVectorImpl<Decl *> &Decls) {
  6630. bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
  6631. auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
  6632. assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
  6633. for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
  6634. auto K = (Decl::Kind)+LexicalDecls[I];
  6635. if (!IsKindWeWant(K))
  6636. continue;
  6637. auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
  6638. // Don't add predefined declarations to the lexical context more
  6639. // than once.
  6640. if (ID < NUM_PREDEF_DECL_IDS) {
  6641. if (PredefsVisited[ID])
  6642. continue;
  6643. PredefsVisited[ID] = true;
  6644. }
  6645. if (Decl *D = GetLocalDecl(*M, ID)) {
  6646. assert(D->getKind() == K && "wrong kind for lexical decl");
  6647. if (!DC->isDeclInLexicalTraversal(D))
  6648. Decls.push_back(D);
  6649. }
  6650. }
  6651. };
  6652. if (isa<TranslationUnitDecl>(DC)) {
  6653. for (auto Lexical : TULexicalDecls)
  6654. Visit(Lexical.first, Lexical.second);
  6655. } else {
  6656. auto I = LexicalDecls.find(DC);
  6657. if (I != LexicalDecls.end())
  6658. Visit(I->second.first, I->second.second);
  6659. }
  6660. ++NumLexicalDeclContextsRead;
  6661. }
  6662. namespace {
  6663. class DeclIDComp {
  6664. ASTReader &Reader;
  6665. ModuleFile &Mod;
  6666. public:
  6667. DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
  6668. bool operator()(LocalDeclID L, LocalDeclID R) const {
  6669. SourceLocation LHS = getLocation(L);
  6670. SourceLocation RHS = getLocation(R);
  6671. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  6672. }
  6673. bool operator()(SourceLocation LHS, LocalDeclID R) const {
  6674. SourceLocation RHS = getLocation(R);
  6675. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  6676. }
  6677. bool operator()(LocalDeclID L, SourceLocation RHS) const {
  6678. SourceLocation LHS = getLocation(L);
  6679. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  6680. }
  6681. SourceLocation getLocation(LocalDeclID ID) const {
  6682. return Reader.getSourceManager().getFileLoc(
  6683. Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
  6684. }
  6685. };
  6686. } // namespace
  6687. void ASTReader::FindFileRegionDecls(FileID File,
  6688. unsigned Offset, unsigned Length,
  6689. SmallVectorImpl<Decl *> &Decls) {
  6690. SourceManager &SM = getSourceManager();
  6691. llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
  6692. if (I == FileDeclIDs.end())
  6693. return;
  6694. FileDeclsInfo &DInfo = I->second;
  6695. if (DInfo.Decls.empty())
  6696. return;
  6697. SourceLocation
  6698. BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
  6699. SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
  6700. DeclIDComp DIDComp(*this, *DInfo.Mod);
  6701. ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
  6702. llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
  6703. if (BeginIt != DInfo.Decls.begin())
  6704. --BeginIt;
  6705. // If we are pointing at a top-level decl inside an objc container, we need
  6706. // to backtrack until we find it otherwise we will fail to report that the
  6707. // region overlaps with an objc container.
  6708. while (BeginIt != DInfo.Decls.begin() &&
  6709. GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
  6710. ->isTopLevelDeclInObjCContainer())
  6711. --BeginIt;
  6712. ArrayRef<serialization::LocalDeclID>::iterator EndIt =
  6713. llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
  6714. if (EndIt != DInfo.Decls.end())
  6715. ++EndIt;
  6716. for (ArrayRef<serialization::LocalDeclID>::iterator
  6717. DIt = BeginIt; DIt != EndIt; ++DIt)
  6718. Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
  6719. }
  6720. bool
  6721. ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
  6722. DeclarationName Name) {
  6723. assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
  6724. "DeclContext has no visible decls in storage");
  6725. if (!Name)
  6726. return false;
  6727. auto It = Lookups.find(DC);
  6728. if (It == Lookups.end())
  6729. return false;
  6730. Deserializing LookupResults(this);
  6731. // Load the list of declarations.
  6732. SmallVector<NamedDecl *, 64> Decls;
  6733. llvm::SmallPtrSet<NamedDecl *, 8> Found;
  6734. for (DeclID ID : It->second.Table.find(Name)) {
  6735. NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
  6736. if (ND->getDeclName() == Name && Found.insert(ND).second)
  6737. Decls.push_back(ND);
  6738. }
  6739. ++NumVisibleDeclContextsRead;
  6740. SetExternalVisibleDeclsForName(DC, Name, Decls);
  6741. return !Decls.empty();
  6742. }
  6743. void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
  6744. if (!DC->hasExternalVisibleStorage())
  6745. return;
  6746. auto It = Lookups.find(DC);
  6747. assert(It != Lookups.end() &&
  6748. "have external visible storage but no lookup tables");
  6749. DeclsMap Decls;
  6750. for (DeclID ID : It->second.Table.findAll()) {
  6751. NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
  6752. Decls[ND->getDeclName()].push_back(ND);
  6753. }
  6754. ++NumVisibleDeclContextsRead;
  6755. for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
  6756. SetExternalVisibleDeclsForName(DC, I->first, I->second);
  6757. }
  6758. const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
  6759. }
  6760. const serialization::reader::DeclContextLookupTable *
  6761. ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
  6762. auto I = Lookups.find(Primary);
  6763. return I == Lookups.end() ? nullptr : &I->second;
  6764. }
  6765. /// Under non-PCH compilation the consumer receives the objc methods
  6766. /// before receiving the implementation, and codegen depends on this.
  6767. /// We simulate this by deserializing and passing to consumer the methods of the
  6768. /// implementation before passing the deserialized implementation decl.
  6769. static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
  6770. ASTConsumer *Consumer) {
  6771. assert(ImplD && Consumer);
  6772. for (auto *I : ImplD->methods())
  6773. Consumer->HandleInterestingDecl(DeclGroupRef(I));
  6774. Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
  6775. }
  6776. void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
  6777. if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
  6778. PassObjCImplDeclToConsumer(ImplD, Consumer);
  6779. else
  6780. Consumer->HandleInterestingDecl(DeclGroupRef(D));
  6781. }
  6782. void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
  6783. this->Consumer = Consumer;
  6784. if (Consumer)
  6785. PassInterestingDeclsToConsumer();
  6786. if (DeserializationListener)
  6787. DeserializationListener->ReaderInitialized(this);
  6788. }
  6789. void ASTReader::PrintStats() {
  6790. std::fprintf(stderr, "*** AST File Statistics:\n");
  6791. unsigned NumTypesLoaded =
  6792. TypesLoaded.size() - llvm::count(TypesLoaded, QualType());
  6793. unsigned NumDeclsLoaded =
  6794. DeclsLoaded.size() - llvm::count(DeclsLoaded, (Decl *)nullptr);
  6795. unsigned NumIdentifiersLoaded =
  6796. IdentifiersLoaded.size() -
  6797. llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
  6798. unsigned NumMacrosLoaded =
  6799. MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
  6800. unsigned NumSelectorsLoaded =
  6801. SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
  6802. if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
  6803. std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
  6804. NumSLocEntriesRead, TotalNumSLocEntries,
  6805. ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
  6806. if (!TypesLoaded.empty())
  6807. std::fprintf(stderr, " %u/%u types read (%f%%)\n",
  6808. NumTypesLoaded, (unsigned)TypesLoaded.size(),
  6809. ((float)NumTypesLoaded/TypesLoaded.size() * 100));
  6810. if (!DeclsLoaded.empty())
  6811. std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
  6812. NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
  6813. ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
  6814. if (!IdentifiersLoaded.empty())
  6815. std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
  6816. NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
  6817. ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
  6818. if (!MacrosLoaded.empty())
  6819. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  6820. NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
  6821. ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
  6822. if (!SelectorsLoaded.empty())
  6823. std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
  6824. NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
  6825. ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
  6826. if (TotalNumStatements)
  6827. std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
  6828. NumStatementsRead, TotalNumStatements,
  6829. ((float)NumStatementsRead/TotalNumStatements * 100));
  6830. if (TotalNumMacros)
  6831. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  6832. NumMacrosRead, TotalNumMacros,
  6833. ((float)NumMacrosRead/TotalNumMacros * 100));
  6834. if (TotalLexicalDeclContexts)
  6835. std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
  6836. NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
  6837. ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
  6838. * 100));
  6839. if (TotalVisibleDeclContexts)
  6840. std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
  6841. NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
  6842. ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
  6843. * 100));
  6844. if (TotalNumMethodPoolEntries)
  6845. std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
  6846. NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
  6847. ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
  6848. * 100));
  6849. if (NumMethodPoolLookups)
  6850. std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
  6851. NumMethodPoolHits, NumMethodPoolLookups,
  6852. ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
  6853. if (NumMethodPoolTableLookups)
  6854. std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
  6855. NumMethodPoolTableHits, NumMethodPoolTableLookups,
  6856. ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
  6857. * 100.0));
  6858. if (NumIdentifierLookupHits)
  6859. std::fprintf(stderr,
  6860. " %u / %u identifier table lookups succeeded (%f%%)\n",
  6861. NumIdentifierLookupHits, NumIdentifierLookups,
  6862. (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
  6863. if (GlobalIndex) {
  6864. std::fprintf(stderr, "\n");
  6865. GlobalIndex->printStats();
  6866. }
  6867. std::fprintf(stderr, "\n");
  6868. dump();
  6869. std::fprintf(stderr, "\n");
  6870. }
  6871. template<typename Key, typename ModuleFile, unsigned InitialCapacity>
  6872. LLVM_DUMP_METHOD static void
  6873. dumpModuleIDMap(StringRef Name,
  6874. const ContinuousRangeMap<Key, ModuleFile *,
  6875. InitialCapacity> &Map) {
  6876. if (Map.begin() == Map.end())
  6877. return;
  6878. using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
  6879. llvm::errs() << Name << ":\n";
  6880. for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
  6881. I != IEnd; ++I) {
  6882. llvm::errs() << " " << I->first << " -> " << I->second->FileName
  6883. << "\n";
  6884. }
  6885. }
  6886. LLVM_DUMP_METHOD void ASTReader::dump() {
  6887. llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
  6888. dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
  6889. dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
  6890. dumpModuleIDMap("Global type map", GlobalTypeMap);
  6891. dumpModuleIDMap("Global declaration map", GlobalDeclMap);
  6892. dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
  6893. dumpModuleIDMap("Global macro map", GlobalMacroMap);
  6894. dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
  6895. dumpModuleIDMap("Global selector map", GlobalSelectorMap);
  6896. dumpModuleIDMap("Global preprocessed entity map",
  6897. GlobalPreprocessedEntityMap);
  6898. llvm::errs() << "\n*** PCH/Modules Loaded:";
  6899. for (ModuleFile &M : ModuleMgr)
  6900. M.dump();
  6901. }
  6902. /// Return the amount of memory used by memory buffers, breaking down
  6903. /// by heap-backed versus mmap'ed memory.
  6904. void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
  6905. for (ModuleFile &I : ModuleMgr) {
  6906. if (llvm::MemoryBuffer *buf = I.Buffer) {
  6907. size_t bytes = buf->getBufferSize();
  6908. switch (buf->getBufferKind()) {
  6909. case llvm::MemoryBuffer::MemoryBuffer_Malloc:
  6910. sizes.malloc_bytes += bytes;
  6911. break;
  6912. case llvm::MemoryBuffer::MemoryBuffer_MMap:
  6913. sizes.mmap_bytes += bytes;
  6914. break;
  6915. }
  6916. }
  6917. }
  6918. }
  6919. void ASTReader::InitializeSema(Sema &S) {
  6920. SemaObj = &S;
  6921. S.addExternalSource(this);
  6922. // Makes sure any declarations that were deserialized "too early"
  6923. // still get added to the identifier's declaration chains.
  6924. for (uint64_t ID : PreloadedDeclIDs) {
  6925. NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
  6926. pushExternalDeclIntoScope(D, D->getDeclName());
  6927. }
  6928. PreloadedDeclIDs.clear();
  6929. // FIXME: What happens if these are changed by a module import?
  6930. if (!FPPragmaOptions.empty()) {
  6931. assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
  6932. FPOptionsOverride NewOverrides =
  6933. FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
  6934. SemaObj->CurFPFeatures =
  6935. NewOverrides.applyOverrides(SemaObj->getLangOpts());
  6936. }
  6937. SemaObj->OpenCLFeatures = OpenCLExtensions;
  6938. UpdateSema();
  6939. }
  6940. void ASTReader::UpdateSema() {
  6941. assert(SemaObj && "no Sema to update");
  6942. // Load the offsets of the declarations that Sema references.
  6943. // They will be lazily deserialized when needed.
  6944. if (!SemaDeclRefs.empty()) {
  6945. assert(SemaDeclRefs.size() % 3 == 0);
  6946. for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
  6947. if (!SemaObj->StdNamespace)
  6948. SemaObj->StdNamespace = SemaDeclRefs[I];
  6949. if (!SemaObj->StdBadAlloc)
  6950. SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
  6951. if (!SemaObj->StdAlignValT)
  6952. SemaObj->StdAlignValT = SemaDeclRefs[I+2];
  6953. }
  6954. SemaDeclRefs.clear();
  6955. }
  6956. // Update the state of pragmas. Use the same API as if we had encountered the
  6957. // pragma in the source.
  6958. if(OptimizeOffPragmaLocation.isValid())
  6959. SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
  6960. if (PragmaMSStructState != -1)
  6961. SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
  6962. if (PointersToMembersPragmaLocation.isValid()) {
  6963. SemaObj->ActOnPragmaMSPointersToMembers(
  6964. (LangOptions::PragmaMSPointersToMembersKind)
  6965. PragmaMSPointersToMembersState,
  6966. PointersToMembersPragmaLocation);
  6967. }
  6968. SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
  6969. if (PragmaAlignPackCurrentValue) {
  6970. // The bottom of the stack might have a default value. It must be adjusted
  6971. // to the current value to ensure that the packing state is preserved after
  6972. // popping entries that were included/imported from a PCH/module.
  6973. bool DropFirst = false;
  6974. if (!PragmaAlignPackStack.empty() &&
  6975. PragmaAlignPackStack.front().Location.isInvalid()) {
  6976. assert(PragmaAlignPackStack.front().Value ==
  6977. SemaObj->AlignPackStack.DefaultValue &&
  6978. "Expected a default alignment value");
  6979. SemaObj->AlignPackStack.Stack.emplace_back(
  6980. PragmaAlignPackStack.front().SlotLabel,
  6981. SemaObj->AlignPackStack.CurrentValue,
  6982. SemaObj->AlignPackStack.CurrentPragmaLocation,
  6983. PragmaAlignPackStack.front().PushLocation);
  6984. DropFirst = true;
  6985. }
  6986. for (const auto &Entry :
  6987. llvm::ArrayRef(PragmaAlignPackStack).drop_front(DropFirst ? 1 : 0)) {
  6988. SemaObj->AlignPackStack.Stack.emplace_back(
  6989. Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
  6990. }
  6991. if (PragmaAlignPackCurrentLocation.isInvalid()) {
  6992. assert(*PragmaAlignPackCurrentValue ==
  6993. SemaObj->AlignPackStack.DefaultValue &&
  6994. "Expected a default align and pack value");
  6995. // Keep the current values.
  6996. } else {
  6997. SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
  6998. SemaObj->AlignPackStack.CurrentPragmaLocation =
  6999. PragmaAlignPackCurrentLocation;
  7000. }
  7001. }
  7002. if (FpPragmaCurrentValue) {
  7003. // The bottom of the stack might have a default value. It must be adjusted
  7004. // to the current value to ensure that fp-pragma state is preserved after
  7005. // popping entries that were included/imported from a PCH/module.
  7006. bool DropFirst = false;
  7007. if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
  7008. assert(FpPragmaStack.front().Value ==
  7009. SemaObj->FpPragmaStack.DefaultValue &&
  7010. "Expected a default pragma float_control value");
  7011. SemaObj->FpPragmaStack.Stack.emplace_back(
  7012. FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
  7013. SemaObj->FpPragmaStack.CurrentPragmaLocation,
  7014. FpPragmaStack.front().PushLocation);
  7015. DropFirst = true;
  7016. }
  7017. for (const auto &Entry :
  7018. llvm::ArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
  7019. SemaObj->FpPragmaStack.Stack.emplace_back(
  7020. Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
  7021. if (FpPragmaCurrentLocation.isInvalid()) {
  7022. assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
  7023. "Expected a default pragma float_control value");
  7024. // Keep the current values.
  7025. } else {
  7026. SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
  7027. SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
  7028. }
  7029. }
  7030. // For non-modular AST files, restore visiblity of modules.
  7031. for (auto &Import : ImportedModules) {
  7032. if (Import.ImportLoc.isInvalid())
  7033. continue;
  7034. if (Module *Imported = getSubmodule(Import.ID)) {
  7035. SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
  7036. }
  7037. }
  7038. }
  7039. IdentifierInfo *ASTReader::get(StringRef Name) {
  7040. // Note that we are loading an identifier.
  7041. Deserializing AnIdentifier(this);
  7042. IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
  7043. NumIdentifierLookups,
  7044. NumIdentifierLookupHits);
  7045. // We don't need to do identifier table lookups in C++ modules (we preload
  7046. // all interesting declarations, and don't need to use the scope for name
  7047. // lookups). Perform the lookup in PCH files, though, since we don't build
  7048. // a complete initial identifier table if we're carrying on from a PCH.
  7049. if (PP.getLangOpts().CPlusPlus) {
  7050. for (auto *F : ModuleMgr.pch_modules())
  7051. if (Visitor(*F))
  7052. break;
  7053. } else {
  7054. // If there is a global index, look there first to determine which modules
  7055. // provably do not have any results for this identifier.
  7056. GlobalModuleIndex::HitSet Hits;
  7057. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  7058. if (!loadGlobalIndex()) {
  7059. if (GlobalIndex->lookupIdentifier(Name, Hits)) {
  7060. HitsPtr = &Hits;
  7061. }
  7062. }
  7063. ModuleMgr.visit(Visitor, HitsPtr);
  7064. }
  7065. IdentifierInfo *II = Visitor.getIdentifierInfo();
  7066. markIdentifierUpToDate(II);
  7067. return II;
  7068. }
  7069. namespace clang {
  7070. /// An identifier-lookup iterator that enumerates all of the
  7071. /// identifiers stored within a set of AST files.
  7072. class ASTIdentifierIterator : public IdentifierIterator {
  7073. /// The AST reader whose identifiers are being enumerated.
  7074. const ASTReader &Reader;
  7075. /// The current index into the chain of AST files stored in
  7076. /// the AST reader.
  7077. unsigned Index;
  7078. /// The current position within the identifier lookup table
  7079. /// of the current AST file.
  7080. ASTIdentifierLookupTable::key_iterator Current;
  7081. /// The end position within the identifier lookup table of
  7082. /// the current AST file.
  7083. ASTIdentifierLookupTable::key_iterator End;
  7084. /// Whether to skip any modules in the ASTReader.
  7085. bool SkipModules;
  7086. public:
  7087. explicit ASTIdentifierIterator(const ASTReader &Reader,
  7088. bool SkipModules = false);
  7089. StringRef Next() override;
  7090. };
  7091. } // namespace clang
  7092. ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
  7093. bool SkipModules)
  7094. : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
  7095. }
  7096. StringRef ASTIdentifierIterator::Next() {
  7097. while (Current == End) {
  7098. // If we have exhausted all of our AST files, we're done.
  7099. if (Index == 0)
  7100. return StringRef();
  7101. --Index;
  7102. ModuleFile &F = Reader.ModuleMgr[Index];
  7103. if (SkipModules && F.isModule())
  7104. continue;
  7105. ASTIdentifierLookupTable *IdTable =
  7106. (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
  7107. Current = IdTable->key_begin();
  7108. End = IdTable->key_end();
  7109. }
  7110. // We have any identifiers remaining in the current AST file; return
  7111. // the next one.
  7112. StringRef Result = *Current;
  7113. ++Current;
  7114. return Result;
  7115. }
  7116. namespace {
  7117. /// A utility for appending two IdentifierIterators.
  7118. class ChainedIdentifierIterator : public IdentifierIterator {
  7119. std::unique_ptr<IdentifierIterator> Current;
  7120. std::unique_ptr<IdentifierIterator> Queued;
  7121. public:
  7122. ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
  7123. std::unique_ptr<IdentifierIterator> Second)
  7124. : Current(std::move(First)), Queued(std::move(Second)) {}
  7125. StringRef Next() override {
  7126. if (!Current)
  7127. return StringRef();
  7128. StringRef result = Current->Next();
  7129. if (!result.empty())
  7130. return result;
  7131. // Try the queued iterator, which may itself be empty.
  7132. Current.reset();
  7133. std::swap(Current, Queued);
  7134. return Next();
  7135. }
  7136. };
  7137. } // namespace
  7138. IdentifierIterator *ASTReader::getIdentifiers() {
  7139. if (!loadGlobalIndex()) {
  7140. std::unique_ptr<IdentifierIterator> ReaderIter(
  7141. new ASTIdentifierIterator(*this, /*SkipModules=*/true));
  7142. std::unique_ptr<IdentifierIterator> ModulesIter(
  7143. GlobalIndex->createIdentifierIterator());
  7144. return new ChainedIdentifierIterator(std::move(ReaderIter),
  7145. std::move(ModulesIter));
  7146. }
  7147. return new ASTIdentifierIterator(*this);
  7148. }
  7149. namespace clang {
  7150. namespace serialization {
  7151. class ReadMethodPoolVisitor {
  7152. ASTReader &Reader;
  7153. Selector Sel;
  7154. unsigned PriorGeneration;
  7155. unsigned InstanceBits = 0;
  7156. unsigned FactoryBits = 0;
  7157. bool InstanceHasMoreThanOneDecl = false;
  7158. bool FactoryHasMoreThanOneDecl = false;
  7159. SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
  7160. SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
  7161. public:
  7162. ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
  7163. unsigned PriorGeneration)
  7164. : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
  7165. bool operator()(ModuleFile &M) {
  7166. if (!M.SelectorLookupTable)
  7167. return false;
  7168. // If we've already searched this module file, skip it now.
  7169. if (M.Generation <= PriorGeneration)
  7170. return true;
  7171. ++Reader.NumMethodPoolTableLookups;
  7172. ASTSelectorLookupTable *PoolTable
  7173. = (ASTSelectorLookupTable*)M.SelectorLookupTable;
  7174. ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
  7175. if (Pos == PoolTable->end())
  7176. return false;
  7177. ++Reader.NumMethodPoolTableHits;
  7178. ++Reader.NumSelectorsRead;
  7179. // FIXME: Not quite happy with the statistics here. We probably should
  7180. // disable this tracking when called via LoadSelector.
  7181. // Also, should entries without methods count as misses?
  7182. ++Reader.NumMethodPoolEntriesRead;
  7183. ASTSelectorLookupTrait::data_type Data = *Pos;
  7184. if (Reader.DeserializationListener)
  7185. Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
  7186. // Append methods in the reverse order, so that later we can process them
  7187. // in the order they appear in the source code by iterating through
  7188. // the vector in the reverse order.
  7189. InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
  7190. FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
  7191. InstanceBits = Data.InstanceBits;
  7192. FactoryBits = Data.FactoryBits;
  7193. InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
  7194. FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
  7195. return false;
  7196. }
  7197. /// Retrieve the instance methods found by this visitor.
  7198. ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
  7199. return InstanceMethods;
  7200. }
  7201. /// Retrieve the instance methods found by this visitor.
  7202. ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
  7203. return FactoryMethods;
  7204. }
  7205. unsigned getInstanceBits() const { return InstanceBits; }
  7206. unsigned getFactoryBits() const { return FactoryBits; }
  7207. bool instanceHasMoreThanOneDecl() const {
  7208. return InstanceHasMoreThanOneDecl;
  7209. }
  7210. bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
  7211. };
  7212. } // namespace serialization
  7213. } // namespace clang
  7214. /// Add the given set of methods to the method list.
  7215. static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
  7216. ObjCMethodList &List) {
  7217. for (ObjCMethodDecl *M : llvm::reverse(Methods))
  7218. S.addMethodToGlobalList(&List, M);
  7219. }
  7220. void ASTReader::ReadMethodPool(Selector Sel) {
  7221. // Get the selector generation and update it to the current generation.
  7222. unsigned &Generation = SelectorGeneration[Sel];
  7223. unsigned PriorGeneration = Generation;
  7224. Generation = getGeneration();
  7225. SelectorOutOfDate[Sel] = false;
  7226. // Search for methods defined with this selector.
  7227. ++NumMethodPoolLookups;
  7228. ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
  7229. ModuleMgr.visit(Visitor);
  7230. if (Visitor.getInstanceMethods().empty() &&
  7231. Visitor.getFactoryMethods().empty())
  7232. return;
  7233. ++NumMethodPoolHits;
  7234. if (!getSema())
  7235. return;
  7236. Sema &S = *getSema();
  7237. Sema::GlobalMethodPool::iterator Pos =
  7238. S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
  7239. .first;
  7240. Pos->second.first.setBits(Visitor.getInstanceBits());
  7241. Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
  7242. Pos->second.second.setBits(Visitor.getFactoryBits());
  7243. Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
  7244. // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
  7245. // when building a module we keep every method individually and may need to
  7246. // update hasMoreThanOneDecl as we add the methods.
  7247. addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
  7248. addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
  7249. }
  7250. void ASTReader::updateOutOfDateSelector(Selector Sel) {
  7251. if (SelectorOutOfDate[Sel])
  7252. ReadMethodPool(Sel);
  7253. }
  7254. void ASTReader::ReadKnownNamespaces(
  7255. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  7256. Namespaces.clear();
  7257. for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
  7258. if (NamespaceDecl *Namespace
  7259. = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
  7260. Namespaces.push_back(Namespace);
  7261. }
  7262. }
  7263. void ASTReader::ReadUndefinedButUsed(
  7264. llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
  7265. for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
  7266. NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
  7267. SourceLocation Loc =
  7268. SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
  7269. Undefined.insert(std::make_pair(D, Loc));
  7270. }
  7271. }
  7272. void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
  7273. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
  7274. Exprs) {
  7275. for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
  7276. FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
  7277. uint64_t Count = DelayedDeleteExprs[Idx++];
  7278. for (uint64_t C = 0; C < Count; ++C) {
  7279. SourceLocation DeleteLoc =
  7280. SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
  7281. const bool IsArrayForm = DelayedDeleteExprs[Idx++];
  7282. Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
  7283. }
  7284. }
  7285. }
  7286. void ASTReader::ReadTentativeDefinitions(
  7287. SmallVectorImpl<VarDecl *> &TentativeDefs) {
  7288. for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
  7289. VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
  7290. if (Var)
  7291. TentativeDefs.push_back(Var);
  7292. }
  7293. TentativeDefinitions.clear();
  7294. }
  7295. void ASTReader::ReadUnusedFileScopedDecls(
  7296. SmallVectorImpl<const DeclaratorDecl *> &Decls) {
  7297. for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
  7298. DeclaratorDecl *D
  7299. = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
  7300. if (D)
  7301. Decls.push_back(D);
  7302. }
  7303. UnusedFileScopedDecls.clear();
  7304. }
  7305. void ASTReader::ReadDelegatingConstructors(
  7306. SmallVectorImpl<CXXConstructorDecl *> &Decls) {
  7307. for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
  7308. CXXConstructorDecl *D
  7309. = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
  7310. if (D)
  7311. Decls.push_back(D);
  7312. }
  7313. DelegatingCtorDecls.clear();
  7314. }
  7315. void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
  7316. for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
  7317. TypedefNameDecl *D
  7318. = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
  7319. if (D)
  7320. Decls.push_back(D);
  7321. }
  7322. ExtVectorDecls.clear();
  7323. }
  7324. void ASTReader::ReadUnusedLocalTypedefNameCandidates(
  7325. llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
  7326. for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
  7327. ++I) {
  7328. TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
  7329. GetDecl(UnusedLocalTypedefNameCandidates[I]));
  7330. if (D)
  7331. Decls.insert(D);
  7332. }
  7333. UnusedLocalTypedefNameCandidates.clear();
  7334. }
  7335. void ASTReader::ReadDeclsToCheckForDeferredDiags(
  7336. llvm::SmallSetVector<Decl *, 4> &Decls) {
  7337. for (auto I : DeclsToCheckForDeferredDiags) {
  7338. auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
  7339. if (D)
  7340. Decls.insert(D);
  7341. }
  7342. DeclsToCheckForDeferredDiags.clear();
  7343. }
  7344. void ASTReader::ReadReferencedSelectors(
  7345. SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
  7346. if (ReferencedSelectorsData.empty())
  7347. return;
  7348. // If there are @selector references added them to its pool. This is for
  7349. // implementation of -Wselector.
  7350. unsigned int DataSize = ReferencedSelectorsData.size()-1;
  7351. unsigned I = 0;
  7352. while (I < DataSize) {
  7353. Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
  7354. SourceLocation SelLoc
  7355. = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
  7356. Sels.push_back(std::make_pair(Sel, SelLoc));
  7357. }
  7358. ReferencedSelectorsData.clear();
  7359. }
  7360. void ASTReader::ReadWeakUndeclaredIdentifiers(
  7361. SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
  7362. if (WeakUndeclaredIdentifiers.empty())
  7363. return;
  7364. for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
  7365. IdentifierInfo *WeakId
  7366. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  7367. IdentifierInfo *AliasId
  7368. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  7369. SourceLocation Loc =
  7370. SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
  7371. WeakInfo WI(AliasId, Loc);
  7372. WeakIDs.push_back(std::make_pair(WeakId, WI));
  7373. }
  7374. WeakUndeclaredIdentifiers.clear();
  7375. }
  7376. void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
  7377. for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
  7378. ExternalVTableUse VT;
  7379. VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
  7380. VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
  7381. VT.DefinitionRequired = VTableUses[Idx++];
  7382. VTables.push_back(VT);
  7383. }
  7384. VTableUses.clear();
  7385. }
  7386. void ASTReader::ReadPendingInstantiations(
  7387. SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
  7388. for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
  7389. ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
  7390. SourceLocation Loc
  7391. = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
  7392. Pending.push_back(std::make_pair(D, Loc));
  7393. }
  7394. PendingInstantiations.clear();
  7395. }
  7396. void ASTReader::ReadLateParsedTemplates(
  7397. llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
  7398. &LPTMap) {
  7399. for (auto &LPT : LateParsedTemplates) {
  7400. ModuleFile *FMod = LPT.first;
  7401. RecordDataImpl &LateParsed = LPT.second;
  7402. for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
  7403. /* In loop */) {
  7404. FunctionDecl *FD =
  7405. cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++]));
  7406. auto LT = std::make_unique<LateParsedTemplate>();
  7407. LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
  7408. ModuleFile *F = getOwningModuleFile(LT->D);
  7409. assert(F && "No module");
  7410. unsigned TokN = LateParsed[Idx++];
  7411. LT->Toks.reserve(TokN);
  7412. for (unsigned T = 0; T < TokN; ++T)
  7413. LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
  7414. LPTMap.insert(std::make_pair(FD, std::move(LT)));
  7415. }
  7416. }
  7417. LateParsedTemplates.clear();
  7418. }
  7419. void ASTReader::LoadSelector(Selector Sel) {
  7420. // It would be complicated to avoid reading the methods anyway. So don't.
  7421. ReadMethodPool(Sel);
  7422. }
  7423. void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
  7424. assert(ID && "Non-zero identifier ID required");
  7425. assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
  7426. IdentifiersLoaded[ID - 1] = II;
  7427. if (DeserializationListener)
  7428. DeserializationListener->IdentifierRead(ID, II);
  7429. }
  7430. /// Set the globally-visible declarations associated with the given
  7431. /// identifier.
  7432. ///
  7433. /// If the AST reader is currently in a state where the given declaration IDs
  7434. /// cannot safely be resolved, they are queued until it is safe to resolve
  7435. /// them.
  7436. ///
  7437. /// \param II an IdentifierInfo that refers to one or more globally-visible
  7438. /// declarations.
  7439. ///
  7440. /// \param DeclIDs the set of declaration IDs with the name @p II that are
  7441. /// visible at global scope.
  7442. ///
  7443. /// \param Decls if non-null, this vector will be populated with the set of
  7444. /// deserialized declarations. These declarations will not be pushed into
  7445. /// scope.
  7446. void
  7447. ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
  7448. const SmallVectorImpl<uint32_t> &DeclIDs,
  7449. SmallVectorImpl<Decl *> *Decls) {
  7450. if (NumCurrentElementsDeserializing && !Decls) {
  7451. PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
  7452. return;
  7453. }
  7454. for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
  7455. if (!SemaObj) {
  7456. // Queue this declaration so that it will be added to the
  7457. // translation unit scope and identifier's declaration chain
  7458. // once a Sema object is known.
  7459. PreloadedDeclIDs.push_back(DeclIDs[I]);
  7460. continue;
  7461. }
  7462. NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
  7463. // If we're simply supposed to record the declarations, do so now.
  7464. if (Decls) {
  7465. Decls->push_back(D);
  7466. continue;
  7467. }
  7468. // Introduce this declaration into the translation-unit scope
  7469. // and add it to the declaration chain for this identifier, so
  7470. // that (unqualified) name lookup will find it.
  7471. pushExternalDeclIntoScope(D, II);
  7472. }
  7473. }
  7474. IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
  7475. if (ID == 0)
  7476. return nullptr;
  7477. if (IdentifiersLoaded.empty()) {
  7478. Error("no identifier table in AST file");
  7479. return nullptr;
  7480. }
  7481. ID -= 1;
  7482. if (!IdentifiersLoaded[ID]) {
  7483. GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
  7484. assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
  7485. ModuleFile *M = I->second;
  7486. unsigned Index = ID - M->BaseIdentifierID;
  7487. const unsigned char *Data =
  7488. M->IdentifierTableData + M->IdentifierOffsets[Index];
  7489. ASTIdentifierLookupTrait Trait(*this, *M);
  7490. auto KeyDataLen = Trait.ReadKeyDataLength(Data);
  7491. auto Key = Trait.ReadKey(Data, KeyDataLen.first);
  7492. auto &II = PP.getIdentifierTable().get(Key);
  7493. IdentifiersLoaded[ID] = &II;
  7494. markIdentifierFromAST(*this, II);
  7495. if (DeserializationListener)
  7496. DeserializationListener->IdentifierRead(ID + 1, &II);
  7497. }
  7498. return IdentifiersLoaded[ID];
  7499. }
  7500. IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
  7501. return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
  7502. }
  7503. IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
  7504. if (LocalID < NUM_PREDEF_IDENT_IDS)
  7505. return LocalID;
  7506. if (!M.ModuleOffsetMap.empty())
  7507. ReadModuleOffsetMap(M);
  7508. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7509. = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
  7510. assert(I != M.IdentifierRemap.end()
  7511. && "Invalid index into identifier index remap");
  7512. return LocalID + I->second;
  7513. }
  7514. MacroInfo *ASTReader::getMacro(MacroID ID) {
  7515. if (ID == 0)
  7516. return nullptr;
  7517. if (MacrosLoaded.empty()) {
  7518. Error("no macro table in AST file");
  7519. return nullptr;
  7520. }
  7521. ID -= NUM_PREDEF_MACRO_IDS;
  7522. if (!MacrosLoaded[ID]) {
  7523. GlobalMacroMapType::iterator I
  7524. = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
  7525. assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
  7526. ModuleFile *M = I->second;
  7527. unsigned Index = ID - M->BaseMacroID;
  7528. MacrosLoaded[ID] =
  7529. ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
  7530. if (DeserializationListener)
  7531. DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
  7532. MacrosLoaded[ID]);
  7533. }
  7534. return MacrosLoaded[ID];
  7535. }
  7536. MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
  7537. if (LocalID < NUM_PREDEF_MACRO_IDS)
  7538. return LocalID;
  7539. if (!M.ModuleOffsetMap.empty())
  7540. ReadModuleOffsetMap(M);
  7541. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7542. = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
  7543. assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
  7544. return LocalID + I->second;
  7545. }
  7546. serialization::SubmoduleID
  7547. ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
  7548. if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
  7549. return LocalID;
  7550. if (!M.ModuleOffsetMap.empty())
  7551. ReadModuleOffsetMap(M);
  7552. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7553. = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
  7554. assert(I != M.SubmoduleRemap.end()
  7555. && "Invalid index into submodule index remap");
  7556. return LocalID + I->second;
  7557. }
  7558. Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
  7559. if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
  7560. assert(GlobalID == 0 && "Unhandled global submodule ID");
  7561. return nullptr;
  7562. }
  7563. if (GlobalID > SubmodulesLoaded.size()) {
  7564. Error("submodule ID out of range in AST file");
  7565. return nullptr;
  7566. }
  7567. return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
  7568. }
  7569. Module *ASTReader::getModule(unsigned ID) {
  7570. return getSubmodule(ID);
  7571. }
  7572. ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
  7573. if (ID & 1) {
  7574. // It's a module, look it up by submodule ID.
  7575. auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
  7576. return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
  7577. } else {
  7578. // It's a prefix (preamble, PCH, ...). Look it up by index.
  7579. unsigned IndexFromEnd = ID >> 1;
  7580. assert(IndexFromEnd && "got reference to unknown module file");
  7581. return getModuleManager().pch_modules().end()[-IndexFromEnd];
  7582. }
  7583. }
  7584. unsigned ASTReader::getModuleFileID(ModuleFile *F) {
  7585. if (!F)
  7586. return 1;
  7587. // For a file representing a module, use the submodule ID of the top-level
  7588. // module as the file ID. For any other kind of file, the number of such
  7589. // files loaded beforehand will be the same on reload.
  7590. // FIXME: Is this true even if we have an explicit module file and a PCH?
  7591. if (F->isModule())
  7592. return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
  7593. auto PCHModules = getModuleManager().pch_modules();
  7594. auto I = llvm::find(PCHModules, F);
  7595. assert(I != PCHModules.end() && "emitting reference to unknown file");
  7596. return (I - PCHModules.end()) << 1;
  7597. }
  7598. std::optional<ASTSourceDescriptor> ASTReader::getSourceDescriptor(unsigned ID) {
  7599. if (Module *M = getSubmodule(ID))
  7600. return ASTSourceDescriptor(*M);
  7601. // If there is only a single PCH, return it instead.
  7602. // Chained PCH are not supported.
  7603. const auto &PCHChain = ModuleMgr.pch_modules();
  7604. if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
  7605. ModuleFile &MF = ModuleMgr.getPrimaryModule();
  7606. StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
  7607. StringRef FileName = llvm::sys::path::filename(MF.FileName);
  7608. return ASTSourceDescriptor(ModuleName,
  7609. llvm::sys::path::parent_path(MF.FileName),
  7610. FileName, MF.Signature);
  7611. }
  7612. return std::nullopt;
  7613. }
  7614. ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
  7615. auto I = DefinitionSource.find(FD);
  7616. if (I == DefinitionSource.end())
  7617. return EK_ReplyHazy;
  7618. return I->second ? EK_Never : EK_Always;
  7619. }
  7620. Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
  7621. return DecodeSelector(getGlobalSelectorID(M, LocalID));
  7622. }
  7623. Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
  7624. if (ID == 0)
  7625. return Selector();
  7626. if (ID > SelectorsLoaded.size()) {
  7627. Error("selector ID out of range in AST file");
  7628. return Selector();
  7629. }
  7630. if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
  7631. // Load this selector from the selector table.
  7632. GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
  7633. assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
  7634. ModuleFile &M = *I->second;
  7635. ASTSelectorLookupTrait Trait(*this, M);
  7636. unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
  7637. SelectorsLoaded[ID - 1] =
  7638. Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
  7639. if (DeserializationListener)
  7640. DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
  7641. }
  7642. return SelectorsLoaded[ID - 1];
  7643. }
  7644. Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
  7645. return DecodeSelector(ID);
  7646. }
  7647. uint32_t ASTReader::GetNumExternalSelectors() {
  7648. // ID 0 (the null selector) is considered an external selector.
  7649. return getTotalNumSelectors() + 1;
  7650. }
  7651. serialization::SelectorID
  7652. ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
  7653. if (LocalID < NUM_PREDEF_SELECTOR_IDS)
  7654. return LocalID;
  7655. if (!M.ModuleOffsetMap.empty())
  7656. ReadModuleOffsetMap(M);
  7657. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7658. = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
  7659. assert(I != M.SelectorRemap.end()
  7660. && "Invalid index into selector index remap");
  7661. return LocalID + I->second;
  7662. }
  7663. DeclarationNameLoc
  7664. ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
  7665. switch (Name.getNameKind()) {
  7666. case DeclarationName::CXXConstructorName:
  7667. case DeclarationName::CXXDestructorName:
  7668. case DeclarationName::CXXConversionFunctionName:
  7669. return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
  7670. case DeclarationName::CXXOperatorName:
  7671. return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
  7672. case DeclarationName::CXXLiteralOperatorName:
  7673. return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
  7674. readSourceLocation());
  7675. case DeclarationName::Identifier:
  7676. case DeclarationName::ObjCZeroArgSelector:
  7677. case DeclarationName::ObjCOneArgSelector:
  7678. case DeclarationName::ObjCMultiArgSelector:
  7679. case DeclarationName::CXXUsingDirective:
  7680. case DeclarationName::CXXDeductionGuideName:
  7681. break;
  7682. }
  7683. return DeclarationNameLoc();
  7684. }
  7685. DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
  7686. DeclarationNameInfo NameInfo;
  7687. NameInfo.setName(readDeclarationName());
  7688. NameInfo.setLoc(readSourceLocation());
  7689. NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
  7690. return NameInfo;
  7691. }
  7692. void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
  7693. Info.QualifierLoc = readNestedNameSpecifierLoc();
  7694. unsigned NumTPLists = readInt();
  7695. Info.NumTemplParamLists = NumTPLists;
  7696. if (NumTPLists) {
  7697. Info.TemplParamLists =
  7698. new (getContext()) TemplateParameterList *[NumTPLists];
  7699. for (unsigned i = 0; i != NumTPLists; ++i)
  7700. Info.TemplParamLists[i] = readTemplateParameterList();
  7701. }
  7702. }
  7703. TemplateParameterList *
  7704. ASTRecordReader::readTemplateParameterList() {
  7705. SourceLocation TemplateLoc = readSourceLocation();
  7706. SourceLocation LAngleLoc = readSourceLocation();
  7707. SourceLocation RAngleLoc = readSourceLocation();
  7708. unsigned NumParams = readInt();
  7709. SmallVector<NamedDecl *, 16> Params;
  7710. Params.reserve(NumParams);
  7711. while (NumParams--)
  7712. Params.push_back(readDeclAs<NamedDecl>());
  7713. bool HasRequiresClause = readBool();
  7714. Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
  7715. TemplateParameterList *TemplateParams = TemplateParameterList::Create(
  7716. getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
  7717. return TemplateParams;
  7718. }
  7719. void ASTRecordReader::readTemplateArgumentList(
  7720. SmallVectorImpl<TemplateArgument> &TemplArgs,
  7721. bool Canonicalize) {
  7722. unsigned NumTemplateArgs = readInt();
  7723. TemplArgs.reserve(NumTemplateArgs);
  7724. while (NumTemplateArgs--)
  7725. TemplArgs.push_back(readTemplateArgument(Canonicalize));
  7726. }
  7727. /// Read a UnresolvedSet structure.
  7728. void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
  7729. unsigned NumDecls = readInt();
  7730. Set.reserve(getContext(), NumDecls);
  7731. while (NumDecls--) {
  7732. DeclID ID = readDeclID();
  7733. AccessSpecifier AS = (AccessSpecifier) readInt();
  7734. Set.addLazyDecl(getContext(), ID, AS);
  7735. }
  7736. }
  7737. CXXBaseSpecifier
  7738. ASTRecordReader::readCXXBaseSpecifier() {
  7739. bool isVirtual = readBool();
  7740. bool isBaseOfClass = readBool();
  7741. AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
  7742. bool inheritConstructors = readBool();
  7743. TypeSourceInfo *TInfo = readTypeSourceInfo();
  7744. SourceRange Range = readSourceRange();
  7745. SourceLocation EllipsisLoc = readSourceLocation();
  7746. CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
  7747. EllipsisLoc);
  7748. Result.setInheritConstructors(inheritConstructors);
  7749. return Result;
  7750. }
  7751. CXXCtorInitializer **
  7752. ASTRecordReader::readCXXCtorInitializers() {
  7753. ASTContext &Context = getContext();
  7754. unsigned NumInitializers = readInt();
  7755. assert(NumInitializers && "wrote ctor initializers but have no inits");
  7756. auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
  7757. for (unsigned i = 0; i != NumInitializers; ++i) {
  7758. TypeSourceInfo *TInfo = nullptr;
  7759. bool IsBaseVirtual = false;
  7760. FieldDecl *Member = nullptr;
  7761. IndirectFieldDecl *IndirectMember = nullptr;
  7762. CtorInitializerType Type = (CtorInitializerType) readInt();
  7763. switch (Type) {
  7764. case CTOR_INITIALIZER_BASE:
  7765. TInfo = readTypeSourceInfo();
  7766. IsBaseVirtual = readBool();
  7767. break;
  7768. case CTOR_INITIALIZER_DELEGATING:
  7769. TInfo = readTypeSourceInfo();
  7770. break;
  7771. case CTOR_INITIALIZER_MEMBER:
  7772. Member = readDeclAs<FieldDecl>();
  7773. break;
  7774. case CTOR_INITIALIZER_INDIRECT_MEMBER:
  7775. IndirectMember = readDeclAs<IndirectFieldDecl>();
  7776. break;
  7777. }
  7778. SourceLocation MemberOrEllipsisLoc = readSourceLocation();
  7779. Expr *Init = readExpr();
  7780. SourceLocation LParenLoc = readSourceLocation();
  7781. SourceLocation RParenLoc = readSourceLocation();
  7782. CXXCtorInitializer *BOMInit;
  7783. if (Type == CTOR_INITIALIZER_BASE)
  7784. BOMInit = new (Context)
  7785. CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
  7786. RParenLoc, MemberOrEllipsisLoc);
  7787. else if (Type == CTOR_INITIALIZER_DELEGATING)
  7788. BOMInit = new (Context)
  7789. CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
  7790. else if (Member)
  7791. BOMInit = new (Context)
  7792. CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
  7793. Init, RParenLoc);
  7794. else
  7795. BOMInit = new (Context)
  7796. CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
  7797. LParenLoc, Init, RParenLoc);
  7798. if (/*IsWritten*/readBool()) {
  7799. unsigned SourceOrder = readInt();
  7800. BOMInit->setSourceOrder(SourceOrder);
  7801. }
  7802. CtorInitializers[i] = BOMInit;
  7803. }
  7804. return CtorInitializers;
  7805. }
  7806. NestedNameSpecifierLoc
  7807. ASTRecordReader::readNestedNameSpecifierLoc() {
  7808. ASTContext &Context = getContext();
  7809. unsigned N = readInt();
  7810. NestedNameSpecifierLocBuilder Builder;
  7811. for (unsigned I = 0; I != N; ++I) {
  7812. auto Kind = readNestedNameSpecifierKind();
  7813. switch (Kind) {
  7814. case NestedNameSpecifier::Identifier: {
  7815. IdentifierInfo *II = readIdentifier();
  7816. SourceRange Range = readSourceRange();
  7817. Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
  7818. break;
  7819. }
  7820. case NestedNameSpecifier::Namespace: {
  7821. NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
  7822. SourceRange Range = readSourceRange();
  7823. Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
  7824. break;
  7825. }
  7826. case NestedNameSpecifier::NamespaceAlias: {
  7827. NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
  7828. SourceRange Range = readSourceRange();
  7829. Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
  7830. break;
  7831. }
  7832. case NestedNameSpecifier::TypeSpec:
  7833. case NestedNameSpecifier::TypeSpecWithTemplate: {
  7834. bool Template = readBool();
  7835. TypeSourceInfo *T = readTypeSourceInfo();
  7836. if (!T)
  7837. return NestedNameSpecifierLoc();
  7838. SourceLocation ColonColonLoc = readSourceLocation();
  7839. // FIXME: 'template' keyword location not saved anywhere, so we fake it.
  7840. Builder.Extend(Context,
  7841. Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
  7842. T->getTypeLoc(), ColonColonLoc);
  7843. break;
  7844. }
  7845. case NestedNameSpecifier::Global: {
  7846. SourceLocation ColonColonLoc = readSourceLocation();
  7847. Builder.MakeGlobal(Context, ColonColonLoc);
  7848. break;
  7849. }
  7850. case NestedNameSpecifier::Super: {
  7851. CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
  7852. SourceRange Range = readSourceRange();
  7853. Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
  7854. break;
  7855. }
  7856. }
  7857. }
  7858. return Builder.getWithLocInContext(Context);
  7859. }
  7860. SourceRange ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
  7861. unsigned &Idx, LocSeq *Seq) {
  7862. SourceLocation beg = ReadSourceLocation(F, Record, Idx, Seq);
  7863. SourceLocation end = ReadSourceLocation(F, Record, Idx, Seq);
  7864. return SourceRange(beg, end);
  7865. }
  7866. /// Read a floating-point value
  7867. llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
  7868. return llvm::APFloat(Sem, readAPInt());
  7869. }
  7870. // Read a string
  7871. std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
  7872. unsigned Len = Record[Idx++];
  7873. std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
  7874. Idx += Len;
  7875. return Result;
  7876. }
  7877. std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
  7878. unsigned &Idx) {
  7879. std::string Filename = ReadString(Record, Idx);
  7880. ResolveImportedPath(F, Filename);
  7881. return Filename;
  7882. }
  7883. std::string ASTReader::ReadPath(StringRef BaseDirectory,
  7884. const RecordData &Record, unsigned &Idx) {
  7885. std::string Filename = ReadString(Record, Idx);
  7886. if (!BaseDirectory.empty())
  7887. ResolveImportedPath(Filename, BaseDirectory);
  7888. return Filename;
  7889. }
  7890. VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
  7891. unsigned &Idx) {
  7892. unsigned Major = Record[Idx++];
  7893. unsigned Minor = Record[Idx++];
  7894. unsigned Subminor = Record[Idx++];
  7895. if (Minor == 0)
  7896. return VersionTuple(Major);
  7897. if (Subminor == 0)
  7898. return VersionTuple(Major, Minor - 1);
  7899. return VersionTuple(Major, Minor - 1, Subminor - 1);
  7900. }
  7901. CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
  7902. const RecordData &Record,
  7903. unsigned &Idx) {
  7904. CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
  7905. return CXXTemporary::Create(getContext(), Decl);
  7906. }
  7907. DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
  7908. return Diag(CurrentImportLoc, DiagID);
  7909. }
  7910. DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
  7911. return Diags.Report(Loc, DiagID);
  7912. }
  7913. /// Retrieve the identifier table associated with the
  7914. /// preprocessor.
  7915. IdentifierTable &ASTReader::getIdentifierTable() {
  7916. return PP.getIdentifierTable();
  7917. }
  7918. /// Record that the given ID maps to the given switch-case
  7919. /// statement.
  7920. void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
  7921. assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
  7922. "Already have a SwitchCase with this ID");
  7923. (*CurrSwitchCaseStmts)[ID] = SC;
  7924. }
  7925. /// Retrieve the switch-case statement with the given ID.
  7926. SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
  7927. assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
  7928. return (*CurrSwitchCaseStmts)[ID];
  7929. }
  7930. void ASTReader::ClearSwitchCaseIDs() {
  7931. CurrSwitchCaseStmts->clear();
  7932. }
  7933. void ASTReader::ReadComments() {
  7934. ASTContext &Context = getContext();
  7935. std::vector<RawComment *> Comments;
  7936. for (SmallVectorImpl<std::pair<BitstreamCursor,
  7937. serialization::ModuleFile *>>::iterator
  7938. I = CommentsCursors.begin(),
  7939. E = CommentsCursors.end();
  7940. I != E; ++I) {
  7941. Comments.clear();
  7942. BitstreamCursor &Cursor = I->first;
  7943. serialization::ModuleFile &F = *I->second;
  7944. SavedStreamPosition SavedPosition(Cursor);
  7945. RecordData Record;
  7946. while (true) {
  7947. Expected<llvm::BitstreamEntry> MaybeEntry =
  7948. Cursor.advanceSkippingSubblocks(
  7949. BitstreamCursor::AF_DontPopBlockAtEnd);
  7950. if (!MaybeEntry) {
  7951. Error(MaybeEntry.takeError());
  7952. return;
  7953. }
  7954. llvm::BitstreamEntry Entry = MaybeEntry.get();
  7955. switch (Entry.Kind) {
  7956. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  7957. case llvm::BitstreamEntry::Error:
  7958. Error("malformed block record in AST file");
  7959. return;
  7960. case llvm::BitstreamEntry::EndBlock:
  7961. goto NextCursor;
  7962. case llvm::BitstreamEntry::Record:
  7963. // The interesting case.
  7964. break;
  7965. }
  7966. // Read a record.
  7967. Record.clear();
  7968. Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
  7969. if (!MaybeComment) {
  7970. Error(MaybeComment.takeError());
  7971. return;
  7972. }
  7973. switch ((CommentRecordTypes)MaybeComment.get()) {
  7974. case COMMENTS_RAW_COMMENT: {
  7975. unsigned Idx = 0;
  7976. SourceRange SR = ReadSourceRange(F, Record, Idx);
  7977. RawComment::CommentKind Kind =
  7978. (RawComment::CommentKind) Record[Idx++];
  7979. bool IsTrailingComment = Record[Idx++];
  7980. bool IsAlmostTrailingComment = Record[Idx++];
  7981. Comments.push_back(new (Context) RawComment(
  7982. SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
  7983. break;
  7984. }
  7985. }
  7986. }
  7987. NextCursor:
  7988. llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
  7989. FileToOffsetToComment;
  7990. for (RawComment *C : Comments) {
  7991. SourceLocation CommentLoc = C->getBeginLoc();
  7992. if (CommentLoc.isValid()) {
  7993. std::pair<FileID, unsigned> Loc =
  7994. SourceMgr.getDecomposedLoc(CommentLoc);
  7995. if (Loc.first.isValid())
  7996. Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
  7997. }
  7998. }
  7999. }
  8000. }
  8001. void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
  8002. bool IncludeSystem, bool Complain,
  8003. llvm::function_ref<void(const serialization::InputFile &IF,
  8004. bool isSystem)> Visitor) {
  8005. unsigned NumUserInputs = MF.NumUserInputFiles;
  8006. unsigned NumInputs = MF.InputFilesLoaded.size();
  8007. assert(NumUserInputs <= NumInputs);
  8008. unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
  8009. for (unsigned I = 0; I < N; ++I) {
  8010. bool IsSystem = I >= NumUserInputs;
  8011. InputFile IF = getInputFile(MF, I+1, Complain);
  8012. Visitor(IF, IsSystem);
  8013. }
  8014. }
  8015. void ASTReader::visitTopLevelModuleMaps(
  8016. serialization::ModuleFile &MF,
  8017. llvm::function_ref<void(FileEntryRef FE)> Visitor) {
  8018. unsigned NumInputs = MF.InputFilesLoaded.size();
  8019. for (unsigned I = 0; I < NumInputs; ++I) {
  8020. InputFileInfo IFI = getInputFileInfo(MF, I + 1);
  8021. if (IFI.TopLevelModuleMap)
  8022. if (auto FE = getInputFile(MF, I + 1).getFile())
  8023. Visitor(*FE);
  8024. }
  8025. }
  8026. void ASTReader::finishPendingActions() {
  8027. while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
  8028. !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
  8029. !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
  8030. !PendingUpdateRecords.empty() ||
  8031. !PendingObjCExtensionIvarRedeclarations.empty()) {
  8032. // If any identifiers with corresponding top-level declarations have
  8033. // been loaded, load those declarations now.
  8034. using TopLevelDeclsMap =
  8035. llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
  8036. TopLevelDeclsMap TopLevelDecls;
  8037. while (!PendingIdentifierInfos.empty()) {
  8038. IdentifierInfo *II = PendingIdentifierInfos.back().first;
  8039. SmallVector<uint32_t, 4> DeclIDs =
  8040. std::move(PendingIdentifierInfos.back().second);
  8041. PendingIdentifierInfos.pop_back();
  8042. SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
  8043. }
  8044. // Load each function type that we deferred loading because it was a
  8045. // deduced type that might refer to a local type declared within itself.
  8046. for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
  8047. auto *FD = PendingFunctionTypes[I].first;
  8048. FD->setType(GetType(PendingFunctionTypes[I].second));
  8049. // If we gave a function a deduced return type, remember that we need to
  8050. // propagate that along the redeclaration chain.
  8051. auto *DT = FD->getReturnType()->getContainedDeducedType();
  8052. if (DT && DT->isDeduced())
  8053. PendingDeducedTypeUpdates.insert(
  8054. {FD->getCanonicalDecl(), FD->getReturnType()});
  8055. }
  8056. PendingFunctionTypes.clear();
  8057. // For each decl chain that we wanted to complete while deserializing, mark
  8058. // it as "still needs to be completed".
  8059. for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
  8060. markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
  8061. }
  8062. PendingIncompleteDeclChains.clear();
  8063. // Load pending declaration chains.
  8064. for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
  8065. loadPendingDeclChain(PendingDeclChains[I].first,
  8066. PendingDeclChains[I].second);
  8067. PendingDeclChains.clear();
  8068. // Make the most recent of the top-level declarations visible.
  8069. for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
  8070. TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
  8071. IdentifierInfo *II = TLD->first;
  8072. for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
  8073. pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
  8074. }
  8075. }
  8076. // Load any pending macro definitions.
  8077. for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
  8078. IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
  8079. SmallVector<PendingMacroInfo, 2> GlobalIDs;
  8080. GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
  8081. // Initialize the macro history from chained-PCHs ahead of module imports.
  8082. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  8083. ++IDIdx) {
  8084. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  8085. if (!Info.M->isModule())
  8086. resolvePendingMacro(II, Info);
  8087. }
  8088. // Handle module imports.
  8089. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  8090. ++IDIdx) {
  8091. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  8092. if (Info.M->isModule())
  8093. resolvePendingMacro(II, Info);
  8094. }
  8095. }
  8096. PendingMacroIDs.clear();
  8097. // Wire up the DeclContexts for Decls that we delayed setting until
  8098. // recursive loading is completed.
  8099. while (!PendingDeclContextInfos.empty()) {
  8100. PendingDeclContextInfo Info = PendingDeclContextInfos.front();
  8101. PendingDeclContextInfos.pop_front();
  8102. DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
  8103. DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
  8104. Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
  8105. }
  8106. // Perform any pending declaration updates.
  8107. while (!PendingUpdateRecords.empty()) {
  8108. auto Update = PendingUpdateRecords.pop_back_val();
  8109. ReadingKindTracker ReadingKind(Read_Decl, *this);
  8110. loadDeclUpdateRecords(Update);
  8111. }
  8112. while (!PendingObjCExtensionIvarRedeclarations.empty()) {
  8113. auto ExtensionsPair = PendingObjCExtensionIvarRedeclarations.back().first;
  8114. auto DuplicateIvars =
  8115. PendingObjCExtensionIvarRedeclarations.back().second;
  8116. llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
  8117. StructuralEquivalenceContext Ctx(
  8118. ExtensionsPair.first->getASTContext(),
  8119. ExtensionsPair.second->getASTContext(), NonEquivalentDecls,
  8120. StructuralEquivalenceKind::Default, /*StrictTypeSpelling =*/false,
  8121. /*Complain =*/false,
  8122. /*ErrorOnTagTypeMismatch =*/true);
  8123. if (Ctx.IsEquivalent(ExtensionsPair.first, ExtensionsPair.second)) {
  8124. // Merge redeclared ivars with their predecessors.
  8125. for (auto IvarPair : DuplicateIvars) {
  8126. ObjCIvarDecl *Ivar = IvarPair.first, *PrevIvar = IvarPair.second;
  8127. // Change semantic DeclContext but keep the lexical one.
  8128. Ivar->setDeclContextsImpl(PrevIvar->getDeclContext(),
  8129. Ivar->getLexicalDeclContext(),
  8130. getContext());
  8131. getContext().setPrimaryMergedDecl(Ivar, PrevIvar->getCanonicalDecl());
  8132. }
  8133. // Invalidate duplicate extension and the cached ivar list.
  8134. ExtensionsPair.first->setInvalidDecl();
  8135. ExtensionsPair.second->getClassInterface()
  8136. ->getDefinition()
  8137. ->setIvarList(nullptr);
  8138. } else {
  8139. for (auto IvarPair : DuplicateIvars) {
  8140. Diag(IvarPair.first->getLocation(),
  8141. diag::err_duplicate_ivar_declaration)
  8142. << IvarPair.first->getIdentifier();
  8143. Diag(IvarPair.second->getLocation(), diag::note_previous_definition);
  8144. }
  8145. }
  8146. PendingObjCExtensionIvarRedeclarations.pop_back();
  8147. }
  8148. }
  8149. // At this point, all update records for loaded decls are in place, so any
  8150. // fake class definitions should have become real.
  8151. assert(PendingFakeDefinitionData.empty() &&
  8152. "faked up a class definition but never saw the real one");
  8153. // If we deserialized any C++ or Objective-C class definitions, any
  8154. // Objective-C protocol definitions, or any redeclarable templates, make sure
  8155. // that all redeclarations point to the definitions. Note that this can only
  8156. // happen now, after the redeclaration chains have been fully wired.
  8157. for (Decl *D : PendingDefinitions) {
  8158. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  8159. if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
  8160. // Make sure that the TagType points at the definition.
  8161. const_cast<TagType*>(TagT)->decl = TD;
  8162. }
  8163. if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
  8164. for (auto *R = getMostRecentExistingDecl(RD); R;
  8165. R = R->getPreviousDecl()) {
  8166. assert((R == D) ==
  8167. cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
  8168. "declaration thinks it's the definition but it isn't");
  8169. cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
  8170. }
  8171. }
  8172. continue;
  8173. }
  8174. if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
  8175. // Make sure that the ObjCInterfaceType points at the definition.
  8176. const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
  8177. ->Decl = ID;
  8178. for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
  8179. cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
  8180. continue;
  8181. }
  8182. if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
  8183. for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
  8184. cast<ObjCProtocolDecl>(R)->Data = PD->Data;
  8185. continue;
  8186. }
  8187. auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
  8188. for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
  8189. cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
  8190. }
  8191. PendingDefinitions.clear();
  8192. // Load the bodies of any functions or methods we've encountered. We do
  8193. // this now (delayed) so that we can be sure that the declaration chains
  8194. // have been fully wired up (hasBody relies on this).
  8195. // FIXME: We shouldn't require complete redeclaration chains here.
  8196. for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
  8197. PBEnd = PendingBodies.end();
  8198. PB != PBEnd; ++PB) {
  8199. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
  8200. // For a function defined inline within a class template, force the
  8201. // canonical definition to be the one inside the canonical definition of
  8202. // the template. This ensures that we instantiate from a correct view
  8203. // of the template.
  8204. //
  8205. // Sadly we can't do this more generally: we can't be sure that all
  8206. // copies of an arbitrary class definition will have the same members
  8207. // defined (eg, some member functions may not be instantiated, and some
  8208. // special members may or may not have been implicitly defined).
  8209. if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
  8210. if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
  8211. continue;
  8212. // FIXME: Check for =delete/=default?
  8213. // FIXME: Complain about ODR violations here?
  8214. const FunctionDecl *Defn = nullptr;
  8215. if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
  8216. FD->setLazyBody(PB->second);
  8217. } else {
  8218. auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
  8219. mergeDefinitionVisibility(NonConstDefn, FD);
  8220. if (!FD->isLateTemplateParsed() &&
  8221. !NonConstDefn->isLateTemplateParsed() &&
  8222. FD->getODRHash() != NonConstDefn->getODRHash()) {
  8223. if (!isa<CXXMethodDecl>(FD)) {
  8224. PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
  8225. } else if (FD->getLexicalParent()->isFileContext() &&
  8226. NonConstDefn->getLexicalParent()->isFileContext()) {
  8227. // Only diagnose out-of-line method definitions. If they are
  8228. // in class definitions, then an error will be generated when
  8229. // processing the class bodies.
  8230. PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
  8231. }
  8232. }
  8233. }
  8234. continue;
  8235. }
  8236. ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
  8237. if (!getContext().getLangOpts().Modules || !MD->hasBody())
  8238. MD->setLazyBody(PB->second);
  8239. }
  8240. PendingBodies.clear();
  8241. // Do some cleanup.
  8242. for (auto *ND : PendingMergedDefinitionsToDeduplicate)
  8243. getContext().deduplicateMergedDefinitonsFor(ND);
  8244. PendingMergedDefinitionsToDeduplicate.clear();
  8245. }
  8246. void ASTReader::diagnoseOdrViolations() {
  8247. if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
  8248. PendingRecordOdrMergeFailures.empty() &&
  8249. PendingFunctionOdrMergeFailures.empty() &&
  8250. PendingEnumOdrMergeFailures.empty() &&
  8251. PendingObjCInterfaceOdrMergeFailures.empty() &&
  8252. PendingObjCProtocolOdrMergeFailures.empty())
  8253. return;
  8254. // Trigger the import of the full definition of each class that had any
  8255. // odr-merging problems, so we can produce better diagnostics for them.
  8256. // These updates may in turn find and diagnose some ODR failures, so take
  8257. // ownership of the set first.
  8258. auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
  8259. PendingOdrMergeFailures.clear();
  8260. for (auto &Merge : OdrMergeFailures) {
  8261. Merge.first->buildLookup();
  8262. Merge.first->decls_begin();
  8263. Merge.first->bases_begin();
  8264. Merge.first->vbases_begin();
  8265. for (auto &RecordPair : Merge.second) {
  8266. auto *RD = RecordPair.first;
  8267. RD->decls_begin();
  8268. RD->bases_begin();
  8269. RD->vbases_begin();
  8270. }
  8271. }
  8272. // Trigger the import of the full definition of each record in C/ObjC.
  8273. auto RecordOdrMergeFailures = std::move(PendingRecordOdrMergeFailures);
  8274. PendingRecordOdrMergeFailures.clear();
  8275. for (auto &Merge : RecordOdrMergeFailures) {
  8276. Merge.first->decls_begin();
  8277. for (auto &D : Merge.second)
  8278. D->decls_begin();
  8279. }
  8280. // Trigger the import of the full interface definition.
  8281. auto ObjCInterfaceOdrMergeFailures =
  8282. std::move(PendingObjCInterfaceOdrMergeFailures);
  8283. PendingObjCInterfaceOdrMergeFailures.clear();
  8284. for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
  8285. Merge.first->decls_begin();
  8286. for (auto &InterfacePair : Merge.second)
  8287. InterfacePair.first->decls_begin();
  8288. }
  8289. // Trigger the import of functions.
  8290. auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
  8291. PendingFunctionOdrMergeFailures.clear();
  8292. for (auto &Merge : FunctionOdrMergeFailures) {
  8293. Merge.first->buildLookup();
  8294. Merge.first->decls_begin();
  8295. Merge.first->getBody();
  8296. for (auto &FD : Merge.second) {
  8297. FD->buildLookup();
  8298. FD->decls_begin();
  8299. FD->getBody();
  8300. }
  8301. }
  8302. // Trigger the import of enums.
  8303. auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
  8304. PendingEnumOdrMergeFailures.clear();
  8305. for (auto &Merge : EnumOdrMergeFailures) {
  8306. Merge.first->decls_begin();
  8307. for (auto &Enum : Merge.second) {
  8308. Enum->decls_begin();
  8309. }
  8310. }
  8311. // Trigger the import of the full protocol definition.
  8312. auto ObjCProtocolOdrMergeFailures =
  8313. std::move(PendingObjCProtocolOdrMergeFailures);
  8314. PendingObjCProtocolOdrMergeFailures.clear();
  8315. for (auto &Merge : ObjCProtocolOdrMergeFailures) {
  8316. Merge.first->decls_begin();
  8317. for (auto &ProtocolPair : Merge.second)
  8318. ProtocolPair.first->decls_begin();
  8319. }
  8320. // For each declaration from a merged context, check that the canonical
  8321. // definition of that context also contains a declaration of the same
  8322. // entity.
  8323. //
  8324. // Caution: this loop does things that might invalidate iterators into
  8325. // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
  8326. while (!PendingOdrMergeChecks.empty()) {
  8327. NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
  8328. // FIXME: Skip over implicit declarations for now. This matters for things
  8329. // like implicitly-declared special member functions. This isn't entirely
  8330. // correct; we can end up with multiple unmerged declarations of the same
  8331. // implicit entity.
  8332. if (D->isImplicit())
  8333. continue;
  8334. DeclContext *CanonDef = D->getDeclContext();
  8335. bool Found = false;
  8336. const Decl *DCanon = D->getCanonicalDecl();
  8337. for (auto *RI : D->redecls()) {
  8338. if (RI->getLexicalDeclContext() == CanonDef) {
  8339. Found = true;
  8340. break;
  8341. }
  8342. }
  8343. if (Found)
  8344. continue;
  8345. // Quick check failed, time to do the slow thing. Note, we can't just
  8346. // look up the name of D in CanonDef here, because the member that is
  8347. // in CanonDef might not be found by name lookup (it might have been
  8348. // replaced by a more recent declaration in the lookup table), and we
  8349. // can't necessarily find it in the redeclaration chain because it might
  8350. // be merely mergeable, not redeclarable.
  8351. llvm::SmallVector<const NamedDecl*, 4> Candidates;
  8352. for (auto *CanonMember : CanonDef->decls()) {
  8353. if (CanonMember->getCanonicalDecl() == DCanon) {
  8354. // This can happen if the declaration is merely mergeable and not
  8355. // actually redeclarable (we looked for redeclarations earlier).
  8356. //
  8357. // FIXME: We should be able to detect this more efficiently, without
  8358. // pulling in all of the members of CanonDef.
  8359. Found = true;
  8360. break;
  8361. }
  8362. if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
  8363. if (ND->getDeclName() == D->getDeclName())
  8364. Candidates.push_back(ND);
  8365. }
  8366. if (!Found) {
  8367. // The AST doesn't like TagDecls becoming invalid after they've been
  8368. // completed. We only really need to mark FieldDecls as invalid here.
  8369. if (!isa<TagDecl>(D))
  8370. D->setInvalidDecl();
  8371. // Ensure we don't accidentally recursively enter deserialization while
  8372. // we're producing our diagnostic.
  8373. Deserializing RecursionGuard(this);
  8374. std::string CanonDefModule =
  8375. ODRDiagsEmitter::getOwningModuleNameForDiagnostic(
  8376. cast<Decl>(CanonDef));
  8377. Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
  8378. << D << ODRDiagsEmitter::getOwningModuleNameForDiagnostic(D)
  8379. << CanonDef << CanonDefModule.empty() << CanonDefModule;
  8380. if (Candidates.empty())
  8381. Diag(cast<Decl>(CanonDef)->getLocation(),
  8382. diag::note_module_odr_violation_no_possible_decls) << D;
  8383. else {
  8384. for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
  8385. Diag(Candidates[I]->getLocation(),
  8386. diag::note_module_odr_violation_possible_decl)
  8387. << Candidates[I];
  8388. }
  8389. DiagnosedOdrMergeFailures.insert(CanonDef);
  8390. }
  8391. }
  8392. if (OdrMergeFailures.empty() && RecordOdrMergeFailures.empty() &&
  8393. FunctionOdrMergeFailures.empty() && EnumOdrMergeFailures.empty() &&
  8394. ObjCInterfaceOdrMergeFailures.empty() &&
  8395. ObjCProtocolOdrMergeFailures.empty())
  8396. return;
  8397. // Ensure we don't accidentally recursively enter deserialization while
  8398. // we're producing our diagnostics.
  8399. Deserializing RecursionGuard(this);
  8400. ODRDiagsEmitter DiagsEmitter(Diags, getContext(),
  8401. getPreprocessor().getLangOpts());
  8402. // Issue any pending ODR-failure diagnostics.
  8403. for (auto &Merge : OdrMergeFailures) {
  8404. // If we've already pointed out a specific problem with this class, don't
  8405. // bother issuing a general "something's different" diagnostic.
  8406. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
  8407. continue;
  8408. bool Diagnosed = false;
  8409. CXXRecordDecl *FirstRecord = Merge.first;
  8410. for (auto &RecordPair : Merge.second) {
  8411. if (DiagsEmitter.diagnoseMismatch(FirstRecord, RecordPair.first,
  8412. RecordPair.second)) {
  8413. Diagnosed = true;
  8414. break;
  8415. }
  8416. }
  8417. if (!Diagnosed) {
  8418. // All definitions are updates to the same declaration. This happens if a
  8419. // module instantiates the declaration of a class template specialization
  8420. // and two or more other modules instantiate its definition.
  8421. //
  8422. // FIXME: Indicate which modules had instantiations of this definition.
  8423. // FIXME: How can this even happen?
  8424. Diag(Merge.first->getLocation(),
  8425. diag::err_module_odr_violation_different_instantiations)
  8426. << Merge.first;
  8427. }
  8428. }
  8429. // Issue any pending ODR-failure diagnostics for RecordDecl in C/ObjC. Note
  8430. // that in C++ this is done as a part of CXXRecordDecl ODR checking.
  8431. for (auto &Merge : RecordOdrMergeFailures) {
  8432. // If we've already pointed out a specific problem with this class, don't
  8433. // bother issuing a general "something's different" diagnostic.
  8434. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
  8435. continue;
  8436. RecordDecl *FirstRecord = Merge.first;
  8437. bool Diagnosed = false;
  8438. for (auto *SecondRecord : Merge.second) {
  8439. if (DiagsEmitter.diagnoseMismatch(FirstRecord, SecondRecord)) {
  8440. Diagnosed = true;
  8441. break;
  8442. }
  8443. }
  8444. (void)Diagnosed;
  8445. assert(Diagnosed && "Unable to emit ODR diagnostic.");
  8446. }
  8447. // Issue ODR failures diagnostics for functions.
  8448. for (auto &Merge : FunctionOdrMergeFailures) {
  8449. FunctionDecl *FirstFunction = Merge.first;
  8450. bool Diagnosed = false;
  8451. for (auto &SecondFunction : Merge.second) {
  8452. if (DiagsEmitter.diagnoseMismatch(FirstFunction, SecondFunction)) {
  8453. Diagnosed = true;
  8454. break;
  8455. }
  8456. }
  8457. (void)Diagnosed;
  8458. assert(Diagnosed && "Unable to emit ODR diagnostic.");
  8459. }
  8460. // Issue ODR failures diagnostics for enums.
  8461. for (auto &Merge : EnumOdrMergeFailures) {
  8462. // If we've already pointed out a specific problem with this enum, don't
  8463. // bother issuing a general "something's different" diagnostic.
  8464. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
  8465. continue;
  8466. EnumDecl *FirstEnum = Merge.first;
  8467. bool Diagnosed = false;
  8468. for (auto &SecondEnum : Merge.second) {
  8469. if (DiagsEmitter.diagnoseMismatch(FirstEnum, SecondEnum)) {
  8470. Diagnosed = true;
  8471. break;
  8472. }
  8473. }
  8474. (void)Diagnosed;
  8475. assert(Diagnosed && "Unable to emit ODR diagnostic.");
  8476. }
  8477. for (auto &Merge : ObjCInterfaceOdrMergeFailures) {
  8478. // If we've already pointed out a specific problem with this interface,
  8479. // don't bother issuing a general "something's different" diagnostic.
  8480. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
  8481. continue;
  8482. bool Diagnosed = false;
  8483. ObjCInterfaceDecl *FirstID = Merge.first;
  8484. for (auto &InterfacePair : Merge.second) {
  8485. if (DiagsEmitter.diagnoseMismatch(FirstID, InterfacePair.first,
  8486. InterfacePair.second)) {
  8487. Diagnosed = true;
  8488. break;
  8489. }
  8490. }
  8491. (void)Diagnosed;
  8492. assert(Diagnosed && "Unable to emit ODR diagnostic.");
  8493. }
  8494. for (auto &Merge : ObjCProtocolOdrMergeFailures) {
  8495. // If we've already pointed out a specific problem with this protocol,
  8496. // don't bother issuing a general "something's different" diagnostic.
  8497. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
  8498. continue;
  8499. ObjCProtocolDecl *FirstProtocol = Merge.first;
  8500. bool Diagnosed = false;
  8501. for (auto &ProtocolPair : Merge.second) {
  8502. if (DiagsEmitter.diagnoseMismatch(FirstProtocol, ProtocolPair.first,
  8503. ProtocolPair.second)) {
  8504. Diagnosed = true;
  8505. break;
  8506. }
  8507. }
  8508. (void)Diagnosed;
  8509. assert(Diagnosed && "Unable to emit ODR diagnostic.");
  8510. }
  8511. }
  8512. void ASTReader::StartedDeserializing() {
  8513. if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
  8514. ReadTimer->startTimer();
  8515. }
  8516. void ASTReader::FinishedDeserializing() {
  8517. assert(NumCurrentElementsDeserializing &&
  8518. "FinishedDeserializing not paired with StartedDeserializing");
  8519. if (NumCurrentElementsDeserializing == 1) {
  8520. // We decrease NumCurrentElementsDeserializing only after pending actions
  8521. // are finished, to avoid recursively re-calling finishPendingActions().
  8522. finishPendingActions();
  8523. }
  8524. --NumCurrentElementsDeserializing;
  8525. if (NumCurrentElementsDeserializing == 0) {
  8526. // Propagate exception specification and deduced type updates along
  8527. // redeclaration chains.
  8528. //
  8529. // We do this now rather than in finishPendingActions because we want to
  8530. // be able to walk the complete redeclaration chains of the updated decls.
  8531. while (!PendingExceptionSpecUpdates.empty() ||
  8532. !PendingDeducedTypeUpdates.empty()) {
  8533. auto ESUpdates = std::move(PendingExceptionSpecUpdates);
  8534. PendingExceptionSpecUpdates.clear();
  8535. for (auto Update : ESUpdates) {
  8536. ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
  8537. auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
  8538. auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
  8539. if (auto *Listener = getContext().getASTMutationListener())
  8540. Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
  8541. for (auto *Redecl : Update.second->redecls())
  8542. getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
  8543. }
  8544. auto DTUpdates = std::move(PendingDeducedTypeUpdates);
  8545. PendingDeducedTypeUpdates.clear();
  8546. for (auto Update : DTUpdates) {
  8547. ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
  8548. // FIXME: If the return type is already deduced, check that it matches.
  8549. getContext().adjustDeducedFunctionResultType(Update.first,
  8550. Update.second);
  8551. }
  8552. }
  8553. if (ReadTimer)
  8554. ReadTimer->stopTimer();
  8555. diagnoseOdrViolations();
  8556. // We are not in recursive loading, so it's safe to pass the "interesting"
  8557. // decls to the consumer.
  8558. if (Consumer)
  8559. PassInterestingDeclsToConsumer();
  8560. }
  8561. }
  8562. void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  8563. if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
  8564. // Remove any fake results before adding any real ones.
  8565. auto It = PendingFakeLookupResults.find(II);
  8566. if (It != PendingFakeLookupResults.end()) {
  8567. for (auto *ND : It->second)
  8568. SemaObj->IdResolver.RemoveDecl(ND);
  8569. // FIXME: this works around module+PCH performance issue.
  8570. // Rather than erase the result from the map, which is O(n), just clear
  8571. // the vector of NamedDecls.
  8572. It->second.clear();
  8573. }
  8574. }
  8575. if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
  8576. SemaObj->TUScope->AddDecl(D);
  8577. } else if (SemaObj->TUScope) {
  8578. // Adding the decl to IdResolver may have failed because it was already in
  8579. // (even though it was not added in scope). If it is already in, make sure
  8580. // it gets in the scope as well.
  8581. if (std::find(SemaObj->IdResolver.begin(Name),
  8582. SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
  8583. SemaObj->TUScope->AddDecl(D);
  8584. }
  8585. }
  8586. ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
  8587. ASTContext *Context,
  8588. const PCHContainerReader &PCHContainerRdr,
  8589. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
  8590. StringRef isysroot,
  8591. DisableValidationForModuleKind DisableValidationKind,
  8592. bool AllowASTWithCompilerErrors,
  8593. bool AllowConfigurationMismatch, bool ValidateSystemInputs,
  8594. bool ValidateASTInputFilesContent, bool UseGlobalIndex,
  8595. std::unique_ptr<llvm::Timer> ReadTimer)
  8596. : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
  8597. ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
  8598. : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
  8599. SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
  8600. PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
  8601. ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
  8602. PCHContainerRdr, PP.getHeaderSearchInfo()),
  8603. DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
  8604. DisableValidationKind(DisableValidationKind),
  8605. AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
  8606. AllowConfigurationMismatch(AllowConfigurationMismatch),
  8607. ValidateSystemInputs(ValidateSystemInputs),
  8608. ValidateASTInputFilesContent(ValidateASTInputFilesContent),
  8609. UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
  8610. SourceMgr.setExternalSLocEntrySource(this);
  8611. for (const auto &Ext : Extensions) {
  8612. auto BlockName = Ext->getExtensionMetadata().BlockName;
  8613. auto Known = ModuleFileExtensions.find(BlockName);
  8614. if (Known != ModuleFileExtensions.end()) {
  8615. Diags.Report(diag::warn_duplicate_module_file_extension)
  8616. << BlockName;
  8617. continue;
  8618. }
  8619. ModuleFileExtensions.insert({BlockName, Ext});
  8620. }
  8621. }
  8622. ASTReader::~ASTReader() {
  8623. if (OwnsDeserializationListener)
  8624. delete DeserializationListener;
  8625. }
  8626. IdentifierResolver &ASTReader::getIdResolver() {
  8627. return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
  8628. }
  8629. Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
  8630. unsigned AbbrevID) {
  8631. Idx = 0;
  8632. Record.clear();
  8633. return Cursor.readRecord(AbbrevID, Record);
  8634. }
  8635. //===----------------------------------------------------------------------===//
  8636. //// OMPClauseReader implementation
  8637. ////===----------------------------------------------------------------------===//
  8638. // This has to be in namespace clang because it's friended by all
  8639. // of the OMP clauses.
  8640. namespace clang {
  8641. class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
  8642. ASTRecordReader &Record;
  8643. ASTContext &Context;
  8644. public:
  8645. OMPClauseReader(ASTRecordReader &Record)
  8646. : Record(Record), Context(Record.getContext()) {}
  8647. #define GEN_CLANG_CLAUSE_CLASS
  8648. #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
  8649. #include "llvm/Frontend/OpenMP/OMP.inc"
  8650. OMPClause *readClause();
  8651. void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
  8652. void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
  8653. };
  8654. } // end namespace clang
  8655. OMPClause *ASTRecordReader::readOMPClause() {
  8656. return OMPClauseReader(*this).readClause();
  8657. }
  8658. OMPClause *OMPClauseReader::readClause() {
  8659. OMPClause *C = nullptr;
  8660. switch (llvm::omp::Clause(Record.readInt())) {
  8661. case llvm::omp::OMPC_if:
  8662. C = new (Context) OMPIfClause();
  8663. break;
  8664. case llvm::omp::OMPC_final:
  8665. C = new (Context) OMPFinalClause();
  8666. break;
  8667. case llvm::omp::OMPC_num_threads:
  8668. C = new (Context) OMPNumThreadsClause();
  8669. break;
  8670. case llvm::omp::OMPC_safelen:
  8671. C = new (Context) OMPSafelenClause();
  8672. break;
  8673. case llvm::omp::OMPC_simdlen:
  8674. C = new (Context) OMPSimdlenClause();
  8675. break;
  8676. case llvm::omp::OMPC_sizes: {
  8677. unsigned NumSizes = Record.readInt();
  8678. C = OMPSizesClause::CreateEmpty(Context, NumSizes);
  8679. break;
  8680. }
  8681. case llvm::omp::OMPC_full:
  8682. C = OMPFullClause::CreateEmpty(Context);
  8683. break;
  8684. case llvm::omp::OMPC_partial:
  8685. C = OMPPartialClause::CreateEmpty(Context);
  8686. break;
  8687. case llvm::omp::OMPC_allocator:
  8688. C = new (Context) OMPAllocatorClause();
  8689. break;
  8690. case llvm::omp::OMPC_collapse:
  8691. C = new (Context) OMPCollapseClause();
  8692. break;
  8693. case llvm::omp::OMPC_default:
  8694. C = new (Context) OMPDefaultClause();
  8695. break;
  8696. case llvm::omp::OMPC_proc_bind:
  8697. C = new (Context) OMPProcBindClause();
  8698. break;
  8699. case llvm::omp::OMPC_schedule:
  8700. C = new (Context) OMPScheduleClause();
  8701. break;
  8702. case llvm::omp::OMPC_ordered:
  8703. C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
  8704. break;
  8705. case llvm::omp::OMPC_nowait:
  8706. C = new (Context) OMPNowaitClause();
  8707. break;
  8708. case llvm::omp::OMPC_untied:
  8709. C = new (Context) OMPUntiedClause();
  8710. break;
  8711. case llvm::omp::OMPC_mergeable:
  8712. C = new (Context) OMPMergeableClause();
  8713. break;
  8714. case llvm::omp::OMPC_read:
  8715. C = new (Context) OMPReadClause();
  8716. break;
  8717. case llvm::omp::OMPC_write:
  8718. C = new (Context) OMPWriteClause();
  8719. break;
  8720. case llvm::omp::OMPC_update:
  8721. C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
  8722. break;
  8723. case llvm::omp::OMPC_capture:
  8724. C = new (Context) OMPCaptureClause();
  8725. break;
  8726. case llvm::omp::OMPC_compare:
  8727. C = new (Context) OMPCompareClause();
  8728. break;
  8729. case llvm::omp::OMPC_seq_cst:
  8730. C = new (Context) OMPSeqCstClause();
  8731. break;
  8732. case llvm::omp::OMPC_acq_rel:
  8733. C = new (Context) OMPAcqRelClause();
  8734. break;
  8735. case llvm::omp::OMPC_acquire:
  8736. C = new (Context) OMPAcquireClause();
  8737. break;
  8738. case llvm::omp::OMPC_release:
  8739. C = new (Context) OMPReleaseClause();
  8740. break;
  8741. case llvm::omp::OMPC_relaxed:
  8742. C = new (Context) OMPRelaxedClause();
  8743. break;
  8744. case llvm::omp::OMPC_threads:
  8745. C = new (Context) OMPThreadsClause();
  8746. break;
  8747. case llvm::omp::OMPC_simd:
  8748. C = new (Context) OMPSIMDClause();
  8749. break;
  8750. case llvm::omp::OMPC_nogroup:
  8751. C = new (Context) OMPNogroupClause();
  8752. break;
  8753. case llvm::omp::OMPC_unified_address:
  8754. C = new (Context) OMPUnifiedAddressClause();
  8755. break;
  8756. case llvm::omp::OMPC_unified_shared_memory:
  8757. C = new (Context) OMPUnifiedSharedMemoryClause();
  8758. break;
  8759. case llvm::omp::OMPC_reverse_offload:
  8760. C = new (Context) OMPReverseOffloadClause();
  8761. break;
  8762. case llvm::omp::OMPC_dynamic_allocators:
  8763. C = new (Context) OMPDynamicAllocatorsClause();
  8764. break;
  8765. case llvm::omp::OMPC_atomic_default_mem_order:
  8766. C = new (Context) OMPAtomicDefaultMemOrderClause();
  8767. break;
  8768. case llvm::omp::OMPC_at:
  8769. C = new (Context) OMPAtClause();
  8770. break;
  8771. case llvm::omp::OMPC_severity:
  8772. C = new (Context) OMPSeverityClause();
  8773. break;
  8774. case llvm::omp::OMPC_message:
  8775. C = new (Context) OMPMessageClause();
  8776. break;
  8777. case llvm::omp::OMPC_private:
  8778. C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
  8779. break;
  8780. case llvm::omp::OMPC_firstprivate:
  8781. C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
  8782. break;
  8783. case llvm::omp::OMPC_lastprivate:
  8784. C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
  8785. break;
  8786. case llvm::omp::OMPC_shared:
  8787. C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
  8788. break;
  8789. case llvm::omp::OMPC_reduction: {
  8790. unsigned N = Record.readInt();
  8791. auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
  8792. C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
  8793. break;
  8794. }
  8795. case llvm::omp::OMPC_task_reduction:
  8796. C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
  8797. break;
  8798. case llvm::omp::OMPC_in_reduction:
  8799. C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
  8800. break;
  8801. case llvm::omp::OMPC_linear:
  8802. C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
  8803. break;
  8804. case llvm::omp::OMPC_aligned:
  8805. C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
  8806. break;
  8807. case llvm::omp::OMPC_copyin:
  8808. C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
  8809. break;
  8810. case llvm::omp::OMPC_copyprivate:
  8811. C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
  8812. break;
  8813. case llvm::omp::OMPC_flush:
  8814. C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
  8815. break;
  8816. case llvm::omp::OMPC_depobj:
  8817. C = OMPDepobjClause::CreateEmpty(Context);
  8818. break;
  8819. case llvm::omp::OMPC_depend: {
  8820. unsigned NumVars = Record.readInt();
  8821. unsigned NumLoops = Record.readInt();
  8822. C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
  8823. break;
  8824. }
  8825. case llvm::omp::OMPC_device:
  8826. C = new (Context) OMPDeviceClause();
  8827. break;
  8828. case llvm::omp::OMPC_map: {
  8829. OMPMappableExprListSizeTy Sizes;
  8830. Sizes.NumVars = Record.readInt();
  8831. Sizes.NumUniqueDeclarations = Record.readInt();
  8832. Sizes.NumComponentLists = Record.readInt();
  8833. Sizes.NumComponents = Record.readInt();
  8834. C = OMPMapClause::CreateEmpty(Context, Sizes);
  8835. break;
  8836. }
  8837. case llvm::omp::OMPC_num_teams:
  8838. C = new (Context) OMPNumTeamsClause();
  8839. break;
  8840. case llvm::omp::OMPC_thread_limit:
  8841. C = new (Context) OMPThreadLimitClause();
  8842. break;
  8843. case llvm::omp::OMPC_priority:
  8844. C = new (Context) OMPPriorityClause();
  8845. break;
  8846. case llvm::omp::OMPC_grainsize:
  8847. C = new (Context) OMPGrainsizeClause();
  8848. break;
  8849. case llvm::omp::OMPC_num_tasks:
  8850. C = new (Context) OMPNumTasksClause();
  8851. break;
  8852. case llvm::omp::OMPC_hint:
  8853. C = new (Context) OMPHintClause();
  8854. break;
  8855. case llvm::omp::OMPC_dist_schedule:
  8856. C = new (Context) OMPDistScheduleClause();
  8857. break;
  8858. case llvm::omp::OMPC_defaultmap:
  8859. C = new (Context) OMPDefaultmapClause();
  8860. break;
  8861. case llvm::omp::OMPC_to: {
  8862. OMPMappableExprListSizeTy Sizes;
  8863. Sizes.NumVars = Record.readInt();
  8864. Sizes.NumUniqueDeclarations = Record.readInt();
  8865. Sizes.NumComponentLists = Record.readInt();
  8866. Sizes.NumComponents = Record.readInt();
  8867. C = OMPToClause::CreateEmpty(Context, Sizes);
  8868. break;
  8869. }
  8870. case llvm::omp::OMPC_from: {
  8871. OMPMappableExprListSizeTy Sizes;
  8872. Sizes.NumVars = Record.readInt();
  8873. Sizes.NumUniqueDeclarations = Record.readInt();
  8874. Sizes.NumComponentLists = Record.readInt();
  8875. Sizes.NumComponents = Record.readInt();
  8876. C = OMPFromClause::CreateEmpty(Context, Sizes);
  8877. break;
  8878. }
  8879. case llvm::omp::OMPC_use_device_ptr: {
  8880. OMPMappableExprListSizeTy Sizes;
  8881. Sizes.NumVars = Record.readInt();
  8882. Sizes.NumUniqueDeclarations = Record.readInt();
  8883. Sizes.NumComponentLists = Record.readInt();
  8884. Sizes.NumComponents = Record.readInt();
  8885. C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
  8886. break;
  8887. }
  8888. case llvm::omp::OMPC_use_device_addr: {
  8889. OMPMappableExprListSizeTy Sizes;
  8890. Sizes.NumVars = Record.readInt();
  8891. Sizes.NumUniqueDeclarations = Record.readInt();
  8892. Sizes.NumComponentLists = Record.readInt();
  8893. Sizes.NumComponents = Record.readInt();
  8894. C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
  8895. break;
  8896. }
  8897. case llvm::omp::OMPC_is_device_ptr: {
  8898. OMPMappableExprListSizeTy Sizes;
  8899. Sizes.NumVars = Record.readInt();
  8900. Sizes.NumUniqueDeclarations = Record.readInt();
  8901. Sizes.NumComponentLists = Record.readInt();
  8902. Sizes.NumComponents = Record.readInt();
  8903. C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
  8904. break;
  8905. }
  8906. case llvm::omp::OMPC_has_device_addr: {
  8907. OMPMappableExprListSizeTy Sizes;
  8908. Sizes.NumVars = Record.readInt();
  8909. Sizes.NumUniqueDeclarations = Record.readInt();
  8910. Sizes.NumComponentLists = Record.readInt();
  8911. Sizes.NumComponents = Record.readInt();
  8912. C = OMPHasDeviceAddrClause::CreateEmpty(Context, Sizes);
  8913. break;
  8914. }
  8915. case llvm::omp::OMPC_allocate:
  8916. C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
  8917. break;
  8918. case llvm::omp::OMPC_nontemporal:
  8919. C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
  8920. break;
  8921. case llvm::omp::OMPC_inclusive:
  8922. C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
  8923. break;
  8924. case llvm::omp::OMPC_exclusive:
  8925. C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
  8926. break;
  8927. case llvm::omp::OMPC_order:
  8928. C = new (Context) OMPOrderClause();
  8929. break;
  8930. case llvm::omp::OMPC_init:
  8931. C = OMPInitClause::CreateEmpty(Context, Record.readInt());
  8932. break;
  8933. case llvm::omp::OMPC_use:
  8934. C = new (Context) OMPUseClause();
  8935. break;
  8936. case llvm::omp::OMPC_destroy:
  8937. C = new (Context) OMPDestroyClause();
  8938. break;
  8939. case llvm::omp::OMPC_novariants:
  8940. C = new (Context) OMPNovariantsClause();
  8941. break;
  8942. case llvm::omp::OMPC_nocontext:
  8943. C = new (Context) OMPNocontextClause();
  8944. break;
  8945. case llvm::omp::OMPC_detach:
  8946. C = new (Context) OMPDetachClause();
  8947. break;
  8948. case llvm::omp::OMPC_uses_allocators:
  8949. C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
  8950. break;
  8951. case llvm::omp::OMPC_affinity:
  8952. C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
  8953. break;
  8954. case llvm::omp::OMPC_filter:
  8955. C = new (Context) OMPFilterClause();
  8956. break;
  8957. case llvm::omp::OMPC_bind:
  8958. C = OMPBindClause::CreateEmpty(Context);
  8959. break;
  8960. case llvm::omp::OMPC_align:
  8961. C = new (Context) OMPAlignClause();
  8962. break;
  8963. case llvm::omp::OMPC_ompx_dyn_cgroup_mem:
  8964. C = new (Context) OMPXDynCGroupMemClause();
  8965. break;
  8966. #define OMP_CLAUSE_NO_CLASS(Enum, Str) \
  8967. case llvm::omp::Enum: \
  8968. break;
  8969. #include "llvm/Frontend/OpenMP/OMPKinds.def"
  8970. default:
  8971. break;
  8972. }
  8973. assert(C && "Unknown OMPClause type");
  8974. Visit(C);
  8975. C->setLocStart(Record.readSourceLocation());
  8976. C->setLocEnd(Record.readSourceLocation());
  8977. return C;
  8978. }
  8979. void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
  8980. C->setPreInitStmt(Record.readSubStmt(),
  8981. static_cast<OpenMPDirectiveKind>(Record.readInt()));
  8982. }
  8983. void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
  8984. VisitOMPClauseWithPreInit(C);
  8985. C->setPostUpdateExpr(Record.readSubExpr());
  8986. }
  8987. void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
  8988. VisitOMPClauseWithPreInit(C);
  8989. C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
  8990. C->setNameModifierLoc(Record.readSourceLocation());
  8991. C->setColonLoc(Record.readSourceLocation());
  8992. C->setCondition(Record.readSubExpr());
  8993. C->setLParenLoc(Record.readSourceLocation());
  8994. }
  8995. void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
  8996. VisitOMPClauseWithPreInit(C);
  8997. C->setCondition(Record.readSubExpr());
  8998. C->setLParenLoc(Record.readSourceLocation());
  8999. }
  9000. void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
  9001. VisitOMPClauseWithPreInit(C);
  9002. C->setNumThreads(Record.readSubExpr());
  9003. C->setLParenLoc(Record.readSourceLocation());
  9004. }
  9005. void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
  9006. C->setSafelen(Record.readSubExpr());
  9007. C->setLParenLoc(Record.readSourceLocation());
  9008. }
  9009. void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
  9010. C->setSimdlen(Record.readSubExpr());
  9011. C->setLParenLoc(Record.readSourceLocation());
  9012. }
  9013. void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
  9014. for (Expr *&E : C->getSizesRefs())
  9015. E = Record.readSubExpr();
  9016. C->setLParenLoc(Record.readSourceLocation());
  9017. }
  9018. void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
  9019. void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
  9020. C->setFactor(Record.readSubExpr());
  9021. C->setLParenLoc(Record.readSourceLocation());
  9022. }
  9023. void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
  9024. C->setAllocator(Record.readExpr());
  9025. C->setLParenLoc(Record.readSourceLocation());
  9026. }
  9027. void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
  9028. C->setNumForLoops(Record.readSubExpr());
  9029. C->setLParenLoc(Record.readSourceLocation());
  9030. }
  9031. void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
  9032. C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
  9033. C->setLParenLoc(Record.readSourceLocation());
  9034. C->setDefaultKindKwLoc(Record.readSourceLocation());
  9035. }
  9036. void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
  9037. C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
  9038. C->setLParenLoc(Record.readSourceLocation());
  9039. C->setProcBindKindKwLoc(Record.readSourceLocation());
  9040. }
  9041. void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
  9042. VisitOMPClauseWithPreInit(C);
  9043. C->setScheduleKind(
  9044. static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
  9045. C->setFirstScheduleModifier(
  9046. static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
  9047. C->setSecondScheduleModifier(
  9048. static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
  9049. C->setChunkSize(Record.readSubExpr());
  9050. C->setLParenLoc(Record.readSourceLocation());
  9051. C->setFirstScheduleModifierLoc(Record.readSourceLocation());
  9052. C->setSecondScheduleModifierLoc(Record.readSourceLocation());
  9053. C->setScheduleKindLoc(Record.readSourceLocation());
  9054. C->setCommaLoc(Record.readSourceLocation());
  9055. }
  9056. void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
  9057. C->setNumForLoops(Record.readSubExpr());
  9058. for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
  9059. C->setLoopNumIterations(I, Record.readSubExpr());
  9060. for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
  9061. C->setLoopCounter(I, Record.readSubExpr());
  9062. C->setLParenLoc(Record.readSourceLocation());
  9063. }
  9064. void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
  9065. C->setEventHandler(Record.readSubExpr());
  9066. C->setLParenLoc(Record.readSourceLocation());
  9067. }
  9068. void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
  9069. void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
  9070. void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
  9071. void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
  9072. void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
  9073. void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
  9074. if (C->isExtended()) {
  9075. C->setLParenLoc(Record.readSourceLocation());
  9076. C->setArgumentLoc(Record.readSourceLocation());
  9077. C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
  9078. }
  9079. }
  9080. void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
  9081. void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
  9082. void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
  9083. void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
  9084. void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
  9085. void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
  9086. void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
  9087. void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
  9088. void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
  9089. void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
  9090. void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
  9091. unsigned NumVars = C->varlist_size();
  9092. SmallVector<Expr *, 16> Vars;
  9093. Vars.reserve(NumVars);
  9094. for (unsigned I = 0; I != NumVars; ++I)
  9095. Vars.push_back(Record.readSubExpr());
  9096. C->setVarRefs(Vars);
  9097. C->setIsTarget(Record.readBool());
  9098. C->setIsTargetSync(Record.readBool());
  9099. C->setLParenLoc(Record.readSourceLocation());
  9100. C->setVarLoc(Record.readSourceLocation());
  9101. }
  9102. void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
  9103. C->setInteropVar(Record.readSubExpr());
  9104. C->setLParenLoc(Record.readSourceLocation());
  9105. C->setVarLoc(Record.readSourceLocation());
  9106. }
  9107. void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
  9108. C->setInteropVar(Record.readSubExpr());
  9109. C->setLParenLoc(Record.readSourceLocation());
  9110. C->setVarLoc(Record.readSourceLocation());
  9111. }
  9112. void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
  9113. VisitOMPClauseWithPreInit(C);
  9114. C->setCondition(Record.readSubExpr());
  9115. C->setLParenLoc(Record.readSourceLocation());
  9116. }
  9117. void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
  9118. VisitOMPClauseWithPreInit(C);
  9119. C->setCondition(Record.readSubExpr());
  9120. C->setLParenLoc(Record.readSourceLocation());
  9121. }
  9122. void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
  9123. void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
  9124. OMPUnifiedSharedMemoryClause *) {}
  9125. void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
  9126. void
  9127. OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
  9128. }
  9129. void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
  9130. OMPAtomicDefaultMemOrderClause *C) {
  9131. C->setAtomicDefaultMemOrderKind(
  9132. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
  9133. C->setLParenLoc(Record.readSourceLocation());
  9134. C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
  9135. }
  9136. void OMPClauseReader::VisitOMPAtClause(OMPAtClause *C) {
  9137. C->setAtKind(static_cast<OpenMPAtClauseKind>(Record.readInt()));
  9138. C->setLParenLoc(Record.readSourceLocation());
  9139. C->setAtKindKwLoc(Record.readSourceLocation());
  9140. }
  9141. void OMPClauseReader::VisitOMPSeverityClause(OMPSeverityClause *C) {
  9142. C->setSeverityKind(static_cast<OpenMPSeverityClauseKind>(Record.readInt()));
  9143. C->setLParenLoc(Record.readSourceLocation());
  9144. C->setSeverityKindKwLoc(Record.readSourceLocation());
  9145. }
  9146. void OMPClauseReader::VisitOMPMessageClause(OMPMessageClause *C) {
  9147. C->setMessageString(Record.readSubExpr());
  9148. C->setLParenLoc(Record.readSourceLocation());
  9149. }
  9150. void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
  9151. C->setLParenLoc(Record.readSourceLocation());
  9152. unsigned NumVars = C->varlist_size();
  9153. SmallVector<Expr *, 16> Vars;
  9154. Vars.reserve(NumVars);
  9155. for (unsigned i = 0; i != NumVars; ++i)
  9156. Vars.push_back(Record.readSubExpr());
  9157. C->setVarRefs(Vars);
  9158. Vars.clear();
  9159. for (unsigned i = 0; i != NumVars; ++i)
  9160. Vars.push_back(Record.readSubExpr());
  9161. C->setPrivateCopies(Vars);
  9162. }
  9163. void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
  9164. VisitOMPClauseWithPreInit(C);
  9165. C->setLParenLoc(Record.readSourceLocation());
  9166. unsigned NumVars = C->varlist_size();
  9167. SmallVector<Expr *, 16> Vars;
  9168. Vars.reserve(NumVars);
  9169. for (unsigned i = 0; i != NumVars; ++i)
  9170. Vars.push_back(Record.readSubExpr());
  9171. C->setVarRefs(Vars);
  9172. Vars.clear();
  9173. for (unsigned i = 0; i != NumVars; ++i)
  9174. Vars.push_back(Record.readSubExpr());
  9175. C->setPrivateCopies(Vars);
  9176. Vars.clear();
  9177. for (unsigned i = 0; i != NumVars; ++i)
  9178. Vars.push_back(Record.readSubExpr());
  9179. C->setInits(Vars);
  9180. }
  9181. void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
  9182. VisitOMPClauseWithPostUpdate(C);
  9183. C->setLParenLoc(Record.readSourceLocation());
  9184. C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
  9185. C->setKindLoc(Record.readSourceLocation());
  9186. C->setColonLoc(Record.readSourceLocation());
  9187. unsigned NumVars = C->varlist_size();
  9188. SmallVector<Expr *, 16> Vars;
  9189. Vars.reserve(NumVars);
  9190. for (unsigned i = 0; i != NumVars; ++i)
  9191. Vars.push_back(Record.readSubExpr());
  9192. C->setVarRefs(Vars);
  9193. Vars.clear();
  9194. for (unsigned i = 0; i != NumVars; ++i)
  9195. Vars.push_back(Record.readSubExpr());
  9196. C->setPrivateCopies(Vars);
  9197. Vars.clear();
  9198. for (unsigned i = 0; i != NumVars; ++i)
  9199. Vars.push_back(Record.readSubExpr());
  9200. C->setSourceExprs(Vars);
  9201. Vars.clear();
  9202. for (unsigned i = 0; i != NumVars; ++i)
  9203. Vars.push_back(Record.readSubExpr());
  9204. C->setDestinationExprs(Vars);
  9205. Vars.clear();
  9206. for (unsigned i = 0; i != NumVars; ++i)
  9207. Vars.push_back(Record.readSubExpr());
  9208. C->setAssignmentOps(Vars);
  9209. }
  9210. void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
  9211. C->setLParenLoc(Record.readSourceLocation());
  9212. unsigned NumVars = C->varlist_size();
  9213. SmallVector<Expr *, 16> Vars;
  9214. Vars.reserve(NumVars);
  9215. for (unsigned i = 0; i != NumVars; ++i)
  9216. Vars.push_back(Record.readSubExpr());
  9217. C->setVarRefs(Vars);
  9218. }
  9219. void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
  9220. VisitOMPClauseWithPostUpdate(C);
  9221. C->setLParenLoc(Record.readSourceLocation());
  9222. C->setModifierLoc(Record.readSourceLocation());
  9223. C->setColonLoc(Record.readSourceLocation());
  9224. NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
  9225. DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
  9226. C->setQualifierLoc(NNSL);
  9227. C->setNameInfo(DNI);
  9228. unsigned NumVars = C->varlist_size();
  9229. SmallVector<Expr *, 16> Vars;
  9230. Vars.reserve(NumVars);
  9231. for (unsigned i = 0; i != NumVars; ++i)
  9232. Vars.push_back(Record.readSubExpr());
  9233. C->setVarRefs(Vars);
  9234. Vars.clear();
  9235. for (unsigned i = 0; i != NumVars; ++i)
  9236. Vars.push_back(Record.readSubExpr());
  9237. C->setPrivates(Vars);
  9238. Vars.clear();
  9239. for (unsigned i = 0; i != NumVars; ++i)
  9240. Vars.push_back(Record.readSubExpr());
  9241. C->setLHSExprs(Vars);
  9242. Vars.clear();
  9243. for (unsigned i = 0; i != NumVars; ++i)
  9244. Vars.push_back(Record.readSubExpr());
  9245. C->setRHSExprs(Vars);
  9246. Vars.clear();
  9247. for (unsigned i = 0; i != NumVars; ++i)
  9248. Vars.push_back(Record.readSubExpr());
  9249. C->setReductionOps(Vars);
  9250. if (C->getModifier() == OMPC_REDUCTION_inscan) {
  9251. Vars.clear();
  9252. for (unsigned i = 0; i != NumVars; ++i)
  9253. Vars.push_back(Record.readSubExpr());
  9254. C->setInscanCopyOps(Vars);
  9255. Vars.clear();
  9256. for (unsigned i = 0; i != NumVars; ++i)
  9257. Vars.push_back(Record.readSubExpr());
  9258. C->setInscanCopyArrayTemps(Vars);
  9259. Vars.clear();
  9260. for (unsigned i = 0; i != NumVars; ++i)
  9261. Vars.push_back(Record.readSubExpr());
  9262. C->setInscanCopyArrayElems(Vars);
  9263. }
  9264. }
  9265. void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
  9266. VisitOMPClauseWithPostUpdate(C);
  9267. C->setLParenLoc(Record.readSourceLocation());
  9268. C->setColonLoc(Record.readSourceLocation());
  9269. NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
  9270. DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
  9271. C->setQualifierLoc(NNSL);
  9272. C->setNameInfo(DNI);
  9273. unsigned NumVars = C->varlist_size();
  9274. SmallVector<Expr *, 16> Vars;
  9275. Vars.reserve(NumVars);
  9276. for (unsigned I = 0; I != NumVars; ++I)
  9277. Vars.push_back(Record.readSubExpr());
  9278. C->setVarRefs(Vars);
  9279. Vars.clear();
  9280. for (unsigned I = 0; I != NumVars; ++I)
  9281. Vars.push_back(Record.readSubExpr());
  9282. C->setPrivates(Vars);
  9283. Vars.clear();
  9284. for (unsigned I = 0; I != NumVars; ++I)
  9285. Vars.push_back(Record.readSubExpr());
  9286. C->setLHSExprs(Vars);
  9287. Vars.clear();
  9288. for (unsigned I = 0; I != NumVars; ++I)
  9289. Vars.push_back(Record.readSubExpr());
  9290. C->setRHSExprs(Vars);
  9291. Vars.clear();
  9292. for (unsigned I = 0; I != NumVars; ++I)
  9293. Vars.push_back(Record.readSubExpr());
  9294. C->setReductionOps(Vars);
  9295. }
  9296. void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
  9297. VisitOMPClauseWithPostUpdate(C);
  9298. C->setLParenLoc(Record.readSourceLocation());
  9299. C->setColonLoc(Record.readSourceLocation());
  9300. NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
  9301. DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
  9302. C->setQualifierLoc(NNSL);
  9303. C->setNameInfo(DNI);
  9304. unsigned NumVars = C->varlist_size();
  9305. SmallVector<Expr *, 16> Vars;
  9306. Vars.reserve(NumVars);
  9307. for (unsigned I = 0; I != NumVars; ++I)
  9308. Vars.push_back(Record.readSubExpr());
  9309. C->setVarRefs(Vars);
  9310. Vars.clear();
  9311. for (unsigned I = 0; I != NumVars; ++I)
  9312. Vars.push_back(Record.readSubExpr());
  9313. C->setPrivates(Vars);
  9314. Vars.clear();
  9315. for (unsigned I = 0; I != NumVars; ++I)
  9316. Vars.push_back(Record.readSubExpr());
  9317. C->setLHSExprs(Vars);
  9318. Vars.clear();
  9319. for (unsigned I = 0; I != NumVars; ++I)
  9320. Vars.push_back(Record.readSubExpr());
  9321. C->setRHSExprs(Vars);
  9322. Vars.clear();
  9323. for (unsigned I = 0; I != NumVars; ++I)
  9324. Vars.push_back(Record.readSubExpr());
  9325. C->setReductionOps(Vars);
  9326. Vars.clear();
  9327. for (unsigned I = 0; I != NumVars; ++I)
  9328. Vars.push_back(Record.readSubExpr());
  9329. C->setTaskgroupDescriptors(Vars);
  9330. }
  9331. void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
  9332. VisitOMPClauseWithPostUpdate(C);
  9333. C->setLParenLoc(Record.readSourceLocation());
  9334. C->setColonLoc(Record.readSourceLocation());
  9335. C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
  9336. C->setModifierLoc(Record.readSourceLocation());
  9337. unsigned NumVars = C->varlist_size();
  9338. SmallVector<Expr *, 16> Vars;
  9339. Vars.reserve(NumVars);
  9340. for (unsigned i = 0; i != NumVars; ++i)
  9341. Vars.push_back(Record.readSubExpr());
  9342. C->setVarRefs(Vars);
  9343. Vars.clear();
  9344. for (unsigned i = 0; i != NumVars; ++i)
  9345. Vars.push_back(Record.readSubExpr());
  9346. C->setPrivates(Vars);
  9347. Vars.clear();
  9348. for (unsigned i = 0; i != NumVars; ++i)
  9349. Vars.push_back(Record.readSubExpr());
  9350. C->setInits(Vars);
  9351. Vars.clear();
  9352. for (unsigned i = 0; i != NumVars; ++i)
  9353. Vars.push_back(Record.readSubExpr());
  9354. C->setUpdates(Vars);
  9355. Vars.clear();
  9356. for (unsigned i = 0; i != NumVars; ++i)
  9357. Vars.push_back(Record.readSubExpr());
  9358. C->setFinals(Vars);
  9359. C->setStep(Record.readSubExpr());
  9360. C->setCalcStep(Record.readSubExpr());
  9361. Vars.clear();
  9362. for (unsigned I = 0; I != NumVars + 1; ++I)
  9363. Vars.push_back(Record.readSubExpr());
  9364. C->setUsedExprs(Vars);
  9365. }
  9366. void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
  9367. C->setLParenLoc(Record.readSourceLocation());
  9368. C->setColonLoc(Record.readSourceLocation());
  9369. unsigned NumVars = C->varlist_size();
  9370. SmallVector<Expr *, 16> Vars;
  9371. Vars.reserve(NumVars);
  9372. for (unsigned i = 0; i != NumVars; ++i)
  9373. Vars.push_back(Record.readSubExpr());
  9374. C->setVarRefs(Vars);
  9375. C->setAlignment(Record.readSubExpr());
  9376. }
  9377. void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
  9378. C->setLParenLoc(Record.readSourceLocation());
  9379. unsigned NumVars = C->varlist_size();
  9380. SmallVector<Expr *, 16> Exprs;
  9381. Exprs.reserve(NumVars);
  9382. for (unsigned i = 0; i != NumVars; ++i)
  9383. Exprs.push_back(Record.readSubExpr());
  9384. C->setVarRefs(Exprs);
  9385. Exprs.clear();
  9386. for (unsigned i = 0; i != NumVars; ++i)
  9387. Exprs.push_back(Record.readSubExpr());
  9388. C->setSourceExprs(Exprs);
  9389. Exprs.clear();
  9390. for (unsigned i = 0; i != NumVars; ++i)
  9391. Exprs.push_back(Record.readSubExpr());
  9392. C->setDestinationExprs(Exprs);
  9393. Exprs.clear();
  9394. for (unsigned i = 0; i != NumVars; ++i)
  9395. Exprs.push_back(Record.readSubExpr());
  9396. C->setAssignmentOps(Exprs);
  9397. }
  9398. void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
  9399. C->setLParenLoc(Record.readSourceLocation());
  9400. unsigned NumVars = C->varlist_size();
  9401. SmallVector<Expr *, 16> Exprs;
  9402. Exprs.reserve(NumVars);
  9403. for (unsigned i = 0; i != NumVars; ++i)
  9404. Exprs.push_back(Record.readSubExpr());
  9405. C->setVarRefs(Exprs);
  9406. Exprs.clear();
  9407. for (unsigned i = 0; i != NumVars; ++i)
  9408. Exprs.push_back(Record.readSubExpr());
  9409. C->setSourceExprs(Exprs);
  9410. Exprs.clear();
  9411. for (unsigned i = 0; i != NumVars; ++i)
  9412. Exprs.push_back(Record.readSubExpr());
  9413. C->setDestinationExprs(Exprs);
  9414. Exprs.clear();
  9415. for (unsigned i = 0; i != NumVars; ++i)
  9416. Exprs.push_back(Record.readSubExpr());
  9417. C->setAssignmentOps(Exprs);
  9418. }
  9419. void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
  9420. C->setLParenLoc(Record.readSourceLocation());
  9421. unsigned NumVars = C->varlist_size();
  9422. SmallVector<Expr *, 16> Vars;
  9423. Vars.reserve(NumVars);
  9424. for (unsigned i = 0; i != NumVars; ++i)
  9425. Vars.push_back(Record.readSubExpr());
  9426. C->setVarRefs(Vars);
  9427. }
  9428. void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
  9429. C->setDepobj(Record.readSubExpr());
  9430. C->setLParenLoc(Record.readSourceLocation());
  9431. }
  9432. void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
  9433. C->setLParenLoc(Record.readSourceLocation());
  9434. C->setModifier(Record.readSubExpr());
  9435. C->setDependencyKind(
  9436. static_cast<OpenMPDependClauseKind>(Record.readInt()));
  9437. C->setDependencyLoc(Record.readSourceLocation());
  9438. C->setColonLoc(Record.readSourceLocation());
  9439. C->setOmpAllMemoryLoc(Record.readSourceLocation());
  9440. unsigned NumVars = C->varlist_size();
  9441. SmallVector<Expr *, 16> Vars;
  9442. Vars.reserve(NumVars);
  9443. for (unsigned I = 0; I != NumVars; ++I)
  9444. Vars.push_back(Record.readSubExpr());
  9445. C->setVarRefs(Vars);
  9446. for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
  9447. C->setLoopData(I, Record.readSubExpr());
  9448. }
  9449. void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
  9450. VisitOMPClauseWithPreInit(C);
  9451. C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
  9452. C->setDevice(Record.readSubExpr());
  9453. C->setModifierLoc(Record.readSourceLocation());
  9454. C->setLParenLoc(Record.readSourceLocation());
  9455. }
  9456. void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
  9457. C->setLParenLoc(Record.readSourceLocation());
  9458. bool HasIteratorModifier = false;
  9459. for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
  9460. C->setMapTypeModifier(
  9461. I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
  9462. C->setMapTypeModifierLoc(I, Record.readSourceLocation());
  9463. if (C->getMapTypeModifier(I) == OMPC_MAP_MODIFIER_iterator)
  9464. HasIteratorModifier = true;
  9465. }
  9466. C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
  9467. C->setMapperIdInfo(Record.readDeclarationNameInfo());
  9468. C->setMapType(
  9469. static_cast<OpenMPMapClauseKind>(Record.readInt()));
  9470. C->setMapLoc(Record.readSourceLocation());
  9471. C->setColonLoc(Record.readSourceLocation());
  9472. auto NumVars = C->varlist_size();
  9473. auto UniqueDecls = C->getUniqueDeclarationsNum();
  9474. auto TotalLists = C->getTotalComponentListNum();
  9475. auto TotalComponents = C->getTotalComponentsNum();
  9476. SmallVector<Expr *, 16> Vars;
  9477. Vars.reserve(NumVars);
  9478. for (unsigned i = 0; i != NumVars; ++i)
  9479. Vars.push_back(Record.readExpr());
  9480. C->setVarRefs(Vars);
  9481. SmallVector<Expr *, 16> UDMappers;
  9482. UDMappers.reserve(NumVars);
  9483. for (unsigned I = 0; I < NumVars; ++I)
  9484. UDMappers.push_back(Record.readExpr());
  9485. C->setUDMapperRefs(UDMappers);
  9486. if (HasIteratorModifier)
  9487. C->setIteratorModifier(Record.readExpr());
  9488. SmallVector<ValueDecl *, 16> Decls;
  9489. Decls.reserve(UniqueDecls);
  9490. for (unsigned i = 0; i < UniqueDecls; ++i)
  9491. Decls.push_back(Record.readDeclAs<ValueDecl>());
  9492. C->setUniqueDecls(Decls);
  9493. SmallVector<unsigned, 16> ListsPerDecl;
  9494. ListsPerDecl.reserve(UniqueDecls);
  9495. for (unsigned i = 0; i < UniqueDecls; ++i)
  9496. ListsPerDecl.push_back(Record.readInt());
  9497. C->setDeclNumLists(ListsPerDecl);
  9498. SmallVector<unsigned, 32> ListSizes;
  9499. ListSizes.reserve(TotalLists);
  9500. for (unsigned i = 0; i < TotalLists; ++i)
  9501. ListSizes.push_back(Record.readInt());
  9502. C->setComponentListSizes(ListSizes);
  9503. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  9504. Components.reserve(TotalComponents);
  9505. for (unsigned i = 0; i < TotalComponents; ++i) {
  9506. Expr *AssociatedExprPr = Record.readExpr();
  9507. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  9508. Components.emplace_back(AssociatedExprPr, AssociatedDecl,
  9509. /*IsNonContiguous=*/false);
  9510. }
  9511. C->setComponents(Components, ListSizes);
  9512. }
  9513. void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
  9514. C->setLParenLoc(Record.readSourceLocation());
  9515. C->setColonLoc(Record.readSourceLocation());
  9516. C->setAllocator(Record.readSubExpr());
  9517. unsigned NumVars = C->varlist_size();
  9518. SmallVector<Expr *, 16> Vars;
  9519. Vars.reserve(NumVars);
  9520. for (unsigned i = 0; i != NumVars; ++i)
  9521. Vars.push_back(Record.readSubExpr());
  9522. C->setVarRefs(Vars);
  9523. }
  9524. void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
  9525. VisitOMPClauseWithPreInit(C);
  9526. C->setNumTeams(Record.readSubExpr());
  9527. C->setLParenLoc(Record.readSourceLocation());
  9528. }
  9529. void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
  9530. VisitOMPClauseWithPreInit(C);
  9531. C->setThreadLimit(Record.readSubExpr());
  9532. C->setLParenLoc(Record.readSourceLocation());
  9533. }
  9534. void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
  9535. VisitOMPClauseWithPreInit(C);
  9536. C->setPriority(Record.readSubExpr());
  9537. C->setLParenLoc(Record.readSourceLocation());
  9538. }
  9539. void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
  9540. VisitOMPClauseWithPreInit(C);
  9541. C->setModifier(Record.readEnum<OpenMPGrainsizeClauseModifier>());
  9542. C->setGrainsize(Record.readSubExpr());
  9543. C->setModifierLoc(Record.readSourceLocation());
  9544. C->setLParenLoc(Record.readSourceLocation());
  9545. }
  9546. void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
  9547. VisitOMPClauseWithPreInit(C);
  9548. C->setModifier(Record.readEnum<OpenMPNumTasksClauseModifier>());
  9549. C->setNumTasks(Record.readSubExpr());
  9550. C->setModifierLoc(Record.readSourceLocation());
  9551. C->setLParenLoc(Record.readSourceLocation());
  9552. }
  9553. void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
  9554. C->setHint(Record.readSubExpr());
  9555. C->setLParenLoc(Record.readSourceLocation());
  9556. }
  9557. void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
  9558. VisitOMPClauseWithPreInit(C);
  9559. C->setDistScheduleKind(
  9560. static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
  9561. C->setChunkSize(Record.readSubExpr());
  9562. C->setLParenLoc(Record.readSourceLocation());
  9563. C->setDistScheduleKindLoc(Record.readSourceLocation());
  9564. C->setCommaLoc(Record.readSourceLocation());
  9565. }
  9566. void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
  9567. C->setDefaultmapKind(
  9568. static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
  9569. C->setDefaultmapModifier(
  9570. static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
  9571. C->setLParenLoc(Record.readSourceLocation());
  9572. C->setDefaultmapModifierLoc(Record.readSourceLocation());
  9573. C->setDefaultmapKindLoc(Record.readSourceLocation());
  9574. }
  9575. void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
  9576. C->setLParenLoc(Record.readSourceLocation());
  9577. for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
  9578. C->setMotionModifier(
  9579. I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
  9580. C->setMotionModifierLoc(I, Record.readSourceLocation());
  9581. }
  9582. C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
  9583. C->setMapperIdInfo(Record.readDeclarationNameInfo());
  9584. C->setColonLoc(Record.readSourceLocation());
  9585. auto NumVars = C->varlist_size();
  9586. auto UniqueDecls = C->getUniqueDeclarationsNum();
  9587. auto TotalLists = C->getTotalComponentListNum();
  9588. auto TotalComponents = C->getTotalComponentsNum();
  9589. SmallVector<Expr *, 16> Vars;
  9590. Vars.reserve(NumVars);
  9591. for (unsigned i = 0; i != NumVars; ++i)
  9592. Vars.push_back(Record.readSubExpr());
  9593. C->setVarRefs(Vars);
  9594. SmallVector<Expr *, 16> UDMappers;
  9595. UDMappers.reserve(NumVars);
  9596. for (unsigned I = 0; I < NumVars; ++I)
  9597. UDMappers.push_back(Record.readSubExpr());
  9598. C->setUDMapperRefs(UDMappers);
  9599. SmallVector<ValueDecl *, 16> Decls;
  9600. Decls.reserve(UniqueDecls);
  9601. for (unsigned i = 0; i < UniqueDecls; ++i)
  9602. Decls.push_back(Record.readDeclAs<ValueDecl>());
  9603. C->setUniqueDecls(Decls);
  9604. SmallVector<unsigned, 16> ListsPerDecl;
  9605. ListsPerDecl.reserve(UniqueDecls);
  9606. for (unsigned i = 0; i < UniqueDecls; ++i)
  9607. ListsPerDecl.push_back(Record.readInt());
  9608. C->setDeclNumLists(ListsPerDecl);
  9609. SmallVector<unsigned, 32> ListSizes;
  9610. ListSizes.reserve(TotalLists);
  9611. for (unsigned i = 0; i < TotalLists; ++i)
  9612. ListSizes.push_back(Record.readInt());
  9613. C->setComponentListSizes(ListSizes);
  9614. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  9615. Components.reserve(TotalComponents);
  9616. for (unsigned i = 0; i < TotalComponents; ++i) {
  9617. Expr *AssociatedExprPr = Record.readSubExpr();
  9618. bool IsNonContiguous = Record.readBool();
  9619. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  9620. Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
  9621. }
  9622. C->setComponents(Components, ListSizes);
  9623. }
  9624. void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
  9625. C->setLParenLoc(Record.readSourceLocation());
  9626. for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
  9627. C->setMotionModifier(
  9628. I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
  9629. C->setMotionModifierLoc(I, Record.readSourceLocation());
  9630. }
  9631. C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
  9632. C->setMapperIdInfo(Record.readDeclarationNameInfo());
  9633. C->setColonLoc(Record.readSourceLocation());
  9634. auto NumVars = C->varlist_size();
  9635. auto UniqueDecls = C->getUniqueDeclarationsNum();
  9636. auto TotalLists = C->getTotalComponentListNum();
  9637. auto TotalComponents = C->getTotalComponentsNum();
  9638. SmallVector<Expr *, 16> Vars;
  9639. Vars.reserve(NumVars);
  9640. for (unsigned i = 0; i != NumVars; ++i)
  9641. Vars.push_back(Record.readSubExpr());
  9642. C->setVarRefs(Vars);
  9643. SmallVector<Expr *, 16> UDMappers;
  9644. UDMappers.reserve(NumVars);
  9645. for (unsigned I = 0; I < NumVars; ++I)
  9646. UDMappers.push_back(Record.readSubExpr());
  9647. C->setUDMapperRefs(UDMappers);
  9648. SmallVector<ValueDecl *, 16> Decls;
  9649. Decls.reserve(UniqueDecls);
  9650. for (unsigned i = 0; i < UniqueDecls; ++i)
  9651. Decls.push_back(Record.readDeclAs<ValueDecl>());
  9652. C->setUniqueDecls(Decls);
  9653. SmallVector<unsigned, 16> ListsPerDecl;
  9654. ListsPerDecl.reserve(UniqueDecls);
  9655. for (unsigned i = 0; i < UniqueDecls; ++i)
  9656. ListsPerDecl.push_back(Record.readInt());
  9657. C->setDeclNumLists(ListsPerDecl);
  9658. SmallVector<unsigned, 32> ListSizes;
  9659. ListSizes.reserve(TotalLists);
  9660. for (unsigned i = 0; i < TotalLists; ++i)
  9661. ListSizes.push_back(Record.readInt());
  9662. C->setComponentListSizes(ListSizes);
  9663. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  9664. Components.reserve(TotalComponents);
  9665. for (unsigned i = 0; i < TotalComponents; ++i) {
  9666. Expr *AssociatedExprPr = Record.readSubExpr();
  9667. bool IsNonContiguous = Record.readBool();
  9668. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  9669. Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
  9670. }
  9671. C->setComponents(Components, ListSizes);
  9672. }
  9673. void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
  9674. C->setLParenLoc(Record.readSourceLocation());
  9675. auto NumVars = C->varlist_size();
  9676. auto UniqueDecls = C->getUniqueDeclarationsNum();
  9677. auto TotalLists = C->getTotalComponentListNum();
  9678. auto TotalComponents = C->getTotalComponentsNum();
  9679. SmallVector<Expr *, 16> Vars;
  9680. Vars.reserve(NumVars);
  9681. for (unsigned i = 0; i != NumVars; ++i)
  9682. Vars.push_back(Record.readSubExpr());
  9683. C->setVarRefs(Vars);
  9684. Vars.clear();
  9685. for (unsigned i = 0; i != NumVars; ++i)
  9686. Vars.push_back(Record.readSubExpr());
  9687. C->setPrivateCopies(Vars);
  9688. Vars.clear();
  9689. for (unsigned i = 0; i != NumVars; ++i)
  9690. Vars.push_back(Record.readSubExpr());
  9691. C->setInits(Vars);
  9692. SmallVector<ValueDecl *, 16> Decls;
  9693. Decls.reserve(UniqueDecls);
  9694. for (unsigned i = 0; i < UniqueDecls; ++i)
  9695. Decls.push_back(Record.readDeclAs<ValueDecl>());
  9696. C->setUniqueDecls(Decls);
  9697. SmallVector<unsigned, 16> ListsPerDecl;
  9698. ListsPerDecl.reserve(UniqueDecls);
  9699. for (unsigned i = 0; i < UniqueDecls; ++i)
  9700. ListsPerDecl.push_back(Record.readInt());
  9701. C->setDeclNumLists(ListsPerDecl);
  9702. SmallVector<unsigned, 32> ListSizes;
  9703. ListSizes.reserve(TotalLists);
  9704. for (unsigned i = 0; i < TotalLists; ++i)
  9705. ListSizes.push_back(Record.readInt());
  9706. C->setComponentListSizes(ListSizes);
  9707. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  9708. Components.reserve(TotalComponents);
  9709. for (unsigned i = 0; i < TotalComponents; ++i) {
  9710. auto *AssociatedExprPr = Record.readSubExpr();
  9711. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  9712. Components.emplace_back(AssociatedExprPr, AssociatedDecl,
  9713. /*IsNonContiguous=*/false);
  9714. }
  9715. C->setComponents(Components, ListSizes);
  9716. }
  9717. void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
  9718. C->setLParenLoc(Record.readSourceLocation());
  9719. auto NumVars = C->varlist_size();
  9720. auto UniqueDecls = C->getUniqueDeclarationsNum();
  9721. auto TotalLists = C->getTotalComponentListNum();
  9722. auto TotalComponents = C->getTotalComponentsNum();
  9723. SmallVector<Expr *, 16> Vars;
  9724. Vars.reserve(NumVars);
  9725. for (unsigned i = 0; i != NumVars; ++i)
  9726. Vars.push_back(Record.readSubExpr());
  9727. C->setVarRefs(Vars);
  9728. SmallVector<ValueDecl *, 16> Decls;
  9729. Decls.reserve(UniqueDecls);
  9730. for (unsigned i = 0; i < UniqueDecls; ++i)
  9731. Decls.push_back(Record.readDeclAs<ValueDecl>());
  9732. C->setUniqueDecls(Decls);
  9733. SmallVector<unsigned, 16> ListsPerDecl;
  9734. ListsPerDecl.reserve(UniqueDecls);
  9735. for (unsigned i = 0; i < UniqueDecls; ++i)
  9736. ListsPerDecl.push_back(Record.readInt());
  9737. C->setDeclNumLists(ListsPerDecl);
  9738. SmallVector<unsigned, 32> ListSizes;
  9739. ListSizes.reserve(TotalLists);
  9740. for (unsigned i = 0; i < TotalLists; ++i)
  9741. ListSizes.push_back(Record.readInt());
  9742. C->setComponentListSizes(ListSizes);
  9743. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  9744. Components.reserve(TotalComponents);
  9745. for (unsigned i = 0; i < TotalComponents; ++i) {
  9746. Expr *AssociatedExpr = Record.readSubExpr();
  9747. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  9748. Components.emplace_back(AssociatedExpr, AssociatedDecl,
  9749. /*IsNonContiguous*/ false);
  9750. }
  9751. C->setComponents(Components, ListSizes);
  9752. }
  9753. void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
  9754. C->setLParenLoc(Record.readSourceLocation());
  9755. auto NumVars = C->varlist_size();
  9756. auto UniqueDecls = C->getUniqueDeclarationsNum();
  9757. auto TotalLists = C->getTotalComponentListNum();
  9758. auto TotalComponents = C->getTotalComponentsNum();
  9759. SmallVector<Expr *, 16> Vars;
  9760. Vars.reserve(NumVars);
  9761. for (unsigned i = 0; i != NumVars; ++i)
  9762. Vars.push_back(Record.readSubExpr());
  9763. C->setVarRefs(Vars);
  9764. Vars.clear();
  9765. SmallVector<ValueDecl *, 16> Decls;
  9766. Decls.reserve(UniqueDecls);
  9767. for (unsigned i = 0; i < UniqueDecls; ++i)
  9768. Decls.push_back(Record.readDeclAs<ValueDecl>());
  9769. C->setUniqueDecls(Decls);
  9770. SmallVector<unsigned, 16> ListsPerDecl;
  9771. ListsPerDecl.reserve(UniqueDecls);
  9772. for (unsigned i = 0; i < UniqueDecls; ++i)
  9773. ListsPerDecl.push_back(Record.readInt());
  9774. C->setDeclNumLists(ListsPerDecl);
  9775. SmallVector<unsigned, 32> ListSizes;
  9776. ListSizes.reserve(TotalLists);
  9777. for (unsigned i = 0; i < TotalLists; ++i)
  9778. ListSizes.push_back(Record.readInt());
  9779. C->setComponentListSizes(ListSizes);
  9780. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  9781. Components.reserve(TotalComponents);
  9782. for (unsigned i = 0; i < TotalComponents; ++i) {
  9783. Expr *AssociatedExpr = Record.readSubExpr();
  9784. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  9785. Components.emplace_back(AssociatedExpr, AssociatedDecl,
  9786. /*IsNonContiguous=*/false);
  9787. }
  9788. C->setComponents(Components, ListSizes);
  9789. }
  9790. void OMPClauseReader::VisitOMPHasDeviceAddrClause(OMPHasDeviceAddrClause *C) {
  9791. C->setLParenLoc(Record.readSourceLocation());
  9792. auto NumVars = C->varlist_size();
  9793. auto UniqueDecls = C->getUniqueDeclarationsNum();
  9794. auto TotalLists = C->getTotalComponentListNum();
  9795. auto TotalComponents = C->getTotalComponentsNum();
  9796. SmallVector<Expr *, 16> Vars;
  9797. Vars.reserve(NumVars);
  9798. for (unsigned I = 0; I != NumVars; ++I)
  9799. Vars.push_back(Record.readSubExpr());
  9800. C->setVarRefs(Vars);
  9801. Vars.clear();
  9802. SmallVector<ValueDecl *, 16> Decls;
  9803. Decls.reserve(UniqueDecls);
  9804. for (unsigned I = 0; I < UniqueDecls; ++I)
  9805. Decls.push_back(Record.readDeclAs<ValueDecl>());
  9806. C->setUniqueDecls(Decls);
  9807. SmallVector<unsigned, 16> ListsPerDecl;
  9808. ListsPerDecl.reserve(UniqueDecls);
  9809. for (unsigned I = 0; I < UniqueDecls; ++I)
  9810. ListsPerDecl.push_back(Record.readInt());
  9811. C->setDeclNumLists(ListsPerDecl);
  9812. SmallVector<unsigned, 32> ListSizes;
  9813. ListSizes.reserve(TotalLists);
  9814. for (unsigned i = 0; i < TotalLists; ++i)
  9815. ListSizes.push_back(Record.readInt());
  9816. C->setComponentListSizes(ListSizes);
  9817. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  9818. Components.reserve(TotalComponents);
  9819. for (unsigned I = 0; I < TotalComponents; ++I) {
  9820. Expr *AssociatedExpr = Record.readSubExpr();
  9821. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  9822. Components.emplace_back(AssociatedExpr, AssociatedDecl,
  9823. /*IsNonContiguous=*/false);
  9824. }
  9825. C->setComponents(Components, ListSizes);
  9826. }
  9827. void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
  9828. C->setLParenLoc(Record.readSourceLocation());
  9829. unsigned NumVars = C->varlist_size();
  9830. SmallVector<Expr *, 16> Vars;
  9831. Vars.reserve(NumVars);
  9832. for (unsigned i = 0; i != NumVars; ++i)
  9833. Vars.push_back(Record.readSubExpr());
  9834. C->setVarRefs(Vars);
  9835. Vars.clear();
  9836. Vars.reserve(NumVars);
  9837. for (unsigned i = 0; i != NumVars; ++i)
  9838. Vars.push_back(Record.readSubExpr());
  9839. C->setPrivateRefs(Vars);
  9840. }
  9841. void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
  9842. C->setLParenLoc(Record.readSourceLocation());
  9843. unsigned NumVars = C->varlist_size();
  9844. SmallVector<Expr *, 16> Vars;
  9845. Vars.reserve(NumVars);
  9846. for (unsigned i = 0; i != NumVars; ++i)
  9847. Vars.push_back(Record.readSubExpr());
  9848. C->setVarRefs(Vars);
  9849. }
  9850. void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
  9851. C->setLParenLoc(Record.readSourceLocation());
  9852. unsigned NumVars = C->varlist_size();
  9853. SmallVector<Expr *, 16> Vars;
  9854. Vars.reserve(NumVars);
  9855. for (unsigned i = 0; i != NumVars; ++i)
  9856. Vars.push_back(Record.readSubExpr());
  9857. C->setVarRefs(Vars);
  9858. }
  9859. void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
  9860. C->setLParenLoc(Record.readSourceLocation());
  9861. unsigned NumOfAllocators = C->getNumberOfAllocators();
  9862. SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
  9863. Data.reserve(NumOfAllocators);
  9864. for (unsigned I = 0; I != NumOfAllocators; ++I) {
  9865. OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
  9866. D.Allocator = Record.readSubExpr();
  9867. D.AllocatorTraits = Record.readSubExpr();
  9868. D.LParenLoc = Record.readSourceLocation();
  9869. D.RParenLoc = Record.readSourceLocation();
  9870. }
  9871. C->setAllocatorsData(Data);
  9872. }
  9873. void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
  9874. C->setLParenLoc(Record.readSourceLocation());
  9875. C->setModifier(Record.readSubExpr());
  9876. C->setColonLoc(Record.readSourceLocation());
  9877. unsigned NumOfLocators = C->varlist_size();
  9878. SmallVector<Expr *, 4> Locators;
  9879. Locators.reserve(NumOfLocators);
  9880. for (unsigned I = 0; I != NumOfLocators; ++I)
  9881. Locators.push_back(Record.readSubExpr());
  9882. C->setVarRefs(Locators);
  9883. }
  9884. void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
  9885. C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
  9886. C->setModifier(Record.readEnum<OpenMPOrderClauseModifier>());
  9887. C->setLParenLoc(Record.readSourceLocation());
  9888. C->setKindKwLoc(Record.readSourceLocation());
  9889. C->setModifierKwLoc(Record.readSourceLocation());
  9890. }
  9891. void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
  9892. VisitOMPClauseWithPreInit(C);
  9893. C->setThreadID(Record.readSubExpr());
  9894. C->setLParenLoc(Record.readSourceLocation());
  9895. }
  9896. void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
  9897. C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
  9898. C->setLParenLoc(Record.readSourceLocation());
  9899. C->setBindKindLoc(Record.readSourceLocation());
  9900. }
  9901. void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
  9902. C->setAlignment(Record.readExpr());
  9903. C->setLParenLoc(Record.readSourceLocation());
  9904. }
  9905. void OMPClauseReader::VisitOMPXDynCGroupMemClause(OMPXDynCGroupMemClause *C) {
  9906. VisitOMPClauseWithPreInit(C);
  9907. C->setSize(Record.readSubExpr());
  9908. C->setLParenLoc(Record.readSourceLocation());
  9909. }
  9910. OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
  9911. OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
  9912. TI.Sets.resize(readUInt32());
  9913. for (auto &Set : TI.Sets) {
  9914. Set.Kind = readEnum<llvm::omp::TraitSet>();
  9915. Set.Selectors.resize(readUInt32());
  9916. for (auto &Selector : Set.Selectors) {
  9917. Selector.Kind = readEnum<llvm::omp::TraitSelector>();
  9918. Selector.ScoreOrCondition = nullptr;
  9919. if (readBool())
  9920. Selector.ScoreOrCondition = readExprRef();
  9921. Selector.Properties.resize(readUInt32());
  9922. for (auto &Property : Selector.Properties)
  9923. Property.Kind = readEnum<llvm::omp::TraitProperty>();
  9924. }
  9925. }
  9926. return &TI;
  9927. }
  9928. void ASTRecordReader::readOMPChildren(OMPChildren *Data) {
  9929. if (!Data)
  9930. return;
  9931. if (Reader->ReadingKind == ASTReader::Read_Stmt) {
  9932. // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
  9933. skipInts(3);
  9934. }
  9935. SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
  9936. for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
  9937. Clauses[I] = readOMPClause();
  9938. Data->setClauses(Clauses);
  9939. if (Data->hasAssociatedStmt())
  9940. Data->setAssociatedStmt(readStmt());
  9941. for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
  9942. Data->getChildren()[I] = readStmt();
  9943. }