ASTWriter.cpp 252 KB

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