ASTReader.cpp 303 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532
  1. //===-- ASTReader.cpp - AST File Reader ----------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the ASTReader class, which reads AST files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Serialization/ASTReader.h"
  14. #include "ASTCommon.h"
  15. #include "ASTReaderInternals.h"
  16. #include "clang/AST/ASTConsumer.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/DeclTemplate.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ExprCXX.h"
  21. #include "clang/Frontend/PCHContainerOperations.h"
  22. #include "clang/AST/NestedNameSpecifier.h"
  23. #include "clang/AST/Type.h"
  24. #include "clang/AST/TypeLocVisitor.h"
  25. #include "clang/Basic/DiagnosticOptions.h"
  26. #include "clang/Basic/FileManager.h"
  27. #include "clang/Basic/SourceManager.h"
  28. #include "clang/Basic/SourceManagerInternals.h"
  29. #include "clang/Basic/TargetInfo.h"
  30. #include "clang/Basic/TargetOptions.h"
  31. #include "clang/Basic/Version.h"
  32. #include "clang/Basic/VersionTuple.h"
  33. #include "clang/Frontend/Utils.h"
  34. #include "clang/Lex/HeaderSearch.h"
  35. #include "clang/Lex/HeaderSearchOptions.h"
  36. #include "clang/Lex/MacroInfo.h"
  37. #include "clang/Lex/PreprocessingRecord.h"
  38. #include "clang/Lex/Preprocessor.h"
  39. #include "clang/Lex/PreprocessorOptions.h"
  40. #include "clang/Sema/Scope.h"
  41. #include "clang/Sema/Sema.h"
  42. #include "clang/Serialization/ASTDeserializationListener.h"
  43. #include "clang/Serialization/GlobalModuleIndex.h"
  44. #include "clang/Serialization/ModuleManager.h"
  45. #include "clang/Serialization/SerializationDiagnostic.h"
  46. #include "llvm/ADT/Hashing.h"
  47. #include "llvm/ADT/StringExtras.h"
  48. #include "llvm/Bitcode/BitstreamReader.h"
  49. #include "llvm/Support/ErrorHandling.h"
  50. #include "llvm/Support/FileSystem.h"
  51. #include "llvm/Support/MemoryBuffer.h"
  52. #include "llvm/Support/Path.h"
  53. #include "llvm/Support/SaveAndRestore.h"
  54. #include "llvm/Support/raw_ostream.h"
  55. #include <algorithm>
  56. #include <cstdio>
  57. #include <iterator>
  58. #include <system_error>
  59. using namespace clang;
  60. using namespace clang::serialization;
  61. using namespace clang::serialization::reader;
  62. using llvm::BitstreamCursor;
  63. //===----------------------------------------------------------------------===//
  64. // ChainedASTReaderListener implementation
  65. //===----------------------------------------------------------------------===//
  66. bool
  67. ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
  68. return First->ReadFullVersionInformation(FullVersion) ||
  69. Second->ReadFullVersionInformation(FullVersion);
  70. }
  71. void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
  72. First->ReadModuleName(ModuleName);
  73. Second->ReadModuleName(ModuleName);
  74. }
  75. void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
  76. First->ReadModuleMapFile(ModuleMapPath);
  77. Second->ReadModuleMapFile(ModuleMapPath);
  78. }
  79. bool
  80. ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
  81. bool Complain,
  82. bool AllowCompatibleDifferences) {
  83. return First->ReadLanguageOptions(LangOpts, Complain,
  84. AllowCompatibleDifferences) ||
  85. Second->ReadLanguageOptions(LangOpts, Complain,
  86. AllowCompatibleDifferences);
  87. }
  88. bool ChainedASTReaderListener::ReadTargetOptions(
  89. const TargetOptions &TargetOpts, bool Complain,
  90. bool AllowCompatibleDifferences) {
  91. return First->ReadTargetOptions(TargetOpts, Complain,
  92. AllowCompatibleDifferences) ||
  93. Second->ReadTargetOptions(TargetOpts, Complain,
  94. AllowCompatibleDifferences);
  95. }
  96. bool ChainedASTReaderListener::ReadDiagnosticOptions(
  97. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  98. return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
  99. Second->ReadDiagnosticOptions(DiagOpts, Complain);
  100. }
  101. bool
  102. ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
  103. bool Complain) {
  104. return First->ReadFileSystemOptions(FSOpts, Complain) ||
  105. Second->ReadFileSystemOptions(FSOpts, Complain);
  106. }
  107. bool ChainedASTReaderListener::ReadHeaderSearchOptions(
  108. const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
  109. bool Complain) {
  110. return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  111. Complain) ||
  112. Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  113. Complain);
  114. }
  115. bool ChainedASTReaderListener::ReadPreprocessorOptions(
  116. const PreprocessorOptions &PPOpts, bool Complain,
  117. std::string &SuggestedPredefines) {
  118. return First->ReadPreprocessorOptions(PPOpts, Complain,
  119. SuggestedPredefines) ||
  120. Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
  121. }
  122. void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
  123. unsigned Value) {
  124. First->ReadCounter(M, Value);
  125. Second->ReadCounter(M, Value);
  126. }
  127. bool ChainedASTReaderListener::needsInputFileVisitation() {
  128. return First->needsInputFileVisitation() ||
  129. Second->needsInputFileVisitation();
  130. }
  131. bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
  132. return First->needsSystemInputFileVisitation() ||
  133. Second->needsSystemInputFileVisitation();
  134. }
  135. void ChainedASTReaderListener::visitModuleFile(StringRef Filename) {
  136. First->visitModuleFile(Filename);
  137. Second->visitModuleFile(Filename);
  138. }
  139. bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
  140. bool isSystem,
  141. bool isOverridden) {
  142. bool Continue = false;
  143. if (First->needsInputFileVisitation() &&
  144. (!isSystem || First->needsSystemInputFileVisitation()))
  145. Continue |= First->visitInputFile(Filename, isSystem, isOverridden);
  146. if (Second->needsInputFileVisitation() &&
  147. (!isSystem || Second->needsSystemInputFileVisitation()))
  148. Continue |= Second->visitInputFile(Filename, isSystem, isOverridden);
  149. return Continue;
  150. }
  151. //===----------------------------------------------------------------------===//
  152. // PCH validator implementation
  153. //===----------------------------------------------------------------------===//
  154. ASTReaderListener::~ASTReaderListener() {}
  155. /// \brief Compare the given set of language options against an existing set of
  156. /// language options.
  157. ///
  158. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  159. /// \param AllowCompatibleDifferences If true, differences between compatible
  160. /// language options will be permitted.
  161. ///
  162. /// \returns true if the languagae options mis-match, false otherwise.
  163. static bool checkLanguageOptions(const LangOptions &LangOpts,
  164. const LangOptions &ExistingLangOpts,
  165. DiagnosticsEngine *Diags,
  166. bool AllowCompatibleDifferences = true) {
  167. #define LANGOPT(Name, Bits, Default, Description) \
  168. if (ExistingLangOpts.Name != LangOpts.Name) { \
  169. if (Diags) \
  170. Diags->Report(diag::err_pch_langopt_mismatch) \
  171. << Description << LangOpts.Name << ExistingLangOpts.Name; \
  172. return true; \
  173. }
  174. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  175. if (ExistingLangOpts.Name != LangOpts.Name) { \
  176. if (Diags) \
  177. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  178. << Description; \
  179. return true; \
  180. }
  181. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  182. if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
  183. if (Diags) \
  184. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  185. << Description; \
  186. return true; \
  187. }
  188. #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
  189. if (!AllowCompatibleDifferences) \
  190. LANGOPT(Name, Bits, Default, Description)
  191. #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
  192. if (!AllowCompatibleDifferences) \
  193. ENUM_LANGOPT(Name, Bits, Default, Description)
  194. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  195. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  196. #include "clang/Basic/LangOptions.fixed.def"
  197. if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
  198. if (Diags)
  199. Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
  200. return true;
  201. }
  202. if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
  203. if (Diags)
  204. Diags->Report(diag::err_pch_langopt_value_mismatch)
  205. << "target Objective-C runtime";
  206. return true;
  207. }
  208. if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
  209. LangOpts.CommentOpts.BlockCommandNames) {
  210. if (Diags)
  211. Diags->Report(diag::err_pch_langopt_value_mismatch)
  212. << "block command names";
  213. return true;
  214. }
  215. return false;
  216. }
  217. /// \brief Compare the given set of target options against an existing set of
  218. /// target options.
  219. ///
  220. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  221. ///
  222. /// \returns true if the target options mis-match, false otherwise.
  223. static bool checkTargetOptions(const TargetOptions &TargetOpts,
  224. const TargetOptions &ExistingTargetOpts,
  225. DiagnosticsEngine *Diags,
  226. bool AllowCompatibleDifferences = true) {
  227. #define CHECK_TARGET_OPT(Field, Name) \
  228. if (TargetOpts.Field != ExistingTargetOpts.Field) { \
  229. if (Diags) \
  230. Diags->Report(diag::err_pch_targetopt_mismatch) \
  231. << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
  232. return true; \
  233. }
  234. // The triple and ABI must match exactly.
  235. CHECK_TARGET_OPT(Triple, "target");
  236. CHECK_TARGET_OPT(ABI, "target ABI");
  237. // We can tolerate different CPUs in many cases, notably when one CPU
  238. // supports a strict superset of another. When allowing compatible
  239. // differences skip this check.
  240. if (!AllowCompatibleDifferences)
  241. CHECK_TARGET_OPT(CPU, "target CPU");
  242. #undef CHECK_TARGET_OPT
  243. // Compare feature sets.
  244. SmallVector<StringRef, 4> ExistingFeatures(
  245. ExistingTargetOpts.FeaturesAsWritten.begin(),
  246. ExistingTargetOpts.FeaturesAsWritten.end());
  247. SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
  248. TargetOpts.FeaturesAsWritten.end());
  249. std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
  250. std::sort(ReadFeatures.begin(), ReadFeatures.end());
  251. // We compute the set difference in both directions explicitly so that we can
  252. // diagnose the differences differently.
  253. SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
  254. std::set_difference(
  255. ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
  256. ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
  257. std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
  258. ExistingFeatures.begin(), ExistingFeatures.end(),
  259. std::back_inserter(UnmatchedReadFeatures));
  260. // If we are allowing compatible differences and the read feature set is
  261. // a strict subset of the existing feature set, there is nothing to diagnose.
  262. if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
  263. return false;
  264. if (Diags) {
  265. for (StringRef Feature : UnmatchedReadFeatures)
  266. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  267. << /* is-existing-feature */ false << Feature;
  268. for (StringRef Feature : UnmatchedExistingFeatures)
  269. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  270. << /* is-existing-feature */ true << Feature;
  271. }
  272. return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
  273. }
  274. bool
  275. PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
  276. bool Complain,
  277. bool AllowCompatibleDifferences) {
  278. const LangOptions &ExistingLangOpts = PP.getLangOpts();
  279. return checkLanguageOptions(LangOpts, ExistingLangOpts,
  280. Complain ? &Reader.Diags : nullptr,
  281. AllowCompatibleDifferences);
  282. }
  283. bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
  284. bool Complain,
  285. bool AllowCompatibleDifferences) {
  286. const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
  287. return checkTargetOptions(TargetOpts, ExistingTargetOpts,
  288. Complain ? &Reader.Diags : nullptr,
  289. AllowCompatibleDifferences);
  290. }
  291. namespace {
  292. typedef llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >
  293. MacroDefinitionsMap;
  294. typedef llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8> >
  295. DeclsMap;
  296. }
  297. static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
  298. DiagnosticsEngine &Diags,
  299. bool Complain) {
  300. typedef DiagnosticsEngine::Level Level;
  301. // Check current mappings for new -Werror mappings, and the stored mappings
  302. // for cases that were explicitly mapped to *not* be errors that are now
  303. // errors because of options like -Werror.
  304. DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
  305. for (DiagnosticsEngine *MappingSource : MappingSources) {
  306. for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
  307. diag::kind DiagID = DiagIDMappingPair.first;
  308. Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
  309. if (CurLevel < DiagnosticsEngine::Error)
  310. continue; // not significant
  311. Level StoredLevel =
  312. StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
  313. if (StoredLevel < DiagnosticsEngine::Error) {
  314. if (Complain)
  315. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
  316. Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
  317. return true;
  318. }
  319. }
  320. }
  321. return false;
  322. }
  323. static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
  324. diag::Severity Ext = Diags.getExtensionHandlingBehavior();
  325. if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
  326. return true;
  327. return Ext >= diag::Severity::Error;
  328. }
  329. static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
  330. DiagnosticsEngine &Diags,
  331. bool IsSystem, bool Complain) {
  332. // Top-level options
  333. if (IsSystem) {
  334. if (Diags.getSuppressSystemWarnings())
  335. return false;
  336. // If -Wsystem-headers was not enabled before, be conservative
  337. if (StoredDiags.getSuppressSystemWarnings()) {
  338. if (Complain)
  339. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
  340. return true;
  341. }
  342. }
  343. if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
  344. if (Complain)
  345. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
  346. return true;
  347. }
  348. if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
  349. !StoredDiags.getEnableAllWarnings()) {
  350. if (Complain)
  351. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
  352. return true;
  353. }
  354. if (isExtHandlingFromDiagsError(Diags) &&
  355. !isExtHandlingFromDiagsError(StoredDiags)) {
  356. if (Complain)
  357. Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
  358. return true;
  359. }
  360. return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
  361. }
  362. bool PCHValidator::ReadDiagnosticOptions(
  363. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  364. DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
  365. IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
  366. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
  367. new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
  368. // This should never fail, because we would have processed these options
  369. // before writing them to an ASTFile.
  370. ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
  371. ModuleManager &ModuleMgr = Reader.getModuleManager();
  372. assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
  373. // If the original import came from a file explicitly generated by the user,
  374. // don't check the diagnostic mappings.
  375. // FIXME: currently this is approximated by checking whether this is not a
  376. // module import of an implicitly-loaded module file.
  377. // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
  378. // the transitive closure of its imports, since unrelated modules cannot be
  379. // imported until after this module finishes validation.
  380. ModuleFile *TopImport = *ModuleMgr.rbegin();
  381. while (!TopImport->ImportedBy.empty())
  382. TopImport = TopImport->ImportedBy[0];
  383. if (TopImport->Kind != MK_ImplicitModule)
  384. return false;
  385. StringRef ModuleName = TopImport->ModuleName;
  386. assert(!ModuleName.empty() && "diagnostic options read before module name");
  387. Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
  388. assert(M && "missing module");
  389. // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
  390. // contains the union of their flags.
  391. return checkDiagnosticMappings(*Diags, ExistingDiags, M->IsSystem, Complain);
  392. }
  393. /// \brief Collect the macro definitions provided by the given preprocessor
  394. /// options.
  395. static void
  396. collectMacroDefinitions(const PreprocessorOptions &PPOpts,
  397. MacroDefinitionsMap &Macros,
  398. SmallVectorImpl<StringRef> *MacroNames = nullptr) {
  399. for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
  400. StringRef Macro = PPOpts.Macros[I].first;
  401. bool IsUndef = PPOpts.Macros[I].second;
  402. std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
  403. StringRef MacroName = MacroPair.first;
  404. StringRef MacroBody = MacroPair.second;
  405. // For an #undef'd macro, we only care about the name.
  406. if (IsUndef) {
  407. if (MacroNames && !Macros.count(MacroName))
  408. MacroNames->push_back(MacroName);
  409. Macros[MacroName] = std::make_pair("", true);
  410. continue;
  411. }
  412. // For a #define'd macro, figure out the actual definition.
  413. if (MacroName.size() == Macro.size())
  414. MacroBody = "1";
  415. else {
  416. // Note: GCC drops anything following an end-of-line character.
  417. StringRef::size_type End = MacroBody.find_first_of("\n\r");
  418. MacroBody = MacroBody.substr(0, End);
  419. }
  420. if (MacroNames && !Macros.count(MacroName))
  421. MacroNames->push_back(MacroName);
  422. Macros[MacroName] = std::make_pair(MacroBody, false);
  423. }
  424. }
  425. /// \brief Check the preprocessor options deserialized from the control block
  426. /// against the preprocessor options in an existing preprocessor.
  427. ///
  428. /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
  429. static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
  430. const PreprocessorOptions &ExistingPPOpts,
  431. DiagnosticsEngine *Diags,
  432. FileManager &FileMgr,
  433. std::string &SuggestedPredefines,
  434. const LangOptions &LangOpts) {
  435. // Check macro definitions.
  436. MacroDefinitionsMap ASTFileMacros;
  437. collectMacroDefinitions(PPOpts, ASTFileMacros);
  438. MacroDefinitionsMap ExistingMacros;
  439. SmallVector<StringRef, 4> ExistingMacroNames;
  440. collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
  441. for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
  442. // Dig out the macro definition in the existing preprocessor options.
  443. StringRef MacroName = ExistingMacroNames[I];
  444. std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
  445. // Check whether we know anything about this macro name or not.
  446. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/> >::iterator Known
  447. = ASTFileMacros.find(MacroName);
  448. if (Known == ASTFileMacros.end()) {
  449. // FIXME: Check whether this identifier was referenced anywhere in the
  450. // AST file. If so, we should reject the AST file. Unfortunately, this
  451. // information isn't in the control block. What shall we do about it?
  452. if (Existing.second) {
  453. SuggestedPredefines += "#undef ";
  454. SuggestedPredefines += MacroName.str();
  455. SuggestedPredefines += '\n';
  456. } else {
  457. SuggestedPredefines += "#define ";
  458. SuggestedPredefines += MacroName.str();
  459. SuggestedPredefines += ' ';
  460. SuggestedPredefines += Existing.first.str();
  461. SuggestedPredefines += '\n';
  462. }
  463. continue;
  464. }
  465. // If the macro was defined in one but undef'd in the other, we have a
  466. // conflict.
  467. if (Existing.second != Known->second.second) {
  468. if (Diags) {
  469. Diags->Report(diag::err_pch_macro_def_undef)
  470. << MacroName << Known->second.second;
  471. }
  472. return true;
  473. }
  474. // If the macro was #undef'd in both, or if the macro bodies are identical,
  475. // it's fine.
  476. if (Existing.second || Existing.first == Known->second.first)
  477. continue;
  478. // The macro bodies differ; complain.
  479. if (Diags) {
  480. Diags->Report(diag::err_pch_macro_def_conflict)
  481. << MacroName << Known->second.first << Existing.first;
  482. }
  483. return true;
  484. }
  485. // Check whether we're using predefines.
  486. if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines) {
  487. if (Diags) {
  488. Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
  489. }
  490. return true;
  491. }
  492. // Detailed record is important since it is used for the module cache hash.
  493. if (LangOpts.Modules &&
  494. PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord) {
  495. if (Diags) {
  496. Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
  497. }
  498. return true;
  499. }
  500. // Compute the #include and #include_macros lines we need.
  501. for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
  502. StringRef File = ExistingPPOpts.Includes[I];
  503. if (File == ExistingPPOpts.ImplicitPCHInclude)
  504. continue;
  505. if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
  506. != PPOpts.Includes.end())
  507. continue;
  508. SuggestedPredefines += "#include \"";
  509. SuggestedPredefines += File;
  510. SuggestedPredefines += "\"\n";
  511. }
  512. for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
  513. StringRef File = ExistingPPOpts.MacroIncludes[I];
  514. if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
  515. File)
  516. != PPOpts.MacroIncludes.end())
  517. continue;
  518. SuggestedPredefines += "#__include_macros \"";
  519. SuggestedPredefines += File;
  520. SuggestedPredefines += "\"\n##\n";
  521. }
  522. return false;
  523. }
  524. bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  525. bool Complain,
  526. std::string &SuggestedPredefines) {
  527. const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
  528. return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
  529. Complain? &Reader.Diags : nullptr,
  530. PP.getFileManager(),
  531. SuggestedPredefines,
  532. PP.getLangOpts());
  533. }
  534. /// Check the header search options deserialized from the control block
  535. /// against the header search options in an existing preprocessor.
  536. ///
  537. /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
  538. static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  539. StringRef SpecificModuleCachePath,
  540. StringRef ExistingModuleCachePath,
  541. DiagnosticsEngine *Diags,
  542. const LangOptions &LangOpts) {
  543. if (LangOpts.Modules) {
  544. if (SpecificModuleCachePath != ExistingModuleCachePath) {
  545. if (Diags)
  546. Diags->Report(diag::err_pch_modulecache_mismatch)
  547. << SpecificModuleCachePath << ExistingModuleCachePath;
  548. return true;
  549. }
  550. }
  551. return false;
  552. }
  553. bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  554. StringRef SpecificModuleCachePath,
  555. bool Complain) {
  556. return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  557. PP.getHeaderSearchInfo().getModuleCachePath(),
  558. Complain ? &Reader.Diags : nullptr,
  559. PP.getLangOpts());
  560. }
  561. void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
  562. PP.setCounterValue(Value);
  563. }
  564. //===----------------------------------------------------------------------===//
  565. // AST reader implementation
  566. //===----------------------------------------------------------------------===//
  567. void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
  568. bool TakeOwnership) {
  569. DeserializationListener = Listener;
  570. OwnsDeserializationListener = TakeOwnership;
  571. }
  572. unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
  573. return serialization::ComputeHash(Sel);
  574. }
  575. std::pair<unsigned, unsigned>
  576. ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
  577. using namespace llvm::support;
  578. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  579. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  580. return std::make_pair(KeyLen, DataLen);
  581. }
  582. ASTSelectorLookupTrait::internal_key_type
  583. ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
  584. using namespace llvm::support;
  585. SelectorTable &SelTable = Reader.getContext().Selectors;
  586. unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
  587. IdentifierInfo *FirstII = Reader.getLocalIdentifier(
  588. F, endian::readNext<uint32_t, little, unaligned>(d));
  589. if (N == 0)
  590. return SelTable.getNullarySelector(FirstII);
  591. else if (N == 1)
  592. return SelTable.getUnarySelector(FirstII);
  593. SmallVector<IdentifierInfo *, 16> Args;
  594. Args.push_back(FirstII);
  595. for (unsigned I = 1; I != N; ++I)
  596. Args.push_back(Reader.getLocalIdentifier(
  597. F, endian::readNext<uint32_t, little, unaligned>(d)));
  598. return SelTable.getSelector(N, Args.data());
  599. }
  600. ASTSelectorLookupTrait::data_type
  601. ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
  602. unsigned DataLen) {
  603. using namespace llvm::support;
  604. data_type Result;
  605. Result.ID = Reader.getGlobalSelectorID(
  606. F, endian::readNext<uint32_t, little, unaligned>(d));
  607. unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
  608. unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
  609. Result.InstanceBits = FullInstanceBits & 0x3;
  610. Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
  611. Result.FactoryBits = FullFactoryBits & 0x3;
  612. Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
  613. unsigned NumInstanceMethods = FullInstanceBits >> 3;
  614. unsigned NumFactoryMethods = FullFactoryBits >> 3;
  615. // Load instance methods
  616. for (unsigned I = 0; I != NumInstanceMethods; ++I) {
  617. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  618. F, endian::readNext<uint32_t, little, unaligned>(d)))
  619. Result.Instance.push_back(Method);
  620. }
  621. // Load factory methods
  622. for (unsigned I = 0; I != NumFactoryMethods; ++I) {
  623. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  624. F, endian::readNext<uint32_t, little, unaligned>(d)))
  625. Result.Factory.push_back(Method);
  626. }
  627. return Result;
  628. }
  629. unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
  630. return llvm::HashString(a);
  631. }
  632. std::pair<unsigned, unsigned>
  633. ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
  634. using namespace llvm::support;
  635. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  636. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  637. return std::make_pair(KeyLen, DataLen);
  638. }
  639. ASTIdentifierLookupTraitBase::internal_key_type
  640. ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
  641. assert(n >= 2 && d[n-1] == '\0');
  642. return StringRef((const char*) d, n-1);
  643. }
  644. /// \brief Whether the given identifier is "interesting".
  645. static bool isInterestingIdentifier(IdentifierInfo &II) {
  646. return II.isPoisoned() ||
  647. II.isExtensionToken() ||
  648. II.getObjCOrBuiltinID() ||
  649. II.hasRevertedTokenIDToIdentifier() ||
  650. II.hadMacroDefinition() ||
  651. II.getFETokenInfo<void>();
  652. }
  653. IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
  654. const unsigned char* d,
  655. unsigned DataLen) {
  656. using namespace llvm::support;
  657. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  658. bool IsInteresting = RawID & 0x01;
  659. // Wipe out the "is interesting" bit.
  660. RawID = RawID >> 1;
  661. IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
  662. if (!IsInteresting) {
  663. // For uninteresting identifiers, just build the IdentifierInfo
  664. // and associate it with the persistent ID.
  665. IdentifierInfo *II = KnownII;
  666. if (!II) {
  667. II = &Reader.getIdentifierTable().getOwn(k);
  668. KnownII = II;
  669. }
  670. Reader.SetIdentifierInfo(ID, II);
  671. if (!II->isFromAST()) {
  672. bool WasInteresting = isInterestingIdentifier(*II);
  673. II->setIsFromAST();
  674. if (WasInteresting)
  675. II->setChangedSinceDeserialization();
  676. }
  677. Reader.markIdentifierUpToDate(II);
  678. return II;
  679. }
  680. unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
  681. unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
  682. bool CPlusPlusOperatorKeyword = Bits & 0x01;
  683. Bits >>= 1;
  684. bool HasRevertedTokenIDToIdentifier = Bits & 0x01;
  685. Bits >>= 1;
  686. bool Poisoned = Bits & 0x01;
  687. Bits >>= 1;
  688. bool ExtensionToken = Bits & 0x01;
  689. Bits >>= 1;
  690. bool hadMacroDefinition = Bits & 0x01;
  691. Bits >>= 1;
  692. assert(Bits == 0 && "Extra bits in the identifier?");
  693. DataLen -= 8;
  694. // Build the IdentifierInfo itself and link the identifier ID with
  695. // the new IdentifierInfo.
  696. IdentifierInfo *II = KnownII;
  697. if (!II) {
  698. II = &Reader.getIdentifierTable().getOwn(StringRef(k));
  699. KnownII = II;
  700. }
  701. Reader.markIdentifierUpToDate(II);
  702. if (!II->isFromAST()) {
  703. bool WasInteresting = isInterestingIdentifier(*II);
  704. II->setIsFromAST();
  705. if (WasInteresting)
  706. II->setChangedSinceDeserialization();
  707. }
  708. // Set or check the various bits in the IdentifierInfo structure.
  709. // Token IDs are read-only.
  710. if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
  711. II->RevertTokenIDToIdentifier();
  712. II->setObjCOrBuiltinID(ObjCOrBuiltinID);
  713. assert(II->isExtensionToken() == ExtensionToken &&
  714. "Incorrect extension token flag");
  715. (void)ExtensionToken;
  716. if (Poisoned)
  717. II->setIsPoisoned(true);
  718. assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
  719. "Incorrect C++ operator keyword flag");
  720. (void)CPlusPlusOperatorKeyword;
  721. // If this identifier is a macro, deserialize the macro
  722. // definition.
  723. if (hadMacroDefinition) {
  724. uint32_t MacroDirectivesOffset =
  725. endian::readNext<uint32_t, little, unaligned>(d);
  726. DataLen -= 4;
  727. Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
  728. }
  729. Reader.SetIdentifierInfo(ID, II);
  730. // Read all of the declarations visible at global scope with this
  731. // name.
  732. if (DataLen > 0) {
  733. SmallVector<uint32_t, 4> DeclIDs;
  734. for (; DataLen > 0; DataLen -= 4)
  735. DeclIDs.push_back(Reader.getGlobalDeclID(
  736. F, endian::readNext<uint32_t, little, unaligned>(d)));
  737. Reader.SetGloballyVisibleDecls(II, DeclIDs);
  738. }
  739. return II;
  740. }
  741. unsigned
  742. ASTDeclContextNameLookupTrait::ComputeHash(const DeclNameKey &Key) {
  743. llvm::FoldingSetNodeID ID;
  744. ID.AddInteger(Key.Kind);
  745. switch (Key.Kind) {
  746. case DeclarationName::Identifier:
  747. case DeclarationName::CXXLiteralOperatorName:
  748. ID.AddString(((IdentifierInfo*)Key.Data)->getName());
  749. break;
  750. case DeclarationName::ObjCZeroArgSelector:
  751. case DeclarationName::ObjCOneArgSelector:
  752. case DeclarationName::ObjCMultiArgSelector:
  753. ID.AddInteger(serialization::ComputeHash(Selector(Key.Data)));
  754. break;
  755. case DeclarationName::CXXOperatorName:
  756. ID.AddInteger((OverloadedOperatorKind)Key.Data);
  757. break;
  758. case DeclarationName::CXXConstructorName:
  759. case DeclarationName::CXXDestructorName:
  760. case DeclarationName::CXXConversionFunctionName:
  761. case DeclarationName::CXXUsingDirective:
  762. break;
  763. }
  764. return ID.ComputeHash();
  765. }
  766. ASTDeclContextNameLookupTrait::internal_key_type
  767. ASTDeclContextNameLookupTrait::GetInternalKey(
  768. const external_key_type& Name) {
  769. DeclNameKey Key;
  770. Key.Kind = Name.getNameKind();
  771. switch (Name.getNameKind()) {
  772. case DeclarationName::Identifier:
  773. Key.Data = (uint64_t)Name.getAsIdentifierInfo();
  774. break;
  775. case DeclarationName::ObjCZeroArgSelector:
  776. case DeclarationName::ObjCOneArgSelector:
  777. case DeclarationName::ObjCMultiArgSelector:
  778. Key.Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
  779. break;
  780. case DeclarationName::CXXOperatorName:
  781. Key.Data = Name.getCXXOverloadedOperator();
  782. break;
  783. case DeclarationName::CXXLiteralOperatorName:
  784. Key.Data = (uint64_t)Name.getCXXLiteralIdentifier();
  785. break;
  786. case DeclarationName::CXXConstructorName:
  787. case DeclarationName::CXXDestructorName:
  788. case DeclarationName::CXXConversionFunctionName:
  789. case DeclarationName::CXXUsingDirective:
  790. Key.Data = 0;
  791. break;
  792. }
  793. return Key;
  794. }
  795. std::pair<unsigned, unsigned>
  796. ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
  797. using namespace llvm::support;
  798. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  799. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  800. return std::make_pair(KeyLen, DataLen);
  801. }
  802. ASTDeclContextNameLookupTrait::internal_key_type
  803. ASTDeclContextNameLookupTrait::ReadKey(const unsigned char* d, unsigned) {
  804. using namespace llvm::support;
  805. DeclNameKey Key;
  806. Key.Kind = (DeclarationName::NameKind)*d++;
  807. switch (Key.Kind) {
  808. case DeclarationName::Identifier:
  809. Key.Data = (uint64_t)Reader.getLocalIdentifier(
  810. F, endian::readNext<uint32_t, little, unaligned>(d));
  811. break;
  812. case DeclarationName::ObjCZeroArgSelector:
  813. case DeclarationName::ObjCOneArgSelector:
  814. case DeclarationName::ObjCMultiArgSelector:
  815. Key.Data =
  816. (uint64_t)Reader.getLocalSelector(
  817. F, endian::readNext<uint32_t, little, unaligned>(
  818. d)).getAsOpaquePtr();
  819. break;
  820. case DeclarationName::CXXOperatorName:
  821. Key.Data = *d++; // OverloadedOperatorKind
  822. break;
  823. case DeclarationName::CXXLiteralOperatorName:
  824. Key.Data = (uint64_t)Reader.getLocalIdentifier(
  825. F, endian::readNext<uint32_t, little, unaligned>(d));
  826. break;
  827. case DeclarationName::CXXConstructorName:
  828. case DeclarationName::CXXDestructorName:
  829. case DeclarationName::CXXConversionFunctionName:
  830. case DeclarationName::CXXUsingDirective:
  831. Key.Data = 0;
  832. break;
  833. }
  834. return Key;
  835. }
  836. ASTDeclContextNameLookupTrait::data_type
  837. ASTDeclContextNameLookupTrait::ReadData(internal_key_type,
  838. const unsigned char* d,
  839. unsigned DataLen) {
  840. using namespace llvm::support;
  841. unsigned NumDecls = endian::readNext<uint16_t, little, unaligned>(d);
  842. LE32DeclID *Start = reinterpret_cast<LE32DeclID *>(
  843. const_cast<unsigned char *>(d));
  844. return std::make_pair(Start, Start + NumDecls);
  845. }
  846. bool ASTReader::ReadDeclContextStorage(ModuleFile &M,
  847. BitstreamCursor &Cursor,
  848. const std::pair<uint64_t, uint64_t> &Offsets,
  849. DeclContextInfo &Info) {
  850. SavedStreamPosition SavedPosition(Cursor);
  851. // First the lexical decls.
  852. if (Offsets.first != 0) {
  853. Cursor.JumpToBit(Offsets.first);
  854. RecordData Record;
  855. StringRef Blob;
  856. unsigned Code = Cursor.ReadCode();
  857. unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
  858. if (RecCode != DECL_CONTEXT_LEXICAL) {
  859. Error("Expected lexical block");
  860. return true;
  861. }
  862. Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair*>(Blob.data());
  863. Info.NumLexicalDecls = Blob.size() / sizeof(KindDeclIDPair);
  864. }
  865. // Now the lookup table.
  866. if (Offsets.second != 0) {
  867. Cursor.JumpToBit(Offsets.second);
  868. RecordData Record;
  869. StringRef Blob;
  870. unsigned Code = Cursor.ReadCode();
  871. unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
  872. if (RecCode != DECL_CONTEXT_VISIBLE) {
  873. Error("Expected visible lookup table block");
  874. return true;
  875. }
  876. Info.NameLookupTableData = ASTDeclContextNameLookupTable::Create(
  877. (const unsigned char *)Blob.data() + Record[0],
  878. (const unsigned char *)Blob.data() + sizeof(uint32_t),
  879. (const unsigned char *)Blob.data(),
  880. ASTDeclContextNameLookupTrait(*this, M));
  881. }
  882. return false;
  883. }
  884. void ASTReader::Error(StringRef Msg) {
  885. Error(diag::err_fe_pch_malformed, Msg);
  886. if (Context.getLangOpts().Modules && !Diags.isDiagnosticInFlight()) {
  887. Diag(diag::note_module_cache_path)
  888. << PP.getHeaderSearchInfo().getModuleCachePath();
  889. }
  890. }
  891. void ASTReader::Error(unsigned DiagID,
  892. StringRef Arg1, StringRef Arg2) {
  893. if (Diags.isDiagnosticInFlight())
  894. Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
  895. else
  896. Diag(DiagID) << Arg1 << Arg2;
  897. }
  898. //===----------------------------------------------------------------------===//
  899. // Source Manager Deserialization
  900. //===----------------------------------------------------------------------===//
  901. /// \brief Read the line table in the source manager block.
  902. /// \returns true if there was an error.
  903. bool ASTReader::ParseLineTable(ModuleFile &F,
  904. const RecordData &Record) {
  905. unsigned Idx = 0;
  906. LineTableInfo &LineTable = SourceMgr.getLineTable();
  907. // Parse the file names
  908. std::map<int, int> FileIDs;
  909. for (int I = 0, N = Record[Idx++]; I != N; ++I) {
  910. // Extract the file name
  911. auto Filename = ReadPath(F, Record, Idx);
  912. FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
  913. }
  914. // Parse the line entries
  915. std::vector<LineEntry> Entries;
  916. while (Idx < Record.size()) {
  917. int FID = Record[Idx++];
  918. assert(FID >= 0 && "Serialized line entries for non-local file.");
  919. // Remap FileID from 1-based old view.
  920. FID += F.SLocEntryBaseID - 1;
  921. // Extract the line entries
  922. unsigned NumEntries = Record[Idx++];
  923. assert(NumEntries && "Numentries is 00000");
  924. Entries.clear();
  925. Entries.reserve(NumEntries);
  926. for (unsigned I = 0; I != NumEntries; ++I) {
  927. unsigned FileOffset = Record[Idx++];
  928. unsigned LineNo = Record[Idx++];
  929. int FilenameID = FileIDs[Record[Idx++]];
  930. SrcMgr::CharacteristicKind FileKind
  931. = (SrcMgr::CharacteristicKind)Record[Idx++];
  932. unsigned IncludeOffset = Record[Idx++];
  933. Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
  934. FileKind, IncludeOffset));
  935. }
  936. LineTable.AddEntry(FileID::get(FID), Entries);
  937. }
  938. return false;
  939. }
  940. /// \brief Read a source manager block
  941. bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
  942. using namespace SrcMgr;
  943. BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
  944. // Set the source-location entry cursor to the current position in
  945. // the stream. This cursor will be used to read the contents of the
  946. // source manager block initially, and then lazily read
  947. // source-location entries as needed.
  948. SLocEntryCursor = F.Stream;
  949. // The stream itself is going to skip over the source manager block.
  950. if (F.Stream.SkipBlock()) {
  951. Error("malformed block record in AST file");
  952. return true;
  953. }
  954. // Enter the source manager block.
  955. if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
  956. Error("malformed source manager block record in AST file");
  957. return true;
  958. }
  959. RecordData Record;
  960. while (true) {
  961. llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
  962. switch (E.Kind) {
  963. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  964. case llvm::BitstreamEntry::Error:
  965. Error("malformed block record in AST file");
  966. return true;
  967. case llvm::BitstreamEntry::EndBlock:
  968. return false;
  969. case llvm::BitstreamEntry::Record:
  970. // The interesting case.
  971. break;
  972. }
  973. // Read a record.
  974. Record.clear();
  975. StringRef Blob;
  976. switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
  977. default: // Default behavior: ignore.
  978. break;
  979. case SM_SLOC_FILE_ENTRY:
  980. case SM_SLOC_BUFFER_ENTRY:
  981. case SM_SLOC_EXPANSION_ENTRY:
  982. // Once we hit one of the source location entries, we're done.
  983. return false;
  984. }
  985. }
  986. }
  987. /// \brief If a header file is not found at the path that we expect it to be
  988. /// and the PCH file was moved from its original location, try to resolve the
  989. /// file by assuming that header+PCH were moved together and the header is in
  990. /// the same place relative to the PCH.
  991. static std::string
  992. resolveFileRelativeToOriginalDir(const std::string &Filename,
  993. const std::string &OriginalDir,
  994. const std::string &CurrDir) {
  995. assert(OriginalDir != CurrDir &&
  996. "No point trying to resolve the file if the PCH dir didn't change");
  997. using namespace llvm::sys;
  998. SmallString<128> filePath(Filename);
  999. fs::make_absolute(filePath);
  1000. assert(path::is_absolute(OriginalDir));
  1001. SmallString<128> currPCHPath(CurrDir);
  1002. path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
  1003. fileDirE = path::end(path::parent_path(filePath));
  1004. path::const_iterator origDirI = path::begin(OriginalDir),
  1005. origDirE = path::end(OriginalDir);
  1006. // Skip the common path components from filePath and OriginalDir.
  1007. while (fileDirI != fileDirE && origDirI != origDirE &&
  1008. *fileDirI == *origDirI) {
  1009. ++fileDirI;
  1010. ++origDirI;
  1011. }
  1012. for (; origDirI != origDirE; ++origDirI)
  1013. path::append(currPCHPath, "..");
  1014. path::append(currPCHPath, fileDirI, fileDirE);
  1015. path::append(currPCHPath, path::filename(Filename));
  1016. return currPCHPath.str();
  1017. }
  1018. bool ASTReader::ReadSLocEntry(int ID) {
  1019. if (ID == 0)
  1020. return false;
  1021. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1022. Error("source location entry ID out-of-range for AST file");
  1023. return true;
  1024. }
  1025. ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
  1026. F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
  1027. BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
  1028. unsigned BaseOffset = F->SLocEntryBaseOffset;
  1029. ++NumSLocEntriesRead;
  1030. llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
  1031. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1032. Error("incorrectly-formatted source location entry in AST file");
  1033. return true;
  1034. }
  1035. RecordData Record;
  1036. StringRef Blob;
  1037. switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
  1038. default:
  1039. Error("incorrectly-formatted source location entry in AST file");
  1040. return true;
  1041. case SM_SLOC_FILE_ENTRY: {
  1042. // We will detect whether a file changed and return 'Failure' for it, but
  1043. // we will also try to fail gracefully by setting up the SLocEntry.
  1044. unsigned InputID = Record[4];
  1045. InputFile IF = getInputFile(*F, InputID);
  1046. const FileEntry *File = IF.getFile();
  1047. bool OverriddenBuffer = IF.isOverridden();
  1048. // Note that we only check if a File was returned. If it was out-of-date
  1049. // we have complained but we will continue creating a FileID to recover
  1050. // gracefully.
  1051. if (!File)
  1052. return true;
  1053. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1054. if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
  1055. // This is the module's main file.
  1056. IncludeLoc = getImportLocation(F);
  1057. }
  1058. SrcMgr::CharacteristicKind
  1059. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1060. FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
  1061. ID, BaseOffset + Record[0]);
  1062. SrcMgr::FileInfo &FileInfo =
  1063. const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
  1064. FileInfo.NumCreatedFIDs = Record[5];
  1065. if (Record[3])
  1066. FileInfo.setHasLineDirectives();
  1067. const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
  1068. unsigned NumFileDecls = Record[7];
  1069. if (NumFileDecls) {
  1070. assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
  1071. FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
  1072. NumFileDecls));
  1073. }
  1074. const SrcMgr::ContentCache *ContentCache
  1075. = SourceMgr.getOrCreateContentCache(File,
  1076. /*isSystemFile=*/FileCharacter != SrcMgr::C_User);
  1077. if (OverriddenBuffer && !ContentCache->BufferOverridden &&
  1078. ContentCache->ContentsEntry == ContentCache->OrigEntry) {
  1079. unsigned Code = SLocEntryCursor.ReadCode();
  1080. Record.clear();
  1081. unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
  1082. if (RecCode != SM_SLOC_BUFFER_BLOB) {
  1083. Error("AST record has invalid code");
  1084. return true;
  1085. }
  1086. std::unique_ptr<llvm::MemoryBuffer> Buffer
  1087. = llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), File->getName());
  1088. SourceMgr.overrideFileContents(File, std::move(Buffer));
  1089. }
  1090. break;
  1091. }
  1092. case SM_SLOC_BUFFER_ENTRY: {
  1093. const char *Name = Blob.data();
  1094. unsigned Offset = Record[0];
  1095. SrcMgr::CharacteristicKind
  1096. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1097. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1098. if (IncludeLoc.isInvalid() &&
  1099. (F->Kind == MK_ImplicitModule || F->Kind == MK_ExplicitModule)) {
  1100. IncludeLoc = getImportLocation(F);
  1101. }
  1102. unsigned Code = SLocEntryCursor.ReadCode();
  1103. Record.clear();
  1104. unsigned RecCode
  1105. = SLocEntryCursor.readRecord(Code, Record, &Blob);
  1106. if (RecCode != SM_SLOC_BUFFER_BLOB) {
  1107. Error("AST record has invalid code");
  1108. return true;
  1109. }
  1110. std::unique_ptr<llvm::MemoryBuffer> Buffer =
  1111. llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name);
  1112. SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
  1113. BaseOffset + Offset, IncludeLoc);
  1114. break;
  1115. }
  1116. case SM_SLOC_EXPANSION_ENTRY: {
  1117. SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
  1118. SourceMgr.createExpansionLoc(SpellingLoc,
  1119. ReadSourceLocation(*F, Record[2]),
  1120. ReadSourceLocation(*F, Record[3]),
  1121. Record[4],
  1122. ID,
  1123. BaseOffset + Record[0]);
  1124. break;
  1125. }
  1126. }
  1127. return false;
  1128. }
  1129. std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
  1130. if (ID == 0)
  1131. return std::make_pair(SourceLocation(), "");
  1132. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1133. Error("source location entry ID out-of-range for AST file");
  1134. return std::make_pair(SourceLocation(), "");
  1135. }
  1136. // Find which module file this entry lands in.
  1137. ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
  1138. if (M->Kind != MK_ImplicitModule && M->Kind != MK_ExplicitModule)
  1139. return std::make_pair(SourceLocation(), "");
  1140. // FIXME: Can we map this down to a particular submodule? That would be
  1141. // ideal.
  1142. return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
  1143. }
  1144. /// \brief Find the location where the module F is imported.
  1145. SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
  1146. if (F->ImportLoc.isValid())
  1147. return F->ImportLoc;
  1148. // Otherwise we have a PCH. It's considered to be "imported" at the first
  1149. // location of its includer.
  1150. if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
  1151. // Main file is the importer.
  1152. assert(!SourceMgr.getMainFileID().isInvalid() && "missing main file");
  1153. return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  1154. }
  1155. return F->ImportedBy[0]->FirstLoc;
  1156. }
  1157. /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
  1158. /// specified cursor. Read the abbreviations that are at the top of the block
  1159. /// and then leave the cursor pointing into the block.
  1160. bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
  1161. if (Cursor.EnterSubBlock(BlockID)) {
  1162. Error("malformed block record in AST file");
  1163. return Failure;
  1164. }
  1165. while (true) {
  1166. uint64_t Offset = Cursor.GetCurrentBitNo();
  1167. unsigned Code = Cursor.ReadCode();
  1168. // We expect all abbrevs to be at the start of the block.
  1169. if (Code != llvm::bitc::DEFINE_ABBREV) {
  1170. Cursor.JumpToBit(Offset);
  1171. return false;
  1172. }
  1173. Cursor.ReadAbbrevRecord();
  1174. }
  1175. }
  1176. Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
  1177. unsigned &Idx) {
  1178. Token Tok;
  1179. Tok.startToken();
  1180. Tok.setLocation(ReadSourceLocation(F, Record, Idx));
  1181. Tok.setLength(Record[Idx++]);
  1182. if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
  1183. Tok.setIdentifierInfo(II);
  1184. Tok.setKind((tok::TokenKind)Record[Idx++]);
  1185. Tok.setFlag((Token::TokenFlags)Record[Idx++]);
  1186. return Tok;
  1187. }
  1188. MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
  1189. BitstreamCursor &Stream = F.MacroCursor;
  1190. // Keep track of where we are in the stream, then jump back there
  1191. // after reading this macro.
  1192. SavedStreamPosition SavedPosition(Stream);
  1193. Stream.JumpToBit(Offset);
  1194. RecordData Record;
  1195. SmallVector<IdentifierInfo*, 16> MacroArgs;
  1196. MacroInfo *Macro = nullptr;
  1197. while (true) {
  1198. // Advance to the next record, but if we get to the end of the block, don't
  1199. // pop it (removing all the abbreviations from the cursor) since we want to
  1200. // be able to reseek within the block and read entries.
  1201. unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
  1202. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
  1203. switch (Entry.Kind) {
  1204. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1205. case llvm::BitstreamEntry::Error:
  1206. Error("malformed block record in AST file");
  1207. return Macro;
  1208. case llvm::BitstreamEntry::EndBlock:
  1209. return Macro;
  1210. case llvm::BitstreamEntry::Record:
  1211. // The interesting case.
  1212. break;
  1213. }
  1214. // Read a record.
  1215. Record.clear();
  1216. PreprocessorRecordTypes RecType =
  1217. (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
  1218. switch (RecType) {
  1219. case PP_MODULE_MACRO:
  1220. case PP_MACRO_DIRECTIVE_HISTORY:
  1221. return Macro;
  1222. case PP_MACRO_OBJECT_LIKE:
  1223. case PP_MACRO_FUNCTION_LIKE: {
  1224. // If we already have a macro, that means that we've hit the end
  1225. // of the definition of the macro we were looking for. We're
  1226. // done.
  1227. if (Macro)
  1228. return Macro;
  1229. unsigned NextIndex = 1; // Skip identifier ID.
  1230. SubmoduleID SubModID = getGlobalSubmoduleID(F, Record[NextIndex++]);
  1231. SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
  1232. MacroInfo *MI = PP.AllocateDeserializedMacroInfo(Loc, SubModID);
  1233. MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
  1234. MI->setIsUsed(Record[NextIndex++]);
  1235. MI->setUsedForHeaderGuard(Record[NextIndex++]);
  1236. if (RecType == PP_MACRO_FUNCTION_LIKE) {
  1237. // Decode function-like macro info.
  1238. bool isC99VarArgs = Record[NextIndex++];
  1239. bool isGNUVarArgs = Record[NextIndex++];
  1240. bool hasCommaPasting = Record[NextIndex++];
  1241. MacroArgs.clear();
  1242. unsigned NumArgs = Record[NextIndex++];
  1243. for (unsigned i = 0; i != NumArgs; ++i)
  1244. MacroArgs.push_back(getLocalIdentifier(F, Record[NextIndex++]));
  1245. // Install function-like macro info.
  1246. MI->setIsFunctionLike();
  1247. if (isC99VarArgs) MI->setIsC99Varargs();
  1248. if (isGNUVarArgs) MI->setIsGNUVarargs();
  1249. if (hasCommaPasting) MI->setHasCommaPasting();
  1250. MI->setArgumentList(MacroArgs.data(), MacroArgs.size(),
  1251. PP.getPreprocessorAllocator());
  1252. }
  1253. // Remember that we saw this macro last so that we add the tokens that
  1254. // form its body to it.
  1255. Macro = MI;
  1256. if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
  1257. Record[NextIndex]) {
  1258. // We have a macro definition. Register the association
  1259. PreprocessedEntityID
  1260. GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
  1261. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  1262. PreprocessingRecord::PPEntityID PPID =
  1263. PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
  1264. MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
  1265. PPRec.getPreprocessedEntity(PPID));
  1266. if (PPDef)
  1267. PPRec.RegisterMacroDefinition(Macro, PPDef);
  1268. }
  1269. ++NumMacrosRead;
  1270. break;
  1271. }
  1272. case PP_TOKEN: {
  1273. // If we see a TOKEN before a PP_MACRO_*, then the file is
  1274. // erroneous, just pretend we didn't see this.
  1275. if (!Macro) break;
  1276. unsigned Idx = 0;
  1277. Token Tok = ReadToken(F, Record, Idx);
  1278. Macro->AddTokenToBody(Tok);
  1279. break;
  1280. }
  1281. }
  1282. }
  1283. }
  1284. PreprocessedEntityID
  1285. ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M, unsigned LocalID) const {
  1286. ContinuousRangeMap<uint32_t, int, 2>::const_iterator
  1287. I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
  1288. assert(I != M.PreprocessedEntityRemap.end()
  1289. && "Invalid index into preprocessed entity index remap");
  1290. return LocalID + I->second;
  1291. }
  1292. unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
  1293. return llvm::hash_combine(ikey.Size, ikey.ModTime);
  1294. }
  1295. HeaderFileInfoTrait::internal_key_type
  1296. HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
  1297. internal_key_type ikey = { FE->getSize(), FE->getModificationTime(),
  1298. FE->getName(), /*Imported*/false };
  1299. return ikey;
  1300. }
  1301. bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
  1302. if (a.Size != b.Size || a.ModTime != b.ModTime)
  1303. return false;
  1304. if (llvm::sys::path::is_absolute(a.Filename) &&
  1305. strcmp(a.Filename, b.Filename) == 0)
  1306. return true;
  1307. // Determine whether the actual files are equivalent.
  1308. FileManager &FileMgr = Reader.getFileManager();
  1309. auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
  1310. if (!Key.Imported)
  1311. return FileMgr.getFile(Key.Filename);
  1312. std::string Resolved = Key.Filename;
  1313. Reader.ResolveImportedPath(M, Resolved);
  1314. return FileMgr.getFile(Resolved);
  1315. };
  1316. const FileEntry *FEA = GetFile(a);
  1317. const FileEntry *FEB = GetFile(b);
  1318. return FEA && FEA == FEB;
  1319. }
  1320. std::pair<unsigned, unsigned>
  1321. HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
  1322. using namespace llvm::support;
  1323. unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
  1324. unsigned DataLen = (unsigned) *d++;
  1325. return std::make_pair(KeyLen, DataLen);
  1326. }
  1327. HeaderFileInfoTrait::internal_key_type
  1328. HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
  1329. using namespace llvm::support;
  1330. internal_key_type ikey;
  1331. ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
  1332. ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
  1333. ikey.Filename = (const char *)d;
  1334. ikey.Imported = true;
  1335. return ikey;
  1336. }
  1337. HeaderFileInfoTrait::data_type
  1338. HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
  1339. unsigned DataLen) {
  1340. const unsigned char *End = d + DataLen;
  1341. using namespace llvm::support;
  1342. HeaderFileInfo HFI;
  1343. unsigned Flags = *d++;
  1344. HFI.HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>
  1345. ((Flags >> 6) & 0x03);
  1346. HFI.isImport = (Flags >> 5) & 0x01;
  1347. HFI.isPragmaOnce = (Flags >> 4) & 0x01;
  1348. HFI.DirInfo = (Flags >> 2) & 0x03;
  1349. HFI.Resolved = (Flags >> 1) & 0x01;
  1350. HFI.IndexHeaderMapHeader = Flags & 0x01;
  1351. HFI.NumIncludes = endian::readNext<uint16_t, little, unaligned>(d);
  1352. HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
  1353. M, endian::readNext<uint32_t, little, unaligned>(d));
  1354. if (unsigned FrameworkOffset =
  1355. endian::readNext<uint32_t, little, unaligned>(d)) {
  1356. // The framework offset is 1 greater than the actual offset,
  1357. // since 0 is used as an indicator for "no framework name".
  1358. StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
  1359. HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
  1360. }
  1361. if (d != End) {
  1362. uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
  1363. if (LocalSMID) {
  1364. // This header is part of a module. Associate it with the module to enable
  1365. // implicit module import.
  1366. SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
  1367. Module *Mod = Reader.getSubmodule(GlobalSMID);
  1368. HFI.isModuleHeader = true;
  1369. FileManager &FileMgr = Reader.getFileManager();
  1370. ModuleMap &ModMap =
  1371. Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1372. // FIXME: This information should be propagated through the
  1373. // SUBMODULE_HEADER etc records rather than from here.
  1374. // FIXME: We don't ever mark excluded headers.
  1375. std::string Filename = key.Filename;
  1376. if (key.Imported)
  1377. Reader.ResolveImportedPath(M, Filename);
  1378. Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
  1379. ModMap.addHeader(Mod, H, HFI.getHeaderRole());
  1380. }
  1381. }
  1382. assert(End == d && "Wrong data length in HeaderFileInfo deserialization");
  1383. (void)End;
  1384. // This HeaderFileInfo was externally loaded.
  1385. HFI.External = true;
  1386. return HFI;
  1387. }
  1388. void ASTReader::addPendingMacro(IdentifierInfo *II,
  1389. ModuleFile *M,
  1390. uint64_t MacroDirectivesOffset) {
  1391. assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
  1392. PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
  1393. }
  1394. void ASTReader::ReadDefinedMacros() {
  1395. // Note that we are loading defined macros.
  1396. Deserializing Macros(this);
  1397. for (ModuleReverseIterator I = ModuleMgr.rbegin(),
  1398. E = ModuleMgr.rend(); I != E; ++I) {
  1399. BitstreamCursor &MacroCursor = (*I)->MacroCursor;
  1400. // If there was no preprocessor block, skip this file.
  1401. if (!MacroCursor.getBitStreamReader())
  1402. continue;
  1403. BitstreamCursor Cursor = MacroCursor;
  1404. Cursor.JumpToBit((*I)->MacroStartOffset);
  1405. RecordData Record;
  1406. while (true) {
  1407. llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
  1408. switch (E.Kind) {
  1409. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1410. case llvm::BitstreamEntry::Error:
  1411. Error("malformed block record in AST file");
  1412. return;
  1413. case llvm::BitstreamEntry::EndBlock:
  1414. goto NextCursor;
  1415. case llvm::BitstreamEntry::Record:
  1416. Record.clear();
  1417. switch (Cursor.readRecord(E.ID, Record)) {
  1418. default: // Default behavior: ignore.
  1419. break;
  1420. case PP_MACRO_OBJECT_LIKE:
  1421. case PP_MACRO_FUNCTION_LIKE:
  1422. getLocalIdentifier(**I, Record[0]);
  1423. break;
  1424. case PP_TOKEN:
  1425. // Ignore tokens.
  1426. break;
  1427. }
  1428. break;
  1429. }
  1430. }
  1431. NextCursor: ;
  1432. }
  1433. }
  1434. namespace {
  1435. /// \brief Visitor class used to look up identifirs in an AST file.
  1436. class IdentifierLookupVisitor {
  1437. StringRef Name;
  1438. unsigned NameHash;
  1439. unsigned PriorGeneration;
  1440. unsigned &NumIdentifierLookups;
  1441. unsigned &NumIdentifierLookupHits;
  1442. IdentifierInfo *Found;
  1443. public:
  1444. IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
  1445. unsigned &NumIdentifierLookups,
  1446. unsigned &NumIdentifierLookupHits)
  1447. : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
  1448. PriorGeneration(PriorGeneration),
  1449. NumIdentifierLookups(NumIdentifierLookups),
  1450. NumIdentifierLookupHits(NumIdentifierLookupHits),
  1451. Found()
  1452. {
  1453. }
  1454. static bool visit(ModuleFile &M, void *UserData) {
  1455. IdentifierLookupVisitor *This
  1456. = static_cast<IdentifierLookupVisitor *>(UserData);
  1457. // If we've already searched this module file, skip it now.
  1458. if (M.Generation <= This->PriorGeneration)
  1459. return true;
  1460. ASTIdentifierLookupTable *IdTable
  1461. = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
  1462. if (!IdTable)
  1463. return false;
  1464. ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(),
  1465. M, This->Found);
  1466. ++This->NumIdentifierLookups;
  1467. ASTIdentifierLookupTable::iterator Pos =
  1468. IdTable->find_hashed(This->Name, This->NameHash, &Trait);
  1469. if (Pos == IdTable->end())
  1470. return false;
  1471. // Dereferencing the iterator has the effect of building the
  1472. // IdentifierInfo node and populating it with the various
  1473. // declarations it needs.
  1474. ++This->NumIdentifierLookupHits;
  1475. This->Found = *Pos;
  1476. return true;
  1477. }
  1478. // \brief Retrieve the identifier info found within the module
  1479. // files.
  1480. IdentifierInfo *getIdentifierInfo() const { return Found; }
  1481. };
  1482. }
  1483. void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
  1484. // Note that we are loading an identifier.
  1485. Deserializing AnIdentifier(this);
  1486. unsigned PriorGeneration = 0;
  1487. if (getContext().getLangOpts().Modules)
  1488. PriorGeneration = IdentifierGeneration[&II];
  1489. // If there is a global index, look there first to determine which modules
  1490. // provably do not have any results for this identifier.
  1491. GlobalModuleIndex::HitSet Hits;
  1492. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  1493. if (!loadGlobalIndex()) {
  1494. if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
  1495. HitsPtr = &Hits;
  1496. }
  1497. }
  1498. IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
  1499. NumIdentifierLookups,
  1500. NumIdentifierLookupHits);
  1501. ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
  1502. markIdentifierUpToDate(&II);
  1503. }
  1504. void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
  1505. if (!II)
  1506. return;
  1507. II->setOutOfDate(false);
  1508. // Update the generation for this identifier.
  1509. if (getContext().getLangOpts().Modules)
  1510. IdentifierGeneration[II] = getGeneration();
  1511. }
  1512. void ASTReader::resolvePendingMacro(IdentifierInfo *II,
  1513. const PendingMacroInfo &PMInfo) {
  1514. ModuleFile &M = *PMInfo.M;
  1515. BitstreamCursor &Cursor = M.MacroCursor;
  1516. SavedStreamPosition SavedPosition(Cursor);
  1517. Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
  1518. struct ModuleMacroRecord {
  1519. SubmoduleID SubModID;
  1520. MacroInfo *MI;
  1521. SmallVector<SubmoduleID, 8> Overrides;
  1522. };
  1523. llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
  1524. // We expect to see a sequence of PP_MODULE_MACRO records listing exported
  1525. // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
  1526. // macro histroy.
  1527. RecordData Record;
  1528. while (true) {
  1529. llvm::BitstreamEntry Entry =
  1530. Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  1531. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1532. Error("malformed block record in AST file");
  1533. return;
  1534. }
  1535. Record.clear();
  1536. switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
  1537. case PP_MACRO_DIRECTIVE_HISTORY:
  1538. break;
  1539. case PP_MODULE_MACRO: {
  1540. ModuleMacros.push_back(ModuleMacroRecord());
  1541. auto &Info = ModuleMacros.back();
  1542. Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
  1543. Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
  1544. for (int I = 2, N = Record.size(); I != N; ++I)
  1545. Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
  1546. continue;
  1547. }
  1548. default:
  1549. Error("malformed block record in AST file");
  1550. return;
  1551. }
  1552. // We found the macro directive history; that's the last record
  1553. // for this macro.
  1554. break;
  1555. }
  1556. // Module macros are listed in reverse dependency order.
  1557. {
  1558. std::reverse(ModuleMacros.begin(), ModuleMacros.end());
  1559. llvm::SmallVector<ModuleMacro*, 8> Overrides;
  1560. for (auto &MMR : ModuleMacros) {
  1561. Overrides.clear();
  1562. for (unsigned ModID : MMR.Overrides) {
  1563. Module *Mod = getSubmodule(ModID);
  1564. auto *Macro = PP.getModuleMacro(Mod, II);
  1565. assert(Macro && "missing definition for overridden macro");
  1566. Overrides.push_back(Macro);
  1567. }
  1568. bool Inserted = false;
  1569. Module *Owner = getSubmodule(MMR.SubModID);
  1570. PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
  1571. }
  1572. }
  1573. // Don't read the directive history for a module; we don't have anywhere
  1574. // to put it.
  1575. if (M.Kind == MK_ImplicitModule || M.Kind == MK_ExplicitModule)
  1576. return;
  1577. // Deserialize the macro directives history in reverse source-order.
  1578. MacroDirective *Latest = nullptr, *Earliest = nullptr;
  1579. unsigned Idx = 0, N = Record.size();
  1580. while (Idx < N) {
  1581. MacroDirective *MD = nullptr;
  1582. SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
  1583. MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
  1584. switch (K) {
  1585. case MacroDirective::MD_Define: {
  1586. MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
  1587. MD = PP.AllocateDefMacroDirective(MI, Loc);
  1588. break;
  1589. }
  1590. case MacroDirective::MD_Undefine: {
  1591. MD = PP.AllocateUndefMacroDirective(Loc);
  1592. break;
  1593. }
  1594. case MacroDirective::MD_Visibility:
  1595. bool isPublic = Record[Idx++];
  1596. MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
  1597. break;
  1598. }
  1599. if (!Latest)
  1600. Latest = MD;
  1601. if (Earliest)
  1602. Earliest->setPrevious(MD);
  1603. Earliest = MD;
  1604. }
  1605. if (Latest)
  1606. PP.setLoadedMacroDirective(II, Latest);
  1607. }
  1608. ASTReader::InputFileInfo
  1609. ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
  1610. // Go find this input file.
  1611. BitstreamCursor &Cursor = F.InputFilesCursor;
  1612. SavedStreamPosition SavedPosition(Cursor);
  1613. Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
  1614. unsigned Code = Cursor.ReadCode();
  1615. RecordData Record;
  1616. StringRef Blob;
  1617. unsigned Result = Cursor.readRecord(Code, Record, &Blob);
  1618. assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
  1619. "invalid record type for input file");
  1620. (void)Result;
  1621. std::string Filename;
  1622. off_t StoredSize;
  1623. time_t StoredTime;
  1624. bool Overridden;
  1625. assert(Record[0] == ID && "Bogus stored ID or offset");
  1626. StoredSize = static_cast<off_t>(Record[1]);
  1627. StoredTime = static_cast<time_t>(Record[2]);
  1628. Overridden = static_cast<bool>(Record[3]);
  1629. Filename = Blob;
  1630. ResolveImportedPath(F, Filename);
  1631. InputFileInfo R = { std::move(Filename), StoredSize, StoredTime, Overridden };
  1632. return R;
  1633. }
  1634. std::string ASTReader::getInputFileName(ModuleFile &F, unsigned int ID) {
  1635. return readInputFileInfo(F, ID).Filename;
  1636. }
  1637. InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
  1638. // If this ID is bogus, just return an empty input file.
  1639. if (ID == 0 || ID > F.InputFilesLoaded.size())
  1640. return InputFile();
  1641. // If we've already loaded this input file, return it.
  1642. if (F.InputFilesLoaded[ID-1].getFile())
  1643. return F.InputFilesLoaded[ID-1];
  1644. if (F.InputFilesLoaded[ID-1].isNotFound())
  1645. return InputFile();
  1646. // Go find this input file.
  1647. BitstreamCursor &Cursor = F.InputFilesCursor;
  1648. SavedStreamPosition SavedPosition(Cursor);
  1649. Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
  1650. InputFileInfo FI = readInputFileInfo(F, ID);
  1651. off_t StoredSize = FI.StoredSize;
  1652. time_t StoredTime = FI.StoredTime;
  1653. bool Overridden = FI.Overridden;
  1654. StringRef Filename = FI.Filename;
  1655. const FileEntry *File
  1656. = Overridden? FileMgr.getVirtualFile(Filename, StoredSize, StoredTime)
  1657. : FileMgr.getFile(Filename, /*OpenFile=*/false);
  1658. // If we didn't find the file, resolve it relative to the
  1659. // original directory from which this AST file was created.
  1660. if (File == nullptr && !F.OriginalDir.empty() && !CurrentDir.empty() &&
  1661. F.OriginalDir != CurrentDir) {
  1662. std::string Resolved = resolveFileRelativeToOriginalDir(Filename,
  1663. F.OriginalDir,
  1664. CurrentDir);
  1665. if (!Resolved.empty())
  1666. File = FileMgr.getFile(Resolved);
  1667. }
  1668. // For an overridden file, create a virtual file with the stored
  1669. // size/timestamp.
  1670. if (Overridden && File == nullptr) {
  1671. File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
  1672. }
  1673. if (File == nullptr) {
  1674. if (Complain) {
  1675. std::string ErrorStr = "could not find file '";
  1676. ErrorStr += Filename;
  1677. ErrorStr += "' referenced by AST file";
  1678. Error(ErrorStr.c_str());
  1679. }
  1680. // Record that we didn't find the file.
  1681. F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
  1682. return InputFile();
  1683. }
  1684. // Check if there was a request to override the contents of the file
  1685. // that was part of the precompiled header. Overridding such a file
  1686. // can lead to problems when lexing using the source locations from the
  1687. // PCH.
  1688. SourceManager &SM = getSourceManager();
  1689. if (!Overridden && SM.isFileOverridden(File)) {
  1690. if (Complain)
  1691. Error(diag::err_fe_pch_file_overridden, Filename);
  1692. // After emitting the diagnostic, recover by disabling the override so
  1693. // that the original file will be used.
  1694. SM.disableFileContentsOverride(File);
  1695. // The FileEntry is a virtual file entry with the size of the contents
  1696. // that would override the original contents. Set it to the original's
  1697. // size/time.
  1698. FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
  1699. StoredSize, StoredTime);
  1700. }
  1701. bool IsOutOfDate = false;
  1702. // For an overridden file, there is nothing to validate.
  1703. if (!Overridden && //
  1704. (StoredSize != File->getSize() ||
  1705. #if defined(LLVM_ON_WIN32)
  1706. false
  1707. #else
  1708. // In our regression testing, the Windows file system seems to
  1709. // have inconsistent modification times that sometimes
  1710. // erroneously trigger this error-handling path.
  1711. //
  1712. // This also happens in networked file systems, so disable this
  1713. // check if validation is disabled or if we have an explicitly
  1714. // built PCM file.
  1715. //
  1716. // FIXME: Should we also do this for PCH files? They could also
  1717. // reasonably get shared across a network during a distributed build.
  1718. (StoredTime != File->getModificationTime() && !DisableValidation &&
  1719. F.Kind != MK_ExplicitModule)
  1720. #endif
  1721. )) {
  1722. if (Complain) {
  1723. // Build a list of the PCH imports that got us here (in reverse).
  1724. SmallVector<ModuleFile *, 4> ImportStack(1, &F);
  1725. while (ImportStack.back()->ImportedBy.size() > 0)
  1726. ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
  1727. // The top-level PCH is stale.
  1728. StringRef TopLevelPCHName(ImportStack.back()->FileName);
  1729. Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
  1730. // Print the import stack.
  1731. if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
  1732. Diag(diag::note_pch_required_by)
  1733. << Filename << ImportStack[0]->FileName;
  1734. for (unsigned I = 1; I < ImportStack.size(); ++I)
  1735. Diag(diag::note_pch_required_by)
  1736. << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
  1737. }
  1738. if (!Diags.isDiagnosticInFlight())
  1739. Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
  1740. }
  1741. IsOutOfDate = true;
  1742. }
  1743. InputFile IF = InputFile(File, Overridden, IsOutOfDate);
  1744. // Note that we've loaded this input file.
  1745. F.InputFilesLoaded[ID-1] = IF;
  1746. return IF;
  1747. }
  1748. /// \brief If we are loading a relocatable PCH or module file, and the filename
  1749. /// is not an absolute path, add the system or module root to the beginning of
  1750. /// the file name.
  1751. void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
  1752. // Resolve relative to the base directory, if we have one.
  1753. if (!M.BaseDirectory.empty())
  1754. return ResolveImportedPath(Filename, M.BaseDirectory);
  1755. }
  1756. void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
  1757. if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
  1758. return;
  1759. SmallString<128> Buffer;
  1760. llvm::sys::path::append(Buffer, Prefix, Filename);
  1761. Filename.assign(Buffer.begin(), Buffer.end());
  1762. }
  1763. ASTReader::ASTReadResult
  1764. ASTReader::ReadControlBlock(ModuleFile &F,
  1765. SmallVectorImpl<ImportedModule> &Loaded,
  1766. const ModuleFile *ImportedBy,
  1767. unsigned ClientLoadCapabilities) {
  1768. BitstreamCursor &Stream = F.Stream;
  1769. if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
  1770. Error("malformed block record in AST file");
  1771. return Failure;
  1772. }
  1773. // Should we allow the configuration of the module file to differ from the
  1774. // configuration of the current translation unit in a compatible way?
  1775. //
  1776. // FIXME: Allow this for files explicitly specified with -include-pch too.
  1777. bool AllowCompatibleConfigurationMismatch = F.Kind == MK_ExplicitModule;
  1778. // Read all of the records and blocks in the control block.
  1779. RecordData Record;
  1780. unsigned NumInputs = 0;
  1781. unsigned NumUserInputs = 0;
  1782. while (1) {
  1783. llvm::BitstreamEntry Entry = Stream.advance();
  1784. switch (Entry.Kind) {
  1785. case llvm::BitstreamEntry::Error:
  1786. Error("malformed block record in AST file");
  1787. return Failure;
  1788. case llvm::BitstreamEntry::EndBlock: {
  1789. // Validate input files.
  1790. const HeaderSearchOptions &HSOpts =
  1791. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  1792. // All user input files reside at the index range [0, NumUserInputs), and
  1793. // system input files reside at [NumUserInputs, NumInputs).
  1794. if (!DisableValidation) {
  1795. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
  1796. // If we are reading a module, we will create a verification timestamp,
  1797. // so we verify all input files. Otherwise, verify only user input
  1798. // files.
  1799. unsigned N = NumUserInputs;
  1800. if (ValidateSystemInputs ||
  1801. (HSOpts.ModulesValidateOncePerBuildSession &&
  1802. F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
  1803. F.Kind == MK_ImplicitModule))
  1804. N = NumInputs;
  1805. for (unsigned I = 0; I < N; ++I) {
  1806. InputFile IF = getInputFile(F, I+1, Complain);
  1807. if (!IF.getFile() || IF.isOutOfDate())
  1808. return OutOfDate;
  1809. }
  1810. }
  1811. if (Listener)
  1812. Listener->visitModuleFile(F.FileName);
  1813. if (Listener && Listener->needsInputFileVisitation()) {
  1814. unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
  1815. : NumUserInputs;
  1816. for (unsigned I = 0; I < N; ++I) {
  1817. bool IsSystem = I >= NumUserInputs;
  1818. InputFileInfo FI = readInputFileInfo(F, I+1);
  1819. Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden);
  1820. }
  1821. }
  1822. return Success;
  1823. }
  1824. case llvm::BitstreamEntry::SubBlock:
  1825. switch (Entry.ID) {
  1826. case INPUT_FILES_BLOCK_ID:
  1827. F.InputFilesCursor = Stream;
  1828. if (Stream.SkipBlock() || // Skip with the main cursor
  1829. // Read the abbreviations
  1830. ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
  1831. Error("malformed block record in AST file");
  1832. return Failure;
  1833. }
  1834. continue;
  1835. default:
  1836. if (Stream.SkipBlock()) {
  1837. Error("malformed block record in AST file");
  1838. return Failure;
  1839. }
  1840. continue;
  1841. }
  1842. case llvm::BitstreamEntry::Record:
  1843. // The interesting case.
  1844. break;
  1845. }
  1846. // Read and process a record.
  1847. Record.clear();
  1848. StringRef Blob;
  1849. switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
  1850. case METADATA: {
  1851. if (Record[0] != VERSION_MAJOR && !DisableValidation) {
  1852. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  1853. Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
  1854. : diag::err_pch_version_too_new);
  1855. return VersionMismatch;
  1856. }
  1857. bool hasErrors = Record[5];
  1858. if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
  1859. Diag(diag::err_pch_with_compiler_errors);
  1860. return HadErrors;
  1861. }
  1862. F.RelocatablePCH = Record[4];
  1863. // Relative paths in a relocatable PCH are relative to our sysroot.
  1864. if (F.RelocatablePCH)
  1865. F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
  1866. const std::string &CurBranch = getClangFullRepositoryVersion();
  1867. StringRef ASTBranch = Blob;
  1868. if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
  1869. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  1870. Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
  1871. return VersionMismatch;
  1872. }
  1873. break;
  1874. }
  1875. case SIGNATURE:
  1876. assert((!F.Signature || F.Signature == Record[0]) && "signature changed");
  1877. F.Signature = Record[0];
  1878. break;
  1879. case IMPORTS: {
  1880. // Load each of the imported PCH files.
  1881. unsigned Idx = 0, N = Record.size();
  1882. while (Idx < N) {
  1883. // Read information about the AST file.
  1884. ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
  1885. // The import location will be the local one for now; we will adjust
  1886. // all import locations of module imports after the global source
  1887. // location info are setup.
  1888. SourceLocation ImportLoc =
  1889. SourceLocation::getFromRawEncoding(Record[Idx++]);
  1890. off_t StoredSize = (off_t)Record[Idx++];
  1891. time_t StoredModTime = (time_t)Record[Idx++];
  1892. ASTFileSignature StoredSignature = Record[Idx++];
  1893. auto ImportedFile = ReadPath(F, Record, Idx);
  1894. // Load the AST file.
  1895. switch(ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F, Loaded,
  1896. StoredSize, StoredModTime, StoredSignature,
  1897. ClientLoadCapabilities)) {
  1898. case Failure: return Failure;
  1899. // If we have to ignore the dependency, we'll have to ignore this too.
  1900. case Missing:
  1901. case OutOfDate: return OutOfDate;
  1902. case VersionMismatch: return VersionMismatch;
  1903. case ConfigurationMismatch: return ConfigurationMismatch;
  1904. case HadErrors: return HadErrors;
  1905. case Success: break;
  1906. }
  1907. }
  1908. break;
  1909. }
  1910. case KNOWN_MODULE_FILES:
  1911. break;
  1912. case LANGUAGE_OPTIONS: {
  1913. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  1914. // FIXME: The &F == *ModuleMgr.begin() check is wrong for modules.
  1915. if (Listener && &F == *ModuleMgr.begin() &&
  1916. ParseLanguageOptions(Record, Complain, *Listener,
  1917. AllowCompatibleConfigurationMismatch) &&
  1918. !DisableValidation && !AllowConfigurationMismatch)
  1919. return ConfigurationMismatch;
  1920. break;
  1921. }
  1922. case TARGET_OPTIONS: {
  1923. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
  1924. if (Listener && &F == *ModuleMgr.begin() &&
  1925. ParseTargetOptions(Record, Complain, *Listener,
  1926. AllowCompatibleConfigurationMismatch) &&
  1927. !DisableValidation && !AllowConfigurationMismatch)
  1928. return ConfigurationMismatch;
  1929. break;
  1930. }
  1931. case DIAGNOSTIC_OPTIONS: {
  1932. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate)==0;
  1933. if (Listener && &F == *ModuleMgr.begin() &&
  1934. !AllowCompatibleConfigurationMismatch &&
  1935. ParseDiagnosticOptions(Record, Complain, *Listener) &&
  1936. !DisableValidation)
  1937. return OutOfDate;
  1938. break;
  1939. }
  1940. case FILE_SYSTEM_OPTIONS: {
  1941. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
  1942. if (Listener && &F == *ModuleMgr.begin() &&
  1943. !AllowCompatibleConfigurationMismatch &&
  1944. ParseFileSystemOptions(Record, Complain, *Listener) &&
  1945. !DisableValidation && !AllowConfigurationMismatch)
  1946. return ConfigurationMismatch;
  1947. break;
  1948. }
  1949. case HEADER_SEARCH_OPTIONS: {
  1950. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
  1951. if (Listener && &F == *ModuleMgr.begin() &&
  1952. !AllowCompatibleConfigurationMismatch &&
  1953. ParseHeaderSearchOptions(Record, Complain, *Listener) &&
  1954. !DisableValidation && !AllowConfigurationMismatch)
  1955. return ConfigurationMismatch;
  1956. break;
  1957. }
  1958. case PREPROCESSOR_OPTIONS: {
  1959. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch)==0;
  1960. if (Listener && &F == *ModuleMgr.begin() &&
  1961. !AllowCompatibleConfigurationMismatch &&
  1962. ParsePreprocessorOptions(Record, Complain, *Listener,
  1963. SuggestedPredefines) &&
  1964. !DisableValidation && !AllowConfigurationMismatch)
  1965. return ConfigurationMismatch;
  1966. break;
  1967. }
  1968. case ORIGINAL_FILE:
  1969. F.OriginalSourceFileID = FileID::get(Record[0]);
  1970. F.ActualOriginalSourceFileName = Blob;
  1971. F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
  1972. ResolveImportedPath(F, F.OriginalSourceFileName);
  1973. break;
  1974. case ORIGINAL_FILE_ID:
  1975. F.OriginalSourceFileID = FileID::get(Record[0]);
  1976. break;
  1977. case ORIGINAL_PCH_DIR:
  1978. F.OriginalDir = Blob;
  1979. break;
  1980. case MODULE_NAME:
  1981. F.ModuleName = Blob;
  1982. if (Listener)
  1983. Listener->ReadModuleName(F.ModuleName);
  1984. break;
  1985. case MODULE_DIRECTORY: {
  1986. assert(!F.ModuleName.empty() &&
  1987. "MODULE_DIRECTORY found before MODULE_NAME");
  1988. // If we've already loaded a module map file covering this module, we may
  1989. // have a better path for it (relative to the current build).
  1990. Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
  1991. if (M && M->Directory) {
  1992. // If we're implicitly loading a module, the base directory can't
  1993. // change between the build and use.
  1994. if (F.Kind != MK_ExplicitModule) {
  1995. const DirectoryEntry *BuildDir =
  1996. PP.getFileManager().getDirectory(Blob);
  1997. if (!BuildDir || BuildDir != M->Directory) {
  1998. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  1999. Diag(diag::err_imported_module_relocated)
  2000. << F.ModuleName << Blob << M->Directory->getName();
  2001. return OutOfDate;
  2002. }
  2003. }
  2004. F.BaseDirectory = M->Directory->getName();
  2005. } else {
  2006. F.BaseDirectory = Blob;
  2007. }
  2008. break;
  2009. }
  2010. case MODULE_MAP_FILE:
  2011. if (ASTReadResult Result =
  2012. ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
  2013. return Result;
  2014. break;
  2015. case INPUT_FILE_OFFSETS:
  2016. NumInputs = Record[0];
  2017. NumUserInputs = Record[1];
  2018. F.InputFileOffsets =
  2019. (const llvm::support::unaligned_uint64_t *)Blob.data();
  2020. F.InputFilesLoaded.resize(NumInputs);
  2021. break;
  2022. }
  2023. }
  2024. }
  2025. ASTReader::ASTReadResult
  2026. ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
  2027. BitstreamCursor &Stream = F.Stream;
  2028. if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
  2029. Error("malformed block record in AST file");
  2030. return Failure;
  2031. }
  2032. // Read all of the records and blocks for the AST file.
  2033. RecordData Record;
  2034. while (1) {
  2035. llvm::BitstreamEntry Entry = Stream.advance();
  2036. switch (Entry.Kind) {
  2037. case llvm::BitstreamEntry::Error:
  2038. Error("error at end of module block in AST file");
  2039. return Failure;
  2040. case llvm::BitstreamEntry::EndBlock: {
  2041. // Outside of C++, we do not store a lookup map for the translation unit.
  2042. // Instead, mark it as needing a lookup map to be built if this module
  2043. // contains any declarations lexically within it (which it always does!).
  2044. // This usually has no cost, since we very rarely need the lookup map for
  2045. // the translation unit outside C++.
  2046. DeclContext *DC = Context.getTranslationUnitDecl();
  2047. if (DC->hasExternalLexicalStorage() &&
  2048. !getContext().getLangOpts().CPlusPlus)
  2049. DC->setMustBuildLookupTable();
  2050. return Success;
  2051. }
  2052. case llvm::BitstreamEntry::SubBlock:
  2053. switch (Entry.ID) {
  2054. case DECLTYPES_BLOCK_ID:
  2055. // We lazily load the decls block, but we want to set up the
  2056. // DeclsCursor cursor to point into it. Clone our current bitcode
  2057. // cursor to it, enter the block and read the abbrevs in that block.
  2058. // With the main cursor, we just skip over it.
  2059. F.DeclsCursor = Stream;
  2060. if (Stream.SkipBlock() || // Skip with the main cursor.
  2061. // Read the abbrevs.
  2062. ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
  2063. Error("malformed block record in AST file");
  2064. return Failure;
  2065. }
  2066. break;
  2067. case PREPROCESSOR_BLOCK_ID:
  2068. F.MacroCursor = Stream;
  2069. if (!PP.getExternalSource())
  2070. PP.setExternalSource(this);
  2071. if (Stream.SkipBlock() ||
  2072. ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
  2073. Error("malformed block record in AST file");
  2074. return Failure;
  2075. }
  2076. F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
  2077. break;
  2078. case PREPROCESSOR_DETAIL_BLOCK_ID:
  2079. F.PreprocessorDetailCursor = Stream;
  2080. if (Stream.SkipBlock() ||
  2081. ReadBlockAbbrevs(F.PreprocessorDetailCursor,
  2082. PREPROCESSOR_DETAIL_BLOCK_ID)) {
  2083. Error("malformed preprocessor detail record in AST file");
  2084. return Failure;
  2085. }
  2086. F.PreprocessorDetailStartOffset
  2087. = F.PreprocessorDetailCursor.GetCurrentBitNo();
  2088. if (!PP.getPreprocessingRecord())
  2089. PP.createPreprocessingRecord();
  2090. if (!PP.getPreprocessingRecord()->getExternalSource())
  2091. PP.getPreprocessingRecord()->SetExternalSource(*this);
  2092. break;
  2093. case SOURCE_MANAGER_BLOCK_ID:
  2094. if (ReadSourceManagerBlock(F))
  2095. return Failure;
  2096. break;
  2097. case SUBMODULE_BLOCK_ID:
  2098. if (ASTReadResult Result = ReadSubmoduleBlock(F, ClientLoadCapabilities))
  2099. return Result;
  2100. break;
  2101. case COMMENTS_BLOCK_ID: {
  2102. BitstreamCursor C = Stream;
  2103. if (Stream.SkipBlock() ||
  2104. ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
  2105. Error("malformed comments block in AST file");
  2106. return Failure;
  2107. }
  2108. CommentsCursors.push_back(std::make_pair(C, &F));
  2109. break;
  2110. }
  2111. default:
  2112. if (Stream.SkipBlock()) {
  2113. Error("malformed block record in AST file");
  2114. return Failure;
  2115. }
  2116. break;
  2117. }
  2118. continue;
  2119. case llvm::BitstreamEntry::Record:
  2120. // The interesting case.
  2121. break;
  2122. }
  2123. // Read and process a record.
  2124. Record.clear();
  2125. StringRef Blob;
  2126. switch ((ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
  2127. default: // Default behavior: ignore.
  2128. break;
  2129. case TYPE_OFFSET: {
  2130. if (F.LocalNumTypes != 0) {
  2131. Error("duplicate TYPE_OFFSET record in AST file");
  2132. return Failure;
  2133. }
  2134. F.TypeOffsets = (const uint32_t *)Blob.data();
  2135. F.LocalNumTypes = Record[0];
  2136. unsigned LocalBaseTypeIndex = Record[1];
  2137. F.BaseTypeIndex = getTotalNumTypes();
  2138. if (F.LocalNumTypes > 0) {
  2139. // Introduce the global -> local mapping for types within this module.
  2140. GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
  2141. // Introduce the local -> global mapping for types within this module.
  2142. F.TypeRemap.insertOrReplace(
  2143. std::make_pair(LocalBaseTypeIndex,
  2144. F.BaseTypeIndex - LocalBaseTypeIndex));
  2145. TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
  2146. }
  2147. break;
  2148. }
  2149. case DECL_OFFSET: {
  2150. if (F.LocalNumDecls != 0) {
  2151. Error("duplicate DECL_OFFSET record in AST file");
  2152. return Failure;
  2153. }
  2154. F.DeclOffsets = (const DeclOffset *)Blob.data();
  2155. F.LocalNumDecls = Record[0];
  2156. unsigned LocalBaseDeclID = Record[1];
  2157. F.BaseDeclID = getTotalNumDecls();
  2158. if (F.LocalNumDecls > 0) {
  2159. // Introduce the global -> local mapping for declarations within this
  2160. // module.
  2161. GlobalDeclMap.insert(
  2162. std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
  2163. // Introduce the local -> global mapping for declarations within this
  2164. // module.
  2165. F.DeclRemap.insertOrReplace(
  2166. std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
  2167. // Introduce the global -> local mapping for declarations within this
  2168. // module.
  2169. F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
  2170. DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
  2171. }
  2172. break;
  2173. }
  2174. case TU_UPDATE_LEXICAL: {
  2175. DeclContext *TU = Context.getTranslationUnitDecl();
  2176. DeclContextInfo &Info = F.DeclContextInfos[TU];
  2177. Info.LexicalDecls = reinterpret_cast<const KindDeclIDPair *>(Blob.data());
  2178. Info.NumLexicalDecls
  2179. = static_cast<unsigned int>(Blob.size() / sizeof(KindDeclIDPair));
  2180. TU->setHasExternalLexicalStorage(true);
  2181. break;
  2182. }
  2183. case UPDATE_VISIBLE: {
  2184. unsigned Idx = 0;
  2185. serialization::DeclID ID = ReadDeclID(F, Record, Idx);
  2186. ASTDeclContextNameLookupTable *Table =
  2187. ASTDeclContextNameLookupTable::Create(
  2188. (const unsigned char *)Blob.data() + Record[Idx++],
  2189. (const unsigned char *)Blob.data() + sizeof(uint32_t),
  2190. (const unsigned char *)Blob.data(),
  2191. ASTDeclContextNameLookupTrait(*this, F));
  2192. if (Decl *D = GetExistingDecl(ID)) {
  2193. auto *DC = cast<DeclContext>(D);
  2194. DC->getPrimaryContext()->setHasExternalVisibleStorage(true);
  2195. auto *&LookupTable = F.DeclContextInfos[DC].NameLookupTableData;
  2196. delete LookupTable;
  2197. LookupTable = Table;
  2198. } else
  2199. PendingVisibleUpdates[ID].push_back(std::make_pair(Table, &F));
  2200. break;
  2201. }
  2202. case IDENTIFIER_TABLE:
  2203. F.IdentifierTableData = Blob.data();
  2204. if (Record[0]) {
  2205. F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
  2206. (const unsigned char *)F.IdentifierTableData + Record[0],
  2207. (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
  2208. (const unsigned char *)F.IdentifierTableData,
  2209. ASTIdentifierLookupTrait(*this, F));
  2210. PP.getIdentifierTable().setExternalIdentifierLookup(this);
  2211. }
  2212. break;
  2213. case IDENTIFIER_OFFSET: {
  2214. if (F.LocalNumIdentifiers != 0) {
  2215. Error("duplicate IDENTIFIER_OFFSET record in AST file");
  2216. return Failure;
  2217. }
  2218. F.IdentifierOffsets = (const uint32_t *)Blob.data();
  2219. F.LocalNumIdentifiers = Record[0];
  2220. unsigned LocalBaseIdentifierID = Record[1];
  2221. F.BaseIdentifierID = getTotalNumIdentifiers();
  2222. if (F.LocalNumIdentifiers > 0) {
  2223. // Introduce the global -> local mapping for identifiers within this
  2224. // module.
  2225. GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
  2226. &F));
  2227. // Introduce the local -> global mapping for identifiers within this
  2228. // module.
  2229. F.IdentifierRemap.insertOrReplace(
  2230. std::make_pair(LocalBaseIdentifierID,
  2231. F.BaseIdentifierID - LocalBaseIdentifierID));
  2232. IdentifiersLoaded.resize(IdentifiersLoaded.size()
  2233. + F.LocalNumIdentifiers);
  2234. }
  2235. break;
  2236. }
  2237. case EAGERLY_DESERIALIZED_DECLS:
  2238. // FIXME: Skip reading this record if our ASTConsumer doesn't care
  2239. // about "interesting" decls (for instance, if we're building a module).
  2240. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2241. EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2242. break;
  2243. case SPECIAL_TYPES:
  2244. if (SpecialTypes.empty()) {
  2245. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2246. SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
  2247. break;
  2248. }
  2249. if (SpecialTypes.size() != Record.size()) {
  2250. Error("invalid special-types record");
  2251. return Failure;
  2252. }
  2253. for (unsigned I = 0, N = Record.size(); I != N; ++I) {
  2254. serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
  2255. if (!SpecialTypes[I])
  2256. SpecialTypes[I] = ID;
  2257. // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
  2258. // merge step?
  2259. }
  2260. break;
  2261. case STATISTICS:
  2262. TotalNumStatements += Record[0];
  2263. TotalNumMacros += Record[1];
  2264. TotalLexicalDeclContexts += Record[2];
  2265. TotalVisibleDeclContexts += Record[3];
  2266. break;
  2267. case UNUSED_FILESCOPED_DECLS:
  2268. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2269. UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2270. break;
  2271. case DELEGATING_CTORS:
  2272. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2273. DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
  2274. break;
  2275. case WEAK_UNDECLARED_IDENTIFIERS:
  2276. if (Record.size() % 4 != 0) {
  2277. Error("invalid weak identifiers record");
  2278. return Failure;
  2279. }
  2280. // FIXME: Ignore weak undeclared identifiers from non-original PCH
  2281. // files. This isn't the way to do it :)
  2282. WeakUndeclaredIdentifiers.clear();
  2283. // Translate the weak, undeclared identifiers into global IDs.
  2284. for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
  2285. WeakUndeclaredIdentifiers.push_back(
  2286. getGlobalIdentifierID(F, Record[I++]));
  2287. WeakUndeclaredIdentifiers.push_back(
  2288. getGlobalIdentifierID(F, Record[I++]));
  2289. WeakUndeclaredIdentifiers.push_back(
  2290. ReadSourceLocation(F, Record, I).getRawEncoding());
  2291. WeakUndeclaredIdentifiers.push_back(Record[I++]);
  2292. }
  2293. break;
  2294. case SELECTOR_OFFSETS: {
  2295. F.SelectorOffsets = (const uint32_t *)Blob.data();
  2296. F.LocalNumSelectors = Record[0];
  2297. unsigned LocalBaseSelectorID = Record[1];
  2298. F.BaseSelectorID = getTotalNumSelectors();
  2299. if (F.LocalNumSelectors > 0) {
  2300. // Introduce the global -> local mapping for selectors within this
  2301. // module.
  2302. GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
  2303. // Introduce the local -> global mapping for selectors within this
  2304. // module.
  2305. F.SelectorRemap.insertOrReplace(
  2306. std::make_pair(LocalBaseSelectorID,
  2307. F.BaseSelectorID - LocalBaseSelectorID));
  2308. SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
  2309. }
  2310. break;
  2311. }
  2312. case METHOD_POOL:
  2313. F.SelectorLookupTableData = (const unsigned char *)Blob.data();
  2314. if (Record[0])
  2315. F.SelectorLookupTable
  2316. = ASTSelectorLookupTable::Create(
  2317. F.SelectorLookupTableData + Record[0],
  2318. F.SelectorLookupTableData,
  2319. ASTSelectorLookupTrait(*this, F));
  2320. TotalNumMethodPoolEntries += Record[1];
  2321. break;
  2322. case REFERENCED_SELECTOR_POOL:
  2323. if (!Record.empty()) {
  2324. for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
  2325. ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
  2326. Record[Idx++]));
  2327. ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
  2328. getRawEncoding());
  2329. }
  2330. }
  2331. break;
  2332. case PP_COUNTER_VALUE:
  2333. if (!Record.empty() && Listener)
  2334. Listener->ReadCounter(F, Record[0]);
  2335. break;
  2336. case FILE_SORTED_DECLS:
  2337. F.FileSortedDecls = (const DeclID *)Blob.data();
  2338. F.NumFileSortedDecls = Record[0];
  2339. break;
  2340. case SOURCE_LOCATION_OFFSETS: {
  2341. F.SLocEntryOffsets = (const uint32_t *)Blob.data();
  2342. F.LocalNumSLocEntries = Record[0];
  2343. unsigned SLocSpaceSize = Record[1];
  2344. std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
  2345. SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
  2346. SLocSpaceSize);
  2347. // Make our entry in the range map. BaseID is negative and growing, so
  2348. // we invert it. Because we invert it, though, we need the other end of
  2349. // the range.
  2350. unsigned RangeStart =
  2351. unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
  2352. GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
  2353. F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
  2354. // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
  2355. assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
  2356. GlobalSLocOffsetMap.insert(
  2357. std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
  2358. - SLocSpaceSize,&F));
  2359. // Initialize the remapping table.
  2360. // Invalid stays invalid.
  2361. F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
  2362. // This module. Base was 2 when being compiled.
  2363. F.SLocRemap.insertOrReplace(std::make_pair(2U,
  2364. static_cast<int>(F.SLocEntryBaseOffset - 2)));
  2365. TotalNumSLocEntries += F.LocalNumSLocEntries;
  2366. break;
  2367. }
  2368. case MODULE_OFFSET_MAP: {
  2369. // Additional remapping information.
  2370. const unsigned char *Data = (const unsigned char*)Blob.data();
  2371. const unsigned char *DataEnd = Data + Blob.size();
  2372. // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
  2373. if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
  2374. F.SLocRemap.insert(std::make_pair(0U, 0));
  2375. F.SLocRemap.insert(std::make_pair(2U, 1));
  2376. }
  2377. // Continuous range maps we may be updating in our module.
  2378. typedef ContinuousRangeMap<uint32_t, int, 2>::Builder
  2379. RemapBuilder;
  2380. RemapBuilder SLocRemap(F.SLocRemap);
  2381. RemapBuilder IdentifierRemap(F.IdentifierRemap);
  2382. RemapBuilder MacroRemap(F.MacroRemap);
  2383. RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
  2384. RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
  2385. RemapBuilder SelectorRemap(F.SelectorRemap);
  2386. RemapBuilder DeclRemap(F.DeclRemap);
  2387. RemapBuilder TypeRemap(F.TypeRemap);
  2388. while(Data < DataEnd) {
  2389. using namespace llvm::support;
  2390. uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
  2391. StringRef Name = StringRef((const char*)Data, Len);
  2392. Data += Len;
  2393. ModuleFile *OM = ModuleMgr.lookup(Name);
  2394. if (!OM) {
  2395. Error("SourceLocation remap refers to unknown module");
  2396. return Failure;
  2397. }
  2398. uint32_t SLocOffset =
  2399. endian::readNext<uint32_t, little, unaligned>(Data);
  2400. uint32_t IdentifierIDOffset =
  2401. endian::readNext<uint32_t, little, unaligned>(Data);
  2402. uint32_t MacroIDOffset =
  2403. endian::readNext<uint32_t, little, unaligned>(Data);
  2404. uint32_t PreprocessedEntityIDOffset =
  2405. endian::readNext<uint32_t, little, unaligned>(Data);
  2406. uint32_t SubmoduleIDOffset =
  2407. endian::readNext<uint32_t, little, unaligned>(Data);
  2408. uint32_t SelectorIDOffset =
  2409. endian::readNext<uint32_t, little, unaligned>(Data);
  2410. uint32_t DeclIDOffset =
  2411. endian::readNext<uint32_t, little, unaligned>(Data);
  2412. uint32_t TypeIndexOffset =
  2413. endian::readNext<uint32_t, little, unaligned>(Data);
  2414. uint32_t None = std::numeric_limits<uint32_t>::max();
  2415. auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
  2416. RemapBuilder &Remap) {
  2417. if (Offset != None)
  2418. Remap.insert(std::make_pair(Offset,
  2419. static_cast<int>(BaseOffset - Offset)));
  2420. };
  2421. mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
  2422. mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
  2423. mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
  2424. mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
  2425. PreprocessedEntityRemap);
  2426. mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
  2427. mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
  2428. mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
  2429. mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
  2430. // Global -> local mappings.
  2431. F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
  2432. }
  2433. break;
  2434. }
  2435. case SOURCE_MANAGER_LINE_TABLE:
  2436. if (ParseLineTable(F, Record))
  2437. return Failure;
  2438. break;
  2439. case SOURCE_LOCATION_PRELOADS: {
  2440. // Need to transform from the local view (1-based IDs) to the global view,
  2441. // which is based off F.SLocEntryBaseID.
  2442. if (!F.PreloadSLocEntries.empty()) {
  2443. Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
  2444. return Failure;
  2445. }
  2446. F.PreloadSLocEntries.swap(Record);
  2447. break;
  2448. }
  2449. case EXT_VECTOR_DECLS:
  2450. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2451. ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
  2452. break;
  2453. case VTABLE_USES:
  2454. if (Record.size() % 3 != 0) {
  2455. Error("Invalid VTABLE_USES record");
  2456. return Failure;
  2457. }
  2458. // Later tables overwrite earlier ones.
  2459. // FIXME: Modules will have some trouble with this. This is clearly not
  2460. // the right way to do this.
  2461. VTableUses.clear();
  2462. for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
  2463. VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
  2464. VTableUses.push_back(
  2465. ReadSourceLocation(F, Record, Idx).getRawEncoding());
  2466. VTableUses.push_back(Record[Idx++]);
  2467. }
  2468. break;
  2469. case PENDING_IMPLICIT_INSTANTIATIONS:
  2470. if (PendingInstantiations.size() % 2 != 0) {
  2471. Error("Invalid existing PendingInstantiations");
  2472. return Failure;
  2473. }
  2474. if (Record.size() % 2 != 0) {
  2475. Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
  2476. return Failure;
  2477. }
  2478. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  2479. PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
  2480. PendingInstantiations.push_back(
  2481. ReadSourceLocation(F, Record, I).getRawEncoding());
  2482. }
  2483. break;
  2484. case SEMA_DECL_REFS:
  2485. if (Record.size() != 2) {
  2486. Error("Invalid SEMA_DECL_REFS block");
  2487. return Failure;
  2488. }
  2489. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2490. SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  2491. break;
  2492. case PPD_ENTITIES_OFFSETS: {
  2493. F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
  2494. assert(Blob.size() % sizeof(PPEntityOffset) == 0);
  2495. F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
  2496. unsigned LocalBasePreprocessedEntityID = Record[0];
  2497. unsigned StartingID;
  2498. if (!PP.getPreprocessingRecord())
  2499. PP.createPreprocessingRecord();
  2500. if (!PP.getPreprocessingRecord()->getExternalSource())
  2501. PP.getPreprocessingRecord()->SetExternalSource(*this);
  2502. StartingID
  2503. = PP.getPreprocessingRecord()
  2504. ->allocateLoadedEntities(F.NumPreprocessedEntities);
  2505. F.BasePreprocessedEntityID = StartingID;
  2506. if (F.NumPreprocessedEntities > 0) {
  2507. // Introduce the global -> local mapping for preprocessed entities in
  2508. // this module.
  2509. GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
  2510. // Introduce the local -> global mapping for preprocessed entities in
  2511. // this module.
  2512. F.PreprocessedEntityRemap.insertOrReplace(
  2513. std::make_pair(LocalBasePreprocessedEntityID,
  2514. F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
  2515. }
  2516. break;
  2517. }
  2518. case DECL_UPDATE_OFFSETS: {
  2519. if (Record.size() % 2 != 0) {
  2520. Error("invalid DECL_UPDATE_OFFSETS block in AST file");
  2521. return Failure;
  2522. }
  2523. for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
  2524. GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
  2525. DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
  2526. // If we've already loaded the decl, perform the updates when we finish
  2527. // loading this block.
  2528. if (Decl *D = GetExistingDecl(ID))
  2529. PendingUpdateRecords.push_back(std::make_pair(ID, D));
  2530. }
  2531. break;
  2532. }
  2533. case DECL_REPLACEMENTS: {
  2534. if (Record.size() % 3 != 0) {
  2535. Error("invalid DECL_REPLACEMENTS block in AST file");
  2536. return Failure;
  2537. }
  2538. for (unsigned I = 0, N = Record.size(); I != N; I += 3)
  2539. ReplacedDecls[getGlobalDeclID(F, Record[I])]
  2540. = ReplacedDeclInfo(&F, Record[I+1], Record[I+2]);
  2541. break;
  2542. }
  2543. case OBJC_CATEGORIES_MAP: {
  2544. if (F.LocalNumObjCCategoriesInMap != 0) {
  2545. Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
  2546. return Failure;
  2547. }
  2548. F.LocalNumObjCCategoriesInMap = Record[0];
  2549. F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
  2550. break;
  2551. }
  2552. case OBJC_CATEGORIES:
  2553. F.ObjCCategories.swap(Record);
  2554. break;
  2555. case CXX_BASE_SPECIFIER_OFFSETS: {
  2556. if (F.LocalNumCXXBaseSpecifiers != 0) {
  2557. Error("duplicate CXX_BASE_SPECIFIER_OFFSETS record in AST file");
  2558. return Failure;
  2559. }
  2560. F.LocalNumCXXBaseSpecifiers = Record[0];
  2561. F.CXXBaseSpecifiersOffsets = (const uint32_t *)Blob.data();
  2562. break;
  2563. }
  2564. case CXX_CTOR_INITIALIZERS_OFFSETS: {
  2565. if (F.LocalNumCXXCtorInitializers != 0) {
  2566. Error("duplicate CXX_CTOR_INITIALIZERS_OFFSETS record in AST file");
  2567. return Failure;
  2568. }
  2569. F.LocalNumCXXCtorInitializers = Record[0];
  2570. F.CXXCtorInitializersOffsets = (const uint32_t *)Blob.data();
  2571. break;
  2572. }
  2573. case DIAG_PRAGMA_MAPPINGS:
  2574. if (F.PragmaDiagMappings.empty())
  2575. F.PragmaDiagMappings.swap(Record);
  2576. else
  2577. F.PragmaDiagMappings.insert(F.PragmaDiagMappings.end(),
  2578. Record.begin(), Record.end());
  2579. break;
  2580. case CUDA_SPECIAL_DECL_REFS:
  2581. // Later tables overwrite earlier ones.
  2582. // FIXME: Modules will have trouble with this.
  2583. CUDASpecialDeclRefs.clear();
  2584. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2585. CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  2586. break;
  2587. case HEADER_SEARCH_TABLE: {
  2588. F.HeaderFileInfoTableData = Blob.data();
  2589. F.LocalNumHeaderFileInfos = Record[1];
  2590. if (Record[0]) {
  2591. F.HeaderFileInfoTable
  2592. = HeaderFileInfoLookupTable::Create(
  2593. (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
  2594. (const unsigned char *)F.HeaderFileInfoTableData,
  2595. HeaderFileInfoTrait(*this, F,
  2596. &PP.getHeaderSearchInfo(),
  2597. Blob.data() + Record[2]));
  2598. PP.getHeaderSearchInfo().SetExternalSource(this);
  2599. if (!PP.getHeaderSearchInfo().getExternalLookup())
  2600. PP.getHeaderSearchInfo().SetExternalLookup(this);
  2601. }
  2602. break;
  2603. }
  2604. case FP_PRAGMA_OPTIONS:
  2605. // Later tables overwrite earlier ones.
  2606. FPPragmaOptions.swap(Record);
  2607. break;
  2608. case OPENCL_EXTENSIONS:
  2609. // Later tables overwrite earlier ones.
  2610. OpenCLExtensions.swap(Record);
  2611. break;
  2612. case TENTATIVE_DEFINITIONS:
  2613. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2614. TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
  2615. break;
  2616. case KNOWN_NAMESPACES:
  2617. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2618. KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
  2619. break;
  2620. case UNDEFINED_BUT_USED:
  2621. if (UndefinedButUsed.size() % 2 != 0) {
  2622. Error("Invalid existing UndefinedButUsed");
  2623. return Failure;
  2624. }
  2625. if (Record.size() % 2 != 0) {
  2626. Error("invalid undefined-but-used record");
  2627. return Failure;
  2628. }
  2629. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  2630. UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
  2631. UndefinedButUsed.push_back(
  2632. ReadSourceLocation(F, Record, I).getRawEncoding());
  2633. }
  2634. break;
  2635. case DELETE_EXPRS_TO_ANALYZE:
  2636. for (unsigned I = 0, N = Record.size(); I != N;) {
  2637. DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
  2638. const uint64_t Count = Record[I++];
  2639. DelayedDeleteExprs.push_back(Count);
  2640. for (uint64_t C = 0; C < Count; ++C) {
  2641. DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
  2642. bool IsArrayForm = Record[I++] == 1;
  2643. DelayedDeleteExprs.push_back(IsArrayForm);
  2644. }
  2645. }
  2646. break;
  2647. case IMPORTED_MODULES: {
  2648. if (F.Kind != MK_ImplicitModule && F.Kind != MK_ExplicitModule) {
  2649. // If we aren't loading a module (which has its own exports), make
  2650. // all of the imported modules visible.
  2651. // FIXME: Deal with macros-only imports.
  2652. for (unsigned I = 0, N = Record.size(); I != N; /**/) {
  2653. unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
  2654. SourceLocation Loc = ReadSourceLocation(F, Record, I);
  2655. if (GlobalID)
  2656. ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
  2657. }
  2658. }
  2659. break;
  2660. }
  2661. case LOCAL_REDECLARATIONS: {
  2662. F.RedeclarationChains.swap(Record);
  2663. break;
  2664. }
  2665. case LOCAL_REDECLARATIONS_MAP: {
  2666. if (F.LocalNumRedeclarationsInMap != 0) {
  2667. Error("duplicate LOCAL_REDECLARATIONS_MAP record in AST file");
  2668. return Failure;
  2669. }
  2670. F.LocalNumRedeclarationsInMap = Record[0];
  2671. F.RedeclarationsMap = (const LocalRedeclarationsInfo *)Blob.data();
  2672. break;
  2673. }
  2674. case MACRO_OFFSET: {
  2675. if (F.LocalNumMacros != 0) {
  2676. Error("duplicate MACRO_OFFSET record in AST file");
  2677. return Failure;
  2678. }
  2679. F.MacroOffsets = (const uint32_t *)Blob.data();
  2680. F.LocalNumMacros = Record[0];
  2681. unsigned LocalBaseMacroID = Record[1];
  2682. F.BaseMacroID = getTotalNumMacros();
  2683. if (F.LocalNumMacros > 0) {
  2684. // Introduce the global -> local mapping for macros within this module.
  2685. GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
  2686. // Introduce the local -> global mapping for macros within this module.
  2687. F.MacroRemap.insertOrReplace(
  2688. std::make_pair(LocalBaseMacroID,
  2689. F.BaseMacroID - LocalBaseMacroID));
  2690. MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
  2691. }
  2692. break;
  2693. }
  2694. case LATE_PARSED_TEMPLATE: {
  2695. LateParsedTemplates.append(Record.begin(), Record.end());
  2696. break;
  2697. }
  2698. case OPTIMIZE_PRAGMA_OPTIONS:
  2699. if (Record.size() != 1) {
  2700. Error("invalid pragma optimize record");
  2701. return Failure;
  2702. }
  2703. OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
  2704. break;
  2705. case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
  2706. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2707. UnusedLocalTypedefNameCandidates.push_back(
  2708. getGlobalDeclID(F, Record[I]));
  2709. break;
  2710. }
  2711. }
  2712. }
  2713. ASTReader::ASTReadResult
  2714. ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
  2715. const ModuleFile *ImportedBy,
  2716. unsigned ClientLoadCapabilities) {
  2717. unsigned Idx = 0;
  2718. F.ModuleMapPath = ReadPath(F, Record, Idx);
  2719. if (F.Kind == MK_ExplicitModule) {
  2720. // For an explicitly-loaded module, we don't care whether the original
  2721. // module map file exists or matches.
  2722. return Success;
  2723. }
  2724. // Try to resolve ModuleName in the current header search context and
  2725. // verify that it is found in the same module map file as we saved. If the
  2726. // top-level AST file is a main file, skip this check because there is no
  2727. // usable header search context.
  2728. assert(!F.ModuleName.empty() &&
  2729. "MODULE_NAME should come before MODULE_MAP_FILE");
  2730. if (F.Kind == MK_ImplicitModule &&
  2731. (*ModuleMgr.begin())->Kind != MK_MainFile) {
  2732. // An implicitly-loaded module file should have its module listed in some
  2733. // module map file that we've already loaded.
  2734. Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
  2735. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  2736. const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
  2737. if (!ModMap) {
  2738. assert(ImportedBy && "top-level import should be verified");
  2739. if ((ClientLoadCapabilities & ARR_Missing) == 0)
  2740. Diag(diag::err_imported_module_not_found) << F.ModuleName << F.FileName
  2741. << ImportedBy->FileName
  2742. << F.ModuleMapPath;
  2743. return Missing;
  2744. }
  2745. assert(M->Name == F.ModuleName && "found module with different name");
  2746. // Check the primary module map file.
  2747. const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
  2748. if (StoredModMap == nullptr || StoredModMap != ModMap) {
  2749. assert(ModMap && "found module is missing module map file");
  2750. assert(ImportedBy && "top-level import should be verified");
  2751. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2752. Diag(diag::err_imported_module_modmap_changed)
  2753. << F.ModuleName << ImportedBy->FileName
  2754. << ModMap->getName() << F.ModuleMapPath;
  2755. return OutOfDate;
  2756. }
  2757. llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
  2758. for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
  2759. // FIXME: we should use input files rather than storing names.
  2760. std::string Filename = ReadPath(F, Record, Idx);
  2761. const FileEntry *F =
  2762. FileMgr.getFile(Filename, false, false);
  2763. if (F == nullptr) {
  2764. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2765. Error("could not find file '" + Filename +"' referenced by AST file");
  2766. return OutOfDate;
  2767. }
  2768. AdditionalStoredMaps.insert(F);
  2769. }
  2770. // Check any additional module map files (e.g. module.private.modulemap)
  2771. // that are not in the pcm.
  2772. if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
  2773. for (const FileEntry *ModMap : *AdditionalModuleMaps) {
  2774. // Remove files that match
  2775. // Note: SmallPtrSet::erase is really remove
  2776. if (!AdditionalStoredMaps.erase(ModMap)) {
  2777. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2778. Diag(diag::err_module_different_modmap)
  2779. << F.ModuleName << /*new*/0 << ModMap->getName();
  2780. return OutOfDate;
  2781. }
  2782. }
  2783. }
  2784. // Check any additional module map files that are in the pcm, but not
  2785. // found in header search. Cases that match are already removed.
  2786. for (const FileEntry *ModMap : AdditionalStoredMaps) {
  2787. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2788. Diag(diag::err_module_different_modmap)
  2789. << F.ModuleName << /*not new*/1 << ModMap->getName();
  2790. return OutOfDate;
  2791. }
  2792. }
  2793. if (Listener)
  2794. Listener->ReadModuleMapFile(F.ModuleMapPath);
  2795. return Success;
  2796. }
  2797. /// \brief Move the given method to the back of the global list of methods.
  2798. static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
  2799. // Find the entry for this selector in the method pool.
  2800. Sema::GlobalMethodPool::iterator Known
  2801. = S.MethodPool.find(Method->getSelector());
  2802. if (Known == S.MethodPool.end())
  2803. return;
  2804. // Retrieve the appropriate method list.
  2805. ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
  2806. : Known->second.second;
  2807. bool Found = false;
  2808. for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
  2809. if (!Found) {
  2810. if (List->getMethod() == Method) {
  2811. Found = true;
  2812. } else {
  2813. // Keep searching.
  2814. continue;
  2815. }
  2816. }
  2817. if (List->getNext())
  2818. List->setMethod(List->getNext()->getMethod());
  2819. else
  2820. List->setMethod(Method);
  2821. }
  2822. }
  2823. void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
  2824. assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
  2825. for (Decl *D : Names) {
  2826. bool wasHidden = D->Hidden;
  2827. D->Hidden = false;
  2828. if (wasHidden && SemaObj) {
  2829. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
  2830. moveMethodToBackOfGlobalList(*SemaObj, Method);
  2831. }
  2832. }
  2833. }
  2834. }
  2835. void ASTReader::makeModuleVisible(Module *Mod,
  2836. Module::NameVisibilityKind NameVisibility,
  2837. SourceLocation ImportLoc) {
  2838. llvm::SmallPtrSet<Module *, 4> Visited;
  2839. SmallVector<Module *, 4> Stack;
  2840. Stack.push_back(Mod);
  2841. while (!Stack.empty()) {
  2842. Mod = Stack.pop_back_val();
  2843. if (NameVisibility <= Mod->NameVisibility) {
  2844. // This module already has this level of visibility (or greater), so
  2845. // there is nothing more to do.
  2846. continue;
  2847. }
  2848. if (!Mod->isAvailable()) {
  2849. // Modules that aren't available cannot be made visible.
  2850. continue;
  2851. }
  2852. // Update the module's name visibility.
  2853. Mod->NameVisibility = NameVisibility;
  2854. // If we've already deserialized any names from this module,
  2855. // mark them as visible.
  2856. HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
  2857. if (Hidden != HiddenNamesMap.end()) {
  2858. auto HiddenNames = std::move(*Hidden);
  2859. HiddenNamesMap.erase(Hidden);
  2860. makeNamesVisible(HiddenNames.second, HiddenNames.first);
  2861. assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
  2862. "making names visible added hidden names");
  2863. }
  2864. // Push any exported modules onto the stack to be marked as visible.
  2865. SmallVector<Module *, 16> Exports;
  2866. Mod->getExportedModules(Exports);
  2867. for (SmallVectorImpl<Module *>::iterator
  2868. I = Exports.begin(), E = Exports.end(); I != E; ++I) {
  2869. Module *Exported = *I;
  2870. if (Visited.insert(Exported).second)
  2871. Stack.push_back(Exported);
  2872. }
  2873. }
  2874. }
  2875. bool ASTReader::loadGlobalIndex() {
  2876. if (GlobalIndex)
  2877. return false;
  2878. if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
  2879. !Context.getLangOpts().Modules)
  2880. return true;
  2881. // Try to load the global index.
  2882. TriedLoadingGlobalIndex = true;
  2883. StringRef ModuleCachePath
  2884. = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
  2885. std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
  2886. = GlobalModuleIndex::readIndex(ModuleCachePath);
  2887. if (!Result.first)
  2888. return true;
  2889. GlobalIndex.reset(Result.first);
  2890. ModuleMgr.setGlobalIndex(GlobalIndex.get());
  2891. return false;
  2892. }
  2893. bool ASTReader::isGlobalIndexUnavailable() const {
  2894. return Context.getLangOpts().Modules && UseGlobalIndex &&
  2895. !hasGlobalIndex() && TriedLoadingGlobalIndex;
  2896. }
  2897. static void updateModuleTimestamp(ModuleFile &MF) {
  2898. // Overwrite the timestamp file contents so that file's mtime changes.
  2899. std::string TimestampFilename = MF.getTimestampFilename();
  2900. std::error_code EC;
  2901. llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
  2902. if (EC)
  2903. return;
  2904. OS << "Timestamp file\n";
  2905. }
  2906. ASTReader::ASTReadResult ASTReader::ReadAST(const std::string &FileName,
  2907. ModuleKind Type,
  2908. SourceLocation ImportLoc,
  2909. unsigned ClientLoadCapabilities) {
  2910. llvm::SaveAndRestore<SourceLocation>
  2911. SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
  2912. // Defer any pending actions until we get to the end of reading the AST file.
  2913. Deserializing AnASTFile(this);
  2914. // Bump the generation number.
  2915. unsigned PreviousGeneration = incrementGeneration(Context);
  2916. unsigned NumModules = ModuleMgr.size();
  2917. SmallVector<ImportedModule, 4> Loaded;
  2918. switch(ASTReadResult ReadResult = ReadASTCore(FileName, Type, ImportLoc,
  2919. /*ImportedBy=*/nullptr, Loaded,
  2920. 0, 0, 0,
  2921. ClientLoadCapabilities)) {
  2922. case Failure:
  2923. case Missing:
  2924. case OutOfDate:
  2925. case VersionMismatch:
  2926. case ConfigurationMismatch:
  2927. case HadErrors: {
  2928. llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
  2929. for (const ImportedModule &IM : Loaded)
  2930. LoadedSet.insert(IM.Mod);
  2931. ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, ModuleMgr.end(),
  2932. LoadedSet,
  2933. Context.getLangOpts().Modules
  2934. ? &PP.getHeaderSearchInfo().getModuleMap()
  2935. : nullptr);
  2936. // If we find that any modules are unusable, the global index is going
  2937. // to be out-of-date. Just remove it.
  2938. GlobalIndex.reset();
  2939. ModuleMgr.setGlobalIndex(nullptr);
  2940. return ReadResult;
  2941. }
  2942. case Success:
  2943. break;
  2944. }
  2945. // Here comes stuff that we only do once the entire chain is loaded.
  2946. // Load the AST blocks of all of the modules that we loaded.
  2947. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
  2948. MEnd = Loaded.end();
  2949. M != MEnd; ++M) {
  2950. ModuleFile &F = *M->Mod;
  2951. // Read the AST block.
  2952. if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
  2953. return Result;
  2954. // Once read, set the ModuleFile bit base offset and update the size in
  2955. // bits of all files we've seen.
  2956. F.GlobalBitOffset = TotalModulesSizeInBits;
  2957. TotalModulesSizeInBits += F.SizeInBits;
  2958. GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
  2959. // Preload SLocEntries.
  2960. for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
  2961. int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
  2962. // Load it through the SourceManager and don't call ReadSLocEntry()
  2963. // directly because the entry may have already been loaded in which case
  2964. // calling ReadSLocEntry() directly would trigger an assertion in
  2965. // SourceManager.
  2966. SourceMgr.getLoadedSLocEntryByID(Index);
  2967. }
  2968. }
  2969. // Setup the import locations and notify the module manager that we've
  2970. // committed to these module files.
  2971. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
  2972. MEnd = Loaded.end();
  2973. M != MEnd; ++M) {
  2974. ModuleFile &F = *M->Mod;
  2975. ModuleMgr.moduleFileAccepted(&F);
  2976. // Set the import location.
  2977. F.DirectImportLoc = ImportLoc;
  2978. if (!M->ImportedBy)
  2979. F.ImportLoc = M->ImportLoc;
  2980. else
  2981. F.ImportLoc = ReadSourceLocation(*M->ImportedBy,
  2982. M->ImportLoc.getRawEncoding());
  2983. }
  2984. // Mark all of the identifiers in the identifier table as being out of date,
  2985. // so that various accessors know to check the loaded modules when the
  2986. // identifier is used.
  2987. for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
  2988. IdEnd = PP.getIdentifierTable().end();
  2989. Id != IdEnd; ++Id)
  2990. Id->second->setOutOfDate(true);
  2991. // Resolve any unresolved module exports.
  2992. for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
  2993. UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
  2994. SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
  2995. Module *ResolvedMod = getSubmodule(GlobalID);
  2996. switch (Unresolved.Kind) {
  2997. case UnresolvedModuleRef::Conflict:
  2998. if (ResolvedMod) {
  2999. Module::Conflict Conflict;
  3000. Conflict.Other = ResolvedMod;
  3001. Conflict.Message = Unresolved.String.str();
  3002. Unresolved.Mod->Conflicts.push_back(Conflict);
  3003. }
  3004. continue;
  3005. case UnresolvedModuleRef::Import:
  3006. if (ResolvedMod)
  3007. Unresolved.Mod->Imports.insert(ResolvedMod);
  3008. continue;
  3009. case UnresolvedModuleRef::Export:
  3010. if (ResolvedMod || Unresolved.IsWildcard)
  3011. Unresolved.Mod->Exports.push_back(
  3012. Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
  3013. continue;
  3014. }
  3015. }
  3016. UnresolvedModuleRefs.clear();
  3017. // FIXME: How do we load the 'use'd modules? They may not be submodules.
  3018. // Might be unnecessary as use declarations are only used to build the
  3019. // module itself.
  3020. InitializeContext();
  3021. if (SemaObj)
  3022. UpdateSema();
  3023. if (DeserializationListener)
  3024. DeserializationListener->ReaderInitialized(this);
  3025. ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
  3026. if (!PrimaryModule.OriginalSourceFileID.isInvalid()) {
  3027. PrimaryModule.OriginalSourceFileID
  3028. = FileID::get(PrimaryModule.SLocEntryBaseID
  3029. + PrimaryModule.OriginalSourceFileID.getOpaqueValue() - 1);
  3030. // If this AST file is a precompiled preamble, then set the
  3031. // preamble file ID of the source manager to the file source file
  3032. // from which the preamble was built.
  3033. if (Type == MK_Preamble) {
  3034. SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
  3035. } else if (Type == MK_MainFile) {
  3036. SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
  3037. }
  3038. }
  3039. // For any Objective-C class definitions we have already loaded, make sure
  3040. // that we load any additional categories.
  3041. for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
  3042. loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
  3043. ObjCClassesLoaded[I],
  3044. PreviousGeneration);
  3045. }
  3046. if (PP.getHeaderSearchInfo()
  3047. .getHeaderSearchOpts()
  3048. .ModulesValidateOncePerBuildSession) {
  3049. // Now we are certain that the module and all modules it depends on are
  3050. // up to date. Create or update timestamp files for modules that are
  3051. // located in the module cache (not for PCH files that could be anywhere
  3052. // in the filesystem).
  3053. for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
  3054. ImportedModule &M = Loaded[I];
  3055. if (M.Mod->Kind == MK_ImplicitModule) {
  3056. updateModuleTimestamp(*M.Mod);
  3057. }
  3058. }
  3059. }
  3060. return Success;
  3061. }
  3062. static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile);
  3063. /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
  3064. static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
  3065. return Stream.Read(8) == 'C' &&
  3066. Stream.Read(8) == 'P' &&
  3067. Stream.Read(8) == 'C' &&
  3068. Stream.Read(8) == 'H';
  3069. }
  3070. ASTReader::ASTReadResult
  3071. ASTReader::ReadASTCore(StringRef FileName,
  3072. ModuleKind Type,
  3073. SourceLocation ImportLoc,
  3074. ModuleFile *ImportedBy,
  3075. SmallVectorImpl<ImportedModule> &Loaded,
  3076. off_t ExpectedSize, time_t ExpectedModTime,
  3077. ASTFileSignature ExpectedSignature,
  3078. unsigned ClientLoadCapabilities) {
  3079. ModuleFile *M;
  3080. std::string ErrorStr;
  3081. ModuleManager::AddModuleResult AddResult
  3082. = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
  3083. getGeneration(), ExpectedSize, ExpectedModTime,
  3084. ExpectedSignature, readASTFileSignature,
  3085. M, ErrorStr);
  3086. switch (AddResult) {
  3087. case ModuleManager::AlreadyLoaded:
  3088. return Success;
  3089. case ModuleManager::NewlyLoaded:
  3090. // Load module file below.
  3091. break;
  3092. case ModuleManager::Missing:
  3093. // The module file was missing; if the client can handle that, return
  3094. // it.
  3095. if (ClientLoadCapabilities & ARR_Missing)
  3096. return Missing;
  3097. // Otherwise, return an error.
  3098. {
  3099. std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
  3100. + ErrorStr;
  3101. Error(Msg);
  3102. }
  3103. return Failure;
  3104. case ModuleManager::OutOfDate:
  3105. // We couldn't load the module file because it is out-of-date. If the
  3106. // client can handle out-of-date, return it.
  3107. if (ClientLoadCapabilities & ARR_OutOfDate)
  3108. return OutOfDate;
  3109. // Otherwise, return an error.
  3110. {
  3111. std::string Msg = "Unable to load module \"" + FileName.str() + "\": "
  3112. + ErrorStr;
  3113. Error(Msg);
  3114. }
  3115. return Failure;
  3116. }
  3117. assert(M && "Missing module file");
  3118. // FIXME: This seems rather a hack. Should CurrentDir be part of the
  3119. // module?
  3120. if (FileName != "-") {
  3121. CurrentDir = llvm::sys::path::parent_path(FileName);
  3122. if (CurrentDir.empty()) CurrentDir = ".";
  3123. }
  3124. ModuleFile &F = *M;
  3125. BitstreamCursor &Stream = F.Stream;
  3126. PCHContainerRdr.ExtractPCH(F.Buffer->getMemBufferRef(), F.StreamFile);
  3127. Stream.init(&F.StreamFile);
  3128. F.SizeInBits = F.Buffer->getBufferSize() * 8;
  3129. // Sniff for the signature.
  3130. if (!startsWithASTFileMagic(Stream)) {
  3131. Diag(diag::err_not_a_pch_file) << FileName;
  3132. return Failure;
  3133. }
  3134. // This is used for compatibility with older PCH formats.
  3135. bool HaveReadControlBlock = false;
  3136. while (1) {
  3137. llvm::BitstreamEntry Entry = Stream.advance();
  3138. switch (Entry.Kind) {
  3139. case llvm::BitstreamEntry::Error:
  3140. case llvm::BitstreamEntry::EndBlock:
  3141. case llvm::BitstreamEntry::Record:
  3142. Error("invalid record at top-level of AST file");
  3143. return Failure;
  3144. case llvm::BitstreamEntry::SubBlock:
  3145. break;
  3146. }
  3147. // We only know the control subblock ID.
  3148. switch (Entry.ID) {
  3149. case llvm::bitc::BLOCKINFO_BLOCK_ID:
  3150. if (Stream.ReadBlockInfoBlock()) {
  3151. Error("malformed BlockInfoBlock in AST file");
  3152. return Failure;
  3153. }
  3154. break;
  3155. case CONTROL_BLOCK_ID:
  3156. HaveReadControlBlock = true;
  3157. switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
  3158. case Success:
  3159. break;
  3160. case Failure: return Failure;
  3161. case Missing: return Missing;
  3162. case OutOfDate: return OutOfDate;
  3163. case VersionMismatch: return VersionMismatch;
  3164. case ConfigurationMismatch: return ConfigurationMismatch;
  3165. case HadErrors: return HadErrors;
  3166. }
  3167. break;
  3168. case AST_BLOCK_ID:
  3169. if (!HaveReadControlBlock) {
  3170. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  3171. Diag(diag::err_pch_version_too_old);
  3172. return VersionMismatch;
  3173. }
  3174. // Record that we've loaded this module.
  3175. Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
  3176. return Success;
  3177. default:
  3178. if (Stream.SkipBlock()) {
  3179. Error("malformed block record in AST file");
  3180. return Failure;
  3181. }
  3182. break;
  3183. }
  3184. }
  3185. return Success;
  3186. }
  3187. void ASTReader::InitializeContext() {
  3188. // If there's a listener, notify them that we "read" the translation unit.
  3189. if (DeserializationListener)
  3190. DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
  3191. Context.getTranslationUnitDecl());
  3192. // FIXME: Find a better way to deal with collisions between these
  3193. // built-in types. Right now, we just ignore the problem.
  3194. // Load the special types.
  3195. if (SpecialTypes.size() >= NumSpecialTypeIDs) {
  3196. if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
  3197. if (!Context.CFConstantStringTypeDecl)
  3198. Context.setCFConstantStringType(GetType(String));
  3199. }
  3200. if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
  3201. QualType FileType = GetType(File);
  3202. if (FileType.isNull()) {
  3203. Error("FILE type is NULL");
  3204. return;
  3205. }
  3206. if (!Context.FILEDecl) {
  3207. if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
  3208. Context.setFILEDecl(Typedef->getDecl());
  3209. else {
  3210. const TagType *Tag = FileType->getAs<TagType>();
  3211. if (!Tag) {
  3212. Error("Invalid FILE type in AST file");
  3213. return;
  3214. }
  3215. Context.setFILEDecl(Tag->getDecl());
  3216. }
  3217. }
  3218. }
  3219. if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
  3220. QualType Jmp_bufType = GetType(Jmp_buf);
  3221. if (Jmp_bufType.isNull()) {
  3222. Error("jmp_buf type is NULL");
  3223. return;
  3224. }
  3225. if (!Context.jmp_bufDecl) {
  3226. if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
  3227. Context.setjmp_bufDecl(Typedef->getDecl());
  3228. else {
  3229. const TagType *Tag = Jmp_bufType->getAs<TagType>();
  3230. if (!Tag) {
  3231. Error("Invalid jmp_buf type in AST file");
  3232. return;
  3233. }
  3234. Context.setjmp_bufDecl(Tag->getDecl());
  3235. }
  3236. }
  3237. }
  3238. if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
  3239. QualType Sigjmp_bufType = GetType(Sigjmp_buf);
  3240. if (Sigjmp_bufType.isNull()) {
  3241. Error("sigjmp_buf type is NULL");
  3242. return;
  3243. }
  3244. if (!Context.sigjmp_bufDecl) {
  3245. if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
  3246. Context.setsigjmp_bufDecl(Typedef->getDecl());
  3247. else {
  3248. const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
  3249. assert(Tag && "Invalid sigjmp_buf type in AST file");
  3250. Context.setsigjmp_bufDecl(Tag->getDecl());
  3251. }
  3252. }
  3253. }
  3254. if (unsigned ObjCIdRedef
  3255. = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
  3256. if (Context.ObjCIdRedefinitionType.isNull())
  3257. Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
  3258. }
  3259. if (unsigned ObjCClassRedef
  3260. = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
  3261. if (Context.ObjCClassRedefinitionType.isNull())
  3262. Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
  3263. }
  3264. if (unsigned ObjCSelRedef
  3265. = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
  3266. if (Context.ObjCSelRedefinitionType.isNull())
  3267. Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
  3268. }
  3269. if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
  3270. QualType Ucontext_tType = GetType(Ucontext_t);
  3271. if (Ucontext_tType.isNull()) {
  3272. Error("ucontext_t type is NULL");
  3273. return;
  3274. }
  3275. if (!Context.ucontext_tDecl) {
  3276. if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
  3277. Context.setucontext_tDecl(Typedef->getDecl());
  3278. else {
  3279. const TagType *Tag = Ucontext_tType->getAs<TagType>();
  3280. assert(Tag && "Invalid ucontext_t type in AST file");
  3281. Context.setucontext_tDecl(Tag->getDecl());
  3282. }
  3283. }
  3284. }
  3285. }
  3286. ReadPragmaDiagnosticMappings(Context.getDiagnostics());
  3287. // If there were any CUDA special declarations, deserialize them.
  3288. if (!CUDASpecialDeclRefs.empty()) {
  3289. assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
  3290. Context.setcudaConfigureCallDecl(
  3291. cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
  3292. }
  3293. // Re-export any modules that were imported by a non-module AST file.
  3294. // FIXME: This does not make macro-only imports visible again.
  3295. for (auto &Import : ImportedModules) {
  3296. if (Module *Imported = getSubmodule(Import.ID)) {
  3297. makeModuleVisible(Imported, Module::AllVisible,
  3298. /*ImportLoc=*/Import.ImportLoc);
  3299. PP.makeModuleVisible(Imported, Import.ImportLoc);
  3300. }
  3301. }
  3302. ImportedModules.clear();
  3303. }
  3304. void ASTReader::finalizeForWriting() {
  3305. // Nothing to do for now.
  3306. }
  3307. /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
  3308. /// cursor into the start of the given block ID, returning false on success and
  3309. /// true on failure.
  3310. static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
  3311. while (1) {
  3312. llvm::BitstreamEntry Entry = Cursor.advance();
  3313. switch (Entry.Kind) {
  3314. case llvm::BitstreamEntry::Error:
  3315. case llvm::BitstreamEntry::EndBlock:
  3316. return true;
  3317. case llvm::BitstreamEntry::Record:
  3318. // Ignore top-level records.
  3319. Cursor.skipRecord(Entry.ID);
  3320. break;
  3321. case llvm::BitstreamEntry::SubBlock:
  3322. if (Entry.ID == BlockID) {
  3323. if (Cursor.EnterSubBlock(BlockID))
  3324. return true;
  3325. // Found it!
  3326. return false;
  3327. }
  3328. if (Cursor.SkipBlock())
  3329. return true;
  3330. }
  3331. }
  3332. }
  3333. /// \brief Reads and return the signature record from \p StreamFile's control
  3334. /// block, or else returns 0.
  3335. static ASTFileSignature readASTFileSignature(llvm::BitstreamReader &StreamFile){
  3336. BitstreamCursor Stream(StreamFile);
  3337. if (!startsWithASTFileMagic(Stream))
  3338. return 0;
  3339. // Scan for the CONTROL_BLOCK_ID block.
  3340. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
  3341. return 0;
  3342. // Scan for SIGNATURE inside the control block.
  3343. ASTReader::RecordData Record;
  3344. while (1) {
  3345. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3346. if (Entry.Kind == llvm::BitstreamEntry::EndBlock ||
  3347. Entry.Kind != llvm::BitstreamEntry::Record)
  3348. return 0;
  3349. Record.clear();
  3350. StringRef Blob;
  3351. if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
  3352. return Record[0];
  3353. }
  3354. }
  3355. /// \brief Retrieve the name of the original source file name
  3356. /// directly from the AST file, without actually loading the AST
  3357. /// file.
  3358. std::string ASTReader::getOriginalSourceFile(
  3359. const std::string &ASTFileName, FileManager &FileMgr,
  3360. const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
  3361. // Open the AST file.
  3362. auto Buffer = FileMgr.getBufferForFile(ASTFileName);
  3363. if (!Buffer) {
  3364. Diags.Report(diag::err_fe_unable_to_read_pch_file)
  3365. << ASTFileName << Buffer.getError().message();
  3366. return std::string();
  3367. }
  3368. // Initialize the stream
  3369. llvm::BitstreamReader StreamFile;
  3370. PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
  3371. BitstreamCursor Stream(StreamFile);
  3372. // Sniff for the signature.
  3373. if (!startsWithASTFileMagic(Stream)) {
  3374. Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
  3375. return std::string();
  3376. }
  3377. // Scan for the CONTROL_BLOCK_ID block.
  3378. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
  3379. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  3380. return std::string();
  3381. }
  3382. // Scan for ORIGINAL_FILE inside the control block.
  3383. RecordData Record;
  3384. while (1) {
  3385. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3386. if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
  3387. return std::string();
  3388. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  3389. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  3390. return std::string();
  3391. }
  3392. Record.clear();
  3393. StringRef Blob;
  3394. if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
  3395. return Blob.str();
  3396. }
  3397. }
  3398. namespace {
  3399. class SimplePCHValidator : public ASTReaderListener {
  3400. const LangOptions &ExistingLangOpts;
  3401. const TargetOptions &ExistingTargetOpts;
  3402. const PreprocessorOptions &ExistingPPOpts;
  3403. std::string ExistingModuleCachePath;
  3404. FileManager &FileMgr;
  3405. public:
  3406. SimplePCHValidator(const LangOptions &ExistingLangOpts,
  3407. const TargetOptions &ExistingTargetOpts,
  3408. const PreprocessorOptions &ExistingPPOpts,
  3409. StringRef ExistingModuleCachePath,
  3410. FileManager &FileMgr)
  3411. : ExistingLangOpts(ExistingLangOpts),
  3412. ExistingTargetOpts(ExistingTargetOpts),
  3413. ExistingPPOpts(ExistingPPOpts),
  3414. ExistingModuleCachePath(ExistingModuleCachePath),
  3415. FileMgr(FileMgr)
  3416. {
  3417. }
  3418. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  3419. bool AllowCompatibleDifferences) override {
  3420. return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
  3421. AllowCompatibleDifferences);
  3422. }
  3423. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  3424. bool AllowCompatibleDifferences) override {
  3425. return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
  3426. AllowCompatibleDifferences);
  3427. }
  3428. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  3429. StringRef SpecificModuleCachePath,
  3430. bool Complain) override {
  3431. return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  3432. ExistingModuleCachePath,
  3433. nullptr, ExistingLangOpts);
  3434. }
  3435. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  3436. bool Complain,
  3437. std::string &SuggestedPredefines) override {
  3438. return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
  3439. SuggestedPredefines, ExistingLangOpts);
  3440. }
  3441. };
  3442. }
  3443. bool ASTReader::readASTFileControlBlock(
  3444. StringRef Filename, FileManager &FileMgr,
  3445. const PCHContainerReader &PCHContainerRdr,
  3446. ASTReaderListener &Listener) {
  3447. // Open the AST file.
  3448. // FIXME: This allows use of the VFS; we do not allow use of the
  3449. // VFS when actually loading a module.
  3450. auto Buffer = FileMgr.getBufferForFile(Filename);
  3451. if (!Buffer) {
  3452. return true;
  3453. }
  3454. // Initialize the stream
  3455. llvm::BitstreamReader StreamFile;
  3456. PCHContainerRdr.ExtractPCH((*Buffer)->getMemBufferRef(), StreamFile);
  3457. BitstreamCursor Stream(StreamFile);
  3458. // Sniff for the signature.
  3459. if (!startsWithASTFileMagic(Stream))
  3460. return true;
  3461. // Scan for the CONTROL_BLOCK_ID block.
  3462. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
  3463. return true;
  3464. bool NeedsInputFiles = Listener.needsInputFileVisitation();
  3465. bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
  3466. bool NeedsImports = Listener.needsImportVisitation();
  3467. BitstreamCursor InputFilesCursor;
  3468. if (NeedsInputFiles) {
  3469. InputFilesCursor = Stream;
  3470. if (SkipCursorToBlock(InputFilesCursor, INPUT_FILES_BLOCK_ID))
  3471. return true;
  3472. // Read the abbreviations
  3473. while (true) {
  3474. uint64_t Offset = InputFilesCursor.GetCurrentBitNo();
  3475. unsigned Code = InputFilesCursor.ReadCode();
  3476. // We expect all abbrevs to be at the start of the block.
  3477. if (Code != llvm::bitc::DEFINE_ABBREV) {
  3478. InputFilesCursor.JumpToBit(Offset);
  3479. break;
  3480. }
  3481. InputFilesCursor.ReadAbbrevRecord();
  3482. }
  3483. }
  3484. // Scan for ORIGINAL_FILE inside the control block.
  3485. RecordData Record;
  3486. std::string ModuleDir;
  3487. while (1) {
  3488. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3489. if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
  3490. return false;
  3491. if (Entry.Kind != llvm::BitstreamEntry::Record)
  3492. return true;
  3493. Record.clear();
  3494. StringRef Blob;
  3495. unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
  3496. switch ((ControlRecordTypes)RecCode) {
  3497. case METADATA: {
  3498. if (Record[0] != VERSION_MAJOR)
  3499. return true;
  3500. if (Listener.ReadFullVersionInformation(Blob))
  3501. return true;
  3502. break;
  3503. }
  3504. case MODULE_NAME:
  3505. Listener.ReadModuleName(Blob);
  3506. break;
  3507. case MODULE_DIRECTORY:
  3508. ModuleDir = Blob;
  3509. break;
  3510. case MODULE_MAP_FILE: {
  3511. unsigned Idx = 0;
  3512. auto Path = ReadString(Record, Idx);
  3513. ResolveImportedPath(Path, ModuleDir);
  3514. Listener.ReadModuleMapFile(Path);
  3515. break;
  3516. }
  3517. case LANGUAGE_OPTIONS:
  3518. if (ParseLanguageOptions(Record, false, Listener,
  3519. /*AllowCompatibleConfigurationMismatch*/false))
  3520. return true;
  3521. break;
  3522. case TARGET_OPTIONS:
  3523. if (ParseTargetOptions(Record, false, Listener,
  3524. /*AllowCompatibleConfigurationMismatch*/ false))
  3525. return true;
  3526. break;
  3527. case DIAGNOSTIC_OPTIONS:
  3528. if (ParseDiagnosticOptions(Record, false, Listener))
  3529. return true;
  3530. break;
  3531. case FILE_SYSTEM_OPTIONS:
  3532. if (ParseFileSystemOptions(Record, false, Listener))
  3533. return true;
  3534. break;
  3535. case HEADER_SEARCH_OPTIONS:
  3536. if (ParseHeaderSearchOptions(Record, false, Listener))
  3537. return true;
  3538. break;
  3539. case PREPROCESSOR_OPTIONS: {
  3540. std::string IgnoredSuggestedPredefines;
  3541. if (ParsePreprocessorOptions(Record, false, Listener,
  3542. IgnoredSuggestedPredefines))
  3543. return true;
  3544. break;
  3545. }
  3546. case INPUT_FILE_OFFSETS: {
  3547. if (!NeedsInputFiles)
  3548. break;
  3549. unsigned NumInputFiles = Record[0];
  3550. unsigned NumUserFiles = Record[1];
  3551. const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
  3552. for (unsigned I = 0; I != NumInputFiles; ++I) {
  3553. // Go find this input file.
  3554. bool isSystemFile = I >= NumUserFiles;
  3555. if (isSystemFile && !NeedsSystemInputFiles)
  3556. break; // the rest are system input files
  3557. BitstreamCursor &Cursor = InputFilesCursor;
  3558. SavedStreamPosition SavedPosition(Cursor);
  3559. Cursor.JumpToBit(InputFileOffs[I]);
  3560. unsigned Code = Cursor.ReadCode();
  3561. RecordData Record;
  3562. StringRef Blob;
  3563. bool shouldContinue = false;
  3564. switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
  3565. case INPUT_FILE:
  3566. bool Overridden = static_cast<bool>(Record[3]);
  3567. std::string Filename = Blob;
  3568. ResolveImportedPath(Filename, ModuleDir);
  3569. shouldContinue =
  3570. Listener.visitInputFile(Filename, isSystemFile, Overridden);
  3571. break;
  3572. }
  3573. if (!shouldContinue)
  3574. break;
  3575. }
  3576. break;
  3577. }
  3578. case IMPORTS: {
  3579. if (!NeedsImports)
  3580. break;
  3581. unsigned Idx = 0, N = Record.size();
  3582. while (Idx < N) {
  3583. // Read information about the AST file.
  3584. Idx += 5; // ImportLoc, Size, ModTime, Signature
  3585. std::string Filename = ReadString(Record, Idx);
  3586. ResolveImportedPath(Filename, ModuleDir);
  3587. Listener.visitImport(Filename);
  3588. }
  3589. break;
  3590. }
  3591. case KNOWN_MODULE_FILES: {
  3592. // Known-but-not-technically-used module files are treated as imports.
  3593. if (!NeedsImports)
  3594. break;
  3595. unsigned Idx = 0, N = Record.size();
  3596. while (Idx < N) {
  3597. std::string Filename = ReadString(Record, Idx);
  3598. ResolveImportedPath(Filename, ModuleDir);
  3599. Listener.visitImport(Filename);
  3600. }
  3601. break;
  3602. }
  3603. default:
  3604. // No other validation to perform.
  3605. break;
  3606. }
  3607. }
  3608. }
  3609. bool ASTReader::isAcceptableASTFile(
  3610. StringRef Filename, FileManager &FileMgr,
  3611. const PCHContainerReader &PCHContainerRdr, const LangOptions &LangOpts,
  3612. const TargetOptions &TargetOpts, const PreprocessorOptions &PPOpts,
  3613. std::string ExistingModuleCachePath) {
  3614. SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
  3615. ExistingModuleCachePath, FileMgr);
  3616. return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
  3617. validator);
  3618. }
  3619. ASTReader::ASTReadResult
  3620. ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
  3621. // Enter the submodule block.
  3622. if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
  3623. Error("malformed submodule block record in AST file");
  3624. return Failure;
  3625. }
  3626. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  3627. bool First = true;
  3628. Module *CurrentModule = nullptr;
  3629. RecordData Record;
  3630. while (true) {
  3631. llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
  3632. switch (Entry.Kind) {
  3633. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  3634. case llvm::BitstreamEntry::Error:
  3635. Error("malformed block record in AST file");
  3636. return Failure;
  3637. case llvm::BitstreamEntry::EndBlock:
  3638. return Success;
  3639. case llvm::BitstreamEntry::Record:
  3640. // The interesting case.
  3641. break;
  3642. }
  3643. // Read a record.
  3644. StringRef Blob;
  3645. Record.clear();
  3646. auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
  3647. if ((Kind == SUBMODULE_METADATA) != First) {
  3648. Error("submodule metadata record should be at beginning of block");
  3649. return Failure;
  3650. }
  3651. First = false;
  3652. // Submodule information is only valid if we have a current module.
  3653. // FIXME: Should we error on these cases?
  3654. if (!CurrentModule && Kind != SUBMODULE_METADATA &&
  3655. Kind != SUBMODULE_DEFINITION)
  3656. continue;
  3657. switch (Kind) {
  3658. default: // Default behavior: ignore.
  3659. break;
  3660. case SUBMODULE_DEFINITION: {
  3661. if (Record.size() < 8) {
  3662. Error("malformed module definition");
  3663. return Failure;
  3664. }
  3665. StringRef Name = Blob;
  3666. unsigned Idx = 0;
  3667. SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
  3668. SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
  3669. bool IsFramework = Record[Idx++];
  3670. bool IsExplicit = Record[Idx++];
  3671. bool IsSystem = Record[Idx++];
  3672. bool IsExternC = Record[Idx++];
  3673. bool InferSubmodules = Record[Idx++];
  3674. bool InferExplicitSubmodules = Record[Idx++];
  3675. bool InferExportWildcard = Record[Idx++];
  3676. bool ConfigMacrosExhaustive = Record[Idx++];
  3677. Module *ParentModule = nullptr;
  3678. if (Parent)
  3679. ParentModule = getSubmodule(Parent);
  3680. // Retrieve this (sub)module from the module map, creating it if
  3681. // necessary.
  3682. CurrentModule = ModMap.findOrCreateModule(Name, ParentModule, IsFramework,
  3683. IsExplicit).first;
  3684. // FIXME: set the definition loc for CurrentModule, or call
  3685. // ModMap.setInferredModuleAllowedBy()
  3686. SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
  3687. if (GlobalIndex >= SubmodulesLoaded.size() ||
  3688. SubmodulesLoaded[GlobalIndex]) {
  3689. Error("too many submodules");
  3690. return Failure;
  3691. }
  3692. if (!ParentModule) {
  3693. if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
  3694. if (CurFile != F.File) {
  3695. if (!Diags.isDiagnosticInFlight()) {
  3696. Diag(diag::err_module_file_conflict)
  3697. << CurrentModule->getTopLevelModuleName()
  3698. << CurFile->getName()
  3699. << F.File->getName();
  3700. }
  3701. return Failure;
  3702. }
  3703. }
  3704. CurrentModule->setASTFile(F.File);
  3705. }
  3706. CurrentModule->Signature = F.Signature;
  3707. CurrentModule->IsFromModuleFile = true;
  3708. CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
  3709. CurrentModule->IsExternC = IsExternC;
  3710. CurrentModule->InferSubmodules = InferSubmodules;
  3711. CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
  3712. CurrentModule->InferExportWildcard = InferExportWildcard;
  3713. CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
  3714. if (DeserializationListener)
  3715. DeserializationListener->ModuleRead(GlobalID, CurrentModule);
  3716. SubmodulesLoaded[GlobalIndex] = CurrentModule;
  3717. // Clear out data that will be replaced by what is the module file.
  3718. CurrentModule->LinkLibraries.clear();
  3719. CurrentModule->ConfigMacros.clear();
  3720. CurrentModule->UnresolvedConflicts.clear();
  3721. CurrentModule->Conflicts.clear();
  3722. break;
  3723. }
  3724. case SUBMODULE_UMBRELLA_HEADER: {
  3725. std::string Filename = Blob;
  3726. ResolveImportedPath(F, Filename);
  3727. if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
  3728. if (!CurrentModule->getUmbrellaHeader())
  3729. ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
  3730. else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
  3731. // This can be a spurious difference caused by changing the VFS to
  3732. // point to a different copy of the file, and it is too late to
  3733. // to rebuild safely.
  3734. // FIXME: If we wrote the virtual paths instead of the 'real' paths,
  3735. // after input file validation only real problems would remain and we
  3736. // could just error. For now, assume it's okay.
  3737. break;
  3738. }
  3739. }
  3740. break;
  3741. }
  3742. case SUBMODULE_HEADER:
  3743. case SUBMODULE_EXCLUDED_HEADER:
  3744. case SUBMODULE_PRIVATE_HEADER:
  3745. // We lazily associate headers with their modules via the HeaderInfo table.
  3746. // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
  3747. // of complete filenames or remove it entirely.
  3748. break;
  3749. case SUBMODULE_TEXTUAL_HEADER:
  3750. case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
  3751. // FIXME: Textual headers are not marked in the HeaderInfo table. Load
  3752. // them here.
  3753. break;
  3754. case SUBMODULE_TOPHEADER: {
  3755. CurrentModule->addTopHeaderFilename(Blob);
  3756. break;
  3757. }
  3758. case SUBMODULE_UMBRELLA_DIR: {
  3759. std::string Dirname = Blob;
  3760. ResolveImportedPath(F, Dirname);
  3761. if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
  3762. if (!CurrentModule->getUmbrellaDir())
  3763. ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
  3764. else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
  3765. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  3766. Error("mismatched umbrella directories in submodule");
  3767. return OutOfDate;
  3768. }
  3769. }
  3770. break;
  3771. }
  3772. case SUBMODULE_METADATA: {
  3773. F.BaseSubmoduleID = getTotalNumSubmodules();
  3774. F.LocalNumSubmodules = Record[0];
  3775. unsigned LocalBaseSubmoduleID = Record[1];
  3776. if (F.LocalNumSubmodules > 0) {
  3777. // Introduce the global -> local mapping for submodules within this
  3778. // module.
  3779. GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
  3780. // Introduce the local -> global mapping for submodules within this
  3781. // module.
  3782. F.SubmoduleRemap.insertOrReplace(
  3783. std::make_pair(LocalBaseSubmoduleID,
  3784. F.BaseSubmoduleID - LocalBaseSubmoduleID));
  3785. SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
  3786. }
  3787. break;
  3788. }
  3789. case SUBMODULE_IMPORTS: {
  3790. for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
  3791. UnresolvedModuleRef Unresolved;
  3792. Unresolved.File = &F;
  3793. Unresolved.Mod = CurrentModule;
  3794. Unresolved.ID = Record[Idx];
  3795. Unresolved.Kind = UnresolvedModuleRef::Import;
  3796. Unresolved.IsWildcard = false;
  3797. UnresolvedModuleRefs.push_back(Unresolved);
  3798. }
  3799. break;
  3800. }
  3801. case SUBMODULE_EXPORTS: {
  3802. for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
  3803. UnresolvedModuleRef Unresolved;
  3804. Unresolved.File = &F;
  3805. Unresolved.Mod = CurrentModule;
  3806. Unresolved.ID = Record[Idx];
  3807. Unresolved.Kind = UnresolvedModuleRef::Export;
  3808. Unresolved.IsWildcard = Record[Idx + 1];
  3809. UnresolvedModuleRefs.push_back(Unresolved);
  3810. }
  3811. // Once we've loaded the set of exports, there's no reason to keep
  3812. // the parsed, unresolved exports around.
  3813. CurrentModule->UnresolvedExports.clear();
  3814. break;
  3815. }
  3816. case SUBMODULE_REQUIRES: {
  3817. CurrentModule->addRequirement(Blob, Record[0], Context.getLangOpts(),
  3818. Context.getTargetInfo());
  3819. break;
  3820. }
  3821. case SUBMODULE_LINK_LIBRARY:
  3822. CurrentModule->LinkLibraries.push_back(
  3823. Module::LinkLibrary(Blob, Record[0]));
  3824. break;
  3825. case SUBMODULE_CONFIG_MACRO:
  3826. CurrentModule->ConfigMacros.push_back(Blob.str());
  3827. break;
  3828. case SUBMODULE_CONFLICT: {
  3829. UnresolvedModuleRef Unresolved;
  3830. Unresolved.File = &F;
  3831. Unresolved.Mod = CurrentModule;
  3832. Unresolved.ID = Record[0];
  3833. Unresolved.Kind = UnresolvedModuleRef::Conflict;
  3834. Unresolved.IsWildcard = false;
  3835. Unresolved.String = Blob;
  3836. UnresolvedModuleRefs.push_back(Unresolved);
  3837. break;
  3838. }
  3839. }
  3840. }
  3841. }
  3842. /// \brief Parse the record that corresponds to a LangOptions data
  3843. /// structure.
  3844. ///
  3845. /// This routine parses the language options from the AST file and then gives
  3846. /// them to the AST listener if one is set.
  3847. ///
  3848. /// \returns true if the listener deems the file unacceptable, false otherwise.
  3849. bool ASTReader::ParseLanguageOptions(const RecordData &Record,
  3850. bool Complain,
  3851. ASTReaderListener &Listener,
  3852. bool AllowCompatibleDifferences) {
  3853. LangOptions LangOpts;
  3854. unsigned Idx = 0;
  3855. #ifdef MS_SUPPORT_VARIABLE_LANGOPTS
  3856. #define LANGOPT(Name, Bits, Default, Description) \
  3857. LangOpts.Name = Record[Idx++];
  3858. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  3859. LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
  3860. #include "clang/Basic/LangOptions.def"
  3861. #else
  3862. #define LANGOPT(Name, Bits, Default, Description) \
  3863. Idx++;
  3864. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  3865. Idx++;
  3866. #include "clang/Basic/LangOptions.fixed.def"
  3867. #endif
  3868. #define SANITIZER(NAME, ID) \
  3869. LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
  3870. #include "clang/Basic/Sanitizers.def"
  3871. for (unsigned N = Record[Idx++]; N; --N)
  3872. LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
  3873. ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
  3874. VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
  3875. LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
  3876. LangOpts.CurrentModule = ReadString(Record, Idx);
  3877. // Comment options.
  3878. for (unsigned N = Record[Idx++]; N; --N) {
  3879. LangOpts.CommentOpts.BlockCommandNames.push_back(
  3880. ReadString(Record, Idx));
  3881. }
  3882. LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
  3883. return Listener.ReadLanguageOptions(LangOpts, Complain,
  3884. AllowCompatibleDifferences);
  3885. }
  3886. bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
  3887. ASTReaderListener &Listener,
  3888. bool AllowCompatibleDifferences) {
  3889. unsigned Idx = 0;
  3890. TargetOptions TargetOpts;
  3891. TargetOpts.Triple = ReadString(Record, Idx);
  3892. TargetOpts.CPU = ReadString(Record, Idx);
  3893. TargetOpts.ABI = ReadString(Record, Idx);
  3894. for (unsigned N = Record[Idx++]; N; --N) {
  3895. TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
  3896. }
  3897. for (unsigned N = Record[Idx++]; N; --N) {
  3898. TargetOpts.Features.push_back(ReadString(Record, Idx));
  3899. }
  3900. return Listener.ReadTargetOptions(TargetOpts, Complain,
  3901. AllowCompatibleDifferences);
  3902. }
  3903. bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
  3904. ASTReaderListener &Listener) {
  3905. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
  3906. unsigned Idx = 0;
  3907. #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
  3908. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  3909. DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
  3910. #include "clang/Basic/DiagnosticOptions.def"
  3911. for (unsigned N = Record[Idx++]; N; --N)
  3912. DiagOpts->Warnings.push_back(ReadString(Record, Idx));
  3913. for (unsigned N = Record[Idx++]; N; --N)
  3914. DiagOpts->Remarks.push_back(ReadString(Record, Idx));
  3915. return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
  3916. }
  3917. bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
  3918. ASTReaderListener &Listener) {
  3919. FileSystemOptions FSOpts;
  3920. unsigned Idx = 0;
  3921. FSOpts.WorkingDir = ReadString(Record, Idx);
  3922. return Listener.ReadFileSystemOptions(FSOpts, Complain);
  3923. }
  3924. bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
  3925. bool Complain,
  3926. ASTReaderListener &Listener) {
  3927. HeaderSearchOptions HSOpts;
  3928. unsigned Idx = 0;
  3929. HSOpts.Sysroot = ReadString(Record, Idx);
  3930. // Include entries.
  3931. for (unsigned N = Record[Idx++]; N; --N) {
  3932. std::string Path = ReadString(Record, Idx);
  3933. frontend::IncludeDirGroup Group
  3934. = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
  3935. bool IsFramework = Record[Idx++];
  3936. bool IgnoreSysRoot = Record[Idx++];
  3937. HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
  3938. IgnoreSysRoot);
  3939. }
  3940. // System header prefixes.
  3941. for (unsigned N = Record[Idx++]; N; --N) {
  3942. std::string Prefix = ReadString(Record, Idx);
  3943. bool IsSystemHeader = Record[Idx++];
  3944. HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
  3945. }
  3946. HSOpts.ResourceDir = ReadString(Record, Idx);
  3947. HSOpts.ModuleCachePath = ReadString(Record, Idx);
  3948. HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
  3949. HSOpts.DisableModuleHash = Record[Idx++];
  3950. HSOpts.UseBuiltinIncludes = Record[Idx++];
  3951. HSOpts.UseStandardSystemIncludes = Record[Idx++];
  3952. HSOpts.UseStandardCXXIncludes = Record[Idx++];
  3953. HSOpts.UseLibcxx = Record[Idx++];
  3954. std::string SpecificModuleCachePath = ReadString(Record, Idx);
  3955. return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  3956. Complain);
  3957. }
  3958. bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
  3959. bool Complain,
  3960. ASTReaderListener &Listener,
  3961. std::string &SuggestedPredefines) {
  3962. PreprocessorOptions PPOpts;
  3963. unsigned Idx = 0;
  3964. // Macro definitions/undefs
  3965. for (unsigned N = Record[Idx++]; N; --N) {
  3966. std::string Macro = ReadString(Record, Idx);
  3967. bool IsUndef = Record[Idx++];
  3968. PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
  3969. }
  3970. // Includes
  3971. for (unsigned N = Record[Idx++]; N; --N) {
  3972. PPOpts.Includes.push_back(ReadString(Record, Idx));
  3973. }
  3974. // Macro Includes
  3975. for (unsigned N = Record[Idx++]; N; --N) {
  3976. PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
  3977. }
  3978. PPOpts.UsePredefines = Record[Idx++];
  3979. PPOpts.DetailedRecord = Record[Idx++];
  3980. PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
  3981. PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
  3982. PPOpts.ObjCXXARCStandardLibrary =
  3983. static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
  3984. SuggestedPredefines.clear();
  3985. return Listener.ReadPreprocessorOptions(PPOpts, Complain,
  3986. SuggestedPredefines);
  3987. }
  3988. std::pair<ModuleFile *, unsigned>
  3989. ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
  3990. GlobalPreprocessedEntityMapType::iterator
  3991. I = GlobalPreprocessedEntityMap.find(GlobalIndex);
  3992. assert(I != GlobalPreprocessedEntityMap.end() &&
  3993. "Corrupted global preprocessed entity map");
  3994. ModuleFile *M = I->second;
  3995. unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
  3996. return std::make_pair(M, LocalIndex);
  3997. }
  3998. llvm::iterator_range<PreprocessingRecord::iterator>
  3999. ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
  4000. if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
  4001. return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
  4002. Mod.NumPreprocessedEntities);
  4003. return llvm::make_range(PreprocessingRecord::iterator(),
  4004. PreprocessingRecord::iterator());
  4005. }
  4006. llvm::iterator_range<ASTReader::ModuleDeclIterator>
  4007. ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
  4008. return llvm::make_range(
  4009. ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
  4010. ModuleDeclIterator(this, &Mod,
  4011. Mod.FileSortedDecls + Mod.NumFileSortedDecls));
  4012. }
  4013. PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
  4014. PreprocessedEntityID PPID = Index+1;
  4015. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  4016. ModuleFile &M = *PPInfo.first;
  4017. unsigned LocalIndex = PPInfo.second;
  4018. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  4019. if (!PP.getPreprocessingRecord()) {
  4020. Error("no preprocessing record");
  4021. return nullptr;
  4022. }
  4023. SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
  4024. M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
  4025. llvm::BitstreamEntry Entry =
  4026. M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  4027. if (Entry.Kind != llvm::BitstreamEntry::Record)
  4028. return nullptr;
  4029. // Read the record.
  4030. SourceRange Range(ReadSourceLocation(M, PPOffs.Begin),
  4031. ReadSourceLocation(M, PPOffs.End));
  4032. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  4033. StringRef Blob;
  4034. RecordData Record;
  4035. PreprocessorDetailRecordTypes RecType =
  4036. (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
  4037. Entry.ID, Record, &Blob);
  4038. switch (RecType) {
  4039. case PPD_MACRO_EXPANSION: {
  4040. bool isBuiltin = Record[0];
  4041. IdentifierInfo *Name = nullptr;
  4042. MacroDefinitionRecord *Def = nullptr;
  4043. if (isBuiltin)
  4044. Name = getLocalIdentifier(M, Record[1]);
  4045. else {
  4046. PreprocessedEntityID GlobalID =
  4047. getGlobalPreprocessedEntityID(M, Record[1]);
  4048. Def = cast<MacroDefinitionRecord>(
  4049. PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
  4050. }
  4051. MacroExpansion *ME;
  4052. if (isBuiltin)
  4053. ME = new (PPRec) MacroExpansion(Name, Range);
  4054. else
  4055. ME = new (PPRec) MacroExpansion(Def, Range);
  4056. return ME;
  4057. }
  4058. case PPD_MACRO_DEFINITION: {
  4059. // Decode the identifier info and then check again; if the macro is
  4060. // still defined and associated with the identifier,
  4061. IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
  4062. MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
  4063. if (DeserializationListener)
  4064. DeserializationListener->MacroDefinitionRead(PPID, MD);
  4065. return MD;
  4066. }
  4067. case PPD_INCLUSION_DIRECTIVE: {
  4068. const char *FullFileNameStart = Blob.data() + Record[0];
  4069. StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
  4070. const FileEntry *File = nullptr;
  4071. if (!FullFileName.empty())
  4072. File = PP.getFileManager().getFile(FullFileName);
  4073. // FIXME: Stable encoding
  4074. InclusionDirective::InclusionKind Kind
  4075. = static_cast<InclusionDirective::InclusionKind>(Record[2]);
  4076. InclusionDirective *ID
  4077. = new (PPRec) InclusionDirective(PPRec, Kind,
  4078. StringRef(Blob.data(), Record[0]),
  4079. Record[1], Record[3],
  4080. File,
  4081. Range);
  4082. return ID;
  4083. }
  4084. }
  4085. llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
  4086. }
  4087. /// \brief \arg SLocMapI points at a chunk of a module that contains no
  4088. /// preprocessed entities or the entities it contains are not the ones we are
  4089. /// looking for. Find the next module that contains entities and return the ID
  4090. /// of the first entry.
  4091. PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
  4092. GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
  4093. ++SLocMapI;
  4094. for (GlobalSLocOffsetMapType::const_iterator
  4095. EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
  4096. ModuleFile &M = *SLocMapI->second;
  4097. if (M.NumPreprocessedEntities)
  4098. return M.BasePreprocessedEntityID;
  4099. }
  4100. return getTotalNumPreprocessedEntities();
  4101. }
  4102. namespace {
  4103. template <unsigned PPEntityOffset::*PPLoc>
  4104. struct PPEntityComp {
  4105. const ASTReader &Reader;
  4106. ModuleFile &M;
  4107. PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) { }
  4108. bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
  4109. SourceLocation LHS = getLoc(L);
  4110. SourceLocation RHS = getLoc(R);
  4111. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  4112. }
  4113. bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
  4114. SourceLocation LHS = getLoc(L);
  4115. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  4116. }
  4117. bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
  4118. SourceLocation RHS = getLoc(R);
  4119. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  4120. }
  4121. SourceLocation getLoc(const PPEntityOffset &PPE) const {
  4122. return Reader.ReadSourceLocation(M, PPE.*PPLoc);
  4123. }
  4124. };
  4125. }
  4126. PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
  4127. bool EndsAfter) const {
  4128. if (SourceMgr.isLocalSourceLocation(Loc))
  4129. return getTotalNumPreprocessedEntities();
  4130. GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
  4131. SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
  4132. assert(SLocMapI != GlobalSLocOffsetMap.end() &&
  4133. "Corrupted global sloc offset map");
  4134. if (SLocMapI->second->NumPreprocessedEntities == 0)
  4135. return findNextPreprocessedEntity(SLocMapI);
  4136. ModuleFile &M = *SLocMapI->second;
  4137. typedef const PPEntityOffset *pp_iterator;
  4138. pp_iterator pp_begin = M.PreprocessedEntityOffsets;
  4139. pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
  4140. size_t Count = M.NumPreprocessedEntities;
  4141. size_t Half;
  4142. pp_iterator First = pp_begin;
  4143. pp_iterator PPI;
  4144. if (EndsAfter) {
  4145. PPI = std::upper_bound(pp_begin, pp_end, Loc,
  4146. PPEntityComp<&PPEntityOffset::Begin>(*this, M));
  4147. } else {
  4148. // Do a binary search manually instead of using std::lower_bound because
  4149. // The end locations of entities may be unordered (when a macro expansion
  4150. // is inside another macro argument), but for this case it is not important
  4151. // whether we get the first macro expansion or its containing macro.
  4152. while (Count > 0) {
  4153. Half = Count / 2;
  4154. PPI = First;
  4155. std::advance(PPI, Half);
  4156. if (SourceMgr.isBeforeInTranslationUnit(ReadSourceLocation(M, PPI->End),
  4157. Loc)) {
  4158. First = PPI;
  4159. ++First;
  4160. Count = Count - Half - 1;
  4161. } else
  4162. Count = Half;
  4163. }
  4164. }
  4165. if (PPI == pp_end)
  4166. return findNextPreprocessedEntity(SLocMapI);
  4167. return M.BasePreprocessedEntityID + (PPI - pp_begin);
  4168. }
  4169. /// \brief Returns a pair of [Begin, End) indices of preallocated
  4170. /// preprocessed entities that \arg Range encompasses.
  4171. std::pair<unsigned, unsigned>
  4172. ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
  4173. if (Range.isInvalid())
  4174. return std::make_pair(0,0);
  4175. assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
  4176. PreprocessedEntityID BeginID =
  4177. findPreprocessedEntity(Range.getBegin(), false);
  4178. PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
  4179. return std::make_pair(BeginID, EndID);
  4180. }
  4181. /// \brief Optionally returns true or false if the preallocated preprocessed
  4182. /// entity with index \arg Index came from file \arg FID.
  4183. Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
  4184. FileID FID) {
  4185. if (FID.isInvalid())
  4186. return false;
  4187. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  4188. ModuleFile &M = *PPInfo.first;
  4189. unsigned LocalIndex = PPInfo.second;
  4190. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  4191. SourceLocation Loc = ReadSourceLocation(M, PPOffs.Begin);
  4192. if (Loc.isInvalid())
  4193. return false;
  4194. if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
  4195. return true;
  4196. else
  4197. return false;
  4198. }
  4199. namespace {
  4200. /// \brief Visitor used to search for information about a header file.
  4201. class HeaderFileInfoVisitor {
  4202. const FileEntry *FE;
  4203. Optional<HeaderFileInfo> HFI;
  4204. public:
  4205. explicit HeaderFileInfoVisitor(const FileEntry *FE)
  4206. : FE(FE) { }
  4207. static bool visit(ModuleFile &M, void *UserData) {
  4208. HeaderFileInfoVisitor *This
  4209. = static_cast<HeaderFileInfoVisitor *>(UserData);
  4210. HeaderFileInfoLookupTable *Table
  4211. = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
  4212. if (!Table)
  4213. return false;
  4214. // Look in the on-disk hash table for an entry for this file name.
  4215. HeaderFileInfoLookupTable::iterator Pos = Table->find(This->FE);
  4216. if (Pos == Table->end())
  4217. return false;
  4218. This->HFI = *Pos;
  4219. return true;
  4220. }
  4221. Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
  4222. };
  4223. }
  4224. HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
  4225. HeaderFileInfoVisitor Visitor(FE);
  4226. ModuleMgr.visit(&HeaderFileInfoVisitor::visit, &Visitor);
  4227. if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
  4228. return *HFI;
  4229. return HeaderFileInfo();
  4230. }
  4231. void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
  4232. // FIXME: Make it work properly with modules.
  4233. SmallVector<DiagnosticsEngine::DiagState *, 32> DiagStates;
  4234. for (ModuleIterator I = ModuleMgr.begin(), E = ModuleMgr.end(); I != E; ++I) {
  4235. ModuleFile &F = *(*I);
  4236. unsigned Idx = 0;
  4237. DiagStates.clear();
  4238. assert(!Diag.DiagStates.empty());
  4239. DiagStates.push_back(&Diag.DiagStates.front()); // the command-line one.
  4240. while (Idx < F.PragmaDiagMappings.size()) {
  4241. SourceLocation Loc = ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
  4242. unsigned DiagStateID = F.PragmaDiagMappings[Idx++];
  4243. if (DiagStateID != 0) {
  4244. Diag.DiagStatePoints.push_back(
  4245. DiagnosticsEngine::DiagStatePoint(DiagStates[DiagStateID-1],
  4246. FullSourceLoc(Loc, SourceMgr)));
  4247. continue;
  4248. }
  4249. assert(DiagStateID == 0);
  4250. // A new DiagState was created here.
  4251. Diag.DiagStates.push_back(*Diag.GetCurDiagState());
  4252. DiagnosticsEngine::DiagState *NewState = &Diag.DiagStates.back();
  4253. DiagStates.push_back(NewState);
  4254. Diag.DiagStatePoints.push_back(
  4255. DiagnosticsEngine::DiagStatePoint(NewState,
  4256. FullSourceLoc(Loc, SourceMgr)));
  4257. while (1) {
  4258. assert(Idx < F.PragmaDiagMappings.size() &&
  4259. "Invalid data, didn't find '-1' marking end of diag/map pairs");
  4260. if (Idx >= F.PragmaDiagMappings.size()) {
  4261. break; // Something is messed up but at least avoid infinite loop in
  4262. // release build.
  4263. }
  4264. unsigned DiagID = F.PragmaDiagMappings[Idx++];
  4265. if (DiagID == (unsigned)-1) {
  4266. break; // no more diag/map pairs for this location.
  4267. }
  4268. diag::Severity Map = (diag::Severity)F.PragmaDiagMappings[Idx++];
  4269. DiagnosticMapping Mapping = Diag.makeUserMapping(Map, Loc);
  4270. Diag.GetCurDiagState()->setMapping(DiagID, Mapping);
  4271. }
  4272. }
  4273. }
  4274. }
  4275. /// \brief Get the correct cursor and offset for loading a type.
  4276. ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
  4277. GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
  4278. assert(I != GlobalTypeMap.end() && "Corrupted global type map");
  4279. ModuleFile *M = I->second;
  4280. return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
  4281. }
  4282. /// \brief Read and return the type with the given index..
  4283. ///
  4284. /// The index is the type ID, shifted and minus the number of predefs. This
  4285. /// routine actually reads the record corresponding to the type at the given
  4286. /// location. It is a helper routine for GetType, which deals with reading type
  4287. /// IDs.
  4288. QualType ASTReader::readTypeRecord(unsigned Index) {
  4289. RecordLocation Loc = TypeCursorForIndex(Index);
  4290. BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
  4291. // Keep track of where we are in the stream, then jump back there
  4292. // after reading this type.
  4293. SavedStreamPosition SavedPosition(DeclsCursor);
  4294. ReadingKindTracker ReadingKind(Read_Type, *this);
  4295. // Note that we are loading a type record.
  4296. Deserializing AType(this);
  4297. unsigned Idx = 0;
  4298. DeclsCursor.JumpToBit(Loc.Offset);
  4299. RecordData Record;
  4300. unsigned Code = DeclsCursor.ReadCode();
  4301. switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
  4302. case TYPE_EXT_QUAL: {
  4303. if (Record.size() != 2) {
  4304. Error("Incorrect encoding of extended qualifier type");
  4305. return QualType();
  4306. }
  4307. QualType Base = readType(*Loc.F, Record, Idx);
  4308. Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
  4309. return Context.getQualifiedType(Base, Quals);
  4310. }
  4311. case TYPE_COMPLEX: {
  4312. if (Record.size() != 1) {
  4313. Error("Incorrect encoding of complex type");
  4314. return QualType();
  4315. }
  4316. QualType ElemType = readType(*Loc.F, Record, Idx);
  4317. return Context.getComplexType(ElemType);
  4318. }
  4319. case TYPE_POINTER: {
  4320. if (Record.size() != 1) {
  4321. Error("Incorrect encoding of pointer type");
  4322. return QualType();
  4323. }
  4324. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4325. return Context.getPointerType(PointeeType);
  4326. }
  4327. case TYPE_DECAYED: {
  4328. if (Record.size() != 1) {
  4329. Error("Incorrect encoding of decayed type");
  4330. return QualType();
  4331. }
  4332. QualType OriginalType = readType(*Loc.F, Record, Idx);
  4333. QualType DT = Context.getAdjustedParameterType(OriginalType);
  4334. if (!isa<DecayedType>(DT))
  4335. Error("Decayed type does not decay");
  4336. return DT;
  4337. }
  4338. case TYPE_ADJUSTED: {
  4339. if (Record.size() != 2) {
  4340. Error("Incorrect encoding of adjusted type");
  4341. return QualType();
  4342. }
  4343. QualType OriginalTy = readType(*Loc.F, Record, Idx);
  4344. QualType AdjustedTy = readType(*Loc.F, Record, Idx);
  4345. return Context.getAdjustedType(OriginalTy, AdjustedTy);
  4346. }
  4347. case TYPE_BLOCK_POINTER: {
  4348. if (Record.size() != 1) {
  4349. Error("Incorrect encoding of block pointer type");
  4350. return QualType();
  4351. }
  4352. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4353. return Context.getBlockPointerType(PointeeType);
  4354. }
  4355. case TYPE_LVALUE_REFERENCE: {
  4356. if (Record.size() != 2) {
  4357. Error("Incorrect encoding of lvalue reference type");
  4358. return QualType();
  4359. }
  4360. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4361. return Context.getLValueReferenceType(PointeeType, Record[1]);
  4362. }
  4363. case TYPE_RVALUE_REFERENCE: {
  4364. if (Record.size() != 1) {
  4365. Error("Incorrect encoding of rvalue reference type");
  4366. return QualType();
  4367. }
  4368. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4369. return Context.getRValueReferenceType(PointeeType);
  4370. }
  4371. case TYPE_MEMBER_POINTER: {
  4372. if (Record.size() != 2) {
  4373. Error("Incorrect encoding of member pointer type");
  4374. return QualType();
  4375. }
  4376. QualType PointeeType = readType(*Loc.F, Record, Idx);
  4377. QualType ClassType = readType(*Loc.F, Record, Idx);
  4378. if (PointeeType.isNull() || ClassType.isNull())
  4379. return QualType();
  4380. return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
  4381. }
  4382. case TYPE_CONSTANT_ARRAY: {
  4383. QualType ElementType = readType(*Loc.F, Record, Idx);
  4384. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  4385. unsigned IndexTypeQuals = Record[2];
  4386. unsigned Idx = 3;
  4387. llvm::APInt Size = ReadAPInt(Record, Idx);
  4388. return Context.getConstantArrayType(ElementType, Size,
  4389. ASM, IndexTypeQuals);
  4390. }
  4391. case TYPE_INCOMPLETE_ARRAY: {
  4392. QualType ElementType = readType(*Loc.F, Record, Idx);
  4393. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  4394. unsigned IndexTypeQuals = Record[2];
  4395. return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
  4396. }
  4397. case TYPE_VARIABLE_ARRAY: {
  4398. QualType ElementType = readType(*Loc.F, Record, Idx);
  4399. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  4400. unsigned IndexTypeQuals = Record[2];
  4401. SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
  4402. SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
  4403. return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
  4404. ASM, IndexTypeQuals,
  4405. SourceRange(LBLoc, RBLoc));
  4406. }
  4407. case TYPE_VECTOR: {
  4408. if (Record.size() != 3) {
  4409. Error("incorrect encoding of vector type in AST file");
  4410. return QualType();
  4411. }
  4412. QualType ElementType = readType(*Loc.F, Record, Idx);
  4413. unsigned NumElements = Record[1];
  4414. unsigned VecKind = Record[2];
  4415. return Context.getVectorType(ElementType, NumElements,
  4416. (VectorType::VectorKind)VecKind);
  4417. }
  4418. case TYPE_EXT_VECTOR: {
  4419. if (Record.size() != 3) {
  4420. Error("incorrect encoding of extended vector type in AST file");
  4421. return QualType();
  4422. }
  4423. QualType ElementType = readType(*Loc.F, Record, Idx);
  4424. unsigned NumElements = Record[1];
  4425. return Context.getExtVectorType(ElementType, NumElements);
  4426. }
  4427. case TYPE_FUNCTION_NO_PROTO: {
  4428. if (Record.size() != 6) {
  4429. Error("incorrect encoding of no-proto function type");
  4430. return QualType();
  4431. }
  4432. QualType ResultType = readType(*Loc.F, Record, Idx);
  4433. FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
  4434. (CallingConv)Record[4], Record[5]);
  4435. return Context.getFunctionNoProtoType(ResultType, Info);
  4436. }
  4437. case TYPE_FUNCTION_PROTO: {
  4438. QualType ResultType = readType(*Loc.F, Record, Idx);
  4439. FunctionProtoType::ExtProtoInfo EPI;
  4440. EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
  4441. /*hasregparm*/ Record[2],
  4442. /*regparm*/ Record[3],
  4443. static_cast<CallingConv>(Record[4]),
  4444. /*produces*/ Record[5]);
  4445. unsigned Idx = 6;
  4446. EPI.Variadic = Record[Idx++];
  4447. EPI.HasTrailingReturn = Record[Idx++];
  4448. EPI.TypeQuals = Record[Idx++];
  4449. EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
  4450. SmallVector<QualType, 8> ExceptionStorage;
  4451. readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
  4452. unsigned NumParams = Record[Idx++];
  4453. SmallVector<QualType, 16> ParamTypes;
  4454. for (unsigned I = 0; I != NumParams; ++I)
  4455. ParamTypes.push_back(readType(*Loc.F, Record, Idx));
  4456. return Context.getFunctionType(ResultType, ParamTypes, EPI, None); // HLSL Change
  4457. }
  4458. case TYPE_UNRESOLVED_USING: {
  4459. unsigned Idx = 0;
  4460. return Context.getTypeDeclType(
  4461. ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
  4462. }
  4463. case TYPE_TYPEDEF: {
  4464. if (Record.size() != 2) {
  4465. Error("incorrect encoding of typedef type");
  4466. return QualType();
  4467. }
  4468. unsigned Idx = 0;
  4469. TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
  4470. QualType Canonical = readType(*Loc.F, Record, Idx);
  4471. if (!Canonical.isNull())
  4472. Canonical = Context.getCanonicalType(Canonical);
  4473. return Context.getTypedefType(Decl, Canonical);
  4474. }
  4475. case TYPE_TYPEOF_EXPR:
  4476. return Context.getTypeOfExprType(ReadExpr(*Loc.F));
  4477. case TYPE_TYPEOF: {
  4478. if (Record.size() != 1) {
  4479. Error("incorrect encoding of typeof(type) in AST file");
  4480. return QualType();
  4481. }
  4482. QualType UnderlyingType = readType(*Loc.F, Record, Idx);
  4483. return Context.getTypeOfType(UnderlyingType);
  4484. }
  4485. case TYPE_DECLTYPE: {
  4486. QualType UnderlyingType = readType(*Loc.F, Record, Idx);
  4487. return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
  4488. }
  4489. case TYPE_UNARY_TRANSFORM: {
  4490. QualType BaseType = readType(*Loc.F, Record, Idx);
  4491. QualType UnderlyingType = readType(*Loc.F, Record, Idx);
  4492. UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
  4493. return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
  4494. }
  4495. case TYPE_AUTO: {
  4496. QualType Deduced = readType(*Loc.F, Record, Idx);
  4497. bool IsDecltypeAuto = Record[Idx++];
  4498. bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
  4499. return Context.getAutoType(Deduced, IsDecltypeAuto, IsDependent);
  4500. }
  4501. case TYPE_RECORD: {
  4502. if (Record.size() != 2) {
  4503. Error("incorrect encoding of record type");
  4504. return QualType();
  4505. }
  4506. unsigned Idx = 0;
  4507. bool IsDependent = Record[Idx++];
  4508. RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
  4509. RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
  4510. QualType T = Context.getRecordType(RD);
  4511. const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
  4512. return T;
  4513. }
  4514. case TYPE_ENUM: {
  4515. if (Record.size() != 2) {
  4516. Error("incorrect encoding of enum type");
  4517. return QualType();
  4518. }
  4519. unsigned Idx = 0;
  4520. bool IsDependent = Record[Idx++];
  4521. QualType T
  4522. = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
  4523. const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
  4524. return T;
  4525. }
  4526. case TYPE_ATTRIBUTED: {
  4527. if (Record.size() != 3) {
  4528. Error("incorrect encoding of attributed type");
  4529. return QualType();
  4530. }
  4531. QualType modifiedType = readType(*Loc.F, Record, Idx);
  4532. QualType equivalentType = readType(*Loc.F, Record, Idx);
  4533. AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
  4534. return Context.getAttributedType(kind, modifiedType, equivalentType);
  4535. }
  4536. case TYPE_PAREN: {
  4537. if (Record.size() != 1) {
  4538. Error("incorrect encoding of paren type");
  4539. return QualType();
  4540. }
  4541. QualType InnerType = readType(*Loc.F, Record, Idx);
  4542. return Context.getParenType(InnerType);
  4543. }
  4544. case TYPE_PACK_EXPANSION: {
  4545. if (Record.size() != 2) {
  4546. Error("incorrect encoding of pack expansion type");
  4547. return QualType();
  4548. }
  4549. QualType Pattern = readType(*Loc.F, Record, Idx);
  4550. if (Pattern.isNull())
  4551. return QualType();
  4552. Optional<unsigned> NumExpansions;
  4553. if (Record[1])
  4554. NumExpansions = Record[1] - 1;
  4555. return Context.getPackExpansionType(Pattern, NumExpansions);
  4556. }
  4557. case TYPE_ELABORATED: {
  4558. unsigned Idx = 0;
  4559. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  4560. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
  4561. QualType NamedType = readType(*Loc.F, Record, Idx);
  4562. return Context.getElaboratedType(Keyword, NNS, NamedType);
  4563. }
  4564. case TYPE_OBJC_INTERFACE: {
  4565. unsigned Idx = 0;
  4566. ObjCInterfaceDecl *ItfD
  4567. = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
  4568. return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
  4569. }
  4570. case TYPE_OBJC_OBJECT: {
  4571. unsigned Idx = 0;
  4572. QualType Base = readType(*Loc.F, Record, Idx);
  4573. unsigned NumTypeArgs = Record[Idx++];
  4574. SmallVector<QualType, 4> TypeArgs;
  4575. for (unsigned I = 0; I != NumTypeArgs; ++I)
  4576. TypeArgs.push_back(readType(*Loc.F, Record, Idx));
  4577. unsigned NumProtos = Record[Idx++];
  4578. SmallVector<ObjCProtocolDecl*, 4> Protos;
  4579. for (unsigned I = 0; I != NumProtos; ++I)
  4580. Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
  4581. bool IsKindOf = Record[Idx++];
  4582. return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
  4583. }
  4584. case TYPE_OBJC_OBJECT_POINTER: {
  4585. unsigned Idx = 0;
  4586. QualType Pointee = readType(*Loc.F, Record, Idx);
  4587. return Context.getObjCObjectPointerType(Pointee);
  4588. }
  4589. case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
  4590. unsigned Idx = 0;
  4591. QualType Parm = readType(*Loc.F, Record, Idx);
  4592. QualType Replacement = readType(*Loc.F, Record, Idx);
  4593. return Context.getSubstTemplateTypeParmType(
  4594. cast<TemplateTypeParmType>(Parm),
  4595. Context.getCanonicalType(Replacement));
  4596. }
  4597. case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
  4598. unsigned Idx = 0;
  4599. QualType Parm = readType(*Loc.F, Record, Idx);
  4600. TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
  4601. return Context.getSubstTemplateTypeParmPackType(
  4602. cast<TemplateTypeParmType>(Parm),
  4603. ArgPack);
  4604. }
  4605. case TYPE_INJECTED_CLASS_NAME: {
  4606. CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
  4607. QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
  4608. // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
  4609. // for AST reading, too much interdependencies.
  4610. const Type *T = nullptr;
  4611. for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
  4612. if (const Type *Existing = DI->getTypeForDecl()) {
  4613. T = Existing;
  4614. break;
  4615. }
  4616. }
  4617. if (!T) {
  4618. T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
  4619. for (auto *DI = D; DI; DI = DI->getPreviousDecl())
  4620. DI->setTypeForDecl(T);
  4621. }
  4622. return QualType(T, 0);
  4623. }
  4624. case TYPE_TEMPLATE_TYPE_PARM: {
  4625. unsigned Idx = 0;
  4626. unsigned Depth = Record[Idx++];
  4627. unsigned Index = Record[Idx++];
  4628. bool Pack = Record[Idx++];
  4629. TemplateTypeParmDecl *D
  4630. = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
  4631. return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
  4632. }
  4633. case TYPE_DEPENDENT_NAME: {
  4634. unsigned Idx = 0;
  4635. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  4636. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
  4637. const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
  4638. QualType Canon = readType(*Loc.F, Record, Idx);
  4639. if (!Canon.isNull())
  4640. Canon = Context.getCanonicalType(Canon);
  4641. return Context.getDependentNameType(Keyword, NNS, Name, Canon);
  4642. }
  4643. case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
  4644. unsigned Idx = 0;
  4645. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  4646. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
  4647. const IdentifierInfo *Name = this->GetIdentifierInfo(*Loc.F, Record, Idx);
  4648. unsigned NumArgs = Record[Idx++];
  4649. SmallVector<TemplateArgument, 8> Args;
  4650. Args.reserve(NumArgs);
  4651. while (NumArgs--)
  4652. Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
  4653. return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
  4654. Args.size(), Args.data());
  4655. }
  4656. case TYPE_DEPENDENT_SIZED_ARRAY: {
  4657. unsigned Idx = 0;
  4658. // ArrayType
  4659. QualType ElementType = readType(*Loc.F, Record, Idx);
  4660. ArrayType::ArraySizeModifier ASM
  4661. = (ArrayType::ArraySizeModifier)Record[Idx++];
  4662. unsigned IndexTypeQuals = Record[Idx++];
  4663. // DependentSizedArrayType
  4664. Expr *NumElts = ReadExpr(*Loc.F);
  4665. SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
  4666. return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
  4667. IndexTypeQuals, Brackets);
  4668. }
  4669. case TYPE_TEMPLATE_SPECIALIZATION: {
  4670. unsigned Idx = 0;
  4671. bool IsDependent = Record[Idx++];
  4672. TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
  4673. SmallVector<TemplateArgument, 8> Args;
  4674. ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
  4675. QualType Underlying = readType(*Loc.F, Record, Idx);
  4676. QualType T;
  4677. if (Underlying.isNull())
  4678. T = Context.getCanonicalTemplateSpecializationType(Name, Args.data(),
  4679. Args.size());
  4680. else
  4681. T = Context.getTemplateSpecializationType(Name, Args.data(),
  4682. Args.size(), Underlying);
  4683. const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
  4684. return T;
  4685. }
  4686. case TYPE_ATOMIC: {
  4687. if (Record.size() != 1) {
  4688. Error("Incorrect encoding of atomic type");
  4689. return QualType();
  4690. }
  4691. QualType ValueType = readType(*Loc.F, Record, Idx);
  4692. return Context.getAtomicType(ValueType);
  4693. }
  4694. }
  4695. llvm_unreachable("Invalid TypeCode!");
  4696. }
  4697. void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
  4698. SmallVectorImpl<QualType> &Exceptions,
  4699. FunctionProtoType::ExceptionSpecInfo &ESI,
  4700. const RecordData &Record, unsigned &Idx) {
  4701. ExceptionSpecificationType EST =
  4702. static_cast<ExceptionSpecificationType>(Record[Idx++]);
  4703. ESI.Type = EST;
  4704. if (EST == EST_Dynamic) {
  4705. for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
  4706. Exceptions.push_back(readType(ModuleFile, Record, Idx));
  4707. ESI.Exceptions = Exceptions;
  4708. } else if (EST == EST_ComputedNoexcept) {
  4709. ESI.NoexceptExpr = ReadExpr(ModuleFile);
  4710. } else if (EST == EST_Uninstantiated) {
  4711. ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
  4712. ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
  4713. } else if (EST == EST_Unevaluated) {
  4714. ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
  4715. }
  4716. }
  4717. class clang::TypeLocReader : public TypeLocVisitor<TypeLocReader> {
  4718. ASTReader &Reader;
  4719. ModuleFile &F;
  4720. const ASTReader::RecordData &Record;
  4721. unsigned &Idx;
  4722. SourceLocation ReadSourceLocation(const ASTReader::RecordData &R,
  4723. unsigned &I) {
  4724. return Reader.ReadSourceLocation(F, R, I);
  4725. }
  4726. template<typename T>
  4727. T *ReadDeclAs(const ASTReader::RecordData &Record, unsigned &Idx) {
  4728. return Reader.ReadDeclAs<T>(F, Record, Idx);
  4729. }
  4730. public:
  4731. TypeLocReader(ASTReader &Reader, ModuleFile &F,
  4732. const ASTReader::RecordData &Record, unsigned &Idx)
  4733. : Reader(Reader), F(F), Record(Record), Idx(Idx)
  4734. { }
  4735. // We want compile-time assurance that we've enumerated all of
  4736. // these, so unfortunately we have to declare them first, then
  4737. // define them out-of-line.
  4738. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  4739. #define TYPELOC(CLASS, PARENT) \
  4740. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  4741. #include "clang/AST/TypeLocNodes.def"
  4742. void VisitFunctionTypeLoc(FunctionTypeLoc);
  4743. void VisitArrayTypeLoc(ArrayTypeLoc);
  4744. };
  4745. void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  4746. // nothing to do
  4747. }
  4748. void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  4749. TL.setBuiltinLoc(ReadSourceLocation(Record, Idx));
  4750. if (TL.needsExtraLocalData()) {
  4751. TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
  4752. TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
  4753. TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
  4754. TL.setModeAttr(Record[Idx++]);
  4755. }
  4756. }
  4757. void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  4758. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4759. }
  4760. void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
  4761. TL.setStarLoc(ReadSourceLocation(Record, Idx));
  4762. }
  4763. void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  4764. // nothing to do
  4765. }
  4766. void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  4767. // nothing to do
  4768. }
  4769. void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  4770. TL.setCaretLoc(ReadSourceLocation(Record, Idx));
  4771. }
  4772. void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  4773. TL.setAmpLoc(ReadSourceLocation(Record, Idx));
  4774. }
  4775. void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  4776. TL.setAmpAmpLoc(ReadSourceLocation(Record, Idx));
  4777. }
  4778. void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  4779. TL.setStarLoc(ReadSourceLocation(Record, Idx));
  4780. TL.setClassTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
  4781. }
  4782. void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  4783. TL.setLBracketLoc(ReadSourceLocation(Record, Idx));
  4784. TL.setRBracketLoc(ReadSourceLocation(Record, Idx));
  4785. if (Record[Idx++])
  4786. TL.setSizeExpr(Reader.ReadExpr(F));
  4787. else
  4788. TL.setSizeExpr(nullptr);
  4789. }
  4790. void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  4791. VisitArrayTypeLoc(TL);
  4792. }
  4793. void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  4794. VisitArrayTypeLoc(TL);
  4795. }
  4796. void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  4797. VisitArrayTypeLoc(TL);
  4798. }
  4799. void TypeLocReader::VisitDependentSizedArrayTypeLoc(
  4800. DependentSizedArrayTypeLoc TL) {
  4801. VisitArrayTypeLoc(TL);
  4802. }
  4803. void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
  4804. DependentSizedExtVectorTypeLoc TL) {
  4805. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4806. }
  4807. void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
  4808. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4809. }
  4810. void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  4811. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4812. }
  4813. void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  4814. TL.setLocalRangeBegin(ReadSourceLocation(Record, Idx));
  4815. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4816. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4817. TL.setLocalRangeEnd(ReadSourceLocation(Record, Idx));
  4818. for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
  4819. TL.setParam(i, ReadDeclAs<ParmVarDecl>(Record, Idx));
  4820. }
  4821. }
  4822. void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  4823. VisitFunctionTypeLoc(TL);
  4824. }
  4825. void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  4826. VisitFunctionTypeLoc(TL);
  4827. }
  4828. void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  4829. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4830. }
  4831. void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  4832. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4833. }
  4834. void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  4835. TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
  4836. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4837. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4838. }
  4839. void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  4840. TL.setTypeofLoc(ReadSourceLocation(Record, Idx));
  4841. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4842. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4843. TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
  4844. }
  4845. void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  4846. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4847. }
  4848. void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  4849. TL.setKWLoc(ReadSourceLocation(Record, Idx));
  4850. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4851. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4852. TL.setUnderlyingTInfo(Reader.GetTypeSourceInfo(F, Record, Idx));
  4853. }
  4854. void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
  4855. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4856. }
  4857. void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
  4858. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4859. }
  4860. void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
  4861. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4862. }
  4863. void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  4864. TL.setAttrNameLoc(ReadSourceLocation(Record, Idx));
  4865. if (TL.hasAttrOperand()) {
  4866. SourceRange range;
  4867. range.setBegin(ReadSourceLocation(Record, Idx));
  4868. range.setEnd(ReadSourceLocation(Record, Idx));
  4869. TL.setAttrOperandParensRange(range);
  4870. }
  4871. if (TL.hasAttrExprOperand()) {
  4872. if (Record[Idx++])
  4873. TL.setAttrExprOperand(Reader.ReadExpr(F));
  4874. else
  4875. TL.setAttrExprOperand(nullptr);
  4876. } else if (TL.hasAttrEnumOperand())
  4877. TL.setAttrEnumOperandLoc(ReadSourceLocation(Record, Idx));
  4878. }
  4879. void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  4880. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4881. }
  4882. void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
  4883. SubstTemplateTypeParmTypeLoc TL) {
  4884. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4885. }
  4886. void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
  4887. SubstTemplateTypeParmPackTypeLoc TL) {
  4888. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4889. }
  4890. void TypeLocReader::VisitTemplateSpecializationTypeLoc(
  4891. TemplateSpecializationTypeLoc TL) {
  4892. TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
  4893. TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
  4894. TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
  4895. TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
  4896. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  4897. TL.setArgLocInfo(i,
  4898. Reader.GetTemplateArgumentLocInfo(F,
  4899. TL.getTypePtr()->getArg(i).getKind(),
  4900. Record, Idx));
  4901. }
  4902. void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
  4903. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4904. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4905. }
  4906. void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  4907. TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
  4908. TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
  4909. }
  4910. void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  4911. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4912. }
  4913. void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  4914. TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
  4915. TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
  4916. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4917. }
  4918. void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
  4919. DependentTemplateSpecializationTypeLoc TL) {
  4920. TL.setElaboratedKeywordLoc(ReadSourceLocation(Record, Idx));
  4921. TL.setQualifierLoc(Reader.ReadNestedNameSpecifierLoc(F, Record, Idx));
  4922. TL.setTemplateKeywordLoc(ReadSourceLocation(Record, Idx));
  4923. TL.setTemplateNameLoc(ReadSourceLocation(Record, Idx));
  4924. TL.setLAngleLoc(ReadSourceLocation(Record, Idx));
  4925. TL.setRAngleLoc(ReadSourceLocation(Record, Idx));
  4926. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  4927. TL.setArgLocInfo(I,
  4928. Reader.GetTemplateArgumentLocInfo(F,
  4929. TL.getTypePtr()->getArg(I).getKind(),
  4930. Record, Idx));
  4931. }
  4932. void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  4933. TL.setEllipsisLoc(ReadSourceLocation(Record, Idx));
  4934. }
  4935. void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  4936. TL.setNameLoc(ReadSourceLocation(Record, Idx));
  4937. }
  4938. void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  4939. TL.setHasBaseTypeAsWritten(Record[Idx++]);
  4940. TL.setTypeArgsLAngleLoc(ReadSourceLocation(Record, Idx));
  4941. TL.setTypeArgsRAngleLoc(ReadSourceLocation(Record, Idx));
  4942. for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
  4943. TL.setTypeArgTInfo(i, Reader.GetTypeSourceInfo(F, Record, Idx));
  4944. TL.setProtocolLAngleLoc(ReadSourceLocation(Record, Idx));
  4945. TL.setProtocolRAngleLoc(ReadSourceLocation(Record, Idx));
  4946. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  4947. TL.setProtocolLoc(i, ReadSourceLocation(Record, Idx));
  4948. }
  4949. void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  4950. TL.setStarLoc(ReadSourceLocation(Record, Idx));
  4951. }
  4952. void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  4953. TL.setKWLoc(ReadSourceLocation(Record, Idx));
  4954. TL.setLParenLoc(ReadSourceLocation(Record, Idx));
  4955. TL.setRParenLoc(ReadSourceLocation(Record, Idx));
  4956. }
  4957. TypeSourceInfo *ASTReader::GetTypeSourceInfo(ModuleFile &F,
  4958. const RecordData &Record,
  4959. unsigned &Idx) {
  4960. QualType InfoTy = readType(F, Record, Idx);
  4961. if (InfoTy.isNull())
  4962. return nullptr;
  4963. TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
  4964. TypeLocReader TLR(*this, F, Record, Idx);
  4965. for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
  4966. TLR.Visit(TL);
  4967. return TInfo;
  4968. }
  4969. QualType ASTReader::GetType(TypeID ID) {
  4970. unsigned FastQuals = ID & Qualifiers::FastMask;
  4971. unsigned Index = ID >> Qualifiers::FastWidth;
  4972. if (Index < NUM_PREDEF_TYPE_IDS) {
  4973. QualType T;
  4974. switch ((PredefinedTypeIDs)Index) {
  4975. case PREDEF_TYPE_NULL_ID: return QualType();
  4976. case PREDEF_TYPE_VOID_ID: T = Context.VoidTy; break;
  4977. case PREDEF_TYPE_BOOL_ID: T = Context.BoolTy; break;
  4978. case PREDEF_TYPE_CHAR_U_ID:
  4979. case PREDEF_TYPE_CHAR_S_ID:
  4980. // FIXME: Check that the signedness of CharTy is correct!
  4981. T = Context.CharTy;
  4982. break;
  4983. case PREDEF_TYPE_UCHAR_ID: T = Context.UnsignedCharTy; break;
  4984. case PREDEF_TYPE_USHORT_ID: T = Context.UnsignedShortTy; break;
  4985. case PREDEF_TYPE_UINT_ID: T = Context.UnsignedIntTy; break;
  4986. case PREDEF_TYPE_ULONG_ID: T = Context.UnsignedLongTy; break;
  4987. case PREDEF_TYPE_ULONGLONG_ID: T = Context.UnsignedLongLongTy; break;
  4988. case PREDEF_TYPE_UINT128_ID: T = Context.UnsignedInt128Ty; break;
  4989. case PREDEF_TYPE_SCHAR_ID: T = Context.SignedCharTy; break;
  4990. case PREDEF_TYPE_WCHAR_ID: T = Context.WCharTy; break;
  4991. case PREDEF_TYPE_SHORT_ID: T = Context.ShortTy; break;
  4992. case PREDEF_TYPE_INT_ID: T = Context.IntTy; break;
  4993. case PREDEF_TYPE_LONG_ID: T = Context.LongTy; break;
  4994. case PREDEF_TYPE_LONGLONG_ID: T = Context.LongLongTy; break;
  4995. case PREDEF_TYPE_INT128_ID: T = Context.Int128Ty; break;
  4996. case PREDEF_TYPE_HALF_ID: T = Context.HalfTy; break;
  4997. case PREDEF_TYPE_FLOAT_ID: T = Context.FloatTy; break;
  4998. case PREDEF_TYPE_DOUBLE_ID: T = Context.DoubleTy; break;
  4999. case PREDEF_TYPE_LONGDOUBLE_ID: T = Context.LongDoubleTy; break;
  5000. case PREDEF_TYPE_OVERLOAD_ID: T = Context.OverloadTy; break;
  5001. case PREDEF_TYPE_BOUND_MEMBER: T = Context.BoundMemberTy; break;
  5002. case PREDEF_TYPE_PSEUDO_OBJECT: T = Context.PseudoObjectTy; break;
  5003. case PREDEF_TYPE_DEPENDENT_ID: T = Context.DependentTy; break;
  5004. case PREDEF_TYPE_UNKNOWN_ANY: T = Context.UnknownAnyTy; break;
  5005. case PREDEF_TYPE_NULLPTR_ID: T = Context.NullPtrTy; break;
  5006. case PREDEF_TYPE_CHAR16_ID: T = Context.Char16Ty; break;
  5007. case PREDEF_TYPE_CHAR32_ID: T = Context.Char32Ty; break;
  5008. case PREDEF_TYPE_OBJC_ID: T = Context.ObjCBuiltinIdTy; break;
  5009. case PREDEF_TYPE_OBJC_CLASS: T = Context.ObjCBuiltinClassTy; break;
  5010. case PREDEF_TYPE_OBJC_SEL: T = Context.ObjCBuiltinSelTy; break;
  5011. case PREDEF_TYPE_IMAGE1D_ID: T = Context.OCLImage1dTy; break;
  5012. case PREDEF_TYPE_IMAGE1D_ARR_ID: T = Context.OCLImage1dArrayTy; break;
  5013. case PREDEF_TYPE_IMAGE1D_BUFF_ID: T = Context.OCLImage1dBufferTy; break;
  5014. case PREDEF_TYPE_IMAGE2D_ID: T = Context.OCLImage2dTy; break;
  5015. case PREDEF_TYPE_IMAGE2D_ARR_ID: T = Context.OCLImage2dArrayTy; break;
  5016. case PREDEF_TYPE_IMAGE3D_ID: T = Context.OCLImage3dTy; break;
  5017. case PREDEF_TYPE_SAMPLER_ID: T = Context.OCLSamplerTy; break;
  5018. case PREDEF_TYPE_EVENT_ID: T = Context.OCLEventTy; break;
  5019. case PREDEF_TYPE_AUTO_DEDUCT: T = Context.getAutoDeductType(); break;
  5020. case PREDEF_TYPE_AUTO_RREF_DEDUCT:
  5021. T = Context.getAutoRRefDeductType();
  5022. break;
  5023. case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
  5024. T = Context.ARCUnbridgedCastTy;
  5025. break;
  5026. case PREDEF_TYPE_VA_LIST_TAG:
  5027. T = Context.getVaListTagType();
  5028. break;
  5029. case PREDEF_TYPE_BUILTIN_FN:
  5030. T = Context.BuiltinFnTy;
  5031. break;
  5032. }
  5033. assert(!T.isNull() && "Unknown predefined type");
  5034. return T.withFastQualifiers(FastQuals);
  5035. }
  5036. Index -= NUM_PREDEF_TYPE_IDS;
  5037. assert(Index < TypesLoaded.size() && "Type index out-of-range");
  5038. if (TypesLoaded[Index].isNull()) {
  5039. TypesLoaded[Index] = readTypeRecord(Index);
  5040. if (TypesLoaded[Index].isNull())
  5041. return QualType();
  5042. TypesLoaded[Index]->setFromAST();
  5043. if (DeserializationListener)
  5044. DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
  5045. TypesLoaded[Index]);
  5046. }
  5047. return TypesLoaded[Index].withFastQualifiers(FastQuals);
  5048. }
  5049. QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
  5050. return GetType(getGlobalTypeID(F, LocalID));
  5051. }
  5052. serialization::TypeID
  5053. ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
  5054. unsigned FastQuals = LocalID & Qualifiers::FastMask;
  5055. unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
  5056. if (LocalIndex < NUM_PREDEF_TYPE_IDS)
  5057. return LocalID;
  5058. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  5059. = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
  5060. assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
  5061. unsigned GlobalIndex = LocalIndex + I->second;
  5062. return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
  5063. }
  5064. TemplateArgumentLocInfo
  5065. ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
  5066. TemplateArgument::ArgKind Kind,
  5067. const RecordData &Record,
  5068. unsigned &Index) {
  5069. switch (Kind) {
  5070. case TemplateArgument::Expression:
  5071. return ReadExpr(F);
  5072. case TemplateArgument::Type:
  5073. return GetTypeSourceInfo(F, Record, Index);
  5074. case TemplateArgument::Template: {
  5075. NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
  5076. Index);
  5077. SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
  5078. return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
  5079. SourceLocation());
  5080. }
  5081. case TemplateArgument::TemplateExpansion: {
  5082. NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
  5083. Index);
  5084. SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
  5085. SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
  5086. return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
  5087. EllipsisLoc);
  5088. }
  5089. case TemplateArgument::Null:
  5090. case TemplateArgument::Integral:
  5091. case TemplateArgument::Declaration:
  5092. case TemplateArgument::NullPtr:
  5093. case TemplateArgument::Pack:
  5094. // FIXME: Is this right?
  5095. return TemplateArgumentLocInfo();
  5096. }
  5097. llvm_unreachable("unexpected template argument loc");
  5098. }
  5099. TemplateArgumentLoc
  5100. ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
  5101. const RecordData &Record, unsigned &Index) {
  5102. TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
  5103. if (Arg.getKind() == TemplateArgument::Expression) {
  5104. if (Record[Index++]) // bool InfoHasSameExpr.
  5105. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
  5106. }
  5107. return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
  5108. Record, Index));
  5109. }
  5110. const ASTTemplateArgumentListInfo*
  5111. ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
  5112. const RecordData &Record,
  5113. unsigned &Index) {
  5114. SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
  5115. SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
  5116. unsigned NumArgsAsWritten = Record[Index++];
  5117. TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
  5118. for (unsigned i = 0; i != NumArgsAsWritten; ++i)
  5119. TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
  5120. return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
  5121. }
  5122. Decl *ASTReader::GetExternalDecl(uint32_t ID) {
  5123. return GetDecl(ID);
  5124. }
  5125. template<typename TemplateSpecializationDecl>
  5126. static void completeRedeclChainForTemplateSpecialization(Decl *D) {
  5127. if (auto *TSD = dyn_cast<TemplateSpecializationDecl>(D))
  5128. TSD->getSpecializedTemplate()->LoadLazySpecializations();
  5129. }
  5130. void ASTReader::CompleteRedeclChain(const Decl *D) {
  5131. if (NumCurrentElementsDeserializing) {
  5132. // We arrange to not care about the complete redeclaration chain while we're
  5133. // deserializing. Just remember that the AST has marked this one as complete
  5134. // but that it's not actually complete yet, so we know we still need to
  5135. // complete it later.
  5136. PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
  5137. return;
  5138. }
  5139. const DeclContext *DC = D->getDeclContext()->getRedeclContext();
  5140. // If this is a named declaration, complete it by looking it up
  5141. // within its context.
  5142. //
  5143. // FIXME: Merging a function definition should merge
  5144. // all mergeable entities within it.
  5145. if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
  5146. isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
  5147. if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
  5148. auto *II = Name.getAsIdentifierInfo();
  5149. if (isa<TranslationUnitDecl>(DC) && II) {
  5150. // Outside of C++, we don't have a lookup table for the TU, so update
  5151. // the identifier instead. In C++, either way should work fine.
  5152. if (II->isOutOfDate())
  5153. updateOutOfDateIdentifier(*II);
  5154. } else
  5155. DC->lookup(Name);
  5156. } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
  5157. // FIXME: It'd be nice to do something a bit more targeted here.
  5158. D->getDeclContext()->decls_begin();
  5159. }
  5160. }
  5161. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
  5162. CTSD->getSpecializedTemplate()->LoadLazySpecializations();
  5163. if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
  5164. VTSD->getSpecializedTemplate()->LoadLazySpecializations();
  5165. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  5166. if (auto *Template = FD->getPrimaryTemplate())
  5167. Template->LoadLazySpecializations();
  5168. }
  5169. }
  5170. uint64_t ASTReader::ReadCXXCtorInitializersRef(ModuleFile &M,
  5171. const RecordData &Record,
  5172. unsigned &Idx) {
  5173. if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXCtorInitializers) {
  5174. Error("malformed AST file: missing C++ ctor initializers");
  5175. return 0;
  5176. }
  5177. unsigned LocalID = Record[Idx++];
  5178. return getGlobalBitOffset(M, M.CXXCtorInitializersOffsets[LocalID - 1]);
  5179. }
  5180. CXXCtorInitializer **
  5181. ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
  5182. RecordLocation Loc = getLocalBitOffset(Offset);
  5183. BitstreamCursor &Cursor = Loc.F->DeclsCursor;
  5184. SavedStreamPosition SavedPosition(Cursor);
  5185. Cursor.JumpToBit(Loc.Offset);
  5186. ReadingKindTracker ReadingKind(Read_Decl, *this);
  5187. RecordData Record;
  5188. unsigned Code = Cursor.ReadCode();
  5189. unsigned RecCode = Cursor.readRecord(Code, Record);
  5190. if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
  5191. Error("malformed AST file: missing C++ ctor initializers");
  5192. return nullptr;
  5193. }
  5194. unsigned Idx = 0;
  5195. return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
  5196. }
  5197. uint64_t ASTReader::readCXXBaseSpecifiers(ModuleFile &M,
  5198. const RecordData &Record,
  5199. unsigned &Idx) {
  5200. if (Idx >= Record.size() || Record[Idx] > M.LocalNumCXXBaseSpecifiers) {
  5201. Error("malformed AST file: missing C++ base specifier");
  5202. return 0;
  5203. }
  5204. unsigned LocalID = Record[Idx++];
  5205. return getGlobalBitOffset(M, M.CXXBaseSpecifiersOffsets[LocalID - 1]);
  5206. }
  5207. CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
  5208. RecordLocation Loc = getLocalBitOffset(Offset);
  5209. BitstreamCursor &Cursor = Loc.F->DeclsCursor;
  5210. SavedStreamPosition SavedPosition(Cursor);
  5211. Cursor.JumpToBit(Loc.Offset);
  5212. ReadingKindTracker ReadingKind(Read_Decl, *this);
  5213. RecordData Record;
  5214. unsigned Code = Cursor.ReadCode();
  5215. unsigned RecCode = Cursor.readRecord(Code, Record);
  5216. if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
  5217. Error("malformed AST file: missing C++ base specifiers");
  5218. return nullptr;
  5219. }
  5220. unsigned Idx = 0;
  5221. unsigned NumBases = Record[Idx++];
  5222. void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
  5223. CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
  5224. for (unsigned I = 0; I != NumBases; ++I)
  5225. Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
  5226. return Bases;
  5227. }
  5228. serialization::DeclID
  5229. ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
  5230. if (LocalID < NUM_PREDEF_DECL_IDS)
  5231. return LocalID;
  5232. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  5233. = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
  5234. assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
  5235. return LocalID + I->second;
  5236. }
  5237. bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
  5238. ModuleFile &M) const {
  5239. // Predefined decls aren't from any module.
  5240. if (ID < NUM_PREDEF_DECL_IDS)
  5241. return false;
  5242. return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
  5243. ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
  5244. }
  5245. ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
  5246. if (!D->isFromASTFile())
  5247. return nullptr;
  5248. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
  5249. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  5250. return I->second;
  5251. }
  5252. SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
  5253. if (ID < NUM_PREDEF_DECL_IDS)
  5254. return SourceLocation();
  5255. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  5256. if (Index > DeclsLoaded.size()) {
  5257. Error("declaration ID out-of-range for AST file");
  5258. return SourceLocation();
  5259. }
  5260. if (Decl *D = DeclsLoaded[Index])
  5261. return D->getLocation();
  5262. unsigned RawLocation = 0;
  5263. RecordLocation Rec = DeclCursorForID(ID, RawLocation);
  5264. return ReadSourceLocation(*Rec.F, RawLocation);
  5265. }
  5266. static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
  5267. switch (ID) {
  5268. case PREDEF_DECL_NULL_ID:
  5269. return nullptr;
  5270. case PREDEF_DECL_TRANSLATION_UNIT_ID:
  5271. return Context.getTranslationUnitDecl();
  5272. case PREDEF_DECL_OBJC_ID_ID:
  5273. return Context.getObjCIdDecl();
  5274. case PREDEF_DECL_OBJC_SEL_ID:
  5275. return Context.getObjCSelDecl();
  5276. case PREDEF_DECL_OBJC_CLASS_ID:
  5277. return Context.getObjCClassDecl();
  5278. case PREDEF_DECL_OBJC_PROTOCOL_ID:
  5279. return Context.getObjCProtocolDecl();
  5280. case PREDEF_DECL_INT_128_ID:
  5281. return Context.getInt128Decl();
  5282. case PREDEF_DECL_UNSIGNED_INT_128_ID:
  5283. return Context.getUInt128Decl();
  5284. case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
  5285. return Context.getObjCInstanceTypeDecl();
  5286. case PREDEF_DECL_BUILTIN_VA_LIST_ID:
  5287. return Context.getBuiltinVaListDecl();
  5288. case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
  5289. return Context.getExternCContextDecl();
  5290. }
  5291. llvm_unreachable("PredefinedDeclIDs unknown enum value");
  5292. }
  5293. Decl *ASTReader::GetExistingDecl(DeclID ID) {
  5294. if (ID < NUM_PREDEF_DECL_IDS) {
  5295. Decl *D = getPredefinedDecl(Context, (PredefinedDeclIDs)ID);
  5296. if (D) {
  5297. // Track that we have merged the declaration with ID \p ID into the
  5298. // pre-existing predefined declaration \p D.
  5299. auto &Merged = KeyDecls[D->getCanonicalDecl()];
  5300. if (Merged.empty())
  5301. Merged.push_back(ID);
  5302. }
  5303. return D;
  5304. }
  5305. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  5306. if (Index >= DeclsLoaded.size()) {
  5307. assert(0 && "declaration ID out-of-range for AST file");
  5308. Error("declaration ID out-of-range for AST file");
  5309. return nullptr;
  5310. }
  5311. return DeclsLoaded[Index];
  5312. }
  5313. Decl *ASTReader::GetDecl(DeclID ID) {
  5314. if (ID < NUM_PREDEF_DECL_IDS)
  5315. return GetExistingDecl(ID);
  5316. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  5317. if (Index >= DeclsLoaded.size()) {
  5318. assert(0 && "declaration ID out-of-range for AST file");
  5319. Error("declaration ID out-of-range for AST file");
  5320. return nullptr;
  5321. }
  5322. if (!DeclsLoaded[Index]) {
  5323. ReadDeclRecord(ID);
  5324. if (DeserializationListener)
  5325. DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
  5326. }
  5327. return DeclsLoaded[Index];
  5328. }
  5329. DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
  5330. DeclID GlobalID) {
  5331. if (GlobalID < NUM_PREDEF_DECL_IDS)
  5332. return GlobalID;
  5333. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
  5334. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  5335. ModuleFile *Owner = I->second;
  5336. llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
  5337. = M.GlobalToLocalDeclIDs.find(Owner);
  5338. if (Pos == M.GlobalToLocalDeclIDs.end())
  5339. return 0;
  5340. return GlobalID - Owner->BaseDeclID + Pos->second;
  5341. }
  5342. serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
  5343. const RecordData &Record,
  5344. unsigned &Idx) {
  5345. if (Idx >= Record.size()) {
  5346. Error("Corrupted AST file");
  5347. return 0;
  5348. }
  5349. return getGlobalDeclID(F, Record[Idx++]);
  5350. }
  5351. /// \brief Resolve the offset of a statement into a statement.
  5352. ///
  5353. /// This operation will read a new statement from the external
  5354. /// source each time it is called, and is meant to be used via a
  5355. /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
  5356. Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
  5357. // Switch case IDs are per Decl.
  5358. ClearSwitchCaseIDs();
  5359. // Offset here is a global offset across the entire chain.
  5360. RecordLocation Loc = getLocalBitOffset(Offset);
  5361. Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
  5362. return ReadStmtFromStream(*Loc.F);
  5363. }
  5364. namespace {
  5365. class FindExternalLexicalDeclsVisitor {
  5366. ASTReader &Reader;
  5367. const DeclContext *DC;
  5368. bool (*isKindWeWant)(Decl::Kind);
  5369. SmallVectorImpl<Decl*> &Decls;
  5370. bool PredefsVisited[NUM_PREDEF_DECL_IDS];
  5371. public:
  5372. FindExternalLexicalDeclsVisitor(ASTReader &Reader, const DeclContext *DC,
  5373. bool (*isKindWeWant)(Decl::Kind),
  5374. SmallVectorImpl<Decl*> &Decls)
  5375. : Reader(Reader), DC(DC), isKindWeWant(isKindWeWant), Decls(Decls)
  5376. {
  5377. for (unsigned I = 0; I != NUM_PREDEF_DECL_IDS; ++I)
  5378. PredefsVisited[I] = false;
  5379. }
  5380. static bool visitPostorder(ModuleFile &M, void *UserData) {
  5381. FindExternalLexicalDeclsVisitor *This
  5382. = static_cast<FindExternalLexicalDeclsVisitor *>(UserData);
  5383. ModuleFile::DeclContextInfosMap::iterator Info
  5384. = M.DeclContextInfos.find(This->DC);
  5385. if (Info == M.DeclContextInfos.end() || !Info->second.LexicalDecls)
  5386. return false;
  5387. // Load all of the declaration IDs
  5388. for (const KindDeclIDPair *ID = Info->second.LexicalDecls,
  5389. *IDE = ID + Info->second.NumLexicalDecls;
  5390. ID != IDE; ++ID) {
  5391. if (This->isKindWeWant && !This->isKindWeWant((Decl::Kind)ID->first))
  5392. continue;
  5393. // Don't add predefined declarations to the lexical context more
  5394. // than once.
  5395. if (ID->second < NUM_PREDEF_DECL_IDS) {
  5396. if (This->PredefsVisited[ID->second])
  5397. continue;
  5398. This->PredefsVisited[ID->second] = true;
  5399. }
  5400. if (Decl *D = This->Reader.GetLocalDecl(M, ID->second)) {
  5401. if (!This->DC->isDeclInLexicalTraversal(D))
  5402. This->Decls.push_back(D);
  5403. }
  5404. }
  5405. return false;
  5406. }
  5407. };
  5408. }
  5409. ExternalLoadResult ASTReader::FindExternalLexicalDecls(const DeclContext *DC,
  5410. bool (*isKindWeWant)(Decl::Kind),
  5411. SmallVectorImpl<Decl*> &Decls) {
  5412. // There might be lexical decls in multiple modules, for the TU at
  5413. // least. Walk all of the modules in the order they were loaded.
  5414. FindExternalLexicalDeclsVisitor Visitor(*this, DC, isKindWeWant, Decls);
  5415. ModuleMgr.visitDepthFirst(
  5416. nullptr, &FindExternalLexicalDeclsVisitor::visitPostorder, &Visitor);
  5417. ++NumLexicalDeclContextsRead;
  5418. return ELR_Success;
  5419. }
  5420. namespace {
  5421. class DeclIDComp {
  5422. ASTReader &Reader;
  5423. ModuleFile &Mod;
  5424. public:
  5425. DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
  5426. bool operator()(LocalDeclID L, LocalDeclID R) const {
  5427. SourceLocation LHS = getLocation(L);
  5428. SourceLocation RHS = getLocation(R);
  5429. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5430. }
  5431. bool operator()(SourceLocation LHS, LocalDeclID R) const {
  5432. SourceLocation RHS = getLocation(R);
  5433. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5434. }
  5435. bool operator()(LocalDeclID L, SourceLocation RHS) const {
  5436. SourceLocation LHS = getLocation(L);
  5437. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5438. }
  5439. SourceLocation getLocation(LocalDeclID ID) const {
  5440. return Reader.getSourceManager().getFileLoc(
  5441. Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
  5442. }
  5443. };
  5444. }
  5445. void ASTReader::FindFileRegionDecls(FileID File,
  5446. unsigned Offset, unsigned Length,
  5447. SmallVectorImpl<Decl *> &Decls) {
  5448. SourceManager &SM = getSourceManager();
  5449. llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
  5450. if (I == FileDeclIDs.end())
  5451. return;
  5452. FileDeclsInfo &DInfo = I->second;
  5453. if (DInfo.Decls.empty())
  5454. return;
  5455. SourceLocation
  5456. BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
  5457. SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
  5458. DeclIDComp DIDComp(*this, *DInfo.Mod);
  5459. ArrayRef<serialization::LocalDeclID>::iterator
  5460. BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
  5461. BeginLoc, DIDComp);
  5462. if (BeginIt != DInfo.Decls.begin())
  5463. --BeginIt;
  5464. // If we are pointing at a top-level decl inside an objc container, we need
  5465. // to backtrack until we find it otherwise we will fail to report that the
  5466. // region overlaps with an objc container.
  5467. while (BeginIt != DInfo.Decls.begin() &&
  5468. GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
  5469. ->isTopLevelDeclInObjCContainer())
  5470. --BeginIt;
  5471. ArrayRef<serialization::LocalDeclID>::iterator
  5472. EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
  5473. EndLoc, DIDComp);
  5474. if (EndIt != DInfo.Decls.end())
  5475. ++EndIt;
  5476. for (ArrayRef<serialization::LocalDeclID>::iterator
  5477. DIt = BeginIt; DIt != EndIt; ++DIt)
  5478. Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
  5479. }
  5480. /// \brief Retrieve the "definitive" module file for the definition of the
  5481. /// given declaration context, if there is one.
  5482. ///
  5483. /// The "definitive" module file is the only place where we need to look to
  5484. /// find information about the declarations within the given declaration
  5485. /// context. For example, C++ and Objective-C classes, C structs/unions, and
  5486. /// Objective-C protocols, categories, and extensions are all defined in a
  5487. /// single place in the source code, so they have definitive module files
  5488. /// associated with them. C++ namespaces, on the other hand, can have
  5489. /// definitions in multiple different module files.
  5490. ///
  5491. /// Note: this needs to be kept in sync with ASTWriter::AddedVisibleDecl's
  5492. /// NDEBUG checking.
  5493. static ModuleFile *getDefinitiveModuleFileFor(const DeclContext *DC,
  5494. ASTReader &Reader) {
  5495. if (const DeclContext *DefDC = getDefinitiveDeclContext(DC))
  5496. return Reader.getOwningModuleFile(cast<Decl>(DefDC));
  5497. return nullptr;
  5498. }
  5499. namespace {
  5500. /// \brief ModuleFile visitor used to perform name lookup into a
  5501. /// declaration context.
  5502. class DeclContextNameLookupVisitor {
  5503. ASTReader &Reader;
  5504. ArrayRef<const DeclContext *> Contexts;
  5505. DeclarationName Name;
  5506. ASTDeclContextNameLookupTrait::DeclNameKey NameKey;
  5507. unsigned NameHash;
  5508. SmallVectorImpl<NamedDecl *> &Decls;
  5509. llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet;
  5510. public:
  5511. DeclContextNameLookupVisitor(ASTReader &Reader,
  5512. DeclarationName Name,
  5513. SmallVectorImpl<NamedDecl *> &Decls,
  5514. llvm::SmallPtrSetImpl<NamedDecl *> &DeclSet)
  5515. : Reader(Reader), Name(Name),
  5516. NameKey(ASTDeclContextNameLookupTrait::GetInternalKey(Name)),
  5517. NameHash(ASTDeclContextNameLookupTrait::ComputeHash(NameKey)),
  5518. Decls(Decls), DeclSet(DeclSet) {}
  5519. void visitContexts(ArrayRef<const DeclContext*> Contexts) {
  5520. if (Contexts.empty())
  5521. return;
  5522. this->Contexts = Contexts;
  5523. // If we can definitively determine which module file to look into,
  5524. // only look there. Otherwise, look in all module files.
  5525. ModuleFile *Definitive;
  5526. if (Contexts.size() == 1 &&
  5527. (Definitive = getDefinitiveModuleFileFor(Contexts[0], Reader))) {
  5528. visit(*Definitive, this);
  5529. } else {
  5530. Reader.getModuleManager().visit(&visit, this);
  5531. }
  5532. }
  5533. private:
  5534. static bool visit(ModuleFile &M, void *UserData) {
  5535. DeclContextNameLookupVisitor *This
  5536. = static_cast<DeclContextNameLookupVisitor *>(UserData);
  5537. // Check whether we have any visible declaration information for
  5538. // this context in this module.
  5539. ModuleFile::DeclContextInfosMap::iterator Info;
  5540. bool FoundInfo = false;
  5541. for (auto *DC : This->Contexts) {
  5542. Info = M.DeclContextInfos.find(DC);
  5543. if (Info != M.DeclContextInfos.end() &&
  5544. Info->second.NameLookupTableData) {
  5545. FoundInfo = true;
  5546. break;
  5547. }
  5548. }
  5549. if (!FoundInfo)
  5550. return false;
  5551. // Look for this name within this module.
  5552. ASTDeclContextNameLookupTable *LookupTable =
  5553. Info->second.NameLookupTableData;
  5554. ASTDeclContextNameLookupTable::iterator Pos
  5555. = LookupTable->find_hashed(This->NameKey, This->NameHash);
  5556. if (Pos == LookupTable->end())
  5557. return false;
  5558. bool FoundAnything = false;
  5559. ASTDeclContextNameLookupTrait::data_type Data = *Pos;
  5560. for (; Data.first != Data.second; ++Data.first) {
  5561. NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M, *Data.first);
  5562. if (!ND)
  5563. continue;
  5564. if (ND->getDeclName() != This->Name) {
  5565. // A name might be null because the decl's redeclarable part is
  5566. // currently read before reading its name. The lookup is triggered by
  5567. // building that decl (likely indirectly), and so it is later in the
  5568. // sense of "already existing" and can be ignored here.
  5569. // FIXME: This should not happen; deserializing declarations should
  5570. // not perform lookups since that can lead to deserialization cycles.
  5571. continue;
  5572. }
  5573. // Record this declaration.
  5574. FoundAnything = true;
  5575. if (This->DeclSet.insert(ND).second)
  5576. This->Decls.push_back(ND);
  5577. }
  5578. return FoundAnything;
  5579. }
  5580. };
  5581. }
  5582. bool
  5583. ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
  5584. DeclarationName Name) {
  5585. assert(DC->hasExternalVisibleStorage() &&
  5586. "DeclContext has no visible decls in storage");
  5587. if (!Name)
  5588. return false;
  5589. Deserializing LookupResults(this);
  5590. SmallVector<NamedDecl *, 64> Decls;
  5591. llvm::SmallPtrSet<NamedDecl*, 64> DeclSet;
  5592. // Compute the declaration contexts we need to look into. Multiple such
  5593. // declaration contexts occur when two declaration contexts from disjoint
  5594. // modules get merged, e.g., when two namespaces with the same name are
  5595. // independently defined in separate modules.
  5596. SmallVector<const DeclContext *, 2> Contexts;
  5597. Contexts.push_back(DC);
  5598. if (DC->isNamespace()) {
  5599. auto Key = KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
  5600. if (Key != KeyDecls.end()) {
  5601. for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
  5602. Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
  5603. }
  5604. }
  5605. DeclContextNameLookupVisitor Visitor(*this, Name, Decls, DeclSet);
  5606. Visitor.visitContexts(Contexts);
  5607. // If this might be an implicit special member function, then also search
  5608. // all merged definitions of the surrounding class. We need to search them
  5609. // individually, because finding an entity in one of them doesn't imply that
  5610. // we can't find a different entity in another one.
  5611. if (isa<CXXRecordDecl>(DC)) {
  5612. auto Merged = MergedLookups.find(DC);
  5613. if (Merged != MergedLookups.end()) {
  5614. for (unsigned I = 0; I != Merged->second.size(); ++I) {
  5615. const DeclContext *Context = Merged->second[I];
  5616. Visitor.visitContexts(Context);
  5617. // We might have just added some more merged lookups. If so, our
  5618. // iterator is now invalid, so grab a fresh one before continuing.
  5619. Merged = MergedLookups.find(DC);
  5620. }
  5621. }
  5622. }
  5623. ++NumVisibleDeclContextsRead;
  5624. SetExternalVisibleDeclsForName(DC, Name, Decls);
  5625. return !Decls.empty();
  5626. }
  5627. namespace {
  5628. /// \brief ModuleFile visitor used to retrieve all visible names in a
  5629. /// declaration context.
  5630. class DeclContextAllNamesVisitor {
  5631. ASTReader &Reader;
  5632. SmallVectorImpl<const DeclContext *> &Contexts;
  5633. DeclsMap &Decls;
  5634. llvm::SmallPtrSet<NamedDecl *, 256> DeclSet;
  5635. bool VisitAll;
  5636. public:
  5637. DeclContextAllNamesVisitor(ASTReader &Reader,
  5638. SmallVectorImpl<const DeclContext *> &Contexts,
  5639. DeclsMap &Decls, bool VisitAll)
  5640. : Reader(Reader), Contexts(Contexts), Decls(Decls), VisitAll(VisitAll) { }
  5641. static bool visit(ModuleFile &M, void *UserData) {
  5642. DeclContextAllNamesVisitor *This
  5643. = static_cast<DeclContextAllNamesVisitor *>(UserData);
  5644. // Check whether we have any visible declaration information for
  5645. // this context in this module.
  5646. ModuleFile::DeclContextInfosMap::iterator Info;
  5647. bool FoundInfo = false;
  5648. for (unsigned I = 0, N = This->Contexts.size(); I != N; ++I) {
  5649. Info = M.DeclContextInfos.find(This->Contexts[I]);
  5650. if (Info != M.DeclContextInfos.end() &&
  5651. Info->second.NameLookupTableData) {
  5652. FoundInfo = true;
  5653. break;
  5654. }
  5655. }
  5656. if (!FoundInfo)
  5657. return false;
  5658. ASTDeclContextNameLookupTable *LookupTable =
  5659. Info->second.NameLookupTableData;
  5660. bool FoundAnything = false;
  5661. for (ASTDeclContextNameLookupTable::data_iterator
  5662. I = LookupTable->data_begin(), E = LookupTable->data_end();
  5663. I != E;
  5664. ++I) {
  5665. ASTDeclContextNameLookupTrait::data_type Data = *I;
  5666. for (; Data.first != Data.second; ++Data.first) {
  5667. NamedDecl *ND = This->Reader.GetLocalDeclAs<NamedDecl>(M,
  5668. *Data.first);
  5669. if (!ND)
  5670. continue;
  5671. // Record this declaration.
  5672. FoundAnything = true;
  5673. if (This->DeclSet.insert(ND).second)
  5674. This->Decls[ND->getDeclName()].push_back(ND);
  5675. }
  5676. }
  5677. return FoundAnything && !This->VisitAll;
  5678. }
  5679. };
  5680. }
  5681. void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
  5682. if (!DC->hasExternalVisibleStorage())
  5683. return;
  5684. DeclsMap Decls;
  5685. // Compute the declaration contexts we need to look into. Multiple such
  5686. // declaration contexts occur when two declaration contexts from disjoint
  5687. // modules get merged, e.g., when two namespaces with the same name are
  5688. // independently defined in separate modules.
  5689. SmallVector<const DeclContext *, 2> Contexts;
  5690. Contexts.push_back(DC);
  5691. if (DC->isNamespace()) {
  5692. KeyDeclsMap::iterator Key =
  5693. KeyDecls.find(const_cast<Decl *>(cast<Decl>(DC)));
  5694. if (Key != KeyDecls.end()) {
  5695. for (unsigned I = 0, N = Key->second.size(); I != N; ++I)
  5696. Contexts.push_back(cast<DeclContext>(GetDecl(Key->second[I])));
  5697. }
  5698. }
  5699. DeclContextAllNamesVisitor Visitor(*this, Contexts, Decls,
  5700. /*VisitAll=*/DC->isFileContext());
  5701. ModuleMgr.visit(&DeclContextAllNamesVisitor::visit, &Visitor);
  5702. ++NumVisibleDeclContextsRead;
  5703. for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
  5704. SetExternalVisibleDeclsForName(DC, I->first, I->second);
  5705. }
  5706. const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
  5707. }
  5708. /// \brief Under non-PCH compilation the consumer receives the objc methods
  5709. /// before receiving the implementation, and codegen depends on this.
  5710. /// We simulate this by deserializing and passing to consumer the methods of the
  5711. /// implementation before passing the deserialized implementation decl.
  5712. static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
  5713. ASTConsumer *Consumer) {
  5714. assert(ImplD && Consumer);
  5715. for (auto *I : ImplD->methods())
  5716. Consumer->HandleInterestingDecl(DeclGroupRef(I));
  5717. Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
  5718. }
  5719. void ASTReader::PassInterestingDeclsToConsumer() {
  5720. assert(Consumer);
  5721. if (PassingDeclsToConsumer)
  5722. return;
  5723. // Guard variable to avoid recursively redoing the process of passing
  5724. // decls to consumer.
  5725. SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
  5726. true);
  5727. // Ensure that we've loaded all potentially-interesting declarations
  5728. // that need to be eagerly loaded.
  5729. for (auto ID : EagerlyDeserializedDecls)
  5730. GetDecl(ID);
  5731. EagerlyDeserializedDecls.clear();
  5732. while (!InterestingDecls.empty()) {
  5733. Decl *D = InterestingDecls.front();
  5734. InterestingDecls.pop_front();
  5735. PassInterestingDeclToConsumer(D);
  5736. }
  5737. }
  5738. void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
  5739. if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
  5740. PassObjCImplDeclToConsumer(ImplD, Consumer);
  5741. else
  5742. Consumer->HandleInterestingDecl(DeclGroupRef(D));
  5743. }
  5744. void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
  5745. this->Consumer = Consumer;
  5746. if (Consumer)
  5747. PassInterestingDeclsToConsumer();
  5748. if (DeserializationListener)
  5749. DeserializationListener->ReaderInitialized(this);
  5750. }
  5751. void ASTReader::PrintStats() {
  5752. std::fprintf(stderr, "*** AST File Statistics:\n");
  5753. unsigned NumTypesLoaded
  5754. = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
  5755. QualType());
  5756. unsigned NumDeclsLoaded
  5757. = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
  5758. (Decl *)nullptr);
  5759. unsigned NumIdentifiersLoaded
  5760. = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
  5761. IdentifiersLoaded.end(),
  5762. (IdentifierInfo *)nullptr);
  5763. unsigned NumMacrosLoaded
  5764. = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
  5765. MacrosLoaded.end(),
  5766. (MacroInfo *)nullptr);
  5767. unsigned NumSelectorsLoaded
  5768. = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
  5769. SelectorsLoaded.end(),
  5770. Selector());
  5771. if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
  5772. std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
  5773. NumSLocEntriesRead, TotalNumSLocEntries,
  5774. ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
  5775. if (!TypesLoaded.empty())
  5776. std::fprintf(stderr, " %u/%u types read (%f%%)\n",
  5777. NumTypesLoaded, (unsigned)TypesLoaded.size(),
  5778. ((float)NumTypesLoaded/TypesLoaded.size() * 100));
  5779. if (!DeclsLoaded.empty())
  5780. std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
  5781. NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
  5782. ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
  5783. if (!IdentifiersLoaded.empty())
  5784. std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
  5785. NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
  5786. ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
  5787. if (!MacrosLoaded.empty())
  5788. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  5789. NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
  5790. ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
  5791. if (!SelectorsLoaded.empty())
  5792. std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
  5793. NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
  5794. ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
  5795. if (TotalNumStatements)
  5796. std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
  5797. NumStatementsRead, TotalNumStatements,
  5798. ((float)NumStatementsRead/TotalNumStatements * 100));
  5799. if (TotalNumMacros)
  5800. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  5801. NumMacrosRead, TotalNumMacros,
  5802. ((float)NumMacrosRead/TotalNumMacros * 100));
  5803. if (TotalLexicalDeclContexts)
  5804. std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
  5805. NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
  5806. ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
  5807. * 100));
  5808. if (TotalVisibleDeclContexts)
  5809. std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
  5810. NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
  5811. ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
  5812. * 100));
  5813. if (TotalNumMethodPoolEntries) {
  5814. std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
  5815. NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
  5816. ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
  5817. * 100));
  5818. }
  5819. if (NumMethodPoolLookups) {
  5820. std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
  5821. NumMethodPoolHits, NumMethodPoolLookups,
  5822. ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
  5823. }
  5824. if (NumMethodPoolTableLookups) {
  5825. std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
  5826. NumMethodPoolTableHits, NumMethodPoolTableLookups,
  5827. ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
  5828. * 100.0));
  5829. }
  5830. if (NumIdentifierLookupHits) {
  5831. std::fprintf(stderr,
  5832. " %u / %u identifier table lookups succeeded (%f%%)\n",
  5833. NumIdentifierLookupHits, NumIdentifierLookups,
  5834. (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
  5835. }
  5836. if (GlobalIndex) {
  5837. std::fprintf(stderr, "\n");
  5838. GlobalIndex->printStats();
  5839. }
  5840. std::fprintf(stderr, "\n");
  5841. dump();
  5842. std::fprintf(stderr, "\n");
  5843. }
  5844. template<typename Key, typename ModuleFile, unsigned InitialCapacity>
  5845. static void
  5846. dumpModuleIDMap(StringRef Name,
  5847. const ContinuousRangeMap<Key, ModuleFile *,
  5848. InitialCapacity> &Map) {
  5849. if (Map.begin() == Map.end())
  5850. return;
  5851. typedef ContinuousRangeMap<Key, ModuleFile *, InitialCapacity> MapType;
  5852. llvm::errs() << Name << ":\n";
  5853. for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
  5854. I != IEnd; ++I) {
  5855. llvm::errs() << " " << I->first << " -> " << I->second->FileName
  5856. << "\n";
  5857. }
  5858. }
  5859. void ASTReader::dump() {
  5860. llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
  5861. dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
  5862. dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
  5863. dumpModuleIDMap("Global type map", GlobalTypeMap);
  5864. dumpModuleIDMap("Global declaration map", GlobalDeclMap);
  5865. dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
  5866. dumpModuleIDMap("Global macro map", GlobalMacroMap);
  5867. dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
  5868. dumpModuleIDMap("Global selector map", GlobalSelectorMap);
  5869. dumpModuleIDMap("Global preprocessed entity map",
  5870. GlobalPreprocessedEntityMap);
  5871. llvm::errs() << "\n*** PCH/Modules Loaded:";
  5872. for (ModuleManager::ModuleConstIterator M = ModuleMgr.begin(),
  5873. MEnd = ModuleMgr.end();
  5874. M != MEnd; ++M)
  5875. (*M)->dump();
  5876. }
  5877. /// Return the amount of memory used by memory buffers, breaking down
  5878. /// by heap-backed versus mmap'ed memory.
  5879. void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
  5880. for (ModuleConstIterator I = ModuleMgr.begin(),
  5881. E = ModuleMgr.end(); I != E; ++I) {
  5882. if (llvm::MemoryBuffer *buf = (*I)->Buffer.get()) {
  5883. size_t bytes = buf->getBufferSize();
  5884. switch (buf->getBufferKind()) {
  5885. case llvm::MemoryBuffer::MemoryBuffer_Malloc:
  5886. sizes.malloc_bytes += bytes;
  5887. break;
  5888. case llvm::MemoryBuffer::MemoryBuffer_MMap:
  5889. sizes.mmap_bytes += bytes;
  5890. break;
  5891. }
  5892. }
  5893. }
  5894. }
  5895. void ASTReader::InitializeSema(Sema &S) {
  5896. SemaObj = &S;
  5897. S.addExternalSource(this);
  5898. // Makes sure any declarations that were deserialized "too early"
  5899. // still get added to the identifier's declaration chains.
  5900. for (uint64_t ID : PreloadedDeclIDs) {
  5901. NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
  5902. pushExternalDeclIntoScope(D, D->getDeclName());
  5903. }
  5904. PreloadedDeclIDs.clear();
  5905. // FIXME: What happens if these are changed by a module import?
  5906. if (!FPPragmaOptions.empty()) {
  5907. assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
  5908. SemaObj->FPFeatures.fp_contract = FPPragmaOptions[0];
  5909. }
  5910. // FIXME: What happens if these are changed by a module import?
  5911. if (!OpenCLExtensions.empty()) {
  5912. unsigned I = 0;
  5913. #define OPENCLEXT(nm) SemaObj->OpenCLFeatures.nm = OpenCLExtensions[I++];
  5914. #include "clang/Basic/OpenCLExtensions.def"
  5915. assert(OpenCLExtensions.size() == I && "Wrong number of OPENCL_EXTENSIONS");
  5916. }
  5917. UpdateSema();
  5918. }
  5919. void ASTReader::UpdateSema() {
  5920. assert(SemaObj && "no Sema to update");
  5921. // Load the offsets of the declarations that Sema references.
  5922. // They will be lazily deserialized when needed.
  5923. if (!SemaDeclRefs.empty()) {
  5924. assert(SemaDeclRefs.size() % 2 == 0);
  5925. for (unsigned I = 0; I != SemaDeclRefs.size(); I += 2) {
  5926. if (!SemaObj->StdNamespace)
  5927. SemaObj->StdNamespace = SemaDeclRefs[I];
  5928. if (!SemaObj->StdBadAlloc)
  5929. SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
  5930. }
  5931. SemaDeclRefs.clear();
  5932. }
  5933. // Update the state of 'pragma clang optimize'. Use the same API as if we had
  5934. // encountered the pragma in the source.
  5935. if(OptimizeOffPragmaLocation.isValid())
  5936. SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
  5937. }
  5938. IdentifierInfo* ASTReader::get(const char *NameStart, const char *NameEnd) {
  5939. // Note that we are loading an identifier.
  5940. Deserializing AnIdentifier(this);
  5941. StringRef Name(NameStart, NameEnd - NameStart);
  5942. // If there is a global index, look there first to determine which modules
  5943. // provably do not have any results for this identifier.
  5944. GlobalModuleIndex::HitSet Hits;
  5945. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  5946. if (!loadGlobalIndex()) {
  5947. if (GlobalIndex->lookupIdentifier(Name, Hits)) {
  5948. HitsPtr = &Hits;
  5949. }
  5950. }
  5951. IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
  5952. NumIdentifierLookups,
  5953. NumIdentifierLookupHits);
  5954. ModuleMgr.visit(IdentifierLookupVisitor::visit, &Visitor, HitsPtr);
  5955. IdentifierInfo *II = Visitor.getIdentifierInfo();
  5956. markIdentifierUpToDate(II);
  5957. return II;
  5958. }
  5959. namespace clang {
  5960. /// \brief An identifier-lookup iterator that enumerates all of the
  5961. /// identifiers stored within a set of AST files.
  5962. class ASTIdentifierIterator : public IdentifierIterator {
  5963. /// \brief The AST reader whose identifiers are being enumerated.
  5964. const ASTReader &Reader;
  5965. /// \brief The current index into the chain of AST files stored in
  5966. /// the AST reader.
  5967. unsigned Index;
  5968. /// \brief The current position within the identifier lookup table
  5969. /// of the current AST file.
  5970. ASTIdentifierLookupTable::key_iterator Current;
  5971. /// \brief The end position within the identifier lookup table of
  5972. /// the current AST file.
  5973. ASTIdentifierLookupTable::key_iterator End;
  5974. public:
  5975. explicit ASTIdentifierIterator(const ASTReader &Reader);
  5976. StringRef Next() override;
  5977. };
  5978. }
  5979. ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader)
  5980. : Reader(Reader), Index(Reader.ModuleMgr.size() - 1) {
  5981. ASTIdentifierLookupTable *IdTable
  5982. = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].IdentifierLookupTable;
  5983. Current = IdTable->key_begin();
  5984. End = IdTable->key_end();
  5985. }
  5986. StringRef ASTIdentifierIterator::Next() {
  5987. while (Current == End) {
  5988. // If we have exhausted all of our AST files, we're done.
  5989. if (Index == 0)
  5990. return StringRef();
  5991. --Index;
  5992. ASTIdentifierLookupTable *IdTable
  5993. = (ASTIdentifierLookupTable *)Reader.ModuleMgr[Index].
  5994. IdentifierLookupTable;
  5995. Current = IdTable->key_begin();
  5996. End = IdTable->key_end();
  5997. }
  5998. // We have any identifiers remaining in the current AST file; return
  5999. // the next one.
  6000. StringRef Result = *Current;
  6001. ++Current;
  6002. return Result;
  6003. }
  6004. IdentifierIterator *ASTReader::getIdentifiers() {
  6005. if (!loadGlobalIndex())
  6006. return GlobalIndex->createIdentifierIterator();
  6007. return new ASTIdentifierIterator(*this);
  6008. }
  6009. namespace clang { namespace serialization {
  6010. class ReadMethodPoolVisitor {
  6011. ASTReader &Reader;
  6012. Selector Sel;
  6013. unsigned PriorGeneration;
  6014. unsigned InstanceBits;
  6015. unsigned FactoryBits;
  6016. bool InstanceHasMoreThanOneDecl;
  6017. bool FactoryHasMoreThanOneDecl;
  6018. SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
  6019. SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
  6020. public:
  6021. ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
  6022. unsigned PriorGeneration)
  6023. : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration),
  6024. InstanceBits(0), FactoryBits(0), InstanceHasMoreThanOneDecl(false),
  6025. FactoryHasMoreThanOneDecl(false) {}
  6026. static bool visit(ModuleFile &M, void *UserData) {
  6027. ReadMethodPoolVisitor *This
  6028. = static_cast<ReadMethodPoolVisitor *>(UserData);
  6029. if (!M.SelectorLookupTable)
  6030. return false;
  6031. // If we've already searched this module file, skip it now.
  6032. if (M.Generation <= This->PriorGeneration)
  6033. return true;
  6034. ++This->Reader.NumMethodPoolTableLookups;
  6035. ASTSelectorLookupTable *PoolTable
  6036. = (ASTSelectorLookupTable*)M.SelectorLookupTable;
  6037. ASTSelectorLookupTable::iterator Pos = PoolTable->find(This->Sel);
  6038. if (Pos == PoolTable->end())
  6039. return false;
  6040. ++This->Reader.NumMethodPoolTableHits;
  6041. ++This->Reader.NumSelectorsRead;
  6042. // FIXME: Not quite happy with the statistics here. We probably should
  6043. // disable this tracking when called via LoadSelector.
  6044. // Also, should entries without methods count as misses?
  6045. ++This->Reader.NumMethodPoolEntriesRead;
  6046. ASTSelectorLookupTrait::data_type Data = *Pos;
  6047. if (This->Reader.DeserializationListener)
  6048. This->Reader.DeserializationListener->SelectorRead(Data.ID,
  6049. This->Sel);
  6050. This->InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
  6051. This->FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
  6052. This->InstanceBits = Data.InstanceBits;
  6053. This->FactoryBits = Data.FactoryBits;
  6054. This->InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
  6055. This->FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
  6056. return true;
  6057. }
  6058. /// \brief Retrieve the instance methods found by this visitor.
  6059. ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
  6060. return InstanceMethods;
  6061. }
  6062. /// \brief Retrieve the instance methods found by this visitor.
  6063. ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
  6064. return FactoryMethods;
  6065. }
  6066. unsigned getInstanceBits() const { return InstanceBits; }
  6067. unsigned getFactoryBits() const { return FactoryBits; }
  6068. bool instanceHasMoreThanOneDecl() const {
  6069. return InstanceHasMoreThanOneDecl;
  6070. }
  6071. bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
  6072. };
  6073. } } // end namespace clang::serialization
  6074. /// \brief Add the given set of methods to the method list.
  6075. static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
  6076. ObjCMethodList &List) {
  6077. for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
  6078. S.addMethodToGlobalList(&List, Methods[I]);
  6079. }
  6080. }
  6081. void ASTReader::ReadMethodPool(Selector Sel) {
  6082. // Get the selector generation and update it to the current generation.
  6083. unsigned &Generation = SelectorGeneration[Sel];
  6084. unsigned PriorGeneration = Generation;
  6085. Generation = getGeneration();
  6086. // Search for methods defined with this selector.
  6087. ++NumMethodPoolLookups;
  6088. ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
  6089. ModuleMgr.visit(&ReadMethodPoolVisitor::visit, &Visitor);
  6090. if (Visitor.getInstanceMethods().empty() &&
  6091. Visitor.getFactoryMethods().empty())
  6092. return;
  6093. ++NumMethodPoolHits;
  6094. if (!getSema())
  6095. return;
  6096. Sema &S = *getSema();
  6097. Sema::GlobalMethodPool::iterator Pos
  6098. = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
  6099. Pos->second.first.setBits(Visitor.getInstanceBits());
  6100. Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
  6101. Pos->second.second.setBits(Visitor.getFactoryBits());
  6102. Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
  6103. // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
  6104. // when building a module we keep every method individually and may need to
  6105. // update hasMoreThanOneDecl as we add the methods.
  6106. addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
  6107. addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
  6108. }
  6109. void ASTReader::ReadKnownNamespaces(
  6110. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  6111. Namespaces.clear();
  6112. for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
  6113. if (NamespaceDecl *Namespace
  6114. = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
  6115. Namespaces.push_back(Namespace);
  6116. }
  6117. }
  6118. void ASTReader::ReadUndefinedButUsed(
  6119. llvm::DenseMap<NamedDecl*, SourceLocation> &Undefined) {
  6120. for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
  6121. NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
  6122. SourceLocation Loc =
  6123. SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
  6124. Undefined.insert(std::make_pair(D, Loc));
  6125. }
  6126. }
  6127. void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
  6128. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
  6129. Exprs) {
  6130. for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
  6131. FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
  6132. uint64_t Count = DelayedDeleteExprs[Idx++];
  6133. for (uint64_t C = 0; C < Count; ++C) {
  6134. SourceLocation DeleteLoc =
  6135. SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
  6136. const bool IsArrayForm = DelayedDeleteExprs[Idx++];
  6137. Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
  6138. }
  6139. }
  6140. }
  6141. void ASTReader::ReadTentativeDefinitions(
  6142. SmallVectorImpl<VarDecl *> &TentativeDefs) {
  6143. for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
  6144. VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
  6145. if (Var)
  6146. TentativeDefs.push_back(Var);
  6147. }
  6148. TentativeDefinitions.clear();
  6149. }
  6150. void ASTReader::ReadUnusedFileScopedDecls(
  6151. SmallVectorImpl<const DeclaratorDecl *> &Decls) {
  6152. for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
  6153. DeclaratorDecl *D
  6154. = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
  6155. if (D)
  6156. Decls.push_back(D);
  6157. }
  6158. UnusedFileScopedDecls.clear();
  6159. }
  6160. void ASTReader::ReadDelegatingConstructors(
  6161. SmallVectorImpl<CXXConstructorDecl *> &Decls) {
  6162. for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
  6163. CXXConstructorDecl *D
  6164. = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
  6165. if (D)
  6166. Decls.push_back(D);
  6167. }
  6168. DelegatingCtorDecls.clear();
  6169. }
  6170. void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
  6171. for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
  6172. TypedefNameDecl *D
  6173. = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
  6174. if (D)
  6175. Decls.push_back(D);
  6176. }
  6177. ExtVectorDecls.clear();
  6178. }
  6179. void ASTReader::ReadUnusedLocalTypedefNameCandidates(
  6180. llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
  6181. for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
  6182. ++I) {
  6183. TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
  6184. GetDecl(UnusedLocalTypedefNameCandidates[I]));
  6185. if (D)
  6186. Decls.insert(D);
  6187. }
  6188. UnusedLocalTypedefNameCandidates.clear();
  6189. }
  6190. void ASTReader::ReadReferencedSelectors(
  6191. SmallVectorImpl<std::pair<Selector, SourceLocation> > &Sels) {
  6192. if (ReferencedSelectorsData.empty())
  6193. return;
  6194. // If there are @selector references added them to its pool. This is for
  6195. // implementation of -Wselector.
  6196. unsigned int DataSize = ReferencedSelectorsData.size()-1;
  6197. unsigned I = 0;
  6198. while (I < DataSize) {
  6199. Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
  6200. SourceLocation SelLoc
  6201. = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
  6202. Sels.push_back(std::make_pair(Sel, SelLoc));
  6203. }
  6204. ReferencedSelectorsData.clear();
  6205. }
  6206. void ASTReader::ReadWeakUndeclaredIdentifiers(
  6207. SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo> > &WeakIDs) {
  6208. if (WeakUndeclaredIdentifiers.empty())
  6209. return;
  6210. for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
  6211. IdentifierInfo *WeakId
  6212. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  6213. IdentifierInfo *AliasId
  6214. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  6215. SourceLocation Loc
  6216. = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
  6217. bool Used = WeakUndeclaredIdentifiers[I++];
  6218. WeakInfo WI(AliasId, Loc);
  6219. WI.setUsed(Used);
  6220. WeakIDs.push_back(std::make_pair(WeakId, WI));
  6221. }
  6222. WeakUndeclaredIdentifiers.clear();
  6223. }
  6224. void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
  6225. for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
  6226. ExternalVTableUse VT;
  6227. VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
  6228. VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
  6229. VT.DefinitionRequired = VTableUses[Idx++];
  6230. VTables.push_back(VT);
  6231. }
  6232. VTableUses.clear();
  6233. }
  6234. void ASTReader::ReadPendingInstantiations(
  6235. SmallVectorImpl<std::pair<ValueDecl *, SourceLocation> > &Pending) {
  6236. for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
  6237. ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
  6238. SourceLocation Loc
  6239. = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
  6240. Pending.push_back(std::make_pair(D, Loc));
  6241. }
  6242. PendingInstantiations.clear();
  6243. }
  6244. void ASTReader::ReadLateParsedTemplates(
  6245. llvm::MapVector<const FunctionDecl *, LateParsedTemplate *> &LPTMap) {
  6246. for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
  6247. /* In loop */) {
  6248. FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
  6249. LateParsedTemplate *LT = new LateParsedTemplate;
  6250. LT->D = GetDecl(LateParsedTemplates[Idx++]);
  6251. ModuleFile *F = getOwningModuleFile(LT->D);
  6252. assert(F && "No module");
  6253. unsigned TokN = LateParsedTemplates[Idx++];
  6254. LT->Toks.reserve(TokN);
  6255. for (unsigned T = 0; T < TokN; ++T)
  6256. LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
  6257. LPTMap.insert(std::make_pair(FD, LT));
  6258. }
  6259. LateParsedTemplates.clear();
  6260. }
  6261. void ASTReader::LoadSelector(Selector Sel) {
  6262. // It would be complicated to avoid reading the methods anyway. So don't.
  6263. ReadMethodPool(Sel);
  6264. }
  6265. void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
  6266. assert(ID && "Non-zero identifier ID required");
  6267. assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
  6268. IdentifiersLoaded[ID - 1] = II;
  6269. if (DeserializationListener)
  6270. DeserializationListener->IdentifierRead(ID, II);
  6271. }
  6272. /// \brief Set the globally-visible declarations associated with the given
  6273. /// identifier.
  6274. ///
  6275. /// If the AST reader is currently in a state where the given declaration IDs
  6276. /// cannot safely be resolved, they are queued until it is safe to resolve
  6277. /// them.
  6278. ///
  6279. /// \param II an IdentifierInfo that refers to one or more globally-visible
  6280. /// declarations.
  6281. ///
  6282. /// \param DeclIDs the set of declaration IDs with the name @p II that are
  6283. /// visible at global scope.
  6284. ///
  6285. /// \param Decls if non-null, this vector will be populated with the set of
  6286. /// deserialized declarations. These declarations will not be pushed into
  6287. /// scope.
  6288. void
  6289. ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
  6290. const SmallVectorImpl<uint32_t> &DeclIDs,
  6291. SmallVectorImpl<Decl *> *Decls) {
  6292. if (NumCurrentElementsDeserializing && !Decls) {
  6293. PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
  6294. return;
  6295. }
  6296. for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
  6297. if (!SemaObj) {
  6298. // Queue this declaration so that it will be added to the
  6299. // translation unit scope and identifier's declaration chain
  6300. // once a Sema object is known.
  6301. PreloadedDeclIDs.push_back(DeclIDs[I]);
  6302. continue;
  6303. }
  6304. NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
  6305. // If we're simply supposed to record the declarations, do so now.
  6306. if (Decls) {
  6307. Decls->push_back(D);
  6308. continue;
  6309. }
  6310. // Introduce this declaration into the translation-unit scope
  6311. // and add it to the declaration chain for this identifier, so
  6312. // that (unqualified) name lookup will find it.
  6313. pushExternalDeclIntoScope(D, II);
  6314. }
  6315. }
  6316. IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
  6317. if (ID == 0)
  6318. return nullptr;
  6319. if (IdentifiersLoaded.empty()) {
  6320. Error("no identifier table in AST file");
  6321. return nullptr;
  6322. }
  6323. ID -= 1;
  6324. if (!IdentifiersLoaded[ID]) {
  6325. GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
  6326. assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
  6327. ModuleFile *M = I->second;
  6328. unsigned Index = ID - M->BaseIdentifierID;
  6329. const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
  6330. // All of the strings in the AST file are preceded by a 16-bit length.
  6331. // Extract that 16-bit length to avoid having to execute strlen().
  6332. // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
  6333. // unsigned integers. This is important to avoid integer overflow when
  6334. // we cast them to 'unsigned'.
  6335. const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
  6336. unsigned StrLen = (((unsigned) StrLenPtr[0])
  6337. | (((unsigned) StrLenPtr[1]) << 8)) - 1;
  6338. IdentifiersLoaded[ID]
  6339. = &PP.getIdentifierTable().get(StringRef(Str, StrLen));
  6340. if (DeserializationListener)
  6341. DeserializationListener->IdentifierRead(ID + 1, IdentifiersLoaded[ID]);
  6342. }
  6343. return IdentifiersLoaded[ID];
  6344. }
  6345. IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
  6346. return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
  6347. }
  6348. IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
  6349. if (LocalID < NUM_PREDEF_IDENT_IDS)
  6350. return LocalID;
  6351. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6352. = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
  6353. assert(I != M.IdentifierRemap.end()
  6354. && "Invalid index into identifier index remap");
  6355. return LocalID + I->second;
  6356. }
  6357. MacroInfo *ASTReader::getMacro(MacroID ID) {
  6358. if (ID == 0)
  6359. return nullptr;
  6360. if (MacrosLoaded.empty()) {
  6361. Error("no macro table in AST file");
  6362. return nullptr;
  6363. }
  6364. ID -= NUM_PREDEF_MACRO_IDS;
  6365. if (!MacrosLoaded[ID]) {
  6366. GlobalMacroMapType::iterator I
  6367. = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
  6368. assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
  6369. ModuleFile *M = I->second;
  6370. unsigned Index = ID - M->BaseMacroID;
  6371. MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
  6372. if (DeserializationListener)
  6373. DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
  6374. MacrosLoaded[ID]);
  6375. }
  6376. return MacrosLoaded[ID];
  6377. }
  6378. MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
  6379. if (LocalID < NUM_PREDEF_MACRO_IDS)
  6380. return LocalID;
  6381. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6382. = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
  6383. assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
  6384. return LocalID + I->second;
  6385. }
  6386. serialization::SubmoduleID
  6387. ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
  6388. if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
  6389. return LocalID;
  6390. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6391. = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
  6392. assert(I != M.SubmoduleRemap.end()
  6393. && "Invalid index into submodule index remap");
  6394. return LocalID + I->second;
  6395. }
  6396. Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
  6397. if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
  6398. assert(GlobalID == 0 && "Unhandled global submodule ID");
  6399. return nullptr;
  6400. }
  6401. if (GlobalID > SubmodulesLoaded.size()) {
  6402. Error("submodule ID out of range in AST file");
  6403. return nullptr;
  6404. }
  6405. return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
  6406. }
  6407. Module *ASTReader::getModule(unsigned ID) {
  6408. return getSubmodule(ID);
  6409. }
  6410. ExternalASTSource::ASTSourceDescriptor
  6411. ASTReader::getSourceDescriptor(const Module &M) {
  6412. StringRef Dir, Filename;
  6413. if (M.Directory)
  6414. Dir = M.Directory->getName();
  6415. if (auto *File = M.getASTFile())
  6416. Filename = File->getName();
  6417. return ASTReader::ASTSourceDescriptor{
  6418. M.getFullModuleName(), Dir, Filename,
  6419. M.Signature
  6420. };
  6421. }
  6422. llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
  6423. ASTReader::getSourceDescriptor(unsigned ID) {
  6424. if (const Module *M = getSubmodule(ID))
  6425. return getSourceDescriptor(*M);
  6426. // If there is only a single PCH, return it instead.
  6427. // Chained PCH are not suported.
  6428. if (ModuleMgr.size() == 1) {
  6429. ModuleFile &MF = ModuleMgr.getPrimaryModule();
  6430. return ASTReader::ASTSourceDescriptor{
  6431. MF.OriginalSourceFileName, MF.OriginalDir,
  6432. MF.FileName,
  6433. MF.Signature
  6434. };
  6435. }
  6436. return None;
  6437. }
  6438. Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
  6439. return DecodeSelector(getGlobalSelectorID(M, LocalID));
  6440. }
  6441. Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
  6442. if (ID == 0)
  6443. return Selector();
  6444. if (ID > SelectorsLoaded.size()) {
  6445. Error("selector ID out of range in AST file");
  6446. return Selector();
  6447. }
  6448. if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
  6449. // Load this selector from the selector table.
  6450. GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
  6451. assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
  6452. ModuleFile &M = *I->second;
  6453. ASTSelectorLookupTrait Trait(*this, M);
  6454. unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
  6455. SelectorsLoaded[ID - 1] =
  6456. Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
  6457. if (DeserializationListener)
  6458. DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
  6459. }
  6460. return SelectorsLoaded[ID - 1];
  6461. }
  6462. Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
  6463. return DecodeSelector(ID);
  6464. }
  6465. uint32_t ASTReader::GetNumExternalSelectors() {
  6466. // ID 0 (the null selector) is considered an external selector.
  6467. return getTotalNumSelectors() + 1;
  6468. }
  6469. serialization::SelectorID
  6470. ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
  6471. if (LocalID < NUM_PREDEF_SELECTOR_IDS)
  6472. return LocalID;
  6473. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6474. = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
  6475. assert(I != M.SelectorRemap.end()
  6476. && "Invalid index into selector index remap");
  6477. return LocalID + I->second;
  6478. }
  6479. DeclarationName
  6480. ASTReader::ReadDeclarationName(ModuleFile &F,
  6481. const RecordData &Record, unsigned &Idx) {
  6482. DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
  6483. switch (Kind) {
  6484. case DeclarationName::Identifier:
  6485. return DeclarationName(GetIdentifierInfo(F, Record, Idx));
  6486. case DeclarationName::ObjCZeroArgSelector:
  6487. case DeclarationName::ObjCOneArgSelector:
  6488. case DeclarationName::ObjCMultiArgSelector:
  6489. return DeclarationName(ReadSelector(F, Record, Idx));
  6490. case DeclarationName::CXXConstructorName:
  6491. return Context.DeclarationNames.getCXXConstructorName(
  6492. Context.getCanonicalType(readType(F, Record, Idx)));
  6493. case DeclarationName::CXXDestructorName:
  6494. return Context.DeclarationNames.getCXXDestructorName(
  6495. Context.getCanonicalType(readType(F, Record, Idx)));
  6496. case DeclarationName::CXXConversionFunctionName:
  6497. return Context.DeclarationNames.getCXXConversionFunctionName(
  6498. Context.getCanonicalType(readType(F, Record, Idx)));
  6499. case DeclarationName::CXXOperatorName:
  6500. return Context.DeclarationNames.getCXXOperatorName(
  6501. (OverloadedOperatorKind)Record[Idx++]);
  6502. case DeclarationName::CXXLiteralOperatorName:
  6503. return Context.DeclarationNames.getCXXLiteralOperatorName(
  6504. GetIdentifierInfo(F, Record, Idx));
  6505. case DeclarationName::CXXUsingDirective:
  6506. return DeclarationName::getUsingDirectiveName();
  6507. }
  6508. llvm_unreachable("Invalid NameKind!");
  6509. }
  6510. void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
  6511. DeclarationNameLoc &DNLoc,
  6512. DeclarationName Name,
  6513. const RecordData &Record, unsigned &Idx) {
  6514. switch (Name.getNameKind()) {
  6515. case DeclarationName::CXXConstructorName:
  6516. case DeclarationName::CXXDestructorName:
  6517. case DeclarationName::CXXConversionFunctionName:
  6518. DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
  6519. break;
  6520. case DeclarationName::CXXOperatorName:
  6521. DNLoc.CXXOperatorName.BeginOpNameLoc
  6522. = ReadSourceLocation(F, Record, Idx).getRawEncoding();
  6523. DNLoc.CXXOperatorName.EndOpNameLoc
  6524. = ReadSourceLocation(F, Record, Idx).getRawEncoding();
  6525. break;
  6526. case DeclarationName::CXXLiteralOperatorName:
  6527. DNLoc.CXXLiteralOperatorName.OpNameLoc
  6528. = ReadSourceLocation(F, Record, Idx).getRawEncoding();
  6529. break;
  6530. case DeclarationName::Identifier:
  6531. case DeclarationName::ObjCZeroArgSelector:
  6532. case DeclarationName::ObjCOneArgSelector:
  6533. case DeclarationName::ObjCMultiArgSelector:
  6534. case DeclarationName::CXXUsingDirective:
  6535. break;
  6536. }
  6537. }
  6538. void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
  6539. DeclarationNameInfo &NameInfo,
  6540. const RecordData &Record, unsigned &Idx) {
  6541. NameInfo.setName(ReadDeclarationName(F, Record, Idx));
  6542. NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
  6543. DeclarationNameLoc DNLoc;
  6544. ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
  6545. NameInfo.setInfo(DNLoc);
  6546. }
  6547. void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
  6548. const RecordData &Record, unsigned &Idx) {
  6549. Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
  6550. unsigned NumTPLists = Record[Idx++];
  6551. Info.NumTemplParamLists = NumTPLists;
  6552. if (NumTPLists) {
  6553. Info.TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
  6554. for (unsigned i=0; i != NumTPLists; ++i)
  6555. Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
  6556. }
  6557. }
  6558. TemplateName
  6559. ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
  6560. unsigned &Idx) {
  6561. TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
  6562. switch (Kind) {
  6563. case TemplateName::Template:
  6564. return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
  6565. case TemplateName::OverloadedTemplate: {
  6566. unsigned size = Record[Idx++];
  6567. UnresolvedSet<8> Decls;
  6568. while (size--)
  6569. Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
  6570. return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
  6571. }
  6572. case TemplateName::QualifiedTemplate: {
  6573. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
  6574. bool hasTemplKeyword = Record[Idx++];
  6575. TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
  6576. return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
  6577. }
  6578. case TemplateName::DependentTemplate: {
  6579. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
  6580. if (Record[Idx++]) // isIdentifier
  6581. return Context.getDependentTemplateName(NNS,
  6582. GetIdentifierInfo(F, Record,
  6583. Idx));
  6584. return Context.getDependentTemplateName(NNS,
  6585. (OverloadedOperatorKind)Record[Idx++]);
  6586. }
  6587. case TemplateName::SubstTemplateTemplateParm: {
  6588. TemplateTemplateParmDecl *param
  6589. = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
  6590. if (!param) return TemplateName();
  6591. TemplateName replacement = ReadTemplateName(F, Record, Idx);
  6592. return Context.getSubstTemplateTemplateParm(param, replacement);
  6593. }
  6594. case TemplateName::SubstTemplateTemplateParmPack: {
  6595. TemplateTemplateParmDecl *Param
  6596. = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
  6597. if (!Param)
  6598. return TemplateName();
  6599. TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
  6600. if (ArgPack.getKind() != TemplateArgument::Pack)
  6601. return TemplateName();
  6602. return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
  6603. }
  6604. }
  6605. llvm_unreachable("Unhandled template name kind!");
  6606. }
  6607. TemplateArgument
  6608. ASTReader::ReadTemplateArgument(ModuleFile &F,
  6609. const RecordData &Record, unsigned &Idx) {
  6610. TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
  6611. switch (Kind) {
  6612. case TemplateArgument::Null:
  6613. return TemplateArgument();
  6614. case TemplateArgument::Type:
  6615. return TemplateArgument(readType(F, Record, Idx));
  6616. case TemplateArgument::Declaration: {
  6617. ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
  6618. return TemplateArgument(D, readType(F, Record, Idx));
  6619. }
  6620. case TemplateArgument::NullPtr:
  6621. return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
  6622. case TemplateArgument::Integral: {
  6623. llvm::APSInt Value = ReadAPSInt(Record, Idx);
  6624. QualType T = readType(F, Record, Idx);
  6625. return TemplateArgument(Context, Value, T);
  6626. }
  6627. case TemplateArgument::Template:
  6628. return TemplateArgument(ReadTemplateName(F, Record, Idx));
  6629. case TemplateArgument::TemplateExpansion: {
  6630. TemplateName Name = ReadTemplateName(F, Record, Idx);
  6631. Optional<unsigned> NumTemplateExpansions;
  6632. if (unsigned NumExpansions = Record[Idx++])
  6633. NumTemplateExpansions = NumExpansions - 1;
  6634. return TemplateArgument(Name, NumTemplateExpansions);
  6635. }
  6636. case TemplateArgument::Expression:
  6637. return TemplateArgument(ReadExpr(F));
  6638. case TemplateArgument::Pack: {
  6639. unsigned NumArgs = Record[Idx++];
  6640. TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
  6641. for (unsigned I = 0; I != NumArgs; ++I)
  6642. Args[I] = ReadTemplateArgument(F, Record, Idx);
  6643. return TemplateArgument(Args, NumArgs);
  6644. }
  6645. }
  6646. llvm_unreachable("Unhandled template argument kind!");
  6647. }
  6648. TemplateParameterList *
  6649. ASTReader::ReadTemplateParameterList(ModuleFile &F,
  6650. const RecordData &Record, unsigned &Idx) {
  6651. SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
  6652. SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
  6653. SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
  6654. unsigned NumParams = Record[Idx++];
  6655. SmallVector<NamedDecl *, 16> Params;
  6656. Params.reserve(NumParams);
  6657. while (NumParams--)
  6658. Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
  6659. TemplateParameterList* TemplateParams =
  6660. TemplateParameterList::Create(Context, TemplateLoc, LAngleLoc,
  6661. Params.data(), Params.size(), RAngleLoc);
  6662. return TemplateParams;
  6663. }
  6664. void
  6665. ASTReader::
  6666. ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
  6667. ModuleFile &F, const RecordData &Record,
  6668. unsigned &Idx) {
  6669. unsigned NumTemplateArgs = Record[Idx++];
  6670. TemplArgs.reserve(NumTemplateArgs);
  6671. while (NumTemplateArgs--)
  6672. TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx));
  6673. }
  6674. /// \brief Read a UnresolvedSet structure.
  6675. void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
  6676. const RecordData &Record, unsigned &Idx) {
  6677. unsigned NumDecls = Record[Idx++];
  6678. Set.reserve(Context, NumDecls);
  6679. while (NumDecls--) {
  6680. DeclID ID = ReadDeclID(F, Record, Idx);
  6681. AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
  6682. Set.addLazyDecl(Context, ID, AS);
  6683. }
  6684. }
  6685. CXXBaseSpecifier
  6686. ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
  6687. const RecordData &Record, unsigned &Idx) {
  6688. bool isVirtual = static_cast<bool>(Record[Idx++]);
  6689. bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
  6690. AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
  6691. bool inheritConstructors = static_cast<bool>(Record[Idx++]);
  6692. TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
  6693. SourceRange Range = ReadSourceRange(F, Record, Idx);
  6694. SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
  6695. CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
  6696. EllipsisLoc);
  6697. Result.setInheritConstructors(inheritConstructors);
  6698. return Result;
  6699. }
  6700. CXXCtorInitializer **
  6701. ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
  6702. unsigned &Idx) {
  6703. unsigned NumInitializers = Record[Idx++];
  6704. assert(NumInitializers && "wrote ctor initializers but have no inits");
  6705. auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
  6706. for (unsigned i = 0; i != NumInitializers; ++i) {
  6707. TypeSourceInfo *TInfo = nullptr;
  6708. bool IsBaseVirtual = false;
  6709. FieldDecl *Member = nullptr;
  6710. IndirectFieldDecl *IndirectMember = nullptr;
  6711. CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
  6712. switch (Type) {
  6713. case CTOR_INITIALIZER_BASE:
  6714. TInfo = GetTypeSourceInfo(F, Record, Idx);
  6715. IsBaseVirtual = Record[Idx++];
  6716. break;
  6717. case CTOR_INITIALIZER_DELEGATING:
  6718. TInfo = GetTypeSourceInfo(F, Record, Idx);
  6719. break;
  6720. case CTOR_INITIALIZER_MEMBER:
  6721. Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
  6722. break;
  6723. case CTOR_INITIALIZER_INDIRECT_MEMBER:
  6724. IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
  6725. break;
  6726. }
  6727. SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
  6728. Expr *Init = ReadExpr(F);
  6729. SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
  6730. SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
  6731. bool IsWritten = Record[Idx++];
  6732. unsigned SourceOrderOrNumArrayIndices;
  6733. SmallVector<VarDecl *, 8> Indices;
  6734. if (IsWritten) {
  6735. SourceOrderOrNumArrayIndices = Record[Idx++];
  6736. } else {
  6737. SourceOrderOrNumArrayIndices = Record[Idx++];
  6738. Indices.reserve(SourceOrderOrNumArrayIndices);
  6739. for (unsigned i=0; i != SourceOrderOrNumArrayIndices; ++i)
  6740. Indices.push_back(ReadDeclAs<VarDecl>(F, Record, Idx));
  6741. }
  6742. CXXCtorInitializer *BOMInit;
  6743. if (Type == CTOR_INITIALIZER_BASE) {
  6744. BOMInit = new (Context)
  6745. CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
  6746. RParenLoc, MemberOrEllipsisLoc);
  6747. } else if (Type == CTOR_INITIALIZER_DELEGATING) {
  6748. BOMInit = new (Context)
  6749. CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
  6750. } else if (IsWritten) {
  6751. if (Member)
  6752. BOMInit = new (Context) CXXCtorInitializer(
  6753. Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc);
  6754. else
  6755. BOMInit = new (Context)
  6756. CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
  6757. LParenLoc, Init, RParenLoc);
  6758. } else {
  6759. if (IndirectMember) {
  6760. assert(Indices.empty() && "Indirect field improperly initialized");
  6761. BOMInit = new (Context)
  6762. CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
  6763. LParenLoc, Init, RParenLoc);
  6764. } else {
  6765. BOMInit = CXXCtorInitializer::Create(
  6766. Context, Member, MemberOrEllipsisLoc, LParenLoc, Init, RParenLoc,
  6767. Indices.data(), Indices.size());
  6768. }
  6769. }
  6770. if (IsWritten)
  6771. BOMInit->setSourceOrder(SourceOrderOrNumArrayIndices);
  6772. CtorInitializers[i] = BOMInit;
  6773. }
  6774. return CtorInitializers;
  6775. }
  6776. NestedNameSpecifier *
  6777. ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
  6778. const RecordData &Record, unsigned &Idx) {
  6779. unsigned N = Record[Idx++];
  6780. NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
  6781. for (unsigned I = 0; I != N; ++I) {
  6782. NestedNameSpecifier::SpecifierKind Kind
  6783. = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
  6784. switch (Kind) {
  6785. case NestedNameSpecifier::Identifier: {
  6786. IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
  6787. NNS = NestedNameSpecifier::Create(Context, Prev, II);
  6788. break;
  6789. }
  6790. case NestedNameSpecifier::Namespace: {
  6791. NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
  6792. NNS = NestedNameSpecifier::Create(Context, Prev, NS);
  6793. break;
  6794. }
  6795. case NestedNameSpecifier::NamespaceAlias: {
  6796. NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
  6797. NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
  6798. break;
  6799. }
  6800. case NestedNameSpecifier::TypeSpec:
  6801. case NestedNameSpecifier::TypeSpecWithTemplate: {
  6802. const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
  6803. if (!T)
  6804. return nullptr;
  6805. bool Template = Record[Idx++];
  6806. NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
  6807. break;
  6808. }
  6809. case NestedNameSpecifier::Global: {
  6810. NNS = NestedNameSpecifier::GlobalSpecifier(Context);
  6811. // No associated value, and there can't be a prefix.
  6812. break;
  6813. }
  6814. case NestedNameSpecifier::Super: {
  6815. CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
  6816. NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
  6817. break;
  6818. }
  6819. }
  6820. Prev = NNS;
  6821. }
  6822. return NNS;
  6823. }
  6824. NestedNameSpecifierLoc
  6825. ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
  6826. unsigned &Idx) {
  6827. unsigned N = Record[Idx++];
  6828. NestedNameSpecifierLocBuilder Builder;
  6829. for (unsigned I = 0; I != N; ++I) {
  6830. NestedNameSpecifier::SpecifierKind Kind
  6831. = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
  6832. switch (Kind) {
  6833. case NestedNameSpecifier::Identifier: {
  6834. IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
  6835. SourceRange Range = ReadSourceRange(F, Record, Idx);
  6836. Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
  6837. break;
  6838. }
  6839. case NestedNameSpecifier::Namespace: {
  6840. NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
  6841. SourceRange Range = ReadSourceRange(F, Record, Idx);
  6842. Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
  6843. break;
  6844. }
  6845. case NestedNameSpecifier::NamespaceAlias: {
  6846. NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
  6847. SourceRange Range = ReadSourceRange(F, Record, Idx);
  6848. Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
  6849. break;
  6850. }
  6851. case NestedNameSpecifier::TypeSpec:
  6852. case NestedNameSpecifier::TypeSpecWithTemplate: {
  6853. bool Template = Record[Idx++];
  6854. TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
  6855. if (!T)
  6856. return NestedNameSpecifierLoc();
  6857. SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
  6858. // FIXME: 'template' keyword location not saved anywhere, so we fake it.
  6859. Builder.Extend(Context,
  6860. Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
  6861. T->getTypeLoc(), ColonColonLoc);
  6862. break;
  6863. }
  6864. case NestedNameSpecifier::Global: {
  6865. SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
  6866. Builder.MakeGlobal(Context, ColonColonLoc);
  6867. break;
  6868. }
  6869. case NestedNameSpecifier::Super: {
  6870. CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
  6871. SourceRange Range = ReadSourceRange(F, Record, Idx);
  6872. Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
  6873. break;
  6874. }
  6875. }
  6876. }
  6877. return Builder.getWithLocInContext(Context);
  6878. }
  6879. SourceRange
  6880. ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
  6881. unsigned &Idx) {
  6882. SourceLocation beg = ReadSourceLocation(F, Record, Idx);
  6883. SourceLocation end = ReadSourceLocation(F, Record, Idx);
  6884. return SourceRange(beg, end);
  6885. }
  6886. /// \brief Read an integral value
  6887. llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
  6888. unsigned BitWidth = Record[Idx++];
  6889. unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
  6890. llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
  6891. Idx += NumWords;
  6892. return Result;
  6893. }
  6894. /// \brief Read a signed integral value
  6895. llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
  6896. bool isUnsigned = Record[Idx++];
  6897. return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
  6898. }
  6899. /// \brief Read a floating-point value
  6900. llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
  6901. const llvm::fltSemantics &Sem,
  6902. unsigned &Idx) {
  6903. return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
  6904. }
  6905. // \brief Read a string
  6906. std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
  6907. unsigned Len = Record[Idx++];
  6908. std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
  6909. Idx += Len;
  6910. return Result;
  6911. }
  6912. std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
  6913. unsigned &Idx) {
  6914. std::string Filename = ReadString(Record, Idx);
  6915. ResolveImportedPath(F, Filename);
  6916. return Filename;
  6917. }
  6918. VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
  6919. unsigned &Idx) {
  6920. unsigned Major = Record[Idx++];
  6921. unsigned Minor = Record[Idx++];
  6922. unsigned Subminor = Record[Idx++];
  6923. if (Minor == 0)
  6924. return VersionTuple(Major);
  6925. if (Subminor == 0)
  6926. return VersionTuple(Major, Minor - 1);
  6927. return VersionTuple(Major, Minor - 1, Subminor - 1);
  6928. }
  6929. CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
  6930. const RecordData &Record,
  6931. unsigned &Idx) {
  6932. CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
  6933. return CXXTemporary::Create(Context, Decl);
  6934. }
  6935. DiagnosticBuilder ASTReader::Diag(unsigned DiagID) {
  6936. return Diag(CurrentImportLoc, DiagID);
  6937. }
  6938. DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) {
  6939. return Diags.Report(Loc, DiagID);
  6940. }
  6941. /// \brief Retrieve the identifier table associated with the
  6942. /// preprocessor.
  6943. IdentifierTable &ASTReader::getIdentifierTable() {
  6944. return PP.getIdentifierTable();
  6945. }
  6946. /// \brief Record that the given ID maps to the given switch-case
  6947. /// statement.
  6948. void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
  6949. assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
  6950. "Already have a SwitchCase with this ID");
  6951. (*CurrSwitchCaseStmts)[ID] = SC;
  6952. }
  6953. /// \brief Retrieve the switch-case statement with the given ID.
  6954. SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
  6955. assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
  6956. return (*CurrSwitchCaseStmts)[ID];
  6957. }
  6958. void ASTReader::ClearSwitchCaseIDs() {
  6959. CurrSwitchCaseStmts->clear();
  6960. }
  6961. void ASTReader::ReadComments() {
  6962. std::vector<RawComment *> Comments;
  6963. for (SmallVectorImpl<std::pair<BitstreamCursor,
  6964. serialization::ModuleFile *> >::iterator
  6965. I = CommentsCursors.begin(),
  6966. E = CommentsCursors.end();
  6967. I != E; ++I) {
  6968. Comments.clear();
  6969. BitstreamCursor &Cursor = I->first;
  6970. serialization::ModuleFile &F = *I->second;
  6971. SavedStreamPosition SavedPosition(Cursor);
  6972. RecordData Record;
  6973. while (true) {
  6974. llvm::BitstreamEntry Entry =
  6975. Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
  6976. switch (Entry.Kind) {
  6977. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  6978. case llvm::BitstreamEntry::Error:
  6979. Error("malformed block record in AST file");
  6980. return;
  6981. case llvm::BitstreamEntry::EndBlock:
  6982. goto NextCursor;
  6983. case llvm::BitstreamEntry::Record:
  6984. // The interesting case.
  6985. break;
  6986. }
  6987. // Read a record.
  6988. Record.clear();
  6989. switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
  6990. case COMMENTS_RAW_COMMENT: {
  6991. unsigned Idx = 0;
  6992. SourceRange SR = ReadSourceRange(F, Record, Idx);
  6993. RawComment::CommentKind Kind =
  6994. (RawComment::CommentKind) Record[Idx++];
  6995. bool IsTrailingComment = Record[Idx++];
  6996. bool IsAlmostTrailingComment = Record[Idx++];
  6997. Comments.push_back(new (Context) RawComment(
  6998. SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
  6999. Context.getLangOpts().CommentOpts.ParseAllComments));
  7000. break;
  7001. }
  7002. }
  7003. }
  7004. NextCursor:
  7005. Context.Comments.addDeserializedComments(Comments);
  7006. }
  7007. }
  7008. void ASTReader::getInputFiles(ModuleFile &F,
  7009. SmallVectorImpl<serialization::InputFile> &Files) {
  7010. for (unsigned I = 0, E = F.InputFilesLoaded.size(); I != E; ++I) {
  7011. unsigned ID = I+1;
  7012. Files.push_back(getInputFile(F, ID));
  7013. }
  7014. }
  7015. std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
  7016. // If we know the owning module, use it.
  7017. if (Module *M = D->getImportedOwningModule())
  7018. return M->getFullModuleName();
  7019. // Otherwise, use the name of the top-level module the decl is within.
  7020. if (ModuleFile *M = getOwningModuleFile(D))
  7021. return M->ModuleName;
  7022. // Not from a module.
  7023. return "";
  7024. }
  7025. void ASTReader::finishPendingActions() {
  7026. while (!PendingIdentifierInfos.empty() ||
  7027. !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
  7028. !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
  7029. !PendingUpdateRecords.empty()) {
  7030. // If any identifiers with corresponding top-level declarations have
  7031. // been loaded, load those declarations now.
  7032. typedef llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2> >
  7033. TopLevelDeclsMap;
  7034. TopLevelDeclsMap TopLevelDecls;
  7035. while (!PendingIdentifierInfos.empty()) {
  7036. IdentifierInfo *II = PendingIdentifierInfos.back().first;
  7037. SmallVector<uint32_t, 4> DeclIDs =
  7038. std::move(PendingIdentifierInfos.back().second);
  7039. PendingIdentifierInfos.pop_back();
  7040. SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
  7041. }
  7042. // For each decl chain that we wanted to complete while deserializing, mark
  7043. // it as "still needs to be completed".
  7044. for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
  7045. markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
  7046. }
  7047. PendingIncompleteDeclChains.clear();
  7048. // Load pending declaration chains.
  7049. for (unsigned I = 0; I != PendingDeclChains.size(); ++I) {
  7050. PendingDeclChainsKnown.erase(PendingDeclChains[I]);
  7051. loadPendingDeclChain(PendingDeclChains[I]);
  7052. }
  7053. assert(PendingDeclChainsKnown.empty());
  7054. PendingDeclChains.clear();
  7055. // Make the most recent of the top-level declarations visible.
  7056. for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
  7057. TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
  7058. IdentifierInfo *II = TLD->first;
  7059. for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
  7060. pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
  7061. }
  7062. }
  7063. // Load any pending macro definitions.
  7064. for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
  7065. IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
  7066. SmallVector<PendingMacroInfo, 2> GlobalIDs;
  7067. GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
  7068. // Initialize the macro history from chained-PCHs ahead of module imports.
  7069. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  7070. ++IDIdx) {
  7071. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  7072. if (Info.M->Kind != MK_ImplicitModule &&
  7073. Info.M->Kind != MK_ExplicitModule)
  7074. resolvePendingMacro(II, Info);
  7075. }
  7076. // Handle module imports.
  7077. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  7078. ++IDIdx) {
  7079. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  7080. if (Info.M->Kind == MK_ImplicitModule ||
  7081. Info.M->Kind == MK_ExplicitModule)
  7082. resolvePendingMacro(II, Info);
  7083. }
  7084. }
  7085. PendingMacroIDs.clear();
  7086. // Wire up the DeclContexts for Decls that we delayed setting until
  7087. // recursive loading is completed.
  7088. while (!PendingDeclContextInfos.empty()) {
  7089. PendingDeclContextInfo Info = PendingDeclContextInfos.front();
  7090. PendingDeclContextInfos.pop_front();
  7091. DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
  7092. DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
  7093. Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
  7094. }
  7095. // Perform any pending declaration updates.
  7096. while (!PendingUpdateRecords.empty()) {
  7097. auto Update = PendingUpdateRecords.pop_back_val();
  7098. ReadingKindTracker ReadingKind(Read_Decl, *this);
  7099. loadDeclUpdateRecords(Update.first, Update.second);
  7100. }
  7101. }
  7102. // At this point, all update records for loaded decls are in place, so any
  7103. // fake class definitions should have become real.
  7104. assert(PendingFakeDefinitionData.empty() &&
  7105. "faked up a class definition but never saw the real one");
  7106. // If we deserialized any C++ or Objective-C class definitions, any
  7107. // Objective-C protocol definitions, or any redeclarable templates, make sure
  7108. // that all redeclarations point to the definitions. Note that this can only
  7109. // happen now, after the redeclaration chains have been fully wired.
  7110. for (Decl *D : PendingDefinitions) {
  7111. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  7112. if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
  7113. // Make sure that the TagType points at the definition.
  7114. const_cast<TagType*>(TagT)->decl = TD;
  7115. }
  7116. if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
  7117. for (auto *R = getMostRecentExistingDecl(RD); R;
  7118. R = R->getPreviousDecl()) {
  7119. assert((R == D) ==
  7120. cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
  7121. "declaration thinks it's the definition but it isn't");
  7122. cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
  7123. }
  7124. }
  7125. continue;
  7126. }
  7127. if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
  7128. // Make sure that the ObjCInterfaceType points at the definition.
  7129. const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
  7130. ->Decl = ID;
  7131. for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
  7132. cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
  7133. continue;
  7134. }
  7135. if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
  7136. for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
  7137. cast<ObjCProtocolDecl>(R)->Data = PD->Data;
  7138. continue;
  7139. }
  7140. auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
  7141. for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
  7142. cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
  7143. }
  7144. PendingDefinitions.clear();
  7145. // Load the bodies of any functions or methods we've encountered. We do
  7146. // this now (delayed) so that we can be sure that the declaration chains
  7147. // have been fully wired up.
  7148. // FIXME: There seems to be no point in delaying this, it does not depend
  7149. // on the redecl chains having been wired up.
  7150. for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
  7151. PBEnd = PendingBodies.end();
  7152. PB != PBEnd; ++PB) {
  7153. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
  7154. // FIXME: Check for =delete/=default?
  7155. // FIXME: Complain about ODR violations here?
  7156. if (!getContext().getLangOpts().Modules || !FD->hasBody())
  7157. FD->setLazyBody(PB->second);
  7158. continue;
  7159. }
  7160. ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
  7161. if (!getContext().getLangOpts().Modules || !MD->hasBody())
  7162. MD->setLazyBody(PB->second);
  7163. }
  7164. PendingBodies.clear();
  7165. // Do some cleanup.
  7166. for (auto *ND : PendingMergedDefinitionsToDeduplicate)
  7167. getContext().deduplicateMergedDefinitonsFor(ND);
  7168. PendingMergedDefinitionsToDeduplicate.clear();
  7169. }
  7170. void ASTReader::diagnoseOdrViolations() {
  7171. if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
  7172. return;
  7173. // Trigger the import of the full definition of each class that had any
  7174. // odr-merging problems, so we can produce better diagnostics for them.
  7175. // These updates may in turn find and diagnose some ODR failures, so take
  7176. // ownership of the set first.
  7177. auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
  7178. PendingOdrMergeFailures.clear();
  7179. for (auto &Merge : OdrMergeFailures) {
  7180. Merge.first->buildLookup();
  7181. Merge.first->decls_begin();
  7182. Merge.first->bases_begin();
  7183. Merge.first->vbases_begin();
  7184. for (auto *RD : Merge.second) {
  7185. RD->decls_begin();
  7186. RD->bases_begin();
  7187. RD->vbases_begin();
  7188. }
  7189. }
  7190. // For each declaration from a merged context, check that the canonical
  7191. // definition of that context also contains a declaration of the same
  7192. // entity.
  7193. //
  7194. // Caution: this loop does things that might invalidate iterators into
  7195. // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
  7196. while (!PendingOdrMergeChecks.empty()) {
  7197. NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
  7198. // FIXME: Skip over implicit declarations for now. This matters for things
  7199. // like implicitly-declared special member functions. This isn't entirely
  7200. // correct; we can end up with multiple unmerged declarations of the same
  7201. // implicit entity.
  7202. if (D->isImplicit())
  7203. continue;
  7204. DeclContext *CanonDef = D->getDeclContext();
  7205. bool Found = false;
  7206. const Decl *DCanon = D->getCanonicalDecl();
  7207. for (auto RI : D->redecls()) {
  7208. if (RI->getLexicalDeclContext() == CanonDef) {
  7209. Found = true;
  7210. break;
  7211. }
  7212. }
  7213. if (Found)
  7214. continue;
  7215. llvm::SmallVector<const NamedDecl*, 4> Candidates;
  7216. DeclContext::lookup_result R = CanonDef->lookup(D->getDeclName());
  7217. for (DeclContext::lookup_iterator I = R.begin(), E = R.end();
  7218. !Found && I != E; ++I) {
  7219. for (auto RI : (*I)->redecls()) {
  7220. if (RI->getLexicalDeclContext() == CanonDef) {
  7221. // This declaration is present in the canonical definition. If it's
  7222. // in the same redecl chain, it's the one we're looking for.
  7223. if (RI->getCanonicalDecl() == DCanon)
  7224. Found = true;
  7225. else
  7226. Candidates.push_back(cast<NamedDecl>(RI));
  7227. break;
  7228. }
  7229. }
  7230. }
  7231. if (!Found) {
  7232. // The AST doesn't like TagDecls becoming invalid after they've been
  7233. // completed. We only really need to mark FieldDecls as invalid here.
  7234. if (!isa<TagDecl>(D))
  7235. D->setInvalidDecl();
  7236. // Ensure we don't accidentally recursively enter deserialization while
  7237. // we're producing our diagnostic.
  7238. Deserializing RecursionGuard(this);
  7239. std::string CanonDefModule =
  7240. getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
  7241. Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
  7242. << D << getOwningModuleNameForDiagnostic(D)
  7243. << CanonDef << CanonDefModule.empty() << CanonDefModule;
  7244. if (Candidates.empty())
  7245. Diag(cast<Decl>(CanonDef)->getLocation(),
  7246. diag::note_module_odr_violation_no_possible_decls) << D;
  7247. else {
  7248. for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
  7249. Diag(Candidates[I]->getLocation(),
  7250. diag::note_module_odr_violation_possible_decl)
  7251. << Candidates[I];
  7252. }
  7253. DiagnosedOdrMergeFailures.insert(CanonDef);
  7254. }
  7255. }
  7256. if (OdrMergeFailures.empty())
  7257. return;
  7258. // Ensure we don't accidentally recursively enter deserialization while
  7259. // we're producing our diagnostics.
  7260. Deserializing RecursionGuard(this);
  7261. // Issue any pending ODR-failure diagnostics.
  7262. for (auto &Merge : OdrMergeFailures) {
  7263. // If we've already pointed out a specific problem with this class, don't
  7264. // bother issuing a general "something's different" diagnostic.
  7265. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
  7266. continue;
  7267. bool Diagnosed = false;
  7268. for (auto *RD : Merge.second) {
  7269. // Multiple different declarations got merged together; tell the user
  7270. // where they came from.
  7271. if (Merge.first != RD) {
  7272. // FIXME: Walk the definition, figure out what's different,
  7273. // and diagnose that.
  7274. if (!Diagnosed) {
  7275. std::string Module = getOwningModuleNameForDiagnostic(Merge.first);
  7276. Diag(Merge.first->getLocation(),
  7277. diag::err_module_odr_violation_different_definitions)
  7278. << Merge.first << Module.empty() << Module;
  7279. Diagnosed = true;
  7280. }
  7281. Diag(RD->getLocation(),
  7282. diag::note_module_odr_violation_different_definitions)
  7283. << getOwningModuleNameForDiagnostic(RD);
  7284. }
  7285. }
  7286. if (!Diagnosed) {
  7287. // All definitions are updates to the same declaration. This happens if a
  7288. // module instantiates the declaration of a class template specialization
  7289. // and two or more other modules instantiate its definition.
  7290. //
  7291. // FIXME: Indicate which modules had instantiations of this definition.
  7292. // FIXME: How can this even happen?
  7293. Diag(Merge.first->getLocation(),
  7294. diag::err_module_odr_violation_different_instantiations)
  7295. << Merge.first;
  7296. }
  7297. }
  7298. }
  7299. void ASTReader::StartedDeserializing() {
  7300. if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
  7301. ReadTimer->startTimer();
  7302. }
  7303. void ASTReader::FinishedDeserializing() {
  7304. assert(NumCurrentElementsDeserializing &&
  7305. "FinishedDeserializing not paired with StartedDeserializing");
  7306. if (NumCurrentElementsDeserializing == 1) {
  7307. // We decrease NumCurrentElementsDeserializing only after pending actions
  7308. // are finished, to avoid recursively re-calling finishPendingActions().
  7309. finishPendingActions();
  7310. }
  7311. --NumCurrentElementsDeserializing;
  7312. if (NumCurrentElementsDeserializing == 0) {
  7313. // Propagate exception specification updates along redeclaration chains.
  7314. while (!PendingExceptionSpecUpdates.empty()) {
  7315. auto Updates = std::move(PendingExceptionSpecUpdates);
  7316. PendingExceptionSpecUpdates.clear();
  7317. for (auto Update : Updates) {
  7318. auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
  7319. SemaObj->UpdateExceptionSpec(Update.second,
  7320. FPT->getExtProtoInfo().ExceptionSpec);
  7321. }
  7322. }
  7323. diagnoseOdrViolations();
  7324. if (ReadTimer)
  7325. ReadTimer->stopTimer();
  7326. // We are not in recursive loading, so it's safe to pass the "interesting"
  7327. // decls to the consumer.
  7328. if (Consumer)
  7329. PassInterestingDeclsToConsumer();
  7330. }
  7331. }
  7332. void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  7333. if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
  7334. // Remove any fake results before adding any real ones.
  7335. auto It = PendingFakeLookupResults.find(II);
  7336. if (It != PendingFakeLookupResults.end()) {
  7337. for (auto *ND : PendingFakeLookupResults[II])
  7338. SemaObj->IdResolver.RemoveDecl(ND);
  7339. // FIXME: this works around module+PCH performance issue.
  7340. // Rather than erase the result from the map, which is O(n), just clear
  7341. // the vector of NamedDecls.
  7342. It->second.clear();
  7343. }
  7344. }
  7345. if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
  7346. SemaObj->TUScope->AddDecl(D);
  7347. } else if (SemaObj->TUScope) {
  7348. // Adding the decl to IdResolver may have failed because it was already in
  7349. // (even though it was not added in scope). If it is already in, make sure
  7350. // it gets in the scope as well.
  7351. if (std::find(SemaObj->IdResolver.begin(Name),
  7352. SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
  7353. SemaObj->TUScope->AddDecl(D);
  7354. }
  7355. }
  7356. ASTReader::ASTReader(Preprocessor &PP, ASTContext &Context,
  7357. const PCHContainerReader &PCHContainerRdr,
  7358. StringRef isysroot, bool DisableValidation,
  7359. bool AllowASTWithCompilerErrors,
  7360. bool AllowConfigurationMismatch, bool ValidateSystemInputs,
  7361. bool UseGlobalIndex,
  7362. std::unique_ptr<llvm::Timer> ReadTimer)
  7363. : Listener(new PCHValidator(PP, *this)), DeserializationListener(nullptr),
  7364. OwnsDeserializationListener(false), SourceMgr(PP.getSourceManager()),
  7365. FileMgr(PP.getFileManager()), PCHContainerRdr(PCHContainerRdr),
  7366. Diags(PP.getDiagnostics()), SemaObj(nullptr), PP(PP), Context(Context),
  7367. Consumer(nullptr), ModuleMgr(PP.getFileManager(), PCHContainerRdr),
  7368. ReadTimer(std::move(ReadTimer)),
  7369. isysroot(isysroot), DisableValidation(DisableValidation),
  7370. AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
  7371. AllowConfigurationMismatch(AllowConfigurationMismatch),
  7372. ValidateSystemInputs(ValidateSystemInputs),
  7373. UseGlobalIndex(UseGlobalIndex), TriedLoadingGlobalIndex(false),
  7374. CurrSwitchCaseStmts(&SwitchCaseStmts), NumSLocEntriesRead(0),
  7375. TotalNumSLocEntries(0), NumStatementsRead(0), TotalNumStatements(0),
  7376. NumMacrosRead(0), TotalNumMacros(0), NumIdentifierLookups(0),
  7377. NumIdentifierLookupHits(0), NumSelectorsRead(0),
  7378. NumMethodPoolEntriesRead(0), NumMethodPoolLookups(0),
  7379. NumMethodPoolHits(0), NumMethodPoolTableLookups(0),
  7380. NumMethodPoolTableHits(0), TotalNumMethodPoolEntries(0),
  7381. NumLexicalDeclContextsRead(0), TotalLexicalDeclContexts(0),
  7382. NumVisibleDeclContextsRead(0), TotalVisibleDeclContexts(0),
  7383. TotalModulesSizeInBits(0), NumCurrentElementsDeserializing(0),
  7384. PassingDeclsToConsumer(false), ReadingKind(Read_None) {
  7385. SourceMgr.setExternalSLocEntrySource(this);
  7386. }
  7387. ASTReader::~ASTReader() {
  7388. if (OwnsDeserializationListener)
  7389. delete DeserializationListener;
  7390. for (DeclContextVisibleUpdatesPending::iterator
  7391. I = PendingVisibleUpdates.begin(),
  7392. E = PendingVisibleUpdates.end();
  7393. I != E; ++I) {
  7394. for (DeclContextVisibleUpdates::iterator J = I->second.begin(),
  7395. F = I->second.end();
  7396. J != F; ++J)
  7397. delete J->first;
  7398. }
  7399. }