ASTWriter.cpp 253 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122
  1. //===- ASTWriter.cpp - AST File Writer ------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the ASTWriter class, which writes AST files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Serialization/ASTWriter.h"
  13. #include "ASTCommon.h"
  14. #include "ASTReaderInternals.h"
  15. #include "MultiOnDiskHashTable.h"
  16. #include "clang/AST/ASTContext.h"
  17. #include "clang/AST/ASTUnresolvedSet.h"
  18. #include "clang/AST/Attr.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclBase.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclContextInternals.h"
  23. #include "clang/AST/DeclFriend.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/DeclTemplate.h"
  26. #include "clang/AST/DeclarationName.h"
  27. #include "clang/AST/Expr.h"
  28. #include "clang/AST/ExprCXX.h"
  29. #include "clang/AST/LambdaCapture.h"
  30. #include "clang/AST/NestedNameSpecifier.h"
  31. #include "clang/AST/RawCommentList.h"
  32. #include "clang/AST/TemplateName.h"
  33. #include "clang/AST/Type.h"
  34. #include "clang/AST/TypeLocVisitor.h"
  35. #include "clang/Basic/Diagnostic.h"
  36. #include "clang/Basic/DiagnosticOptions.h"
  37. #include "clang/Basic/FileManager.h"
  38. #include "clang/Basic/FileSystemOptions.h"
  39. #include "clang/Basic/IdentifierTable.h"
  40. #include "clang/Basic/LLVM.h"
  41. #include "clang/Basic/Lambda.h"
  42. #include "clang/Basic/LangOptions.h"
  43. #include "clang/Basic/Module.h"
  44. #include "clang/Basic/ObjCRuntime.h"
  45. #include "clang/Basic/OpenCLOptions.h"
  46. #include "clang/Basic/SourceLocation.h"
  47. #include "clang/Basic/SourceManager.h"
  48. #include "clang/Basic/SourceManagerInternals.h"
  49. #include "clang/Basic/Specifiers.h"
  50. #include "clang/Basic/TargetInfo.h"
  51. #include "clang/Basic/TargetOptions.h"
  52. #include "clang/Basic/Version.h"
  53. #include "clang/Lex/HeaderSearch.h"
  54. #include "clang/Lex/HeaderSearchOptions.h"
  55. #include "clang/Lex/MacroInfo.h"
  56. #include "clang/Lex/ModuleMap.h"
  57. #include "clang/Lex/PreprocessingRecord.h"
  58. #include "clang/Lex/Preprocessor.h"
  59. #include "clang/Lex/PreprocessorOptions.h"
  60. #include "clang/Lex/Token.h"
  61. #include "clang/Sema/IdentifierResolver.h"
  62. #include "clang/Sema/ObjCMethodList.h"
  63. #include "clang/Sema/Sema.h"
  64. #include "clang/Sema/Weak.h"
  65. #include "clang/Serialization/ASTReader.h"
  66. #include "clang/Serialization/InMemoryModuleCache.h"
  67. #include "clang/Serialization/Module.h"
  68. #include "clang/Serialization/ModuleFileExtension.h"
  69. #include "clang/Serialization/SerializationDiagnostic.h"
  70. #include "llvm/ADT/APFloat.h"
  71. #include "llvm/ADT/APInt.h"
  72. #include "llvm/ADT/APSInt.h"
  73. #include "llvm/ADT/ArrayRef.h"
  74. #include "llvm/ADT/DenseMap.h"
  75. #include "llvm/ADT/Hashing.h"
  76. #include "llvm/ADT/Optional.h"
  77. #include "llvm/ADT/PointerIntPair.h"
  78. #include "llvm/ADT/STLExtras.h"
  79. #include "llvm/ADT/ScopeExit.h"
  80. #include "llvm/ADT/SmallSet.h"
  81. #include "llvm/ADT/SmallString.h"
  82. #include "llvm/ADT/SmallVector.h"
  83. #include "llvm/ADT/StringMap.h"
  84. #include "llvm/ADT/StringRef.h"
  85. #include "llvm/Bitstream/BitCodes.h"
  86. #include "llvm/Bitstream/BitstreamWriter.h"
  87. #include "llvm/Support/Casting.h"
  88. #include "llvm/Support/Compression.h"
  89. #include "llvm/Support/DJB.h"
  90. #include "llvm/Support/Endian.h"
  91. #include "llvm/Support/EndianStream.h"
  92. #include "llvm/Support/Error.h"
  93. #include "llvm/Support/ErrorHandling.h"
  94. #include "llvm/Support/MemoryBuffer.h"
  95. #include "llvm/Support/OnDiskHashTable.h"
  96. #include "llvm/Support/Path.h"
  97. #include "llvm/Support/SHA1.h"
  98. #include "llvm/Support/VersionTuple.h"
  99. #include "llvm/Support/raw_ostream.h"
  100. #include <algorithm>
  101. #include <cassert>
  102. #include <cstdint>
  103. #include <cstdlib>
  104. #include <cstring>
  105. #include <ctime>
  106. #include <deque>
  107. #include <limits>
  108. #include <memory>
  109. #include <queue>
  110. #include <tuple>
  111. #include <utility>
  112. #include <vector>
  113. using namespace clang;
  114. using namespace clang::serialization;
  115. template <typename T, typename Allocator>
  116. static StringRef bytes(const std::vector<T, Allocator> &v) {
  117. if (v.empty()) return StringRef();
  118. return StringRef(reinterpret_cast<const char*>(&v[0]),
  119. sizeof(T) * v.size());
  120. }
  121. template <typename T>
  122. static StringRef bytes(const SmallVectorImpl<T> &v) {
  123. return StringRef(reinterpret_cast<const char*>(v.data()),
  124. sizeof(T) * v.size());
  125. }
  126. //===----------------------------------------------------------------------===//
  127. // Type serialization
  128. //===----------------------------------------------------------------------===//
  129. namespace clang {
  130. class ASTTypeWriter {
  131. ASTWriter &Writer;
  132. ASTRecordWriter Record;
  133. /// Type code that corresponds to the record generated.
  134. TypeCode Code = static_cast<TypeCode>(0);
  135. /// Abbreviation to use for the record, if any.
  136. unsigned AbbrevToUse = 0;
  137. public:
  138. ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
  139. : Writer(Writer), Record(Writer, Record) {}
  140. uint64_t Emit() {
  141. return Record.Emit(Code, AbbrevToUse);
  142. }
  143. void Visit(QualType T) {
  144. if (T.hasLocalNonFastQualifiers()) {
  145. Qualifiers Qs = T.getLocalQualifiers();
  146. Record.AddTypeRef(T.getLocalUnqualifiedType());
  147. Record.push_back(Qs.getAsOpaqueValue());
  148. Code = TYPE_EXT_QUAL;
  149. AbbrevToUse = Writer.TypeExtQualAbbrev;
  150. } else {
  151. switch (T->getTypeClass()) {
  152. // For all of the concrete, non-dependent types, call the
  153. // appropriate visitor function.
  154. #define TYPE(Class, Base) \
  155. case Type::Class: Visit##Class##Type(cast<Class##Type>(T)); break;
  156. #define ABSTRACT_TYPE(Class, Base)
  157. #include "clang/AST/TypeNodes.inc"
  158. }
  159. }
  160. }
  161. void VisitArrayType(const ArrayType *T);
  162. void VisitFunctionType(const FunctionType *T);
  163. void VisitTagType(const TagType *T);
  164. #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
  165. #define ABSTRACT_TYPE(Class, Base)
  166. #include "clang/AST/TypeNodes.inc"
  167. };
  168. } // namespace clang
  169. void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
  170. llvm_unreachable("Built-in types are never serialized");
  171. }
  172. void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
  173. Record.AddTypeRef(T->getElementType());
  174. Code = TYPE_COMPLEX;
  175. }
  176. void ASTTypeWriter::VisitPointerType(const PointerType *T) {
  177. Record.AddTypeRef(T->getPointeeType());
  178. Code = TYPE_POINTER;
  179. }
  180. void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
  181. Record.AddTypeRef(T->getOriginalType());
  182. Code = TYPE_DECAYED;
  183. }
  184. void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
  185. Record.AddTypeRef(T->getOriginalType());
  186. Record.AddTypeRef(T->getAdjustedType());
  187. Code = TYPE_ADJUSTED;
  188. }
  189. void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
  190. Record.AddTypeRef(T->getPointeeType());
  191. Code = TYPE_BLOCK_POINTER;
  192. }
  193. void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
  194. Record.AddTypeRef(T->getPointeeTypeAsWritten());
  195. Record.push_back(T->isSpelledAsLValue());
  196. Code = TYPE_LVALUE_REFERENCE;
  197. }
  198. void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
  199. Record.AddTypeRef(T->getPointeeTypeAsWritten());
  200. Code = TYPE_RVALUE_REFERENCE;
  201. }
  202. void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
  203. Record.AddTypeRef(T->getPointeeType());
  204. Record.AddTypeRef(QualType(T->getClass(), 0));
  205. Code = TYPE_MEMBER_POINTER;
  206. }
  207. void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
  208. Record.AddTypeRef(T->getElementType());
  209. Record.push_back(T->getSizeModifier()); // FIXME: stable values
  210. Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
  211. }
  212. void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
  213. VisitArrayType(T);
  214. Record.AddAPInt(T->getSize());
  215. Record.AddStmt(const_cast<Expr*>(T->getSizeExpr()));
  216. Code = TYPE_CONSTANT_ARRAY;
  217. }
  218. void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
  219. VisitArrayType(T);
  220. Code = TYPE_INCOMPLETE_ARRAY;
  221. }
  222. void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
  223. VisitArrayType(T);
  224. Record.AddSourceLocation(T->getLBracketLoc());
  225. Record.AddSourceLocation(T->getRBracketLoc());
  226. Record.AddStmt(T->getSizeExpr());
  227. Code = TYPE_VARIABLE_ARRAY;
  228. }
  229. void ASTTypeWriter::VisitVectorType(const VectorType *T) {
  230. Record.AddTypeRef(T->getElementType());
  231. Record.push_back(T->getNumElements());
  232. Record.push_back(T->getVectorKind());
  233. Code = TYPE_VECTOR;
  234. }
  235. void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
  236. VisitVectorType(T);
  237. Code = TYPE_EXT_VECTOR;
  238. }
  239. void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
  240. Record.AddTypeRef(T->getReturnType());
  241. FunctionType::ExtInfo C = T->getExtInfo();
  242. Record.push_back(C.getNoReturn());
  243. Record.push_back(C.getHasRegParm());
  244. Record.push_back(C.getRegParm());
  245. // FIXME: need to stabilize encoding of calling convention...
  246. Record.push_back(C.getCC());
  247. Record.push_back(C.getProducesResult());
  248. Record.push_back(C.getNoCallerSavedRegs());
  249. Record.push_back(C.getNoCfCheck());
  250. if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
  251. AbbrevToUse = 0;
  252. }
  253. void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
  254. VisitFunctionType(T);
  255. Code = TYPE_FUNCTION_NO_PROTO;
  256. }
  257. static void addExceptionSpec(const FunctionProtoType *T,
  258. ASTRecordWriter &Record) {
  259. Record.push_back(T->getExceptionSpecType());
  260. if (T->getExceptionSpecType() == EST_Dynamic) {
  261. Record.push_back(T->getNumExceptions());
  262. for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
  263. Record.AddTypeRef(T->getExceptionType(I));
  264. } else if (isComputedNoexcept(T->getExceptionSpecType())) {
  265. Record.AddStmt(T->getNoexceptExpr());
  266. } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
  267. Record.AddDeclRef(T->getExceptionSpecDecl());
  268. Record.AddDeclRef(T->getExceptionSpecTemplate());
  269. } else if (T->getExceptionSpecType() == EST_Unevaluated) {
  270. Record.AddDeclRef(T->getExceptionSpecDecl());
  271. }
  272. }
  273. void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
  274. VisitFunctionType(T);
  275. Record.push_back(T->isVariadic());
  276. Record.push_back(T->hasTrailingReturn());
  277. Record.push_back(T->getMethodQuals().getAsOpaqueValue());
  278. Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
  279. addExceptionSpec(T, Record);
  280. Record.push_back(T->getNumParams());
  281. for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
  282. Record.AddTypeRef(T->getParamType(I));
  283. if (T->hasExtParameterInfos()) {
  284. for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
  285. Record.push_back(T->getExtParameterInfo(I).getOpaqueValue());
  286. }
  287. if (T->isVariadic() || T->hasTrailingReturn() || T->getMethodQuals() ||
  288. T->getRefQualifier() || T->getExceptionSpecType() != EST_None ||
  289. T->hasExtParameterInfos())
  290. AbbrevToUse = 0;
  291. Code = TYPE_FUNCTION_PROTO;
  292. }
  293. void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
  294. Record.AddDeclRef(T->getDecl());
  295. Code = TYPE_UNRESOLVED_USING;
  296. }
  297. void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
  298. Record.AddDeclRef(T->getDecl());
  299. assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
  300. Record.AddTypeRef(T->getCanonicalTypeInternal());
  301. Code = TYPE_TYPEDEF;
  302. }
  303. void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
  304. Record.AddStmt(T->getUnderlyingExpr());
  305. Code = TYPE_TYPEOF_EXPR;
  306. }
  307. void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
  308. Record.AddTypeRef(T->getUnderlyingType());
  309. Code = TYPE_TYPEOF;
  310. }
  311. void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
  312. Record.AddTypeRef(T->getUnderlyingType());
  313. Record.AddStmt(T->getUnderlyingExpr());
  314. Code = TYPE_DECLTYPE;
  315. }
  316. void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
  317. Record.AddTypeRef(T->getBaseType());
  318. Record.AddTypeRef(T->getUnderlyingType());
  319. Record.push_back(T->getUTTKind());
  320. Code = TYPE_UNARY_TRANSFORM;
  321. }
  322. void ASTTypeWriter::VisitAutoType(const AutoType *T) {
  323. Record.AddTypeRef(T->getDeducedType());
  324. Record.push_back((unsigned)T->getKeyword());
  325. if (T->getDeducedType().isNull())
  326. Record.push_back(T->containsUnexpandedParameterPack() ? 2 :
  327. T->isDependentType() ? 1 : 0);
  328. Code = TYPE_AUTO;
  329. }
  330. void ASTTypeWriter::VisitDeducedTemplateSpecializationType(
  331. const DeducedTemplateSpecializationType *T) {
  332. Record.AddTemplateName(T->getTemplateName());
  333. Record.AddTypeRef(T->getDeducedType());
  334. if (T->getDeducedType().isNull())
  335. Record.push_back(T->isDependentType());
  336. Code = TYPE_DEDUCED_TEMPLATE_SPECIALIZATION;
  337. }
  338. void ASTTypeWriter::VisitTagType(const TagType *T) {
  339. Record.push_back(T->isDependentType());
  340. Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
  341. assert(!T->isBeingDefined() &&
  342. "Cannot serialize in the middle of a type definition");
  343. }
  344. void ASTTypeWriter::VisitRecordType(const RecordType *T) {
  345. VisitTagType(T);
  346. Code = TYPE_RECORD;
  347. }
  348. void ASTTypeWriter::VisitEnumType(const EnumType *T) {
  349. VisitTagType(T);
  350. Code = TYPE_ENUM;
  351. }
  352. void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
  353. Record.AddTypeRef(T->getModifiedType());
  354. Record.AddTypeRef(T->getEquivalentType());
  355. Record.push_back(T->getAttrKind());
  356. Code = TYPE_ATTRIBUTED;
  357. }
  358. void
  359. ASTTypeWriter::VisitSubstTemplateTypeParmType(
  360. const SubstTemplateTypeParmType *T) {
  361. Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
  362. Record.AddTypeRef(T->getReplacementType());
  363. Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
  364. }
  365. void
  366. ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
  367. const SubstTemplateTypeParmPackType *T) {
  368. Record.AddTypeRef(QualType(T->getReplacedParameter(), 0));
  369. Record.AddTemplateArgument(T->getArgumentPack());
  370. Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
  371. }
  372. void
  373. ASTTypeWriter::VisitTemplateSpecializationType(
  374. const TemplateSpecializationType *T) {
  375. Record.push_back(T->isDependentType());
  376. Record.AddTemplateName(T->getTemplateName());
  377. Record.push_back(T->getNumArgs());
  378. for (const auto &ArgI : *T)
  379. Record.AddTemplateArgument(ArgI);
  380. Record.AddTypeRef(T->isTypeAlias() ? T->getAliasedType()
  381. : T->isCanonicalUnqualified()
  382. ? QualType()
  383. : T->getCanonicalTypeInternal());
  384. Code = TYPE_TEMPLATE_SPECIALIZATION;
  385. }
  386. void
  387. ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
  388. VisitArrayType(T);
  389. Record.AddStmt(T->getSizeExpr());
  390. Record.AddSourceRange(T->getBracketsRange());
  391. Code = TYPE_DEPENDENT_SIZED_ARRAY;
  392. }
  393. void
  394. ASTTypeWriter::VisitDependentSizedExtVectorType(
  395. const DependentSizedExtVectorType *T) {
  396. Record.AddTypeRef(T->getElementType());
  397. Record.AddStmt(T->getSizeExpr());
  398. Record.AddSourceLocation(T->getAttributeLoc());
  399. Code = TYPE_DEPENDENT_SIZED_EXT_VECTOR;
  400. }
  401. void ASTTypeWriter::VisitDependentVectorType(const DependentVectorType *T) {
  402. Record.AddTypeRef(T->getElementType());
  403. Record.AddStmt(const_cast<Expr*>(T->getSizeExpr()));
  404. Record.AddSourceLocation(T->getAttributeLoc());
  405. Record.push_back(T->getVectorKind());
  406. Code = TYPE_DEPENDENT_SIZED_VECTOR;
  407. }
  408. void
  409. ASTTypeWriter::VisitDependentAddressSpaceType(
  410. const DependentAddressSpaceType *T) {
  411. Record.AddTypeRef(T->getPointeeType());
  412. Record.AddStmt(T->getAddrSpaceExpr());
  413. Record.AddSourceLocation(T->getAttributeLoc());
  414. Code = TYPE_DEPENDENT_ADDRESS_SPACE;
  415. }
  416. void
  417. ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
  418. Record.push_back(T->getDepth());
  419. Record.push_back(T->getIndex());
  420. Record.push_back(T->isParameterPack());
  421. Record.AddDeclRef(T->getDecl());
  422. Code = TYPE_TEMPLATE_TYPE_PARM;
  423. }
  424. void
  425. ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
  426. Record.push_back(T->getKeyword());
  427. Record.AddNestedNameSpecifier(T->getQualifier());
  428. Record.AddIdentifierRef(T->getIdentifier());
  429. Record.AddTypeRef(
  430. T->isCanonicalUnqualified() ? QualType() : T->getCanonicalTypeInternal());
  431. Code = TYPE_DEPENDENT_NAME;
  432. }
  433. void
  434. ASTTypeWriter::VisitDependentTemplateSpecializationType(
  435. const DependentTemplateSpecializationType *T) {
  436. Record.push_back(T->getKeyword());
  437. Record.AddNestedNameSpecifier(T->getQualifier());
  438. Record.AddIdentifierRef(T->getIdentifier());
  439. Record.push_back(T->getNumArgs());
  440. for (const auto &I : *T)
  441. Record.AddTemplateArgument(I);
  442. Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
  443. }
  444. void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
  445. Record.AddTypeRef(T->getPattern());
  446. if (Optional<unsigned> NumExpansions = T->getNumExpansions())
  447. Record.push_back(*NumExpansions + 1);
  448. else
  449. Record.push_back(0);
  450. Code = TYPE_PACK_EXPANSION;
  451. }
  452. void ASTTypeWriter::VisitParenType(const ParenType *T) {
  453. Record.AddTypeRef(T->getInnerType());
  454. Code = TYPE_PAREN;
  455. }
  456. void ASTTypeWriter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
  457. Record.AddTypeRef(T->getUnderlyingType());
  458. Record.AddIdentifierRef(T->getMacroIdentifier());
  459. Code = TYPE_MACRO_QUALIFIED;
  460. }
  461. void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
  462. Record.push_back(T->getKeyword());
  463. Record.AddNestedNameSpecifier(T->getQualifier());
  464. Record.AddTypeRef(T->getNamedType());
  465. Record.AddDeclRef(T->getOwnedTagDecl());
  466. Code = TYPE_ELABORATED;
  467. }
  468. void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
  469. Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
  470. Record.AddTypeRef(T->getInjectedSpecializationType());
  471. Code = TYPE_INJECTED_CLASS_NAME;
  472. }
  473. void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
  474. Record.AddDeclRef(T->getDecl()->getCanonicalDecl());
  475. Code = TYPE_OBJC_INTERFACE;
  476. }
  477. void ASTTypeWriter::VisitObjCTypeParamType(const ObjCTypeParamType *T) {
  478. Record.AddDeclRef(T->getDecl());
  479. Record.push_back(T->getNumProtocols());
  480. for (const auto *I : T->quals())
  481. Record.AddDeclRef(I);
  482. Code = TYPE_OBJC_TYPE_PARAM;
  483. }
  484. void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
  485. Record.AddTypeRef(T->getBaseType());
  486. Record.push_back(T->getTypeArgsAsWritten().size());
  487. for (auto TypeArg : T->getTypeArgsAsWritten())
  488. Record.AddTypeRef(TypeArg);
  489. Record.push_back(T->getNumProtocols());
  490. for (const auto *I : T->quals())
  491. Record.AddDeclRef(I);
  492. Record.push_back(T->isKindOfTypeAsWritten());
  493. Code = TYPE_OBJC_OBJECT;
  494. }
  495. void
  496. ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
  497. Record.AddTypeRef(T->getPointeeType());
  498. Code = TYPE_OBJC_OBJECT_POINTER;
  499. }
  500. void
  501. ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
  502. Record.AddTypeRef(T->getValueType());
  503. Code = TYPE_ATOMIC;
  504. }
  505. void
  506. ASTTypeWriter::VisitPipeType(const PipeType *T) {
  507. Record.AddTypeRef(T->getElementType());
  508. Record.push_back(T->isReadOnly());
  509. Code = TYPE_PIPE;
  510. }
  511. namespace {
  512. class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
  513. ASTRecordWriter &Record;
  514. public:
  515. TypeLocWriter(ASTRecordWriter &Record) : Record(Record) {}
  516. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  517. #define TYPELOC(CLASS, PARENT) \
  518. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  519. #include "clang/AST/TypeLocNodes.def"
  520. void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
  521. void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
  522. };
  523. } // namespace
  524. void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  525. // nothing to do
  526. }
  527. void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  528. Record.AddSourceLocation(TL.getBuiltinLoc());
  529. if (TL.needsExtraLocalData()) {
  530. Record.push_back(TL.getWrittenTypeSpec());
  531. Record.push_back(TL.getWrittenSignSpec());
  532. Record.push_back(TL.getWrittenWidthSpec());
  533. Record.push_back(TL.hasModeAttr());
  534. }
  535. }
  536. void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  537. Record.AddSourceLocation(TL.getNameLoc());
  538. }
  539. void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
  540. Record.AddSourceLocation(TL.getStarLoc());
  541. }
  542. void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  543. // nothing to do
  544. }
  545. void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  546. // nothing to do
  547. }
  548. void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  549. Record.AddSourceLocation(TL.getCaretLoc());
  550. }
  551. void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  552. Record.AddSourceLocation(TL.getAmpLoc());
  553. }
  554. void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  555. Record.AddSourceLocation(TL.getAmpAmpLoc());
  556. }
  557. void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  558. Record.AddSourceLocation(TL.getStarLoc());
  559. Record.AddTypeSourceInfo(TL.getClassTInfo());
  560. }
  561. void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  562. Record.AddSourceLocation(TL.getLBracketLoc());
  563. Record.AddSourceLocation(TL.getRBracketLoc());
  564. Record.push_back(TL.getSizeExpr() ? 1 : 0);
  565. if (TL.getSizeExpr())
  566. Record.AddStmt(TL.getSizeExpr());
  567. }
  568. void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  569. VisitArrayTypeLoc(TL);
  570. }
  571. void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  572. VisitArrayTypeLoc(TL);
  573. }
  574. void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  575. VisitArrayTypeLoc(TL);
  576. }
  577. void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
  578. DependentSizedArrayTypeLoc TL) {
  579. VisitArrayTypeLoc(TL);
  580. }
  581. void TypeLocWriter::VisitDependentAddressSpaceTypeLoc(
  582. DependentAddressSpaceTypeLoc TL) {
  583. Record.AddSourceLocation(TL.getAttrNameLoc());
  584. SourceRange range = TL.getAttrOperandParensRange();
  585. Record.AddSourceLocation(range.getBegin());
  586. Record.AddSourceLocation(range.getEnd());
  587. Record.AddStmt(TL.getAttrExprOperand());
  588. }
  589. void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
  590. DependentSizedExtVectorTypeLoc TL) {
  591. Record.AddSourceLocation(TL.getNameLoc());
  592. }
  593. void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
  594. Record.AddSourceLocation(TL.getNameLoc());
  595. }
  596. void TypeLocWriter::VisitDependentVectorTypeLoc(
  597. DependentVectorTypeLoc TL) {
  598. Record.AddSourceLocation(TL.getNameLoc());
  599. }
  600. void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  601. Record.AddSourceLocation(TL.getNameLoc());
  602. }
  603. void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  604. Record.AddSourceLocation(TL.getLocalRangeBegin());
  605. Record.AddSourceLocation(TL.getLParenLoc());
  606. Record.AddSourceLocation(TL.getRParenLoc());
  607. Record.AddSourceRange(TL.getExceptionSpecRange());
  608. Record.AddSourceLocation(TL.getLocalRangeEnd());
  609. for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
  610. Record.AddDeclRef(TL.getParam(i));
  611. }
  612. void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  613. VisitFunctionTypeLoc(TL);
  614. }
  615. void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  616. VisitFunctionTypeLoc(TL);
  617. }
  618. void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  619. Record.AddSourceLocation(TL.getNameLoc());
  620. }
  621. void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  622. Record.AddSourceLocation(TL.getNameLoc());
  623. }
  624. void TypeLocWriter::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
  625. if (TL.getNumProtocols()) {
  626. Record.AddSourceLocation(TL.getProtocolLAngleLoc());
  627. Record.AddSourceLocation(TL.getProtocolRAngleLoc());
  628. }
  629. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  630. Record.AddSourceLocation(TL.getProtocolLoc(i));
  631. }
  632. void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  633. Record.AddSourceLocation(TL.getTypeofLoc());
  634. Record.AddSourceLocation(TL.getLParenLoc());
  635. Record.AddSourceLocation(TL.getRParenLoc());
  636. }
  637. void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  638. Record.AddSourceLocation(TL.getTypeofLoc());
  639. Record.AddSourceLocation(TL.getLParenLoc());
  640. Record.AddSourceLocation(TL.getRParenLoc());
  641. Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
  642. }
  643. void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  644. Record.AddSourceLocation(TL.getNameLoc());
  645. }
  646. void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  647. Record.AddSourceLocation(TL.getKWLoc());
  648. Record.AddSourceLocation(TL.getLParenLoc());
  649. Record.AddSourceLocation(TL.getRParenLoc());
  650. Record.AddTypeSourceInfo(TL.getUnderlyingTInfo());
  651. }
  652. void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
  653. Record.AddSourceLocation(TL.getNameLoc());
  654. }
  655. void TypeLocWriter::VisitDeducedTemplateSpecializationTypeLoc(
  656. DeducedTemplateSpecializationTypeLoc TL) {
  657. Record.AddSourceLocation(TL.getTemplateNameLoc());
  658. }
  659. void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
  660. Record.AddSourceLocation(TL.getNameLoc());
  661. }
  662. void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
  663. Record.AddSourceLocation(TL.getNameLoc());
  664. }
  665. void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  666. Record.AddAttr(TL.getAttr());
  667. }
  668. void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  669. Record.AddSourceLocation(TL.getNameLoc());
  670. }
  671. void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
  672. SubstTemplateTypeParmTypeLoc TL) {
  673. Record.AddSourceLocation(TL.getNameLoc());
  674. }
  675. void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
  676. SubstTemplateTypeParmPackTypeLoc TL) {
  677. Record.AddSourceLocation(TL.getNameLoc());
  678. }
  679. void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
  680. TemplateSpecializationTypeLoc TL) {
  681. Record.AddSourceLocation(TL.getTemplateKeywordLoc());
  682. Record.AddSourceLocation(TL.getTemplateNameLoc());
  683. Record.AddSourceLocation(TL.getLAngleLoc());
  684. Record.AddSourceLocation(TL.getRAngleLoc());
  685. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  686. Record.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
  687. TL.getArgLoc(i).getLocInfo());
  688. }
  689. void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
  690. Record.AddSourceLocation(TL.getLParenLoc());
  691. Record.AddSourceLocation(TL.getRParenLoc());
  692. }
  693. void TypeLocWriter::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
  694. Record.AddSourceLocation(TL.getExpansionLoc());
  695. }
  696. void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  697. Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
  698. Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
  699. }
  700. void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  701. Record.AddSourceLocation(TL.getNameLoc());
  702. }
  703. void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  704. Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
  705. Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
  706. Record.AddSourceLocation(TL.getNameLoc());
  707. }
  708. void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
  709. DependentTemplateSpecializationTypeLoc TL) {
  710. Record.AddSourceLocation(TL.getElaboratedKeywordLoc());
  711. Record.AddNestedNameSpecifierLoc(TL.getQualifierLoc());
  712. Record.AddSourceLocation(TL.getTemplateKeywordLoc());
  713. Record.AddSourceLocation(TL.getTemplateNameLoc());
  714. Record.AddSourceLocation(TL.getLAngleLoc());
  715. Record.AddSourceLocation(TL.getRAngleLoc());
  716. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  717. Record.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
  718. TL.getArgLoc(I).getLocInfo());
  719. }
  720. void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  721. Record.AddSourceLocation(TL.getEllipsisLoc());
  722. }
  723. void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  724. Record.AddSourceLocation(TL.getNameLoc());
  725. }
  726. void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  727. Record.push_back(TL.hasBaseTypeAsWritten());
  728. Record.AddSourceLocation(TL.getTypeArgsLAngleLoc());
  729. Record.AddSourceLocation(TL.getTypeArgsRAngleLoc());
  730. for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
  731. Record.AddTypeSourceInfo(TL.getTypeArgTInfo(i));
  732. Record.AddSourceLocation(TL.getProtocolLAngleLoc());
  733. Record.AddSourceLocation(TL.getProtocolRAngleLoc());
  734. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  735. Record.AddSourceLocation(TL.getProtocolLoc(i));
  736. }
  737. void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  738. Record.AddSourceLocation(TL.getStarLoc());
  739. }
  740. void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  741. Record.AddSourceLocation(TL.getKWLoc());
  742. Record.AddSourceLocation(TL.getLParenLoc());
  743. Record.AddSourceLocation(TL.getRParenLoc());
  744. }
  745. void TypeLocWriter::VisitPipeTypeLoc(PipeTypeLoc TL) {
  746. Record.AddSourceLocation(TL.getKWLoc());
  747. }
  748. void ASTWriter::WriteTypeAbbrevs() {
  749. using namespace llvm;
  750. std::shared_ptr<BitCodeAbbrev> Abv;
  751. // Abbreviation for TYPE_EXT_QUAL
  752. Abv = std::make_shared<BitCodeAbbrev>();
  753. Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
  754. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
  755. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
  756. TypeExtQualAbbrev = Stream.EmitAbbrev(std::move(Abv));
  757. // Abbreviation for TYPE_FUNCTION_PROTO
  758. Abv = std::make_shared<BitCodeAbbrev>();
  759. Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
  760. // FunctionType
  761. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
  762. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
  763. Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
  764. Abv->Add(BitCodeAbbrevOp(0)); // RegParm
  765. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
  766. Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
  767. Abv->Add(BitCodeAbbrevOp(0)); // NoCallerSavedRegs
  768. Abv->Add(BitCodeAbbrevOp(0)); // NoCfCheck
  769. // FunctionProtoType
  770. Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
  771. Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
  772. Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
  773. Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
  774. Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
  775. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
  776. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  777. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
  778. TypeFunctionProtoAbbrev = Stream.EmitAbbrev(std::move(Abv));
  779. }
  780. //===----------------------------------------------------------------------===//
  781. // ASTWriter Implementation
  782. //===----------------------------------------------------------------------===//
  783. static void EmitBlockID(unsigned ID, const char *Name,
  784. llvm::BitstreamWriter &Stream,
  785. ASTWriter::RecordDataImpl &Record) {
  786. Record.clear();
  787. Record.push_back(ID);
  788. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
  789. // Emit the block name if present.
  790. if (!Name || Name[0] == 0)
  791. return;
  792. Record.clear();
  793. while (*Name)
  794. Record.push_back(*Name++);
  795. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
  796. }
  797. static void EmitRecordID(unsigned ID, const char *Name,
  798. llvm::BitstreamWriter &Stream,
  799. ASTWriter::RecordDataImpl &Record) {
  800. Record.clear();
  801. Record.push_back(ID);
  802. while (*Name)
  803. Record.push_back(*Name++);
  804. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
  805. }
  806. static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
  807. ASTWriter::RecordDataImpl &Record) {
  808. #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
  809. RECORD(STMT_STOP);
  810. RECORD(STMT_NULL_PTR);
  811. RECORD(STMT_REF_PTR);
  812. RECORD(STMT_NULL);
  813. RECORD(STMT_COMPOUND);
  814. RECORD(STMT_CASE);
  815. RECORD(STMT_DEFAULT);
  816. RECORD(STMT_LABEL);
  817. RECORD(STMT_ATTRIBUTED);
  818. RECORD(STMT_IF);
  819. RECORD(STMT_SWITCH);
  820. RECORD(STMT_WHILE);
  821. RECORD(STMT_DO);
  822. RECORD(STMT_FOR);
  823. RECORD(STMT_GOTO);
  824. RECORD(STMT_INDIRECT_GOTO);
  825. RECORD(STMT_CONTINUE);
  826. RECORD(STMT_BREAK);
  827. RECORD(STMT_RETURN);
  828. RECORD(STMT_DECL);
  829. RECORD(STMT_GCCASM);
  830. RECORD(STMT_MSASM);
  831. RECORD(EXPR_PREDEFINED);
  832. RECORD(EXPR_DECL_REF);
  833. RECORD(EXPR_INTEGER_LITERAL);
  834. RECORD(EXPR_FLOATING_LITERAL);
  835. RECORD(EXPR_IMAGINARY_LITERAL);
  836. RECORD(EXPR_STRING_LITERAL);
  837. RECORD(EXPR_CHARACTER_LITERAL);
  838. RECORD(EXPR_PAREN);
  839. RECORD(EXPR_PAREN_LIST);
  840. RECORD(EXPR_UNARY_OPERATOR);
  841. RECORD(EXPR_SIZEOF_ALIGN_OF);
  842. RECORD(EXPR_ARRAY_SUBSCRIPT);
  843. RECORD(EXPR_CALL);
  844. RECORD(EXPR_MEMBER);
  845. RECORD(EXPR_BINARY_OPERATOR);
  846. RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
  847. RECORD(EXPR_CONDITIONAL_OPERATOR);
  848. RECORD(EXPR_IMPLICIT_CAST);
  849. RECORD(EXPR_CSTYLE_CAST);
  850. RECORD(EXPR_COMPOUND_LITERAL);
  851. RECORD(EXPR_EXT_VECTOR_ELEMENT);
  852. RECORD(EXPR_INIT_LIST);
  853. RECORD(EXPR_DESIGNATED_INIT);
  854. RECORD(EXPR_DESIGNATED_INIT_UPDATE);
  855. RECORD(EXPR_IMPLICIT_VALUE_INIT);
  856. RECORD(EXPR_NO_INIT);
  857. RECORD(EXPR_VA_ARG);
  858. RECORD(EXPR_ADDR_LABEL);
  859. RECORD(EXPR_STMT);
  860. RECORD(EXPR_CHOOSE);
  861. RECORD(EXPR_GNU_NULL);
  862. RECORD(EXPR_SHUFFLE_VECTOR);
  863. RECORD(EXPR_BLOCK);
  864. RECORD(EXPR_GENERIC_SELECTION);
  865. RECORD(EXPR_OBJC_STRING_LITERAL);
  866. RECORD(EXPR_OBJC_BOXED_EXPRESSION);
  867. RECORD(EXPR_OBJC_ARRAY_LITERAL);
  868. RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
  869. RECORD(EXPR_OBJC_ENCODE);
  870. RECORD(EXPR_OBJC_SELECTOR_EXPR);
  871. RECORD(EXPR_OBJC_PROTOCOL_EXPR);
  872. RECORD(EXPR_OBJC_IVAR_REF_EXPR);
  873. RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
  874. RECORD(EXPR_OBJC_KVC_REF_EXPR);
  875. RECORD(EXPR_OBJC_MESSAGE_EXPR);
  876. RECORD(STMT_OBJC_FOR_COLLECTION);
  877. RECORD(STMT_OBJC_CATCH);
  878. RECORD(STMT_OBJC_FINALLY);
  879. RECORD(STMT_OBJC_AT_TRY);
  880. RECORD(STMT_OBJC_AT_SYNCHRONIZED);
  881. RECORD(STMT_OBJC_AT_THROW);
  882. RECORD(EXPR_OBJC_BOOL_LITERAL);
  883. RECORD(STMT_CXX_CATCH);
  884. RECORD(STMT_CXX_TRY);
  885. RECORD(STMT_CXX_FOR_RANGE);
  886. RECORD(EXPR_CXX_OPERATOR_CALL);
  887. RECORD(EXPR_CXX_MEMBER_CALL);
  888. RECORD(EXPR_CXX_CONSTRUCT);
  889. RECORD(EXPR_CXX_TEMPORARY_OBJECT);
  890. RECORD(EXPR_CXX_STATIC_CAST);
  891. RECORD(EXPR_CXX_DYNAMIC_CAST);
  892. RECORD(EXPR_CXX_REINTERPRET_CAST);
  893. RECORD(EXPR_CXX_CONST_CAST);
  894. RECORD(EXPR_CXX_FUNCTIONAL_CAST);
  895. RECORD(EXPR_USER_DEFINED_LITERAL);
  896. RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
  897. RECORD(EXPR_CXX_BOOL_LITERAL);
  898. RECORD(EXPR_CXX_NULL_PTR_LITERAL);
  899. RECORD(EXPR_CXX_TYPEID_EXPR);
  900. RECORD(EXPR_CXX_TYPEID_TYPE);
  901. RECORD(EXPR_CXX_THIS);
  902. RECORD(EXPR_CXX_THROW);
  903. RECORD(EXPR_CXX_DEFAULT_ARG);
  904. RECORD(EXPR_CXX_DEFAULT_INIT);
  905. RECORD(EXPR_CXX_BIND_TEMPORARY);
  906. RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
  907. RECORD(EXPR_CXX_NEW);
  908. RECORD(EXPR_CXX_DELETE);
  909. RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
  910. RECORD(EXPR_EXPR_WITH_CLEANUPS);
  911. RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
  912. RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
  913. RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
  914. RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
  915. RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
  916. RECORD(EXPR_CXX_EXPRESSION_TRAIT);
  917. RECORD(EXPR_CXX_NOEXCEPT);
  918. RECORD(EXPR_OPAQUE_VALUE);
  919. RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
  920. RECORD(EXPR_TYPE_TRAIT);
  921. RECORD(EXPR_ARRAY_TYPE_TRAIT);
  922. RECORD(EXPR_PACK_EXPANSION);
  923. RECORD(EXPR_SIZEOF_PACK);
  924. RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
  925. RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
  926. RECORD(EXPR_FUNCTION_PARM_PACK);
  927. RECORD(EXPR_MATERIALIZE_TEMPORARY);
  928. RECORD(EXPR_CUDA_KERNEL_CALL);
  929. RECORD(EXPR_CXX_UUIDOF_EXPR);
  930. RECORD(EXPR_CXX_UUIDOF_TYPE);
  931. RECORD(EXPR_LAMBDA);
  932. #undef RECORD
  933. }
  934. void ASTWriter::WriteBlockInfoBlock() {
  935. RecordData Record;
  936. Stream.EnterBlockInfoBlock();
  937. #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
  938. #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
  939. // Control Block.
  940. BLOCK(CONTROL_BLOCK);
  941. RECORD(METADATA);
  942. RECORD(MODULE_NAME);
  943. RECORD(MODULE_DIRECTORY);
  944. RECORD(MODULE_MAP_FILE);
  945. RECORD(IMPORTS);
  946. RECORD(ORIGINAL_FILE);
  947. RECORD(ORIGINAL_PCH_DIR);
  948. RECORD(ORIGINAL_FILE_ID);
  949. RECORD(INPUT_FILE_OFFSETS);
  950. BLOCK(OPTIONS_BLOCK);
  951. RECORD(LANGUAGE_OPTIONS);
  952. RECORD(TARGET_OPTIONS);
  953. RECORD(FILE_SYSTEM_OPTIONS);
  954. RECORD(HEADER_SEARCH_OPTIONS);
  955. RECORD(PREPROCESSOR_OPTIONS);
  956. BLOCK(INPUT_FILES_BLOCK);
  957. RECORD(INPUT_FILE);
  958. // AST Top-Level Block.
  959. BLOCK(AST_BLOCK);
  960. RECORD(TYPE_OFFSET);
  961. RECORD(DECL_OFFSET);
  962. RECORD(IDENTIFIER_OFFSET);
  963. RECORD(IDENTIFIER_TABLE);
  964. RECORD(EAGERLY_DESERIALIZED_DECLS);
  965. RECORD(MODULAR_CODEGEN_DECLS);
  966. RECORD(SPECIAL_TYPES);
  967. RECORD(STATISTICS);
  968. RECORD(TENTATIVE_DEFINITIONS);
  969. RECORD(SELECTOR_OFFSETS);
  970. RECORD(METHOD_POOL);
  971. RECORD(PP_COUNTER_VALUE);
  972. RECORD(SOURCE_LOCATION_OFFSETS);
  973. RECORD(SOURCE_LOCATION_PRELOADS);
  974. RECORD(EXT_VECTOR_DECLS);
  975. RECORD(UNUSED_FILESCOPED_DECLS);
  976. RECORD(PPD_ENTITIES_OFFSETS);
  977. RECORD(VTABLE_USES);
  978. RECORD(PPD_SKIPPED_RANGES);
  979. RECORD(REFERENCED_SELECTOR_POOL);
  980. RECORD(TU_UPDATE_LEXICAL);
  981. RECORD(SEMA_DECL_REFS);
  982. RECORD(WEAK_UNDECLARED_IDENTIFIERS);
  983. RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
  984. RECORD(UPDATE_VISIBLE);
  985. RECORD(DECL_UPDATE_OFFSETS);
  986. RECORD(DECL_UPDATES);
  987. RECORD(CUDA_SPECIAL_DECL_REFS);
  988. RECORD(HEADER_SEARCH_TABLE);
  989. RECORD(FP_PRAGMA_OPTIONS);
  990. RECORD(OPENCL_EXTENSIONS);
  991. RECORD(OPENCL_EXTENSION_TYPES);
  992. RECORD(OPENCL_EXTENSION_DECLS);
  993. RECORD(DELEGATING_CTORS);
  994. RECORD(KNOWN_NAMESPACES);
  995. RECORD(MODULE_OFFSET_MAP);
  996. RECORD(SOURCE_MANAGER_LINE_TABLE);
  997. RECORD(OBJC_CATEGORIES_MAP);
  998. RECORD(FILE_SORTED_DECLS);
  999. RECORD(IMPORTED_MODULES);
  1000. RECORD(OBJC_CATEGORIES);
  1001. RECORD(MACRO_OFFSET);
  1002. RECORD(INTERESTING_IDENTIFIERS);
  1003. RECORD(UNDEFINED_BUT_USED);
  1004. RECORD(LATE_PARSED_TEMPLATE);
  1005. RECORD(OPTIMIZE_PRAGMA_OPTIONS);
  1006. RECORD(MSSTRUCT_PRAGMA_OPTIONS);
  1007. RECORD(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS);
  1008. RECORD(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES);
  1009. RECORD(DELETE_EXPRS_TO_ANALYZE);
  1010. RECORD(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH);
  1011. RECORD(PP_CONDITIONAL_STACK);
  1012. // SourceManager Block.
  1013. BLOCK(SOURCE_MANAGER_BLOCK);
  1014. RECORD(SM_SLOC_FILE_ENTRY);
  1015. RECORD(SM_SLOC_BUFFER_ENTRY);
  1016. RECORD(SM_SLOC_BUFFER_BLOB);
  1017. RECORD(SM_SLOC_BUFFER_BLOB_COMPRESSED);
  1018. RECORD(SM_SLOC_EXPANSION_ENTRY);
  1019. // Preprocessor Block.
  1020. BLOCK(PREPROCESSOR_BLOCK);
  1021. RECORD(PP_MACRO_DIRECTIVE_HISTORY);
  1022. RECORD(PP_MACRO_FUNCTION_LIKE);
  1023. RECORD(PP_MACRO_OBJECT_LIKE);
  1024. RECORD(PP_MODULE_MACRO);
  1025. RECORD(PP_TOKEN);
  1026. // Submodule Block.
  1027. BLOCK(SUBMODULE_BLOCK);
  1028. RECORD(SUBMODULE_METADATA);
  1029. RECORD(SUBMODULE_DEFINITION);
  1030. RECORD(SUBMODULE_UMBRELLA_HEADER);
  1031. RECORD(SUBMODULE_HEADER);
  1032. RECORD(SUBMODULE_TOPHEADER);
  1033. RECORD(SUBMODULE_UMBRELLA_DIR);
  1034. RECORD(SUBMODULE_IMPORTS);
  1035. RECORD(SUBMODULE_EXPORTS);
  1036. RECORD(SUBMODULE_REQUIRES);
  1037. RECORD(SUBMODULE_EXCLUDED_HEADER);
  1038. RECORD(SUBMODULE_LINK_LIBRARY);
  1039. RECORD(SUBMODULE_CONFIG_MACRO);
  1040. RECORD(SUBMODULE_CONFLICT);
  1041. RECORD(SUBMODULE_PRIVATE_HEADER);
  1042. RECORD(SUBMODULE_TEXTUAL_HEADER);
  1043. RECORD(SUBMODULE_PRIVATE_TEXTUAL_HEADER);
  1044. RECORD(SUBMODULE_INITIALIZERS);
  1045. RECORD(SUBMODULE_EXPORT_AS);
  1046. // Comments Block.
  1047. BLOCK(COMMENTS_BLOCK);
  1048. RECORD(COMMENTS_RAW_COMMENT);
  1049. // Decls and Types block.
  1050. BLOCK(DECLTYPES_BLOCK);
  1051. RECORD(TYPE_EXT_QUAL);
  1052. RECORD(TYPE_COMPLEX);
  1053. RECORD(TYPE_POINTER);
  1054. RECORD(TYPE_BLOCK_POINTER);
  1055. RECORD(TYPE_LVALUE_REFERENCE);
  1056. RECORD(TYPE_RVALUE_REFERENCE);
  1057. RECORD(TYPE_MEMBER_POINTER);
  1058. RECORD(TYPE_CONSTANT_ARRAY);
  1059. RECORD(TYPE_INCOMPLETE_ARRAY);
  1060. RECORD(TYPE_VARIABLE_ARRAY);
  1061. RECORD(TYPE_VECTOR);
  1062. RECORD(TYPE_EXT_VECTOR);
  1063. RECORD(TYPE_FUNCTION_NO_PROTO);
  1064. RECORD(TYPE_FUNCTION_PROTO);
  1065. RECORD(TYPE_TYPEDEF);
  1066. RECORD(TYPE_TYPEOF_EXPR);
  1067. RECORD(TYPE_TYPEOF);
  1068. RECORD(TYPE_RECORD);
  1069. RECORD(TYPE_ENUM);
  1070. RECORD(TYPE_OBJC_INTERFACE);
  1071. RECORD(TYPE_OBJC_OBJECT_POINTER);
  1072. RECORD(TYPE_DECLTYPE);
  1073. RECORD(TYPE_ELABORATED);
  1074. RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
  1075. RECORD(TYPE_UNRESOLVED_USING);
  1076. RECORD(TYPE_INJECTED_CLASS_NAME);
  1077. RECORD(TYPE_OBJC_OBJECT);
  1078. RECORD(TYPE_TEMPLATE_TYPE_PARM);
  1079. RECORD(TYPE_TEMPLATE_SPECIALIZATION);
  1080. RECORD(TYPE_DEPENDENT_NAME);
  1081. RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
  1082. RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
  1083. RECORD(TYPE_PAREN);
  1084. RECORD(TYPE_MACRO_QUALIFIED);
  1085. RECORD(TYPE_PACK_EXPANSION);
  1086. RECORD(TYPE_ATTRIBUTED);
  1087. RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
  1088. RECORD(TYPE_AUTO);
  1089. RECORD(TYPE_UNARY_TRANSFORM);
  1090. RECORD(TYPE_ATOMIC);
  1091. RECORD(TYPE_DECAYED);
  1092. RECORD(TYPE_ADJUSTED);
  1093. RECORD(TYPE_OBJC_TYPE_PARAM);
  1094. RECORD(LOCAL_REDECLARATIONS);
  1095. RECORD(DECL_TYPEDEF);
  1096. RECORD(DECL_TYPEALIAS);
  1097. RECORD(DECL_ENUM);
  1098. RECORD(DECL_RECORD);
  1099. RECORD(DECL_ENUM_CONSTANT);
  1100. RECORD(DECL_FUNCTION);
  1101. RECORD(DECL_OBJC_METHOD);
  1102. RECORD(DECL_OBJC_INTERFACE);
  1103. RECORD(DECL_OBJC_PROTOCOL);
  1104. RECORD(DECL_OBJC_IVAR);
  1105. RECORD(DECL_OBJC_AT_DEFS_FIELD);
  1106. RECORD(DECL_OBJC_CATEGORY);
  1107. RECORD(DECL_OBJC_CATEGORY_IMPL);
  1108. RECORD(DECL_OBJC_IMPLEMENTATION);
  1109. RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
  1110. RECORD(DECL_OBJC_PROPERTY);
  1111. RECORD(DECL_OBJC_PROPERTY_IMPL);
  1112. RECORD(DECL_FIELD);
  1113. RECORD(DECL_MS_PROPERTY);
  1114. RECORD(DECL_VAR);
  1115. RECORD(DECL_IMPLICIT_PARAM);
  1116. RECORD(DECL_PARM_VAR);
  1117. RECORD(DECL_FILE_SCOPE_ASM);
  1118. RECORD(DECL_BLOCK);
  1119. RECORD(DECL_CONTEXT_LEXICAL);
  1120. RECORD(DECL_CONTEXT_VISIBLE);
  1121. RECORD(DECL_NAMESPACE);
  1122. RECORD(DECL_NAMESPACE_ALIAS);
  1123. RECORD(DECL_USING);
  1124. RECORD(DECL_USING_SHADOW);
  1125. RECORD(DECL_USING_DIRECTIVE);
  1126. RECORD(DECL_UNRESOLVED_USING_VALUE);
  1127. RECORD(DECL_UNRESOLVED_USING_TYPENAME);
  1128. RECORD(DECL_LINKAGE_SPEC);
  1129. RECORD(DECL_CXX_RECORD);
  1130. RECORD(DECL_CXX_METHOD);
  1131. RECORD(DECL_CXX_CONSTRUCTOR);
  1132. RECORD(DECL_CXX_DESTRUCTOR);
  1133. RECORD(DECL_CXX_CONVERSION);
  1134. RECORD(DECL_ACCESS_SPEC);
  1135. RECORD(DECL_FRIEND);
  1136. RECORD(DECL_FRIEND_TEMPLATE);
  1137. RECORD(DECL_CLASS_TEMPLATE);
  1138. RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
  1139. RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
  1140. RECORD(DECL_VAR_TEMPLATE);
  1141. RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
  1142. RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
  1143. RECORD(DECL_FUNCTION_TEMPLATE);
  1144. RECORD(DECL_TEMPLATE_TYPE_PARM);
  1145. RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
  1146. RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
  1147. RECORD(DECL_CONCEPT);
  1148. RECORD(DECL_TYPE_ALIAS_TEMPLATE);
  1149. RECORD(DECL_STATIC_ASSERT);
  1150. RECORD(DECL_CXX_BASE_SPECIFIERS);
  1151. RECORD(DECL_CXX_CTOR_INITIALIZERS);
  1152. RECORD(DECL_INDIRECTFIELD);
  1153. RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
  1154. RECORD(DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK);
  1155. RECORD(DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION);
  1156. RECORD(DECL_IMPORT);
  1157. RECORD(DECL_OMP_THREADPRIVATE);
  1158. RECORD(DECL_EMPTY);
  1159. RECORD(DECL_OBJC_TYPE_PARAM);
  1160. RECORD(DECL_OMP_CAPTUREDEXPR);
  1161. RECORD(DECL_PRAGMA_COMMENT);
  1162. RECORD(DECL_PRAGMA_DETECT_MISMATCH);
  1163. RECORD(DECL_OMP_DECLARE_REDUCTION);
  1164. RECORD(DECL_OMP_ALLOCATE);
  1165. // Statements and Exprs can occur in the Decls and Types block.
  1166. AddStmtsExprs(Stream, Record);
  1167. BLOCK(PREPROCESSOR_DETAIL_BLOCK);
  1168. RECORD(PPD_MACRO_EXPANSION);
  1169. RECORD(PPD_MACRO_DEFINITION);
  1170. RECORD(PPD_INCLUSION_DIRECTIVE);
  1171. // Decls and Types block.
  1172. BLOCK(EXTENSION_BLOCK);
  1173. RECORD(EXTENSION_METADATA);
  1174. BLOCK(UNHASHED_CONTROL_BLOCK);
  1175. RECORD(SIGNATURE);
  1176. RECORD(DIAGNOSTIC_OPTIONS);
  1177. RECORD(DIAG_PRAGMA_MAPPINGS);
  1178. #undef RECORD
  1179. #undef BLOCK
  1180. Stream.ExitBlock();
  1181. }
  1182. /// Prepares a path for being written to an AST file by converting it
  1183. /// to an absolute path and removing nested './'s.
  1184. ///
  1185. /// \return \c true if the path was changed.
  1186. static bool cleanPathForOutput(FileManager &FileMgr,
  1187. SmallVectorImpl<char> &Path) {
  1188. bool Changed = FileMgr.makeAbsolutePath(Path);
  1189. return Changed | llvm::sys::path::remove_dots(Path);
  1190. }
  1191. /// Adjusts the given filename to only write out the portion of the
  1192. /// filename that is not part of the system root directory.
  1193. ///
  1194. /// \param Filename the file name to adjust.
  1195. ///
  1196. /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
  1197. /// the returned filename will be adjusted by this root directory.
  1198. ///
  1199. /// \returns either the original filename (if it needs no adjustment) or the
  1200. /// adjusted filename (which points into the @p Filename parameter).
  1201. static const char *
  1202. adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
  1203. assert(Filename && "No file name to adjust?");
  1204. if (BaseDir.empty())
  1205. return Filename;
  1206. // Verify that the filename and the system root have the same prefix.
  1207. unsigned Pos = 0;
  1208. for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
  1209. if (Filename[Pos] != BaseDir[Pos])
  1210. return Filename; // Prefixes don't match.
  1211. // We hit the end of the filename before we hit the end of the system root.
  1212. if (!Filename[Pos])
  1213. return Filename;
  1214. // If there's not a path separator at the end of the base directory nor
  1215. // immediately after it, then this isn't within the base directory.
  1216. if (!llvm::sys::path::is_separator(Filename[Pos])) {
  1217. if (!llvm::sys::path::is_separator(BaseDir.back()))
  1218. return Filename;
  1219. } else {
  1220. // If the file name has a '/' at the current position, skip over the '/'.
  1221. // We distinguish relative paths from absolute paths by the
  1222. // absence of '/' at the beginning of relative paths.
  1223. //
  1224. // FIXME: This is wrong. We distinguish them by asking if the path is
  1225. // absolute, which isn't the same thing. And there might be multiple '/'s
  1226. // in a row. Use a better mechanism to indicate whether we have emitted an
  1227. // absolute or relative path.
  1228. ++Pos;
  1229. }
  1230. return Filename + Pos;
  1231. }
  1232. ASTFileSignature ASTWriter::createSignature(StringRef Bytes) {
  1233. // Calculate the hash till start of UNHASHED_CONTROL_BLOCK.
  1234. llvm::SHA1 Hasher;
  1235. Hasher.update(ArrayRef<uint8_t>(Bytes.bytes_begin(), Bytes.size()));
  1236. auto Hash = Hasher.result();
  1237. // Convert to an array [5*i32].
  1238. ASTFileSignature Signature;
  1239. auto LShift = [&](unsigned char Val, unsigned Shift) {
  1240. return (uint32_t)Val << Shift;
  1241. };
  1242. for (int I = 0; I != 5; ++I)
  1243. Signature[I] = LShift(Hash[I * 4 + 0], 24) | LShift(Hash[I * 4 + 1], 16) |
  1244. LShift(Hash[I * 4 + 2], 8) | LShift(Hash[I * 4 + 3], 0);
  1245. return Signature;
  1246. }
  1247. ASTFileSignature ASTWriter::writeUnhashedControlBlock(Preprocessor &PP,
  1248. ASTContext &Context) {
  1249. // Flush first to prepare the PCM hash (signature).
  1250. Stream.FlushToWord();
  1251. auto StartOfUnhashedControl = Stream.GetCurrentBitNo() >> 3;
  1252. // Enter the block and prepare to write records.
  1253. RecordData Record;
  1254. Stream.EnterSubblock(UNHASHED_CONTROL_BLOCK_ID, 5);
  1255. // For implicit modules, write the hash of the PCM as its signature.
  1256. ASTFileSignature Signature;
  1257. if (WritingModule &&
  1258. PP.getHeaderSearchInfo().getHeaderSearchOpts().ModulesHashContent) {
  1259. Signature = createSignature(StringRef(Buffer.begin(), StartOfUnhashedControl));
  1260. Record.append(Signature.begin(), Signature.end());
  1261. Stream.EmitRecord(SIGNATURE, Record);
  1262. Record.clear();
  1263. }
  1264. // Diagnostic options.
  1265. const auto &Diags = Context.getDiagnostics();
  1266. const DiagnosticOptions &DiagOpts = Diags.getDiagnosticOptions();
  1267. #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
  1268. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  1269. Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
  1270. #include "clang/Basic/DiagnosticOptions.def"
  1271. Record.push_back(DiagOpts.Warnings.size());
  1272. for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
  1273. AddString(DiagOpts.Warnings[I], Record);
  1274. Record.push_back(DiagOpts.Remarks.size());
  1275. for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
  1276. AddString(DiagOpts.Remarks[I], Record);
  1277. // Note: we don't serialize the log or serialization file names, because they
  1278. // are generally transient files and will almost always be overridden.
  1279. Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
  1280. // Write out the diagnostic/pragma mappings.
  1281. WritePragmaDiagnosticMappings(Diags, /* isModule = */ WritingModule);
  1282. // Leave the options block.
  1283. Stream.ExitBlock();
  1284. return Signature;
  1285. }
  1286. /// Write the control block.
  1287. void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
  1288. StringRef isysroot,
  1289. const std::string &OutputFile) {
  1290. using namespace llvm;
  1291. Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
  1292. RecordData Record;
  1293. // Metadata
  1294. auto MetadataAbbrev = std::make_shared<BitCodeAbbrev>();
  1295. MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
  1296. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
  1297. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
  1298. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
  1299. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
  1300. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
  1301. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Timestamps
  1302. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // PCHHasObjectFile
  1303. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
  1304. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
  1305. unsigned MetadataAbbrevCode = Stream.EmitAbbrev(std::move(MetadataAbbrev));
  1306. assert((!WritingModule || isysroot.empty()) &&
  1307. "writing module as a relocatable PCH?");
  1308. {
  1309. RecordData::value_type Record[] = {
  1310. METADATA,
  1311. VERSION_MAJOR,
  1312. VERSION_MINOR,
  1313. CLANG_VERSION_MAJOR,
  1314. CLANG_VERSION_MINOR,
  1315. !isysroot.empty(),
  1316. IncludeTimestamps,
  1317. Context.getLangOpts().BuildingPCHWithObjectFile,
  1318. ASTHasCompilerErrors};
  1319. Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
  1320. getClangFullRepositoryVersion());
  1321. }
  1322. if (WritingModule) {
  1323. // Module name
  1324. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1325. Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
  1326. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  1327. unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
  1328. RecordData::value_type Record[] = {MODULE_NAME};
  1329. Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
  1330. }
  1331. if (WritingModule && WritingModule->Directory) {
  1332. SmallString<128> BaseDir(WritingModule->Directory->getName());
  1333. cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
  1334. // If the home of the module is the current working directory, then we
  1335. // want to pick up the cwd of the build process loading the module, not
  1336. // our cwd, when we load this module.
  1337. if (!PP.getHeaderSearchInfo()
  1338. .getHeaderSearchOpts()
  1339. .ModuleMapFileHomeIsCwd ||
  1340. WritingModule->Directory->getName() != StringRef(".")) {
  1341. // Module directory.
  1342. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1343. Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
  1344. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
  1345. unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
  1346. RecordData::value_type Record[] = {MODULE_DIRECTORY};
  1347. Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
  1348. }
  1349. // Write out all other paths relative to the base directory if possible.
  1350. BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
  1351. } else if (!isysroot.empty()) {
  1352. // Write out paths relative to the sysroot if possible.
  1353. BaseDirectory = isysroot;
  1354. }
  1355. // Module map file
  1356. if (WritingModule && WritingModule->Kind == Module::ModuleMapModule) {
  1357. Record.clear();
  1358. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  1359. AddPath(WritingModule->PresumedModuleMapFile.empty()
  1360. ? Map.getModuleMapFileForUniquing(WritingModule)->getName()
  1361. : StringRef(WritingModule->PresumedModuleMapFile),
  1362. Record);
  1363. // Additional module map files.
  1364. if (auto *AdditionalModMaps =
  1365. Map.getAdditionalModuleMapFiles(WritingModule)) {
  1366. Record.push_back(AdditionalModMaps->size());
  1367. for (const FileEntry *F : *AdditionalModMaps)
  1368. AddPath(F->getName(), Record);
  1369. } else {
  1370. Record.push_back(0);
  1371. }
  1372. Stream.EmitRecord(MODULE_MAP_FILE, Record);
  1373. }
  1374. // Imports
  1375. if (Chain) {
  1376. serialization::ModuleManager &Mgr = Chain->getModuleManager();
  1377. Record.clear();
  1378. for (ModuleFile &M : Mgr) {
  1379. // Skip modules that weren't directly imported.
  1380. if (!M.isDirectlyImported())
  1381. continue;
  1382. Record.push_back((unsigned)M.Kind); // FIXME: Stable encoding
  1383. AddSourceLocation(M.ImportLoc, Record);
  1384. // If we have calculated signature, there is no need to store
  1385. // the size or timestamp.
  1386. Record.push_back(M.Signature ? 0 : M.File->getSize());
  1387. Record.push_back(M.Signature ? 0 : getTimestampForOutput(M.File));
  1388. for (auto I : M.Signature)
  1389. Record.push_back(I);
  1390. AddString(M.ModuleName, Record);
  1391. AddPath(M.FileName, Record);
  1392. }
  1393. Stream.EmitRecord(IMPORTS, Record);
  1394. }
  1395. // Write the options block.
  1396. Stream.EnterSubblock(OPTIONS_BLOCK_ID, 4);
  1397. // Language options.
  1398. Record.clear();
  1399. const LangOptions &LangOpts = Context.getLangOpts();
  1400. #define LANGOPT(Name, Bits, Default, Description) \
  1401. Record.push_back(LangOpts.Name);
  1402. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  1403. Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
  1404. #include "clang/Basic/LangOptions.def"
  1405. #define SANITIZER(NAME, ID) \
  1406. Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
  1407. #include "clang/Basic/Sanitizers.def"
  1408. Record.push_back(LangOpts.ModuleFeatures.size());
  1409. for (StringRef Feature : LangOpts.ModuleFeatures)
  1410. AddString(Feature, Record);
  1411. Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
  1412. AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
  1413. AddString(LangOpts.CurrentModule, Record);
  1414. // Comment options.
  1415. Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
  1416. for (const auto &I : LangOpts.CommentOpts.BlockCommandNames) {
  1417. AddString(I, Record);
  1418. }
  1419. Record.push_back(LangOpts.CommentOpts.ParseAllComments);
  1420. // OpenMP offloading options.
  1421. Record.push_back(LangOpts.OMPTargetTriples.size());
  1422. for (auto &T : LangOpts.OMPTargetTriples)
  1423. AddString(T.getTriple(), Record);
  1424. AddString(LangOpts.OMPHostIRFile, Record);
  1425. Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
  1426. // Target options.
  1427. Record.clear();
  1428. const TargetInfo &Target = Context.getTargetInfo();
  1429. const TargetOptions &TargetOpts = Target.getTargetOpts();
  1430. AddString(TargetOpts.Triple, Record);
  1431. AddString(TargetOpts.CPU, Record);
  1432. AddString(TargetOpts.ABI, Record);
  1433. Record.push_back(TargetOpts.FeaturesAsWritten.size());
  1434. for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
  1435. AddString(TargetOpts.FeaturesAsWritten[I], Record);
  1436. }
  1437. Record.push_back(TargetOpts.Features.size());
  1438. for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
  1439. AddString(TargetOpts.Features[I], Record);
  1440. }
  1441. Stream.EmitRecord(TARGET_OPTIONS, Record);
  1442. // File system options.
  1443. Record.clear();
  1444. const FileSystemOptions &FSOpts =
  1445. Context.getSourceManager().getFileManager().getFileSystemOpts();
  1446. AddString(FSOpts.WorkingDir, Record);
  1447. Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
  1448. // Header search options.
  1449. Record.clear();
  1450. const HeaderSearchOptions &HSOpts
  1451. = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  1452. AddString(HSOpts.Sysroot, Record);
  1453. // Include entries.
  1454. Record.push_back(HSOpts.UserEntries.size());
  1455. for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
  1456. const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
  1457. AddString(Entry.Path, Record);
  1458. Record.push_back(static_cast<unsigned>(Entry.Group));
  1459. Record.push_back(Entry.IsFramework);
  1460. Record.push_back(Entry.IgnoreSysRoot);
  1461. }
  1462. // System header prefixes.
  1463. Record.push_back(HSOpts.SystemHeaderPrefixes.size());
  1464. for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
  1465. AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
  1466. Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
  1467. }
  1468. AddString(HSOpts.ResourceDir, Record);
  1469. AddString(HSOpts.ModuleCachePath, Record);
  1470. AddString(HSOpts.ModuleUserBuildPath, Record);
  1471. Record.push_back(HSOpts.DisableModuleHash);
  1472. Record.push_back(HSOpts.ImplicitModuleMaps);
  1473. Record.push_back(HSOpts.ModuleMapFileHomeIsCwd);
  1474. Record.push_back(HSOpts.UseBuiltinIncludes);
  1475. Record.push_back(HSOpts.UseStandardSystemIncludes);
  1476. Record.push_back(HSOpts.UseStandardCXXIncludes);
  1477. Record.push_back(HSOpts.UseLibcxx);
  1478. // Write out the specific module cache path that contains the module files.
  1479. AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
  1480. Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
  1481. // Preprocessor options.
  1482. Record.clear();
  1483. const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
  1484. // Macro definitions.
  1485. Record.push_back(PPOpts.Macros.size());
  1486. for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
  1487. AddString(PPOpts.Macros[I].first, Record);
  1488. Record.push_back(PPOpts.Macros[I].second);
  1489. }
  1490. // Includes
  1491. Record.push_back(PPOpts.Includes.size());
  1492. for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
  1493. AddString(PPOpts.Includes[I], Record);
  1494. // Macro includes
  1495. Record.push_back(PPOpts.MacroIncludes.size());
  1496. for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
  1497. AddString(PPOpts.MacroIncludes[I], Record);
  1498. Record.push_back(PPOpts.UsePredefines);
  1499. // Detailed record is important since it is used for the module cache hash.
  1500. Record.push_back(PPOpts.DetailedRecord);
  1501. AddString(PPOpts.ImplicitPCHInclude, Record);
  1502. Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
  1503. Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
  1504. // Leave the options block.
  1505. Stream.ExitBlock();
  1506. // Original file name and file ID
  1507. SourceManager &SM = Context.getSourceManager();
  1508. if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1509. auto FileAbbrev = std::make_shared<BitCodeAbbrev>();
  1510. FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
  1511. FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
  1512. FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1513. unsigned FileAbbrevCode = Stream.EmitAbbrev(std::move(FileAbbrev));
  1514. Record.clear();
  1515. Record.push_back(ORIGINAL_FILE);
  1516. Record.push_back(SM.getMainFileID().getOpaqueValue());
  1517. EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
  1518. }
  1519. Record.clear();
  1520. Record.push_back(SM.getMainFileID().getOpaqueValue());
  1521. Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
  1522. // Original PCH directory
  1523. if (!OutputFile.empty() && OutputFile != "-") {
  1524. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1525. Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
  1526. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1527. unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
  1528. SmallString<128> OutputPath(OutputFile);
  1529. SM.getFileManager().makeAbsolutePath(OutputPath);
  1530. StringRef origDir = llvm::sys::path::parent_path(OutputPath);
  1531. RecordData::value_type Record[] = {ORIGINAL_PCH_DIR};
  1532. Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
  1533. }
  1534. WriteInputFiles(Context.SourceMgr,
  1535. PP.getHeaderSearchInfo().getHeaderSearchOpts(),
  1536. PP.getLangOpts().Modules);
  1537. Stream.ExitBlock();
  1538. }
  1539. namespace {
  1540. /// An input file.
  1541. struct InputFileEntry {
  1542. const FileEntry *File;
  1543. bool IsSystemFile;
  1544. bool IsTransient;
  1545. bool BufferOverridden;
  1546. bool IsTopLevelModuleMap;
  1547. };
  1548. } // namespace
  1549. void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
  1550. HeaderSearchOptions &HSOpts,
  1551. bool Modules) {
  1552. using namespace llvm;
  1553. Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
  1554. // Create input-file abbreviation.
  1555. auto IFAbbrev = std::make_shared<BitCodeAbbrev>();
  1556. IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
  1557. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
  1558. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
  1559. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
  1560. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
  1561. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Transient
  1562. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Module map
  1563. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1564. unsigned IFAbbrevCode = Stream.EmitAbbrev(std::move(IFAbbrev));
  1565. // Get all ContentCache objects for files, sorted by whether the file is a
  1566. // system one or not. System files go at the back, users files at the front.
  1567. std::deque<InputFileEntry> SortedFiles;
  1568. for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
  1569. // Get this source location entry.
  1570. const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
  1571. assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
  1572. // We only care about file entries that were not overridden.
  1573. if (!SLoc->isFile())
  1574. continue;
  1575. const SrcMgr::FileInfo &File = SLoc->getFile();
  1576. const SrcMgr::ContentCache *Cache = File.getContentCache();
  1577. if (!Cache->OrigEntry)
  1578. continue;
  1579. InputFileEntry Entry;
  1580. Entry.File = Cache->OrigEntry;
  1581. Entry.IsSystemFile = isSystem(File.getFileCharacteristic());
  1582. Entry.IsTransient = Cache->IsTransient;
  1583. Entry.BufferOverridden = Cache->BufferOverridden;
  1584. Entry.IsTopLevelModuleMap = isModuleMap(File.getFileCharacteristic()) &&
  1585. File.getIncludeLoc().isInvalid();
  1586. if (Entry.IsSystemFile)
  1587. SortedFiles.push_back(Entry);
  1588. else
  1589. SortedFiles.push_front(Entry);
  1590. }
  1591. unsigned UserFilesNum = 0;
  1592. // Write out all of the input files.
  1593. std::vector<uint64_t> InputFileOffsets;
  1594. for (const auto &Entry : SortedFiles) {
  1595. uint32_t &InputFileID = InputFileIDs[Entry.File];
  1596. if (InputFileID != 0)
  1597. continue; // already recorded this file.
  1598. // Record this entry's offset.
  1599. InputFileOffsets.push_back(Stream.GetCurrentBitNo());
  1600. InputFileID = InputFileOffsets.size();
  1601. if (!Entry.IsSystemFile)
  1602. ++UserFilesNum;
  1603. // Emit size/modification time for this file.
  1604. // And whether this file was overridden.
  1605. RecordData::value_type Record[] = {
  1606. INPUT_FILE,
  1607. InputFileOffsets.size(),
  1608. (uint64_t)Entry.File->getSize(),
  1609. (uint64_t)getTimestampForOutput(Entry.File),
  1610. Entry.BufferOverridden,
  1611. Entry.IsTransient,
  1612. Entry.IsTopLevelModuleMap};
  1613. // FIXME: The path should be taken from the FileEntryRef.
  1614. EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
  1615. }
  1616. Stream.ExitBlock();
  1617. // Create input file offsets abbreviation.
  1618. auto OffsetsAbbrev = std::make_shared<BitCodeAbbrev>();
  1619. OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
  1620. OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
  1621. OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
  1622. // input files
  1623. OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
  1624. unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(std::move(OffsetsAbbrev));
  1625. // Write input file offsets.
  1626. RecordData::value_type Record[] = {INPUT_FILE_OFFSETS,
  1627. InputFileOffsets.size(), UserFilesNum};
  1628. Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
  1629. }
  1630. //===----------------------------------------------------------------------===//
  1631. // Source Manager Serialization
  1632. //===----------------------------------------------------------------------===//
  1633. /// Create an abbreviation for the SLocEntry that refers to a
  1634. /// file.
  1635. static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
  1636. using namespace llvm;
  1637. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1638. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
  1639. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1640. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
  1641. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
  1642. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
  1643. // FileEntry fields.
  1644. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
  1645. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
  1646. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
  1647. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
  1648. return Stream.EmitAbbrev(std::move(Abbrev));
  1649. }
  1650. /// Create an abbreviation for the SLocEntry that refers to a
  1651. /// buffer.
  1652. static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
  1653. using namespace llvm;
  1654. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1655. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
  1656. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1657. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
  1658. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 3)); // Characteristic
  1659. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
  1660. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
  1661. return Stream.EmitAbbrev(std::move(Abbrev));
  1662. }
  1663. /// Create an abbreviation for the SLocEntry that refers to a
  1664. /// buffer's blob.
  1665. static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream,
  1666. bool Compressed) {
  1667. using namespace llvm;
  1668. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1669. Abbrev->Add(BitCodeAbbrevOp(Compressed ? SM_SLOC_BUFFER_BLOB_COMPRESSED
  1670. : SM_SLOC_BUFFER_BLOB));
  1671. if (Compressed)
  1672. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Uncompressed size
  1673. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
  1674. return Stream.EmitAbbrev(std::move(Abbrev));
  1675. }
  1676. /// Create an abbreviation for the SLocEntry that refers to a macro
  1677. /// expansion.
  1678. static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
  1679. using namespace llvm;
  1680. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1681. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
  1682. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1683. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
  1684. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
  1685. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
  1686. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Is token range
  1687. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
  1688. return Stream.EmitAbbrev(std::move(Abbrev));
  1689. }
  1690. namespace {
  1691. // Trait used for the on-disk hash table of header search information.
  1692. class HeaderFileInfoTrait {
  1693. ASTWriter &Writer;
  1694. // Keep track of the framework names we've used during serialization.
  1695. SmallVector<char, 128> FrameworkStringData;
  1696. llvm::StringMap<unsigned> FrameworkNameOffset;
  1697. public:
  1698. HeaderFileInfoTrait(ASTWriter &Writer) : Writer(Writer) {}
  1699. struct key_type {
  1700. StringRef Filename;
  1701. off_t Size;
  1702. time_t ModTime;
  1703. };
  1704. using key_type_ref = const key_type &;
  1705. using UnresolvedModule =
  1706. llvm::PointerIntPair<Module *, 2, ModuleMap::ModuleHeaderRole>;
  1707. struct data_type {
  1708. const HeaderFileInfo &HFI;
  1709. ArrayRef<ModuleMap::KnownHeader> KnownHeaders;
  1710. UnresolvedModule Unresolved;
  1711. };
  1712. using data_type_ref = const data_type &;
  1713. using hash_value_type = unsigned;
  1714. using offset_type = unsigned;
  1715. hash_value_type ComputeHash(key_type_ref key) {
  1716. // The hash is based only on size/time of the file, so that the reader can
  1717. // match even when symlinking or excess path elements ("foo/../", "../")
  1718. // change the form of the name. However, complete path is still the key.
  1719. return llvm::hash_combine(key.Size, key.ModTime);
  1720. }
  1721. std::pair<unsigned, unsigned>
  1722. EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
  1723. using namespace llvm::support;
  1724. endian::Writer LE(Out, little);
  1725. unsigned KeyLen = key.Filename.size() + 1 + 8 + 8;
  1726. LE.write<uint16_t>(KeyLen);
  1727. unsigned DataLen = 1 + 2 + 4 + 4;
  1728. for (auto ModInfo : Data.KnownHeaders)
  1729. if (Writer.getLocalOrImportedSubmoduleID(ModInfo.getModule()))
  1730. DataLen += 4;
  1731. if (Data.Unresolved.getPointer())
  1732. DataLen += 4;
  1733. LE.write<uint8_t>(DataLen);
  1734. return std::make_pair(KeyLen, DataLen);
  1735. }
  1736. void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
  1737. using namespace llvm::support;
  1738. endian::Writer LE(Out, little);
  1739. LE.write<uint64_t>(key.Size);
  1740. KeyLen -= 8;
  1741. LE.write<uint64_t>(key.ModTime);
  1742. KeyLen -= 8;
  1743. Out.write(key.Filename.data(), KeyLen);
  1744. }
  1745. void EmitData(raw_ostream &Out, key_type_ref key,
  1746. data_type_ref Data, unsigned DataLen) {
  1747. using namespace llvm::support;
  1748. endian::Writer LE(Out, little);
  1749. uint64_t Start = Out.tell(); (void)Start;
  1750. unsigned char Flags = (Data.HFI.isImport << 5)
  1751. | (Data.HFI.isPragmaOnce << 4)
  1752. | (Data.HFI.DirInfo << 1)
  1753. | Data.HFI.IndexHeaderMapHeader;
  1754. LE.write<uint8_t>(Flags);
  1755. LE.write<uint16_t>(Data.HFI.NumIncludes);
  1756. if (!Data.HFI.ControllingMacro)
  1757. LE.write<uint32_t>(Data.HFI.ControllingMacroID);
  1758. else
  1759. LE.write<uint32_t>(Writer.getIdentifierRef(Data.HFI.ControllingMacro));
  1760. unsigned Offset = 0;
  1761. if (!Data.HFI.Framework.empty()) {
  1762. // If this header refers into a framework, save the framework name.
  1763. llvm::StringMap<unsigned>::iterator Pos
  1764. = FrameworkNameOffset.find(Data.HFI.Framework);
  1765. if (Pos == FrameworkNameOffset.end()) {
  1766. Offset = FrameworkStringData.size() + 1;
  1767. FrameworkStringData.append(Data.HFI.Framework.begin(),
  1768. Data.HFI.Framework.end());
  1769. FrameworkStringData.push_back(0);
  1770. FrameworkNameOffset[Data.HFI.Framework] = Offset;
  1771. } else
  1772. Offset = Pos->second;
  1773. }
  1774. LE.write<uint32_t>(Offset);
  1775. auto EmitModule = [&](Module *M, ModuleMap::ModuleHeaderRole Role) {
  1776. if (uint32_t ModID = Writer.getLocalOrImportedSubmoduleID(M)) {
  1777. uint32_t Value = (ModID << 2) | (unsigned)Role;
  1778. assert((Value >> 2) == ModID && "overflow in header module info");
  1779. LE.write<uint32_t>(Value);
  1780. }
  1781. };
  1782. // FIXME: If the header is excluded, we should write out some
  1783. // record of that fact.
  1784. for (auto ModInfo : Data.KnownHeaders)
  1785. EmitModule(ModInfo.getModule(), ModInfo.getRole());
  1786. if (Data.Unresolved.getPointer())
  1787. EmitModule(Data.Unresolved.getPointer(), Data.Unresolved.getInt());
  1788. assert(Out.tell() - Start == DataLen && "Wrong data length");
  1789. }
  1790. const char *strings_begin() const { return FrameworkStringData.begin(); }
  1791. const char *strings_end() const { return FrameworkStringData.end(); }
  1792. };
  1793. } // namespace
  1794. /// Write the header search block for the list of files that
  1795. ///
  1796. /// \param HS The header search structure to save.
  1797. void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
  1798. HeaderFileInfoTrait GeneratorTrait(*this);
  1799. llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
  1800. SmallVector<const char *, 4> SavedStrings;
  1801. unsigned NumHeaderSearchEntries = 0;
  1802. // Find all unresolved headers for the current module. We generally will
  1803. // have resolved them before we get here, but not necessarily: we might be
  1804. // compiling a preprocessed module, where there is no requirement for the
  1805. // original files to exist any more.
  1806. const HeaderFileInfo Empty; // So we can take a reference.
  1807. if (WritingModule) {
  1808. llvm::SmallVector<Module *, 16> Worklist(1, WritingModule);
  1809. while (!Worklist.empty()) {
  1810. Module *M = Worklist.pop_back_val();
  1811. if (!M->isAvailable())
  1812. continue;
  1813. // Map to disk files where possible, to pick up any missing stat
  1814. // information. This also means we don't need to check the unresolved
  1815. // headers list when emitting resolved headers in the first loop below.
  1816. // FIXME: It'd be preferable to avoid doing this if we were given
  1817. // sufficient stat information in the module map.
  1818. HS.getModuleMap().resolveHeaderDirectives(M);
  1819. // If the file didn't exist, we can still create a module if we were given
  1820. // enough information in the module map.
  1821. for (auto U : M->MissingHeaders) {
  1822. // Check that we were given enough information to build a module
  1823. // without this file existing on disk.
  1824. if (!U.Size || (!U.ModTime && IncludeTimestamps)) {
  1825. PP->Diag(U.FileNameLoc, diag::err_module_no_size_mtime_for_header)
  1826. << WritingModule->getFullModuleName() << U.Size.hasValue()
  1827. << U.FileName;
  1828. continue;
  1829. }
  1830. // Form the effective relative pathname for the file.
  1831. SmallString<128> Filename(M->Directory->getName());
  1832. llvm::sys::path::append(Filename, U.FileName);
  1833. PreparePathForOutput(Filename);
  1834. StringRef FilenameDup = strdup(Filename.c_str());
  1835. SavedStrings.push_back(FilenameDup.data());
  1836. HeaderFileInfoTrait::key_type Key = {
  1837. FilenameDup, *U.Size, IncludeTimestamps ? *U.ModTime : 0
  1838. };
  1839. HeaderFileInfoTrait::data_type Data = {
  1840. Empty, {}, {M, ModuleMap::headerKindToRole(U.Kind)}
  1841. };
  1842. // FIXME: Deal with cases where there are multiple unresolved header
  1843. // directives in different submodules for the same header.
  1844. Generator.insert(Key, Data, GeneratorTrait);
  1845. ++NumHeaderSearchEntries;
  1846. }
  1847. Worklist.append(M->submodule_begin(), M->submodule_end());
  1848. }
  1849. }
  1850. SmallVector<const FileEntry *, 16> FilesByUID;
  1851. HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
  1852. if (FilesByUID.size() > HS.header_file_size())
  1853. FilesByUID.resize(HS.header_file_size());
  1854. for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
  1855. const FileEntry *File = FilesByUID[UID];
  1856. if (!File)
  1857. continue;
  1858. // Get the file info. This will load info from the external source if
  1859. // necessary. Skip emitting this file if we have no information on it
  1860. // as a header file (in which case HFI will be null) or if it hasn't
  1861. // changed since it was loaded. Also skip it if it's for a modular header
  1862. // from a different module; in that case, we rely on the module(s)
  1863. // containing the header to provide this information.
  1864. const HeaderFileInfo *HFI =
  1865. HS.getExistingFileInfo(File, /*WantExternal*/!Chain);
  1866. if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
  1867. continue;
  1868. // Massage the file path into an appropriate form.
  1869. StringRef Filename = File->getName();
  1870. SmallString<128> FilenameTmp(Filename);
  1871. if (PreparePathForOutput(FilenameTmp)) {
  1872. // If we performed any translation on the file name at all, we need to
  1873. // save this string, since the generator will refer to it later.
  1874. Filename = StringRef(strdup(FilenameTmp.c_str()));
  1875. SavedStrings.push_back(Filename.data());
  1876. }
  1877. HeaderFileInfoTrait::key_type Key = {
  1878. Filename, File->getSize(), getTimestampForOutput(File)
  1879. };
  1880. HeaderFileInfoTrait::data_type Data = {
  1881. *HFI, HS.getModuleMap().findAllModulesForHeader(File), {}
  1882. };
  1883. Generator.insert(Key, Data, GeneratorTrait);
  1884. ++NumHeaderSearchEntries;
  1885. }
  1886. // Create the on-disk hash table in a buffer.
  1887. SmallString<4096> TableData;
  1888. uint32_t BucketOffset;
  1889. {
  1890. using namespace llvm::support;
  1891. llvm::raw_svector_ostream Out(TableData);
  1892. // Make sure that no bucket is at offset 0
  1893. endian::write<uint32_t>(Out, 0, little);
  1894. BucketOffset = Generator.Emit(Out, GeneratorTrait);
  1895. }
  1896. // Create a blob abbreviation
  1897. using namespace llvm;
  1898. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  1899. Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
  1900. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1901. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1902. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1903. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1904. unsigned TableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  1905. // Write the header search table
  1906. RecordData::value_type Record[] = {HEADER_SEARCH_TABLE, BucketOffset,
  1907. NumHeaderSearchEntries, TableData.size()};
  1908. TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
  1909. Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
  1910. // Free all of the strings we had to duplicate.
  1911. for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
  1912. free(const_cast<char *>(SavedStrings[I]));
  1913. }
  1914. static void emitBlob(llvm::BitstreamWriter &Stream, StringRef Blob,
  1915. unsigned SLocBufferBlobCompressedAbbrv,
  1916. unsigned SLocBufferBlobAbbrv) {
  1917. using RecordDataType = ASTWriter::RecordData::value_type;
  1918. // Compress the buffer if possible. We expect that almost all PCM
  1919. // consumers will not want its contents.
  1920. SmallString<0> CompressedBuffer;
  1921. if (llvm::zlib::isAvailable()) {
  1922. llvm::Error E = llvm::zlib::compress(Blob.drop_back(1), CompressedBuffer);
  1923. if (!E) {
  1924. RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB_COMPRESSED,
  1925. Blob.size() - 1};
  1926. Stream.EmitRecordWithBlob(SLocBufferBlobCompressedAbbrv, Record,
  1927. CompressedBuffer);
  1928. return;
  1929. }
  1930. llvm::consumeError(std::move(E));
  1931. }
  1932. RecordDataType Record[] = {SM_SLOC_BUFFER_BLOB};
  1933. Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record, Blob);
  1934. }
  1935. /// Writes the block containing the serialized form of the
  1936. /// source manager.
  1937. ///
  1938. /// TODO: We should probably use an on-disk hash table (stored in a
  1939. /// blob), indexed based on the file name, so that we only create
  1940. /// entries for files that we actually need. In the common case (no
  1941. /// errors), we probably won't have to create file entries for any of
  1942. /// the files in the AST.
  1943. void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
  1944. const Preprocessor &PP) {
  1945. RecordData Record;
  1946. // Enter the source manager block.
  1947. Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 4);
  1948. // Abbreviations for the various kinds of source-location entries.
  1949. unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
  1950. unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
  1951. unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream, false);
  1952. unsigned SLocBufferBlobCompressedAbbrv =
  1953. CreateSLocBufferBlobAbbrev(Stream, true);
  1954. unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
  1955. // Write out the source location entry table. We skip the first
  1956. // entry, which is always the same dummy entry.
  1957. std::vector<uint32_t> SLocEntryOffsets;
  1958. RecordData PreloadSLocs;
  1959. SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
  1960. for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
  1961. I != N; ++I) {
  1962. // Get this source location entry.
  1963. const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
  1964. FileID FID = FileID::get(I);
  1965. assert(&SourceMgr.getSLocEntry(FID) == SLoc);
  1966. // Record the offset of this source-location entry.
  1967. SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
  1968. // Figure out which record code to use.
  1969. unsigned Code;
  1970. if (SLoc->isFile()) {
  1971. const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
  1972. if (Cache->OrigEntry) {
  1973. Code = SM_SLOC_FILE_ENTRY;
  1974. } else
  1975. Code = SM_SLOC_BUFFER_ENTRY;
  1976. } else
  1977. Code = SM_SLOC_EXPANSION_ENTRY;
  1978. Record.clear();
  1979. Record.push_back(Code);
  1980. // Starting offset of this entry within this module, so skip the dummy.
  1981. Record.push_back(SLoc->getOffset() - 2);
  1982. if (SLoc->isFile()) {
  1983. const SrcMgr::FileInfo &File = SLoc->getFile();
  1984. AddSourceLocation(File.getIncludeLoc(), Record);
  1985. Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
  1986. Record.push_back(File.hasLineDirectives());
  1987. const SrcMgr::ContentCache *Content = File.getContentCache();
  1988. bool EmitBlob = false;
  1989. if (Content->OrigEntry) {
  1990. assert(Content->OrigEntry == Content->ContentsEntry &&
  1991. "Writing to AST an overridden file is not supported");
  1992. // The source location entry is a file. Emit input file ID.
  1993. assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
  1994. Record.push_back(InputFileIDs[Content->OrigEntry]);
  1995. Record.push_back(File.NumCreatedFIDs);
  1996. FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
  1997. if (FDI != FileDeclIDs.end()) {
  1998. Record.push_back(FDI->second->FirstDeclIndex);
  1999. Record.push_back(FDI->second->DeclIDs.size());
  2000. } else {
  2001. Record.push_back(0);
  2002. Record.push_back(0);
  2003. }
  2004. Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
  2005. if (Content->BufferOverridden || Content->IsTransient)
  2006. EmitBlob = true;
  2007. } else {
  2008. // The source location entry is a buffer. The blob associated
  2009. // with this entry contains the contents of the buffer.
  2010. // We add one to the size so that we capture the trailing NULL
  2011. // that is required by llvm::MemoryBuffer::getMemBuffer (on
  2012. // the reader side).
  2013. const llvm::MemoryBuffer *Buffer =
  2014. Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
  2015. StringRef Name = Buffer->getBufferIdentifier();
  2016. Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
  2017. StringRef(Name.data(), Name.size() + 1));
  2018. EmitBlob = true;
  2019. if (Name == "<built-in>")
  2020. PreloadSLocs.push_back(SLocEntryOffsets.size());
  2021. }
  2022. if (EmitBlob) {
  2023. // Include the implicit terminating null character in the on-disk buffer
  2024. // if we're writing it uncompressed.
  2025. const llvm::MemoryBuffer *Buffer =
  2026. Content->getBuffer(PP.getDiagnostics(), PP.getFileManager());
  2027. StringRef Blob(Buffer->getBufferStart(), Buffer->getBufferSize() + 1);
  2028. emitBlob(Stream, Blob, SLocBufferBlobCompressedAbbrv,
  2029. SLocBufferBlobAbbrv);
  2030. }
  2031. } else {
  2032. // The source location entry is a macro expansion.
  2033. const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
  2034. AddSourceLocation(Expansion.getSpellingLoc(), Record);
  2035. AddSourceLocation(Expansion.getExpansionLocStart(), Record);
  2036. AddSourceLocation(Expansion.isMacroArgExpansion()
  2037. ? SourceLocation()
  2038. : Expansion.getExpansionLocEnd(),
  2039. Record);
  2040. Record.push_back(Expansion.isExpansionTokenRange());
  2041. // Compute the token length for this macro expansion.
  2042. unsigned NextOffset = SourceMgr.getNextLocalOffset();
  2043. if (I + 1 != N)
  2044. NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
  2045. Record.push_back(NextOffset - SLoc->getOffset() - 1);
  2046. Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
  2047. }
  2048. }
  2049. Stream.ExitBlock();
  2050. if (SLocEntryOffsets.empty())
  2051. return;
  2052. // Write the source-location offsets table into the AST block. This
  2053. // table is used for lazily loading source-location information.
  2054. using namespace llvm;
  2055. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2056. Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
  2057. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
  2058. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
  2059. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
  2060. unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2061. {
  2062. RecordData::value_type Record[] = {
  2063. SOURCE_LOCATION_OFFSETS, SLocEntryOffsets.size(),
  2064. SourceMgr.getNextLocalOffset() - 1 /* skip dummy */};
  2065. Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record,
  2066. bytes(SLocEntryOffsets));
  2067. }
  2068. // Write the source location entry preloads array, telling the AST
  2069. // reader which source locations entries it should load eagerly.
  2070. Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
  2071. // Write the line table. It depends on remapping working, so it must come
  2072. // after the source location offsets.
  2073. if (SourceMgr.hasLineTable()) {
  2074. LineTableInfo &LineTable = SourceMgr.getLineTable();
  2075. Record.clear();
  2076. // Emit the needed file names.
  2077. llvm::DenseMap<int, int> FilenameMap;
  2078. FilenameMap[-1] = -1; // For unspecified filenames.
  2079. for (const auto &L : LineTable) {
  2080. if (L.first.ID < 0)
  2081. continue;
  2082. for (auto &LE : L.second) {
  2083. if (FilenameMap.insert(std::make_pair(LE.FilenameID,
  2084. FilenameMap.size() - 1)).second)
  2085. AddPath(LineTable.getFilename(LE.FilenameID), Record);
  2086. }
  2087. }
  2088. Record.push_back(0);
  2089. // Emit the line entries
  2090. for (const auto &L : LineTable) {
  2091. // Only emit entries for local files.
  2092. if (L.first.ID < 0)
  2093. continue;
  2094. // Emit the file ID
  2095. Record.push_back(L.first.ID);
  2096. // Emit the line entries
  2097. Record.push_back(L.second.size());
  2098. for (const auto &LE : L.second) {
  2099. Record.push_back(LE.FileOffset);
  2100. Record.push_back(LE.LineNo);
  2101. Record.push_back(FilenameMap[LE.FilenameID]);
  2102. Record.push_back((unsigned)LE.FileKind);
  2103. Record.push_back(LE.IncludeOffset);
  2104. }
  2105. }
  2106. Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
  2107. }
  2108. }
  2109. //===----------------------------------------------------------------------===//
  2110. // Preprocessor Serialization
  2111. //===----------------------------------------------------------------------===//
  2112. static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
  2113. const Preprocessor &PP) {
  2114. if (MacroInfo *MI = MD->getMacroInfo())
  2115. if (MI->isBuiltinMacro())
  2116. return true;
  2117. if (IsModule) {
  2118. SourceLocation Loc = MD->getLocation();
  2119. if (Loc.isInvalid())
  2120. return true;
  2121. if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
  2122. return true;
  2123. }
  2124. return false;
  2125. }
  2126. /// Writes the block containing the serialized form of the
  2127. /// preprocessor.
  2128. void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
  2129. PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
  2130. if (PPRec)
  2131. WritePreprocessorDetail(*PPRec);
  2132. RecordData Record;
  2133. RecordData ModuleMacroRecord;
  2134. // If the preprocessor __COUNTER__ value has been bumped, remember it.
  2135. if (PP.getCounterValue() != 0) {
  2136. RecordData::value_type Record[] = {PP.getCounterValue()};
  2137. Stream.EmitRecord(PP_COUNTER_VALUE, Record);
  2138. }
  2139. if (PP.isRecordingPreamble() && PP.hasRecordedPreamble()) {
  2140. assert(!IsModule);
  2141. auto SkipInfo = PP.getPreambleSkipInfo();
  2142. if (SkipInfo.hasValue()) {
  2143. Record.push_back(true);
  2144. AddSourceLocation(SkipInfo->HashTokenLoc, Record);
  2145. AddSourceLocation(SkipInfo->IfTokenLoc, Record);
  2146. Record.push_back(SkipInfo->FoundNonSkipPortion);
  2147. Record.push_back(SkipInfo->FoundElse);
  2148. AddSourceLocation(SkipInfo->ElseLoc, Record);
  2149. } else {
  2150. Record.push_back(false);
  2151. }
  2152. for (const auto &Cond : PP.getPreambleConditionalStack()) {
  2153. AddSourceLocation(Cond.IfLoc, Record);
  2154. Record.push_back(Cond.WasSkipping);
  2155. Record.push_back(Cond.FoundNonSkip);
  2156. Record.push_back(Cond.FoundElse);
  2157. }
  2158. Stream.EmitRecord(PP_CONDITIONAL_STACK, Record);
  2159. Record.clear();
  2160. }
  2161. // Enter the preprocessor block.
  2162. Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
  2163. // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
  2164. // FIXME: Include a location for the use, and say which one was used.
  2165. if (PP.SawDateOrTime())
  2166. PP.Diag(SourceLocation(), diag::warn_module_uses_date_time) << IsModule;
  2167. // Loop over all the macro directives that are live at the end of the file,
  2168. // emitting each to the PP section.
  2169. // Construct the list of identifiers with macro directives that need to be
  2170. // serialized.
  2171. SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
  2172. for (auto &Id : PP.getIdentifierTable())
  2173. if (Id.second->hadMacroDefinition() &&
  2174. (!Id.second->isFromAST() ||
  2175. Id.second->hasChangedSinceDeserialization()))
  2176. MacroIdentifiers.push_back(Id.second);
  2177. // Sort the set of macro definitions that need to be serialized by the
  2178. // name of the macro, to provide a stable ordering.
  2179. llvm::sort(MacroIdentifiers, llvm::deref<std::less<>>());
  2180. // Emit the macro directives as a list and associate the offset with the
  2181. // identifier they belong to.
  2182. for (const IdentifierInfo *Name : MacroIdentifiers) {
  2183. MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
  2184. auto StartOffset = Stream.GetCurrentBitNo();
  2185. // Emit the macro directives in reverse source order.
  2186. for (; MD; MD = MD->getPrevious()) {
  2187. // Once we hit an ignored macro, we're done: the rest of the chain
  2188. // will all be ignored macros.
  2189. if (shouldIgnoreMacro(MD, IsModule, PP))
  2190. break;
  2191. AddSourceLocation(MD->getLocation(), Record);
  2192. Record.push_back(MD->getKind());
  2193. if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
  2194. Record.push_back(getMacroRef(DefMD->getInfo(), Name));
  2195. } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
  2196. Record.push_back(VisMD->isPublic());
  2197. }
  2198. }
  2199. // Write out any exported module macros.
  2200. bool EmittedModuleMacros = false;
  2201. // We write out exported module macros for PCH as well.
  2202. auto Leafs = PP.getLeafModuleMacros(Name);
  2203. SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
  2204. llvm::DenseMap<ModuleMacro*, unsigned> Visits;
  2205. while (!Worklist.empty()) {
  2206. auto *Macro = Worklist.pop_back_val();
  2207. // Emit a record indicating this submodule exports this macro.
  2208. ModuleMacroRecord.push_back(
  2209. getSubmoduleID(Macro->getOwningModule()));
  2210. ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
  2211. for (auto *M : Macro->overrides())
  2212. ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
  2213. Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
  2214. ModuleMacroRecord.clear();
  2215. // Enqueue overridden macros once we've visited all their ancestors.
  2216. for (auto *M : Macro->overrides())
  2217. if (++Visits[M] == M->getNumOverridingMacros())
  2218. Worklist.push_back(M);
  2219. EmittedModuleMacros = true;
  2220. }
  2221. if (Record.empty() && !EmittedModuleMacros)
  2222. continue;
  2223. IdentMacroDirectivesOffsetMap[Name] = StartOffset;
  2224. Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
  2225. Record.clear();
  2226. }
  2227. /// Offsets of each of the macros into the bitstream, indexed by
  2228. /// the local macro ID
  2229. ///
  2230. /// For each identifier that is associated with a macro, this map
  2231. /// provides the offset into the bitstream where that macro is
  2232. /// defined.
  2233. std::vector<uint32_t> MacroOffsets;
  2234. for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
  2235. const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
  2236. MacroInfo *MI = MacroInfosToEmit[I].MI;
  2237. MacroID ID = MacroInfosToEmit[I].ID;
  2238. if (ID < FirstMacroID) {
  2239. assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
  2240. continue;
  2241. }
  2242. // Record the local offset of this macro.
  2243. unsigned Index = ID - FirstMacroID;
  2244. if (Index == MacroOffsets.size())
  2245. MacroOffsets.push_back(Stream.GetCurrentBitNo());
  2246. else {
  2247. if (Index > MacroOffsets.size())
  2248. MacroOffsets.resize(Index + 1);
  2249. MacroOffsets[Index] = Stream.GetCurrentBitNo();
  2250. }
  2251. AddIdentifierRef(Name, Record);
  2252. AddSourceLocation(MI->getDefinitionLoc(), Record);
  2253. AddSourceLocation(MI->getDefinitionEndLoc(), Record);
  2254. Record.push_back(MI->isUsed());
  2255. Record.push_back(MI->isUsedForHeaderGuard());
  2256. unsigned Code;
  2257. if (MI->isObjectLike()) {
  2258. Code = PP_MACRO_OBJECT_LIKE;
  2259. } else {
  2260. Code = PP_MACRO_FUNCTION_LIKE;
  2261. Record.push_back(MI->isC99Varargs());
  2262. Record.push_back(MI->isGNUVarargs());
  2263. Record.push_back(MI->hasCommaPasting());
  2264. Record.push_back(MI->getNumParams());
  2265. for (const IdentifierInfo *Param : MI->params())
  2266. AddIdentifierRef(Param, Record);
  2267. }
  2268. // If we have a detailed preprocessing record, record the macro definition
  2269. // ID that corresponds to this macro.
  2270. if (PPRec)
  2271. Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
  2272. Stream.EmitRecord(Code, Record);
  2273. Record.clear();
  2274. // Emit the tokens array.
  2275. for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
  2276. // Note that we know that the preprocessor does not have any annotation
  2277. // tokens in it because they are created by the parser, and thus can't
  2278. // be in a macro definition.
  2279. const Token &Tok = MI->getReplacementToken(TokNo);
  2280. AddToken(Tok, Record);
  2281. Stream.EmitRecord(PP_TOKEN, Record);
  2282. Record.clear();
  2283. }
  2284. ++NumMacros;
  2285. }
  2286. Stream.ExitBlock();
  2287. // Write the offsets table for macro IDs.
  2288. using namespace llvm;
  2289. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2290. Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
  2291. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
  2292. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  2293. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2294. unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2295. {
  2296. RecordData::value_type Record[] = {MACRO_OFFSET, MacroOffsets.size(),
  2297. FirstMacroID - NUM_PREDEF_MACRO_IDS};
  2298. Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record, bytes(MacroOffsets));
  2299. }
  2300. }
  2301. void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
  2302. if (PPRec.local_begin() == PPRec.local_end())
  2303. return;
  2304. SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
  2305. // Enter the preprocessor block.
  2306. Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
  2307. // If the preprocessor has a preprocessing record, emit it.
  2308. unsigned NumPreprocessingRecords = 0;
  2309. using namespace llvm;
  2310. // Set up the abbreviation for
  2311. unsigned InclusionAbbrev = 0;
  2312. {
  2313. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2314. Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
  2315. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
  2316. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
  2317. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
  2318. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
  2319. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2320. InclusionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2321. }
  2322. unsigned FirstPreprocessorEntityID
  2323. = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
  2324. + NUM_PREDEF_PP_ENTITY_IDS;
  2325. unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
  2326. RecordData Record;
  2327. for (PreprocessingRecord::iterator E = PPRec.local_begin(),
  2328. EEnd = PPRec.local_end();
  2329. E != EEnd;
  2330. (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
  2331. Record.clear();
  2332. PreprocessedEntityOffsets.push_back(
  2333. PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
  2334. if (auto *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
  2335. // Record this macro definition's ID.
  2336. MacroDefinitions[MD] = NextPreprocessorEntityID;
  2337. AddIdentifierRef(MD->getName(), Record);
  2338. Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
  2339. continue;
  2340. }
  2341. if (auto *ME = dyn_cast<MacroExpansion>(*E)) {
  2342. Record.push_back(ME->isBuiltinMacro());
  2343. if (ME->isBuiltinMacro())
  2344. AddIdentifierRef(ME->getName(), Record);
  2345. else
  2346. Record.push_back(MacroDefinitions[ME->getDefinition()]);
  2347. Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
  2348. continue;
  2349. }
  2350. if (auto *ID = dyn_cast<InclusionDirective>(*E)) {
  2351. Record.push_back(PPD_INCLUSION_DIRECTIVE);
  2352. Record.push_back(ID->getFileName().size());
  2353. Record.push_back(ID->wasInQuotes());
  2354. Record.push_back(static_cast<unsigned>(ID->getKind()));
  2355. Record.push_back(ID->importedModule());
  2356. SmallString<64> Buffer;
  2357. Buffer += ID->getFileName();
  2358. // Check that the FileEntry is not null because it was not resolved and
  2359. // we create a PCH even with compiler errors.
  2360. if (ID->getFile())
  2361. Buffer += ID->getFile()->getName();
  2362. Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
  2363. continue;
  2364. }
  2365. llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
  2366. }
  2367. Stream.ExitBlock();
  2368. // Write the offsets table for the preprocessing record.
  2369. if (NumPreprocessingRecords > 0) {
  2370. assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
  2371. // Write the offsets table for identifier IDs.
  2372. using namespace llvm;
  2373. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2374. Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
  2375. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
  2376. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2377. unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2378. RecordData::value_type Record[] = {PPD_ENTITIES_OFFSETS,
  2379. FirstPreprocessorEntityID -
  2380. NUM_PREDEF_PP_ENTITY_IDS};
  2381. Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
  2382. bytes(PreprocessedEntityOffsets));
  2383. }
  2384. // Write the skipped region table for the preprocessing record.
  2385. ArrayRef<SourceRange> SkippedRanges = PPRec.getSkippedRanges();
  2386. if (SkippedRanges.size() > 0) {
  2387. std::vector<PPSkippedRange> SerializedSkippedRanges;
  2388. SerializedSkippedRanges.reserve(SkippedRanges.size());
  2389. for (auto const& Range : SkippedRanges)
  2390. SerializedSkippedRanges.emplace_back(Range);
  2391. using namespace llvm;
  2392. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2393. Abbrev->Add(BitCodeAbbrevOp(PPD_SKIPPED_RANGES));
  2394. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2395. unsigned PPESkippedRangeAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2396. Record.clear();
  2397. Record.push_back(PPD_SKIPPED_RANGES);
  2398. Stream.EmitRecordWithBlob(PPESkippedRangeAbbrev, Record,
  2399. bytes(SerializedSkippedRanges));
  2400. }
  2401. }
  2402. unsigned ASTWriter::getLocalOrImportedSubmoduleID(Module *Mod) {
  2403. if (!Mod)
  2404. return 0;
  2405. llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
  2406. if (Known != SubmoduleIDs.end())
  2407. return Known->second;
  2408. auto *Top = Mod->getTopLevelModule();
  2409. if (Top != WritingModule &&
  2410. (getLangOpts().CompilingPCH ||
  2411. !Top->fullModuleNameIs(StringRef(getLangOpts().CurrentModule))))
  2412. return 0;
  2413. return SubmoduleIDs[Mod] = NextSubmoduleID++;
  2414. }
  2415. unsigned ASTWriter::getSubmoduleID(Module *Mod) {
  2416. // FIXME: This can easily happen, if we have a reference to a submodule that
  2417. // did not result in us loading a module file for that submodule. For
  2418. // instance, a cross-top-level-module 'conflict' declaration will hit this.
  2419. unsigned ID = getLocalOrImportedSubmoduleID(Mod);
  2420. assert((ID || !Mod) &&
  2421. "asked for module ID for non-local, non-imported module");
  2422. return ID;
  2423. }
  2424. /// Compute the number of modules within the given tree (including the
  2425. /// given module).
  2426. static unsigned getNumberOfModules(Module *Mod) {
  2427. unsigned ChildModules = 0;
  2428. for (auto Sub = Mod->submodule_begin(), SubEnd = Mod->submodule_end();
  2429. Sub != SubEnd; ++Sub)
  2430. ChildModules += getNumberOfModules(*Sub);
  2431. return ChildModules + 1;
  2432. }
  2433. void ASTWriter::WriteSubmodules(Module *WritingModule) {
  2434. // Enter the submodule description block.
  2435. Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
  2436. // Write the abbreviations needed for the submodules block.
  2437. using namespace llvm;
  2438. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2439. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
  2440. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
  2441. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
  2442. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Kind
  2443. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
  2444. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
  2445. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
  2446. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
  2447. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
  2448. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
  2449. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
  2450. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
  2451. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ModuleMapIsPriv...
  2452. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2453. unsigned DefinitionAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2454. Abbrev = std::make_shared<BitCodeAbbrev>();
  2455. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
  2456. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2457. unsigned UmbrellaAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2458. Abbrev = std::make_shared<BitCodeAbbrev>();
  2459. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
  2460. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2461. unsigned HeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2462. Abbrev = std::make_shared<BitCodeAbbrev>();
  2463. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
  2464. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2465. unsigned TopHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2466. Abbrev = std::make_shared<BitCodeAbbrev>();
  2467. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
  2468. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2469. unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2470. Abbrev = std::make_shared<BitCodeAbbrev>();
  2471. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
  2472. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
  2473. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
  2474. unsigned RequiresAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2475. Abbrev = std::make_shared<BitCodeAbbrev>();
  2476. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
  2477. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2478. unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2479. Abbrev = std::make_shared<BitCodeAbbrev>();
  2480. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
  2481. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2482. unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2483. Abbrev = std::make_shared<BitCodeAbbrev>();
  2484. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
  2485. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2486. unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2487. Abbrev = std::make_shared<BitCodeAbbrev>();
  2488. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
  2489. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2490. unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2491. Abbrev = std::make_shared<BitCodeAbbrev>();
  2492. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
  2493. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
  2494. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2495. unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2496. Abbrev = std::make_shared<BitCodeAbbrev>();
  2497. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
  2498. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
  2499. unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2500. Abbrev = std::make_shared<BitCodeAbbrev>();
  2501. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
  2502. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
  2503. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
  2504. unsigned ConflictAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2505. Abbrev = std::make_shared<BitCodeAbbrev>();
  2506. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXPORT_AS));
  2507. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
  2508. unsigned ExportAsAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2509. // Write the submodule metadata block.
  2510. RecordData::value_type Record[] = {
  2511. getNumberOfModules(WritingModule),
  2512. FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS};
  2513. Stream.EmitRecord(SUBMODULE_METADATA, Record);
  2514. // Write all of the submodules.
  2515. std::queue<Module *> Q;
  2516. Q.push(WritingModule);
  2517. while (!Q.empty()) {
  2518. Module *Mod = Q.front();
  2519. Q.pop();
  2520. unsigned ID = getSubmoduleID(Mod);
  2521. uint64_t ParentID = 0;
  2522. if (Mod->Parent) {
  2523. assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
  2524. ParentID = SubmoduleIDs[Mod->Parent];
  2525. }
  2526. // Emit the definition of the block.
  2527. {
  2528. RecordData::value_type Record[] = {SUBMODULE_DEFINITION,
  2529. ID,
  2530. ParentID,
  2531. (RecordData::value_type)Mod->Kind,
  2532. Mod->IsFramework,
  2533. Mod->IsExplicit,
  2534. Mod->IsSystem,
  2535. Mod->IsExternC,
  2536. Mod->InferSubmodules,
  2537. Mod->InferExplicitSubmodules,
  2538. Mod->InferExportWildcard,
  2539. Mod->ConfigMacrosExhaustive,
  2540. Mod->ModuleMapIsPrivate};
  2541. Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
  2542. }
  2543. // Emit the requirements.
  2544. for (const auto &R : Mod->Requirements) {
  2545. RecordData::value_type Record[] = {SUBMODULE_REQUIRES, R.second};
  2546. Stream.EmitRecordWithBlob(RequiresAbbrev, Record, R.first);
  2547. }
  2548. // Emit the umbrella header, if there is one.
  2549. if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
  2550. RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_HEADER};
  2551. Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
  2552. UmbrellaHeader.NameAsWritten);
  2553. } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
  2554. RecordData::value_type Record[] = {SUBMODULE_UMBRELLA_DIR};
  2555. Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
  2556. UmbrellaDir.NameAsWritten);
  2557. }
  2558. // Emit the headers.
  2559. struct {
  2560. unsigned RecordKind;
  2561. unsigned Abbrev;
  2562. Module::HeaderKind HeaderKind;
  2563. } HeaderLists[] = {
  2564. {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
  2565. {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
  2566. {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
  2567. {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
  2568. Module::HK_PrivateTextual},
  2569. {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
  2570. };
  2571. for (auto &HL : HeaderLists) {
  2572. RecordData::value_type Record[] = {HL.RecordKind};
  2573. for (auto &H : Mod->Headers[HL.HeaderKind])
  2574. Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
  2575. }
  2576. // Emit the top headers.
  2577. {
  2578. auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
  2579. RecordData::value_type Record[] = {SUBMODULE_TOPHEADER};
  2580. for (auto *H : TopHeaders)
  2581. Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
  2582. }
  2583. // Emit the imports.
  2584. if (!Mod->Imports.empty()) {
  2585. RecordData Record;
  2586. for (auto *I : Mod->Imports)
  2587. Record.push_back(getSubmoduleID(I));
  2588. Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
  2589. }
  2590. // Emit the exports.
  2591. if (!Mod->Exports.empty()) {
  2592. RecordData Record;
  2593. for (const auto &E : Mod->Exports) {
  2594. // FIXME: This may fail; we don't require that all exported modules
  2595. // are local or imported.
  2596. Record.push_back(getSubmoduleID(E.getPointer()));
  2597. Record.push_back(E.getInt());
  2598. }
  2599. Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
  2600. }
  2601. //FIXME: How do we emit the 'use'd modules? They may not be submodules.
  2602. // Might be unnecessary as use declarations are only used to build the
  2603. // module itself.
  2604. // Emit the link libraries.
  2605. for (const auto &LL : Mod->LinkLibraries) {
  2606. RecordData::value_type Record[] = {SUBMODULE_LINK_LIBRARY,
  2607. LL.IsFramework};
  2608. Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record, LL.Library);
  2609. }
  2610. // Emit the conflicts.
  2611. for (const auto &C : Mod->Conflicts) {
  2612. // FIXME: This may fail; we don't require that all conflicting modules
  2613. // are local or imported.
  2614. RecordData::value_type Record[] = {SUBMODULE_CONFLICT,
  2615. getSubmoduleID(C.Other)};
  2616. Stream.EmitRecordWithBlob(ConflictAbbrev, Record, C.Message);
  2617. }
  2618. // Emit the configuration macros.
  2619. for (const auto &CM : Mod->ConfigMacros) {
  2620. RecordData::value_type Record[] = {SUBMODULE_CONFIG_MACRO};
  2621. Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record, CM);
  2622. }
  2623. // Emit the initializers, if any.
  2624. RecordData Inits;
  2625. for (Decl *D : Context->getModuleInitializers(Mod))
  2626. Inits.push_back(GetDeclRef(D));
  2627. if (!Inits.empty())
  2628. Stream.EmitRecord(SUBMODULE_INITIALIZERS, Inits);
  2629. // Emit the name of the re-exported module, if any.
  2630. if (!Mod->ExportAsModule.empty()) {
  2631. RecordData::value_type Record[] = {SUBMODULE_EXPORT_AS};
  2632. Stream.EmitRecordWithBlob(ExportAsAbbrev, Record, Mod->ExportAsModule);
  2633. }
  2634. // Queue up the submodules of this module.
  2635. for (auto *M : Mod->submodules())
  2636. Q.push(M);
  2637. }
  2638. Stream.ExitBlock();
  2639. assert((NextSubmoduleID - FirstSubmoduleID ==
  2640. getNumberOfModules(WritingModule)) &&
  2641. "Wrong # of submodules; found a reference to a non-local, "
  2642. "non-imported submodule?");
  2643. }
  2644. void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
  2645. bool isModule) {
  2646. llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
  2647. DiagStateIDMap;
  2648. unsigned CurrID = 0;
  2649. RecordData Record;
  2650. auto EncodeDiagStateFlags =
  2651. [](const DiagnosticsEngine::DiagState *DS) -> unsigned {
  2652. unsigned Result = (unsigned)DS->ExtBehavior;
  2653. for (unsigned Val :
  2654. {(unsigned)DS->IgnoreAllWarnings, (unsigned)DS->EnableAllWarnings,
  2655. (unsigned)DS->WarningsAsErrors, (unsigned)DS->ErrorsAsFatal,
  2656. (unsigned)DS->SuppressSystemWarnings})
  2657. Result = (Result << 1) | Val;
  2658. return Result;
  2659. };
  2660. unsigned Flags = EncodeDiagStateFlags(Diag.DiagStatesByLoc.FirstDiagState);
  2661. Record.push_back(Flags);
  2662. auto AddDiagState = [&](const DiagnosticsEngine::DiagState *State,
  2663. bool IncludeNonPragmaStates) {
  2664. // Ensure that the diagnostic state wasn't modified since it was created.
  2665. // We will not correctly round-trip this information otherwise.
  2666. assert(Flags == EncodeDiagStateFlags(State) &&
  2667. "diag state flags vary in single AST file");
  2668. unsigned &DiagStateID = DiagStateIDMap[State];
  2669. Record.push_back(DiagStateID);
  2670. if (DiagStateID == 0) {
  2671. DiagStateID = ++CurrID;
  2672. // Add a placeholder for the number of mappings.
  2673. auto SizeIdx = Record.size();
  2674. Record.emplace_back();
  2675. for (const auto &I : *State) {
  2676. if (I.second.isPragma() || IncludeNonPragmaStates) {
  2677. Record.push_back(I.first);
  2678. Record.push_back(I.second.serialize());
  2679. }
  2680. }
  2681. // Update the placeholder.
  2682. Record[SizeIdx] = (Record.size() - SizeIdx) / 2;
  2683. }
  2684. };
  2685. AddDiagState(Diag.DiagStatesByLoc.FirstDiagState, isModule);
  2686. // Reserve a spot for the number of locations with state transitions.
  2687. auto NumLocationsIdx = Record.size();
  2688. Record.emplace_back();
  2689. // Emit the state transitions.
  2690. unsigned NumLocations = 0;
  2691. for (auto &FileIDAndFile : Diag.DiagStatesByLoc.Files) {
  2692. if (!FileIDAndFile.first.isValid() ||
  2693. !FileIDAndFile.second.HasLocalTransitions)
  2694. continue;
  2695. ++NumLocations;
  2696. SourceLocation Loc = Diag.SourceMgr->getComposedLoc(FileIDAndFile.first, 0);
  2697. assert(!Loc.isInvalid() && "start loc for valid FileID is invalid");
  2698. AddSourceLocation(Loc, Record);
  2699. Record.push_back(FileIDAndFile.second.StateTransitions.size());
  2700. for (auto &StatePoint : FileIDAndFile.second.StateTransitions) {
  2701. Record.push_back(StatePoint.Offset);
  2702. AddDiagState(StatePoint.State, false);
  2703. }
  2704. }
  2705. // Backpatch the number of locations.
  2706. Record[NumLocationsIdx] = NumLocations;
  2707. // Emit CurDiagStateLoc. Do it last in order to match source order.
  2708. //
  2709. // This also protects against a hypothetical corner case with simulating
  2710. // -Werror settings for implicit modules in the ASTReader, where reading
  2711. // CurDiagState out of context could change whether warning pragmas are
  2712. // treated as errors.
  2713. AddSourceLocation(Diag.DiagStatesByLoc.CurDiagStateLoc, Record);
  2714. AddDiagState(Diag.DiagStatesByLoc.CurDiagState, false);
  2715. Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
  2716. }
  2717. //===----------------------------------------------------------------------===//
  2718. // Type Serialization
  2719. //===----------------------------------------------------------------------===//
  2720. /// Write the representation of a type to the AST stream.
  2721. void ASTWriter::WriteType(QualType T) {
  2722. TypeIdx &IdxRef = TypeIdxs[T];
  2723. if (IdxRef.getIndex() == 0) // we haven't seen this type before.
  2724. IdxRef = TypeIdx(NextTypeID++);
  2725. TypeIdx Idx = IdxRef;
  2726. assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
  2727. RecordData Record;
  2728. // Emit the type's representation.
  2729. ASTTypeWriter W(*this, Record);
  2730. W.Visit(T);
  2731. uint64_t Offset = W.Emit();
  2732. // Record the offset for this type.
  2733. unsigned Index = Idx.getIndex() - FirstTypeID;
  2734. if (TypeOffsets.size() == Index)
  2735. TypeOffsets.push_back(Offset);
  2736. else if (TypeOffsets.size() < Index) {
  2737. TypeOffsets.resize(Index + 1);
  2738. TypeOffsets[Index] = Offset;
  2739. } else {
  2740. llvm_unreachable("Types emitted in wrong order");
  2741. }
  2742. }
  2743. //===----------------------------------------------------------------------===//
  2744. // Declaration Serialization
  2745. //===----------------------------------------------------------------------===//
  2746. /// Write the block containing all of the declaration IDs
  2747. /// lexically declared within the given DeclContext.
  2748. ///
  2749. /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
  2750. /// bitstream, or 0 if no block was written.
  2751. uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
  2752. DeclContext *DC) {
  2753. if (DC->decls_empty())
  2754. return 0;
  2755. uint64_t Offset = Stream.GetCurrentBitNo();
  2756. SmallVector<uint32_t, 128> KindDeclPairs;
  2757. for (const auto *D : DC->decls()) {
  2758. KindDeclPairs.push_back(D->getKind());
  2759. KindDeclPairs.push_back(GetDeclRef(D));
  2760. }
  2761. ++NumLexicalDeclContexts;
  2762. RecordData::value_type Record[] = {DECL_CONTEXT_LEXICAL};
  2763. Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record,
  2764. bytes(KindDeclPairs));
  2765. return Offset;
  2766. }
  2767. void ASTWriter::WriteTypeDeclOffsets() {
  2768. using namespace llvm;
  2769. // Write the type offsets array
  2770. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2771. Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
  2772. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
  2773. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
  2774. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
  2775. unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2776. {
  2777. RecordData::value_type Record[] = {TYPE_OFFSET, TypeOffsets.size(),
  2778. FirstTypeID - NUM_PREDEF_TYPE_IDS};
  2779. Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
  2780. }
  2781. // Write the declaration offsets array
  2782. Abbrev = std::make_shared<BitCodeAbbrev>();
  2783. Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
  2784. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
  2785. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
  2786. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
  2787. unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  2788. {
  2789. RecordData::value_type Record[] = {DECL_OFFSET, DeclOffsets.size(),
  2790. FirstDeclID - NUM_PREDEF_DECL_IDS};
  2791. Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
  2792. }
  2793. }
  2794. void ASTWriter::WriteFileDeclIDsMap() {
  2795. using namespace llvm;
  2796. SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
  2797. FileDeclIDs.begin(), FileDeclIDs.end());
  2798. llvm::sort(SortedFileDeclIDs, llvm::less_first());
  2799. // Join the vectors of DeclIDs from all files.
  2800. SmallVector<DeclID, 256> FileGroupedDeclIDs;
  2801. for (auto &FileDeclEntry : SortedFileDeclIDs) {
  2802. DeclIDInFileInfo &Info = *FileDeclEntry.second;
  2803. Info.FirstDeclIndex = FileGroupedDeclIDs.size();
  2804. for (auto &LocDeclEntry : Info.DeclIDs)
  2805. FileGroupedDeclIDs.push_back(LocDeclEntry.second);
  2806. }
  2807. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2808. Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
  2809. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2810. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2811. unsigned AbbrevCode = Stream.EmitAbbrev(std::move(Abbrev));
  2812. RecordData::value_type Record[] = {FILE_SORTED_DECLS,
  2813. FileGroupedDeclIDs.size()};
  2814. Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
  2815. }
  2816. void ASTWriter::WriteComments() {
  2817. Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
  2818. auto _ = llvm::make_scope_exit([this] { Stream.ExitBlock(); });
  2819. if (!PP->getPreprocessorOpts().WriteCommentListToPCH)
  2820. return;
  2821. RecordData Record;
  2822. for (const auto &FO : Context->Comments.OrderedComments) {
  2823. for (const auto &OC : FO.second) {
  2824. const RawComment *I = OC.second;
  2825. Record.clear();
  2826. AddSourceRange(I->getSourceRange(), Record);
  2827. Record.push_back(I->getKind());
  2828. Record.push_back(I->isTrailingComment());
  2829. Record.push_back(I->isAlmostTrailingComment());
  2830. Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
  2831. }
  2832. }
  2833. }
  2834. //===----------------------------------------------------------------------===//
  2835. // Global Method Pool and Selector Serialization
  2836. //===----------------------------------------------------------------------===//
  2837. namespace {
  2838. // Trait used for the on-disk hash table used in the method pool.
  2839. class ASTMethodPoolTrait {
  2840. ASTWriter &Writer;
  2841. public:
  2842. using key_type = Selector;
  2843. using key_type_ref = key_type;
  2844. struct data_type {
  2845. SelectorID ID;
  2846. ObjCMethodList Instance, Factory;
  2847. };
  2848. using data_type_ref = const data_type &;
  2849. using hash_value_type = unsigned;
  2850. using offset_type = unsigned;
  2851. explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) {}
  2852. static hash_value_type ComputeHash(Selector Sel) {
  2853. return serialization::ComputeHash(Sel);
  2854. }
  2855. std::pair<unsigned, unsigned>
  2856. EmitKeyDataLength(raw_ostream& Out, Selector Sel,
  2857. data_type_ref Methods) {
  2858. using namespace llvm::support;
  2859. endian::Writer LE(Out, little);
  2860. unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
  2861. LE.write<uint16_t>(KeyLen);
  2862. unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
  2863. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2864. Method = Method->getNext())
  2865. if (Method->getMethod())
  2866. DataLen += 4;
  2867. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2868. Method = Method->getNext())
  2869. if (Method->getMethod())
  2870. DataLen += 4;
  2871. LE.write<uint16_t>(DataLen);
  2872. return std::make_pair(KeyLen, DataLen);
  2873. }
  2874. void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
  2875. using namespace llvm::support;
  2876. endian::Writer LE(Out, little);
  2877. uint64_t Start = Out.tell();
  2878. assert((Start >> 32) == 0 && "Selector key offset too large");
  2879. Writer.SetSelectorOffset(Sel, Start);
  2880. unsigned N = Sel.getNumArgs();
  2881. LE.write<uint16_t>(N);
  2882. if (N == 0)
  2883. N = 1;
  2884. for (unsigned I = 0; I != N; ++I)
  2885. LE.write<uint32_t>(
  2886. Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
  2887. }
  2888. void EmitData(raw_ostream& Out, key_type_ref,
  2889. data_type_ref Methods, unsigned DataLen) {
  2890. using namespace llvm::support;
  2891. endian::Writer LE(Out, little);
  2892. uint64_t Start = Out.tell(); (void)Start;
  2893. LE.write<uint32_t>(Methods.ID);
  2894. unsigned NumInstanceMethods = 0;
  2895. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2896. Method = Method->getNext())
  2897. if (Method->getMethod())
  2898. ++NumInstanceMethods;
  2899. unsigned NumFactoryMethods = 0;
  2900. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2901. Method = Method->getNext())
  2902. if (Method->getMethod())
  2903. ++NumFactoryMethods;
  2904. unsigned InstanceBits = Methods.Instance.getBits();
  2905. assert(InstanceBits < 4);
  2906. unsigned InstanceHasMoreThanOneDeclBit =
  2907. Methods.Instance.hasMoreThanOneDecl();
  2908. unsigned FullInstanceBits = (NumInstanceMethods << 3) |
  2909. (InstanceHasMoreThanOneDeclBit << 2) |
  2910. InstanceBits;
  2911. unsigned FactoryBits = Methods.Factory.getBits();
  2912. assert(FactoryBits < 4);
  2913. unsigned FactoryHasMoreThanOneDeclBit =
  2914. Methods.Factory.hasMoreThanOneDecl();
  2915. unsigned FullFactoryBits = (NumFactoryMethods << 3) |
  2916. (FactoryHasMoreThanOneDeclBit << 2) |
  2917. FactoryBits;
  2918. LE.write<uint16_t>(FullInstanceBits);
  2919. LE.write<uint16_t>(FullFactoryBits);
  2920. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2921. Method = Method->getNext())
  2922. if (Method->getMethod())
  2923. LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
  2924. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2925. Method = Method->getNext())
  2926. if (Method->getMethod())
  2927. LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
  2928. assert(Out.tell() - Start == DataLen && "Data length is wrong");
  2929. }
  2930. };
  2931. } // namespace
  2932. /// Write ObjC data: selectors and the method pool.
  2933. ///
  2934. /// The method pool contains both instance and factory methods, stored
  2935. /// in an on-disk hash table indexed by the selector. The hash table also
  2936. /// contains an empty entry for every other selector known to Sema.
  2937. void ASTWriter::WriteSelectors(Sema &SemaRef) {
  2938. using namespace llvm;
  2939. // Do we have to do anything at all?
  2940. if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
  2941. return;
  2942. unsigned NumTableEntries = 0;
  2943. // Create and write out the blob that contains selectors and the method pool.
  2944. {
  2945. llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
  2946. ASTMethodPoolTrait Trait(*this);
  2947. // Create the on-disk hash table representation. We walk through every
  2948. // selector we've seen and look it up in the method pool.
  2949. SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
  2950. for (auto &SelectorAndID : SelectorIDs) {
  2951. Selector S = SelectorAndID.first;
  2952. SelectorID ID = SelectorAndID.second;
  2953. Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
  2954. ASTMethodPoolTrait::data_type Data = {
  2955. ID,
  2956. ObjCMethodList(),
  2957. ObjCMethodList()
  2958. };
  2959. if (F != SemaRef.MethodPool.end()) {
  2960. Data.Instance = F->second.first;
  2961. Data.Factory = F->second.second;
  2962. }
  2963. // Only write this selector if it's not in an existing AST or something
  2964. // changed.
  2965. if (Chain && ID < FirstSelectorID) {
  2966. // Selector already exists. Did it change?
  2967. bool changed = false;
  2968. for (ObjCMethodList *M = &Data.Instance;
  2969. !changed && M && M->getMethod(); M = M->getNext()) {
  2970. if (!M->getMethod()->isFromASTFile())
  2971. changed = true;
  2972. }
  2973. for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
  2974. M = M->getNext()) {
  2975. if (!M->getMethod()->isFromASTFile())
  2976. changed = true;
  2977. }
  2978. if (!changed)
  2979. continue;
  2980. } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
  2981. // A new method pool entry.
  2982. ++NumTableEntries;
  2983. }
  2984. Generator.insert(S, Data, Trait);
  2985. }
  2986. // Create the on-disk hash table in a buffer.
  2987. SmallString<4096> MethodPool;
  2988. uint32_t BucketOffset;
  2989. {
  2990. using namespace llvm::support;
  2991. ASTMethodPoolTrait Trait(*this);
  2992. llvm::raw_svector_ostream Out(MethodPool);
  2993. // Make sure that no bucket is at offset 0
  2994. endian::write<uint32_t>(Out, 0, little);
  2995. BucketOffset = Generator.Emit(Out, Trait);
  2996. }
  2997. // Create a blob abbreviation
  2998. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  2999. Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
  3000. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3001. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3002. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3003. unsigned MethodPoolAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  3004. // Write the method pool
  3005. {
  3006. RecordData::value_type Record[] = {METHOD_POOL, BucketOffset,
  3007. NumTableEntries};
  3008. Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
  3009. }
  3010. // Create a blob abbreviation for the selector table offsets.
  3011. Abbrev = std::make_shared<BitCodeAbbrev>();
  3012. Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
  3013. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
  3014. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  3015. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3016. unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  3017. // Write the selector offsets table.
  3018. {
  3019. RecordData::value_type Record[] = {
  3020. SELECTOR_OFFSETS, SelectorOffsets.size(),
  3021. FirstSelectorID - NUM_PREDEF_SELECTOR_IDS};
  3022. Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
  3023. bytes(SelectorOffsets));
  3024. }
  3025. }
  3026. }
  3027. /// Write the selectors referenced in @selector expression into AST file.
  3028. void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
  3029. using namespace llvm;
  3030. if (SemaRef.ReferencedSelectors.empty())
  3031. return;
  3032. RecordData Record;
  3033. ASTRecordWriter Writer(*this, Record);
  3034. // Note: this writes out all references even for a dependent AST. But it is
  3035. // very tricky to fix, and given that @selector shouldn't really appear in
  3036. // headers, probably not worth it. It's not a correctness issue.
  3037. for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
  3038. Selector Sel = SelectorAndLocation.first;
  3039. SourceLocation Loc = SelectorAndLocation.second;
  3040. Writer.AddSelectorRef(Sel);
  3041. Writer.AddSourceLocation(Loc);
  3042. }
  3043. Writer.Emit(REFERENCED_SELECTOR_POOL);
  3044. }
  3045. //===----------------------------------------------------------------------===//
  3046. // Identifier Table Serialization
  3047. //===----------------------------------------------------------------------===//
  3048. /// Determine the declaration that should be put into the name lookup table to
  3049. /// represent the given declaration in this module. This is usually D itself,
  3050. /// but if D was imported and merged into a local declaration, we want the most
  3051. /// recent local declaration instead. The chosen declaration will be the most
  3052. /// recent declaration in any module that imports this one.
  3053. static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
  3054. NamedDecl *D) {
  3055. if (!LangOpts.Modules || !D->isFromASTFile())
  3056. return D;
  3057. if (Decl *Redecl = D->getPreviousDecl()) {
  3058. // For Redeclarable decls, a prior declaration might be local.
  3059. for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
  3060. // If we find a local decl, we're done.
  3061. if (!Redecl->isFromASTFile()) {
  3062. // Exception: in very rare cases (for injected-class-names), not all
  3063. // redeclarations are in the same semantic context. Skip ones in a
  3064. // different context. They don't go in this lookup table at all.
  3065. if (!Redecl->getDeclContext()->getRedeclContext()->Equals(
  3066. D->getDeclContext()->getRedeclContext()))
  3067. continue;
  3068. return cast<NamedDecl>(Redecl);
  3069. }
  3070. // If we find a decl from a (chained-)PCH stop since we won't find a
  3071. // local one.
  3072. if (Redecl->getOwningModuleID() == 0)
  3073. break;
  3074. }
  3075. } else if (Decl *First = D->getCanonicalDecl()) {
  3076. // For Mergeable decls, the first decl might be local.
  3077. if (!First->isFromASTFile())
  3078. return cast<NamedDecl>(First);
  3079. }
  3080. // All declarations are imported. Our most recent declaration will also be
  3081. // the most recent one in anyone who imports us.
  3082. return D;
  3083. }
  3084. namespace {
  3085. class ASTIdentifierTableTrait {
  3086. ASTWriter &Writer;
  3087. Preprocessor &PP;
  3088. IdentifierResolver &IdResolver;
  3089. bool IsModule;
  3090. bool NeedDecls;
  3091. ASTWriter::RecordData *InterestingIdentifierOffsets;
  3092. /// Determines whether this is an "interesting" identifier that needs a
  3093. /// full IdentifierInfo structure written into the hash table. Notably, this
  3094. /// doesn't check whether the name has macros defined; use PublicMacroIterator
  3095. /// to check that.
  3096. bool isInterestingIdentifier(const IdentifierInfo *II, uint64_t MacroOffset) {
  3097. if (MacroOffset ||
  3098. II->isPoisoned() ||
  3099. (IsModule ? II->hasRevertedBuiltin() : II->getObjCOrBuiltinID()) ||
  3100. II->hasRevertedTokenIDToIdentifier() ||
  3101. (NeedDecls && II->getFETokenInfo()))
  3102. return true;
  3103. return false;
  3104. }
  3105. public:
  3106. using key_type = IdentifierInfo *;
  3107. using key_type_ref = key_type;
  3108. using data_type = IdentID;
  3109. using data_type_ref = data_type;
  3110. using hash_value_type = unsigned;
  3111. using offset_type = unsigned;
  3112. ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
  3113. IdentifierResolver &IdResolver, bool IsModule,
  3114. ASTWriter::RecordData *InterestingIdentifierOffsets)
  3115. : Writer(Writer), PP(PP), IdResolver(IdResolver), IsModule(IsModule),
  3116. NeedDecls(!IsModule || !Writer.getLangOpts().CPlusPlus),
  3117. InterestingIdentifierOffsets(InterestingIdentifierOffsets) {}
  3118. bool needDecls() const { return NeedDecls; }
  3119. static hash_value_type ComputeHash(const IdentifierInfo* II) {
  3120. return llvm::djbHash(II->getName());
  3121. }
  3122. bool isInterestingIdentifier(const IdentifierInfo *II) {
  3123. auto MacroOffset = Writer.getMacroDirectivesOffset(II);
  3124. return isInterestingIdentifier(II, MacroOffset);
  3125. }
  3126. bool isInterestingNonMacroIdentifier(const IdentifierInfo *II) {
  3127. return isInterestingIdentifier(II, 0);
  3128. }
  3129. std::pair<unsigned, unsigned>
  3130. EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
  3131. unsigned KeyLen = II->getLength() + 1;
  3132. unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
  3133. auto MacroOffset = Writer.getMacroDirectivesOffset(II);
  3134. if (isInterestingIdentifier(II, MacroOffset)) {
  3135. DataLen += 2; // 2 bytes for builtin ID
  3136. DataLen += 2; // 2 bytes for flags
  3137. if (MacroOffset)
  3138. DataLen += 4; // MacroDirectives offset.
  3139. if (NeedDecls) {
  3140. for (IdentifierResolver::iterator D = IdResolver.begin(II),
  3141. DEnd = IdResolver.end();
  3142. D != DEnd; ++D)
  3143. DataLen += 4;
  3144. }
  3145. }
  3146. using namespace llvm::support;
  3147. endian::Writer LE(Out, little);
  3148. assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
  3149. LE.write<uint16_t>(DataLen);
  3150. // We emit the key length after the data length so that every
  3151. // string is preceded by a 16-bit length. This matches the PTH
  3152. // format for storing identifiers.
  3153. LE.write<uint16_t>(KeyLen);
  3154. return std::make_pair(KeyLen, DataLen);
  3155. }
  3156. void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
  3157. unsigned KeyLen) {
  3158. // Record the location of the key data. This is used when generating
  3159. // the mapping from persistent IDs to strings.
  3160. Writer.SetIdentifierOffset(II, Out.tell());
  3161. // Emit the offset of the key/data length information to the interesting
  3162. // identifiers table if necessary.
  3163. if (InterestingIdentifierOffsets && isInterestingIdentifier(II))
  3164. InterestingIdentifierOffsets->push_back(Out.tell() - 4);
  3165. Out.write(II->getNameStart(), KeyLen);
  3166. }
  3167. void EmitData(raw_ostream& Out, IdentifierInfo* II,
  3168. IdentID ID, unsigned) {
  3169. using namespace llvm::support;
  3170. endian::Writer LE(Out, little);
  3171. auto MacroOffset = Writer.getMacroDirectivesOffset(II);
  3172. if (!isInterestingIdentifier(II, MacroOffset)) {
  3173. LE.write<uint32_t>(ID << 1);
  3174. return;
  3175. }
  3176. LE.write<uint32_t>((ID << 1) | 0x01);
  3177. uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
  3178. assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
  3179. LE.write<uint16_t>(Bits);
  3180. Bits = 0;
  3181. bool HadMacroDefinition = MacroOffset != 0;
  3182. Bits = (Bits << 1) | unsigned(HadMacroDefinition);
  3183. Bits = (Bits << 1) | unsigned(II->isExtensionToken());
  3184. Bits = (Bits << 1) | unsigned(II->isPoisoned());
  3185. Bits = (Bits << 1) | unsigned(II->hasRevertedBuiltin());
  3186. Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
  3187. Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
  3188. LE.write<uint16_t>(Bits);
  3189. if (HadMacroDefinition)
  3190. LE.write<uint32_t>(MacroOffset);
  3191. if (NeedDecls) {
  3192. // Emit the declaration IDs in reverse order, because the
  3193. // IdentifierResolver provides the declarations as they would be
  3194. // visible (e.g., the function "stat" would come before the struct
  3195. // "stat"), but the ASTReader adds declarations to the end of the list
  3196. // (so we need to see the struct "stat" before the function "stat").
  3197. // Only emit declarations that aren't from a chained PCH, though.
  3198. SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II),
  3199. IdResolver.end());
  3200. for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
  3201. DEnd = Decls.rend();
  3202. D != DEnd; ++D)
  3203. LE.write<uint32_t>(
  3204. Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
  3205. }
  3206. }
  3207. };
  3208. } // namespace
  3209. /// Write the identifier table into the AST file.
  3210. ///
  3211. /// The identifier table consists of a blob containing string data
  3212. /// (the actual identifiers themselves) and a separate "offsets" index
  3213. /// that maps identifier IDs to locations within the blob.
  3214. void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
  3215. IdentifierResolver &IdResolver,
  3216. bool IsModule) {
  3217. using namespace llvm;
  3218. RecordData InterestingIdents;
  3219. // Create and write out the blob that contains the identifier
  3220. // strings.
  3221. {
  3222. llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
  3223. ASTIdentifierTableTrait Trait(
  3224. *this, PP, IdResolver, IsModule,
  3225. (getLangOpts().CPlusPlus && IsModule) ? &InterestingIdents : nullptr);
  3226. // Look for any identifiers that were named while processing the
  3227. // headers, but are otherwise not needed. We add these to the hash
  3228. // table to enable checking of the predefines buffer in the case
  3229. // where the user adds new macro definitions when building the AST
  3230. // file.
  3231. SmallVector<const IdentifierInfo *, 128> IIs;
  3232. for (const auto &ID : PP.getIdentifierTable())
  3233. IIs.push_back(ID.second);
  3234. // Sort the identifiers lexicographically before getting them references so
  3235. // that their order is stable.
  3236. llvm::sort(IIs, llvm::deref<std::less<>>());
  3237. for (const IdentifierInfo *II : IIs)
  3238. if (Trait.isInterestingNonMacroIdentifier(II))
  3239. getIdentifierRef(II);
  3240. // Create the on-disk hash table representation. We only store offsets
  3241. // for identifiers that appear here for the first time.
  3242. IdentifierOffsets.resize(NextIdentID - FirstIdentID);
  3243. for (auto IdentIDPair : IdentifierIDs) {
  3244. auto *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
  3245. IdentID ID = IdentIDPair.second;
  3246. assert(II && "NULL identifier in identifier table");
  3247. // Write out identifiers if either the ID is local or the identifier has
  3248. // changed since it was loaded.
  3249. if (ID >= FirstIdentID || !Chain || !II->isFromAST()
  3250. || II->hasChangedSinceDeserialization() ||
  3251. (Trait.needDecls() &&
  3252. II->hasFETokenInfoChangedSinceDeserialization()))
  3253. Generator.insert(II, ID, Trait);
  3254. }
  3255. // Create the on-disk hash table in a buffer.
  3256. SmallString<4096> IdentifierTable;
  3257. uint32_t BucketOffset;
  3258. {
  3259. using namespace llvm::support;
  3260. llvm::raw_svector_ostream Out(IdentifierTable);
  3261. // Make sure that no bucket is at offset 0
  3262. endian::write<uint32_t>(Out, 0, little);
  3263. BucketOffset = Generator.Emit(Out, Trait);
  3264. }
  3265. // Create a blob abbreviation
  3266. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  3267. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
  3268. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  3269. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3270. unsigned IDTableAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  3271. // Write the identifier table
  3272. RecordData::value_type Record[] = {IDENTIFIER_TABLE, BucketOffset};
  3273. Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
  3274. }
  3275. // Write the offsets table for identifier IDs.
  3276. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  3277. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
  3278. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
  3279. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  3280. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3281. unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  3282. #ifndef NDEBUG
  3283. for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
  3284. assert(IdentifierOffsets[I] && "Missing identifier offset?");
  3285. #endif
  3286. RecordData::value_type Record[] = {IDENTIFIER_OFFSET,
  3287. IdentifierOffsets.size(),
  3288. FirstIdentID - NUM_PREDEF_IDENT_IDS};
  3289. Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
  3290. bytes(IdentifierOffsets));
  3291. // In C++, write the list of interesting identifiers (those that are
  3292. // defined as macros, poisoned, or similar unusual things).
  3293. if (!InterestingIdents.empty())
  3294. Stream.EmitRecord(INTERESTING_IDENTIFIERS, InterestingIdents);
  3295. }
  3296. //===----------------------------------------------------------------------===//
  3297. // DeclContext's Name Lookup Table Serialization
  3298. //===----------------------------------------------------------------------===//
  3299. namespace {
  3300. // Trait used for the on-disk hash table used in the method pool.
  3301. class ASTDeclContextNameLookupTrait {
  3302. ASTWriter &Writer;
  3303. llvm::SmallVector<DeclID, 64> DeclIDs;
  3304. public:
  3305. using key_type = DeclarationNameKey;
  3306. using key_type_ref = key_type;
  3307. /// A start and end index into DeclIDs, representing a sequence of decls.
  3308. using data_type = std::pair<unsigned, unsigned>;
  3309. using data_type_ref = const data_type &;
  3310. using hash_value_type = unsigned;
  3311. using offset_type = unsigned;
  3312. explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) {}
  3313. template<typename Coll>
  3314. data_type getData(const Coll &Decls) {
  3315. unsigned Start = DeclIDs.size();
  3316. for (NamedDecl *D : Decls) {
  3317. DeclIDs.push_back(
  3318. Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), D)));
  3319. }
  3320. return std::make_pair(Start, DeclIDs.size());
  3321. }
  3322. data_type ImportData(const reader::ASTDeclContextNameLookupTrait::data_type &FromReader) {
  3323. unsigned Start = DeclIDs.size();
  3324. for (auto ID : FromReader)
  3325. DeclIDs.push_back(ID);
  3326. return std::make_pair(Start, DeclIDs.size());
  3327. }
  3328. static bool EqualKey(key_type_ref a, key_type_ref b) {
  3329. return a == b;
  3330. }
  3331. hash_value_type ComputeHash(DeclarationNameKey Name) {
  3332. return Name.getHash();
  3333. }
  3334. void EmitFileRef(raw_ostream &Out, ModuleFile *F) const {
  3335. assert(Writer.hasChain() &&
  3336. "have reference to loaded module file but no chain?");
  3337. using namespace llvm::support;
  3338. endian::write<uint32_t>(Out, Writer.getChain()->getModuleFileID(F), little);
  3339. }
  3340. std::pair<unsigned, unsigned> EmitKeyDataLength(raw_ostream &Out,
  3341. DeclarationNameKey Name,
  3342. data_type_ref Lookup) {
  3343. using namespace llvm::support;
  3344. endian::Writer LE(Out, little);
  3345. unsigned KeyLen = 1;
  3346. switch (Name.getKind()) {
  3347. case DeclarationName::Identifier:
  3348. case DeclarationName::ObjCZeroArgSelector:
  3349. case DeclarationName::ObjCOneArgSelector:
  3350. case DeclarationName::ObjCMultiArgSelector:
  3351. case DeclarationName::CXXLiteralOperatorName:
  3352. case DeclarationName::CXXDeductionGuideName:
  3353. KeyLen += 4;
  3354. break;
  3355. case DeclarationName::CXXOperatorName:
  3356. KeyLen += 1;
  3357. break;
  3358. case DeclarationName::CXXConstructorName:
  3359. case DeclarationName::CXXDestructorName:
  3360. case DeclarationName::CXXConversionFunctionName:
  3361. case DeclarationName::CXXUsingDirective:
  3362. break;
  3363. }
  3364. LE.write<uint16_t>(KeyLen);
  3365. // 4 bytes for each DeclID.
  3366. unsigned DataLen = 4 * (Lookup.second - Lookup.first);
  3367. assert(uint16_t(DataLen) == DataLen &&
  3368. "too many decls for serialized lookup result");
  3369. LE.write<uint16_t>(DataLen);
  3370. return std::make_pair(KeyLen, DataLen);
  3371. }
  3372. void EmitKey(raw_ostream &Out, DeclarationNameKey Name, unsigned) {
  3373. using namespace llvm::support;
  3374. endian::Writer LE(Out, little);
  3375. LE.write<uint8_t>(Name.getKind());
  3376. switch (Name.getKind()) {
  3377. case DeclarationName::Identifier:
  3378. case DeclarationName::CXXLiteralOperatorName:
  3379. case DeclarationName::CXXDeductionGuideName:
  3380. LE.write<uint32_t>(Writer.getIdentifierRef(Name.getIdentifier()));
  3381. return;
  3382. case DeclarationName::ObjCZeroArgSelector:
  3383. case DeclarationName::ObjCOneArgSelector:
  3384. case DeclarationName::ObjCMultiArgSelector:
  3385. LE.write<uint32_t>(Writer.getSelectorRef(Name.getSelector()));
  3386. return;
  3387. case DeclarationName::CXXOperatorName:
  3388. assert(Name.getOperatorKind() < NUM_OVERLOADED_OPERATORS &&
  3389. "Invalid operator?");
  3390. LE.write<uint8_t>(Name.getOperatorKind());
  3391. return;
  3392. case DeclarationName::CXXConstructorName:
  3393. case DeclarationName::CXXDestructorName:
  3394. case DeclarationName::CXXConversionFunctionName:
  3395. case DeclarationName::CXXUsingDirective:
  3396. return;
  3397. }
  3398. llvm_unreachable("Invalid name kind?");
  3399. }
  3400. void EmitData(raw_ostream &Out, key_type_ref, data_type Lookup,
  3401. unsigned DataLen) {
  3402. using namespace llvm::support;
  3403. endian::Writer LE(Out, little);
  3404. uint64_t Start = Out.tell(); (void)Start;
  3405. for (unsigned I = Lookup.first, N = Lookup.second; I != N; ++I)
  3406. LE.write<uint32_t>(DeclIDs[I]);
  3407. assert(Out.tell() - Start == DataLen && "Data length is wrong");
  3408. }
  3409. };
  3410. } // namespace
  3411. bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
  3412. DeclContext *DC) {
  3413. return Result.hasExternalDecls() &&
  3414. DC->hasNeedToReconcileExternalVisibleStorage();
  3415. }
  3416. bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
  3417. DeclContext *DC) {
  3418. for (auto *D : Result.getLookupResult())
  3419. if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
  3420. return false;
  3421. return true;
  3422. }
  3423. void
  3424. ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
  3425. llvm::SmallVectorImpl<char> &LookupTable) {
  3426. assert(!ConstDC->hasLazyLocalLexicalLookups() &&
  3427. !ConstDC->hasLazyExternalLexicalLookups() &&
  3428. "must call buildLookups first");
  3429. // FIXME: We need to build the lookups table, which is logically const.
  3430. auto *DC = const_cast<DeclContext*>(ConstDC);
  3431. assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
  3432. // Create the on-disk hash table representation.
  3433. MultiOnDiskHashTableGenerator<reader::ASTDeclContextNameLookupTrait,
  3434. ASTDeclContextNameLookupTrait> Generator;
  3435. ASTDeclContextNameLookupTrait Trait(*this);
  3436. // The first step is to collect the declaration names which we need to
  3437. // serialize into the name lookup table, and to collect them in a stable
  3438. // order.
  3439. SmallVector<DeclarationName, 16> Names;
  3440. // We also build up small sets of the constructor and conversion function
  3441. // names which are visible.
  3442. llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
  3443. for (auto &Lookup : *DC->buildLookup()) {
  3444. auto &Name = Lookup.first;
  3445. auto &Result = Lookup.second;
  3446. // If there are no local declarations in our lookup result, we
  3447. // don't need to write an entry for the name at all. If we can't
  3448. // write out a lookup set without performing more deserialization,
  3449. // just skip this entry.
  3450. if (isLookupResultExternal(Result, DC) &&
  3451. isLookupResultEntirelyExternal(Result, DC))
  3452. continue;
  3453. // We also skip empty results. If any of the results could be external and
  3454. // the currently available results are empty, then all of the results are
  3455. // external and we skip it above. So the only way we get here with an empty
  3456. // results is when no results could have been external *and* we have
  3457. // external results.
  3458. //
  3459. // FIXME: While we might want to start emitting on-disk entries for negative
  3460. // lookups into a decl context as an optimization, today we *have* to skip
  3461. // them because there are names with empty lookup results in decl contexts
  3462. // which we can't emit in any stable ordering: we lookup constructors and
  3463. // conversion functions in the enclosing namespace scope creating empty
  3464. // results for them. This in almost certainly a bug in Clang's name lookup,
  3465. // but that is likely to be hard or impossible to fix and so we tolerate it
  3466. // here by omitting lookups with empty results.
  3467. if (Lookup.second.getLookupResult().empty())
  3468. continue;
  3469. switch (Lookup.first.getNameKind()) {
  3470. default:
  3471. Names.push_back(Lookup.first);
  3472. break;
  3473. case DeclarationName::CXXConstructorName:
  3474. assert(isa<CXXRecordDecl>(DC) &&
  3475. "Cannot have a constructor name outside of a class!");
  3476. ConstructorNameSet.insert(Name);
  3477. break;
  3478. case DeclarationName::CXXConversionFunctionName:
  3479. assert(isa<CXXRecordDecl>(DC) &&
  3480. "Cannot have a conversion function name outside of a class!");
  3481. ConversionNameSet.insert(Name);
  3482. break;
  3483. }
  3484. }
  3485. // Sort the names into a stable order.
  3486. llvm::sort(Names);
  3487. if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
  3488. // We need to establish an ordering of constructor and conversion function
  3489. // names, and they don't have an intrinsic ordering.
  3490. // First we try the easy case by forming the current context's constructor
  3491. // name and adding that name first. This is a very useful optimization to
  3492. // avoid walking the lexical declarations in many cases, and it also
  3493. // handles the only case where a constructor name can come from some other
  3494. // lexical context -- when that name is an implicit constructor merged from
  3495. // another declaration in the redecl chain. Any non-implicit constructor or
  3496. // conversion function which doesn't occur in all the lexical contexts
  3497. // would be an ODR violation.
  3498. auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
  3499. Context->getCanonicalType(Context->getRecordType(D)));
  3500. if (ConstructorNameSet.erase(ImplicitCtorName))
  3501. Names.push_back(ImplicitCtorName);
  3502. // If we still have constructors or conversion functions, we walk all the
  3503. // names in the decl and add the constructors and conversion functions
  3504. // which are visible in the order they lexically occur within the context.
  3505. if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
  3506. for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
  3507. if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
  3508. auto Name = ChildND->getDeclName();
  3509. switch (Name.getNameKind()) {
  3510. default:
  3511. continue;
  3512. case DeclarationName::CXXConstructorName:
  3513. if (ConstructorNameSet.erase(Name))
  3514. Names.push_back(Name);
  3515. break;
  3516. case DeclarationName::CXXConversionFunctionName:
  3517. if (ConversionNameSet.erase(Name))
  3518. Names.push_back(Name);
  3519. break;
  3520. }
  3521. if (ConstructorNameSet.empty() && ConversionNameSet.empty())
  3522. break;
  3523. }
  3524. assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
  3525. "constructors by walking all the "
  3526. "lexical members of the context.");
  3527. assert(ConversionNameSet.empty() && "Failed to find all of the visible "
  3528. "conversion functions by walking all "
  3529. "the lexical members of the context.");
  3530. }
  3531. // Next we need to do a lookup with each name into this decl context to fully
  3532. // populate any results from external sources. We don't actually use the
  3533. // results of these lookups because we only want to use the results after all
  3534. // results have been loaded and the pointers into them will be stable.
  3535. for (auto &Name : Names)
  3536. DC->lookup(Name);
  3537. // Now we need to insert the results for each name into the hash table. For
  3538. // constructor names and conversion function names, we actually need to merge
  3539. // all of the results for them into one list of results each and insert
  3540. // those.
  3541. SmallVector<NamedDecl *, 8> ConstructorDecls;
  3542. SmallVector<NamedDecl *, 8> ConversionDecls;
  3543. // Now loop over the names, either inserting them or appending for the two
  3544. // special cases.
  3545. for (auto &Name : Names) {
  3546. DeclContext::lookup_result Result = DC->noload_lookup(Name);
  3547. switch (Name.getNameKind()) {
  3548. default:
  3549. Generator.insert(Name, Trait.getData(Result), Trait);
  3550. break;
  3551. case DeclarationName::CXXConstructorName:
  3552. ConstructorDecls.append(Result.begin(), Result.end());
  3553. break;
  3554. case DeclarationName::CXXConversionFunctionName:
  3555. ConversionDecls.append(Result.begin(), Result.end());
  3556. break;
  3557. }
  3558. }
  3559. // Handle our two special cases if we ended up having any. We arbitrarily use
  3560. // the first declaration's name here because the name itself isn't part of
  3561. // the key, only the kind of name is used.
  3562. if (!ConstructorDecls.empty())
  3563. Generator.insert(ConstructorDecls.front()->getDeclName(),
  3564. Trait.getData(ConstructorDecls), Trait);
  3565. if (!ConversionDecls.empty())
  3566. Generator.insert(ConversionDecls.front()->getDeclName(),
  3567. Trait.getData(ConversionDecls), Trait);
  3568. // Create the on-disk hash table. Also emit the existing imported and
  3569. // merged table if there is one.
  3570. auto *Lookups = Chain ? Chain->getLoadedLookupTables(DC) : nullptr;
  3571. Generator.emit(LookupTable, Trait, Lookups ? &Lookups->Table : nullptr);
  3572. }
  3573. /// Write the block containing all of the declaration IDs
  3574. /// visible from the given DeclContext.
  3575. ///
  3576. /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
  3577. /// bitstream, or 0 if no block was written.
  3578. uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
  3579. DeclContext *DC) {
  3580. // If we imported a key declaration of this namespace, write the visible
  3581. // lookup results as an update record for it rather than including them
  3582. // on this declaration. We will only look at key declarations on reload.
  3583. if (isa<NamespaceDecl>(DC) && Chain &&
  3584. Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
  3585. // Only do this once, for the first local declaration of the namespace.
  3586. for (auto *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
  3587. Prev = Prev->getPreviousDecl())
  3588. if (!Prev->isFromASTFile())
  3589. return 0;
  3590. // Note that we need to emit an update record for the primary context.
  3591. UpdatedDeclContexts.insert(DC->getPrimaryContext());
  3592. // Make sure all visible decls are written. They will be recorded later. We
  3593. // do this using a side data structure so we can sort the names into
  3594. // a deterministic order.
  3595. StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
  3596. SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
  3597. LookupResults;
  3598. if (Map) {
  3599. LookupResults.reserve(Map->size());
  3600. for (auto &Entry : *Map)
  3601. LookupResults.push_back(
  3602. std::make_pair(Entry.first, Entry.second.getLookupResult()));
  3603. }
  3604. llvm::sort(LookupResults, llvm::less_first());
  3605. for (auto &NameAndResult : LookupResults) {
  3606. DeclarationName Name = NameAndResult.first;
  3607. DeclContext::lookup_result Result = NameAndResult.second;
  3608. if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
  3609. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  3610. // We have to work around a name lookup bug here where negative lookup
  3611. // results for these names get cached in namespace lookup tables (these
  3612. // names should never be looked up in a namespace).
  3613. assert(Result.empty() && "Cannot have a constructor or conversion "
  3614. "function name in a namespace!");
  3615. continue;
  3616. }
  3617. for (NamedDecl *ND : Result)
  3618. if (!ND->isFromASTFile())
  3619. GetDeclRef(ND);
  3620. }
  3621. return 0;
  3622. }
  3623. if (DC->getPrimaryContext() != DC)
  3624. return 0;
  3625. // Skip contexts which don't support name lookup.
  3626. if (!DC->isLookupContext())
  3627. return 0;
  3628. // If not in C++, we perform name lookup for the translation unit via the
  3629. // IdentifierInfo chains, don't bother to build a visible-declarations table.
  3630. if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
  3631. return 0;
  3632. // Serialize the contents of the mapping used for lookup. Note that,
  3633. // although we have two very different code paths, the serialized
  3634. // representation is the same for both cases: a declaration name,
  3635. // followed by a size, followed by references to the visible
  3636. // declarations that have that name.
  3637. uint64_t Offset = Stream.GetCurrentBitNo();
  3638. StoredDeclsMap *Map = DC->buildLookup();
  3639. if (!Map || Map->empty())
  3640. return 0;
  3641. // Create the on-disk hash table in a buffer.
  3642. SmallString<4096> LookupTable;
  3643. GenerateNameLookupTable(DC, LookupTable);
  3644. // Write the lookup table
  3645. RecordData::value_type Record[] = {DECL_CONTEXT_VISIBLE};
  3646. Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
  3647. LookupTable);
  3648. ++NumVisibleDeclContexts;
  3649. return Offset;
  3650. }
  3651. /// Write an UPDATE_VISIBLE block for the given context.
  3652. ///
  3653. /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
  3654. /// DeclContext in a dependent AST file. As such, they only exist for the TU
  3655. /// (in C++), for namespaces, and for classes with forward-declared unscoped
  3656. /// enumeration members (in C++11).
  3657. void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
  3658. StoredDeclsMap *Map = DC->getLookupPtr();
  3659. if (!Map || Map->empty())
  3660. return;
  3661. // Create the on-disk hash table in a buffer.
  3662. SmallString<4096> LookupTable;
  3663. GenerateNameLookupTable(DC, LookupTable);
  3664. // If we're updating a namespace, select a key declaration as the key for the
  3665. // update record; those are the only ones that will be checked on reload.
  3666. if (isa<NamespaceDecl>(DC))
  3667. DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
  3668. // Write the lookup table
  3669. RecordData::value_type Record[] = {UPDATE_VISIBLE, getDeclID(cast<Decl>(DC))};
  3670. Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
  3671. }
  3672. /// Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
  3673. void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
  3674. RecordData::value_type Record[] = {Opts.getInt()};
  3675. Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
  3676. }
  3677. /// Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
  3678. void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
  3679. if (!SemaRef.Context.getLangOpts().OpenCL)
  3680. return;
  3681. const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
  3682. RecordData Record;
  3683. for (const auto &I:Opts.OptMap) {
  3684. AddString(I.getKey(), Record);
  3685. auto V = I.getValue();
  3686. Record.push_back(V.Supported ? 1 : 0);
  3687. Record.push_back(V.Enabled ? 1 : 0);
  3688. Record.push_back(V.Avail);
  3689. Record.push_back(V.Core);
  3690. }
  3691. Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
  3692. }
  3693. void ASTWriter::WriteOpenCLExtensionTypes(Sema &SemaRef) {
  3694. if (!SemaRef.Context.getLangOpts().OpenCL)
  3695. return;
  3696. // Sort the elements of the map OpenCLTypeExtMap by TypeIDs,
  3697. // without copying them.
  3698. const llvm::DenseMap<const Type *, std::set<std::string>> &OpenCLTypeExtMap =
  3699. SemaRef.OpenCLTypeExtMap;
  3700. using ElementTy = std::pair<TypeID, const std::set<std::string> *>;
  3701. llvm::SmallVector<ElementTy, 8> StableOpenCLTypeExtMap;
  3702. StableOpenCLTypeExtMap.reserve(OpenCLTypeExtMap.size());
  3703. for (const auto &I : OpenCLTypeExtMap)
  3704. StableOpenCLTypeExtMap.emplace_back(
  3705. getTypeID(I.first->getCanonicalTypeInternal()), &I.second);
  3706. auto CompareByTypeID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
  3707. return E1.first < E2.first;
  3708. };
  3709. llvm::sort(StableOpenCLTypeExtMap, CompareByTypeID);
  3710. RecordData Record;
  3711. for (const ElementTy &E : StableOpenCLTypeExtMap) {
  3712. Record.push_back(E.first); // TypeID
  3713. const std::set<std::string> *ExtSet = E.second;
  3714. Record.push_back(static_cast<unsigned>(ExtSet->size()));
  3715. for (const std::string &Ext : *ExtSet)
  3716. AddString(Ext, Record);
  3717. }
  3718. Stream.EmitRecord(OPENCL_EXTENSION_TYPES, Record);
  3719. }
  3720. void ASTWriter::WriteOpenCLExtensionDecls(Sema &SemaRef) {
  3721. if (!SemaRef.Context.getLangOpts().OpenCL)
  3722. return;
  3723. // Sort the elements of the map OpenCLDeclExtMap by DeclIDs,
  3724. // without copying them.
  3725. const llvm::DenseMap<const Decl *, std::set<std::string>> &OpenCLDeclExtMap =
  3726. SemaRef.OpenCLDeclExtMap;
  3727. using ElementTy = std::pair<DeclID, const std::set<std::string> *>;
  3728. llvm::SmallVector<ElementTy, 8> StableOpenCLDeclExtMap;
  3729. StableOpenCLDeclExtMap.reserve(OpenCLDeclExtMap.size());
  3730. for (const auto &I : OpenCLDeclExtMap)
  3731. StableOpenCLDeclExtMap.emplace_back(getDeclID(I.first), &I.second);
  3732. auto CompareByDeclID = [](const ElementTy &E1, const ElementTy &E2) -> bool {
  3733. return E1.first < E2.first;
  3734. };
  3735. llvm::sort(StableOpenCLDeclExtMap, CompareByDeclID);
  3736. RecordData Record;
  3737. for (const ElementTy &E : StableOpenCLDeclExtMap) {
  3738. Record.push_back(E.first); // DeclID
  3739. const std::set<std::string> *ExtSet = E.second;
  3740. Record.push_back(static_cast<unsigned>(ExtSet->size()));
  3741. for (const std::string &Ext : *ExtSet)
  3742. AddString(Ext, Record);
  3743. }
  3744. Stream.EmitRecord(OPENCL_EXTENSION_DECLS, Record);
  3745. }
  3746. void ASTWriter::WriteCUDAPragmas(Sema &SemaRef) {
  3747. if (SemaRef.ForceCUDAHostDeviceDepth > 0) {
  3748. RecordData::value_type Record[] = {SemaRef.ForceCUDAHostDeviceDepth};
  3749. Stream.EmitRecord(CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH, Record);
  3750. }
  3751. }
  3752. void ASTWriter::WriteObjCCategories() {
  3753. SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
  3754. RecordData Categories;
  3755. for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
  3756. unsigned Size = 0;
  3757. unsigned StartIndex = Categories.size();
  3758. ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
  3759. // Allocate space for the size.
  3760. Categories.push_back(0);
  3761. // Add the categories.
  3762. for (ObjCInterfaceDecl::known_categories_iterator
  3763. Cat = Class->known_categories_begin(),
  3764. CatEnd = Class->known_categories_end();
  3765. Cat != CatEnd; ++Cat, ++Size) {
  3766. assert(getDeclID(*Cat) != 0 && "Bogus category");
  3767. AddDeclRef(*Cat, Categories);
  3768. }
  3769. // Update the size.
  3770. Categories[StartIndex] = Size;
  3771. // Record this interface -> category map.
  3772. ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
  3773. CategoriesMap.push_back(CatInfo);
  3774. }
  3775. // Sort the categories map by the definition ID, since the reader will be
  3776. // performing binary searches on this information.
  3777. llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
  3778. // Emit the categories map.
  3779. using namespace llvm;
  3780. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  3781. Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
  3782. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
  3783. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3784. unsigned AbbrevID = Stream.EmitAbbrev(std::move(Abbrev));
  3785. RecordData::value_type Record[] = {OBJC_CATEGORIES_MAP, CategoriesMap.size()};
  3786. Stream.EmitRecordWithBlob(AbbrevID, Record,
  3787. reinterpret_cast<char *>(CategoriesMap.data()),
  3788. CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
  3789. // Emit the category lists.
  3790. Stream.EmitRecord(OBJC_CATEGORIES, Categories);
  3791. }
  3792. void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
  3793. Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
  3794. if (LPTMap.empty())
  3795. return;
  3796. RecordData Record;
  3797. for (auto &LPTMapEntry : LPTMap) {
  3798. const FunctionDecl *FD = LPTMapEntry.first;
  3799. LateParsedTemplate &LPT = *LPTMapEntry.second;
  3800. AddDeclRef(FD, Record);
  3801. AddDeclRef(LPT.D, Record);
  3802. Record.push_back(LPT.Toks.size());
  3803. for (const auto &Tok : LPT.Toks) {
  3804. AddToken(Tok, Record);
  3805. }
  3806. }
  3807. Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
  3808. }
  3809. /// Write the state of 'pragma clang optimize' at the end of the module.
  3810. void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
  3811. RecordData Record;
  3812. SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
  3813. AddSourceLocation(PragmaLoc, Record);
  3814. Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
  3815. }
  3816. /// Write the state of 'pragma ms_struct' at the end of the module.
  3817. void ASTWriter::WriteMSStructPragmaOptions(Sema &SemaRef) {
  3818. RecordData Record;
  3819. Record.push_back(SemaRef.MSStructPragmaOn ? PMSST_ON : PMSST_OFF);
  3820. Stream.EmitRecord(MSSTRUCT_PRAGMA_OPTIONS, Record);
  3821. }
  3822. /// Write the state of 'pragma pointers_to_members' at the end of the
  3823. //module.
  3824. void ASTWriter::WriteMSPointersToMembersPragmaOptions(Sema &SemaRef) {
  3825. RecordData Record;
  3826. Record.push_back(SemaRef.MSPointerToMemberRepresentationMethod);
  3827. AddSourceLocation(SemaRef.ImplicitMSInheritanceAttrLoc, Record);
  3828. Stream.EmitRecord(POINTERS_TO_MEMBERS_PRAGMA_OPTIONS, Record);
  3829. }
  3830. /// Write the state of 'pragma pack' at the end of the module.
  3831. void ASTWriter::WritePackPragmaOptions(Sema &SemaRef) {
  3832. // Don't serialize pragma pack state for modules, since it should only take
  3833. // effect on a per-submodule basis.
  3834. if (WritingModule)
  3835. return;
  3836. RecordData Record;
  3837. Record.push_back(SemaRef.PackStack.CurrentValue);
  3838. AddSourceLocation(SemaRef.PackStack.CurrentPragmaLocation, Record);
  3839. Record.push_back(SemaRef.PackStack.Stack.size());
  3840. for (const auto &StackEntry : SemaRef.PackStack.Stack) {
  3841. Record.push_back(StackEntry.Value);
  3842. AddSourceLocation(StackEntry.PragmaLocation, Record);
  3843. AddSourceLocation(StackEntry.PragmaPushLocation, Record);
  3844. AddString(StackEntry.StackSlotLabel, Record);
  3845. }
  3846. Stream.EmitRecord(PACK_PRAGMA_OPTIONS, Record);
  3847. }
  3848. void ASTWriter::WriteModuleFileExtension(Sema &SemaRef,
  3849. ModuleFileExtensionWriter &Writer) {
  3850. // Enter the extension block.
  3851. Stream.EnterSubblock(EXTENSION_BLOCK_ID, 4);
  3852. // Emit the metadata record abbreviation.
  3853. auto Abv = std::make_shared<llvm::BitCodeAbbrev>();
  3854. Abv->Add(llvm::BitCodeAbbrevOp(EXTENSION_METADATA));
  3855. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  3856. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  3857. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  3858. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  3859. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  3860. unsigned Abbrev = Stream.EmitAbbrev(std::move(Abv));
  3861. // Emit the metadata record.
  3862. RecordData Record;
  3863. auto Metadata = Writer.getExtension()->getExtensionMetadata();
  3864. Record.push_back(EXTENSION_METADATA);
  3865. Record.push_back(Metadata.MajorVersion);
  3866. Record.push_back(Metadata.MinorVersion);
  3867. Record.push_back(Metadata.BlockName.size());
  3868. Record.push_back(Metadata.UserInfo.size());
  3869. SmallString<64> Buffer;
  3870. Buffer += Metadata.BlockName;
  3871. Buffer += Metadata.UserInfo;
  3872. Stream.EmitRecordWithBlob(Abbrev, Record, Buffer);
  3873. // Emit the contents of the extension block.
  3874. Writer.writeExtensionContents(SemaRef, Stream);
  3875. // Exit the extension block.
  3876. Stream.ExitBlock();
  3877. }
  3878. //===----------------------------------------------------------------------===//
  3879. // General Serialization Routines
  3880. //===----------------------------------------------------------------------===//
  3881. void ASTRecordWriter::AddAttr(const Attr *A) {
  3882. auto &Record = *this;
  3883. if (!A)
  3884. return Record.push_back(0);
  3885. Record.push_back(A->getKind() + 1); // FIXME: stable encoding, target attrs
  3886. Record.AddIdentifierRef(A->getAttrName());
  3887. Record.AddIdentifierRef(A->getScopeName());
  3888. Record.AddSourceRange(A->getRange());
  3889. Record.AddSourceLocation(A->getScopeLoc());
  3890. Record.push_back(A->getParsedKind());
  3891. Record.push_back(A->getSyntax());
  3892. Record.push_back(A->getAttributeSpellingListIndexRaw());
  3893. #include "clang/Serialization/AttrPCHWrite.inc"
  3894. }
  3895. /// Emit the list of attributes to the specified record.
  3896. void ASTRecordWriter::AddAttributes(ArrayRef<const Attr *> Attrs) {
  3897. push_back(Attrs.size());
  3898. for (const auto *A : Attrs)
  3899. AddAttr(A);
  3900. }
  3901. void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
  3902. AddSourceLocation(Tok.getLocation(), Record);
  3903. Record.push_back(Tok.getLength());
  3904. // FIXME: When reading literal tokens, reconstruct the literal pointer
  3905. // if it is needed.
  3906. AddIdentifierRef(Tok.getIdentifierInfo(), Record);
  3907. // FIXME: Should translate token kind to a stable encoding.
  3908. Record.push_back(Tok.getKind());
  3909. // FIXME: Should translate token flags to a stable encoding.
  3910. Record.push_back(Tok.getFlags());
  3911. }
  3912. void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
  3913. Record.push_back(Str.size());
  3914. Record.insert(Record.end(), Str.begin(), Str.end());
  3915. }
  3916. bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
  3917. assert(Context && "should have context when outputting path");
  3918. bool Changed =
  3919. cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
  3920. // Remove a prefix to make the path relative, if relevant.
  3921. const char *PathBegin = Path.data();
  3922. const char *PathPtr =
  3923. adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
  3924. if (PathPtr != PathBegin) {
  3925. Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
  3926. Changed = true;
  3927. }
  3928. return Changed;
  3929. }
  3930. void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
  3931. SmallString<128> FilePath(Path);
  3932. PreparePathForOutput(FilePath);
  3933. AddString(FilePath, Record);
  3934. }
  3935. void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataRef Record,
  3936. StringRef Path) {
  3937. SmallString<128> FilePath(Path);
  3938. PreparePathForOutput(FilePath);
  3939. Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
  3940. }
  3941. void ASTWriter::AddVersionTuple(const VersionTuple &Version,
  3942. RecordDataImpl &Record) {
  3943. Record.push_back(Version.getMajor());
  3944. if (Optional<unsigned> Minor = Version.getMinor())
  3945. Record.push_back(*Minor + 1);
  3946. else
  3947. Record.push_back(0);
  3948. if (Optional<unsigned> Subminor = Version.getSubminor())
  3949. Record.push_back(*Subminor + 1);
  3950. else
  3951. Record.push_back(0);
  3952. }
  3953. /// Note that the identifier II occurs at the given offset
  3954. /// within the identifier table.
  3955. void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
  3956. IdentID ID = IdentifierIDs[II];
  3957. // Only store offsets new to this AST file. Other identifier names are looked
  3958. // up earlier in the chain and thus don't need an offset.
  3959. if (ID >= FirstIdentID)
  3960. IdentifierOffsets[ID - FirstIdentID] = Offset;
  3961. }
  3962. /// Note that the selector Sel occurs at the given offset
  3963. /// within the method pool/selector table.
  3964. void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
  3965. unsigned ID = SelectorIDs[Sel];
  3966. assert(ID && "Unknown selector");
  3967. // Don't record offsets for selectors that are also available in a different
  3968. // file.
  3969. if (ID < FirstSelectorID)
  3970. return;
  3971. SelectorOffsets[ID - FirstSelectorID] = Offset;
  3972. }
  3973. ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream,
  3974. SmallVectorImpl<char> &Buffer,
  3975. InMemoryModuleCache &ModuleCache,
  3976. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
  3977. bool IncludeTimestamps)
  3978. : Stream(Stream), Buffer(Buffer), ModuleCache(ModuleCache),
  3979. IncludeTimestamps(IncludeTimestamps) {
  3980. for (const auto &Ext : Extensions) {
  3981. if (auto Writer = Ext->createExtensionWriter(*this))
  3982. ModuleFileExtensionWriters.push_back(std::move(Writer));
  3983. }
  3984. }
  3985. ASTWriter::~ASTWriter() {
  3986. llvm::DeleteContainerSeconds(FileDeclIDs);
  3987. }
  3988. const LangOptions &ASTWriter::getLangOpts() const {
  3989. assert(WritingAST && "can't determine lang opts when not writing AST");
  3990. return Context->getLangOpts();
  3991. }
  3992. time_t ASTWriter::getTimestampForOutput(const FileEntry *E) const {
  3993. return IncludeTimestamps ? E->getModificationTime() : 0;
  3994. }
  3995. ASTFileSignature ASTWriter::WriteAST(Sema &SemaRef,
  3996. const std::string &OutputFile,
  3997. Module *WritingModule, StringRef isysroot,
  3998. bool hasErrors,
  3999. bool ShouldCacheASTInMemory) {
  4000. WritingAST = true;
  4001. ASTHasCompilerErrors = hasErrors;
  4002. // Emit the file header.
  4003. Stream.Emit((unsigned)'C', 8);
  4004. Stream.Emit((unsigned)'P', 8);
  4005. Stream.Emit((unsigned)'C', 8);
  4006. Stream.Emit((unsigned)'H', 8);
  4007. WriteBlockInfoBlock();
  4008. Context = &SemaRef.Context;
  4009. PP = &SemaRef.PP;
  4010. this->WritingModule = WritingModule;
  4011. ASTFileSignature Signature =
  4012. WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
  4013. Context = nullptr;
  4014. PP = nullptr;
  4015. this->WritingModule = nullptr;
  4016. this->BaseDirectory.clear();
  4017. WritingAST = false;
  4018. if (ShouldCacheASTInMemory) {
  4019. // Construct MemoryBuffer and update buffer manager.
  4020. ModuleCache.addBuiltPCM(OutputFile,
  4021. llvm::MemoryBuffer::getMemBufferCopy(
  4022. StringRef(Buffer.begin(), Buffer.size())));
  4023. }
  4024. return Signature;
  4025. }
  4026. template<typename Vector>
  4027. static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
  4028. ASTWriter::RecordData &Record) {
  4029. for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
  4030. I != E; ++I) {
  4031. Writer.AddDeclRef(*I, Record);
  4032. }
  4033. }
  4034. ASTFileSignature ASTWriter::WriteASTCore(Sema &SemaRef, StringRef isysroot,
  4035. const std::string &OutputFile,
  4036. Module *WritingModule) {
  4037. using namespace llvm;
  4038. bool isModule = WritingModule != nullptr;
  4039. // Make sure that the AST reader knows to finalize itself.
  4040. if (Chain)
  4041. Chain->finalizeForWriting();
  4042. ASTContext &Context = SemaRef.Context;
  4043. Preprocessor &PP = SemaRef.PP;
  4044. // Set up predefined declaration IDs.
  4045. auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
  4046. if (D) {
  4047. assert(D->isCanonicalDecl() && "predefined decl is not canonical");
  4048. DeclIDs[D] = ID;
  4049. }
  4050. };
  4051. RegisterPredefDecl(Context.getTranslationUnitDecl(),
  4052. PREDEF_DECL_TRANSLATION_UNIT_ID);
  4053. RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
  4054. RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
  4055. RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
  4056. RegisterPredefDecl(Context.ObjCProtocolClassDecl,
  4057. PREDEF_DECL_OBJC_PROTOCOL_ID);
  4058. RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
  4059. RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
  4060. RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
  4061. PREDEF_DECL_OBJC_INSTANCETYPE_ID);
  4062. RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
  4063. RegisterPredefDecl(Context.VaListTagDecl, PREDEF_DECL_VA_LIST_TAG);
  4064. RegisterPredefDecl(Context.BuiltinMSVaListDecl,
  4065. PREDEF_DECL_BUILTIN_MS_VA_LIST_ID);
  4066. RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
  4067. RegisterPredefDecl(Context.MakeIntegerSeqDecl,
  4068. PREDEF_DECL_MAKE_INTEGER_SEQ_ID);
  4069. RegisterPredefDecl(Context.CFConstantStringTypeDecl,
  4070. PREDEF_DECL_CF_CONSTANT_STRING_ID);
  4071. RegisterPredefDecl(Context.CFConstantStringTagDecl,
  4072. PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID);
  4073. RegisterPredefDecl(Context.TypePackElementDecl,
  4074. PREDEF_DECL_TYPE_PACK_ELEMENT_ID);
  4075. // Build a record containing all of the tentative definitions in this file, in
  4076. // TentativeDefinitions order. Generally, this record will be empty for
  4077. // headers.
  4078. RecordData TentativeDefinitions;
  4079. AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
  4080. // Build a record containing all of the file scoped decls in this file.
  4081. RecordData UnusedFileScopedDecls;
  4082. if (!isModule)
  4083. AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
  4084. UnusedFileScopedDecls);
  4085. // Build a record containing all of the delegating constructors we still need
  4086. // to resolve.
  4087. RecordData DelegatingCtorDecls;
  4088. if (!isModule)
  4089. AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
  4090. // Write the set of weak, undeclared identifiers. We always write the
  4091. // entire table, since later PCH files in a PCH chain are only interested in
  4092. // the results at the end of the chain.
  4093. RecordData WeakUndeclaredIdentifiers;
  4094. for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
  4095. IdentifierInfo *II = WeakUndeclaredIdentifier.first;
  4096. WeakInfo &WI = WeakUndeclaredIdentifier.second;
  4097. AddIdentifierRef(II, WeakUndeclaredIdentifiers);
  4098. AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
  4099. AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
  4100. WeakUndeclaredIdentifiers.push_back(WI.getUsed());
  4101. }
  4102. // Build a record containing all of the ext_vector declarations.
  4103. RecordData ExtVectorDecls;
  4104. AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
  4105. // Build a record containing all of the VTable uses information.
  4106. RecordData VTableUses;
  4107. if (!SemaRef.VTableUses.empty()) {
  4108. for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
  4109. AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
  4110. AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
  4111. VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
  4112. }
  4113. }
  4114. // Build a record containing all of the UnusedLocalTypedefNameCandidates.
  4115. RecordData UnusedLocalTypedefNameCandidates;
  4116. for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
  4117. AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
  4118. // Build a record containing all of pending implicit instantiations.
  4119. RecordData PendingInstantiations;
  4120. for (const auto &I : SemaRef.PendingInstantiations) {
  4121. AddDeclRef(I.first, PendingInstantiations);
  4122. AddSourceLocation(I.second, PendingInstantiations);
  4123. }
  4124. assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
  4125. "There are local ones at end of translation unit!");
  4126. // Build a record containing some declaration references.
  4127. RecordData SemaDeclRefs;
  4128. if (SemaRef.StdNamespace || SemaRef.StdBadAlloc || SemaRef.StdAlignValT) {
  4129. AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
  4130. AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
  4131. AddDeclRef(SemaRef.getStdAlignValT(), SemaDeclRefs);
  4132. }
  4133. RecordData CUDASpecialDeclRefs;
  4134. if (Context.getcudaConfigureCallDecl()) {
  4135. AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
  4136. }
  4137. // Build a record containing all of the known namespaces.
  4138. RecordData KnownNamespaces;
  4139. for (const auto &I : SemaRef.KnownNamespaces) {
  4140. if (!I.second)
  4141. AddDeclRef(I.first, KnownNamespaces);
  4142. }
  4143. // Build a record of all used, undefined objects that require definitions.
  4144. RecordData UndefinedButUsed;
  4145. SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
  4146. SemaRef.getUndefinedButUsed(Undefined);
  4147. for (const auto &I : Undefined) {
  4148. AddDeclRef(I.first, UndefinedButUsed);
  4149. AddSourceLocation(I.second, UndefinedButUsed);
  4150. }
  4151. // Build a record containing all delete-expressions that we would like to
  4152. // analyze later in AST.
  4153. RecordData DeleteExprsToAnalyze;
  4154. if (!isModule) {
  4155. for (const auto &DeleteExprsInfo :
  4156. SemaRef.getMismatchingDeleteExpressions()) {
  4157. AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
  4158. DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
  4159. for (const auto &DeleteLoc : DeleteExprsInfo.second) {
  4160. AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
  4161. DeleteExprsToAnalyze.push_back(DeleteLoc.second);
  4162. }
  4163. }
  4164. }
  4165. // Write the control block
  4166. WriteControlBlock(PP, Context, isysroot, OutputFile);
  4167. // Write the remaining AST contents.
  4168. Stream.EnterSubblock(AST_BLOCK_ID, 5);
  4169. // This is so that older clang versions, before the introduction
  4170. // of the control block, can read and reject the newer PCH format.
  4171. {
  4172. RecordData Record = {VERSION_MAJOR};
  4173. Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
  4174. }
  4175. // Create a lexical update block containing all of the declarations in the
  4176. // translation unit that do not come from other AST files.
  4177. const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
  4178. SmallVector<uint32_t, 128> NewGlobalKindDeclPairs;
  4179. for (const auto *D : TU->noload_decls()) {
  4180. if (!D->isFromASTFile()) {
  4181. NewGlobalKindDeclPairs.push_back(D->getKind());
  4182. NewGlobalKindDeclPairs.push_back(GetDeclRef(D));
  4183. }
  4184. }
  4185. auto Abv = std::make_shared<BitCodeAbbrev>();
  4186. Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
  4187. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  4188. unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(std::move(Abv));
  4189. {
  4190. RecordData::value_type Record[] = {TU_UPDATE_LEXICAL};
  4191. Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
  4192. bytes(NewGlobalKindDeclPairs));
  4193. }
  4194. // And a visible updates block for the translation unit.
  4195. Abv = std::make_shared<BitCodeAbbrev>();
  4196. Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
  4197. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  4198. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  4199. UpdateVisibleAbbrev = Stream.EmitAbbrev(std::move(Abv));
  4200. WriteDeclContextVisibleUpdate(TU);
  4201. // If we have any extern "C" names, write out a visible update for them.
  4202. if (Context.ExternCContext)
  4203. WriteDeclContextVisibleUpdate(Context.ExternCContext);
  4204. // If the translation unit has an anonymous namespace, and we don't already
  4205. // have an update block for it, write it as an update block.
  4206. // FIXME: Why do we not do this if there's already an update block?
  4207. if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
  4208. ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
  4209. if (Record.empty())
  4210. Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
  4211. }
  4212. // Add update records for all mangling numbers and static local numbers.
  4213. // These aren't really update records, but this is a convenient way of
  4214. // tagging this rare extra data onto the declarations.
  4215. for (const auto &Number : Context.MangleNumbers)
  4216. if (!Number.first->isFromASTFile())
  4217. DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
  4218. Number.second));
  4219. for (const auto &Number : Context.StaticLocalNumbers)
  4220. if (!Number.first->isFromASTFile())
  4221. DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
  4222. Number.second));
  4223. // Make sure visible decls, added to DeclContexts previously loaded from
  4224. // an AST file, are registered for serialization. Likewise for template
  4225. // specializations added to imported templates.
  4226. for (const auto *I : DeclsToEmitEvenIfUnreferenced) {
  4227. GetDeclRef(I);
  4228. }
  4229. // Make sure all decls associated with an identifier are registered for
  4230. // serialization, if we're storing decls with identifiers.
  4231. if (!WritingModule || !getLangOpts().CPlusPlus) {
  4232. llvm::SmallVector<const IdentifierInfo*, 256> IIs;
  4233. for (const auto &ID : PP.getIdentifierTable()) {
  4234. const IdentifierInfo *II = ID.second;
  4235. if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
  4236. IIs.push_back(II);
  4237. }
  4238. // Sort the identifiers to visit based on their name.
  4239. llvm::sort(IIs, llvm::deref<std::less<>>());
  4240. for (const IdentifierInfo *II : IIs) {
  4241. for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
  4242. DEnd = SemaRef.IdResolver.end();
  4243. D != DEnd; ++D) {
  4244. GetDeclRef(*D);
  4245. }
  4246. }
  4247. }
  4248. // For method pool in the module, if it contains an entry for a selector,
  4249. // the entry should be complete, containing everything introduced by that
  4250. // module and all modules it imports. It's possible that the entry is out of
  4251. // date, so we need to pull in the new content here.
  4252. // It's possible that updateOutOfDateSelector can update SelectorIDs. To be
  4253. // safe, we copy all selectors out.
  4254. llvm::SmallVector<Selector, 256> AllSelectors;
  4255. for (auto &SelectorAndID : SelectorIDs)
  4256. AllSelectors.push_back(SelectorAndID.first);
  4257. for (auto &Selector : AllSelectors)
  4258. SemaRef.updateOutOfDateSelector(Selector);
  4259. // Form the record of special types.
  4260. RecordData SpecialTypes;
  4261. AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
  4262. AddTypeRef(Context.getFILEType(), SpecialTypes);
  4263. AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
  4264. AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
  4265. AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
  4266. AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
  4267. AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
  4268. AddTypeRef(Context.getucontext_tType(), SpecialTypes);
  4269. if (Chain) {
  4270. // Write the mapping information describing our module dependencies and how
  4271. // each of those modules were mapped into our own offset/ID space, so that
  4272. // the reader can build the appropriate mapping to its own offset/ID space.
  4273. // The map consists solely of a blob with the following format:
  4274. // *(module-kind:i8
  4275. // module-name-len:i16 module-name:len*i8
  4276. // source-location-offset:i32
  4277. // identifier-id:i32
  4278. // preprocessed-entity-id:i32
  4279. // macro-definition-id:i32
  4280. // submodule-id:i32
  4281. // selector-id:i32
  4282. // declaration-id:i32
  4283. // c++-base-specifiers-id:i32
  4284. // type-id:i32)
  4285. //
  4286. // module-kind is the ModuleKind enum value. If it is MK_PrebuiltModule or
  4287. // MK_ExplicitModule, then the module-name is the module name. Otherwise,
  4288. // it is the module file name.
  4289. auto Abbrev = std::make_shared<BitCodeAbbrev>();
  4290. Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
  4291. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  4292. unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(std::move(Abbrev));
  4293. SmallString<2048> Buffer;
  4294. {
  4295. llvm::raw_svector_ostream Out(Buffer);
  4296. for (ModuleFile &M : Chain->ModuleMgr) {
  4297. using namespace llvm::support;
  4298. endian::Writer LE(Out, little);
  4299. LE.write<uint8_t>(static_cast<uint8_t>(M.Kind));
  4300. StringRef Name =
  4301. M.Kind == MK_PrebuiltModule || M.Kind == MK_ExplicitModule
  4302. ? M.ModuleName
  4303. : M.FileName;
  4304. LE.write<uint16_t>(Name.size());
  4305. Out.write(Name.data(), Name.size());
  4306. // Note: if a base ID was uint max, it would not be possible to load
  4307. // another module after it or have more than one entity inside it.
  4308. uint32_t None = std::numeric_limits<uint32_t>::max();
  4309. auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
  4310. assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
  4311. if (ShouldWrite)
  4312. LE.write<uint32_t>(BaseID);
  4313. else
  4314. LE.write<uint32_t>(None);
  4315. };
  4316. // These values should be unique within a chain, since they will be read
  4317. // as keys into ContinuousRangeMaps.
  4318. writeBaseIDOrNone(M.SLocEntryBaseOffset, M.LocalNumSLocEntries);
  4319. writeBaseIDOrNone(M.BaseIdentifierID, M.LocalNumIdentifiers);
  4320. writeBaseIDOrNone(M.BaseMacroID, M.LocalNumMacros);
  4321. writeBaseIDOrNone(M.BasePreprocessedEntityID,
  4322. M.NumPreprocessedEntities);
  4323. writeBaseIDOrNone(M.BaseSubmoduleID, M.LocalNumSubmodules);
  4324. writeBaseIDOrNone(M.BaseSelectorID, M.LocalNumSelectors);
  4325. writeBaseIDOrNone(M.BaseDeclID, M.LocalNumDecls);
  4326. writeBaseIDOrNone(M.BaseTypeIndex, M.LocalNumTypes);
  4327. }
  4328. }
  4329. RecordData::value_type Record[] = {MODULE_OFFSET_MAP};
  4330. Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
  4331. Buffer.data(), Buffer.size());
  4332. }
  4333. RecordData DeclUpdatesOffsetsRecord;
  4334. // Keep writing types, declarations, and declaration update records
  4335. // until we've emitted all of them.
  4336. Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
  4337. WriteTypeAbbrevs();
  4338. WriteDeclAbbrevs();
  4339. do {
  4340. WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
  4341. while (!DeclTypesToEmit.empty()) {
  4342. DeclOrType DOT = DeclTypesToEmit.front();
  4343. DeclTypesToEmit.pop();
  4344. if (DOT.isType())
  4345. WriteType(DOT.getType());
  4346. else
  4347. WriteDecl(Context, DOT.getDecl());
  4348. }
  4349. } while (!DeclUpdates.empty());
  4350. Stream.ExitBlock();
  4351. DoneWritingDeclsAndTypes = true;
  4352. // These things can only be done once we've written out decls and types.
  4353. WriteTypeDeclOffsets();
  4354. if (!DeclUpdatesOffsetsRecord.empty())
  4355. Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
  4356. WriteFileDeclIDsMap();
  4357. WriteSourceManagerBlock(Context.getSourceManager(), PP);
  4358. WriteComments();
  4359. WritePreprocessor(PP, isModule);
  4360. WriteHeaderSearch(PP.getHeaderSearchInfo());
  4361. WriteSelectors(SemaRef);
  4362. WriteReferencedSelectorsPool(SemaRef);
  4363. WriteLateParsedTemplates(SemaRef);
  4364. WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
  4365. WriteFPPragmaOptions(SemaRef.getFPOptions());
  4366. WriteOpenCLExtensions(SemaRef);
  4367. WriteOpenCLExtensionTypes(SemaRef);
  4368. WriteCUDAPragmas(SemaRef);
  4369. // If we're emitting a module, write out the submodule information.
  4370. if (WritingModule)
  4371. WriteSubmodules(WritingModule);
  4372. // We need to have information about submodules to correctly deserialize
  4373. // decls from OpenCLExtensionDecls block
  4374. WriteOpenCLExtensionDecls(SemaRef);
  4375. Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
  4376. // Write the record containing external, unnamed definitions.
  4377. if (!EagerlyDeserializedDecls.empty())
  4378. Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
  4379. if (!ModularCodegenDecls.empty())
  4380. Stream.EmitRecord(MODULAR_CODEGEN_DECLS, ModularCodegenDecls);
  4381. // Write the record containing tentative definitions.
  4382. if (!TentativeDefinitions.empty())
  4383. Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
  4384. // Write the record containing unused file scoped decls.
  4385. if (!UnusedFileScopedDecls.empty())
  4386. Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
  4387. // Write the record containing weak undeclared identifiers.
  4388. if (!WeakUndeclaredIdentifiers.empty())
  4389. Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
  4390. WeakUndeclaredIdentifiers);
  4391. // Write the record containing ext_vector type names.
  4392. if (!ExtVectorDecls.empty())
  4393. Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
  4394. // Write the record containing VTable uses information.
  4395. if (!VTableUses.empty())
  4396. Stream.EmitRecord(VTABLE_USES, VTableUses);
  4397. // Write the record containing potentially unused local typedefs.
  4398. if (!UnusedLocalTypedefNameCandidates.empty())
  4399. Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
  4400. UnusedLocalTypedefNameCandidates);
  4401. // Write the record containing pending implicit instantiations.
  4402. if (!PendingInstantiations.empty())
  4403. Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
  4404. // Write the record containing declaration references of Sema.
  4405. if (!SemaDeclRefs.empty())
  4406. Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
  4407. // Write the record containing CUDA-specific declaration references.
  4408. if (!CUDASpecialDeclRefs.empty())
  4409. Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
  4410. // Write the delegating constructors.
  4411. if (!DelegatingCtorDecls.empty())
  4412. Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
  4413. // Write the known namespaces.
  4414. if (!KnownNamespaces.empty())
  4415. Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
  4416. // Write the undefined internal functions and variables, and inline functions.
  4417. if (!UndefinedButUsed.empty())
  4418. Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
  4419. if (!DeleteExprsToAnalyze.empty())
  4420. Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
  4421. // Write the visible updates to DeclContexts.
  4422. for (auto *DC : UpdatedDeclContexts)
  4423. WriteDeclContextVisibleUpdate(DC);
  4424. if (!WritingModule) {
  4425. // Write the submodules that were imported, if any.
  4426. struct ModuleInfo {
  4427. uint64_t ID;
  4428. Module *M;
  4429. ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
  4430. };
  4431. llvm::SmallVector<ModuleInfo, 64> Imports;
  4432. for (const auto *I : Context.local_imports()) {
  4433. assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
  4434. Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
  4435. I->getImportedModule()));
  4436. }
  4437. if (!Imports.empty()) {
  4438. auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
  4439. return A.ID < B.ID;
  4440. };
  4441. auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
  4442. return A.ID == B.ID;
  4443. };
  4444. // Sort and deduplicate module IDs.
  4445. llvm::sort(Imports, Cmp);
  4446. Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
  4447. Imports.end());
  4448. RecordData ImportedModules;
  4449. for (const auto &Import : Imports) {
  4450. ImportedModules.push_back(Import.ID);
  4451. // FIXME: If the module has macros imported then later has declarations
  4452. // imported, this location won't be the right one as a location for the
  4453. // declaration imports.
  4454. AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
  4455. }
  4456. Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
  4457. }
  4458. }
  4459. WriteObjCCategories();
  4460. if(!WritingModule) {
  4461. WriteOptimizePragmaOptions(SemaRef);
  4462. WriteMSStructPragmaOptions(SemaRef);
  4463. WriteMSPointersToMembersPragmaOptions(SemaRef);
  4464. }
  4465. WritePackPragmaOptions(SemaRef);
  4466. // Some simple statistics
  4467. RecordData::value_type Record[] = {
  4468. NumStatements, NumMacros, NumLexicalDeclContexts, NumVisibleDeclContexts};
  4469. Stream.EmitRecord(STATISTICS, Record);
  4470. Stream.ExitBlock();
  4471. // Write the module file extension blocks.
  4472. for (const auto &ExtWriter : ModuleFileExtensionWriters)
  4473. WriteModuleFileExtension(SemaRef, *ExtWriter);
  4474. return writeUnhashedControlBlock(PP, Context);
  4475. }
  4476. void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
  4477. if (DeclUpdates.empty())
  4478. return;
  4479. DeclUpdateMap LocalUpdates;
  4480. LocalUpdates.swap(DeclUpdates);
  4481. for (auto &DeclUpdate : LocalUpdates) {
  4482. const Decl *D = DeclUpdate.first;
  4483. bool HasUpdatedBody = false;
  4484. RecordData RecordData;
  4485. ASTRecordWriter Record(*this, RecordData);
  4486. for (auto &Update : DeclUpdate.second) {
  4487. DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
  4488. // An updated body is emitted last, so that the reader doesn't need
  4489. // to skip over the lazy body to reach statements for other records.
  4490. if (Kind == UPD_CXX_ADDED_FUNCTION_DEFINITION)
  4491. HasUpdatedBody = true;
  4492. else
  4493. Record.push_back(Kind);
  4494. switch (Kind) {
  4495. case UPD_CXX_ADDED_IMPLICIT_MEMBER:
  4496. case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
  4497. case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
  4498. assert(Update.getDecl() && "no decl to add?");
  4499. Record.push_back(GetDeclRef(Update.getDecl()));
  4500. break;
  4501. case UPD_CXX_ADDED_FUNCTION_DEFINITION:
  4502. break;
  4503. case UPD_CXX_POINT_OF_INSTANTIATION:
  4504. // FIXME: Do we need to also save the template specialization kind here?
  4505. Record.AddSourceLocation(Update.getLoc());
  4506. break;
  4507. case UPD_CXX_ADDED_VAR_DEFINITION: {
  4508. const VarDecl *VD = cast<VarDecl>(D);
  4509. Record.push_back(VD->isInline());
  4510. Record.push_back(VD->isInlineSpecified());
  4511. if (VD->getInit()) {
  4512. Record.push_back(!VD->isInitKnownICE() ? 1
  4513. : (VD->isInitICE() ? 3 : 2));
  4514. Record.AddStmt(const_cast<Expr*>(VD->getInit()));
  4515. } else {
  4516. Record.push_back(0);
  4517. }
  4518. break;
  4519. }
  4520. case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT:
  4521. Record.AddStmt(const_cast<Expr *>(
  4522. cast<ParmVarDecl>(Update.getDecl())->getDefaultArg()));
  4523. break;
  4524. case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER:
  4525. Record.AddStmt(
  4526. cast<FieldDecl>(Update.getDecl())->getInClassInitializer());
  4527. break;
  4528. case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
  4529. auto *RD = cast<CXXRecordDecl>(D);
  4530. UpdatedDeclContexts.insert(RD->getPrimaryContext());
  4531. Record.push_back(RD->isParamDestroyedInCallee());
  4532. Record.push_back(RD->getArgPassingRestrictions());
  4533. Record.AddCXXDefinitionData(RD);
  4534. Record.AddOffset(WriteDeclContextLexicalBlock(
  4535. *Context, const_cast<CXXRecordDecl *>(RD)));
  4536. // This state is sometimes updated by template instantiation, when we
  4537. // switch from the specialization referring to the template declaration
  4538. // to it referring to the template definition.
  4539. if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
  4540. Record.push_back(MSInfo->getTemplateSpecializationKind());
  4541. Record.AddSourceLocation(MSInfo->getPointOfInstantiation());
  4542. } else {
  4543. auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
  4544. Record.push_back(Spec->getTemplateSpecializationKind());
  4545. Record.AddSourceLocation(Spec->getPointOfInstantiation());
  4546. // The instantiation might have been resolved to a partial
  4547. // specialization. If so, record which one.
  4548. auto From = Spec->getInstantiatedFrom();
  4549. if (auto PartialSpec =
  4550. From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
  4551. Record.push_back(true);
  4552. Record.AddDeclRef(PartialSpec);
  4553. Record.AddTemplateArgumentList(
  4554. &Spec->getTemplateInstantiationArgs());
  4555. } else {
  4556. Record.push_back(false);
  4557. }
  4558. }
  4559. Record.push_back(RD->getTagKind());
  4560. Record.AddSourceLocation(RD->getLocation());
  4561. Record.AddSourceLocation(RD->getBeginLoc());
  4562. Record.AddSourceRange(RD->getBraceRange());
  4563. // Instantiation may change attributes; write them all out afresh.
  4564. Record.push_back(D->hasAttrs());
  4565. if (D->hasAttrs())
  4566. Record.AddAttributes(D->getAttrs());
  4567. // FIXME: Ensure we don't get here for explicit instantiations.
  4568. break;
  4569. }
  4570. case UPD_CXX_RESOLVED_DTOR_DELETE:
  4571. Record.AddDeclRef(Update.getDecl());
  4572. Record.AddStmt(cast<CXXDestructorDecl>(D)->getOperatorDeleteThisArg());
  4573. break;
  4574. case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
  4575. addExceptionSpec(
  4576. cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
  4577. Record);
  4578. break;
  4579. case UPD_CXX_DEDUCED_RETURN_TYPE:
  4580. Record.push_back(GetOrCreateTypeID(Update.getType()));
  4581. break;
  4582. case UPD_DECL_MARKED_USED:
  4583. break;
  4584. case UPD_MANGLING_NUMBER:
  4585. case UPD_STATIC_LOCAL_NUMBER:
  4586. Record.push_back(Update.getNumber());
  4587. break;
  4588. case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
  4589. Record.AddSourceRange(
  4590. D->getAttr<OMPThreadPrivateDeclAttr>()->getRange());
  4591. break;
  4592. case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
  4593. auto *A = D->getAttr<OMPAllocateDeclAttr>();
  4594. Record.push_back(A->getAllocatorType());
  4595. Record.AddStmt(A->getAllocator());
  4596. Record.AddSourceRange(A->getRange());
  4597. break;
  4598. }
  4599. case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
  4600. Record.push_back(D->getAttr<OMPDeclareTargetDeclAttr>()->getMapType());
  4601. Record.AddSourceRange(
  4602. D->getAttr<OMPDeclareTargetDeclAttr>()->getRange());
  4603. break;
  4604. case UPD_DECL_EXPORTED:
  4605. Record.push_back(getSubmoduleID(Update.getModule()));
  4606. break;
  4607. case UPD_ADDED_ATTR_TO_RECORD:
  4608. Record.AddAttributes(llvm::makeArrayRef(Update.getAttr()));
  4609. break;
  4610. }
  4611. }
  4612. if (HasUpdatedBody) {
  4613. const auto *Def = cast<FunctionDecl>(D);
  4614. Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
  4615. Record.push_back(Def->isInlined());
  4616. Record.AddSourceLocation(Def->getInnerLocStart());
  4617. Record.AddFunctionDefinition(Def);
  4618. }
  4619. OffsetsRecord.push_back(GetDeclRef(D));
  4620. OffsetsRecord.push_back(Record.Emit(DECL_UPDATES));
  4621. }
  4622. }
  4623. void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
  4624. uint32_t Raw = Loc.getRawEncoding();
  4625. Record.push_back((Raw << 1) | (Raw >> 31));
  4626. }
  4627. void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
  4628. AddSourceLocation(Range.getBegin(), Record);
  4629. AddSourceLocation(Range.getEnd(), Record);
  4630. }
  4631. void ASTRecordWriter::AddAPInt(const llvm::APInt &Value) {
  4632. Record->push_back(Value.getBitWidth());
  4633. const uint64_t *Words = Value.getRawData();
  4634. Record->append(Words, Words + Value.getNumWords());
  4635. }
  4636. void ASTRecordWriter::AddAPSInt(const llvm::APSInt &Value) {
  4637. Record->push_back(Value.isUnsigned());
  4638. AddAPInt(Value);
  4639. }
  4640. void ASTRecordWriter::AddAPFloat(const llvm::APFloat &Value) {
  4641. AddAPInt(Value.bitcastToAPInt());
  4642. }
  4643. static void WriteFixedPointSemantics(ASTRecordWriter &Record,
  4644. FixedPointSemantics FPSema) {
  4645. Record.push_back(FPSema.getWidth());
  4646. Record.push_back(FPSema.getScale());
  4647. Record.push_back(FPSema.isSigned() | FPSema.isSaturated() << 1 |
  4648. FPSema.hasUnsignedPadding() << 2);
  4649. }
  4650. void ASTRecordWriter::AddAPValue(const APValue &Value) {
  4651. APValue::ValueKind Kind = Value.getKind();
  4652. push_back(static_cast<uint64_t>(Kind));
  4653. switch (Kind) {
  4654. case APValue::None:
  4655. case APValue::Indeterminate:
  4656. return;
  4657. case APValue::Int:
  4658. AddAPSInt(Value.getInt());
  4659. return;
  4660. case APValue::Float:
  4661. push_back(static_cast<uint64_t>(
  4662. llvm::APFloatBase::SemanticsToEnum(Value.getFloat().getSemantics())));
  4663. AddAPFloat(Value.getFloat());
  4664. return;
  4665. case APValue::FixedPoint: {
  4666. WriteFixedPointSemantics(*this, Value.getFixedPoint().getSemantics());
  4667. AddAPSInt(Value.getFixedPoint().getValue());
  4668. return;
  4669. }
  4670. case APValue::ComplexInt: {
  4671. AddAPSInt(Value.getComplexIntReal());
  4672. AddAPSInt(Value.getComplexIntImag());
  4673. return;
  4674. }
  4675. case APValue::ComplexFloat: {
  4676. push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
  4677. Value.getComplexFloatReal().getSemantics())));
  4678. AddAPFloat(Value.getComplexFloatReal());
  4679. push_back(static_cast<uint64_t>(llvm::APFloatBase::SemanticsToEnum(
  4680. Value.getComplexFloatImag().getSemantics())));
  4681. AddAPFloat(Value.getComplexFloatImag());
  4682. return;
  4683. }
  4684. case APValue::LValue:
  4685. case APValue::Vector:
  4686. case APValue::Array:
  4687. case APValue::Struct:
  4688. case APValue::Union:
  4689. case APValue::MemberPointer:
  4690. case APValue::AddrLabelDiff:
  4691. // TODO : Handle all these APValue::ValueKind.
  4692. return;
  4693. }
  4694. llvm_unreachable("Invalid APValue::ValueKind");
  4695. }
  4696. void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
  4697. Record.push_back(getIdentifierRef(II));
  4698. }
  4699. IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
  4700. if (!II)
  4701. return 0;
  4702. IdentID &ID = IdentifierIDs[II];
  4703. if (ID == 0)
  4704. ID = NextIdentID++;
  4705. return ID;
  4706. }
  4707. MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
  4708. // Don't emit builtin macros like __LINE__ to the AST file unless they
  4709. // have been redefined by the header (in which case they are not
  4710. // isBuiltinMacro).
  4711. if (!MI || MI->isBuiltinMacro())
  4712. return 0;
  4713. MacroID &ID = MacroIDs[MI];
  4714. if (ID == 0) {
  4715. ID = NextMacroID++;
  4716. MacroInfoToEmitData Info = { Name, MI, ID };
  4717. MacroInfosToEmit.push_back(Info);
  4718. }
  4719. return ID;
  4720. }
  4721. MacroID ASTWriter::getMacroID(MacroInfo *MI) {
  4722. if (!MI || MI->isBuiltinMacro())
  4723. return 0;
  4724. assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
  4725. return MacroIDs[MI];
  4726. }
  4727. uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
  4728. return IdentMacroDirectivesOffsetMap.lookup(Name);
  4729. }
  4730. void ASTRecordWriter::AddSelectorRef(const Selector SelRef) {
  4731. Record->push_back(Writer->getSelectorRef(SelRef));
  4732. }
  4733. SelectorID ASTWriter::getSelectorRef(Selector Sel) {
  4734. if (Sel.getAsOpaquePtr() == nullptr) {
  4735. return 0;
  4736. }
  4737. SelectorID SID = SelectorIDs[Sel];
  4738. if (SID == 0 && Chain) {
  4739. // This might trigger a ReadSelector callback, which will set the ID for
  4740. // this selector.
  4741. Chain->LoadSelector(Sel);
  4742. SID = SelectorIDs[Sel];
  4743. }
  4744. if (SID == 0) {
  4745. SID = NextSelectorID++;
  4746. SelectorIDs[Sel] = SID;
  4747. }
  4748. return SID;
  4749. }
  4750. void ASTRecordWriter::AddCXXTemporary(const CXXTemporary *Temp) {
  4751. AddDeclRef(Temp->getDestructor());
  4752. }
  4753. void ASTRecordWriter::AddTemplateArgumentLocInfo(
  4754. TemplateArgument::ArgKind Kind, const TemplateArgumentLocInfo &Arg) {
  4755. switch (Kind) {
  4756. case TemplateArgument::Expression:
  4757. AddStmt(Arg.getAsExpr());
  4758. break;
  4759. case TemplateArgument::Type:
  4760. AddTypeSourceInfo(Arg.getAsTypeSourceInfo());
  4761. break;
  4762. case TemplateArgument::Template:
  4763. AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
  4764. AddSourceLocation(Arg.getTemplateNameLoc());
  4765. break;
  4766. case TemplateArgument::TemplateExpansion:
  4767. AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc());
  4768. AddSourceLocation(Arg.getTemplateNameLoc());
  4769. AddSourceLocation(Arg.getTemplateEllipsisLoc());
  4770. break;
  4771. case TemplateArgument::Null:
  4772. case TemplateArgument::Integral:
  4773. case TemplateArgument::Declaration:
  4774. case TemplateArgument::NullPtr:
  4775. case TemplateArgument::Pack:
  4776. // FIXME: Is this right?
  4777. break;
  4778. }
  4779. }
  4780. void ASTRecordWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg) {
  4781. AddTemplateArgument(Arg.getArgument());
  4782. if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
  4783. bool InfoHasSameExpr
  4784. = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
  4785. Record->push_back(InfoHasSameExpr);
  4786. if (InfoHasSameExpr)
  4787. return; // Avoid storing the same expr twice.
  4788. }
  4789. AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo());
  4790. }
  4791. void ASTRecordWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo) {
  4792. if (!TInfo) {
  4793. AddTypeRef(QualType());
  4794. return;
  4795. }
  4796. AddTypeRef(TInfo->getType());
  4797. AddTypeLoc(TInfo->getTypeLoc());
  4798. }
  4799. void ASTRecordWriter::AddTypeLoc(TypeLoc TL) {
  4800. TypeLocWriter TLW(*this);
  4801. for (; !TL.isNull(); TL = TL.getNextTypeLoc())
  4802. TLW.Visit(TL);
  4803. }
  4804. void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
  4805. Record.push_back(GetOrCreateTypeID(T));
  4806. }
  4807. TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
  4808. assert(Context);
  4809. return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
  4810. if (T.isNull())
  4811. return TypeIdx();
  4812. assert(!T.getLocalFastQualifiers());
  4813. TypeIdx &Idx = TypeIdxs[T];
  4814. if (Idx.getIndex() == 0) {
  4815. if (DoneWritingDeclsAndTypes) {
  4816. assert(0 && "New type seen after serializing all the types to emit!");
  4817. return TypeIdx();
  4818. }
  4819. // We haven't seen this type before. Assign it a new ID and put it
  4820. // into the queue of types to emit.
  4821. Idx = TypeIdx(NextTypeID++);
  4822. DeclTypesToEmit.push(T);
  4823. }
  4824. return Idx;
  4825. });
  4826. }
  4827. TypeID ASTWriter::getTypeID(QualType T) const {
  4828. assert(Context);
  4829. return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
  4830. if (T.isNull())
  4831. return TypeIdx();
  4832. assert(!T.getLocalFastQualifiers());
  4833. TypeIdxMap::const_iterator I = TypeIdxs.find(T);
  4834. assert(I != TypeIdxs.end() && "Type not emitted!");
  4835. return I->second;
  4836. });
  4837. }
  4838. void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
  4839. Record.push_back(GetDeclRef(D));
  4840. }
  4841. DeclID ASTWriter::GetDeclRef(const Decl *D) {
  4842. assert(WritingAST && "Cannot request a declaration ID before AST writing");
  4843. if (!D) {
  4844. return 0;
  4845. }
  4846. // If D comes from an AST file, its declaration ID is already known and
  4847. // fixed.
  4848. if (D->isFromASTFile())
  4849. return D->getGlobalID();
  4850. assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
  4851. DeclID &ID = DeclIDs[D];
  4852. if (ID == 0) {
  4853. if (DoneWritingDeclsAndTypes) {
  4854. assert(0 && "New decl seen after serializing all the decls to emit!");
  4855. return 0;
  4856. }
  4857. // We haven't seen this declaration before. Give it a new ID and
  4858. // enqueue it in the list of declarations to emit.
  4859. ID = NextDeclID++;
  4860. DeclTypesToEmit.push(const_cast<Decl *>(D));
  4861. }
  4862. return ID;
  4863. }
  4864. DeclID ASTWriter::getDeclID(const Decl *D) {
  4865. if (!D)
  4866. return 0;
  4867. // If D comes from an AST file, its declaration ID is already known and
  4868. // fixed.
  4869. if (D->isFromASTFile())
  4870. return D->getGlobalID();
  4871. assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
  4872. return DeclIDs[D];
  4873. }
  4874. void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
  4875. assert(ID);
  4876. assert(D);
  4877. SourceLocation Loc = D->getLocation();
  4878. if (Loc.isInvalid())
  4879. return;
  4880. // We only keep track of the file-level declarations of each file.
  4881. if (!D->getLexicalDeclContext()->isFileContext())
  4882. return;
  4883. // FIXME: ParmVarDecls that are part of a function type of a parameter of
  4884. // a function/objc method, should not have TU as lexical context.
  4885. // TemplateTemplateParmDecls that are part of an alias template, should not
  4886. // have TU as lexical context.
  4887. if (isa<ParmVarDecl>(D) || isa<TemplateTemplateParmDecl>(D))
  4888. return;
  4889. SourceManager &SM = Context->getSourceManager();
  4890. SourceLocation FileLoc = SM.getFileLoc(Loc);
  4891. assert(SM.isLocalSourceLocation(FileLoc));
  4892. FileID FID;
  4893. unsigned Offset;
  4894. std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
  4895. if (FID.isInvalid())
  4896. return;
  4897. assert(SM.getSLocEntry(FID).isFile());
  4898. DeclIDInFileInfo *&Info = FileDeclIDs[FID];
  4899. if (!Info)
  4900. Info = new DeclIDInFileInfo();
  4901. std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
  4902. LocDeclIDsTy &Decls = Info->DeclIDs;
  4903. if (Decls.empty() || Decls.back().first <= Offset) {
  4904. Decls.push_back(LocDecl);
  4905. return;
  4906. }
  4907. LocDeclIDsTy::iterator I =
  4908. llvm::upper_bound(Decls, LocDecl, llvm::less_first());
  4909. Decls.insert(I, LocDecl);
  4910. }
  4911. void ASTRecordWriter::AddDeclarationName(DeclarationName Name) {
  4912. // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
  4913. Record->push_back(Name.getNameKind());
  4914. switch (Name.getNameKind()) {
  4915. case DeclarationName::Identifier:
  4916. AddIdentifierRef(Name.getAsIdentifierInfo());
  4917. break;
  4918. case DeclarationName::ObjCZeroArgSelector:
  4919. case DeclarationName::ObjCOneArgSelector:
  4920. case DeclarationName::ObjCMultiArgSelector:
  4921. AddSelectorRef(Name.getObjCSelector());
  4922. break;
  4923. case DeclarationName::CXXConstructorName:
  4924. case DeclarationName::CXXDestructorName:
  4925. case DeclarationName::CXXConversionFunctionName:
  4926. AddTypeRef(Name.getCXXNameType());
  4927. break;
  4928. case DeclarationName::CXXDeductionGuideName:
  4929. AddDeclRef(Name.getCXXDeductionGuideTemplate());
  4930. break;
  4931. case DeclarationName::CXXOperatorName:
  4932. Record->push_back(Name.getCXXOverloadedOperator());
  4933. break;
  4934. case DeclarationName::CXXLiteralOperatorName:
  4935. AddIdentifierRef(Name.getCXXLiteralIdentifier());
  4936. break;
  4937. case DeclarationName::CXXUsingDirective:
  4938. // No extra data to emit
  4939. break;
  4940. }
  4941. }
  4942. unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
  4943. assert(needsAnonymousDeclarationNumber(D) &&
  4944. "expected an anonymous declaration");
  4945. // Number the anonymous declarations within this context, if we've not
  4946. // already done so.
  4947. auto It = AnonymousDeclarationNumbers.find(D);
  4948. if (It == AnonymousDeclarationNumbers.end()) {
  4949. auto *DC = D->getLexicalDeclContext();
  4950. numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
  4951. AnonymousDeclarationNumbers[ND] = Number;
  4952. });
  4953. It = AnonymousDeclarationNumbers.find(D);
  4954. assert(It != AnonymousDeclarationNumbers.end() &&
  4955. "declaration not found within its lexical context");
  4956. }
  4957. return It->second;
  4958. }
  4959. void ASTRecordWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
  4960. DeclarationName Name) {
  4961. switch (Name.getNameKind()) {
  4962. case DeclarationName::CXXConstructorName:
  4963. case DeclarationName::CXXDestructorName:
  4964. case DeclarationName::CXXConversionFunctionName:
  4965. AddTypeSourceInfo(DNLoc.NamedType.TInfo);
  4966. break;
  4967. case DeclarationName::CXXOperatorName:
  4968. AddSourceLocation(SourceLocation::getFromRawEncoding(
  4969. DNLoc.CXXOperatorName.BeginOpNameLoc));
  4970. AddSourceLocation(
  4971. SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc));
  4972. break;
  4973. case DeclarationName::CXXLiteralOperatorName:
  4974. AddSourceLocation(SourceLocation::getFromRawEncoding(
  4975. DNLoc.CXXLiteralOperatorName.OpNameLoc));
  4976. break;
  4977. case DeclarationName::Identifier:
  4978. case DeclarationName::ObjCZeroArgSelector:
  4979. case DeclarationName::ObjCOneArgSelector:
  4980. case DeclarationName::ObjCMultiArgSelector:
  4981. case DeclarationName::CXXUsingDirective:
  4982. case DeclarationName::CXXDeductionGuideName:
  4983. break;
  4984. }
  4985. }
  4986. void ASTRecordWriter::AddDeclarationNameInfo(
  4987. const DeclarationNameInfo &NameInfo) {
  4988. AddDeclarationName(NameInfo.getName());
  4989. AddSourceLocation(NameInfo.getLoc());
  4990. AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName());
  4991. }
  4992. void ASTRecordWriter::AddQualifierInfo(const QualifierInfo &Info) {
  4993. AddNestedNameSpecifierLoc(Info.QualifierLoc);
  4994. Record->push_back(Info.NumTemplParamLists);
  4995. for (unsigned i = 0, e = Info.NumTemplParamLists; i != e; ++i)
  4996. AddTemplateParameterList(Info.TemplParamLists[i]);
  4997. }
  4998. void ASTRecordWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS) {
  4999. // Nested name specifiers usually aren't too long. I think that 8 would
  5000. // typically accommodate the vast majority.
  5001. SmallVector<NestedNameSpecifier *, 8> NestedNames;
  5002. // Push each of the NNS's onto a stack for serialization in reverse order.
  5003. while (NNS) {
  5004. NestedNames.push_back(NNS);
  5005. NNS = NNS->getPrefix();
  5006. }
  5007. Record->push_back(NestedNames.size());
  5008. while(!NestedNames.empty()) {
  5009. NNS = NestedNames.pop_back_val();
  5010. NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
  5011. Record->push_back(Kind);
  5012. switch (Kind) {
  5013. case NestedNameSpecifier::Identifier:
  5014. AddIdentifierRef(NNS->getAsIdentifier());
  5015. break;
  5016. case NestedNameSpecifier::Namespace:
  5017. AddDeclRef(NNS->getAsNamespace());
  5018. break;
  5019. case NestedNameSpecifier::NamespaceAlias:
  5020. AddDeclRef(NNS->getAsNamespaceAlias());
  5021. break;
  5022. case NestedNameSpecifier::TypeSpec:
  5023. case NestedNameSpecifier::TypeSpecWithTemplate:
  5024. AddTypeRef(QualType(NNS->getAsType(), 0));
  5025. Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
  5026. break;
  5027. case NestedNameSpecifier::Global:
  5028. // Don't need to write an associated value.
  5029. break;
  5030. case NestedNameSpecifier::Super:
  5031. AddDeclRef(NNS->getAsRecordDecl());
  5032. break;
  5033. }
  5034. }
  5035. }
  5036. void ASTRecordWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS) {
  5037. // Nested name specifiers usually aren't too long. I think that 8 would
  5038. // typically accommodate the vast majority.
  5039. SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
  5040. // Push each of the nested-name-specifiers's onto a stack for
  5041. // serialization in reverse order.
  5042. while (NNS) {
  5043. NestedNames.push_back(NNS);
  5044. NNS = NNS.getPrefix();
  5045. }
  5046. Record->push_back(NestedNames.size());
  5047. while(!NestedNames.empty()) {
  5048. NNS = NestedNames.pop_back_val();
  5049. NestedNameSpecifier::SpecifierKind Kind
  5050. = NNS.getNestedNameSpecifier()->getKind();
  5051. Record->push_back(Kind);
  5052. switch (Kind) {
  5053. case NestedNameSpecifier::Identifier:
  5054. AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier());
  5055. AddSourceRange(NNS.getLocalSourceRange());
  5056. break;
  5057. case NestedNameSpecifier::Namespace:
  5058. AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace());
  5059. AddSourceRange(NNS.getLocalSourceRange());
  5060. break;
  5061. case NestedNameSpecifier::NamespaceAlias:
  5062. AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias());
  5063. AddSourceRange(NNS.getLocalSourceRange());
  5064. break;
  5065. case NestedNameSpecifier::TypeSpec:
  5066. case NestedNameSpecifier::TypeSpecWithTemplate:
  5067. Record->push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
  5068. AddTypeRef(NNS.getTypeLoc().getType());
  5069. AddTypeLoc(NNS.getTypeLoc());
  5070. AddSourceLocation(NNS.getLocalSourceRange().getEnd());
  5071. break;
  5072. case NestedNameSpecifier::Global:
  5073. AddSourceLocation(NNS.getLocalSourceRange().getEnd());
  5074. break;
  5075. case NestedNameSpecifier::Super:
  5076. AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl());
  5077. AddSourceRange(NNS.getLocalSourceRange());
  5078. break;
  5079. }
  5080. }
  5081. }
  5082. void ASTRecordWriter::AddTemplateName(TemplateName Name) {
  5083. TemplateName::NameKind Kind = Name.getKind();
  5084. Record->push_back(Kind);
  5085. switch (Kind) {
  5086. case TemplateName::Template:
  5087. AddDeclRef(Name.getAsTemplateDecl());
  5088. break;
  5089. case TemplateName::OverloadedTemplate: {
  5090. OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
  5091. Record->push_back(OvT->size());
  5092. for (const auto &I : *OvT)
  5093. AddDeclRef(I);
  5094. break;
  5095. }
  5096. case TemplateName::AssumedTemplate: {
  5097. AssumedTemplateStorage *ADLT = Name.getAsAssumedTemplateName();
  5098. AddDeclarationName(ADLT->getDeclName());
  5099. break;
  5100. }
  5101. case TemplateName::QualifiedTemplate: {
  5102. QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
  5103. AddNestedNameSpecifier(QualT->getQualifier());
  5104. Record->push_back(QualT->hasTemplateKeyword());
  5105. AddDeclRef(QualT->getTemplateDecl());
  5106. break;
  5107. }
  5108. case TemplateName::DependentTemplate: {
  5109. DependentTemplateName *DepT = Name.getAsDependentTemplateName();
  5110. AddNestedNameSpecifier(DepT->getQualifier());
  5111. Record->push_back(DepT->isIdentifier());
  5112. if (DepT->isIdentifier())
  5113. AddIdentifierRef(DepT->getIdentifier());
  5114. else
  5115. Record->push_back(DepT->getOperator());
  5116. break;
  5117. }
  5118. case TemplateName::SubstTemplateTemplateParm: {
  5119. SubstTemplateTemplateParmStorage *subst
  5120. = Name.getAsSubstTemplateTemplateParm();
  5121. AddDeclRef(subst->getParameter());
  5122. AddTemplateName(subst->getReplacement());
  5123. break;
  5124. }
  5125. case TemplateName::SubstTemplateTemplateParmPack: {
  5126. SubstTemplateTemplateParmPackStorage *SubstPack
  5127. = Name.getAsSubstTemplateTemplateParmPack();
  5128. AddDeclRef(SubstPack->getParameterPack());
  5129. AddTemplateArgument(SubstPack->getArgumentPack());
  5130. break;
  5131. }
  5132. }
  5133. }
  5134. void ASTRecordWriter::AddTemplateArgument(const TemplateArgument &Arg) {
  5135. Record->push_back(Arg.getKind());
  5136. switch (Arg.getKind()) {
  5137. case TemplateArgument::Null:
  5138. break;
  5139. case TemplateArgument::Type:
  5140. AddTypeRef(Arg.getAsType());
  5141. break;
  5142. case TemplateArgument::Declaration:
  5143. AddDeclRef(Arg.getAsDecl());
  5144. AddTypeRef(Arg.getParamTypeForDecl());
  5145. break;
  5146. case TemplateArgument::NullPtr:
  5147. AddTypeRef(Arg.getNullPtrType());
  5148. break;
  5149. case TemplateArgument::Integral:
  5150. AddAPSInt(Arg.getAsIntegral());
  5151. AddTypeRef(Arg.getIntegralType());
  5152. break;
  5153. case TemplateArgument::Template:
  5154. AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
  5155. break;
  5156. case TemplateArgument::TemplateExpansion:
  5157. AddTemplateName(Arg.getAsTemplateOrTemplatePattern());
  5158. if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
  5159. Record->push_back(*NumExpansions + 1);
  5160. else
  5161. Record->push_back(0);
  5162. break;
  5163. case TemplateArgument::Expression:
  5164. AddStmt(Arg.getAsExpr());
  5165. break;
  5166. case TemplateArgument::Pack:
  5167. Record->push_back(Arg.pack_size());
  5168. for (const auto &P : Arg.pack_elements())
  5169. AddTemplateArgument(P);
  5170. break;
  5171. }
  5172. }
  5173. void ASTRecordWriter::AddTemplateParameterList(
  5174. const TemplateParameterList *TemplateParams) {
  5175. assert(TemplateParams && "No TemplateParams!");
  5176. AddSourceLocation(TemplateParams->getTemplateLoc());
  5177. AddSourceLocation(TemplateParams->getLAngleLoc());
  5178. AddSourceLocation(TemplateParams->getRAngleLoc());
  5179. // TODO: Concepts
  5180. Record->push_back(TemplateParams->size());
  5181. for (const auto &P : *TemplateParams)
  5182. AddDeclRef(P);
  5183. }
  5184. /// Emit a template argument list.
  5185. void ASTRecordWriter::AddTemplateArgumentList(
  5186. const TemplateArgumentList *TemplateArgs) {
  5187. assert(TemplateArgs && "No TemplateArgs!");
  5188. Record->push_back(TemplateArgs->size());
  5189. for (int i = 0, e = TemplateArgs->size(); i != e; ++i)
  5190. AddTemplateArgument(TemplateArgs->get(i));
  5191. }
  5192. void ASTRecordWriter::AddASTTemplateArgumentListInfo(
  5193. const ASTTemplateArgumentListInfo *ASTTemplArgList) {
  5194. assert(ASTTemplArgList && "No ASTTemplArgList!");
  5195. AddSourceLocation(ASTTemplArgList->LAngleLoc);
  5196. AddSourceLocation(ASTTemplArgList->RAngleLoc);
  5197. Record->push_back(ASTTemplArgList->NumTemplateArgs);
  5198. const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
  5199. for (int i = 0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
  5200. AddTemplateArgumentLoc(TemplArgs[i]);
  5201. }
  5202. void ASTRecordWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set) {
  5203. Record->push_back(Set.size());
  5204. for (ASTUnresolvedSet::const_iterator
  5205. I = Set.begin(), E = Set.end(); I != E; ++I) {
  5206. AddDeclRef(I.getDecl());
  5207. Record->push_back(I.getAccess());
  5208. }
  5209. }
  5210. // FIXME: Move this out of the main ASTRecordWriter interface.
  5211. void ASTRecordWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
  5212. Record->push_back(Base.isVirtual());
  5213. Record->push_back(Base.isBaseOfClass());
  5214. Record->push_back(Base.getAccessSpecifierAsWritten());
  5215. Record->push_back(Base.getInheritConstructors());
  5216. AddTypeSourceInfo(Base.getTypeSourceInfo());
  5217. AddSourceRange(Base.getSourceRange());
  5218. AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
  5219. : SourceLocation());
  5220. }
  5221. static uint64_t EmitCXXBaseSpecifiers(ASTWriter &W,
  5222. ArrayRef<CXXBaseSpecifier> Bases) {
  5223. ASTWriter::RecordData Record;
  5224. ASTRecordWriter Writer(W, Record);
  5225. Writer.push_back(Bases.size());
  5226. for (auto &Base : Bases)
  5227. Writer.AddCXXBaseSpecifier(Base);
  5228. return Writer.Emit(serialization::DECL_CXX_BASE_SPECIFIERS);
  5229. }
  5230. // FIXME: Move this out of the main ASTRecordWriter interface.
  5231. void ASTRecordWriter::AddCXXBaseSpecifiers(ArrayRef<CXXBaseSpecifier> Bases) {
  5232. AddOffset(EmitCXXBaseSpecifiers(*Writer, Bases));
  5233. }
  5234. static uint64_t
  5235. EmitCXXCtorInitializers(ASTWriter &W,
  5236. ArrayRef<CXXCtorInitializer *> CtorInits) {
  5237. ASTWriter::RecordData Record;
  5238. ASTRecordWriter Writer(W, Record);
  5239. Writer.push_back(CtorInits.size());
  5240. for (auto *Init : CtorInits) {
  5241. if (Init->isBaseInitializer()) {
  5242. Writer.push_back(CTOR_INITIALIZER_BASE);
  5243. Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
  5244. Writer.push_back(Init->isBaseVirtual());
  5245. } else if (Init->isDelegatingInitializer()) {
  5246. Writer.push_back(CTOR_INITIALIZER_DELEGATING);
  5247. Writer.AddTypeSourceInfo(Init->getTypeSourceInfo());
  5248. } else if (Init->isMemberInitializer()){
  5249. Writer.push_back(CTOR_INITIALIZER_MEMBER);
  5250. Writer.AddDeclRef(Init->getMember());
  5251. } else {
  5252. Writer.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
  5253. Writer.AddDeclRef(Init->getIndirectMember());
  5254. }
  5255. Writer.AddSourceLocation(Init->getMemberLocation());
  5256. Writer.AddStmt(Init->getInit());
  5257. Writer.AddSourceLocation(Init->getLParenLoc());
  5258. Writer.AddSourceLocation(Init->getRParenLoc());
  5259. Writer.push_back(Init->isWritten());
  5260. if (Init->isWritten())
  5261. Writer.push_back(Init->getSourceOrder());
  5262. }
  5263. return Writer.Emit(serialization::DECL_CXX_CTOR_INITIALIZERS);
  5264. }
  5265. // FIXME: Move this out of the main ASTRecordWriter interface.
  5266. void ASTRecordWriter::AddCXXCtorInitializers(
  5267. ArrayRef<CXXCtorInitializer *> CtorInits) {
  5268. AddOffset(EmitCXXCtorInitializers(*Writer, CtorInits));
  5269. }
  5270. void ASTRecordWriter::AddCXXDefinitionData(const CXXRecordDecl *D) {
  5271. auto &Data = D->data();
  5272. Record->push_back(Data.IsLambda);
  5273. Record->push_back(Data.UserDeclaredConstructor);
  5274. Record->push_back(Data.UserDeclaredSpecialMembers);
  5275. Record->push_back(Data.Aggregate);
  5276. Record->push_back(Data.PlainOldData);
  5277. Record->push_back(Data.Empty);
  5278. Record->push_back(Data.Polymorphic);
  5279. Record->push_back(Data.Abstract);
  5280. Record->push_back(Data.IsStandardLayout);
  5281. Record->push_back(Data.IsCXX11StandardLayout);
  5282. Record->push_back(Data.HasBasesWithFields);
  5283. Record->push_back(Data.HasBasesWithNonStaticDataMembers);
  5284. Record->push_back(Data.HasPrivateFields);
  5285. Record->push_back(Data.HasProtectedFields);
  5286. Record->push_back(Data.HasPublicFields);
  5287. Record->push_back(Data.HasMutableFields);
  5288. Record->push_back(Data.HasVariantMembers);
  5289. Record->push_back(Data.HasOnlyCMembers);
  5290. Record->push_back(Data.HasInClassInitializer);
  5291. Record->push_back(Data.HasUninitializedReferenceMember);
  5292. Record->push_back(Data.HasUninitializedFields);
  5293. Record->push_back(Data.HasInheritedConstructor);
  5294. Record->push_back(Data.HasInheritedAssignment);
  5295. Record->push_back(Data.NeedOverloadResolutionForCopyConstructor);
  5296. Record->push_back(Data.NeedOverloadResolutionForMoveConstructor);
  5297. Record->push_back(Data.NeedOverloadResolutionForMoveAssignment);
  5298. Record->push_back(Data.NeedOverloadResolutionForDestructor);
  5299. Record->push_back(Data.DefaultedCopyConstructorIsDeleted);
  5300. Record->push_back(Data.DefaultedMoveConstructorIsDeleted);
  5301. Record->push_back(Data.DefaultedMoveAssignmentIsDeleted);
  5302. Record->push_back(Data.DefaultedDestructorIsDeleted);
  5303. Record->push_back(Data.HasTrivialSpecialMembers);
  5304. Record->push_back(Data.HasTrivialSpecialMembersForCall);
  5305. Record->push_back(Data.DeclaredNonTrivialSpecialMembers);
  5306. Record->push_back(Data.DeclaredNonTrivialSpecialMembersForCall);
  5307. Record->push_back(Data.HasIrrelevantDestructor);
  5308. Record->push_back(Data.HasConstexprNonCopyMoveConstructor);
  5309. Record->push_back(Data.HasDefaultedDefaultConstructor);
  5310. Record->push_back(Data.DefaultedDefaultConstructorIsConstexpr);
  5311. Record->push_back(Data.HasConstexprDefaultConstructor);
  5312. Record->push_back(Data.HasNonLiteralTypeFieldsOrBases);
  5313. Record->push_back(Data.ComputedVisibleConversions);
  5314. Record->push_back(Data.UserProvidedDefaultConstructor);
  5315. Record->push_back(Data.DeclaredSpecialMembers);
  5316. Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForVBase);
  5317. Record->push_back(Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase);
  5318. Record->push_back(Data.ImplicitCopyAssignmentHasConstParam);
  5319. Record->push_back(Data.HasDeclaredCopyConstructorWithConstParam);
  5320. Record->push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
  5321. // getODRHash will compute the ODRHash if it has not been previously computed.
  5322. Record->push_back(D->getODRHash());
  5323. bool ModulesDebugInfo = Writer->Context->getLangOpts().ModulesDebugInfo &&
  5324. Writer->WritingModule && !D->isDependentType();
  5325. Record->push_back(ModulesDebugInfo);
  5326. if (ModulesDebugInfo)
  5327. Writer->ModularCodegenDecls.push_back(Writer->GetDeclRef(D));
  5328. // IsLambda bit is already saved.
  5329. Record->push_back(Data.NumBases);
  5330. if (Data.NumBases > 0)
  5331. AddCXXBaseSpecifiers(Data.bases());
  5332. // FIXME: Make VBases lazily computed when needed to avoid storing them.
  5333. Record->push_back(Data.NumVBases);
  5334. if (Data.NumVBases > 0)
  5335. AddCXXBaseSpecifiers(Data.vbases());
  5336. AddUnresolvedSet(Data.Conversions.get(*Writer->Context));
  5337. AddUnresolvedSet(Data.VisibleConversions.get(*Writer->Context));
  5338. // Data.Definition is the owning decl, no need to write it.
  5339. AddDeclRef(D->getFirstFriend());
  5340. // Add lambda-specific data.
  5341. if (Data.IsLambda) {
  5342. auto &Lambda = D->getLambdaData();
  5343. Record->push_back(Lambda.Dependent);
  5344. Record->push_back(Lambda.IsGenericLambda);
  5345. Record->push_back(Lambda.CaptureDefault);
  5346. Record->push_back(Lambda.NumCaptures);
  5347. Record->push_back(Lambda.NumExplicitCaptures);
  5348. Record->push_back(Lambda.ManglingNumber);
  5349. AddDeclRef(D->getLambdaContextDecl());
  5350. AddTypeSourceInfo(Lambda.MethodTyInfo);
  5351. for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
  5352. const LambdaCapture &Capture = Lambda.Captures[I];
  5353. AddSourceLocation(Capture.getLocation());
  5354. Record->push_back(Capture.isImplicit());
  5355. Record->push_back(Capture.getCaptureKind());
  5356. switch (Capture.getCaptureKind()) {
  5357. case LCK_StarThis:
  5358. case LCK_This:
  5359. case LCK_VLAType:
  5360. break;
  5361. case LCK_ByCopy:
  5362. case LCK_ByRef:
  5363. VarDecl *Var =
  5364. Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
  5365. AddDeclRef(Var);
  5366. AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
  5367. : SourceLocation());
  5368. break;
  5369. }
  5370. }
  5371. }
  5372. }
  5373. void ASTWriter::ReaderInitialized(ASTReader *Reader) {
  5374. assert(Reader && "Cannot remove chain");
  5375. assert((!Chain || Chain == Reader) && "Cannot replace chain");
  5376. assert(FirstDeclID == NextDeclID &&
  5377. FirstTypeID == NextTypeID &&
  5378. FirstIdentID == NextIdentID &&
  5379. FirstMacroID == NextMacroID &&
  5380. FirstSubmoduleID == NextSubmoduleID &&
  5381. FirstSelectorID == NextSelectorID &&
  5382. "Setting chain after writing has started.");
  5383. Chain = Reader;
  5384. // Note, this will get called multiple times, once one the reader starts up
  5385. // and again each time it's done reading a PCH or module.
  5386. FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
  5387. FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
  5388. FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
  5389. FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
  5390. FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
  5391. FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
  5392. NextDeclID = FirstDeclID;
  5393. NextTypeID = FirstTypeID;
  5394. NextIdentID = FirstIdentID;
  5395. NextMacroID = FirstMacroID;
  5396. NextSelectorID = FirstSelectorID;
  5397. NextSubmoduleID = FirstSubmoduleID;
  5398. }
  5399. void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
  5400. // Always keep the highest ID. See \p TypeRead() for more information.
  5401. IdentID &StoredID = IdentifierIDs[II];
  5402. if (ID > StoredID)
  5403. StoredID = ID;
  5404. }
  5405. void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
  5406. // Always keep the highest ID. See \p TypeRead() for more information.
  5407. MacroID &StoredID = MacroIDs[MI];
  5408. if (ID > StoredID)
  5409. StoredID = ID;
  5410. }
  5411. void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
  5412. // Always take the highest-numbered type index. This copes with an interesting
  5413. // case for chained AST writing where we schedule writing the type and then,
  5414. // later, deserialize the type from another AST. In this case, we want to
  5415. // keep the higher-numbered entry so that we can properly write it out to
  5416. // the AST file.
  5417. TypeIdx &StoredIdx = TypeIdxs[T];
  5418. if (Idx.getIndex() >= StoredIdx.getIndex())
  5419. StoredIdx = Idx;
  5420. }
  5421. void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
  5422. // Always keep the highest ID. See \p TypeRead() for more information.
  5423. SelectorID &StoredID = SelectorIDs[S];
  5424. if (ID > StoredID)
  5425. StoredID = ID;
  5426. }
  5427. void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
  5428. MacroDefinitionRecord *MD) {
  5429. assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
  5430. MacroDefinitions[MD] = ID;
  5431. }
  5432. void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
  5433. assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
  5434. SubmoduleIDs[Mod] = ID;
  5435. }
  5436. void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
  5437. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5438. assert(D->isCompleteDefinition());
  5439. assert(!WritingAST && "Already writing the AST!");
  5440. if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
  5441. // We are interested when a PCH decl is modified.
  5442. if (RD->isFromASTFile()) {
  5443. // A forward reference was mutated into a definition. Rewrite it.
  5444. // FIXME: This happens during template instantiation, should we
  5445. // have created a new definition decl instead ?
  5446. assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
  5447. "completed a tag from another module but not by instantiation?");
  5448. DeclUpdates[RD].push_back(
  5449. DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
  5450. }
  5451. }
  5452. }
  5453. static bool isImportedDeclContext(ASTReader *Chain, const Decl *D) {
  5454. if (D->isFromASTFile())
  5455. return true;
  5456. // The predefined __va_list_tag struct is imported if we imported any decls.
  5457. // FIXME: This is a gross hack.
  5458. return D == D->getASTContext().getVaListTagDecl();
  5459. }
  5460. void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
  5461. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5462. assert(DC->isLookupContext() &&
  5463. "Should not add lookup results to non-lookup contexts!");
  5464. // TU is handled elsewhere.
  5465. if (isa<TranslationUnitDecl>(DC))
  5466. return;
  5467. // Namespaces are handled elsewhere, except for template instantiations of
  5468. // FunctionTemplateDecls in namespaces. We are interested in cases where the
  5469. // local instantiations are added to an imported context. Only happens when
  5470. // adding ADL lookup candidates, for example templated friends.
  5471. if (isa<NamespaceDecl>(DC) && D->getFriendObjectKind() == Decl::FOK_None &&
  5472. !isa<FunctionTemplateDecl>(D))
  5473. return;
  5474. // We're only interested in cases where a local declaration is added to an
  5475. // imported context.
  5476. if (D->isFromASTFile() || !isImportedDeclContext(Chain, cast<Decl>(DC)))
  5477. return;
  5478. assert(DC == DC->getPrimaryContext() && "added to non-primary context");
  5479. assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
  5480. assert(!WritingAST && "Already writing the AST!");
  5481. if (UpdatedDeclContexts.insert(DC) && !cast<Decl>(DC)->isFromASTFile()) {
  5482. // We're adding a visible declaration to a predefined decl context. Ensure
  5483. // that we write out all of its lookup results so we don't get a nasty
  5484. // surprise when we try to emit its lookup table.
  5485. for (auto *Child : DC->decls())
  5486. DeclsToEmitEvenIfUnreferenced.push_back(Child);
  5487. }
  5488. DeclsToEmitEvenIfUnreferenced.push_back(D);
  5489. }
  5490. void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
  5491. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5492. assert(D->isImplicit());
  5493. // We're only interested in cases where a local declaration is added to an
  5494. // imported context.
  5495. if (D->isFromASTFile() || !isImportedDeclContext(Chain, RD))
  5496. return;
  5497. if (!isa<CXXMethodDecl>(D))
  5498. return;
  5499. // A decl coming from PCH was modified.
  5500. assert(RD->isCompleteDefinition());
  5501. assert(!WritingAST && "Already writing the AST!");
  5502. DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
  5503. }
  5504. void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
  5505. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5506. assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
  5507. if (!Chain) return;
  5508. Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
  5509. // If we don't already know the exception specification for this redecl
  5510. // chain, add an update record for it.
  5511. if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
  5512. ->getType()
  5513. ->castAs<FunctionProtoType>()
  5514. ->getExceptionSpecType()))
  5515. DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
  5516. });
  5517. }
  5518. void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
  5519. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5520. assert(!WritingAST && "Already writing the AST!");
  5521. if (!Chain) return;
  5522. Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
  5523. DeclUpdates[D].push_back(
  5524. DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
  5525. });
  5526. }
  5527. void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
  5528. const FunctionDecl *Delete,
  5529. Expr *ThisArg) {
  5530. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5531. assert(!WritingAST && "Already writing the AST!");
  5532. assert(Delete && "Not given an operator delete");
  5533. if (!Chain) return;
  5534. Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
  5535. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
  5536. });
  5537. }
  5538. void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
  5539. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5540. assert(!WritingAST && "Already writing the AST!");
  5541. if (!D->isFromASTFile())
  5542. return; // Declaration not imported from PCH.
  5543. // Implicit function decl from a PCH was defined.
  5544. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
  5545. }
  5546. void ASTWriter::VariableDefinitionInstantiated(const VarDecl *D) {
  5547. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5548. assert(!WritingAST && "Already writing the AST!");
  5549. if (!D->isFromASTFile())
  5550. return;
  5551. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_VAR_DEFINITION));
  5552. }
  5553. void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
  5554. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5555. assert(!WritingAST && "Already writing the AST!");
  5556. if (!D->isFromASTFile())
  5557. return;
  5558. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
  5559. }
  5560. void ASTWriter::InstantiationRequested(const ValueDecl *D) {
  5561. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5562. assert(!WritingAST && "Already writing the AST!");
  5563. if (!D->isFromASTFile())
  5564. return;
  5565. // Since the actual instantiation is delayed, this really means that we need
  5566. // to update the instantiation location.
  5567. SourceLocation POI;
  5568. if (auto *VD = dyn_cast<VarDecl>(D))
  5569. POI = VD->getPointOfInstantiation();
  5570. else
  5571. POI = cast<FunctionDecl>(D)->getPointOfInstantiation();
  5572. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_POINT_OF_INSTANTIATION, POI));
  5573. }
  5574. void ASTWriter::DefaultArgumentInstantiated(const ParmVarDecl *D) {
  5575. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5576. assert(!WritingAST && "Already writing the AST!");
  5577. if (!D->isFromASTFile())
  5578. return;
  5579. DeclUpdates[D].push_back(
  5580. DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT, D));
  5581. }
  5582. void ASTWriter::DefaultMemberInitializerInstantiated(const FieldDecl *D) {
  5583. assert(!WritingAST && "Already writing the AST!");
  5584. if (!D->isFromASTFile())
  5585. return;
  5586. DeclUpdates[D].push_back(
  5587. DeclUpdate(UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER, D));
  5588. }
  5589. void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
  5590. const ObjCInterfaceDecl *IFD) {
  5591. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5592. assert(!WritingAST && "Already writing the AST!");
  5593. if (!IFD->isFromASTFile())
  5594. return; // Declaration not imported from PCH.
  5595. assert(IFD->getDefinition() && "Category on a class without a definition?");
  5596. ObjCClassesWithCategories.insert(
  5597. const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
  5598. }
  5599. void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
  5600. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5601. assert(!WritingAST && "Already writing the AST!");
  5602. // If there is *any* declaration of the entity that's not from an AST file,
  5603. // we can skip writing the update record. We make sure that isUsed() triggers
  5604. // completion of the redeclaration chain of the entity.
  5605. for (auto Prev = D->getMostRecentDecl(); Prev; Prev = Prev->getPreviousDecl())
  5606. if (IsLocalDecl(Prev))
  5607. return;
  5608. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
  5609. }
  5610. void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
  5611. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5612. assert(!WritingAST && "Already writing the AST!");
  5613. if (!D->isFromASTFile())
  5614. return;
  5615. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
  5616. }
  5617. void ASTWriter::DeclarationMarkedOpenMPAllocate(const Decl *D, const Attr *A) {
  5618. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5619. assert(!WritingAST && "Already writing the AST!");
  5620. if (!D->isFromASTFile())
  5621. return;
  5622. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_ALLOCATE, A));
  5623. }
  5624. void ASTWriter::DeclarationMarkedOpenMPDeclareTarget(const Decl *D,
  5625. const Attr *Attr) {
  5626. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5627. assert(!WritingAST && "Already writing the AST!");
  5628. if (!D->isFromASTFile())
  5629. return;
  5630. DeclUpdates[D].push_back(
  5631. DeclUpdate(UPD_DECL_MARKED_OPENMP_DECLARETARGET, Attr));
  5632. }
  5633. void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
  5634. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5635. assert(!WritingAST && "Already writing the AST!");
  5636. assert(D->isHidden() && "expected a hidden declaration");
  5637. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
  5638. }
  5639. void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
  5640. const RecordDecl *Record) {
  5641. if (Chain && Chain->isProcessingUpdateRecords()) return;
  5642. assert(!WritingAST && "Already writing the AST!");
  5643. if (!Record->isFromASTFile())
  5644. return;
  5645. DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
  5646. }
  5647. void ASTWriter::AddedCXXTemplateSpecialization(
  5648. const ClassTemplateDecl *TD, const ClassTemplateSpecializationDecl *D) {
  5649. assert(!WritingAST && "Already writing the AST!");
  5650. if (!TD->getFirstDecl()->isFromASTFile())
  5651. return;
  5652. if (Chain && Chain->isProcessingUpdateRecords())
  5653. return;
  5654. DeclsToEmitEvenIfUnreferenced.push_back(D);
  5655. }
  5656. void ASTWriter::AddedCXXTemplateSpecialization(
  5657. const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
  5658. assert(!WritingAST && "Already writing the AST!");
  5659. if (!TD->getFirstDecl()->isFromASTFile())
  5660. return;
  5661. if (Chain && Chain->isProcessingUpdateRecords())
  5662. return;
  5663. DeclsToEmitEvenIfUnreferenced.push_back(D);
  5664. }
  5665. void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
  5666. const FunctionDecl *D) {
  5667. assert(!WritingAST && "Already writing the AST!");
  5668. if (!TD->getFirstDecl()->isFromASTFile())
  5669. return;
  5670. if (Chain && Chain->isProcessingUpdateRecords())
  5671. return;
  5672. DeclsToEmitEvenIfUnreferenced.push_back(D);
  5673. }
  5674. //===----------------------------------------------------------------------===//
  5675. //// OMPClause Serialization
  5676. ////===----------------------------------------------------------------------===//
  5677. void OMPClauseWriter::writeClause(OMPClause *C) {
  5678. Record.push_back(C->getClauseKind());
  5679. Visit(C);
  5680. Record.AddSourceLocation(C->getBeginLoc());
  5681. Record.AddSourceLocation(C->getEndLoc());
  5682. }
  5683. void OMPClauseWriter::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
  5684. Record.push_back(C->getCaptureRegion());
  5685. Record.AddStmt(C->getPreInitStmt());
  5686. }
  5687. void OMPClauseWriter::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
  5688. VisitOMPClauseWithPreInit(C);
  5689. Record.AddStmt(C->getPostUpdateExpr());
  5690. }
  5691. void OMPClauseWriter::VisitOMPIfClause(OMPIfClause *C) {
  5692. VisitOMPClauseWithPreInit(C);
  5693. Record.push_back(C->getNameModifier());
  5694. Record.AddSourceLocation(C->getNameModifierLoc());
  5695. Record.AddSourceLocation(C->getColonLoc());
  5696. Record.AddStmt(C->getCondition());
  5697. Record.AddSourceLocation(C->getLParenLoc());
  5698. }
  5699. void OMPClauseWriter::VisitOMPFinalClause(OMPFinalClause *C) {
  5700. Record.AddStmt(C->getCondition());
  5701. Record.AddSourceLocation(C->getLParenLoc());
  5702. }
  5703. void OMPClauseWriter::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
  5704. VisitOMPClauseWithPreInit(C);
  5705. Record.AddStmt(C->getNumThreads());
  5706. Record.AddSourceLocation(C->getLParenLoc());
  5707. }
  5708. void OMPClauseWriter::VisitOMPSafelenClause(OMPSafelenClause *C) {
  5709. Record.AddStmt(C->getSafelen());
  5710. Record.AddSourceLocation(C->getLParenLoc());
  5711. }
  5712. void OMPClauseWriter::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
  5713. Record.AddStmt(C->getSimdlen());
  5714. Record.AddSourceLocation(C->getLParenLoc());
  5715. }
  5716. void OMPClauseWriter::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
  5717. Record.AddStmt(C->getAllocator());
  5718. Record.AddSourceLocation(C->getLParenLoc());
  5719. }
  5720. void OMPClauseWriter::VisitOMPCollapseClause(OMPCollapseClause *C) {
  5721. Record.AddStmt(C->getNumForLoops());
  5722. Record.AddSourceLocation(C->getLParenLoc());
  5723. }
  5724. void OMPClauseWriter::VisitOMPDefaultClause(OMPDefaultClause *C) {
  5725. Record.push_back(C->getDefaultKind());
  5726. Record.AddSourceLocation(C->getLParenLoc());
  5727. Record.AddSourceLocation(C->getDefaultKindKwLoc());
  5728. }
  5729. void OMPClauseWriter::VisitOMPProcBindClause(OMPProcBindClause *C) {
  5730. Record.push_back(C->getProcBindKind());
  5731. Record.AddSourceLocation(C->getLParenLoc());
  5732. Record.AddSourceLocation(C->getProcBindKindKwLoc());
  5733. }
  5734. void OMPClauseWriter::VisitOMPScheduleClause(OMPScheduleClause *C) {
  5735. VisitOMPClauseWithPreInit(C);
  5736. Record.push_back(C->getScheduleKind());
  5737. Record.push_back(C->getFirstScheduleModifier());
  5738. Record.push_back(C->getSecondScheduleModifier());
  5739. Record.AddStmt(C->getChunkSize());
  5740. Record.AddSourceLocation(C->getLParenLoc());
  5741. Record.AddSourceLocation(C->getFirstScheduleModifierLoc());
  5742. Record.AddSourceLocation(C->getSecondScheduleModifierLoc());
  5743. Record.AddSourceLocation(C->getScheduleKindLoc());
  5744. Record.AddSourceLocation(C->getCommaLoc());
  5745. }
  5746. void OMPClauseWriter::VisitOMPOrderedClause(OMPOrderedClause *C) {
  5747. Record.push_back(C->getLoopNumIterations().size());
  5748. Record.AddStmt(C->getNumForLoops());
  5749. for (Expr *NumIter : C->getLoopNumIterations())
  5750. Record.AddStmt(NumIter);
  5751. for (unsigned I = 0, E = C->getLoopNumIterations().size(); I <E; ++I)
  5752. Record.AddStmt(C->getLoopCounter(I));
  5753. Record.AddSourceLocation(C->getLParenLoc());
  5754. }
  5755. void OMPClauseWriter::VisitOMPNowaitClause(OMPNowaitClause *) {}
  5756. void OMPClauseWriter::VisitOMPUntiedClause(OMPUntiedClause *) {}
  5757. void OMPClauseWriter::VisitOMPMergeableClause(OMPMergeableClause *) {}
  5758. void OMPClauseWriter::VisitOMPReadClause(OMPReadClause *) {}
  5759. void OMPClauseWriter::VisitOMPWriteClause(OMPWriteClause *) {}
  5760. void OMPClauseWriter::VisitOMPUpdateClause(OMPUpdateClause *) {}
  5761. void OMPClauseWriter::VisitOMPCaptureClause(OMPCaptureClause *) {}
  5762. void OMPClauseWriter::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
  5763. void OMPClauseWriter::VisitOMPThreadsClause(OMPThreadsClause *) {}
  5764. void OMPClauseWriter::VisitOMPSIMDClause(OMPSIMDClause *) {}
  5765. void OMPClauseWriter::VisitOMPNogroupClause(OMPNogroupClause *) {}
  5766. void OMPClauseWriter::VisitOMPPrivateClause(OMPPrivateClause *C) {
  5767. Record.push_back(C->varlist_size());
  5768. Record.AddSourceLocation(C->getLParenLoc());
  5769. for (auto *VE : C->varlists()) {
  5770. Record.AddStmt(VE);
  5771. }
  5772. for (auto *VE : C->private_copies()) {
  5773. Record.AddStmt(VE);
  5774. }
  5775. }
  5776. void OMPClauseWriter::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
  5777. Record.push_back(C->varlist_size());
  5778. VisitOMPClauseWithPreInit(C);
  5779. Record.AddSourceLocation(C->getLParenLoc());
  5780. for (auto *VE : C->varlists()) {
  5781. Record.AddStmt(VE);
  5782. }
  5783. for (auto *VE : C->private_copies()) {
  5784. Record.AddStmt(VE);
  5785. }
  5786. for (auto *VE : C->inits()) {
  5787. Record.AddStmt(VE);
  5788. }
  5789. }
  5790. void OMPClauseWriter::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
  5791. Record.push_back(C->varlist_size());
  5792. VisitOMPClauseWithPostUpdate(C);
  5793. Record.AddSourceLocation(C->getLParenLoc());
  5794. for (auto *VE : C->varlists())
  5795. Record.AddStmt(VE);
  5796. for (auto *E : C->private_copies())
  5797. Record.AddStmt(E);
  5798. for (auto *E : C->source_exprs())
  5799. Record.AddStmt(E);
  5800. for (auto *E : C->destination_exprs())
  5801. Record.AddStmt(E);
  5802. for (auto *E : C->assignment_ops())
  5803. Record.AddStmt(E);
  5804. }
  5805. void OMPClauseWriter::VisitOMPSharedClause(OMPSharedClause *C) {
  5806. Record.push_back(C->varlist_size());
  5807. Record.AddSourceLocation(C->getLParenLoc());
  5808. for (auto *VE : C->varlists())
  5809. Record.AddStmt(VE);
  5810. }
  5811. void OMPClauseWriter::VisitOMPReductionClause(OMPReductionClause *C) {
  5812. Record.push_back(C->varlist_size());
  5813. VisitOMPClauseWithPostUpdate(C);
  5814. Record.AddSourceLocation(C->getLParenLoc());
  5815. Record.AddSourceLocation(C->getColonLoc());
  5816. Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
  5817. Record.AddDeclarationNameInfo(C->getNameInfo());
  5818. for (auto *VE : C->varlists())
  5819. Record.AddStmt(VE);
  5820. for (auto *VE : C->privates())
  5821. Record.AddStmt(VE);
  5822. for (auto *E : C->lhs_exprs())
  5823. Record.AddStmt(E);
  5824. for (auto *E : C->rhs_exprs())
  5825. Record.AddStmt(E);
  5826. for (auto *E : C->reduction_ops())
  5827. Record.AddStmt(E);
  5828. }
  5829. void OMPClauseWriter::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
  5830. Record.push_back(C->varlist_size());
  5831. VisitOMPClauseWithPostUpdate(C);
  5832. Record.AddSourceLocation(C->getLParenLoc());
  5833. Record.AddSourceLocation(C->getColonLoc());
  5834. Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
  5835. Record.AddDeclarationNameInfo(C->getNameInfo());
  5836. for (auto *VE : C->varlists())
  5837. Record.AddStmt(VE);
  5838. for (auto *VE : C->privates())
  5839. Record.AddStmt(VE);
  5840. for (auto *E : C->lhs_exprs())
  5841. Record.AddStmt(E);
  5842. for (auto *E : C->rhs_exprs())
  5843. Record.AddStmt(E);
  5844. for (auto *E : C->reduction_ops())
  5845. Record.AddStmt(E);
  5846. }
  5847. void OMPClauseWriter::VisitOMPInReductionClause(OMPInReductionClause *C) {
  5848. Record.push_back(C->varlist_size());
  5849. VisitOMPClauseWithPostUpdate(C);
  5850. Record.AddSourceLocation(C->getLParenLoc());
  5851. Record.AddSourceLocation(C->getColonLoc());
  5852. Record.AddNestedNameSpecifierLoc(C->getQualifierLoc());
  5853. Record.AddDeclarationNameInfo(C->getNameInfo());
  5854. for (auto *VE : C->varlists())
  5855. Record.AddStmt(VE);
  5856. for (auto *VE : C->privates())
  5857. Record.AddStmt(VE);
  5858. for (auto *E : C->lhs_exprs())
  5859. Record.AddStmt(E);
  5860. for (auto *E : C->rhs_exprs())
  5861. Record.AddStmt(E);
  5862. for (auto *E : C->reduction_ops())
  5863. Record.AddStmt(E);
  5864. for (auto *E : C->taskgroup_descriptors())
  5865. Record.AddStmt(E);
  5866. }
  5867. void OMPClauseWriter::VisitOMPLinearClause(OMPLinearClause *C) {
  5868. Record.push_back(C->varlist_size());
  5869. VisitOMPClauseWithPostUpdate(C);
  5870. Record.AddSourceLocation(C->getLParenLoc());
  5871. Record.AddSourceLocation(C->getColonLoc());
  5872. Record.push_back(C->getModifier());
  5873. Record.AddSourceLocation(C->getModifierLoc());
  5874. for (auto *VE : C->varlists()) {
  5875. Record.AddStmt(VE);
  5876. }
  5877. for (auto *VE : C->privates()) {
  5878. Record.AddStmt(VE);
  5879. }
  5880. for (auto *VE : C->inits()) {
  5881. Record.AddStmt(VE);
  5882. }
  5883. for (auto *VE : C->updates()) {
  5884. Record.AddStmt(VE);
  5885. }
  5886. for (auto *VE : C->finals()) {
  5887. Record.AddStmt(VE);
  5888. }
  5889. Record.AddStmt(C->getStep());
  5890. Record.AddStmt(C->getCalcStep());
  5891. for (auto *VE : C->used_expressions())
  5892. Record.AddStmt(VE);
  5893. }
  5894. void OMPClauseWriter::VisitOMPAlignedClause(OMPAlignedClause *C) {
  5895. Record.push_back(C->varlist_size());
  5896. Record.AddSourceLocation(C->getLParenLoc());
  5897. Record.AddSourceLocation(C->getColonLoc());
  5898. for (auto *VE : C->varlists())
  5899. Record.AddStmt(VE);
  5900. Record.AddStmt(C->getAlignment());
  5901. }
  5902. void OMPClauseWriter::VisitOMPCopyinClause(OMPCopyinClause *C) {
  5903. Record.push_back(C->varlist_size());
  5904. Record.AddSourceLocation(C->getLParenLoc());
  5905. for (auto *VE : C->varlists())
  5906. Record.AddStmt(VE);
  5907. for (auto *E : C->source_exprs())
  5908. Record.AddStmt(E);
  5909. for (auto *E : C->destination_exprs())
  5910. Record.AddStmt(E);
  5911. for (auto *E : C->assignment_ops())
  5912. Record.AddStmt(E);
  5913. }
  5914. void OMPClauseWriter::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
  5915. Record.push_back(C->varlist_size());
  5916. Record.AddSourceLocation(C->getLParenLoc());
  5917. for (auto *VE : C->varlists())
  5918. Record.AddStmt(VE);
  5919. for (auto *E : C->source_exprs())
  5920. Record.AddStmt(E);
  5921. for (auto *E : C->destination_exprs())
  5922. Record.AddStmt(E);
  5923. for (auto *E : C->assignment_ops())
  5924. Record.AddStmt(E);
  5925. }
  5926. void OMPClauseWriter::VisitOMPFlushClause(OMPFlushClause *C) {
  5927. Record.push_back(C->varlist_size());
  5928. Record.AddSourceLocation(C->getLParenLoc());
  5929. for (auto *VE : C->varlists())
  5930. Record.AddStmt(VE);
  5931. }
  5932. void OMPClauseWriter::VisitOMPDependClause(OMPDependClause *C) {
  5933. Record.push_back(C->varlist_size());
  5934. Record.push_back(C->getNumLoops());
  5935. Record.AddSourceLocation(C->getLParenLoc());
  5936. Record.push_back(C->getDependencyKind());
  5937. Record.AddSourceLocation(C->getDependencyLoc());
  5938. Record.AddSourceLocation(C->getColonLoc());
  5939. for (auto *VE : C->varlists())
  5940. Record.AddStmt(VE);
  5941. for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
  5942. Record.AddStmt(C->getLoopData(I));
  5943. }
  5944. void OMPClauseWriter::VisitOMPDeviceClause(OMPDeviceClause *C) {
  5945. VisitOMPClauseWithPreInit(C);
  5946. Record.AddStmt(C->getDevice());
  5947. Record.AddSourceLocation(C->getLParenLoc());
  5948. }
  5949. void OMPClauseWriter::VisitOMPMapClause(OMPMapClause *C) {
  5950. Record.push_back(C->varlist_size());
  5951. Record.push_back(C->getUniqueDeclarationsNum());
  5952. Record.push_back(C->getTotalComponentListNum());
  5953. Record.push_back(C->getTotalComponentsNum());
  5954. Record.AddSourceLocation(C->getLParenLoc());
  5955. for (unsigned I = 0; I < OMPMapClause::NumberOfModifiers; ++I) {
  5956. Record.push_back(C->getMapTypeModifier(I));
  5957. Record.AddSourceLocation(C->getMapTypeModifierLoc(I));
  5958. }
  5959. Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
  5960. Record.AddDeclarationNameInfo(C->getMapperIdInfo());
  5961. Record.push_back(C->getMapType());
  5962. Record.AddSourceLocation(C->getMapLoc());
  5963. Record.AddSourceLocation(C->getColonLoc());
  5964. for (auto *E : C->varlists())
  5965. Record.AddStmt(E);
  5966. for (auto *E : C->mapperlists())
  5967. Record.AddStmt(E);
  5968. for (auto *D : C->all_decls())
  5969. Record.AddDeclRef(D);
  5970. for (auto N : C->all_num_lists())
  5971. Record.push_back(N);
  5972. for (auto N : C->all_lists_sizes())
  5973. Record.push_back(N);
  5974. for (auto &M : C->all_components()) {
  5975. Record.AddStmt(M.getAssociatedExpression());
  5976. Record.AddDeclRef(M.getAssociatedDeclaration());
  5977. }
  5978. }
  5979. void OMPClauseWriter::VisitOMPAllocateClause(OMPAllocateClause *C) {
  5980. Record.push_back(C->varlist_size());
  5981. Record.AddSourceLocation(C->getLParenLoc());
  5982. Record.AddSourceLocation(C->getColonLoc());
  5983. Record.AddStmt(C->getAllocator());
  5984. for (auto *VE : C->varlists())
  5985. Record.AddStmt(VE);
  5986. }
  5987. void OMPClauseWriter::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
  5988. VisitOMPClauseWithPreInit(C);
  5989. Record.AddStmt(C->getNumTeams());
  5990. Record.AddSourceLocation(C->getLParenLoc());
  5991. }
  5992. void OMPClauseWriter::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
  5993. VisitOMPClauseWithPreInit(C);
  5994. Record.AddStmt(C->getThreadLimit());
  5995. Record.AddSourceLocation(C->getLParenLoc());
  5996. }
  5997. void OMPClauseWriter::VisitOMPPriorityClause(OMPPriorityClause *C) {
  5998. Record.AddStmt(C->getPriority());
  5999. Record.AddSourceLocation(C->getLParenLoc());
  6000. }
  6001. void OMPClauseWriter::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
  6002. Record.AddStmt(C->getGrainsize());
  6003. Record.AddSourceLocation(C->getLParenLoc());
  6004. }
  6005. void OMPClauseWriter::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
  6006. Record.AddStmt(C->getNumTasks());
  6007. Record.AddSourceLocation(C->getLParenLoc());
  6008. }
  6009. void OMPClauseWriter::VisitOMPHintClause(OMPHintClause *C) {
  6010. Record.AddStmt(C->getHint());
  6011. Record.AddSourceLocation(C->getLParenLoc());
  6012. }
  6013. void OMPClauseWriter::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
  6014. VisitOMPClauseWithPreInit(C);
  6015. Record.push_back(C->getDistScheduleKind());
  6016. Record.AddStmt(C->getChunkSize());
  6017. Record.AddSourceLocation(C->getLParenLoc());
  6018. Record.AddSourceLocation(C->getDistScheduleKindLoc());
  6019. Record.AddSourceLocation(C->getCommaLoc());
  6020. }
  6021. void OMPClauseWriter::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
  6022. Record.push_back(C->getDefaultmapKind());
  6023. Record.push_back(C->getDefaultmapModifier());
  6024. Record.AddSourceLocation(C->getLParenLoc());
  6025. Record.AddSourceLocation(C->getDefaultmapModifierLoc());
  6026. Record.AddSourceLocation(C->getDefaultmapKindLoc());
  6027. }
  6028. void OMPClauseWriter::VisitOMPToClause(OMPToClause *C) {
  6029. Record.push_back(C->varlist_size());
  6030. Record.push_back(C->getUniqueDeclarationsNum());
  6031. Record.push_back(C->getTotalComponentListNum());
  6032. Record.push_back(C->getTotalComponentsNum());
  6033. Record.AddSourceLocation(C->getLParenLoc());
  6034. Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
  6035. Record.AddDeclarationNameInfo(C->getMapperIdInfo());
  6036. for (auto *E : C->varlists())
  6037. Record.AddStmt(E);
  6038. for (auto *E : C->mapperlists())
  6039. Record.AddStmt(E);
  6040. for (auto *D : C->all_decls())
  6041. Record.AddDeclRef(D);
  6042. for (auto N : C->all_num_lists())
  6043. Record.push_back(N);
  6044. for (auto N : C->all_lists_sizes())
  6045. Record.push_back(N);
  6046. for (auto &M : C->all_components()) {
  6047. Record.AddStmt(M.getAssociatedExpression());
  6048. Record.AddDeclRef(M.getAssociatedDeclaration());
  6049. }
  6050. }
  6051. void OMPClauseWriter::VisitOMPFromClause(OMPFromClause *C) {
  6052. Record.push_back(C->varlist_size());
  6053. Record.push_back(C->getUniqueDeclarationsNum());
  6054. Record.push_back(C->getTotalComponentListNum());
  6055. Record.push_back(C->getTotalComponentsNum());
  6056. Record.AddSourceLocation(C->getLParenLoc());
  6057. Record.AddNestedNameSpecifierLoc(C->getMapperQualifierLoc());
  6058. Record.AddDeclarationNameInfo(C->getMapperIdInfo());
  6059. for (auto *E : C->varlists())
  6060. Record.AddStmt(E);
  6061. for (auto *E : C->mapperlists())
  6062. Record.AddStmt(E);
  6063. for (auto *D : C->all_decls())
  6064. Record.AddDeclRef(D);
  6065. for (auto N : C->all_num_lists())
  6066. Record.push_back(N);
  6067. for (auto N : C->all_lists_sizes())
  6068. Record.push_back(N);
  6069. for (auto &M : C->all_components()) {
  6070. Record.AddStmt(M.getAssociatedExpression());
  6071. Record.AddDeclRef(M.getAssociatedDeclaration());
  6072. }
  6073. }
  6074. void OMPClauseWriter::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
  6075. Record.push_back(C->varlist_size());
  6076. Record.push_back(C->getUniqueDeclarationsNum());
  6077. Record.push_back(C->getTotalComponentListNum());
  6078. Record.push_back(C->getTotalComponentsNum());
  6079. Record.AddSourceLocation(C->getLParenLoc());
  6080. for (auto *E : C->varlists())
  6081. Record.AddStmt(E);
  6082. for (auto *VE : C->private_copies())
  6083. Record.AddStmt(VE);
  6084. for (auto *VE : C->inits())
  6085. Record.AddStmt(VE);
  6086. for (auto *D : C->all_decls())
  6087. Record.AddDeclRef(D);
  6088. for (auto N : C->all_num_lists())
  6089. Record.push_back(N);
  6090. for (auto N : C->all_lists_sizes())
  6091. Record.push_back(N);
  6092. for (auto &M : C->all_components()) {
  6093. Record.AddStmt(M.getAssociatedExpression());
  6094. Record.AddDeclRef(M.getAssociatedDeclaration());
  6095. }
  6096. }
  6097. void OMPClauseWriter::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
  6098. Record.push_back(C->varlist_size());
  6099. Record.push_back(C->getUniqueDeclarationsNum());
  6100. Record.push_back(C->getTotalComponentListNum());
  6101. Record.push_back(C->getTotalComponentsNum());
  6102. Record.AddSourceLocation(C->getLParenLoc());
  6103. for (auto *E : C->varlists())
  6104. Record.AddStmt(E);
  6105. for (auto *D : C->all_decls())
  6106. Record.AddDeclRef(D);
  6107. for (auto N : C->all_num_lists())
  6108. Record.push_back(N);
  6109. for (auto N : C->all_lists_sizes())
  6110. Record.push_back(N);
  6111. for (auto &M : C->all_components()) {
  6112. Record.AddStmt(M.getAssociatedExpression());
  6113. Record.AddDeclRef(M.getAssociatedDeclaration());
  6114. }
  6115. }
  6116. void OMPClauseWriter::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
  6117. void OMPClauseWriter::VisitOMPUnifiedSharedMemoryClause(
  6118. OMPUnifiedSharedMemoryClause *) {}
  6119. void OMPClauseWriter::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
  6120. void
  6121. OMPClauseWriter::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
  6122. }
  6123. void OMPClauseWriter::VisitOMPAtomicDefaultMemOrderClause(
  6124. OMPAtomicDefaultMemOrderClause *C) {
  6125. Record.push_back(C->getAtomicDefaultMemOrderKind());
  6126. Record.AddSourceLocation(C->getLParenLoc());
  6127. Record.AddSourceLocation(C->getAtomicDefaultMemOrderKindKwLoc());
  6128. }