ASTWriter.cpp 213 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853
  1. //===--- ASTWriter.cpp - AST File Writer ----------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the ASTWriter class, which writes AST files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Serialization/ASTWriter.h"
  14. #include "ASTCommon.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/Decl.h"
  17. #include "clang/AST/DeclContextInternals.h"
  18. #include "clang/AST/DeclFriend.h"
  19. #include "clang/AST/DeclLookups.h"
  20. #include "clang/AST/DeclTemplate.h"
  21. #include "clang/AST/Expr.h"
  22. #include "clang/AST/ExprCXX.h"
  23. #include "clang/AST/Type.h"
  24. #include "clang/AST/TypeLocVisitor.h"
  25. #include "clang/Basic/DiagnosticOptions.h"
  26. #include "clang/Basic/FileManager.h"
  27. #include "clang/Basic/FileSystemStatCache.h"
  28. #include "clang/Basic/SourceManager.h"
  29. #include "clang/Basic/SourceManagerInternals.h"
  30. #include "clang/Basic/TargetInfo.h"
  31. #include "clang/Basic/TargetOptions.h"
  32. #include "clang/Basic/Version.h"
  33. #include "clang/Basic/VersionTuple.h"
  34. #include "clang/Lex/HeaderSearch.h"
  35. #include "clang/Lex/HeaderSearchOptions.h"
  36. #include "clang/Lex/MacroInfo.h"
  37. #include "clang/Lex/PreprocessingRecord.h"
  38. #include "clang/Lex/Preprocessor.h"
  39. #include "clang/Lex/PreprocessorOptions.h"
  40. #include "clang/Sema/IdentifierResolver.h"
  41. #include "clang/Sema/Sema.h"
  42. #include "clang/Serialization/ASTReader.h"
  43. #include "llvm/ADT/APFloat.h"
  44. #include "llvm/ADT/APInt.h"
  45. #include "llvm/ADT/Hashing.h"
  46. #include "llvm/ADT/StringExtras.h"
  47. #include "llvm/Bitcode/BitstreamWriter.h"
  48. #include "llvm/Support/EndianStream.h"
  49. #include "llvm/Support/FileSystem.h"
  50. #include "llvm/Support/MemoryBuffer.h"
  51. #include "llvm/Support/OnDiskHashTable.h"
  52. #include "llvm/Support/Path.h"
  53. #include "llvm/Support/Process.h"
  54. #include <algorithm>
  55. #include <cstdio>
  56. #include <string.h>
  57. #include <utility>
  58. using namespace clang;
  59. using namespace clang::serialization;
  60. template <typename T, typename Allocator>
  61. static StringRef bytes(const std::vector<T, Allocator> &v) {
  62. if (v.empty()) return StringRef();
  63. return StringRef(reinterpret_cast<const char*>(&v[0]),
  64. sizeof(T) * v.size());
  65. }
  66. template <typename T>
  67. static StringRef bytes(const SmallVectorImpl<T> &v) {
  68. return StringRef(reinterpret_cast<const char*>(v.data()),
  69. sizeof(T) * v.size());
  70. }
  71. //===----------------------------------------------------------------------===//
  72. // Type serialization
  73. //===----------------------------------------------------------------------===//
  74. namespace {
  75. class ASTTypeWriter {
  76. ASTWriter &Writer;
  77. ASTWriter::RecordDataImpl &Record;
  78. public:
  79. /// \brief Type code that corresponds to the record generated.
  80. TypeCode Code;
  81. /// \brief Abbreviation to use for the record, if any.
  82. unsigned AbbrevToUse;
  83. ASTTypeWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
  84. : Writer(Writer), Record(Record), Code(TYPE_EXT_QUAL) { }
  85. void VisitArrayType(const ArrayType *T);
  86. void VisitFunctionType(const FunctionType *T);
  87. void VisitTagType(const TagType *T);
  88. #define TYPE(Class, Base) void Visit##Class##Type(const Class##Type *T);
  89. #define ABSTRACT_TYPE(Class, Base)
  90. #include "clang/AST/TypeNodes.def"
  91. };
  92. }
  93. void ASTTypeWriter::VisitBuiltinType(const BuiltinType *T) {
  94. llvm_unreachable("Built-in types are never serialized");
  95. }
  96. void ASTTypeWriter::VisitComplexType(const ComplexType *T) {
  97. Writer.AddTypeRef(T->getElementType(), Record);
  98. Code = TYPE_COMPLEX;
  99. }
  100. void ASTTypeWriter::VisitPointerType(const PointerType *T) {
  101. Writer.AddTypeRef(T->getPointeeType(), Record);
  102. Code = TYPE_POINTER;
  103. }
  104. void ASTTypeWriter::VisitDecayedType(const DecayedType *T) {
  105. Writer.AddTypeRef(T->getOriginalType(), Record);
  106. Code = TYPE_DECAYED;
  107. }
  108. void ASTTypeWriter::VisitAdjustedType(const AdjustedType *T) {
  109. Writer.AddTypeRef(T->getOriginalType(), Record);
  110. Writer.AddTypeRef(T->getAdjustedType(), Record);
  111. Code = TYPE_ADJUSTED;
  112. }
  113. void ASTTypeWriter::VisitBlockPointerType(const BlockPointerType *T) {
  114. Writer.AddTypeRef(T->getPointeeType(), Record);
  115. Code = TYPE_BLOCK_POINTER;
  116. }
  117. void ASTTypeWriter::VisitLValueReferenceType(const LValueReferenceType *T) {
  118. Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
  119. Record.push_back(T->isSpelledAsLValue());
  120. Code = TYPE_LVALUE_REFERENCE;
  121. }
  122. void ASTTypeWriter::VisitRValueReferenceType(const RValueReferenceType *T) {
  123. Writer.AddTypeRef(T->getPointeeTypeAsWritten(), Record);
  124. Code = TYPE_RVALUE_REFERENCE;
  125. }
  126. void ASTTypeWriter::VisitMemberPointerType(const MemberPointerType *T) {
  127. Writer.AddTypeRef(T->getPointeeType(), Record);
  128. Writer.AddTypeRef(QualType(T->getClass(), 0), Record);
  129. Code = TYPE_MEMBER_POINTER;
  130. }
  131. void ASTTypeWriter::VisitArrayType(const ArrayType *T) {
  132. Writer.AddTypeRef(T->getElementType(), Record);
  133. Record.push_back(T->getSizeModifier()); // FIXME: stable values
  134. Record.push_back(T->getIndexTypeCVRQualifiers()); // FIXME: stable values
  135. }
  136. void ASTTypeWriter::VisitConstantArrayType(const ConstantArrayType *T) {
  137. VisitArrayType(T);
  138. Writer.AddAPInt(T->getSize(), Record);
  139. Code = TYPE_CONSTANT_ARRAY;
  140. }
  141. void ASTTypeWriter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
  142. VisitArrayType(T);
  143. Code = TYPE_INCOMPLETE_ARRAY;
  144. }
  145. void ASTTypeWriter::VisitVariableArrayType(const VariableArrayType *T) {
  146. VisitArrayType(T);
  147. Writer.AddSourceLocation(T->getLBracketLoc(), Record);
  148. Writer.AddSourceLocation(T->getRBracketLoc(), Record);
  149. Writer.AddStmt(T->getSizeExpr());
  150. Code = TYPE_VARIABLE_ARRAY;
  151. }
  152. void ASTTypeWriter::VisitVectorType(const VectorType *T) {
  153. Writer.AddTypeRef(T->getElementType(), Record);
  154. Record.push_back(T->getNumElements());
  155. Record.push_back(T->getVectorKind());
  156. Code = TYPE_VECTOR;
  157. }
  158. void ASTTypeWriter::VisitExtVectorType(const ExtVectorType *T) {
  159. VisitVectorType(T);
  160. Code = TYPE_EXT_VECTOR;
  161. }
  162. void ASTTypeWriter::VisitFunctionType(const FunctionType *T) {
  163. Writer.AddTypeRef(T->getReturnType(), Record);
  164. FunctionType::ExtInfo C = T->getExtInfo();
  165. Record.push_back(C.getNoReturn());
  166. Record.push_back(C.getHasRegParm());
  167. Record.push_back(C.getRegParm());
  168. // FIXME: need to stabilize encoding of calling convention...
  169. Record.push_back(C.getCC());
  170. Record.push_back(C.getProducesResult());
  171. if (C.getHasRegParm() || C.getRegParm() || C.getProducesResult())
  172. AbbrevToUse = 0;
  173. }
  174. void ASTTypeWriter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
  175. VisitFunctionType(T);
  176. Code = TYPE_FUNCTION_NO_PROTO;
  177. }
  178. static void addExceptionSpec(ASTWriter &Writer, const FunctionProtoType *T,
  179. ASTWriter::RecordDataImpl &Record) {
  180. Record.push_back(T->getExceptionSpecType());
  181. if (T->getExceptionSpecType() == EST_Dynamic) {
  182. Record.push_back(T->getNumExceptions());
  183. for (unsigned I = 0, N = T->getNumExceptions(); I != N; ++I)
  184. Writer.AddTypeRef(T->getExceptionType(I), Record);
  185. } else if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
  186. Writer.AddStmt(T->getNoexceptExpr());
  187. } else if (T->getExceptionSpecType() == EST_Uninstantiated) {
  188. Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
  189. Writer.AddDeclRef(T->getExceptionSpecTemplate(), Record);
  190. } else if (T->getExceptionSpecType() == EST_Unevaluated) {
  191. Writer.AddDeclRef(T->getExceptionSpecDecl(), Record);
  192. }
  193. }
  194. void ASTTypeWriter::VisitFunctionProtoType(const FunctionProtoType *T) {
  195. VisitFunctionType(T);
  196. Record.push_back(T->isVariadic());
  197. Record.push_back(T->hasTrailingReturn());
  198. Record.push_back(T->getTypeQuals());
  199. Record.push_back(static_cast<unsigned>(T->getRefQualifier()));
  200. addExceptionSpec(Writer, T, Record);
  201. Record.push_back(T->getNumParams());
  202. for (unsigned I = 0, N = T->getNumParams(); I != N; ++I)
  203. Writer.AddTypeRef(T->getParamType(I), Record);
  204. if (T->isVariadic() || T->hasTrailingReturn() || T->getTypeQuals() ||
  205. T->getRefQualifier() || T->getExceptionSpecType() != EST_None)
  206. AbbrevToUse = 0;
  207. Code = TYPE_FUNCTION_PROTO;
  208. }
  209. void ASTTypeWriter::VisitUnresolvedUsingType(const UnresolvedUsingType *T) {
  210. Writer.AddDeclRef(T->getDecl(), Record);
  211. Code = TYPE_UNRESOLVED_USING;
  212. }
  213. void ASTTypeWriter::VisitTypedefType(const TypedefType *T) {
  214. Writer.AddDeclRef(T->getDecl(), Record);
  215. assert(!T->isCanonicalUnqualified() && "Invalid typedef ?");
  216. Writer.AddTypeRef(T->getCanonicalTypeInternal(), Record);
  217. Code = TYPE_TYPEDEF;
  218. }
  219. void ASTTypeWriter::VisitTypeOfExprType(const TypeOfExprType *T) {
  220. Writer.AddStmt(T->getUnderlyingExpr());
  221. Code = TYPE_TYPEOF_EXPR;
  222. }
  223. void ASTTypeWriter::VisitTypeOfType(const TypeOfType *T) {
  224. Writer.AddTypeRef(T->getUnderlyingType(), Record);
  225. Code = TYPE_TYPEOF;
  226. }
  227. void ASTTypeWriter::VisitDecltypeType(const DecltypeType *T) {
  228. Writer.AddTypeRef(T->getUnderlyingType(), Record);
  229. Writer.AddStmt(T->getUnderlyingExpr());
  230. Code = TYPE_DECLTYPE;
  231. }
  232. void ASTTypeWriter::VisitUnaryTransformType(const UnaryTransformType *T) {
  233. Writer.AddTypeRef(T->getBaseType(), Record);
  234. Writer.AddTypeRef(T->getUnderlyingType(), Record);
  235. Record.push_back(T->getUTTKind());
  236. Code = TYPE_UNARY_TRANSFORM;
  237. }
  238. void ASTTypeWriter::VisitAutoType(const AutoType *T) {
  239. Writer.AddTypeRef(T->getDeducedType(), Record);
  240. Record.push_back(T->isDecltypeAuto());
  241. if (T->getDeducedType().isNull())
  242. Record.push_back(T->isDependentType());
  243. Code = TYPE_AUTO;
  244. }
  245. void ASTTypeWriter::VisitTagType(const TagType *T) {
  246. Record.push_back(T->isDependentType());
  247. Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
  248. assert(!T->isBeingDefined() &&
  249. "Cannot serialize in the middle of a type definition");
  250. }
  251. void ASTTypeWriter::VisitRecordType(const RecordType *T) {
  252. VisitTagType(T);
  253. Code = TYPE_RECORD;
  254. }
  255. void ASTTypeWriter::VisitEnumType(const EnumType *T) {
  256. VisitTagType(T);
  257. Code = TYPE_ENUM;
  258. }
  259. void ASTTypeWriter::VisitAttributedType(const AttributedType *T) {
  260. Writer.AddTypeRef(T->getModifiedType(), Record);
  261. Writer.AddTypeRef(T->getEquivalentType(), Record);
  262. Record.push_back(T->getAttrKind());
  263. Code = TYPE_ATTRIBUTED;
  264. }
  265. void
  266. ASTTypeWriter::VisitSubstTemplateTypeParmType(
  267. const SubstTemplateTypeParmType *T) {
  268. Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
  269. Writer.AddTypeRef(T->getReplacementType(), Record);
  270. Code = TYPE_SUBST_TEMPLATE_TYPE_PARM;
  271. }
  272. void
  273. ASTTypeWriter::VisitSubstTemplateTypeParmPackType(
  274. const SubstTemplateTypeParmPackType *T) {
  275. Writer.AddTypeRef(QualType(T->getReplacedParameter(), 0), Record);
  276. Writer.AddTemplateArgument(T->getArgumentPack(), Record);
  277. Code = TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK;
  278. }
  279. void
  280. ASTTypeWriter::VisitTemplateSpecializationType(
  281. const TemplateSpecializationType *T) {
  282. Record.push_back(T->isDependentType());
  283. Writer.AddTemplateName(T->getTemplateName(), Record);
  284. Record.push_back(T->getNumArgs());
  285. for (TemplateSpecializationType::iterator ArgI = T->begin(), ArgE = T->end();
  286. ArgI != ArgE; ++ArgI)
  287. Writer.AddTemplateArgument(*ArgI, Record);
  288. Writer.AddTypeRef(T->isTypeAlias() ? T->getAliasedType() :
  289. T->isCanonicalUnqualified() ? QualType()
  290. : T->getCanonicalTypeInternal(),
  291. Record);
  292. Code = TYPE_TEMPLATE_SPECIALIZATION;
  293. }
  294. void
  295. ASTTypeWriter::VisitDependentSizedArrayType(const DependentSizedArrayType *T) {
  296. VisitArrayType(T);
  297. Writer.AddStmt(T->getSizeExpr());
  298. Writer.AddSourceRange(T->getBracketsRange(), Record);
  299. Code = TYPE_DEPENDENT_SIZED_ARRAY;
  300. }
  301. void
  302. ASTTypeWriter::VisitDependentSizedExtVectorType(
  303. const DependentSizedExtVectorType *T) {
  304. // FIXME: Serialize this type (C++ only)
  305. llvm_unreachable("Cannot serialize dependent sized extended vector types");
  306. }
  307. void
  308. ASTTypeWriter::VisitTemplateTypeParmType(const TemplateTypeParmType *T) {
  309. Record.push_back(T->getDepth());
  310. Record.push_back(T->getIndex());
  311. Record.push_back(T->isParameterPack());
  312. Writer.AddDeclRef(T->getDecl(), Record);
  313. Code = TYPE_TEMPLATE_TYPE_PARM;
  314. }
  315. void
  316. ASTTypeWriter::VisitDependentNameType(const DependentNameType *T) {
  317. Record.push_back(T->getKeyword());
  318. Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
  319. Writer.AddIdentifierRef(T->getIdentifier(), Record);
  320. Writer.AddTypeRef(T->isCanonicalUnqualified() ? QualType()
  321. : T->getCanonicalTypeInternal(),
  322. Record);
  323. Code = TYPE_DEPENDENT_NAME;
  324. }
  325. void
  326. ASTTypeWriter::VisitDependentTemplateSpecializationType(
  327. const DependentTemplateSpecializationType *T) {
  328. Record.push_back(T->getKeyword());
  329. Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
  330. Writer.AddIdentifierRef(T->getIdentifier(), Record);
  331. Record.push_back(T->getNumArgs());
  332. for (DependentTemplateSpecializationType::iterator
  333. I = T->begin(), E = T->end(); I != E; ++I)
  334. Writer.AddTemplateArgument(*I, Record);
  335. Code = TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION;
  336. }
  337. void ASTTypeWriter::VisitPackExpansionType(const PackExpansionType *T) {
  338. Writer.AddTypeRef(T->getPattern(), Record);
  339. if (Optional<unsigned> NumExpansions = T->getNumExpansions())
  340. Record.push_back(*NumExpansions + 1);
  341. else
  342. Record.push_back(0);
  343. Code = TYPE_PACK_EXPANSION;
  344. }
  345. void ASTTypeWriter::VisitParenType(const ParenType *T) {
  346. Writer.AddTypeRef(T->getInnerType(), Record);
  347. Code = TYPE_PAREN;
  348. }
  349. void ASTTypeWriter::VisitElaboratedType(const ElaboratedType *T) {
  350. Record.push_back(T->getKeyword());
  351. Writer.AddNestedNameSpecifier(T->getQualifier(), Record);
  352. Writer.AddTypeRef(T->getNamedType(), Record);
  353. Code = TYPE_ELABORATED;
  354. }
  355. void ASTTypeWriter::VisitInjectedClassNameType(const InjectedClassNameType *T) {
  356. Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
  357. Writer.AddTypeRef(T->getInjectedSpecializationType(), Record);
  358. Code = TYPE_INJECTED_CLASS_NAME;
  359. }
  360. void ASTTypeWriter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
  361. Writer.AddDeclRef(T->getDecl()->getCanonicalDecl(), Record);
  362. Code = TYPE_OBJC_INTERFACE;
  363. }
  364. void ASTTypeWriter::VisitObjCObjectType(const ObjCObjectType *T) {
  365. Writer.AddTypeRef(T->getBaseType(), Record);
  366. Record.push_back(T->getTypeArgsAsWritten().size());
  367. for (auto TypeArg : T->getTypeArgsAsWritten())
  368. Writer.AddTypeRef(TypeArg, Record);
  369. Record.push_back(T->getNumProtocols());
  370. for (const auto *I : T->quals())
  371. Writer.AddDeclRef(I, Record);
  372. Record.push_back(T->isKindOfTypeAsWritten());
  373. Code = TYPE_OBJC_OBJECT;
  374. }
  375. void
  376. ASTTypeWriter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
  377. Writer.AddTypeRef(T->getPointeeType(), Record);
  378. Code = TYPE_OBJC_OBJECT_POINTER;
  379. }
  380. void
  381. ASTTypeWriter::VisitAtomicType(const AtomicType *T) {
  382. Writer.AddTypeRef(T->getValueType(), Record);
  383. Code = TYPE_ATOMIC;
  384. }
  385. namespace {
  386. class TypeLocWriter : public TypeLocVisitor<TypeLocWriter> {
  387. ASTWriter &Writer;
  388. ASTWriter::RecordDataImpl &Record;
  389. public:
  390. TypeLocWriter(ASTWriter &Writer, ASTWriter::RecordDataImpl &Record)
  391. : Writer(Writer), Record(Record) { }
  392. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  393. #define TYPELOC(CLASS, PARENT) \
  394. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  395. #include "clang/AST/TypeLocNodes.def"
  396. void VisitArrayTypeLoc(ArrayTypeLoc TyLoc);
  397. void VisitFunctionTypeLoc(FunctionTypeLoc TyLoc);
  398. };
  399. }
  400. void TypeLocWriter::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  401. // nothing to do
  402. }
  403. void TypeLocWriter::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  404. Writer.AddSourceLocation(TL.getBuiltinLoc(), Record);
  405. if (TL.needsExtraLocalData()) {
  406. Record.push_back(TL.getWrittenTypeSpec());
  407. Record.push_back(TL.getWrittenSignSpec());
  408. Record.push_back(TL.getWrittenWidthSpec());
  409. Record.push_back(TL.hasModeAttr());
  410. }
  411. }
  412. void TypeLocWriter::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  413. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  414. }
  415. void TypeLocWriter::VisitPointerTypeLoc(PointerTypeLoc TL) {
  416. Writer.AddSourceLocation(TL.getStarLoc(), Record);
  417. }
  418. void TypeLocWriter::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  419. // nothing to do
  420. }
  421. void TypeLocWriter::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  422. // nothing to do
  423. }
  424. void TypeLocWriter::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  425. Writer.AddSourceLocation(TL.getCaretLoc(), Record);
  426. }
  427. void TypeLocWriter::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  428. Writer.AddSourceLocation(TL.getAmpLoc(), Record);
  429. }
  430. void TypeLocWriter::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  431. Writer.AddSourceLocation(TL.getAmpAmpLoc(), Record);
  432. }
  433. void TypeLocWriter::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  434. Writer.AddSourceLocation(TL.getStarLoc(), Record);
  435. Writer.AddTypeSourceInfo(TL.getClassTInfo(), Record);
  436. }
  437. void TypeLocWriter::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  438. Writer.AddSourceLocation(TL.getLBracketLoc(), Record);
  439. Writer.AddSourceLocation(TL.getRBracketLoc(), Record);
  440. Record.push_back(TL.getSizeExpr() ? 1 : 0);
  441. if (TL.getSizeExpr())
  442. Writer.AddStmt(TL.getSizeExpr());
  443. }
  444. void TypeLocWriter::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  445. VisitArrayTypeLoc(TL);
  446. }
  447. void TypeLocWriter::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  448. VisitArrayTypeLoc(TL);
  449. }
  450. void TypeLocWriter::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  451. VisitArrayTypeLoc(TL);
  452. }
  453. void TypeLocWriter::VisitDependentSizedArrayTypeLoc(
  454. DependentSizedArrayTypeLoc TL) {
  455. VisitArrayTypeLoc(TL);
  456. }
  457. void TypeLocWriter::VisitDependentSizedExtVectorTypeLoc(
  458. DependentSizedExtVectorTypeLoc TL) {
  459. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  460. }
  461. void TypeLocWriter::VisitVectorTypeLoc(VectorTypeLoc TL) {
  462. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  463. }
  464. void TypeLocWriter::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  465. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  466. }
  467. void TypeLocWriter::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  468. Writer.AddSourceLocation(TL.getLocalRangeBegin(), Record);
  469. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  470. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  471. Writer.AddSourceLocation(TL.getLocalRangeEnd(), Record);
  472. for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i)
  473. Writer.AddDeclRef(TL.getParam(i), Record);
  474. }
  475. void TypeLocWriter::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  476. VisitFunctionTypeLoc(TL);
  477. }
  478. void TypeLocWriter::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  479. VisitFunctionTypeLoc(TL);
  480. }
  481. void TypeLocWriter::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  482. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  483. }
  484. void TypeLocWriter::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  485. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  486. }
  487. void TypeLocWriter::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  488. Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
  489. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  490. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  491. }
  492. void TypeLocWriter::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  493. Writer.AddSourceLocation(TL.getTypeofLoc(), Record);
  494. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  495. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  496. Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
  497. }
  498. void TypeLocWriter::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  499. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  500. }
  501. void TypeLocWriter::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  502. Writer.AddSourceLocation(TL.getKWLoc(), Record);
  503. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  504. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  505. Writer.AddTypeSourceInfo(TL.getUnderlyingTInfo(), Record);
  506. }
  507. void TypeLocWriter::VisitAutoTypeLoc(AutoTypeLoc TL) {
  508. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  509. }
  510. void TypeLocWriter::VisitRecordTypeLoc(RecordTypeLoc TL) {
  511. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  512. }
  513. void TypeLocWriter::VisitEnumTypeLoc(EnumTypeLoc TL) {
  514. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  515. }
  516. void TypeLocWriter::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  517. Writer.AddSourceLocation(TL.getAttrNameLoc(), Record);
  518. if (TL.hasAttrOperand()) {
  519. SourceRange range = TL.getAttrOperandParensRange();
  520. Writer.AddSourceLocation(range.getBegin(), Record);
  521. Writer.AddSourceLocation(range.getEnd(), Record);
  522. }
  523. if (TL.hasAttrExprOperand()) {
  524. Expr *operand = TL.getAttrExprOperand();
  525. Record.push_back(operand ? 1 : 0);
  526. if (operand) Writer.AddStmt(operand);
  527. } else if (TL.hasAttrEnumOperand()) {
  528. Writer.AddSourceLocation(TL.getAttrEnumOperandLoc(), Record);
  529. }
  530. }
  531. void TypeLocWriter::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  532. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  533. }
  534. void TypeLocWriter::VisitSubstTemplateTypeParmTypeLoc(
  535. SubstTemplateTypeParmTypeLoc TL) {
  536. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  537. }
  538. void TypeLocWriter::VisitSubstTemplateTypeParmPackTypeLoc(
  539. SubstTemplateTypeParmPackTypeLoc TL) {
  540. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  541. }
  542. void TypeLocWriter::VisitTemplateSpecializationTypeLoc(
  543. TemplateSpecializationTypeLoc TL) {
  544. Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
  545. Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
  546. Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
  547. Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
  548. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  549. Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(i).getArgument().getKind(),
  550. TL.getArgLoc(i).getLocInfo(), Record);
  551. }
  552. void TypeLocWriter::VisitParenTypeLoc(ParenTypeLoc TL) {
  553. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  554. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  555. }
  556. void TypeLocWriter::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  557. Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
  558. Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
  559. }
  560. void TypeLocWriter::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  561. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  562. }
  563. void TypeLocWriter::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  564. Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
  565. Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
  566. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  567. }
  568. void TypeLocWriter::VisitDependentTemplateSpecializationTypeLoc(
  569. DependentTemplateSpecializationTypeLoc TL) {
  570. Writer.AddSourceLocation(TL.getElaboratedKeywordLoc(), Record);
  571. Writer.AddNestedNameSpecifierLoc(TL.getQualifierLoc(), Record);
  572. Writer.AddSourceLocation(TL.getTemplateKeywordLoc(), Record);
  573. Writer.AddSourceLocation(TL.getTemplateNameLoc(), Record);
  574. Writer.AddSourceLocation(TL.getLAngleLoc(), Record);
  575. Writer.AddSourceLocation(TL.getRAngleLoc(), Record);
  576. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  577. Writer.AddTemplateArgumentLocInfo(TL.getArgLoc(I).getArgument().getKind(),
  578. TL.getArgLoc(I).getLocInfo(), Record);
  579. }
  580. void TypeLocWriter::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  581. Writer.AddSourceLocation(TL.getEllipsisLoc(), Record);
  582. }
  583. void TypeLocWriter::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  584. Writer.AddSourceLocation(TL.getNameLoc(), Record);
  585. }
  586. void TypeLocWriter::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  587. Record.push_back(TL.hasBaseTypeAsWritten());
  588. Writer.AddSourceLocation(TL.getTypeArgsLAngleLoc(), Record);
  589. Writer.AddSourceLocation(TL.getTypeArgsRAngleLoc(), Record);
  590. for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
  591. Writer.AddTypeSourceInfo(TL.getTypeArgTInfo(i), Record);
  592. Writer.AddSourceLocation(TL.getProtocolLAngleLoc(), Record);
  593. Writer.AddSourceLocation(TL.getProtocolRAngleLoc(), Record);
  594. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  595. Writer.AddSourceLocation(TL.getProtocolLoc(i), Record);
  596. }
  597. void TypeLocWriter::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  598. Writer.AddSourceLocation(TL.getStarLoc(), Record);
  599. }
  600. void TypeLocWriter::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  601. Writer.AddSourceLocation(TL.getKWLoc(), Record);
  602. Writer.AddSourceLocation(TL.getLParenLoc(), Record);
  603. Writer.AddSourceLocation(TL.getRParenLoc(), Record);
  604. }
  605. void ASTWriter::WriteTypeAbbrevs() {
  606. using namespace llvm;
  607. BitCodeAbbrev *Abv;
  608. // Abbreviation for TYPE_EXT_QUAL
  609. Abv = new BitCodeAbbrev();
  610. Abv->Add(BitCodeAbbrevOp(serialization::TYPE_EXT_QUAL));
  611. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Type
  612. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 3)); // Quals
  613. TypeExtQualAbbrev = Stream.EmitAbbrev(Abv);
  614. // Abbreviation for TYPE_FUNCTION_PROTO
  615. Abv = new BitCodeAbbrev();
  616. Abv->Add(BitCodeAbbrevOp(serialization::TYPE_FUNCTION_PROTO));
  617. // FunctionType
  618. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ReturnType
  619. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // NoReturn
  620. Abv->Add(BitCodeAbbrevOp(0)); // HasRegParm
  621. Abv->Add(BitCodeAbbrevOp(0)); // RegParm
  622. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 4)); // CC
  623. Abv->Add(BitCodeAbbrevOp(0)); // ProducesResult
  624. // FunctionProtoType
  625. Abv->Add(BitCodeAbbrevOp(0)); // IsVariadic
  626. Abv->Add(BitCodeAbbrevOp(0)); // HasTrailingReturn
  627. Abv->Add(BitCodeAbbrevOp(0)); // TypeQuals
  628. Abv->Add(BitCodeAbbrevOp(0)); // RefQualifier
  629. Abv->Add(BitCodeAbbrevOp(EST_None)); // ExceptionSpec
  630. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // NumParams
  631. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Array));
  632. Abv->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Params
  633. TypeFunctionProtoAbbrev = Stream.EmitAbbrev(Abv);
  634. }
  635. //===----------------------------------------------------------------------===//
  636. // ASTWriter Implementation
  637. //===----------------------------------------------------------------------===//
  638. static void EmitBlockID(unsigned ID, const char *Name,
  639. llvm::BitstreamWriter &Stream,
  640. ASTWriter::RecordDataImpl &Record) {
  641. Record.clear();
  642. Record.push_back(ID);
  643. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETBID, Record);
  644. // Emit the block name if present.
  645. if (!Name || Name[0] == 0)
  646. return;
  647. Record.clear();
  648. while (*Name)
  649. Record.push_back(*Name++);
  650. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_BLOCKNAME, Record);
  651. }
  652. static void EmitRecordID(unsigned ID, const char *Name,
  653. llvm::BitstreamWriter &Stream,
  654. ASTWriter::RecordDataImpl &Record) {
  655. Record.clear();
  656. Record.push_back(ID);
  657. while (*Name)
  658. Record.push_back(*Name++);
  659. Stream.EmitRecord(llvm::bitc::BLOCKINFO_CODE_SETRECORDNAME, Record);
  660. }
  661. static void AddStmtsExprs(llvm::BitstreamWriter &Stream,
  662. ASTWriter::RecordDataImpl &Record) {
  663. #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
  664. RECORD(STMT_STOP);
  665. RECORD(STMT_NULL_PTR);
  666. RECORD(STMT_REF_PTR);
  667. RECORD(STMT_NULL);
  668. RECORD(STMT_COMPOUND);
  669. RECORD(STMT_CASE);
  670. RECORD(STMT_DEFAULT);
  671. RECORD(STMT_LABEL);
  672. RECORD(STMT_ATTRIBUTED);
  673. RECORD(STMT_IF);
  674. RECORD(STMT_SWITCH);
  675. RECORD(STMT_WHILE);
  676. RECORD(STMT_DO);
  677. RECORD(STMT_FOR);
  678. RECORD(STMT_GOTO);
  679. RECORD(STMT_INDIRECT_GOTO);
  680. RECORD(STMT_CONTINUE);
  681. RECORD(STMT_BREAK);
  682. RECORD(STMT_RETURN);
  683. RECORD(STMT_DECL);
  684. RECORD(STMT_GCCASM);
  685. RECORD(STMT_MSASM);
  686. RECORD(EXPR_PREDEFINED);
  687. RECORD(EXPR_DECL_REF);
  688. RECORD(EXPR_INTEGER_LITERAL);
  689. RECORD(EXPR_FLOATING_LITERAL);
  690. RECORD(EXPR_IMAGINARY_LITERAL);
  691. RECORD(EXPR_STRING_LITERAL);
  692. RECORD(EXPR_CHARACTER_LITERAL);
  693. RECORD(EXPR_PAREN);
  694. RECORD(EXPR_PAREN_LIST);
  695. RECORD(EXPR_UNARY_OPERATOR);
  696. RECORD(EXPR_SIZEOF_ALIGN_OF);
  697. RECORD(EXPR_ARRAY_SUBSCRIPT);
  698. RECORD(EXPR_CALL);
  699. RECORD(EXPR_MEMBER);
  700. RECORD(EXPR_BINARY_OPERATOR);
  701. RECORD(EXPR_COMPOUND_ASSIGN_OPERATOR);
  702. RECORD(EXPR_CONDITIONAL_OPERATOR);
  703. RECORD(EXPR_IMPLICIT_CAST);
  704. RECORD(EXPR_CSTYLE_CAST);
  705. RECORD(EXPR_COMPOUND_LITERAL);
  706. RECORD(EXPR_EXT_VECTOR_ELEMENT);
  707. RECORD(EXPR_INIT_LIST);
  708. RECORD(EXPR_DESIGNATED_INIT);
  709. RECORD(EXPR_DESIGNATED_INIT_UPDATE);
  710. RECORD(EXPR_IMPLICIT_VALUE_INIT);
  711. RECORD(EXPR_NO_INIT);
  712. RECORD(EXPR_VA_ARG);
  713. RECORD(EXPR_ADDR_LABEL);
  714. RECORD(EXPR_STMT);
  715. RECORD(EXPR_CHOOSE);
  716. RECORD(EXPR_GNU_NULL);
  717. RECORD(EXPR_SHUFFLE_VECTOR);
  718. RECORD(EXPR_BLOCK);
  719. RECORD(EXPR_GENERIC_SELECTION);
  720. RECORD(EXPR_OBJC_STRING_LITERAL);
  721. RECORD(EXPR_OBJC_BOXED_EXPRESSION);
  722. RECORD(EXPR_OBJC_ARRAY_LITERAL);
  723. RECORD(EXPR_OBJC_DICTIONARY_LITERAL);
  724. RECORD(EXPR_OBJC_ENCODE);
  725. RECORD(EXPR_OBJC_SELECTOR_EXPR);
  726. RECORD(EXPR_OBJC_PROTOCOL_EXPR);
  727. RECORD(EXPR_OBJC_IVAR_REF_EXPR);
  728. RECORD(EXPR_OBJC_PROPERTY_REF_EXPR);
  729. RECORD(EXPR_OBJC_KVC_REF_EXPR);
  730. RECORD(EXPR_OBJC_MESSAGE_EXPR);
  731. RECORD(STMT_OBJC_FOR_COLLECTION);
  732. RECORD(STMT_OBJC_CATCH);
  733. RECORD(STMT_OBJC_FINALLY);
  734. RECORD(STMT_OBJC_AT_TRY);
  735. RECORD(STMT_OBJC_AT_SYNCHRONIZED);
  736. RECORD(STMT_OBJC_AT_THROW);
  737. RECORD(EXPR_OBJC_BOOL_LITERAL);
  738. RECORD(STMT_CXX_CATCH);
  739. RECORD(STMT_CXX_TRY);
  740. RECORD(STMT_CXX_FOR_RANGE);
  741. RECORD(EXPR_CXX_OPERATOR_CALL);
  742. RECORD(EXPR_CXX_MEMBER_CALL);
  743. RECORD(EXPR_CXX_CONSTRUCT);
  744. RECORD(EXPR_CXX_TEMPORARY_OBJECT);
  745. RECORD(EXPR_CXX_STATIC_CAST);
  746. RECORD(EXPR_CXX_DYNAMIC_CAST);
  747. RECORD(EXPR_CXX_REINTERPRET_CAST);
  748. RECORD(EXPR_CXX_CONST_CAST);
  749. RECORD(EXPR_CXX_FUNCTIONAL_CAST);
  750. RECORD(EXPR_USER_DEFINED_LITERAL);
  751. RECORD(EXPR_CXX_STD_INITIALIZER_LIST);
  752. RECORD(EXPR_CXX_BOOL_LITERAL);
  753. RECORD(EXPR_CXX_NULL_PTR_LITERAL);
  754. RECORD(EXPR_CXX_TYPEID_EXPR);
  755. RECORD(EXPR_CXX_TYPEID_TYPE);
  756. RECORD(EXPR_CXX_THIS);
  757. RECORD(EXPR_CXX_THROW);
  758. RECORD(EXPR_CXX_DEFAULT_ARG);
  759. RECORD(EXPR_CXX_DEFAULT_INIT);
  760. RECORD(EXPR_CXX_BIND_TEMPORARY);
  761. RECORD(EXPR_CXX_SCALAR_VALUE_INIT);
  762. RECORD(EXPR_CXX_NEW);
  763. RECORD(EXPR_CXX_DELETE);
  764. RECORD(EXPR_CXX_PSEUDO_DESTRUCTOR);
  765. RECORD(EXPR_EXPR_WITH_CLEANUPS);
  766. RECORD(EXPR_CXX_DEPENDENT_SCOPE_MEMBER);
  767. RECORD(EXPR_CXX_DEPENDENT_SCOPE_DECL_REF);
  768. RECORD(EXPR_CXX_UNRESOLVED_CONSTRUCT);
  769. RECORD(EXPR_CXX_UNRESOLVED_MEMBER);
  770. RECORD(EXPR_CXX_UNRESOLVED_LOOKUP);
  771. RECORD(EXPR_CXX_EXPRESSION_TRAIT);
  772. RECORD(EXPR_CXX_NOEXCEPT);
  773. RECORD(EXPR_OPAQUE_VALUE);
  774. RECORD(EXPR_BINARY_CONDITIONAL_OPERATOR);
  775. RECORD(EXPR_TYPE_TRAIT);
  776. RECORD(EXPR_ARRAY_TYPE_TRAIT);
  777. RECORD(EXPR_PACK_EXPANSION);
  778. RECORD(EXPR_SIZEOF_PACK);
  779. RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM);
  780. RECORD(EXPR_SUBST_NON_TYPE_TEMPLATE_PARM_PACK);
  781. RECORD(EXPR_FUNCTION_PARM_PACK);
  782. RECORD(EXPR_MATERIALIZE_TEMPORARY);
  783. RECORD(EXPR_CUDA_KERNEL_CALL);
  784. RECORD(EXPR_CXX_UUIDOF_EXPR);
  785. RECORD(EXPR_CXX_UUIDOF_TYPE);
  786. RECORD(EXPR_LAMBDA);
  787. #undef RECORD
  788. }
  789. void ASTWriter::WriteBlockInfoBlock() {
  790. RecordData Record;
  791. Stream.EnterSubblock(llvm::bitc::BLOCKINFO_BLOCK_ID, 3);
  792. #define BLOCK(X) EmitBlockID(X ## _ID, #X, Stream, Record)
  793. #define RECORD(X) EmitRecordID(X, #X, Stream, Record)
  794. // Control Block.
  795. BLOCK(CONTROL_BLOCK);
  796. RECORD(METADATA);
  797. RECORD(SIGNATURE);
  798. RECORD(MODULE_NAME);
  799. RECORD(MODULE_MAP_FILE);
  800. RECORD(IMPORTS);
  801. RECORD(KNOWN_MODULE_FILES);
  802. RECORD(LANGUAGE_OPTIONS);
  803. RECORD(TARGET_OPTIONS);
  804. RECORD(ORIGINAL_FILE);
  805. RECORD(ORIGINAL_PCH_DIR);
  806. RECORD(ORIGINAL_FILE_ID);
  807. RECORD(INPUT_FILE_OFFSETS);
  808. RECORD(DIAGNOSTIC_OPTIONS);
  809. RECORD(FILE_SYSTEM_OPTIONS);
  810. RECORD(HEADER_SEARCH_OPTIONS);
  811. RECORD(PREPROCESSOR_OPTIONS);
  812. BLOCK(INPUT_FILES_BLOCK);
  813. RECORD(INPUT_FILE);
  814. // AST Top-Level Block.
  815. BLOCK(AST_BLOCK);
  816. RECORD(TYPE_OFFSET);
  817. RECORD(DECL_OFFSET);
  818. RECORD(IDENTIFIER_OFFSET);
  819. RECORD(IDENTIFIER_TABLE);
  820. RECORD(EAGERLY_DESERIALIZED_DECLS);
  821. RECORD(SPECIAL_TYPES);
  822. RECORD(STATISTICS);
  823. RECORD(TENTATIVE_DEFINITIONS);
  824. RECORD(UNUSED_FILESCOPED_DECLS);
  825. RECORD(SELECTOR_OFFSETS);
  826. RECORD(METHOD_POOL);
  827. RECORD(PP_COUNTER_VALUE);
  828. RECORD(SOURCE_LOCATION_OFFSETS);
  829. RECORD(SOURCE_LOCATION_PRELOADS);
  830. RECORD(EXT_VECTOR_DECLS);
  831. RECORD(PPD_ENTITIES_OFFSETS);
  832. RECORD(REFERENCED_SELECTOR_POOL);
  833. RECORD(TU_UPDATE_LEXICAL);
  834. RECORD(LOCAL_REDECLARATIONS_MAP);
  835. RECORD(SEMA_DECL_REFS);
  836. RECORD(WEAK_UNDECLARED_IDENTIFIERS);
  837. RECORD(PENDING_IMPLICIT_INSTANTIATIONS);
  838. RECORD(DECL_REPLACEMENTS);
  839. RECORD(UPDATE_VISIBLE);
  840. RECORD(DECL_UPDATE_OFFSETS);
  841. RECORD(DECL_UPDATES);
  842. RECORD(CXX_BASE_SPECIFIER_OFFSETS);
  843. RECORD(DIAG_PRAGMA_MAPPINGS);
  844. RECORD(CUDA_SPECIAL_DECL_REFS);
  845. RECORD(HEADER_SEARCH_TABLE);
  846. RECORD(FP_PRAGMA_OPTIONS);
  847. RECORD(OPENCL_EXTENSIONS);
  848. RECORD(DELEGATING_CTORS);
  849. RECORD(KNOWN_NAMESPACES);
  850. RECORD(UNDEFINED_BUT_USED);
  851. RECORD(MODULE_OFFSET_MAP);
  852. RECORD(SOURCE_MANAGER_LINE_TABLE);
  853. RECORD(OBJC_CATEGORIES_MAP);
  854. RECORD(FILE_SORTED_DECLS);
  855. RECORD(IMPORTED_MODULES);
  856. RECORD(LOCAL_REDECLARATIONS);
  857. RECORD(OBJC_CATEGORIES);
  858. RECORD(MACRO_OFFSET);
  859. RECORD(LATE_PARSED_TEMPLATE);
  860. RECORD(OPTIMIZE_PRAGMA_OPTIONS);
  861. // SourceManager Block.
  862. BLOCK(SOURCE_MANAGER_BLOCK);
  863. RECORD(SM_SLOC_FILE_ENTRY);
  864. RECORD(SM_SLOC_BUFFER_ENTRY);
  865. RECORD(SM_SLOC_BUFFER_BLOB);
  866. RECORD(SM_SLOC_EXPANSION_ENTRY);
  867. // Preprocessor Block.
  868. BLOCK(PREPROCESSOR_BLOCK);
  869. RECORD(PP_MACRO_DIRECTIVE_HISTORY);
  870. RECORD(PP_MACRO_FUNCTION_LIKE);
  871. RECORD(PP_MACRO_OBJECT_LIKE);
  872. RECORD(PP_MODULE_MACRO);
  873. RECORD(PP_TOKEN);
  874. // Decls and Types block.
  875. BLOCK(DECLTYPES_BLOCK);
  876. RECORD(TYPE_EXT_QUAL);
  877. RECORD(TYPE_COMPLEX);
  878. RECORD(TYPE_POINTER);
  879. RECORD(TYPE_BLOCK_POINTER);
  880. RECORD(TYPE_LVALUE_REFERENCE);
  881. RECORD(TYPE_RVALUE_REFERENCE);
  882. RECORD(TYPE_MEMBER_POINTER);
  883. RECORD(TYPE_CONSTANT_ARRAY);
  884. RECORD(TYPE_INCOMPLETE_ARRAY);
  885. RECORD(TYPE_VARIABLE_ARRAY);
  886. RECORD(TYPE_VECTOR);
  887. RECORD(TYPE_EXT_VECTOR);
  888. RECORD(TYPE_FUNCTION_NO_PROTO);
  889. RECORD(TYPE_FUNCTION_PROTO);
  890. RECORD(TYPE_TYPEDEF);
  891. RECORD(TYPE_TYPEOF_EXPR);
  892. RECORD(TYPE_TYPEOF);
  893. RECORD(TYPE_RECORD);
  894. RECORD(TYPE_ENUM);
  895. RECORD(TYPE_OBJC_INTERFACE);
  896. RECORD(TYPE_OBJC_OBJECT_POINTER);
  897. RECORD(TYPE_DECLTYPE);
  898. RECORD(TYPE_ELABORATED);
  899. RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM);
  900. RECORD(TYPE_UNRESOLVED_USING);
  901. RECORD(TYPE_INJECTED_CLASS_NAME);
  902. RECORD(TYPE_OBJC_OBJECT);
  903. RECORD(TYPE_TEMPLATE_TYPE_PARM);
  904. RECORD(TYPE_TEMPLATE_SPECIALIZATION);
  905. RECORD(TYPE_DEPENDENT_NAME);
  906. RECORD(TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION);
  907. RECORD(TYPE_DEPENDENT_SIZED_ARRAY);
  908. RECORD(TYPE_PAREN);
  909. RECORD(TYPE_PACK_EXPANSION);
  910. RECORD(TYPE_ATTRIBUTED);
  911. RECORD(TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK);
  912. RECORD(TYPE_AUTO);
  913. RECORD(TYPE_UNARY_TRANSFORM);
  914. RECORD(TYPE_ATOMIC);
  915. RECORD(TYPE_DECAYED);
  916. RECORD(TYPE_ADJUSTED);
  917. RECORD(DECL_TYPEDEF);
  918. RECORD(DECL_TYPEALIAS);
  919. RECORD(DECL_ENUM);
  920. RECORD(DECL_RECORD);
  921. RECORD(DECL_ENUM_CONSTANT);
  922. RECORD(DECL_FUNCTION);
  923. RECORD(DECL_OBJC_METHOD);
  924. RECORD(DECL_OBJC_INTERFACE);
  925. RECORD(DECL_OBJC_PROTOCOL);
  926. RECORD(DECL_OBJC_IVAR);
  927. RECORD(DECL_OBJC_AT_DEFS_FIELD);
  928. RECORD(DECL_OBJC_CATEGORY);
  929. RECORD(DECL_OBJC_CATEGORY_IMPL);
  930. RECORD(DECL_OBJC_IMPLEMENTATION);
  931. RECORD(DECL_OBJC_COMPATIBLE_ALIAS);
  932. RECORD(DECL_OBJC_PROPERTY);
  933. RECORD(DECL_OBJC_PROPERTY_IMPL);
  934. RECORD(DECL_FIELD);
  935. RECORD(DECL_MS_PROPERTY);
  936. RECORD(DECL_VAR);
  937. RECORD(DECL_IMPLICIT_PARAM);
  938. RECORD(DECL_PARM_VAR);
  939. RECORD(DECL_FILE_SCOPE_ASM);
  940. RECORD(DECL_BLOCK);
  941. RECORD(DECL_CONTEXT_LEXICAL);
  942. RECORD(DECL_CONTEXT_VISIBLE);
  943. RECORD(DECL_NAMESPACE);
  944. RECORD(DECL_NAMESPACE_ALIAS);
  945. RECORD(DECL_USING);
  946. RECORD(DECL_USING_SHADOW);
  947. RECORD(DECL_USING_DIRECTIVE);
  948. RECORD(DECL_UNRESOLVED_USING_VALUE);
  949. RECORD(DECL_UNRESOLVED_USING_TYPENAME);
  950. RECORD(DECL_LINKAGE_SPEC);
  951. RECORD(DECL_CXX_RECORD);
  952. RECORD(DECL_CXX_METHOD);
  953. RECORD(DECL_CXX_CONSTRUCTOR);
  954. RECORD(DECL_CXX_DESTRUCTOR);
  955. RECORD(DECL_CXX_CONVERSION);
  956. RECORD(DECL_ACCESS_SPEC);
  957. RECORD(DECL_FRIEND);
  958. RECORD(DECL_FRIEND_TEMPLATE);
  959. RECORD(DECL_CLASS_TEMPLATE);
  960. RECORD(DECL_CLASS_TEMPLATE_SPECIALIZATION);
  961. RECORD(DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION);
  962. RECORD(DECL_VAR_TEMPLATE);
  963. RECORD(DECL_VAR_TEMPLATE_SPECIALIZATION);
  964. RECORD(DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION);
  965. RECORD(DECL_FUNCTION_TEMPLATE);
  966. RECORD(DECL_TEMPLATE_TYPE_PARM);
  967. RECORD(DECL_NON_TYPE_TEMPLATE_PARM);
  968. RECORD(DECL_TEMPLATE_TEMPLATE_PARM);
  969. RECORD(DECL_STATIC_ASSERT);
  970. RECORD(DECL_CXX_BASE_SPECIFIERS);
  971. RECORD(DECL_INDIRECTFIELD);
  972. RECORD(DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK);
  973. // Statements and Exprs can occur in the Decls and Types block.
  974. AddStmtsExprs(Stream, Record);
  975. BLOCK(PREPROCESSOR_DETAIL_BLOCK);
  976. RECORD(PPD_MACRO_EXPANSION);
  977. RECORD(PPD_MACRO_DEFINITION);
  978. RECORD(PPD_INCLUSION_DIRECTIVE);
  979. #undef RECORD
  980. #undef BLOCK
  981. Stream.ExitBlock();
  982. }
  983. /// \brief Prepares a path for being written to an AST file by converting it
  984. /// to an absolute path and removing nested './'s.
  985. ///
  986. /// \return \c true if the path was changed.
  987. static bool cleanPathForOutput(FileManager &FileMgr,
  988. SmallVectorImpl<char> &Path) {
  989. bool Changed = false;
  990. if (!llvm::sys::path::is_absolute(StringRef(Path.data(), Path.size()))) {
  991. llvm::sys::fs::make_absolute(Path);
  992. Changed = true;
  993. }
  994. return Changed | FileMgr.removeDotPaths(Path);
  995. }
  996. /// \brief Adjusts the given filename to only write out the portion of the
  997. /// filename that is not part of the system root directory.
  998. ///
  999. /// \param Filename the file name to adjust.
  1000. ///
  1001. /// \param BaseDir When non-NULL, the PCH file is a relocatable AST file and
  1002. /// the returned filename will be adjusted by this root directory.
  1003. ///
  1004. /// \returns either the original filename (if it needs no adjustment) or the
  1005. /// adjusted filename (which points into the @p Filename parameter).
  1006. static const char *
  1007. adjustFilenameForRelocatableAST(const char *Filename, StringRef BaseDir) {
  1008. assert(Filename && "No file name to adjust?");
  1009. if (BaseDir.empty())
  1010. return Filename;
  1011. // Verify that the filename and the system root have the same prefix.
  1012. unsigned Pos = 0;
  1013. for (; Filename[Pos] && Pos < BaseDir.size(); ++Pos)
  1014. if (Filename[Pos] != BaseDir[Pos])
  1015. return Filename; // Prefixes don't match.
  1016. // We hit the end of the filename before we hit the end of the system root.
  1017. if (!Filename[Pos])
  1018. return Filename;
  1019. // If there's not a path separator at the end of the base directory nor
  1020. // immediately after it, then this isn't within the base directory.
  1021. if (!llvm::sys::path::is_separator(Filename[Pos])) {
  1022. if (!llvm::sys::path::is_separator(BaseDir.back()))
  1023. return Filename;
  1024. } else {
  1025. // If the file name has a '/' at the current position, skip over the '/'.
  1026. // We distinguish relative paths from absolute paths by the
  1027. // absence of '/' at the beginning of relative paths.
  1028. //
  1029. // FIXME: This is wrong. We distinguish them by asking if the path is
  1030. // absolute, which isn't the same thing. And there might be multiple '/'s
  1031. // in a row. Use a better mechanism to indicate whether we have emitted an
  1032. // absolute or relative path.
  1033. ++Pos;
  1034. }
  1035. return Filename + Pos;
  1036. }
  1037. static ASTFileSignature getSignature() {
  1038. while (1) {
  1039. if (ASTFileSignature S = llvm::sys::Process::GetRandomNumber())
  1040. return S;
  1041. // Rely on GetRandomNumber to eventually return non-zero...
  1042. }
  1043. }
  1044. /// \brief Write the control block.
  1045. void ASTWriter::WriteControlBlock(Preprocessor &PP, ASTContext &Context,
  1046. StringRef isysroot,
  1047. const std::string &OutputFile) {
  1048. using namespace llvm;
  1049. Stream.EnterSubblock(CONTROL_BLOCK_ID, 5);
  1050. RecordData Record;
  1051. // Metadata
  1052. BitCodeAbbrev *MetadataAbbrev = new BitCodeAbbrev();
  1053. MetadataAbbrev->Add(BitCodeAbbrevOp(METADATA));
  1054. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Major
  1055. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Minor
  1056. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang maj.
  1057. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 16)); // Clang min.
  1058. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Relocatable
  1059. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Errors
  1060. MetadataAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // SVN branch/tag
  1061. unsigned MetadataAbbrevCode = Stream.EmitAbbrev(MetadataAbbrev);
  1062. Record.push_back(METADATA);
  1063. Record.push_back(VERSION_MAJOR);
  1064. Record.push_back(VERSION_MINOR);
  1065. Record.push_back(CLANG_VERSION_MAJOR);
  1066. Record.push_back(CLANG_VERSION_MINOR);
  1067. assert((!WritingModule || isysroot.empty()) &&
  1068. "writing module as a relocatable PCH?");
  1069. Record.push_back(!isysroot.empty());
  1070. Record.push_back(ASTHasCompilerErrors);
  1071. Stream.EmitRecordWithBlob(MetadataAbbrevCode, Record,
  1072. getClangFullRepositoryVersion());
  1073. if (WritingModule) {
  1074. // For implicit modules we output a signature that we can use to ensure
  1075. // duplicate module builds don't collide in the cache as their output order
  1076. // is non-deterministic.
  1077. // FIXME: Remove this when output is deterministic.
  1078. if (Context.getLangOpts().ImplicitModules) {
  1079. Record.clear();
  1080. Record.push_back(getSignature());
  1081. Stream.EmitRecord(SIGNATURE, Record);
  1082. }
  1083. // Module name
  1084. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1085. Abbrev->Add(BitCodeAbbrevOp(MODULE_NAME));
  1086. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  1087. unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
  1088. RecordData Record;
  1089. Record.push_back(MODULE_NAME);
  1090. Stream.EmitRecordWithBlob(AbbrevCode, Record, WritingModule->Name);
  1091. }
  1092. if (WritingModule && WritingModule->Directory) {
  1093. // Module directory.
  1094. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1095. Abbrev->Add(BitCodeAbbrevOp(MODULE_DIRECTORY));
  1096. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Directory
  1097. unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
  1098. RecordData Record;
  1099. Record.push_back(MODULE_DIRECTORY);
  1100. SmallString<128> BaseDir(WritingModule->Directory->getName());
  1101. cleanPathForOutput(Context.getSourceManager().getFileManager(), BaseDir);
  1102. Stream.EmitRecordWithBlob(AbbrevCode, Record, BaseDir);
  1103. // Write out all other paths relative to the base directory if possible.
  1104. BaseDirectory.assign(BaseDir.begin(), BaseDir.end());
  1105. } else if (!isysroot.empty()) {
  1106. // Write out paths relative to the sysroot if possible.
  1107. BaseDirectory = isysroot;
  1108. }
  1109. // Module map file
  1110. if (WritingModule) {
  1111. Record.clear();
  1112. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  1113. // Primary module map file.
  1114. AddPath(Map.getModuleMapFileForUniquing(WritingModule)->getName(), Record);
  1115. // Additional module map files.
  1116. if (auto *AdditionalModMaps =
  1117. Map.getAdditionalModuleMapFiles(WritingModule)) {
  1118. Record.push_back(AdditionalModMaps->size());
  1119. for (const FileEntry *F : *AdditionalModMaps)
  1120. AddPath(F->getName(), Record);
  1121. } else {
  1122. Record.push_back(0);
  1123. }
  1124. Stream.EmitRecord(MODULE_MAP_FILE, Record);
  1125. }
  1126. // Imports
  1127. if (Chain) {
  1128. serialization::ModuleManager &Mgr = Chain->getModuleManager();
  1129. Record.clear();
  1130. for (auto *M : Mgr) {
  1131. // Skip modules that weren't directly imported.
  1132. if (!M->isDirectlyImported())
  1133. continue;
  1134. Record.push_back((unsigned)M->Kind); // FIXME: Stable encoding
  1135. AddSourceLocation(M->ImportLoc, Record);
  1136. Record.push_back(M->File->getSize());
  1137. Record.push_back(M->File->getModificationTime());
  1138. Record.push_back(M->Signature);
  1139. AddPath(M->FileName, Record);
  1140. }
  1141. Stream.EmitRecord(IMPORTS, Record);
  1142. // Also emit a list of known module files that were not imported,
  1143. // but are made available by this module.
  1144. // FIXME: Should we also include a signature here?
  1145. Record.clear();
  1146. for (auto *E : Mgr.getAdditionalKnownModuleFiles())
  1147. AddPath(E->getName(), Record);
  1148. if (!Record.empty())
  1149. Stream.EmitRecord(KNOWN_MODULE_FILES, Record);
  1150. }
  1151. // Language options.
  1152. Record.clear();
  1153. const LangOptions &LangOpts = Context.getLangOpts();
  1154. #define LANGOPT(Name, Bits, Default, Description) \
  1155. Record.push_back(LangOpts.Name);
  1156. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  1157. Record.push_back(static_cast<unsigned>(LangOpts.get##Name()));
  1158. #include "clang/Basic/LangOptions.fixed.def"
  1159. #define SANITIZER(NAME, ID) \
  1160. Record.push_back(LangOpts.Sanitize.has(SanitizerKind::ID));
  1161. #include "clang/Basic/Sanitizers.def"
  1162. Record.push_back(LangOpts.ModuleFeatures.size());
  1163. for (StringRef Feature : LangOpts.ModuleFeatures)
  1164. AddString(Feature, Record);
  1165. Record.push_back((unsigned) LangOpts.ObjCRuntime.getKind());
  1166. AddVersionTuple(LangOpts.ObjCRuntime.getVersion(), Record);
  1167. AddString(LangOpts.CurrentModule, Record);
  1168. // Comment options.
  1169. Record.push_back(LangOpts.CommentOpts.BlockCommandNames.size());
  1170. for (CommentOptions::BlockCommandNamesTy::const_iterator
  1171. I = LangOpts.CommentOpts.BlockCommandNames.begin(),
  1172. IEnd = LangOpts.CommentOpts.BlockCommandNames.end();
  1173. I != IEnd; ++I) {
  1174. AddString(*I, Record);
  1175. }
  1176. Record.push_back(LangOpts.CommentOpts.ParseAllComments);
  1177. Stream.EmitRecord(LANGUAGE_OPTIONS, Record);
  1178. // Target options.
  1179. Record.clear();
  1180. const TargetInfo &Target = Context.getTargetInfo();
  1181. const TargetOptions &TargetOpts = Target.getTargetOpts();
  1182. AddString(TargetOpts.Triple, Record);
  1183. AddString(TargetOpts.CPU, Record);
  1184. AddString(TargetOpts.ABI, Record);
  1185. Record.push_back(TargetOpts.FeaturesAsWritten.size());
  1186. for (unsigned I = 0, N = TargetOpts.FeaturesAsWritten.size(); I != N; ++I) {
  1187. AddString(TargetOpts.FeaturesAsWritten[I], Record);
  1188. }
  1189. Record.push_back(TargetOpts.Features.size());
  1190. for (unsigned I = 0, N = TargetOpts.Features.size(); I != N; ++I) {
  1191. AddString(TargetOpts.Features[I], Record);
  1192. }
  1193. Stream.EmitRecord(TARGET_OPTIONS, Record);
  1194. // Diagnostic options.
  1195. Record.clear();
  1196. const DiagnosticOptions &DiagOpts
  1197. = Context.getDiagnostics().getDiagnosticOptions();
  1198. #define DIAGOPT(Name, Bits, Default) Record.push_back(DiagOpts.Name);
  1199. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  1200. Record.push_back(static_cast<unsigned>(DiagOpts.get##Name()));
  1201. #include "clang/Basic/DiagnosticOptions.def"
  1202. Record.push_back(DiagOpts.Warnings.size());
  1203. for (unsigned I = 0, N = DiagOpts.Warnings.size(); I != N; ++I)
  1204. AddString(DiagOpts.Warnings[I], Record);
  1205. Record.push_back(DiagOpts.Remarks.size());
  1206. for (unsigned I = 0, N = DiagOpts.Remarks.size(); I != N; ++I)
  1207. AddString(DiagOpts.Remarks[I], Record);
  1208. // Note: we don't serialize the log or serialization file names, because they
  1209. // are generally transient files and will almost always be overridden.
  1210. Stream.EmitRecord(DIAGNOSTIC_OPTIONS, Record);
  1211. // File system options.
  1212. Record.clear();
  1213. const FileSystemOptions &FSOpts
  1214. = Context.getSourceManager().getFileManager().getFileSystemOptions();
  1215. AddString(FSOpts.WorkingDir, Record);
  1216. Stream.EmitRecord(FILE_SYSTEM_OPTIONS, Record);
  1217. // Header search options.
  1218. Record.clear();
  1219. const HeaderSearchOptions &HSOpts
  1220. = PP.getHeaderSearchInfo().getHeaderSearchOpts();
  1221. AddString(HSOpts.Sysroot, Record);
  1222. // Include entries.
  1223. Record.push_back(HSOpts.UserEntries.size());
  1224. for (unsigned I = 0, N = HSOpts.UserEntries.size(); I != N; ++I) {
  1225. const HeaderSearchOptions::Entry &Entry = HSOpts.UserEntries[I];
  1226. AddString(Entry.Path, Record);
  1227. Record.push_back(static_cast<unsigned>(Entry.Group));
  1228. Record.push_back(Entry.IsFramework);
  1229. Record.push_back(Entry.IgnoreSysRoot);
  1230. }
  1231. // System header prefixes.
  1232. Record.push_back(HSOpts.SystemHeaderPrefixes.size());
  1233. for (unsigned I = 0, N = HSOpts.SystemHeaderPrefixes.size(); I != N; ++I) {
  1234. AddString(HSOpts.SystemHeaderPrefixes[I].Prefix, Record);
  1235. Record.push_back(HSOpts.SystemHeaderPrefixes[I].IsSystemHeader);
  1236. }
  1237. AddString(HSOpts.ResourceDir, Record);
  1238. AddString(HSOpts.ModuleCachePath, Record);
  1239. AddString(HSOpts.ModuleUserBuildPath, Record);
  1240. Record.push_back(HSOpts.DisableModuleHash);
  1241. Record.push_back(HSOpts.UseBuiltinIncludes);
  1242. Record.push_back(HSOpts.UseStandardSystemIncludes);
  1243. Record.push_back(HSOpts.UseStandardCXXIncludes);
  1244. Record.push_back(HSOpts.UseLibcxx);
  1245. // Write out the specific module cache path that contains the module files.
  1246. AddString(PP.getHeaderSearchInfo().getModuleCachePath(), Record);
  1247. Stream.EmitRecord(HEADER_SEARCH_OPTIONS, Record);
  1248. // Preprocessor options.
  1249. Record.clear();
  1250. const PreprocessorOptions &PPOpts = PP.getPreprocessorOpts();
  1251. // Macro definitions.
  1252. Record.push_back(PPOpts.Macros.size());
  1253. for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
  1254. AddString(PPOpts.Macros[I].first, Record);
  1255. Record.push_back(PPOpts.Macros[I].second);
  1256. }
  1257. // Includes
  1258. Record.push_back(PPOpts.Includes.size());
  1259. for (unsigned I = 0, N = PPOpts.Includes.size(); I != N; ++I)
  1260. AddString(PPOpts.Includes[I], Record);
  1261. // Macro includes
  1262. Record.push_back(PPOpts.MacroIncludes.size());
  1263. for (unsigned I = 0, N = PPOpts.MacroIncludes.size(); I != N; ++I)
  1264. AddString(PPOpts.MacroIncludes[I], Record);
  1265. Record.push_back(PPOpts.UsePredefines);
  1266. // Detailed record is important since it is used for the module cache hash.
  1267. Record.push_back(PPOpts.DetailedRecord);
  1268. AddString(PPOpts.ImplicitPCHInclude, Record);
  1269. AddString(PPOpts.ImplicitPTHInclude, Record);
  1270. Record.push_back(static_cast<unsigned>(PPOpts.ObjCXXARCStandardLibrary));
  1271. Stream.EmitRecord(PREPROCESSOR_OPTIONS, Record);
  1272. // Original file name and file ID
  1273. SourceManager &SM = Context.getSourceManager();
  1274. if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
  1275. BitCodeAbbrev *FileAbbrev = new BitCodeAbbrev();
  1276. FileAbbrev->Add(BitCodeAbbrevOp(ORIGINAL_FILE));
  1277. FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // File ID
  1278. FileAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1279. unsigned FileAbbrevCode = Stream.EmitAbbrev(FileAbbrev);
  1280. Record.clear();
  1281. Record.push_back(ORIGINAL_FILE);
  1282. Record.push_back(SM.getMainFileID().getOpaqueValue());
  1283. EmitRecordWithPath(FileAbbrevCode, Record, MainFile->getName());
  1284. }
  1285. Record.clear();
  1286. Record.push_back(SM.getMainFileID().getOpaqueValue());
  1287. Stream.EmitRecord(ORIGINAL_FILE_ID, Record);
  1288. // Original PCH directory
  1289. if (!OutputFile.empty() && OutputFile != "-") {
  1290. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1291. Abbrev->Add(BitCodeAbbrevOp(ORIGINAL_PCH_DIR));
  1292. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1293. unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
  1294. SmallString<128> OutputPath(OutputFile);
  1295. llvm::sys::fs::make_absolute(OutputPath);
  1296. StringRef origDir = llvm::sys::path::parent_path(OutputPath);
  1297. RecordData Record;
  1298. Record.push_back(ORIGINAL_PCH_DIR);
  1299. Stream.EmitRecordWithBlob(AbbrevCode, Record, origDir);
  1300. }
  1301. WriteInputFiles(Context.SourceMgr,
  1302. PP.getHeaderSearchInfo().getHeaderSearchOpts(),
  1303. PP.getLangOpts().Modules);
  1304. Stream.ExitBlock();
  1305. }
  1306. namespace {
  1307. /// \brief An input file.
  1308. struct InputFileEntry {
  1309. const FileEntry *File;
  1310. bool IsSystemFile;
  1311. bool BufferOverridden;
  1312. };
  1313. }
  1314. void ASTWriter::WriteInputFiles(SourceManager &SourceMgr,
  1315. HeaderSearchOptions &HSOpts,
  1316. bool Modules) {
  1317. using namespace llvm;
  1318. Stream.EnterSubblock(INPUT_FILES_BLOCK_ID, 4);
  1319. RecordData Record;
  1320. // Create input-file abbreviation.
  1321. BitCodeAbbrev *IFAbbrev = new BitCodeAbbrev();
  1322. IFAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE));
  1323. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
  1324. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 12)); // Size
  1325. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 32)); // Modification time
  1326. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Overridden
  1327. IFAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // File name
  1328. unsigned IFAbbrevCode = Stream.EmitAbbrev(IFAbbrev);
  1329. // Get all ContentCache objects for files, sorted by whether the file is a
  1330. // system one or not. System files go at the back, users files at the front.
  1331. std::deque<InputFileEntry> SortedFiles;
  1332. for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
  1333. // Get this source location entry.
  1334. const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
  1335. assert(&SourceMgr.getSLocEntry(FileID::get(I)) == SLoc);
  1336. // We only care about file entries that were not overridden.
  1337. if (!SLoc->isFile())
  1338. continue;
  1339. const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
  1340. if (!Cache->OrigEntry)
  1341. continue;
  1342. InputFileEntry Entry;
  1343. Entry.File = Cache->OrigEntry;
  1344. Entry.IsSystemFile = Cache->IsSystemFile;
  1345. Entry.BufferOverridden = Cache->BufferOverridden;
  1346. if (Cache->IsSystemFile)
  1347. SortedFiles.push_back(Entry);
  1348. else
  1349. SortedFiles.push_front(Entry);
  1350. }
  1351. unsigned UserFilesNum = 0;
  1352. // Write out all of the input files.
  1353. std::vector<uint64_t> InputFileOffsets;
  1354. for (std::deque<InputFileEntry>::iterator
  1355. I = SortedFiles.begin(), E = SortedFiles.end(); I != E; ++I) {
  1356. const InputFileEntry &Entry = *I;
  1357. uint32_t &InputFileID = InputFileIDs[Entry.File];
  1358. if (InputFileID != 0)
  1359. continue; // already recorded this file.
  1360. // Record this entry's offset.
  1361. InputFileOffsets.push_back(Stream.GetCurrentBitNo());
  1362. InputFileID = InputFileOffsets.size();
  1363. if (!Entry.IsSystemFile)
  1364. ++UserFilesNum;
  1365. Record.clear();
  1366. Record.push_back(INPUT_FILE);
  1367. Record.push_back(InputFileOffsets.size());
  1368. // Emit size/modification time for this file.
  1369. Record.push_back(Entry.File->getSize());
  1370. Record.push_back(Entry.File->getModificationTime());
  1371. // Whether this file was overridden.
  1372. Record.push_back(Entry.BufferOverridden);
  1373. EmitRecordWithPath(IFAbbrevCode, Record, Entry.File->getName());
  1374. }
  1375. Stream.ExitBlock();
  1376. // Create input file offsets abbreviation.
  1377. BitCodeAbbrev *OffsetsAbbrev = new BitCodeAbbrev();
  1378. OffsetsAbbrev->Add(BitCodeAbbrevOp(INPUT_FILE_OFFSETS));
  1379. OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # input files
  1380. OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # non-system
  1381. // input files
  1382. OffsetsAbbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Array
  1383. unsigned OffsetsAbbrevCode = Stream.EmitAbbrev(OffsetsAbbrev);
  1384. // Write input file offsets.
  1385. Record.clear();
  1386. Record.push_back(INPUT_FILE_OFFSETS);
  1387. Record.push_back(InputFileOffsets.size());
  1388. Record.push_back(UserFilesNum);
  1389. Stream.EmitRecordWithBlob(OffsetsAbbrevCode, Record, bytes(InputFileOffsets));
  1390. }
  1391. //===----------------------------------------------------------------------===//
  1392. // Source Manager Serialization
  1393. //===----------------------------------------------------------------------===//
  1394. /// \brief Create an abbreviation for the SLocEntry that refers to a
  1395. /// file.
  1396. static unsigned CreateSLocFileAbbrev(llvm::BitstreamWriter &Stream) {
  1397. using namespace llvm;
  1398. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1399. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_FILE_ENTRY));
  1400. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1401. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
  1402. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
  1403. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
  1404. // FileEntry fields.
  1405. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Input File ID
  1406. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumCreatedFIDs
  1407. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 24)); // FirstDeclIndex
  1408. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // NumDecls
  1409. return Stream.EmitAbbrev(Abbrev);
  1410. }
  1411. /// \brief Create an abbreviation for the SLocEntry that refers to a
  1412. /// buffer.
  1413. static unsigned CreateSLocBufferAbbrev(llvm::BitstreamWriter &Stream) {
  1414. using namespace llvm;
  1415. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1416. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_ENTRY));
  1417. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1418. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Include location
  1419. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // Characteristic
  1420. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // Line directives
  1421. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Buffer name blob
  1422. return Stream.EmitAbbrev(Abbrev);
  1423. }
  1424. /// \brief Create an abbreviation for the SLocEntry that refers to a
  1425. /// buffer's blob.
  1426. static unsigned CreateSLocBufferBlobAbbrev(llvm::BitstreamWriter &Stream) {
  1427. using namespace llvm;
  1428. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1429. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_BUFFER_BLOB));
  1430. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Blob
  1431. return Stream.EmitAbbrev(Abbrev);
  1432. }
  1433. /// \brief Create an abbreviation for the SLocEntry that refers to a macro
  1434. /// expansion.
  1435. static unsigned CreateSLocExpansionAbbrev(llvm::BitstreamWriter &Stream) {
  1436. using namespace llvm;
  1437. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1438. Abbrev->Add(BitCodeAbbrevOp(SM_SLOC_EXPANSION_ENTRY));
  1439. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Offset
  1440. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Spelling location
  1441. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // Start location
  1442. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 8)); // End location
  1443. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Token length
  1444. return Stream.EmitAbbrev(Abbrev);
  1445. }
  1446. namespace {
  1447. // Trait used for the on-disk hash table of header search information.
  1448. class HeaderFileInfoTrait {
  1449. ASTWriter &Writer;
  1450. const HeaderSearch &HS;
  1451. // Keep track of the framework names we've used during serialization.
  1452. SmallVector<char, 128> FrameworkStringData;
  1453. llvm::StringMap<unsigned> FrameworkNameOffset;
  1454. public:
  1455. HeaderFileInfoTrait(ASTWriter &Writer, const HeaderSearch &HS)
  1456. : Writer(Writer), HS(HS) { }
  1457. struct key_type {
  1458. const FileEntry *FE;
  1459. const char *Filename;
  1460. };
  1461. typedef const key_type &key_type_ref;
  1462. typedef HeaderFileInfo data_type;
  1463. typedef const data_type &data_type_ref;
  1464. typedef unsigned hash_value_type;
  1465. typedef unsigned offset_type;
  1466. static hash_value_type ComputeHash(key_type_ref key) {
  1467. // The hash is based only on size/time of the file, so that the reader can
  1468. // match even when symlinking or excess path elements ("foo/../", "../")
  1469. // change the form of the name. However, complete path is still the key.
  1470. //
  1471. // FIXME: Using the mtime here will cause problems for explicit module
  1472. // imports.
  1473. return llvm::hash_combine(key.FE->getSize(),
  1474. key.FE->getModificationTime());
  1475. }
  1476. std::pair<unsigned,unsigned>
  1477. EmitKeyDataLength(raw_ostream& Out, key_type_ref key, data_type_ref Data) {
  1478. using namespace llvm::support;
  1479. endian::Writer<little> Writer(Out);
  1480. unsigned KeyLen = strlen(key.Filename) + 1 + 8 + 8;
  1481. Writer.write<uint16_t>(KeyLen);
  1482. unsigned DataLen = 1 + 2 + 4 + 4;
  1483. if (Data.isModuleHeader)
  1484. DataLen += 4;
  1485. Writer.write<uint8_t>(DataLen);
  1486. return std::make_pair(KeyLen, DataLen);
  1487. }
  1488. void EmitKey(raw_ostream& Out, key_type_ref key, unsigned KeyLen) {
  1489. using namespace llvm::support;
  1490. endian::Writer<little> LE(Out);
  1491. LE.write<uint64_t>(key.FE->getSize());
  1492. KeyLen -= 8;
  1493. LE.write<uint64_t>(key.FE->getModificationTime());
  1494. KeyLen -= 8;
  1495. Out.write(key.Filename, KeyLen);
  1496. }
  1497. void EmitData(raw_ostream &Out, key_type_ref key,
  1498. data_type_ref Data, unsigned DataLen) {
  1499. using namespace llvm::support;
  1500. endian::Writer<little> LE(Out);
  1501. uint64_t Start = Out.tell(); (void)Start;
  1502. unsigned char Flags = (Data.HeaderRole << 6)
  1503. | (Data.isImport << 5)
  1504. | (Data.isPragmaOnce << 4)
  1505. | (Data.DirInfo << 2)
  1506. | (Data.Resolved << 1)
  1507. | Data.IndexHeaderMapHeader;
  1508. LE.write<uint8_t>(Flags);
  1509. LE.write<uint16_t>(Data.NumIncludes);
  1510. if (!Data.ControllingMacro)
  1511. LE.write<uint32_t>(Data.ControllingMacroID);
  1512. else
  1513. LE.write<uint32_t>(Writer.getIdentifierRef(Data.ControllingMacro));
  1514. unsigned Offset = 0;
  1515. if (!Data.Framework.empty()) {
  1516. // If this header refers into a framework, save the framework name.
  1517. llvm::StringMap<unsigned>::iterator Pos
  1518. = FrameworkNameOffset.find(Data.Framework);
  1519. if (Pos == FrameworkNameOffset.end()) {
  1520. Offset = FrameworkStringData.size() + 1;
  1521. FrameworkStringData.append(Data.Framework.begin(),
  1522. Data.Framework.end());
  1523. FrameworkStringData.push_back(0);
  1524. FrameworkNameOffset[Data.Framework] = Offset;
  1525. } else
  1526. Offset = Pos->second;
  1527. }
  1528. LE.write<uint32_t>(Offset);
  1529. if (Data.isModuleHeader) {
  1530. Module *Mod = HS.findModuleForHeader(key.FE).getModule();
  1531. LE.write<uint32_t>(Writer.getExistingSubmoduleID(Mod));
  1532. }
  1533. assert(Out.tell() - Start == DataLen && "Wrong data length");
  1534. }
  1535. const char *strings_begin() const { return FrameworkStringData.begin(); }
  1536. const char *strings_end() const { return FrameworkStringData.end(); }
  1537. };
  1538. } // end anonymous namespace
  1539. /// \brief Write the header search block for the list of files that
  1540. ///
  1541. /// \param HS The header search structure to save.
  1542. void ASTWriter::WriteHeaderSearch(const HeaderSearch &HS) {
  1543. SmallVector<const FileEntry *, 16> FilesByUID;
  1544. HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
  1545. if (FilesByUID.size() > HS.header_file_size())
  1546. FilesByUID.resize(HS.header_file_size());
  1547. HeaderFileInfoTrait GeneratorTrait(*this, HS);
  1548. llvm::OnDiskChainedHashTableGenerator<HeaderFileInfoTrait> Generator;
  1549. SmallVector<const char *, 4> SavedStrings;
  1550. unsigned NumHeaderSearchEntries = 0;
  1551. for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
  1552. const FileEntry *File = FilesByUID[UID];
  1553. if (!File)
  1554. continue;
  1555. // Use HeaderSearch's getFileInfo to make sure we get the HeaderFileInfo
  1556. // from the external source if it was not provided already.
  1557. HeaderFileInfo HFI;
  1558. if (!HS.tryGetFileInfo(File, HFI) ||
  1559. (HFI.External && Chain) ||
  1560. (HFI.isModuleHeader && !HFI.isCompilingModuleHeader))
  1561. continue;
  1562. // Massage the file path into an appropriate form.
  1563. const char *Filename = File->getName();
  1564. SmallString<128> FilenameTmp(Filename);
  1565. if (PreparePathForOutput(FilenameTmp)) {
  1566. // If we performed any translation on the file name at all, we need to
  1567. // save this string, since the generator will refer to it later.
  1568. Filename = _strdup(FilenameTmp.c_str());
  1569. SavedStrings.push_back(Filename);
  1570. }
  1571. HeaderFileInfoTrait::key_type key = { File, Filename };
  1572. Generator.insert(key, HFI, GeneratorTrait);
  1573. ++NumHeaderSearchEntries;
  1574. }
  1575. // Create the on-disk hash table in a buffer.
  1576. SmallString<4096> TableData;
  1577. uint32_t BucketOffset;
  1578. {
  1579. using namespace llvm::support;
  1580. llvm::raw_svector_ostream Out(TableData);
  1581. // Make sure that no bucket is at offset 0
  1582. endian::Writer<little>(Out).write<uint32_t>(0);
  1583. BucketOffset = Generator.Emit(Out, GeneratorTrait);
  1584. }
  1585. // Create a blob abbreviation
  1586. using namespace llvm;
  1587. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1588. Abbrev->Add(BitCodeAbbrevOp(HEADER_SEARCH_TABLE));
  1589. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1590. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1591. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  1592. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1593. unsigned TableAbbrev = Stream.EmitAbbrev(Abbrev);
  1594. // Write the header search table
  1595. RecordData Record;
  1596. Record.push_back(HEADER_SEARCH_TABLE);
  1597. Record.push_back(BucketOffset);
  1598. Record.push_back(NumHeaderSearchEntries);
  1599. Record.push_back(TableData.size());
  1600. TableData.append(GeneratorTrait.strings_begin(),GeneratorTrait.strings_end());
  1601. Stream.EmitRecordWithBlob(TableAbbrev, Record, TableData);
  1602. // Free all of the strings we had to duplicate.
  1603. for (unsigned I = 0, N = SavedStrings.size(); I != N; ++I)
  1604. free(const_cast<char *>(SavedStrings[I]));
  1605. }
  1606. /// \brief Writes the block containing the serialized form of the
  1607. /// source manager.
  1608. ///
  1609. /// TODO: We should probably use an on-disk hash table (stored in a
  1610. /// blob), indexed based on the file name, so that we only create
  1611. /// entries for files that we actually need. In the common case (no
  1612. /// errors), we probably won't have to create file entries for any of
  1613. /// the files in the AST.
  1614. void ASTWriter::WriteSourceManagerBlock(SourceManager &SourceMgr,
  1615. const Preprocessor &PP) {
  1616. RecordData Record;
  1617. // Enter the source manager block.
  1618. Stream.EnterSubblock(SOURCE_MANAGER_BLOCK_ID, 3);
  1619. // Abbreviations for the various kinds of source-location entries.
  1620. unsigned SLocFileAbbrv = CreateSLocFileAbbrev(Stream);
  1621. unsigned SLocBufferAbbrv = CreateSLocBufferAbbrev(Stream);
  1622. unsigned SLocBufferBlobAbbrv = CreateSLocBufferBlobAbbrev(Stream);
  1623. unsigned SLocExpansionAbbrv = CreateSLocExpansionAbbrev(Stream);
  1624. // Write out the source location entry table. We skip the first
  1625. // entry, which is always the same dummy entry.
  1626. std::vector<uint32_t> SLocEntryOffsets;
  1627. RecordData PreloadSLocs;
  1628. SLocEntryOffsets.reserve(SourceMgr.local_sloc_entry_size() - 1);
  1629. for (unsigned I = 1, N = SourceMgr.local_sloc_entry_size();
  1630. I != N; ++I) {
  1631. // Get this source location entry.
  1632. const SrcMgr::SLocEntry *SLoc = &SourceMgr.getLocalSLocEntry(I);
  1633. FileID FID = FileID::get(I);
  1634. assert(&SourceMgr.getSLocEntry(FID) == SLoc);
  1635. // Record the offset of this source-location entry.
  1636. SLocEntryOffsets.push_back(Stream.GetCurrentBitNo());
  1637. // Figure out which record code to use.
  1638. unsigned Code;
  1639. if (SLoc->isFile()) {
  1640. const SrcMgr::ContentCache *Cache = SLoc->getFile().getContentCache();
  1641. if (Cache->OrigEntry) {
  1642. Code = SM_SLOC_FILE_ENTRY;
  1643. } else
  1644. Code = SM_SLOC_BUFFER_ENTRY;
  1645. } else
  1646. Code = SM_SLOC_EXPANSION_ENTRY;
  1647. Record.clear();
  1648. Record.push_back(Code);
  1649. // Starting offset of this entry within this module, so skip the dummy.
  1650. Record.push_back(SLoc->getOffset() - 2);
  1651. if (SLoc->isFile()) {
  1652. const SrcMgr::FileInfo &File = SLoc->getFile();
  1653. Record.push_back(File.getIncludeLoc().getRawEncoding());
  1654. Record.push_back(File.getFileCharacteristic()); // FIXME: stable encoding
  1655. Record.push_back(File.hasLineDirectives());
  1656. const SrcMgr::ContentCache *Content = File.getContentCache();
  1657. if (Content->OrigEntry) {
  1658. assert(Content->OrigEntry == Content->ContentsEntry &&
  1659. "Writing to AST an overridden file is not supported");
  1660. // The source location entry is a file. Emit input file ID.
  1661. assert(InputFileIDs[Content->OrigEntry] != 0 && "Missed file entry");
  1662. Record.push_back(InputFileIDs[Content->OrigEntry]);
  1663. Record.push_back(File.NumCreatedFIDs);
  1664. FileDeclIDsTy::iterator FDI = FileDeclIDs.find(FID);
  1665. if (FDI != FileDeclIDs.end()) {
  1666. Record.push_back(FDI->second->FirstDeclIndex);
  1667. Record.push_back(FDI->second->DeclIDs.size());
  1668. } else {
  1669. Record.push_back(0);
  1670. Record.push_back(0);
  1671. }
  1672. Stream.EmitRecordWithAbbrev(SLocFileAbbrv, Record);
  1673. if (Content->BufferOverridden) {
  1674. Record.clear();
  1675. Record.push_back(SM_SLOC_BUFFER_BLOB);
  1676. const llvm::MemoryBuffer *Buffer
  1677. = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
  1678. Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
  1679. StringRef(Buffer->getBufferStart(),
  1680. Buffer->getBufferSize() + 1));
  1681. }
  1682. } else {
  1683. // The source location entry is a buffer. The blob associated
  1684. // with this entry contains the contents of the buffer.
  1685. // We add one to the size so that we capture the trailing NULL
  1686. // that is required by llvm::MemoryBuffer::getMemBuffer (on
  1687. // the reader side).
  1688. const llvm::MemoryBuffer *Buffer
  1689. = Content->getBuffer(PP.getDiagnostics(), PP.getSourceManager());
  1690. const char *Name = Buffer->getBufferIdentifier();
  1691. Stream.EmitRecordWithBlob(SLocBufferAbbrv, Record,
  1692. StringRef(Name, strlen(Name) + 1));
  1693. Record.clear();
  1694. Record.push_back(SM_SLOC_BUFFER_BLOB);
  1695. Stream.EmitRecordWithBlob(SLocBufferBlobAbbrv, Record,
  1696. StringRef(Buffer->getBufferStart(),
  1697. Buffer->getBufferSize() + 1));
  1698. if (strcmp(Name, "<built-in>") == 0) {
  1699. PreloadSLocs.push_back(SLocEntryOffsets.size());
  1700. }
  1701. }
  1702. } else {
  1703. // The source location entry is a macro expansion.
  1704. const SrcMgr::ExpansionInfo &Expansion = SLoc->getExpansion();
  1705. Record.push_back(Expansion.getSpellingLoc().getRawEncoding());
  1706. Record.push_back(Expansion.getExpansionLocStart().getRawEncoding());
  1707. Record.push_back(Expansion.isMacroArgExpansion() ? 0
  1708. : Expansion.getExpansionLocEnd().getRawEncoding());
  1709. // Compute the token length for this macro expansion.
  1710. unsigned NextOffset = SourceMgr.getNextLocalOffset();
  1711. if (I + 1 != N)
  1712. NextOffset = SourceMgr.getLocalSLocEntry(I + 1).getOffset();
  1713. Record.push_back(NextOffset - SLoc->getOffset() - 1);
  1714. Stream.EmitRecordWithAbbrev(SLocExpansionAbbrv, Record);
  1715. }
  1716. }
  1717. Stream.ExitBlock();
  1718. if (SLocEntryOffsets.empty())
  1719. return;
  1720. // Write the source-location offsets table into the AST block. This
  1721. // table is used for lazily loading source-location information.
  1722. using namespace llvm;
  1723. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1724. Abbrev->Add(BitCodeAbbrevOp(SOURCE_LOCATION_OFFSETS));
  1725. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // # of slocs
  1726. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 16)); // total size
  1727. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // offsets
  1728. unsigned SLocOffsetsAbbrev = Stream.EmitAbbrev(Abbrev);
  1729. Record.clear();
  1730. Record.push_back(SOURCE_LOCATION_OFFSETS);
  1731. Record.push_back(SLocEntryOffsets.size());
  1732. Record.push_back(SourceMgr.getNextLocalOffset() - 1); // skip dummy
  1733. Stream.EmitRecordWithBlob(SLocOffsetsAbbrev, Record, bytes(SLocEntryOffsets));
  1734. // Write the source location entry preloads array, telling the AST
  1735. // reader which source locations entries it should load eagerly.
  1736. Stream.EmitRecord(SOURCE_LOCATION_PRELOADS, PreloadSLocs);
  1737. // Write the line table. It depends on remapping working, so it must come
  1738. // after the source location offsets.
  1739. if (SourceMgr.hasLineTable()) {
  1740. LineTableInfo &LineTable = SourceMgr.getLineTable();
  1741. Record.clear();
  1742. // Emit the file names.
  1743. Record.push_back(LineTable.getNumFilenames());
  1744. for (unsigned I = 0, N = LineTable.getNumFilenames(); I != N; ++I)
  1745. AddPath(LineTable.getFilename(I), Record);
  1746. // Emit the line entries
  1747. for (LineTableInfo::iterator L = LineTable.begin(), LEnd = LineTable.end();
  1748. L != LEnd; ++L) {
  1749. // Only emit entries for local files.
  1750. if (L->first.ID < 0)
  1751. continue;
  1752. // Emit the file ID
  1753. Record.push_back(L->first.ID);
  1754. // Emit the line entries
  1755. Record.push_back(L->second.size());
  1756. for (std::vector<LineEntry>::iterator LE = L->second.begin(),
  1757. LEEnd = L->second.end();
  1758. LE != LEEnd; ++LE) {
  1759. Record.push_back(LE->FileOffset);
  1760. Record.push_back(LE->LineNo);
  1761. Record.push_back(LE->FilenameID);
  1762. Record.push_back((unsigned)LE->FileKind);
  1763. Record.push_back(LE->IncludeOffset);
  1764. }
  1765. }
  1766. Stream.EmitRecord(SOURCE_MANAGER_LINE_TABLE, Record);
  1767. }
  1768. }
  1769. //===----------------------------------------------------------------------===//
  1770. // Preprocessor Serialization
  1771. //===----------------------------------------------------------------------===//
  1772. static bool shouldIgnoreMacro(MacroDirective *MD, bool IsModule,
  1773. const Preprocessor &PP) {
  1774. if (MacroInfo *MI = MD->getMacroInfo())
  1775. if (MI->isBuiltinMacro())
  1776. return true;
  1777. if (IsModule) {
  1778. SourceLocation Loc = MD->getLocation();
  1779. if (Loc.isInvalid())
  1780. return true;
  1781. if (PP.getSourceManager().getFileID(Loc) == PP.getPredefinesFileID())
  1782. return true;
  1783. }
  1784. return false;
  1785. }
  1786. /// \brief Writes the block containing the serialized form of the
  1787. /// preprocessor.
  1788. ///
  1789. void ASTWriter::WritePreprocessor(const Preprocessor &PP, bool IsModule) {
  1790. PreprocessingRecord *PPRec = PP.getPreprocessingRecord();
  1791. if (PPRec)
  1792. WritePreprocessorDetail(*PPRec);
  1793. RecordData Record;
  1794. RecordData ModuleMacroRecord;
  1795. // If the preprocessor __COUNTER__ value has been bumped, remember it.
  1796. if (PP.getCounterValue() != 0) {
  1797. Record.push_back(PP.getCounterValue());
  1798. Stream.EmitRecord(PP_COUNTER_VALUE, Record);
  1799. Record.clear();
  1800. }
  1801. // Enter the preprocessor block.
  1802. Stream.EnterSubblock(PREPROCESSOR_BLOCK_ID, 3);
  1803. // If the AST file contains __DATE__ or __TIME__ emit a warning about this.
  1804. // FIXME: use diagnostics subsystem for localization etc.
  1805. if (PP.SawDateOrTime())
  1806. fprintf(stderr, "warning: precompiled header used __DATE__ or __TIME__.\n");
  1807. // Loop over all the macro directives that are live at the end of the file,
  1808. // emitting each to the PP section.
  1809. // Construct the list of identifiers with macro directives that need to be
  1810. // serialized.
  1811. SmallVector<const IdentifierInfo *, 128> MacroIdentifiers;
  1812. for (auto &Id : PP.getIdentifierTable())
  1813. if (Id.second->hadMacroDefinition() &&
  1814. (!Id.second->isFromAST() ||
  1815. Id.second->hasChangedSinceDeserialization()))
  1816. MacroIdentifiers.push_back(Id.second);
  1817. // Sort the set of macro definitions that need to be serialized by the
  1818. // name of the macro, to provide a stable ordering.
  1819. std::sort(MacroIdentifiers.begin(), MacroIdentifiers.end(),
  1820. llvm::less_ptr<IdentifierInfo>());
  1821. // Emit the macro directives as a list and associate the offset with the
  1822. // identifier they belong to.
  1823. for (const IdentifierInfo *Name : MacroIdentifiers) {
  1824. MacroDirective *MD = PP.getLocalMacroDirectiveHistory(Name);
  1825. auto StartOffset = Stream.GetCurrentBitNo();
  1826. // Emit the macro directives in reverse source order.
  1827. for (; MD; MD = MD->getPrevious()) {
  1828. // Once we hit an ignored macro, we're done: the rest of the chain
  1829. // will all be ignored macros.
  1830. if (shouldIgnoreMacro(MD, IsModule, PP))
  1831. break;
  1832. AddSourceLocation(MD->getLocation(), Record);
  1833. Record.push_back(MD->getKind());
  1834. if (auto *DefMD = dyn_cast<DefMacroDirective>(MD)) {
  1835. Record.push_back(getMacroRef(DefMD->getInfo(), Name));
  1836. } else if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
  1837. Record.push_back(VisMD->isPublic());
  1838. }
  1839. }
  1840. // Write out any exported module macros.
  1841. bool EmittedModuleMacros = false;
  1842. if (IsModule) {
  1843. auto Leafs = PP.getLeafModuleMacros(Name);
  1844. SmallVector<ModuleMacro*, 8> Worklist(Leafs.begin(), Leafs.end());
  1845. llvm::DenseMap<ModuleMacro*, unsigned> Visits;
  1846. while (!Worklist.empty()) {
  1847. auto *Macro = Worklist.pop_back_val();
  1848. // Emit a record indicating this submodule exports this macro.
  1849. ModuleMacroRecord.push_back(
  1850. getSubmoduleID(Macro->getOwningModule()));
  1851. ModuleMacroRecord.push_back(getMacroRef(Macro->getMacroInfo(), Name));
  1852. for (auto *M : Macro->overrides())
  1853. ModuleMacroRecord.push_back(getSubmoduleID(M->getOwningModule()));
  1854. Stream.EmitRecord(PP_MODULE_MACRO, ModuleMacroRecord);
  1855. ModuleMacroRecord.clear();
  1856. // Enqueue overridden macros once we've visited all their ancestors.
  1857. for (auto *M : Macro->overrides())
  1858. if (++Visits[M] == M->getNumOverridingMacros())
  1859. Worklist.push_back(M);
  1860. EmittedModuleMacros = true;
  1861. }
  1862. }
  1863. if (Record.empty() && !EmittedModuleMacros)
  1864. continue;
  1865. IdentMacroDirectivesOffsetMap[Name] = StartOffset;
  1866. Stream.EmitRecord(PP_MACRO_DIRECTIVE_HISTORY, Record);
  1867. Record.clear();
  1868. }
  1869. /// \brief Offsets of each of the macros into the bitstream, indexed by
  1870. /// the local macro ID
  1871. ///
  1872. /// For each identifier that is associated with a macro, this map
  1873. /// provides the offset into the bitstream where that macro is
  1874. /// defined.
  1875. std::vector<uint32_t> MacroOffsets;
  1876. for (unsigned I = 0, N = MacroInfosToEmit.size(); I != N; ++I) {
  1877. const IdentifierInfo *Name = MacroInfosToEmit[I].Name;
  1878. MacroInfo *MI = MacroInfosToEmit[I].MI;
  1879. MacroID ID = MacroInfosToEmit[I].ID;
  1880. if (ID < FirstMacroID) {
  1881. assert(0 && "Loaded MacroInfo entered MacroInfosToEmit ?");
  1882. continue;
  1883. }
  1884. // Record the local offset of this macro.
  1885. unsigned Index = ID - FirstMacroID;
  1886. if (Index == MacroOffsets.size())
  1887. MacroOffsets.push_back(Stream.GetCurrentBitNo());
  1888. else {
  1889. if (Index > MacroOffsets.size())
  1890. MacroOffsets.resize(Index + 1);
  1891. MacroOffsets[Index] = Stream.GetCurrentBitNo();
  1892. }
  1893. AddIdentifierRef(Name, Record);
  1894. Record.push_back(inferSubmoduleIDFromLocation(MI->getDefinitionLoc()));
  1895. AddSourceLocation(MI->getDefinitionLoc(), Record);
  1896. AddSourceLocation(MI->getDefinitionEndLoc(), Record);
  1897. Record.push_back(MI->isUsed());
  1898. Record.push_back(MI->isUsedForHeaderGuard());
  1899. unsigned Code;
  1900. if (MI->isObjectLike()) {
  1901. Code = PP_MACRO_OBJECT_LIKE;
  1902. } else {
  1903. Code = PP_MACRO_FUNCTION_LIKE;
  1904. Record.push_back(MI->isC99Varargs());
  1905. Record.push_back(MI->isGNUVarargs());
  1906. Record.push_back(MI->hasCommaPasting());
  1907. Record.push_back(MI->getNumArgs());
  1908. for (const IdentifierInfo *Arg : MI->args())
  1909. AddIdentifierRef(Arg, Record);
  1910. }
  1911. // If we have a detailed preprocessing record, record the macro definition
  1912. // ID that corresponds to this macro.
  1913. if (PPRec)
  1914. Record.push_back(MacroDefinitions[PPRec->findMacroDefinition(MI)]);
  1915. Stream.EmitRecord(Code, Record);
  1916. Record.clear();
  1917. // Emit the tokens array.
  1918. for (unsigned TokNo = 0, e = MI->getNumTokens(); TokNo != e; ++TokNo) {
  1919. // Note that we know that the preprocessor does not have any annotation
  1920. // tokens in it because they are created by the parser, and thus can't
  1921. // be in a macro definition.
  1922. const Token &Tok = MI->getReplacementToken(TokNo);
  1923. AddToken(Tok, Record);
  1924. Stream.EmitRecord(PP_TOKEN, Record);
  1925. Record.clear();
  1926. }
  1927. ++NumMacros;
  1928. }
  1929. Stream.ExitBlock();
  1930. // Write the offsets table for macro IDs.
  1931. using namespace llvm;
  1932. auto *Abbrev = new BitCodeAbbrev();
  1933. Abbrev->Add(BitCodeAbbrevOp(MACRO_OFFSET));
  1934. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of macros
  1935. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  1936. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1937. unsigned MacroOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  1938. Record.clear();
  1939. Record.push_back(MACRO_OFFSET);
  1940. Record.push_back(MacroOffsets.size());
  1941. Record.push_back(FirstMacroID - NUM_PREDEF_MACRO_IDS);
  1942. Stream.EmitRecordWithBlob(MacroOffsetAbbrev, Record,
  1943. bytes(MacroOffsets));
  1944. }
  1945. void ASTWriter::WritePreprocessorDetail(PreprocessingRecord &PPRec) {
  1946. if (PPRec.local_begin() == PPRec.local_end())
  1947. return;
  1948. SmallVector<PPEntityOffset, 64> PreprocessedEntityOffsets;
  1949. // Enter the preprocessor block.
  1950. Stream.EnterSubblock(PREPROCESSOR_DETAIL_BLOCK_ID, 3);
  1951. // If the preprocessor has a preprocessing record, emit it.
  1952. unsigned NumPreprocessingRecords = 0;
  1953. using namespace llvm;
  1954. // Set up the abbreviation for
  1955. unsigned InclusionAbbrev = 0;
  1956. {
  1957. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  1958. Abbrev->Add(BitCodeAbbrevOp(PPD_INCLUSION_DIRECTIVE));
  1959. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // filename length
  1960. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // in quotes
  1961. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 2)); // kind
  1962. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // imported module
  1963. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  1964. InclusionAbbrev = Stream.EmitAbbrev(Abbrev);
  1965. }
  1966. unsigned FirstPreprocessorEntityID
  1967. = (Chain ? PPRec.getNumLoadedPreprocessedEntities() : 0)
  1968. + NUM_PREDEF_PP_ENTITY_IDS;
  1969. unsigned NextPreprocessorEntityID = FirstPreprocessorEntityID;
  1970. RecordData Record;
  1971. for (PreprocessingRecord::iterator E = PPRec.local_begin(),
  1972. EEnd = PPRec.local_end();
  1973. E != EEnd;
  1974. (void)++E, ++NumPreprocessingRecords, ++NextPreprocessorEntityID) {
  1975. Record.clear();
  1976. PreprocessedEntityOffsets.push_back(
  1977. PPEntityOffset((*E)->getSourceRange(), Stream.GetCurrentBitNo()));
  1978. if (MacroDefinitionRecord *MD = dyn_cast<MacroDefinitionRecord>(*E)) {
  1979. // Record this macro definition's ID.
  1980. MacroDefinitions[MD] = NextPreprocessorEntityID;
  1981. AddIdentifierRef(MD->getName(), Record);
  1982. Stream.EmitRecord(PPD_MACRO_DEFINITION, Record);
  1983. continue;
  1984. }
  1985. if (MacroExpansion *ME = dyn_cast<MacroExpansion>(*E)) {
  1986. Record.push_back(ME->isBuiltinMacro());
  1987. if (ME->isBuiltinMacro())
  1988. AddIdentifierRef(ME->getName(), Record);
  1989. else
  1990. Record.push_back(MacroDefinitions[ME->getDefinition()]);
  1991. Stream.EmitRecord(PPD_MACRO_EXPANSION, Record);
  1992. continue;
  1993. }
  1994. if (InclusionDirective *ID = dyn_cast<InclusionDirective>(*E)) {
  1995. Record.push_back(PPD_INCLUSION_DIRECTIVE);
  1996. Record.push_back(ID->getFileName().size());
  1997. Record.push_back(ID->wasInQuotes());
  1998. Record.push_back(static_cast<unsigned>(ID->getKind()));
  1999. Record.push_back(ID->importedModule());
  2000. SmallString<64> Buffer;
  2001. Buffer += ID->getFileName();
  2002. // Check that the FileEntry is not null because it was not resolved and
  2003. // we create a PCH even with compiler errors.
  2004. if (ID->getFile())
  2005. Buffer += ID->getFile()->getName();
  2006. Stream.EmitRecordWithBlob(InclusionAbbrev, Record, Buffer);
  2007. continue;
  2008. }
  2009. llvm_unreachable("Unhandled PreprocessedEntity in ASTWriter");
  2010. }
  2011. Stream.ExitBlock();
  2012. // Write the offsets table for the preprocessing record.
  2013. if (NumPreprocessingRecords > 0) {
  2014. assert(PreprocessedEntityOffsets.size() == NumPreprocessingRecords);
  2015. // Write the offsets table for identifier IDs.
  2016. using namespace llvm;
  2017. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2018. Abbrev->Add(BitCodeAbbrevOp(PPD_ENTITIES_OFFSETS));
  2019. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first pp entity
  2020. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2021. unsigned PPEOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  2022. Record.clear();
  2023. Record.push_back(PPD_ENTITIES_OFFSETS);
  2024. Record.push_back(FirstPreprocessorEntityID - NUM_PREDEF_PP_ENTITY_IDS);
  2025. Stream.EmitRecordWithBlob(PPEOffsetAbbrev, Record,
  2026. bytes(PreprocessedEntityOffsets));
  2027. }
  2028. }
  2029. unsigned ASTWriter::getSubmoduleID(Module *Mod) {
  2030. llvm::DenseMap<Module *, unsigned>::iterator Known = SubmoduleIDs.find(Mod);
  2031. if (Known != SubmoduleIDs.end())
  2032. return Known->second;
  2033. return SubmoduleIDs[Mod] = NextSubmoduleID++;
  2034. }
  2035. unsigned ASTWriter::getExistingSubmoduleID(Module *Mod) const {
  2036. if (!Mod)
  2037. return 0;
  2038. llvm::DenseMap<Module *, unsigned>::const_iterator
  2039. Known = SubmoduleIDs.find(Mod);
  2040. if (Known != SubmoduleIDs.end())
  2041. return Known->second;
  2042. return 0;
  2043. }
  2044. /// \brief Compute the number of modules within the given tree (including the
  2045. /// given module).
  2046. static unsigned getNumberOfModules(Module *Mod) {
  2047. unsigned ChildModules = 0;
  2048. for (Module::submodule_iterator Sub = Mod->submodule_begin(),
  2049. SubEnd = Mod->submodule_end();
  2050. Sub != SubEnd; ++Sub)
  2051. ChildModules += getNumberOfModules(*Sub);
  2052. return ChildModules + 1;
  2053. }
  2054. void ASTWriter::WriteSubmodules(Module *WritingModule) {
  2055. // Enter the submodule description block.
  2056. Stream.EnterSubblock(SUBMODULE_BLOCK_ID, /*bits for abbreviations*/5);
  2057. // Write the abbreviations needed for the submodules block.
  2058. using namespace llvm;
  2059. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2060. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_DEFINITION));
  2061. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // ID
  2062. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Parent
  2063. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
  2064. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExplicit
  2065. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsSystem
  2066. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsExternC
  2067. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferSubmodules...
  2068. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExplicit...
  2069. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // InferExportWild...
  2070. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // ConfigMacrosExh...
  2071. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2072. unsigned DefinitionAbbrev = Stream.EmitAbbrev(Abbrev);
  2073. Abbrev = new BitCodeAbbrev();
  2074. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_HEADER));
  2075. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2076. unsigned UmbrellaAbbrev = Stream.EmitAbbrev(Abbrev);
  2077. Abbrev = new BitCodeAbbrev();
  2078. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_HEADER));
  2079. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2080. unsigned HeaderAbbrev = Stream.EmitAbbrev(Abbrev);
  2081. Abbrev = new BitCodeAbbrev();
  2082. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TOPHEADER));
  2083. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2084. unsigned TopHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
  2085. Abbrev = new BitCodeAbbrev();
  2086. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_UMBRELLA_DIR));
  2087. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2088. unsigned UmbrellaDirAbbrev = Stream.EmitAbbrev(Abbrev);
  2089. Abbrev = new BitCodeAbbrev();
  2090. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_REQUIRES));
  2091. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // State
  2092. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Feature
  2093. unsigned RequiresAbbrev = Stream.EmitAbbrev(Abbrev);
  2094. Abbrev = new BitCodeAbbrev();
  2095. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_EXCLUDED_HEADER));
  2096. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2097. unsigned ExcludedHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
  2098. Abbrev = new BitCodeAbbrev();
  2099. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_TEXTUAL_HEADER));
  2100. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2101. unsigned TextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
  2102. Abbrev = new BitCodeAbbrev();
  2103. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_HEADER));
  2104. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2105. unsigned PrivateHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
  2106. Abbrev = new BitCodeAbbrev();
  2107. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_PRIVATE_TEXTUAL_HEADER));
  2108. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2109. unsigned PrivateTextualHeaderAbbrev = Stream.EmitAbbrev(Abbrev);
  2110. Abbrev = new BitCodeAbbrev();
  2111. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_LINK_LIBRARY));
  2112. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 1)); // IsFramework
  2113. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Name
  2114. unsigned LinkLibraryAbbrev = Stream.EmitAbbrev(Abbrev);
  2115. Abbrev = new BitCodeAbbrev();
  2116. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFIG_MACRO));
  2117. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Macro name
  2118. unsigned ConfigMacroAbbrev = Stream.EmitAbbrev(Abbrev);
  2119. Abbrev = new BitCodeAbbrev();
  2120. Abbrev->Add(BitCodeAbbrevOp(SUBMODULE_CONFLICT));
  2121. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // Other module
  2122. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // Message
  2123. unsigned ConflictAbbrev = Stream.EmitAbbrev(Abbrev);
  2124. // Write the submodule metadata block.
  2125. RecordData Record;
  2126. Record.push_back(getNumberOfModules(WritingModule));
  2127. Record.push_back(FirstSubmoduleID - NUM_PREDEF_SUBMODULE_IDS);
  2128. Stream.EmitRecord(SUBMODULE_METADATA, Record);
  2129. // Write all of the submodules.
  2130. std::queue<Module *> Q;
  2131. Q.push(WritingModule);
  2132. while (!Q.empty()) {
  2133. Module *Mod = Q.front();
  2134. Q.pop();
  2135. unsigned ID = getSubmoduleID(Mod);
  2136. // Emit the definition of the block.
  2137. Record.clear();
  2138. Record.push_back(SUBMODULE_DEFINITION);
  2139. Record.push_back(ID);
  2140. if (Mod->Parent) {
  2141. assert(SubmoduleIDs[Mod->Parent] && "Submodule parent not written?");
  2142. Record.push_back(SubmoduleIDs[Mod->Parent]);
  2143. } else {
  2144. Record.push_back(0);
  2145. }
  2146. Record.push_back(Mod->IsFramework);
  2147. Record.push_back(Mod->IsExplicit);
  2148. Record.push_back(Mod->IsSystem);
  2149. Record.push_back(Mod->IsExternC);
  2150. Record.push_back(Mod->InferSubmodules);
  2151. Record.push_back(Mod->InferExplicitSubmodules);
  2152. Record.push_back(Mod->InferExportWildcard);
  2153. Record.push_back(Mod->ConfigMacrosExhaustive);
  2154. Stream.EmitRecordWithBlob(DefinitionAbbrev, Record, Mod->Name);
  2155. // Emit the requirements.
  2156. for (unsigned I = 0, N = Mod->Requirements.size(); I != N; ++I) {
  2157. Record.clear();
  2158. Record.push_back(SUBMODULE_REQUIRES);
  2159. Record.push_back(Mod->Requirements[I].second);
  2160. Stream.EmitRecordWithBlob(RequiresAbbrev, Record,
  2161. Mod->Requirements[I].first);
  2162. }
  2163. // Emit the umbrella header, if there is one.
  2164. if (auto UmbrellaHeader = Mod->getUmbrellaHeader()) {
  2165. Record.clear();
  2166. Record.push_back(SUBMODULE_UMBRELLA_HEADER);
  2167. Stream.EmitRecordWithBlob(UmbrellaAbbrev, Record,
  2168. UmbrellaHeader.NameAsWritten);
  2169. } else if (auto UmbrellaDir = Mod->getUmbrellaDir()) {
  2170. Record.clear();
  2171. Record.push_back(SUBMODULE_UMBRELLA_DIR);
  2172. Stream.EmitRecordWithBlob(UmbrellaDirAbbrev, Record,
  2173. UmbrellaDir.NameAsWritten);
  2174. }
  2175. // Emit the headers.
  2176. struct {
  2177. unsigned RecordKind;
  2178. unsigned Abbrev;
  2179. Module::HeaderKind HeaderKind;
  2180. } HeaderLists[] = {
  2181. {SUBMODULE_HEADER, HeaderAbbrev, Module::HK_Normal},
  2182. {SUBMODULE_TEXTUAL_HEADER, TextualHeaderAbbrev, Module::HK_Textual},
  2183. {SUBMODULE_PRIVATE_HEADER, PrivateHeaderAbbrev, Module::HK_Private},
  2184. {SUBMODULE_PRIVATE_TEXTUAL_HEADER, PrivateTextualHeaderAbbrev,
  2185. Module::HK_PrivateTextual},
  2186. {SUBMODULE_EXCLUDED_HEADER, ExcludedHeaderAbbrev, Module::HK_Excluded}
  2187. };
  2188. for (auto &HL : HeaderLists) {
  2189. Record.clear();
  2190. Record.push_back(HL.RecordKind);
  2191. for (auto &H : Mod->Headers[HL.HeaderKind])
  2192. Stream.EmitRecordWithBlob(HL.Abbrev, Record, H.NameAsWritten);
  2193. }
  2194. // Emit the top headers.
  2195. {
  2196. auto TopHeaders = Mod->getTopHeaders(PP->getFileManager());
  2197. Record.clear();
  2198. Record.push_back(SUBMODULE_TOPHEADER);
  2199. for (auto *H : TopHeaders)
  2200. Stream.EmitRecordWithBlob(TopHeaderAbbrev, Record, H->getName());
  2201. }
  2202. // Emit the imports.
  2203. if (!Mod->Imports.empty()) {
  2204. Record.clear();
  2205. for (unsigned I = 0, N = Mod->Imports.size(); I != N; ++I) {
  2206. unsigned ImportedID = getSubmoduleID(Mod->Imports[I]);
  2207. assert(ImportedID && "Unknown submodule!");
  2208. Record.push_back(ImportedID);
  2209. }
  2210. Stream.EmitRecord(SUBMODULE_IMPORTS, Record);
  2211. }
  2212. // Emit the exports.
  2213. if (!Mod->Exports.empty()) {
  2214. Record.clear();
  2215. for (unsigned I = 0, N = Mod->Exports.size(); I != N; ++I) {
  2216. if (Module *Exported = Mod->Exports[I].getPointer()) {
  2217. unsigned ExportedID = getSubmoduleID(Exported);
  2218. Record.push_back(ExportedID);
  2219. } else {
  2220. Record.push_back(0);
  2221. }
  2222. Record.push_back(Mod->Exports[I].getInt());
  2223. }
  2224. Stream.EmitRecord(SUBMODULE_EXPORTS, Record);
  2225. }
  2226. //FIXME: How do we emit the 'use'd modules? They may not be submodules.
  2227. // Might be unnecessary as use declarations are only used to build the
  2228. // module itself.
  2229. // Emit the link libraries.
  2230. for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) {
  2231. Record.clear();
  2232. Record.push_back(SUBMODULE_LINK_LIBRARY);
  2233. Record.push_back(Mod->LinkLibraries[I].IsFramework);
  2234. Stream.EmitRecordWithBlob(LinkLibraryAbbrev, Record,
  2235. Mod->LinkLibraries[I].Library);
  2236. }
  2237. // Emit the conflicts.
  2238. for (unsigned I = 0, N = Mod->Conflicts.size(); I != N; ++I) {
  2239. Record.clear();
  2240. Record.push_back(SUBMODULE_CONFLICT);
  2241. unsigned OtherID = getSubmoduleID(Mod->Conflicts[I].Other);
  2242. assert(OtherID && "Unknown submodule!");
  2243. Record.push_back(OtherID);
  2244. Stream.EmitRecordWithBlob(ConflictAbbrev, Record,
  2245. Mod->Conflicts[I].Message);
  2246. }
  2247. // Emit the configuration macros.
  2248. for (unsigned I = 0, N = Mod->ConfigMacros.size(); I != N; ++I) {
  2249. Record.clear();
  2250. Record.push_back(SUBMODULE_CONFIG_MACRO);
  2251. Stream.EmitRecordWithBlob(ConfigMacroAbbrev, Record,
  2252. Mod->ConfigMacros[I]);
  2253. }
  2254. // Queue up the submodules of this module.
  2255. for (Module::submodule_iterator Sub = Mod->submodule_begin(),
  2256. SubEnd = Mod->submodule_end();
  2257. Sub != SubEnd; ++Sub)
  2258. Q.push(*Sub);
  2259. }
  2260. Stream.ExitBlock();
  2261. // FIXME: This can easily happen, if we have a reference to a submodule that
  2262. // did not result in us loading a module file for that submodule. For
  2263. // instance, a cross-top-level-module 'conflict' declaration will hit this.
  2264. assert((NextSubmoduleID - FirstSubmoduleID ==
  2265. getNumberOfModules(WritingModule)) &&
  2266. "Wrong # of submodules; found a reference to a non-local, "
  2267. "non-imported submodule?");
  2268. }
  2269. serialization::SubmoduleID
  2270. ASTWriter::inferSubmoduleIDFromLocation(SourceLocation Loc) {
  2271. if (Loc.isInvalid() || !WritingModule)
  2272. return 0; // No submodule
  2273. // Find the module that owns this location.
  2274. ModuleMap &ModMap = PP->getHeaderSearchInfo().getModuleMap();
  2275. Module *OwningMod
  2276. = ModMap.inferModuleFromLocation(FullSourceLoc(Loc,PP->getSourceManager()));
  2277. if (!OwningMod)
  2278. return 0;
  2279. // Check whether this submodule is part of our own module.
  2280. if (WritingModule != OwningMod && !OwningMod->isSubModuleOf(WritingModule))
  2281. return 0;
  2282. return getSubmoduleID(OwningMod);
  2283. }
  2284. void ASTWriter::WritePragmaDiagnosticMappings(const DiagnosticsEngine &Diag,
  2285. bool isModule) {
  2286. // Make sure set diagnostic pragmas don't affect the translation unit that
  2287. // imports the module.
  2288. // FIXME: Make diagnostic pragma sections work properly with modules.
  2289. if (isModule)
  2290. return;
  2291. llvm::SmallDenseMap<const DiagnosticsEngine::DiagState *, unsigned, 64>
  2292. DiagStateIDMap;
  2293. unsigned CurrID = 0;
  2294. DiagStateIDMap[&Diag.DiagStates.front()] = ++CurrID; // the command-line one.
  2295. RecordData Record;
  2296. for (DiagnosticsEngine::DiagStatePointsTy::const_iterator
  2297. I = Diag.DiagStatePoints.begin(), E = Diag.DiagStatePoints.end();
  2298. I != E; ++I) {
  2299. const DiagnosticsEngine::DiagStatePoint &point = *I;
  2300. if (point.Loc.isInvalid())
  2301. continue;
  2302. Record.push_back(point.Loc.getRawEncoding());
  2303. unsigned &DiagStateID = DiagStateIDMap[point.State];
  2304. Record.push_back(DiagStateID);
  2305. if (DiagStateID == 0) {
  2306. DiagStateID = ++CurrID;
  2307. for (DiagnosticsEngine::DiagState::const_iterator
  2308. I = point.State->begin(), E = point.State->end(); I != E; ++I) {
  2309. if (I->second.isPragma()) {
  2310. Record.push_back(I->first);
  2311. Record.push_back((unsigned)I->second.getSeverity());
  2312. }
  2313. }
  2314. Record.push_back(-1); // mark the end of the diag/map pairs for this
  2315. // location.
  2316. }
  2317. }
  2318. if (!Record.empty())
  2319. Stream.EmitRecord(DIAG_PRAGMA_MAPPINGS, Record);
  2320. }
  2321. void ASTWriter::WriteCXXCtorInitializersOffsets() {
  2322. if (CXXCtorInitializersOffsets.empty())
  2323. return;
  2324. RecordData Record;
  2325. // Create a blob abbreviation for the C++ ctor initializer offsets.
  2326. using namespace llvm;
  2327. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2328. Abbrev->Add(BitCodeAbbrevOp(CXX_CTOR_INITIALIZERS_OFFSETS));
  2329. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
  2330. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2331. unsigned CtorInitializersOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  2332. // Write the base specifier offsets table.
  2333. Record.clear();
  2334. Record.push_back(CXX_CTOR_INITIALIZERS_OFFSETS);
  2335. Record.push_back(CXXCtorInitializersOffsets.size());
  2336. Stream.EmitRecordWithBlob(CtorInitializersOffsetAbbrev, Record,
  2337. bytes(CXXCtorInitializersOffsets));
  2338. }
  2339. void ASTWriter::WriteCXXBaseSpecifiersOffsets() {
  2340. if (CXXBaseSpecifiersOffsets.empty())
  2341. return;
  2342. RecordData Record;
  2343. // Create a blob abbreviation for the C++ base specifiers offsets.
  2344. using namespace llvm;
  2345. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2346. Abbrev->Add(BitCodeAbbrevOp(CXX_BASE_SPECIFIER_OFFSETS));
  2347. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
  2348. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2349. unsigned BaseSpecifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  2350. // Write the base specifier offsets table.
  2351. Record.clear();
  2352. Record.push_back(CXX_BASE_SPECIFIER_OFFSETS);
  2353. Record.push_back(CXXBaseSpecifiersOffsets.size());
  2354. Stream.EmitRecordWithBlob(BaseSpecifierOffsetAbbrev, Record,
  2355. bytes(CXXBaseSpecifiersOffsets));
  2356. }
  2357. //===----------------------------------------------------------------------===//
  2358. // Type Serialization
  2359. //===----------------------------------------------------------------------===//
  2360. /// \brief Write the representation of a type to the AST stream.
  2361. void ASTWriter::WriteType(QualType T) {
  2362. TypeIdx &Idx = TypeIdxs[T];
  2363. if (Idx.getIndex() == 0) // we haven't seen this type before.
  2364. Idx = TypeIdx(NextTypeID++);
  2365. assert(Idx.getIndex() >= FirstTypeID && "Re-writing a type from a prior AST");
  2366. // Record the offset for this type.
  2367. unsigned Index = Idx.getIndex() - FirstTypeID;
  2368. if (TypeOffsets.size() == Index)
  2369. TypeOffsets.push_back(Stream.GetCurrentBitNo());
  2370. else if (TypeOffsets.size() < Index) {
  2371. TypeOffsets.resize(Index + 1);
  2372. TypeOffsets[Index] = Stream.GetCurrentBitNo();
  2373. }
  2374. RecordData Record;
  2375. // Emit the type's representation.
  2376. ASTTypeWriter W(*this, Record);
  2377. W.AbbrevToUse = 0;
  2378. if (T.hasLocalNonFastQualifiers()) {
  2379. Qualifiers Qs = T.getLocalQualifiers();
  2380. AddTypeRef(T.getLocalUnqualifiedType(), Record);
  2381. Record.push_back(Qs.getAsOpaqueValue());
  2382. W.Code = TYPE_EXT_QUAL;
  2383. W.AbbrevToUse = TypeExtQualAbbrev;
  2384. } else {
  2385. switch (T->getTypeClass()) {
  2386. // For all of the concrete, non-dependent types, call the
  2387. // appropriate visitor function.
  2388. #define TYPE(Class, Base) \
  2389. case Type::Class: W.Visit##Class##Type(cast<Class##Type>(T)); break;
  2390. #define ABSTRACT_TYPE(Class, Base)
  2391. #include "clang/AST/TypeNodes.def"
  2392. }
  2393. }
  2394. // Emit the serialized record.
  2395. Stream.EmitRecord(W.Code, Record, W.AbbrevToUse);
  2396. // Flush any expressions that were written as part of this type.
  2397. FlushStmts();
  2398. }
  2399. //===----------------------------------------------------------------------===//
  2400. // Declaration Serialization
  2401. //===----------------------------------------------------------------------===//
  2402. /// \brief Write the block containing all of the declaration IDs
  2403. /// lexically declared within the given DeclContext.
  2404. ///
  2405. /// \returns the offset of the DECL_CONTEXT_LEXICAL block within the
  2406. /// bistream, or 0 if no block was written.
  2407. uint64_t ASTWriter::WriteDeclContextLexicalBlock(ASTContext &Context,
  2408. DeclContext *DC) {
  2409. if (DC->decls_empty())
  2410. return 0;
  2411. uint64_t Offset = Stream.GetCurrentBitNo();
  2412. RecordData Record;
  2413. Record.push_back(DECL_CONTEXT_LEXICAL);
  2414. SmallVector<KindDeclIDPair, 64> Decls;
  2415. for (const auto *D : DC->decls())
  2416. Decls.push_back(std::make_pair(D->getKind(), GetDeclRef(D)));
  2417. ++NumLexicalDeclContexts;
  2418. Stream.EmitRecordWithBlob(DeclContextLexicalAbbrev, Record, bytes(Decls));
  2419. return Offset;
  2420. }
  2421. void ASTWriter::WriteTypeDeclOffsets() {
  2422. using namespace llvm;
  2423. RecordData Record;
  2424. // Write the type offsets array
  2425. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2426. Abbrev->Add(BitCodeAbbrevOp(TYPE_OFFSET));
  2427. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of types
  2428. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base type index
  2429. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // types block
  2430. unsigned TypeOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  2431. Record.clear();
  2432. Record.push_back(TYPE_OFFSET);
  2433. Record.push_back(TypeOffsets.size());
  2434. Record.push_back(FirstTypeID - NUM_PREDEF_TYPE_IDS);
  2435. Stream.EmitRecordWithBlob(TypeOffsetAbbrev, Record, bytes(TypeOffsets));
  2436. // Write the declaration offsets array
  2437. Abbrev = new BitCodeAbbrev();
  2438. Abbrev->Add(BitCodeAbbrevOp(DECL_OFFSET));
  2439. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of declarations
  2440. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // base decl ID
  2441. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob)); // declarations block
  2442. unsigned DeclOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  2443. Record.clear();
  2444. Record.push_back(DECL_OFFSET);
  2445. Record.push_back(DeclOffsets.size());
  2446. Record.push_back(FirstDeclID - NUM_PREDEF_DECL_IDS);
  2447. Stream.EmitRecordWithBlob(DeclOffsetAbbrev, Record, bytes(DeclOffsets));
  2448. }
  2449. void ASTWriter::WriteFileDeclIDsMap() {
  2450. using namespace llvm;
  2451. RecordData Record;
  2452. SmallVector<std::pair<FileID, DeclIDInFileInfo *>, 64> SortedFileDeclIDs(
  2453. FileDeclIDs.begin(), FileDeclIDs.end());
  2454. std::sort(SortedFileDeclIDs.begin(), SortedFileDeclIDs.end(),
  2455. llvm::less_first());
  2456. // Join the vectors of DeclIDs from all files.
  2457. SmallVector<DeclID, 256> FileGroupedDeclIDs;
  2458. for (auto &FileDeclEntry : SortedFileDeclIDs) {
  2459. DeclIDInFileInfo &Info = *FileDeclEntry.second;
  2460. Info.FirstDeclIndex = FileGroupedDeclIDs.size();
  2461. for (auto &LocDeclEntry : Info.DeclIDs)
  2462. FileGroupedDeclIDs.push_back(LocDeclEntry.second);
  2463. }
  2464. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2465. Abbrev->Add(BitCodeAbbrevOp(FILE_SORTED_DECLS));
  2466. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2467. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2468. unsigned AbbrevCode = Stream.EmitAbbrev(Abbrev);
  2469. Record.push_back(FILE_SORTED_DECLS);
  2470. Record.push_back(FileGroupedDeclIDs.size());
  2471. Stream.EmitRecordWithBlob(AbbrevCode, Record, bytes(FileGroupedDeclIDs));
  2472. }
  2473. void ASTWriter::WriteComments() {
  2474. Stream.EnterSubblock(COMMENTS_BLOCK_ID, 3);
  2475. ArrayRef<RawComment *> RawComments = Context->Comments.getComments();
  2476. RecordData Record;
  2477. for (ArrayRef<RawComment *>::iterator I = RawComments.begin(),
  2478. E = RawComments.end();
  2479. I != E; ++I) {
  2480. Record.clear();
  2481. AddSourceRange((*I)->getSourceRange(), Record);
  2482. Record.push_back((*I)->getKind());
  2483. Record.push_back((*I)->isTrailingComment());
  2484. Record.push_back((*I)->isAlmostTrailingComment());
  2485. Stream.EmitRecord(COMMENTS_RAW_COMMENT, Record);
  2486. }
  2487. Stream.ExitBlock();
  2488. }
  2489. //===----------------------------------------------------------------------===//
  2490. // Global Method Pool and Selector Serialization
  2491. //===----------------------------------------------------------------------===//
  2492. namespace {
  2493. // Trait used for the on-disk hash table used in the method pool.
  2494. class ASTMethodPoolTrait {
  2495. ASTWriter &Writer;
  2496. public:
  2497. typedef Selector key_type;
  2498. typedef key_type key_type_ref;
  2499. struct data_type {
  2500. SelectorID ID;
  2501. ObjCMethodList Instance, Factory;
  2502. };
  2503. typedef const data_type& data_type_ref;
  2504. typedef unsigned hash_value_type;
  2505. typedef unsigned offset_type;
  2506. explicit ASTMethodPoolTrait(ASTWriter &Writer) : Writer(Writer) { }
  2507. static hash_value_type ComputeHash(Selector Sel) {
  2508. return serialization::ComputeHash(Sel);
  2509. }
  2510. std::pair<unsigned,unsigned>
  2511. EmitKeyDataLength(raw_ostream& Out, Selector Sel,
  2512. data_type_ref Methods) {
  2513. using namespace llvm::support;
  2514. endian::Writer<little> LE(Out);
  2515. unsigned KeyLen = 2 + (Sel.getNumArgs()? Sel.getNumArgs() * 4 : 4);
  2516. LE.write<uint16_t>(KeyLen);
  2517. unsigned DataLen = 4 + 2 + 2; // 2 bytes for each of the method counts
  2518. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2519. Method = Method->getNext())
  2520. if (Method->getMethod())
  2521. DataLen += 4;
  2522. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2523. Method = Method->getNext())
  2524. if (Method->getMethod())
  2525. DataLen += 4;
  2526. LE.write<uint16_t>(DataLen);
  2527. return std::make_pair(KeyLen, DataLen);
  2528. }
  2529. void EmitKey(raw_ostream& Out, Selector Sel, unsigned) {
  2530. using namespace llvm::support;
  2531. endian::Writer<little> LE(Out);
  2532. uint64_t Start = Out.tell();
  2533. assert((Start >> 32) == 0 && "Selector key offset too large");
  2534. Writer.SetSelectorOffset(Sel, Start);
  2535. unsigned N = Sel.getNumArgs();
  2536. LE.write<uint16_t>(N);
  2537. if (N == 0)
  2538. N = 1;
  2539. for (unsigned I = 0; I != N; ++I)
  2540. LE.write<uint32_t>(
  2541. Writer.getIdentifierRef(Sel.getIdentifierInfoForSlot(I)));
  2542. }
  2543. void EmitData(raw_ostream& Out, key_type_ref,
  2544. data_type_ref Methods, unsigned DataLen) {
  2545. using namespace llvm::support;
  2546. endian::Writer<little> LE(Out);
  2547. uint64_t Start = Out.tell(); (void)Start;
  2548. LE.write<uint32_t>(Methods.ID);
  2549. unsigned NumInstanceMethods = 0;
  2550. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2551. Method = Method->getNext())
  2552. if (Method->getMethod())
  2553. ++NumInstanceMethods;
  2554. unsigned NumFactoryMethods = 0;
  2555. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2556. Method = Method->getNext())
  2557. if (Method->getMethod())
  2558. ++NumFactoryMethods;
  2559. unsigned InstanceBits = Methods.Instance.getBits();
  2560. assert(InstanceBits < 4);
  2561. unsigned InstanceHasMoreThanOneDeclBit =
  2562. Methods.Instance.hasMoreThanOneDecl();
  2563. unsigned FullInstanceBits = (NumInstanceMethods << 3) |
  2564. (InstanceHasMoreThanOneDeclBit << 2) |
  2565. InstanceBits;
  2566. unsigned FactoryBits = Methods.Factory.getBits();
  2567. assert(FactoryBits < 4);
  2568. unsigned FactoryHasMoreThanOneDeclBit =
  2569. Methods.Factory.hasMoreThanOneDecl();
  2570. unsigned FullFactoryBits = (NumFactoryMethods << 3) |
  2571. (FactoryHasMoreThanOneDeclBit << 2) |
  2572. FactoryBits;
  2573. LE.write<uint16_t>(FullInstanceBits);
  2574. LE.write<uint16_t>(FullFactoryBits);
  2575. for (const ObjCMethodList *Method = &Methods.Instance; Method;
  2576. Method = Method->getNext())
  2577. if (Method->getMethod())
  2578. LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
  2579. for (const ObjCMethodList *Method = &Methods.Factory; Method;
  2580. Method = Method->getNext())
  2581. if (Method->getMethod())
  2582. LE.write<uint32_t>(Writer.getDeclID(Method->getMethod()));
  2583. assert(Out.tell() - Start == DataLen && "Data length is wrong");
  2584. }
  2585. };
  2586. } // end anonymous namespace
  2587. /// \brief Write ObjC data: selectors and the method pool.
  2588. ///
  2589. /// The method pool contains both instance and factory methods, stored
  2590. /// in an on-disk hash table indexed by the selector. The hash table also
  2591. /// contains an empty entry for every other selector known to Sema.
  2592. void ASTWriter::WriteSelectors(Sema &SemaRef) {
  2593. using namespace llvm;
  2594. // Do we have to do anything at all?
  2595. if (SemaRef.MethodPool.empty() && SelectorIDs.empty())
  2596. return;
  2597. unsigned NumTableEntries = 0;
  2598. // Create and write out the blob that contains selectors and the method pool.
  2599. {
  2600. llvm::OnDiskChainedHashTableGenerator<ASTMethodPoolTrait> Generator;
  2601. ASTMethodPoolTrait Trait(*this);
  2602. // Create the on-disk hash table representation. We walk through every
  2603. // selector we've seen and look it up in the method pool.
  2604. SelectorOffsets.resize(NextSelectorID - FirstSelectorID);
  2605. for (auto &SelectorAndID : SelectorIDs) {
  2606. Selector S = SelectorAndID.first;
  2607. SelectorID ID = SelectorAndID.second;
  2608. Sema::GlobalMethodPool::iterator F = SemaRef.MethodPool.find(S);
  2609. ASTMethodPoolTrait::data_type Data = {
  2610. ID,
  2611. ObjCMethodList(),
  2612. ObjCMethodList()
  2613. };
  2614. if (F != SemaRef.MethodPool.end()) {
  2615. Data.Instance = F->second.first;
  2616. Data.Factory = F->second.second;
  2617. }
  2618. // Only write this selector if it's not in an existing AST or something
  2619. // changed.
  2620. if (Chain && ID < FirstSelectorID) {
  2621. // Selector already exists. Did it change?
  2622. bool changed = false;
  2623. for (ObjCMethodList *M = &Data.Instance;
  2624. !changed && M && M->getMethod(); M = M->getNext()) {
  2625. if (!M->getMethod()->isFromASTFile())
  2626. changed = true;
  2627. }
  2628. for (ObjCMethodList *M = &Data.Factory; !changed && M && M->getMethod();
  2629. M = M->getNext()) {
  2630. if (!M->getMethod()->isFromASTFile())
  2631. changed = true;
  2632. }
  2633. if (!changed)
  2634. continue;
  2635. } else if (Data.Instance.getMethod() || Data.Factory.getMethod()) {
  2636. // A new method pool entry.
  2637. ++NumTableEntries;
  2638. }
  2639. Generator.insert(S, Data, Trait);
  2640. }
  2641. // Create the on-disk hash table in a buffer.
  2642. SmallString<4096> MethodPool;
  2643. uint32_t BucketOffset;
  2644. {
  2645. using namespace llvm::support;
  2646. ASTMethodPoolTrait Trait(*this);
  2647. llvm::raw_svector_ostream Out(MethodPool);
  2648. // Make sure that no bucket is at offset 0
  2649. endian::Writer<little>(Out).write<uint32_t>(0);
  2650. BucketOffset = Generator.Emit(Out, Trait);
  2651. }
  2652. // Create a blob abbreviation
  2653. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2654. Abbrev->Add(BitCodeAbbrevOp(METHOD_POOL));
  2655. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2656. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2657. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2658. unsigned MethodPoolAbbrev = Stream.EmitAbbrev(Abbrev);
  2659. // Write the method pool
  2660. RecordData Record;
  2661. Record.push_back(METHOD_POOL);
  2662. Record.push_back(BucketOffset);
  2663. Record.push_back(NumTableEntries);
  2664. Stream.EmitRecordWithBlob(MethodPoolAbbrev, Record, MethodPool);
  2665. // Create a blob abbreviation for the selector table offsets.
  2666. Abbrev = new BitCodeAbbrev();
  2667. Abbrev->Add(BitCodeAbbrevOp(SELECTOR_OFFSETS));
  2668. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // size
  2669. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  2670. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2671. unsigned SelectorOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  2672. // Write the selector offsets table.
  2673. Record.clear();
  2674. Record.push_back(SELECTOR_OFFSETS);
  2675. Record.push_back(SelectorOffsets.size());
  2676. Record.push_back(FirstSelectorID - NUM_PREDEF_SELECTOR_IDS);
  2677. Stream.EmitRecordWithBlob(SelectorOffsetAbbrev, Record,
  2678. bytes(SelectorOffsets));
  2679. }
  2680. }
  2681. /// \brief Write the selectors referenced in @selector expression into AST file.
  2682. void ASTWriter::WriteReferencedSelectorsPool(Sema &SemaRef) {
  2683. using namespace llvm;
  2684. if (SemaRef.ReferencedSelectors.empty())
  2685. return;
  2686. RecordData Record;
  2687. // Note: this writes out all references even for a dependent AST. But it is
  2688. // very tricky to fix, and given that @selector shouldn't really appear in
  2689. // headers, probably not worth it. It's not a correctness issue.
  2690. for (auto &SelectorAndLocation : SemaRef.ReferencedSelectors) {
  2691. Selector Sel = SelectorAndLocation.first;
  2692. SourceLocation Loc = SelectorAndLocation.second;
  2693. AddSelectorRef(Sel, Record);
  2694. AddSourceLocation(Loc, Record);
  2695. }
  2696. Stream.EmitRecord(REFERENCED_SELECTOR_POOL, Record);
  2697. }
  2698. //===----------------------------------------------------------------------===//
  2699. // Identifier Table Serialization
  2700. //===----------------------------------------------------------------------===//
  2701. /// Determine the declaration that should be put into the name lookup table to
  2702. /// represent the given declaration in this module. This is usually D itself,
  2703. /// but if D was imported and merged into a local declaration, we want the most
  2704. /// recent local declaration instead. The chosen declaration will be the most
  2705. /// recent declaration in any module that imports this one.
  2706. static NamedDecl *getDeclForLocalLookup(const LangOptions &LangOpts,
  2707. NamedDecl *D) {
  2708. if (!LangOpts.Modules || !D->isFromASTFile())
  2709. return D;
  2710. if (Decl *Redecl = D->getPreviousDecl()) {
  2711. // For Redeclarable decls, a prior declaration might be local.
  2712. for (; Redecl; Redecl = Redecl->getPreviousDecl()) {
  2713. if (!Redecl->isFromASTFile())
  2714. return cast<NamedDecl>(Redecl);
  2715. // If we find a decl from a (chained-)PCH stop since we won't find a
  2716. // local one.
  2717. if (D->getOwningModuleID() == 0)
  2718. break;
  2719. }
  2720. } else if (Decl *First = D->getCanonicalDecl()) {
  2721. // For Mergeable decls, the first decl might be local.
  2722. if (!First->isFromASTFile())
  2723. return cast<NamedDecl>(First);
  2724. }
  2725. // All declarations are imported. Our most recent declaration will also be
  2726. // the most recent one in anyone who imports us.
  2727. return D;
  2728. }
  2729. namespace {
  2730. class ASTIdentifierTableTrait {
  2731. ASTWriter &Writer;
  2732. Preprocessor &PP;
  2733. IdentifierResolver &IdResolver;
  2734. /// \brief Determines whether this is an "interesting" identifier that needs a
  2735. /// full IdentifierInfo structure written into the hash table. Notably, this
  2736. /// doesn't check whether the name has macros defined; use PublicMacroIterator
  2737. /// to check that.
  2738. bool isInterestingIdentifier(IdentifierInfo *II, uint64_t MacroOffset) {
  2739. if (MacroOffset ||
  2740. II->isPoisoned() ||
  2741. II->isExtensionToken() ||
  2742. II->getObjCOrBuiltinID() ||
  2743. II->hasRevertedTokenIDToIdentifier() ||
  2744. II->getFETokenInfo<void>())
  2745. return true;
  2746. return false;
  2747. }
  2748. public:
  2749. typedef IdentifierInfo* key_type;
  2750. typedef key_type key_type_ref;
  2751. typedef IdentID data_type;
  2752. typedef data_type data_type_ref;
  2753. typedef unsigned hash_value_type;
  2754. typedef unsigned offset_type;
  2755. ASTIdentifierTableTrait(ASTWriter &Writer, Preprocessor &PP,
  2756. IdentifierResolver &IdResolver)
  2757. : Writer(Writer), PP(PP), IdResolver(IdResolver) {}
  2758. static hash_value_type ComputeHash(const IdentifierInfo* II) {
  2759. return llvm::HashString(II->getName());
  2760. }
  2761. std::pair<unsigned,unsigned>
  2762. EmitKeyDataLength(raw_ostream& Out, IdentifierInfo* II, IdentID ID) {
  2763. unsigned KeyLen = II->getLength() + 1;
  2764. unsigned DataLen = 4; // 4 bytes for the persistent ID << 1
  2765. auto MacroOffset = Writer.getMacroDirectivesOffset(II);
  2766. if (isInterestingIdentifier(II, MacroOffset)) {
  2767. DataLen += 2; // 2 bytes for builtin ID
  2768. DataLen += 2; // 2 bytes for flags
  2769. if (MacroOffset)
  2770. DataLen += 4; // MacroDirectives offset.
  2771. for (IdentifierResolver::iterator D = IdResolver.begin(II),
  2772. DEnd = IdResolver.end();
  2773. D != DEnd; ++D)
  2774. DataLen += 4;
  2775. }
  2776. using namespace llvm::support;
  2777. endian::Writer<little> LE(Out);
  2778. assert((uint16_t)DataLen == DataLen && (uint16_t)KeyLen == KeyLen);
  2779. LE.write<uint16_t>(DataLen);
  2780. // We emit the key length after the data length so that every
  2781. // string is preceded by a 16-bit length. This matches the PTH
  2782. // format for storing identifiers.
  2783. LE.write<uint16_t>(KeyLen);
  2784. return std::make_pair(KeyLen, DataLen);
  2785. }
  2786. void EmitKey(raw_ostream& Out, const IdentifierInfo* II,
  2787. unsigned KeyLen) {
  2788. // Record the location of the key data. This is used when generating
  2789. // the mapping from persistent IDs to strings.
  2790. Writer.SetIdentifierOffset(II, Out.tell());
  2791. Out.write(II->getNameStart(), KeyLen);
  2792. }
  2793. void EmitData(raw_ostream& Out, IdentifierInfo* II,
  2794. IdentID ID, unsigned) {
  2795. using namespace llvm::support;
  2796. endian::Writer<little> LE(Out);
  2797. auto MacroOffset = Writer.getMacroDirectivesOffset(II);
  2798. if (!isInterestingIdentifier(II, MacroOffset)) {
  2799. LE.write<uint32_t>(ID << 1);
  2800. return;
  2801. }
  2802. LE.write<uint32_t>((ID << 1) | 0x01);
  2803. uint32_t Bits = (uint32_t)II->getObjCOrBuiltinID();
  2804. assert((Bits & 0xffff) == Bits && "ObjCOrBuiltinID too big for ASTReader.");
  2805. LE.write<uint16_t>(Bits);
  2806. Bits = 0;
  2807. bool HadMacroDefinition = MacroOffset != 0;
  2808. Bits = (Bits << 1) | unsigned(HadMacroDefinition);
  2809. Bits = (Bits << 1) | unsigned(II->isExtensionToken());
  2810. Bits = (Bits << 1) | unsigned(II->isPoisoned());
  2811. Bits = (Bits << 1) | unsigned(II->hasRevertedTokenIDToIdentifier());
  2812. Bits = (Bits << 1) | unsigned(II->isCPlusPlusOperatorKeyword());
  2813. LE.write<uint16_t>(Bits);
  2814. if (HadMacroDefinition)
  2815. LE.write<uint32_t>(MacroOffset);
  2816. // Emit the declaration IDs in reverse order, because the
  2817. // IdentifierResolver provides the declarations as they would be
  2818. // visible (e.g., the function "stat" would come before the struct
  2819. // "stat"), but the ASTReader adds declarations to the end of the list
  2820. // (so we need to see the struct "stat" before the function "stat").
  2821. // Only emit declarations that aren't from a chained PCH, though.
  2822. SmallVector<NamedDecl *, 16> Decls(IdResolver.begin(II), IdResolver.end());
  2823. for (SmallVectorImpl<NamedDecl *>::reverse_iterator D = Decls.rbegin(),
  2824. DEnd = Decls.rend();
  2825. D != DEnd; ++D)
  2826. LE.write<uint32_t>(
  2827. Writer.getDeclID(getDeclForLocalLookup(PP.getLangOpts(), *D)));
  2828. }
  2829. };
  2830. } // end anonymous namespace
  2831. /// \brief Write the identifier table into the AST file.
  2832. ///
  2833. /// The identifier table consists of a blob containing string data
  2834. /// (the actual identifiers themselves) and a separate "offsets" index
  2835. /// that maps identifier IDs to locations within the blob.
  2836. void ASTWriter::WriteIdentifierTable(Preprocessor &PP,
  2837. IdentifierResolver &IdResolver,
  2838. bool IsModule) {
  2839. using namespace llvm;
  2840. // Create and write out the blob that contains the identifier
  2841. // strings.
  2842. {
  2843. llvm::OnDiskChainedHashTableGenerator<ASTIdentifierTableTrait> Generator;
  2844. ASTIdentifierTableTrait Trait(*this, PP, IdResolver);
  2845. // Look for any identifiers that were named while processing the
  2846. // headers, but are otherwise not needed. We add these to the hash
  2847. // table to enable checking of the predefines buffer in the case
  2848. // where the user adds new macro definitions when building the AST
  2849. // file.
  2850. SmallVector<const IdentifierInfo *, 128> IIs;
  2851. for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
  2852. IDEnd = PP.getIdentifierTable().end();
  2853. ID != IDEnd; ++ID)
  2854. IIs.push_back(ID->second);
  2855. // Sort the identifiers lexicographically before getting them references so
  2856. // that their order is stable.
  2857. std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
  2858. for (const IdentifierInfo *II : IIs)
  2859. getIdentifierRef(II);
  2860. // Create the on-disk hash table representation. We only store offsets
  2861. // for identifiers that appear here for the first time.
  2862. IdentifierOffsets.resize(NextIdentID - FirstIdentID);
  2863. for (auto IdentIDPair : IdentifierIDs) {
  2864. IdentifierInfo *II = const_cast<IdentifierInfo *>(IdentIDPair.first);
  2865. IdentID ID = IdentIDPair.second;
  2866. assert(II && "NULL identifier in identifier table");
  2867. if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
  2868. Generator.insert(II, ID, Trait);
  2869. }
  2870. // Create the on-disk hash table in a buffer.
  2871. SmallString<4096> IdentifierTable;
  2872. uint32_t BucketOffset;
  2873. {
  2874. using namespace llvm::support;
  2875. llvm::raw_svector_ostream Out(IdentifierTable);
  2876. // Make sure that no bucket is at offset 0
  2877. endian::Writer<little>(Out).write<uint32_t>(0);
  2878. BucketOffset = Generator.Emit(Out, Trait);
  2879. }
  2880. // Create a blob abbreviation
  2881. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2882. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_TABLE));
  2883. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32));
  2884. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2885. unsigned IDTableAbbrev = Stream.EmitAbbrev(Abbrev);
  2886. // Write the identifier table
  2887. RecordData Record;
  2888. Record.push_back(IDENTIFIER_TABLE);
  2889. Record.push_back(BucketOffset);
  2890. Stream.EmitRecordWithBlob(IDTableAbbrev, Record, IdentifierTable);
  2891. }
  2892. // Write the offsets table for identifier IDs.
  2893. BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  2894. Abbrev->Add(BitCodeAbbrevOp(IDENTIFIER_OFFSET));
  2895. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // # of identifiers
  2896. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Fixed, 32)); // first ID
  2897. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  2898. unsigned IdentifierOffsetAbbrev = Stream.EmitAbbrev(Abbrev);
  2899. #ifndef NDEBUG
  2900. for (unsigned I = 0, N = IdentifierOffsets.size(); I != N; ++I)
  2901. assert(IdentifierOffsets[I] && "Missing identifier offset?");
  2902. #endif
  2903. RecordData Record;
  2904. Record.push_back(IDENTIFIER_OFFSET);
  2905. Record.push_back(IdentifierOffsets.size());
  2906. Record.push_back(FirstIdentID - NUM_PREDEF_IDENT_IDS);
  2907. Stream.EmitRecordWithBlob(IdentifierOffsetAbbrev, Record,
  2908. bytes(IdentifierOffsets));
  2909. }
  2910. //===----------------------------------------------------------------------===//
  2911. // DeclContext's Name Lookup Table Serialization
  2912. //===----------------------------------------------------------------------===//
  2913. namespace {
  2914. // Trait used for the on-disk hash table used in the method pool.
  2915. class ASTDeclContextNameLookupTrait {
  2916. ASTWriter &Writer;
  2917. public:
  2918. typedef DeclarationName key_type;
  2919. typedef key_type key_type_ref;
  2920. typedef DeclContext::lookup_result data_type;
  2921. typedef const data_type& data_type_ref;
  2922. typedef unsigned hash_value_type;
  2923. typedef unsigned offset_type;
  2924. explicit ASTDeclContextNameLookupTrait(ASTWriter &Writer) : Writer(Writer) { }
  2925. hash_value_type ComputeHash(DeclarationName Name) {
  2926. llvm::FoldingSetNodeID ID;
  2927. ID.AddInteger(Name.getNameKind());
  2928. switch (Name.getNameKind()) {
  2929. case DeclarationName::Identifier:
  2930. ID.AddString(Name.getAsIdentifierInfo()->getName());
  2931. break;
  2932. case DeclarationName::ObjCZeroArgSelector:
  2933. case DeclarationName::ObjCOneArgSelector:
  2934. case DeclarationName::ObjCMultiArgSelector:
  2935. ID.AddInteger(serialization::ComputeHash(Name.getObjCSelector()));
  2936. break;
  2937. case DeclarationName::CXXConstructorName:
  2938. case DeclarationName::CXXDestructorName:
  2939. case DeclarationName::CXXConversionFunctionName:
  2940. break;
  2941. case DeclarationName::CXXOperatorName:
  2942. ID.AddInteger(Name.getCXXOverloadedOperator());
  2943. break;
  2944. case DeclarationName::CXXLiteralOperatorName:
  2945. ID.AddString(Name.getCXXLiteralIdentifier()->getName());
  2946. case DeclarationName::CXXUsingDirective:
  2947. break;
  2948. }
  2949. return ID.ComputeHash();
  2950. }
  2951. std::pair<unsigned,unsigned>
  2952. EmitKeyDataLength(raw_ostream& Out, DeclarationName Name,
  2953. data_type_ref Lookup) {
  2954. using namespace llvm::support;
  2955. endian::Writer<little> LE(Out);
  2956. unsigned KeyLen = 1;
  2957. switch (Name.getNameKind()) {
  2958. case DeclarationName::Identifier:
  2959. case DeclarationName::ObjCZeroArgSelector:
  2960. case DeclarationName::ObjCOneArgSelector:
  2961. case DeclarationName::ObjCMultiArgSelector:
  2962. case DeclarationName::CXXLiteralOperatorName:
  2963. KeyLen += 4;
  2964. break;
  2965. case DeclarationName::CXXOperatorName:
  2966. KeyLen += 1;
  2967. break;
  2968. case DeclarationName::CXXConstructorName:
  2969. case DeclarationName::CXXDestructorName:
  2970. case DeclarationName::CXXConversionFunctionName:
  2971. case DeclarationName::CXXUsingDirective:
  2972. break;
  2973. }
  2974. LE.write<uint16_t>(KeyLen);
  2975. // 2 bytes for num of decls and 4 for each DeclID.
  2976. unsigned DataLen = 2 + 4 * Lookup.size();
  2977. LE.write<uint16_t>(DataLen);
  2978. return std::make_pair(KeyLen, DataLen);
  2979. }
  2980. void EmitKey(raw_ostream& Out, DeclarationName Name, unsigned) {
  2981. using namespace llvm::support;
  2982. endian::Writer<little> LE(Out);
  2983. LE.write<uint8_t>(Name.getNameKind());
  2984. switch (Name.getNameKind()) {
  2985. case DeclarationName::Identifier:
  2986. LE.write<uint32_t>(Writer.getIdentifierRef(Name.getAsIdentifierInfo()));
  2987. return;
  2988. case DeclarationName::ObjCZeroArgSelector:
  2989. case DeclarationName::ObjCOneArgSelector:
  2990. case DeclarationName::ObjCMultiArgSelector:
  2991. LE.write<uint32_t>(Writer.getSelectorRef(Name.getObjCSelector()));
  2992. return;
  2993. case DeclarationName::CXXOperatorName:
  2994. assert(Name.getCXXOverloadedOperator() < NUM_OVERLOADED_OPERATORS &&
  2995. "Invalid operator?");
  2996. LE.write<uint8_t>(Name.getCXXOverloadedOperator());
  2997. return;
  2998. case DeclarationName::CXXLiteralOperatorName:
  2999. LE.write<uint32_t>(Writer.getIdentifierRef(Name.getCXXLiteralIdentifier()));
  3000. return;
  3001. case DeclarationName::CXXConstructorName:
  3002. case DeclarationName::CXXDestructorName:
  3003. case DeclarationName::CXXConversionFunctionName:
  3004. case DeclarationName::CXXUsingDirective:
  3005. return;
  3006. }
  3007. llvm_unreachable("Invalid name kind?");
  3008. }
  3009. void EmitData(raw_ostream& Out, key_type_ref,
  3010. data_type Lookup, unsigned DataLen) {
  3011. using namespace llvm::support;
  3012. endian::Writer<little> LE(Out);
  3013. uint64_t Start = Out.tell(); (void)Start;
  3014. LE.write<uint16_t>(Lookup.size());
  3015. for (DeclContext::lookup_iterator I = Lookup.begin(), E = Lookup.end();
  3016. I != E; ++I)
  3017. LE.write<uint32_t>(
  3018. Writer.GetDeclRef(getDeclForLocalLookup(Writer.getLangOpts(), *I)));
  3019. assert(Out.tell() - Start == DataLen && "Data length is wrong");
  3020. }
  3021. };
  3022. } // end anonymous namespace
  3023. bool ASTWriter::isLookupResultExternal(StoredDeclsList &Result,
  3024. DeclContext *DC) {
  3025. return Result.hasExternalDecls() && DC->NeedToReconcileExternalVisibleStorage;
  3026. }
  3027. bool ASTWriter::isLookupResultEntirelyExternal(StoredDeclsList &Result,
  3028. DeclContext *DC) {
  3029. for (auto *D : Result.getLookupResult())
  3030. if (!getDeclForLocalLookup(getLangOpts(), D)->isFromASTFile())
  3031. return false;
  3032. return true;
  3033. }
  3034. uint32_t
  3035. ASTWriter::GenerateNameLookupTable(const DeclContext *ConstDC,
  3036. llvm::SmallVectorImpl<char> &LookupTable) {
  3037. assert(!ConstDC->HasLazyLocalLexicalLookups &&
  3038. !ConstDC->HasLazyExternalLexicalLookups &&
  3039. "must call buildLookups first");
  3040. // FIXME: We need to build the lookups table, which is logically const.
  3041. DeclContext *DC = const_cast<DeclContext*>(ConstDC);
  3042. assert(DC == DC->getPrimaryContext() && "only primary DC has lookup table");
  3043. // Create the on-disk hash table representation.
  3044. llvm::OnDiskChainedHashTableGenerator<ASTDeclContextNameLookupTrait>
  3045. Generator;
  3046. ASTDeclContextNameLookupTrait Trait(*this);
  3047. // The first step is to collect the declaration names which we need to
  3048. // serialize into the name lookup table, and to collect them in a stable
  3049. // order.
  3050. SmallVector<DeclarationName, 16> Names;
  3051. // We also build up small sets of the constructor and conversion function
  3052. // names which are visible.
  3053. llvm::SmallSet<DeclarationName, 8> ConstructorNameSet, ConversionNameSet;
  3054. for (auto &Lookup : *DC->buildLookup()) {
  3055. auto &Name = Lookup.first;
  3056. auto &Result = Lookup.second;
  3057. // If there are no local declarations in our lookup result, we don't
  3058. // need to write an entry for the name at all unless we're rewriting
  3059. // the decl context. If we can't write out a lookup set without
  3060. // performing more deserialization, just skip this entry.
  3061. if (isLookupResultExternal(Result, DC) && !isRewritten(cast<Decl>(DC)) &&
  3062. isLookupResultEntirelyExternal(Result, DC))
  3063. continue;
  3064. // We also skip empty results. If any of the results could be external and
  3065. // the currently available results are empty, then all of the results are
  3066. // external and we skip it above. So the only way we get here with an empty
  3067. // results is when no results could have been external *and* we have
  3068. // external results.
  3069. //
  3070. // FIXME: While we might want to start emitting on-disk entries for negative
  3071. // lookups into a decl context as an optimization, today we *have* to skip
  3072. // them because there are names with empty lookup results in decl contexts
  3073. // which we can't emit in any stable ordering: we lookup constructors and
  3074. // conversion functions in the enclosing namespace scope creating empty
  3075. // results for them. This in almost certainly a bug in Clang's name lookup,
  3076. // but that is likely to be hard or impossible to fix and so we tolerate it
  3077. // here by omitting lookups with empty results.
  3078. if (Lookup.second.getLookupResult().empty())
  3079. continue;
  3080. switch (Lookup.first.getNameKind()) {
  3081. default:
  3082. Names.push_back(Lookup.first);
  3083. break;
  3084. case DeclarationName::CXXConstructorName:
  3085. assert(isa<CXXRecordDecl>(DC) &&
  3086. "Cannot have a constructor name outside of a class!");
  3087. ConstructorNameSet.insert(Name);
  3088. break;
  3089. case DeclarationName::CXXConversionFunctionName:
  3090. assert(isa<CXXRecordDecl>(DC) &&
  3091. "Cannot have a conversion function name outside of a class!");
  3092. ConversionNameSet.insert(Name);
  3093. break;
  3094. }
  3095. }
  3096. // Sort the names into a stable order.
  3097. std::sort(Names.begin(), Names.end());
  3098. if (auto *D = dyn_cast<CXXRecordDecl>(DC)) {
  3099. // We need to establish an ordering of constructor and conversion function
  3100. // names, and they don't have an intrinsic ordering.
  3101. // First we try the easy case by forming the current context's constructor
  3102. // name and adding that name first. This is a very useful optimization to
  3103. // avoid walking the lexical declarations in many cases, and it also
  3104. // handles the only case where a constructor name can come from some other
  3105. // lexical context -- when that name is an implicit constructor merged from
  3106. // another declaration in the redecl chain. Any non-implicit constructor or
  3107. // conversion function which doesn't occur in all the lexical contexts
  3108. // would be an ODR violation.
  3109. auto ImplicitCtorName = Context->DeclarationNames.getCXXConstructorName(
  3110. Context->getCanonicalType(Context->getRecordType(D)));
  3111. if (ConstructorNameSet.erase(ImplicitCtorName))
  3112. Names.push_back(ImplicitCtorName);
  3113. // If we still have constructors or conversion functions, we walk all the
  3114. // names in the decl and add the constructors and conversion functions
  3115. // which are visible in the order they lexically occur within the context.
  3116. if (!ConstructorNameSet.empty() || !ConversionNameSet.empty())
  3117. for (Decl *ChildD : cast<CXXRecordDecl>(DC)->decls())
  3118. if (auto *ChildND = dyn_cast<NamedDecl>(ChildD)) {
  3119. auto Name = ChildND->getDeclName();
  3120. switch (Name.getNameKind()) {
  3121. default:
  3122. continue;
  3123. case DeclarationName::CXXConstructorName:
  3124. if (ConstructorNameSet.erase(Name))
  3125. Names.push_back(Name);
  3126. break;
  3127. case DeclarationName::CXXConversionFunctionName:
  3128. if (ConversionNameSet.erase(Name))
  3129. Names.push_back(Name);
  3130. break;
  3131. }
  3132. if (ConstructorNameSet.empty() && ConversionNameSet.empty())
  3133. break;
  3134. }
  3135. assert(ConstructorNameSet.empty() && "Failed to find all of the visible "
  3136. "constructors by walking all the "
  3137. "lexical members of the context.");
  3138. assert(ConversionNameSet.empty() && "Failed to find all of the visible "
  3139. "conversion functions by walking all "
  3140. "the lexical members of the context.");
  3141. }
  3142. // Next we need to do a lookup with each name into this decl context to fully
  3143. // populate any results from external sources. We don't actually use the
  3144. // results of these lookups because we only want to use the results after all
  3145. // results have been loaded and the pointers into them will be stable.
  3146. for (auto &Name : Names)
  3147. DC->lookup(Name);
  3148. // Now we need to insert the results for each name into the hash table. For
  3149. // constructor names and conversion function names, we actually need to merge
  3150. // all of the results for them into one list of results each and insert
  3151. // those.
  3152. SmallVector<NamedDecl *, 8> ConstructorDecls;
  3153. SmallVector<NamedDecl *, 8> ConversionDecls;
  3154. // Now loop over the names, either inserting them or appending for the two
  3155. // special cases.
  3156. for (auto &Name : Names) {
  3157. DeclContext::lookup_result Result = DC->noload_lookup(Name);
  3158. switch (Name.getNameKind()) {
  3159. default:
  3160. Generator.insert(Name, Result, Trait);
  3161. break;
  3162. case DeclarationName::CXXConstructorName:
  3163. ConstructorDecls.append(Result.begin(), Result.end());
  3164. break;
  3165. case DeclarationName::CXXConversionFunctionName:
  3166. ConversionDecls.append(Result.begin(), Result.end());
  3167. break;
  3168. }
  3169. }
  3170. // Handle our two special cases if we ended up having any. We arbitrarily use
  3171. // the first declaration's name here because the name itself isn't part of
  3172. // the key, only the kind of name is used.
  3173. if (!ConstructorDecls.empty())
  3174. Generator.insert(ConstructorDecls.front()->getDeclName(),
  3175. DeclContext::lookup_result(ConstructorDecls), Trait);
  3176. if (!ConversionDecls.empty())
  3177. Generator.insert(ConversionDecls.front()->getDeclName(),
  3178. DeclContext::lookup_result(ConversionDecls), Trait);
  3179. // Create the on-disk hash table in a buffer.
  3180. llvm::raw_svector_ostream Out(LookupTable);
  3181. // Make sure that no bucket is at offset 0
  3182. using namespace llvm::support;
  3183. endian::Writer<little>(Out).write<uint32_t>(0);
  3184. return Generator.Emit(Out, Trait);
  3185. }
  3186. /// \brief Write the block containing all of the declaration IDs
  3187. /// visible from the given DeclContext.
  3188. ///
  3189. /// \returns the offset of the DECL_CONTEXT_VISIBLE block within the
  3190. /// bitstream, or 0 if no block was written.
  3191. uint64_t ASTWriter::WriteDeclContextVisibleBlock(ASTContext &Context,
  3192. DeclContext *DC) {
  3193. // If we imported a key declaration of this namespace, write the visible
  3194. // lookup results as an update record for it rather than including them
  3195. // on this declaration. We will only look at key declarations on reload.
  3196. if (isa<NamespaceDecl>(DC) && Chain &&
  3197. Chain->getKeyDeclaration(cast<Decl>(DC))->isFromASTFile()) {
  3198. // Only do this once, for the first local declaration of the namespace.
  3199. for (NamespaceDecl *Prev = cast<NamespaceDecl>(DC)->getPreviousDecl(); Prev;
  3200. Prev = Prev->getPreviousDecl())
  3201. if (!Prev->isFromASTFile())
  3202. return 0;
  3203. // Note that we need to emit an update record for the primary context.
  3204. UpdatedDeclContexts.insert(DC->getPrimaryContext());
  3205. // Make sure all visible decls are written. They will be recorded later. We
  3206. // do this using a side data structure so we can sort the names into
  3207. // a deterministic order.
  3208. StoredDeclsMap *Map = DC->getPrimaryContext()->buildLookup();
  3209. SmallVector<std::pair<DeclarationName, DeclContext::lookup_result>, 16>
  3210. LookupResults;
  3211. if (Map) {
  3212. LookupResults.reserve(Map->size());
  3213. for (auto &Entry : *Map)
  3214. LookupResults.push_back(
  3215. std::make_pair(Entry.first, Entry.second.getLookupResult()));
  3216. }
  3217. std::sort(LookupResults.begin(), LookupResults.end(), llvm::less_first());
  3218. for (auto &NameAndResult : LookupResults) {
  3219. DeclarationName Name = NameAndResult.first;
  3220. DeclContext::lookup_result Result = NameAndResult.second;
  3221. if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
  3222. Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
  3223. // We have to work around a name lookup bug here where negative lookup
  3224. // results for these names get cached in namespace lookup tables (these
  3225. // names should never be looked up in a namespace).
  3226. assert(Result.empty() && "Cannot have a constructor or conversion "
  3227. "function name in a namespace!");
  3228. continue;
  3229. }
  3230. for (NamedDecl *ND : Result)
  3231. if (!ND->isFromASTFile())
  3232. GetDeclRef(ND);
  3233. }
  3234. return 0;
  3235. }
  3236. if (DC->getPrimaryContext() != DC)
  3237. return 0;
  3238. // Skip contexts which don't support name lookup.
  3239. if (!DC->isLookupContext())
  3240. return 0;
  3241. // If not in C++, we perform name lookup for the translation unit via the
  3242. // IdentifierInfo chains, don't bother to build a visible-declarations table.
  3243. if (DC->isTranslationUnit() && !Context.getLangOpts().CPlusPlus)
  3244. return 0;
  3245. // Serialize the contents of the mapping used for lookup. Note that,
  3246. // although we have two very different code paths, the serialized
  3247. // representation is the same for both cases: a declaration name,
  3248. // followed by a size, followed by references to the visible
  3249. // declarations that have that name.
  3250. uint64_t Offset = Stream.GetCurrentBitNo();
  3251. StoredDeclsMap *Map = DC->buildLookup();
  3252. if (!Map || Map->empty())
  3253. return 0;
  3254. // Create the on-disk hash table in a buffer.
  3255. SmallString<4096> LookupTable;
  3256. uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
  3257. // Write the lookup table
  3258. RecordData Record;
  3259. Record.push_back(DECL_CONTEXT_VISIBLE);
  3260. Record.push_back(BucketOffset);
  3261. Stream.EmitRecordWithBlob(DeclContextVisibleLookupAbbrev, Record,
  3262. LookupTable);
  3263. ++NumVisibleDeclContexts;
  3264. return Offset;
  3265. }
  3266. /// \brief Write an UPDATE_VISIBLE block for the given context.
  3267. ///
  3268. /// UPDATE_VISIBLE blocks contain the declarations that are added to an existing
  3269. /// DeclContext in a dependent AST file. As such, they only exist for the TU
  3270. /// (in C++), for namespaces, and for classes with forward-declared unscoped
  3271. /// enumeration members (in C++11).
  3272. void ASTWriter::WriteDeclContextVisibleUpdate(const DeclContext *DC) {
  3273. StoredDeclsMap *Map = DC->getLookupPtr();
  3274. if (!Map || Map->empty())
  3275. return;
  3276. // Create the on-disk hash table in a buffer.
  3277. SmallString<4096> LookupTable;
  3278. uint32_t BucketOffset = GenerateNameLookupTable(DC, LookupTable);
  3279. // If we're updating a namespace, select a key declaration as the key for the
  3280. // update record; those are the only ones that will be checked on reload.
  3281. if (isa<NamespaceDecl>(DC))
  3282. DC = cast<DeclContext>(Chain->getKeyDeclaration(cast<Decl>(DC)));
  3283. // Write the lookup table
  3284. RecordData Record;
  3285. Record.push_back(UPDATE_VISIBLE);
  3286. Record.push_back(getDeclID(cast<Decl>(DC)));
  3287. Record.push_back(BucketOffset);
  3288. Stream.EmitRecordWithBlob(UpdateVisibleAbbrev, Record, LookupTable);
  3289. }
  3290. /// \brief Write an FP_PRAGMA_OPTIONS block for the given FPOptions.
  3291. void ASTWriter::WriteFPPragmaOptions(const FPOptions &Opts) {
  3292. RecordData Record;
  3293. Record.push_back(Opts.fp_contract);
  3294. Stream.EmitRecord(FP_PRAGMA_OPTIONS, Record);
  3295. }
  3296. /// \brief Write an OPENCL_EXTENSIONS block for the given OpenCLOptions.
  3297. void ASTWriter::WriteOpenCLExtensions(Sema &SemaRef) {
  3298. if (!SemaRef.Context.getLangOpts().OpenCL)
  3299. return;
  3300. const OpenCLOptions &Opts = SemaRef.getOpenCLOptions();
  3301. RecordData Record;
  3302. #define OPENCLEXT(nm) Record.push_back(Opts.nm);
  3303. #include "clang/Basic/OpenCLExtensions.def"
  3304. Stream.EmitRecord(OPENCL_EXTENSIONS, Record);
  3305. }
  3306. void ASTWriter::WriteRedeclarations() {
  3307. RecordData LocalRedeclChains;
  3308. SmallVector<serialization::LocalRedeclarationsInfo, 2> LocalRedeclsMap;
  3309. for (unsigned I = 0, N = Redeclarations.size(); I != N; ++I) {
  3310. const Decl *Key = Redeclarations[I];
  3311. assert((Chain ? Chain->getKeyDeclaration(Key) == Key
  3312. : Key->isFirstDecl()) &&
  3313. "not the key declaration");
  3314. const Decl *First = Key->getCanonicalDecl();
  3315. const Decl *MostRecent = First->getMostRecentDecl();
  3316. assert((getDeclID(First) >= NUM_PREDEF_DECL_IDS || First == Key) &&
  3317. "should not have imported key decls for predefined decl");
  3318. // If we only have a single declaration, there is no point in storing
  3319. // a redeclaration chain.
  3320. if (First == MostRecent)
  3321. continue;
  3322. unsigned Offset = LocalRedeclChains.size();
  3323. unsigned Size = 0;
  3324. LocalRedeclChains.push_back(0); // Placeholder for the size.
  3325. // Collect the set of local redeclarations of this declaration.
  3326. for (const Decl *Prev = MostRecent; Prev;
  3327. Prev = Prev->getPreviousDecl()) {
  3328. if (!Prev->isFromASTFile() && Prev != Key) {
  3329. AddDeclRef(Prev, LocalRedeclChains);
  3330. ++Size;
  3331. }
  3332. }
  3333. LocalRedeclChains[Offset] = Size;
  3334. // Reverse the set of local redeclarations, so that we store them in
  3335. // order (since we found them in reverse order).
  3336. std::reverse(LocalRedeclChains.end() - Size, LocalRedeclChains.end());
  3337. // Add the mapping from the first ID from the AST to the set of local
  3338. // declarations.
  3339. LocalRedeclarationsInfo Info = { getDeclID(Key), Offset };
  3340. LocalRedeclsMap.push_back(Info);
  3341. assert(N == Redeclarations.size() &&
  3342. "Deserialized a declaration we shouldn't have");
  3343. }
  3344. if (LocalRedeclChains.empty())
  3345. return;
  3346. // Sort the local redeclarations map by the first declaration ID,
  3347. // since the reader will be performing binary searches on this information.
  3348. llvm::array_pod_sort(LocalRedeclsMap.begin(), LocalRedeclsMap.end());
  3349. // Emit the local redeclarations map.
  3350. using namespace llvm;
  3351. llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  3352. Abbrev->Add(BitCodeAbbrevOp(LOCAL_REDECLARATIONS_MAP));
  3353. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
  3354. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3355. unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
  3356. RecordData Record;
  3357. Record.push_back(LOCAL_REDECLARATIONS_MAP);
  3358. Record.push_back(LocalRedeclsMap.size());
  3359. Stream.EmitRecordWithBlob(AbbrevID, Record,
  3360. reinterpret_cast<char*>(LocalRedeclsMap.data()),
  3361. LocalRedeclsMap.size() * sizeof(LocalRedeclarationsInfo));
  3362. // Emit the redeclaration chains.
  3363. Stream.EmitRecord(LOCAL_REDECLARATIONS, LocalRedeclChains);
  3364. }
  3365. void ASTWriter::WriteObjCCategories() {
  3366. SmallVector<ObjCCategoriesInfo, 2> CategoriesMap;
  3367. RecordData Categories;
  3368. for (unsigned I = 0, N = ObjCClassesWithCategories.size(); I != N; ++I) {
  3369. unsigned Size = 0;
  3370. unsigned StartIndex = Categories.size();
  3371. ObjCInterfaceDecl *Class = ObjCClassesWithCategories[I];
  3372. // Allocate space for the size.
  3373. Categories.push_back(0);
  3374. // Add the categories.
  3375. for (ObjCInterfaceDecl::known_categories_iterator
  3376. Cat = Class->known_categories_begin(),
  3377. CatEnd = Class->known_categories_end();
  3378. Cat != CatEnd; ++Cat, ++Size) {
  3379. assert(getDeclID(*Cat) != 0 && "Bogus category");
  3380. AddDeclRef(*Cat, Categories);
  3381. }
  3382. // Update the size.
  3383. Categories[StartIndex] = Size;
  3384. // Record this interface -> category map.
  3385. ObjCCategoriesInfo CatInfo = { getDeclID(Class), StartIndex };
  3386. CategoriesMap.push_back(CatInfo);
  3387. }
  3388. // Sort the categories map by the definition ID, since the reader will be
  3389. // performing binary searches on this information.
  3390. llvm::array_pod_sort(CategoriesMap.begin(), CategoriesMap.end());
  3391. // Emit the categories map.
  3392. using namespace llvm;
  3393. llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  3394. Abbrev->Add(BitCodeAbbrevOp(OBJC_CATEGORIES_MAP));
  3395. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::VBR, 6)); // # of entries
  3396. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3397. unsigned AbbrevID = Stream.EmitAbbrev(Abbrev);
  3398. RecordData Record;
  3399. Record.push_back(OBJC_CATEGORIES_MAP);
  3400. Record.push_back(CategoriesMap.size());
  3401. Stream.EmitRecordWithBlob(AbbrevID, Record,
  3402. reinterpret_cast<char*>(CategoriesMap.data()),
  3403. CategoriesMap.size() * sizeof(ObjCCategoriesInfo));
  3404. // Emit the category lists.
  3405. Stream.EmitRecord(OBJC_CATEGORIES, Categories);
  3406. }
  3407. void ASTWriter::WriteLateParsedTemplates(Sema &SemaRef) {
  3408. Sema::LateParsedTemplateMapT &LPTMap = SemaRef.LateParsedTemplateMap;
  3409. if (LPTMap.empty())
  3410. return;
  3411. RecordData Record;
  3412. for (auto LPTMapEntry : LPTMap) {
  3413. const FunctionDecl *FD = LPTMapEntry.first;
  3414. LateParsedTemplate *LPT = LPTMapEntry.second;
  3415. AddDeclRef(FD, Record);
  3416. AddDeclRef(LPT->D, Record);
  3417. Record.push_back(LPT->Toks.size());
  3418. for (CachedTokens::iterator TokIt = LPT->Toks.begin(),
  3419. TokEnd = LPT->Toks.end();
  3420. TokIt != TokEnd; ++TokIt) {
  3421. AddToken(*TokIt, Record);
  3422. }
  3423. }
  3424. Stream.EmitRecord(LATE_PARSED_TEMPLATE, Record);
  3425. }
  3426. /// \brief Write the state of 'pragma clang optimize' at the end of the module.
  3427. void ASTWriter::WriteOptimizePragmaOptions(Sema &SemaRef) {
  3428. RecordData Record;
  3429. SourceLocation PragmaLoc = SemaRef.getOptimizeOffPragmaLocation();
  3430. AddSourceLocation(PragmaLoc, Record);
  3431. Stream.EmitRecord(OPTIMIZE_PRAGMA_OPTIONS, Record);
  3432. }
  3433. //===----------------------------------------------------------------------===//
  3434. // General Serialization Routines
  3435. //===----------------------------------------------------------------------===//
  3436. /// \brief Write a record containing the given attributes.
  3437. void ASTWriter::WriteAttributes(ArrayRef<const Attr*> Attrs,
  3438. RecordDataImpl &Record) {
  3439. Record.push_back(Attrs.size());
  3440. for (ArrayRef<const Attr *>::iterator i = Attrs.begin(),
  3441. e = Attrs.end(); i != e; ++i){
  3442. const Attr *A = *i;
  3443. Record.push_back(A->getKind()); // FIXME: stable encoding, target attrs
  3444. AddSourceRange(A->getRange(), Record);
  3445. #include "clang/Serialization/AttrPCHWrite.inc"
  3446. }
  3447. }
  3448. void ASTWriter::AddToken(const Token &Tok, RecordDataImpl &Record) {
  3449. AddSourceLocation(Tok.getLocation(), Record);
  3450. Record.push_back(Tok.getLength());
  3451. // FIXME: When reading literal tokens, reconstruct the literal pointer
  3452. // if it is needed.
  3453. AddIdentifierRef(Tok.getIdentifierInfo(), Record);
  3454. // FIXME: Should translate token kind to a stable encoding.
  3455. Record.push_back(Tok.getKind());
  3456. // FIXME: Should translate token flags to a stable encoding.
  3457. Record.push_back(Tok.getFlags());
  3458. }
  3459. void ASTWriter::AddString(StringRef Str, RecordDataImpl &Record) {
  3460. Record.push_back(Str.size());
  3461. Record.insert(Record.end(), Str.begin(), Str.end());
  3462. }
  3463. bool ASTWriter::PreparePathForOutput(SmallVectorImpl<char> &Path) {
  3464. assert(Context && "should have context when outputting path");
  3465. bool Changed =
  3466. cleanPathForOutput(Context->getSourceManager().getFileManager(), Path);
  3467. // Remove a prefix to make the path relative, if relevant.
  3468. const char *PathBegin = Path.data();
  3469. const char *PathPtr =
  3470. adjustFilenameForRelocatableAST(PathBegin, BaseDirectory);
  3471. if (PathPtr != PathBegin) {
  3472. Path.erase(Path.begin(), Path.begin() + (PathPtr - PathBegin));
  3473. Changed = true;
  3474. }
  3475. return Changed;
  3476. }
  3477. void ASTWriter::AddPath(StringRef Path, RecordDataImpl &Record) {
  3478. SmallString<128> FilePath(Path);
  3479. PreparePathForOutput(FilePath);
  3480. AddString(FilePath, Record);
  3481. }
  3482. void ASTWriter::EmitRecordWithPath(unsigned Abbrev, RecordDataImpl &Record,
  3483. StringRef Path) {
  3484. SmallString<128> FilePath(Path);
  3485. PreparePathForOutput(FilePath);
  3486. Stream.EmitRecordWithBlob(Abbrev, Record, FilePath);
  3487. }
  3488. void ASTWriter::AddVersionTuple(const VersionTuple &Version,
  3489. RecordDataImpl &Record) {
  3490. Record.push_back(Version.getMajor());
  3491. if (Optional<unsigned> Minor = Version.getMinor())
  3492. Record.push_back(*Minor + 1);
  3493. else
  3494. Record.push_back(0);
  3495. if (Optional<unsigned> Subminor = Version.getSubminor())
  3496. Record.push_back(*Subminor + 1);
  3497. else
  3498. Record.push_back(0);
  3499. }
  3500. /// \brief Note that the identifier II occurs at the given offset
  3501. /// within the identifier table.
  3502. void ASTWriter::SetIdentifierOffset(const IdentifierInfo *II, uint32_t Offset) {
  3503. IdentID ID = IdentifierIDs[II];
  3504. // Only store offsets new to this AST file. Other identifier names are looked
  3505. // up earlier in the chain and thus don't need an offset.
  3506. if (ID >= FirstIdentID)
  3507. IdentifierOffsets[ID - FirstIdentID] = Offset;
  3508. }
  3509. /// \brief Note that the selector Sel occurs at the given offset
  3510. /// within the method pool/selector table.
  3511. void ASTWriter::SetSelectorOffset(Selector Sel, uint32_t Offset) {
  3512. unsigned ID = SelectorIDs[Sel];
  3513. assert(ID && "Unknown selector");
  3514. // Don't record offsets for selectors that are also available in a different
  3515. // file.
  3516. if (ID < FirstSelectorID)
  3517. return;
  3518. SelectorOffsets[ID - FirstSelectorID] = Offset;
  3519. }
  3520. ASTWriter::ASTWriter(llvm::BitstreamWriter &Stream)
  3521. : Stream(Stream), Context(nullptr), PP(nullptr), Chain(nullptr),
  3522. WritingModule(nullptr), WritingAST(false),
  3523. DoneWritingDeclsAndTypes(false), ASTHasCompilerErrors(false),
  3524. FirstDeclID(NUM_PREDEF_DECL_IDS), NextDeclID(FirstDeclID),
  3525. FirstTypeID(NUM_PREDEF_TYPE_IDS), NextTypeID(FirstTypeID),
  3526. FirstIdentID(NUM_PREDEF_IDENT_IDS), NextIdentID(FirstIdentID),
  3527. FirstMacroID(NUM_PREDEF_MACRO_IDS), NextMacroID(FirstMacroID),
  3528. FirstSubmoduleID(NUM_PREDEF_SUBMODULE_IDS),
  3529. NextSubmoduleID(FirstSubmoduleID),
  3530. FirstSelectorID(NUM_PREDEF_SELECTOR_IDS), NextSelectorID(FirstSelectorID),
  3531. CollectedStmts(&StmtsToEmit), NumStatements(0), NumMacros(0),
  3532. NumLexicalDeclContexts(0), NumVisibleDeclContexts(0),
  3533. NextCXXBaseSpecifiersID(1), NextCXXCtorInitializersID(1),
  3534. TypeExtQualAbbrev(0),
  3535. TypeFunctionProtoAbbrev(0), DeclParmVarAbbrev(0),
  3536. DeclContextLexicalAbbrev(0), DeclContextVisibleLookupAbbrev(0),
  3537. UpdateVisibleAbbrev(0), DeclRecordAbbrev(0), DeclTypedefAbbrev(0),
  3538. DeclVarAbbrev(0), DeclFieldAbbrev(0), DeclEnumAbbrev(0),
  3539. DeclObjCIvarAbbrev(0), DeclCXXMethodAbbrev(0), DeclRefExprAbbrev(0),
  3540. CharacterLiteralAbbrev(0), IntegerLiteralAbbrev(0),
  3541. ExprImplicitCastAbbrev(0) {}
  3542. ASTWriter::~ASTWriter() {
  3543. llvm::DeleteContainerSeconds(FileDeclIDs);
  3544. }
  3545. const LangOptions &ASTWriter::getLangOpts() const {
  3546. assert(WritingAST && "can't determine lang opts when not writing AST");
  3547. return Context->getLangOpts();
  3548. }
  3549. void ASTWriter::WriteAST(Sema &SemaRef,
  3550. const std::string &OutputFile,
  3551. Module *WritingModule, StringRef isysroot,
  3552. bool hasErrors) {
  3553. WritingAST = true;
  3554. ASTHasCompilerErrors = hasErrors;
  3555. // Emit the file header.
  3556. Stream.Emit((unsigned)'C', 8);
  3557. Stream.Emit((unsigned)'P', 8);
  3558. Stream.Emit((unsigned)'C', 8);
  3559. Stream.Emit((unsigned)'H', 8);
  3560. WriteBlockInfoBlock();
  3561. Context = &SemaRef.Context;
  3562. PP = &SemaRef.PP;
  3563. this->WritingModule = WritingModule;
  3564. WriteASTCore(SemaRef, isysroot, OutputFile, WritingModule);
  3565. Context = nullptr;
  3566. PP = nullptr;
  3567. this->WritingModule = nullptr;
  3568. this->BaseDirectory.clear();
  3569. WritingAST = false;
  3570. }
  3571. template<typename Vector>
  3572. static void AddLazyVectorDecls(ASTWriter &Writer, Vector &Vec,
  3573. ASTWriter::RecordData &Record) {
  3574. for (typename Vector::iterator I = Vec.begin(nullptr, true), E = Vec.end();
  3575. I != E; ++I) {
  3576. Writer.AddDeclRef(*I, Record);
  3577. }
  3578. }
  3579. void ASTWriter::WriteASTCore(Sema &SemaRef,
  3580. StringRef isysroot,
  3581. const std::string &OutputFile,
  3582. Module *WritingModule) {
  3583. using namespace llvm;
  3584. bool isModule = WritingModule != nullptr;
  3585. // Make sure that the AST reader knows to finalize itself.
  3586. if (Chain)
  3587. Chain->finalizeForWriting();
  3588. ASTContext &Context = SemaRef.Context;
  3589. Preprocessor &PP = SemaRef.PP;
  3590. // Set up predefined declaration IDs.
  3591. auto RegisterPredefDecl = [&] (Decl *D, PredefinedDeclIDs ID) {
  3592. if (D) {
  3593. assert(D->isCanonicalDecl() && "predefined decl is not canonical");
  3594. DeclIDs[D] = ID;
  3595. if (D->getMostRecentDecl() != D)
  3596. Redeclarations.push_back(D);
  3597. }
  3598. };
  3599. RegisterPredefDecl(Context.getTranslationUnitDecl(),
  3600. PREDEF_DECL_TRANSLATION_UNIT_ID);
  3601. RegisterPredefDecl(Context.ObjCIdDecl, PREDEF_DECL_OBJC_ID_ID);
  3602. RegisterPredefDecl(Context.ObjCSelDecl, PREDEF_DECL_OBJC_SEL_ID);
  3603. RegisterPredefDecl(Context.ObjCClassDecl, PREDEF_DECL_OBJC_CLASS_ID);
  3604. RegisterPredefDecl(Context.ObjCProtocolClassDecl,
  3605. PREDEF_DECL_OBJC_PROTOCOL_ID);
  3606. RegisterPredefDecl(Context.Int128Decl, PREDEF_DECL_INT_128_ID);
  3607. RegisterPredefDecl(Context.UInt128Decl, PREDEF_DECL_UNSIGNED_INT_128_ID);
  3608. RegisterPredefDecl(Context.ObjCInstanceTypeDecl,
  3609. PREDEF_DECL_OBJC_INSTANCETYPE_ID);
  3610. RegisterPredefDecl(Context.BuiltinVaListDecl, PREDEF_DECL_BUILTIN_VA_LIST_ID);
  3611. RegisterPredefDecl(Context.ExternCContext, PREDEF_DECL_EXTERN_C_CONTEXT_ID);
  3612. // Build a record containing all of the tentative definitions in this file, in
  3613. // TentativeDefinitions order. Generally, this record will be empty for
  3614. // headers.
  3615. RecordData TentativeDefinitions;
  3616. AddLazyVectorDecls(*this, SemaRef.TentativeDefinitions, TentativeDefinitions);
  3617. // Build a record containing all of the file scoped decls in this file.
  3618. RecordData UnusedFileScopedDecls;
  3619. if (!isModule)
  3620. AddLazyVectorDecls(*this, SemaRef.UnusedFileScopedDecls,
  3621. UnusedFileScopedDecls);
  3622. // Build a record containing all of the delegating constructors we still need
  3623. // to resolve.
  3624. RecordData DelegatingCtorDecls;
  3625. if (!isModule)
  3626. AddLazyVectorDecls(*this, SemaRef.DelegatingCtorDecls, DelegatingCtorDecls);
  3627. // Write the set of weak, undeclared identifiers. We always write the
  3628. // entire table, since later PCH files in a PCH chain are only interested in
  3629. // the results at the end of the chain.
  3630. RecordData WeakUndeclaredIdentifiers;
  3631. for (auto &WeakUndeclaredIdentifier : SemaRef.WeakUndeclaredIdentifiers) {
  3632. IdentifierInfo *II = WeakUndeclaredIdentifier.first;
  3633. WeakInfo &WI = WeakUndeclaredIdentifier.second;
  3634. AddIdentifierRef(II, WeakUndeclaredIdentifiers);
  3635. AddIdentifierRef(WI.getAlias(), WeakUndeclaredIdentifiers);
  3636. AddSourceLocation(WI.getLocation(), WeakUndeclaredIdentifiers);
  3637. WeakUndeclaredIdentifiers.push_back(WI.getUsed());
  3638. }
  3639. // Build a record containing all of the ext_vector declarations.
  3640. RecordData ExtVectorDecls;
  3641. AddLazyVectorDecls(*this, SemaRef.ExtVectorDecls, ExtVectorDecls);
  3642. // Build a record containing all of the VTable uses information.
  3643. RecordData VTableUses;
  3644. if (!SemaRef.VTableUses.empty()) {
  3645. for (unsigned I = 0, N = SemaRef.VTableUses.size(); I != N; ++I) {
  3646. AddDeclRef(SemaRef.VTableUses[I].first, VTableUses);
  3647. AddSourceLocation(SemaRef.VTableUses[I].second, VTableUses);
  3648. VTableUses.push_back(SemaRef.VTablesUsed[SemaRef.VTableUses[I].first]);
  3649. }
  3650. }
  3651. // Build a record containing all of the UnusedLocalTypedefNameCandidates.
  3652. RecordData UnusedLocalTypedefNameCandidates;
  3653. for (const TypedefNameDecl *TD : SemaRef.UnusedLocalTypedefNameCandidates)
  3654. AddDeclRef(TD, UnusedLocalTypedefNameCandidates);
  3655. // Build a record containing all of pending implicit instantiations.
  3656. RecordData PendingInstantiations;
  3657. for (std::deque<Sema::PendingImplicitInstantiation>::iterator
  3658. I = SemaRef.PendingInstantiations.begin(),
  3659. N = SemaRef.PendingInstantiations.end(); I != N; ++I) {
  3660. AddDeclRef(I->first, PendingInstantiations);
  3661. AddSourceLocation(I->second, PendingInstantiations);
  3662. }
  3663. assert(SemaRef.PendingLocalImplicitInstantiations.empty() &&
  3664. "There are local ones at end of translation unit!");
  3665. // Build a record containing some declaration references.
  3666. RecordData SemaDeclRefs;
  3667. if (SemaRef.StdNamespace || SemaRef.StdBadAlloc) {
  3668. AddDeclRef(SemaRef.getStdNamespace(), SemaDeclRefs);
  3669. AddDeclRef(SemaRef.getStdBadAlloc(), SemaDeclRefs);
  3670. }
  3671. RecordData CUDASpecialDeclRefs;
  3672. if (Context.getcudaConfigureCallDecl()) {
  3673. AddDeclRef(Context.getcudaConfigureCallDecl(), CUDASpecialDeclRefs);
  3674. }
  3675. // Build a record containing all of the known namespaces.
  3676. RecordData KnownNamespaces;
  3677. for (llvm::MapVector<NamespaceDecl*, bool>::iterator
  3678. I = SemaRef.KnownNamespaces.begin(),
  3679. IEnd = SemaRef.KnownNamespaces.end();
  3680. I != IEnd; ++I) {
  3681. if (!I->second)
  3682. AddDeclRef(I->first, KnownNamespaces);
  3683. }
  3684. // Build a record of all used, undefined objects that require definitions.
  3685. RecordData UndefinedButUsed;
  3686. SmallVector<std::pair<NamedDecl *, SourceLocation>, 16> Undefined;
  3687. SemaRef.getUndefinedButUsed(Undefined);
  3688. for (SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> >::iterator
  3689. I = Undefined.begin(), E = Undefined.end(); I != E; ++I) {
  3690. AddDeclRef(I->first, UndefinedButUsed);
  3691. AddSourceLocation(I->second, UndefinedButUsed);
  3692. }
  3693. // Build a record containing all delete-expressions that we would like to
  3694. // analyze later in AST.
  3695. RecordData DeleteExprsToAnalyze;
  3696. for (const auto &DeleteExprsInfo :
  3697. SemaRef.getMismatchingDeleteExpressions()) {
  3698. AddDeclRef(DeleteExprsInfo.first, DeleteExprsToAnalyze);
  3699. DeleteExprsToAnalyze.push_back(DeleteExprsInfo.second.size());
  3700. for (const auto &DeleteLoc : DeleteExprsInfo.second) {
  3701. AddSourceLocation(DeleteLoc.first, DeleteExprsToAnalyze);
  3702. DeleteExprsToAnalyze.push_back(DeleteLoc.second);
  3703. }
  3704. }
  3705. // Write the control block
  3706. WriteControlBlock(PP, Context, isysroot, OutputFile);
  3707. // Write the remaining AST contents.
  3708. RecordData Record;
  3709. Stream.EnterSubblock(AST_BLOCK_ID, 5);
  3710. // This is so that older clang versions, before the introduction
  3711. // of the control block, can read and reject the newer PCH format.
  3712. Record.clear();
  3713. Record.push_back(VERSION_MAJOR);
  3714. Stream.EmitRecord(METADATA_OLD_FORMAT, Record);
  3715. // Create a lexical update block containing all of the declarations in the
  3716. // translation unit that do not come from other AST files.
  3717. const TranslationUnitDecl *TU = Context.getTranslationUnitDecl();
  3718. SmallVector<KindDeclIDPair, 64> NewGlobalDecls;
  3719. for (const auto *I : TU->noload_decls()) {
  3720. if (!I->isFromASTFile())
  3721. NewGlobalDecls.push_back(std::make_pair(I->getKind(), GetDeclRef(I)));
  3722. }
  3723. llvm::BitCodeAbbrev *Abv = new llvm::BitCodeAbbrev();
  3724. Abv->Add(llvm::BitCodeAbbrevOp(TU_UPDATE_LEXICAL));
  3725. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  3726. unsigned TuUpdateLexicalAbbrev = Stream.EmitAbbrev(Abv);
  3727. Record.clear();
  3728. Record.push_back(TU_UPDATE_LEXICAL);
  3729. Stream.EmitRecordWithBlob(TuUpdateLexicalAbbrev, Record,
  3730. bytes(NewGlobalDecls));
  3731. // And a visible updates block for the translation unit.
  3732. Abv = new llvm::BitCodeAbbrev();
  3733. Abv->Add(llvm::BitCodeAbbrevOp(UPDATE_VISIBLE));
  3734. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::VBR, 6));
  3735. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Fixed, 32));
  3736. Abv->Add(llvm::BitCodeAbbrevOp(llvm::BitCodeAbbrevOp::Blob));
  3737. UpdateVisibleAbbrev = Stream.EmitAbbrev(Abv);
  3738. WriteDeclContextVisibleUpdate(TU);
  3739. // If we have any extern "C" names, write out a visible update for them.
  3740. if (Context.ExternCContext)
  3741. WriteDeclContextVisibleUpdate(Context.ExternCContext);
  3742. // If the translation unit has an anonymous namespace, and we don't already
  3743. // have an update block for it, write it as an update block.
  3744. // FIXME: Why do we not do this if there's already an update block?
  3745. if (NamespaceDecl *NS = TU->getAnonymousNamespace()) {
  3746. ASTWriter::UpdateRecord &Record = DeclUpdates[TU];
  3747. if (Record.empty())
  3748. Record.push_back(DeclUpdate(UPD_CXX_ADDED_ANONYMOUS_NAMESPACE, NS));
  3749. }
  3750. // Add update records for all mangling numbers and static local numbers.
  3751. // These aren't really update records, but this is a convenient way of
  3752. // tagging this rare extra data onto the declarations.
  3753. for (const auto &Number : Context.MangleNumbers)
  3754. if (!Number.first->isFromASTFile())
  3755. DeclUpdates[Number.first].push_back(DeclUpdate(UPD_MANGLING_NUMBER,
  3756. Number.second));
  3757. for (const auto &Number : Context.StaticLocalNumbers)
  3758. if (!Number.first->isFromASTFile())
  3759. DeclUpdates[Number.first].push_back(DeclUpdate(UPD_STATIC_LOCAL_NUMBER,
  3760. Number.second));
  3761. // Make sure visible decls, added to DeclContexts previously loaded from
  3762. // an AST file, are registered for serialization.
  3763. for (SmallVectorImpl<const Decl *>::iterator
  3764. I = UpdatingVisibleDecls.begin(),
  3765. E = UpdatingVisibleDecls.end(); I != E; ++I) {
  3766. GetDeclRef(*I);
  3767. }
  3768. // Make sure all decls associated with an identifier are registered for
  3769. // serialization.
  3770. llvm::SmallVector<const IdentifierInfo*, 256> IIs;
  3771. for (IdentifierTable::iterator ID = PP.getIdentifierTable().begin(),
  3772. IDEnd = PP.getIdentifierTable().end();
  3773. ID != IDEnd; ++ID) {
  3774. const IdentifierInfo *II = ID->second;
  3775. if (!Chain || !II->isFromAST() || II->hasChangedSinceDeserialization())
  3776. IIs.push_back(II);
  3777. }
  3778. // Sort the identifiers to visit based on their name.
  3779. std::sort(IIs.begin(), IIs.end(), llvm::less_ptr<IdentifierInfo>());
  3780. for (const IdentifierInfo *II : IIs) {
  3781. for (IdentifierResolver::iterator D = SemaRef.IdResolver.begin(II),
  3782. DEnd = SemaRef.IdResolver.end();
  3783. D != DEnd; ++D) {
  3784. GetDeclRef(*D);
  3785. }
  3786. }
  3787. // Form the record of special types.
  3788. RecordData SpecialTypes;
  3789. AddTypeRef(Context.getRawCFConstantStringType(), SpecialTypes);
  3790. AddTypeRef(Context.getFILEType(), SpecialTypes);
  3791. AddTypeRef(Context.getjmp_bufType(), SpecialTypes);
  3792. AddTypeRef(Context.getsigjmp_bufType(), SpecialTypes);
  3793. AddTypeRef(Context.ObjCIdRedefinitionType, SpecialTypes);
  3794. AddTypeRef(Context.ObjCClassRedefinitionType, SpecialTypes);
  3795. AddTypeRef(Context.ObjCSelRedefinitionType, SpecialTypes);
  3796. AddTypeRef(Context.getucontext_tType(), SpecialTypes);
  3797. if (Chain) {
  3798. // Write the mapping information describing our module dependencies and how
  3799. // each of those modules were mapped into our own offset/ID space, so that
  3800. // the reader can build the appropriate mapping to its own offset/ID space.
  3801. // The map consists solely of a blob with the following format:
  3802. // *(module-name-len:i16 module-name:len*i8
  3803. // source-location-offset:i32
  3804. // identifier-id:i32
  3805. // preprocessed-entity-id:i32
  3806. // macro-definition-id:i32
  3807. // submodule-id:i32
  3808. // selector-id:i32
  3809. // declaration-id:i32
  3810. // c++-base-specifiers-id:i32
  3811. // type-id:i32)
  3812. //
  3813. llvm::BitCodeAbbrev *Abbrev = new BitCodeAbbrev();
  3814. Abbrev->Add(BitCodeAbbrevOp(MODULE_OFFSET_MAP));
  3815. Abbrev->Add(BitCodeAbbrevOp(BitCodeAbbrevOp::Blob));
  3816. unsigned ModuleOffsetMapAbbrev = Stream.EmitAbbrev(Abbrev);
  3817. SmallString<2048> Buffer;
  3818. {
  3819. llvm::raw_svector_ostream Out(Buffer);
  3820. for (ModuleFile *M : Chain->ModuleMgr) {
  3821. using namespace llvm::support;
  3822. endian::Writer<little> LE(Out);
  3823. StringRef FileName = M->FileName;
  3824. LE.write<uint16_t>(FileName.size());
  3825. Out.write(FileName.data(), FileName.size());
  3826. // Note: if a base ID was uint max, it would not be possible to load
  3827. // another module after it or have more than one entity inside it.
  3828. uint32_t None = std::numeric_limits<uint32_t>::max();
  3829. auto writeBaseIDOrNone = [&](uint32_t BaseID, bool ShouldWrite) {
  3830. assert(BaseID < std::numeric_limits<uint32_t>::max() && "base id too high");
  3831. if (ShouldWrite)
  3832. LE.write<uint32_t>(BaseID);
  3833. else
  3834. LE.write<uint32_t>(None);
  3835. };
  3836. // These values should be unique within a chain, since they will be read
  3837. // as keys into ContinuousRangeMaps.
  3838. writeBaseIDOrNone(M->SLocEntryBaseOffset, M->LocalNumSLocEntries);
  3839. writeBaseIDOrNone(M->BaseIdentifierID, M->LocalNumIdentifiers);
  3840. writeBaseIDOrNone(M->BaseMacroID, M->LocalNumMacros);
  3841. writeBaseIDOrNone(M->BasePreprocessedEntityID,
  3842. M->NumPreprocessedEntities);
  3843. writeBaseIDOrNone(M->BaseSubmoduleID, M->LocalNumSubmodules);
  3844. writeBaseIDOrNone(M->BaseSelectorID, M->LocalNumSelectors);
  3845. writeBaseIDOrNone(M->BaseDeclID, M->LocalNumDecls);
  3846. writeBaseIDOrNone(M->BaseTypeIndex, M->LocalNumTypes);
  3847. }
  3848. }
  3849. Record.clear();
  3850. Record.push_back(MODULE_OFFSET_MAP);
  3851. Stream.EmitRecordWithBlob(ModuleOffsetMapAbbrev, Record,
  3852. Buffer.data(), Buffer.size());
  3853. }
  3854. RecordData DeclUpdatesOffsetsRecord;
  3855. // Keep writing types, declarations, and declaration update records
  3856. // until we've emitted all of them.
  3857. Stream.EnterSubblock(DECLTYPES_BLOCK_ID, /*bits for abbreviations*/5);
  3858. WriteTypeAbbrevs();
  3859. WriteDeclAbbrevs();
  3860. for (DeclsToRewriteTy::iterator I = DeclsToRewrite.begin(),
  3861. E = DeclsToRewrite.end();
  3862. I != E; ++I)
  3863. DeclTypesToEmit.push(const_cast<Decl*>(*I));
  3864. do {
  3865. WriteDeclUpdatesBlocks(DeclUpdatesOffsetsRecord);
  3866. while (!DeclTypesToEmit.empty()) {
  3867. DeclOrType DOT = DeclTypesToEmit.front();
  3868. DeclTypesToEmit.pop();
  3869. if (DOT.isType())
  3870. WriteType(DOT.getType());
  3871. else
  3872. WriteDecl(Context, DOT.getDecl());
  3873. }
  3874. } while (!DeclUpdates.empty());
  3875. Stream.ExitBlock();
  3876. DoneWritingDeclsAndTypes = true;
  3877. // These things can only be done once we've written out decls and types.
  3878. WriteTypeDeclOffsets();
  3879. if (!DeclUpdatesOffsetsRecord.empty())
  3880. Stream.EmitRecord(DECL_UPDATE_OFFSETS, DeclUpdatesOffsetsRecord);
  3881. WriteCXXBaseSpecifiersOffsets();
  3882. WriteCXXCtorInitializersOffsets();
  3883. WriteFileDeclIDsMap();
  3884. WriteSourceManagerBlock(Context.getSourceManager(), PP);
  3885. WriteComments();
  3886. WritePreprocessor(PP, isModule);
  3887. WriteHeaderSearch(PP.getHeaderSearchInfo());
  3888. WriteSelectors(SemaRef);
  3889. WriteReferencedSelectorsPool(SemaRef);
  3890. WriteIdentifierTable(PP, SemaRef.IdResolver, isModule);
  3891. WriteFPPragmaOptions(SemaRef.getFPOptions());
  3892. WriteOpenCLExtensions(SemaRef);
  3893. WritePragmaDiagnosticMappings(Context.getDiagnostics(), isModule);
  3894. // If we're emitting a module, write out the submodule information.
  3895. if (WritingModule)
  3896. WriteSubmodules(WritingModule);
  3897. Stream.EmitRecord(SPECIAL_TYPES, SpecialTypes);
  3898. // Write the record containing external, unnamed definitions.
  3899. if (!EagerlyDeserializedDecls.empty())
  3900. Stream.EmitRecord(EAGERLY_DESERIALIZED_DECLS, EagerlyDeserializedDecls);
  3901. // Write the record containing tentative definitions.
  3902. if (!TentativeDefinitions.empty())
  3903. Stream.EmitRecord(TENTATIVE_DEFINITIONS, TentativeDefinitions);
  3904. // Write the record containing unused file scoped decls.
  3905. if (!UnusedFileScopedDecls.empty())
  3906. Stream.EmitRecord(UNUSED_FILESCOPED_DECLS, UnusedFileScopedDecls);
  3907. // Write the record containing weak undeclared identifiers.
  3908. if (!WeakUndeclaredIdentifiers.empty())
  3909. Stream.EmitRecord(WEAK_UNDECLARED_IDENTIFIERS,
  3910. WeakUndeclaredIdentifiers);
  3911. // Write the record containing ext_vector type names.
  3912. if (!ExtVectorDecls.empty())
  3913. Stream.EmitRecord(EXT_VECTOR_DECLS, ExtVectorDecls);
  3914. // Write the record containing VTable uses information.
  3915. if (!VTableUses.empty())
  3916. Stream.EmitRecord(VTABLE_USES, VTableUses);
  3917. // Write the record containing potentially unused local typedefs.
  3918. if (!UnusedLocalTypedefNameCandidates.empty())
  3919. Stream.EmitRecord(UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES,
  3920. UnusedLocalTypedefNameCandidates);
  3921. // Write the record containing pending implicit instantiations.
  3922. if (!PendingInstantiations.empty())
  3923. Stream.EmitRecord(PENDING_IMPLICIT_INSTANTIATIONS, PendingInstantiations);
  3924. // Write the record containing declaration references of Sema.
  3925. if (!SemaDeclRefs.empty())
  3926. Stream.EmitRecord(SEMA_DECL_REFS, SemaDeclRefs);
  3927. // Write the record containing CUDA-specific declaration references.
  3928. if (!CUDASpecialDeclRefs.empty())
  3929. Stream.EmitRecord(CUDA_SPECIAL_DECL_REFS, CUDASpecialDeclRefs);
  3930. // Write the delegating constructors.
  3931. if (!DelegatingCtorDecls.empty())
  3932. Stream.EmitRecord(DELEGATING_CTORS, DelegatingCtorDecls);
  3933. // Write the known namespaces.
  3934. if (!KnownNamespaces.empty())
  3935. Stream.EmitRecord(KNOWN_NAMESPACES, KnownNamespaces);
  3936. // Write the undefined internal functions and variables, and inline functions.
  3937. if (!UndefinedButUsed.empty())
  3938. Stream.EmitRecord(UNDEFINED_BUT_USED, UndefinedButUsed);
  3939. if (!DeleteExprsToAnalyze.empty())
  3940. Stream.EmitRecord(DELETE_EXPRS_TO_ANALYZE, DeleteExprsToAnalyze);
  3941. // Write the visible updates to DeclContexts.
  3942. for (auto *DC : UpdatedDeclContexts)
  3943. WriteDeclContextVisibleUpdate(DC);
  3944. if (!WritingModule) {
  3945. // Write the submodules that were imported, if any.
  3946. struct ModuleInfo {
  3947. uint64_t ID;
  3948. Module *M;
  3949. ModuleInfo(uint64_t ID, Module *M) : ID(ID), M(M) {}
  3950. };
  3951. llvm::SmallVector<ModuleInfo, 64> Imports;
  3952. for (const auto *I : Context.local_imports()) {
  3953. assert(SubmoduleIDs.find(I->getImportedModule()) != SubmoduleIDs.end());
  3954. Imports.push_back(ModuleInfo(SubmoduleIDs[I->getImportedModule()],
  3955. I->getImportedModule()));
  3956. }
  3957. if (!Imports.empty()) {
  3958. auto Cmp = [](const ModuleInfo &A, const ModuleInfo &B) {
  3959. return A.ID < B.ID;
  3960. };
  3961. auto Eq = [](const ModuleInfo &A, const ModuleInfo &B) {
  3962. return A.ID == B.ID;
  3963. };
  3964. // Sort and deduplicate module IDs.
  3965. std::sort(Imports.begin(), Imports.end(), Cmp);
  3966. Imports.erase(std::unique(Imports.begin(), Imports.end(), Eq),
  3967. Imports.end());
  3968. RecordData ImportedModules;
  3969. for (const auto &Import : Imports) {
  3970. ImportedModules.push_back(Import.ID);
  3971. // FIXME: If the module has macros imported then later has declarations
  3972. // imported, this location won't be the right one as a location for the
  3973. // declaration imports.
  3974. AddSourceLocation(PP.getModuleImportLoc(Import.M), ImportedModules);
  3975. }
  3976. Stream.EmitRecord(IMPORTED_MODULES, ImportedModules);
  3977. }
  3978. }
  3979. WriteDeclReplacementsBlock();
  3980. WriteRedeclarations();
  3981. WriteObjCCategories();
  3982. WriteLateParsedTemplates(SemaRef);
  3983. if(!WritingModule)
  3984. WriteOptimizePragmaOptions(SemaRef);
  3985. // Some simple statistics
  3986. Record.clear();
  3987. Record.push_back(NumStatements);
  3988. Record.push_back(NumMacros);
  3989. Record.push_back(NumLexicalDeclContexts);
  3990. Record.push_back(NumVisibleDeclContexts);
  3991. Stream.EmitRecord(STATISTICS, Record);
  3992. Stream.ExitBlock();
  3993. }
  3994. void ASTWriter::WriteDeclUpdatesBlocks(RecordDataImpl &OffsetsRecord) {
  3995. if (DeclUpdates.empty())
  3996. return;
  3997. DeclUpdateMap LocalUpdates;
  3998. LocalUpdates.swap(DeclUpdates);
  3999. for (auto &DeclUpdate : LocalUpdates) {
  4000. const Decl *D = DeclUpdate.first;
  4001. if (isRewritten(D))
  4002. continue; // The decl will be written completely,no need to store updates.
  4003. bool HasUpdatedBody = false;
  4004. RecordData Record;
  4005. for (auto &Update : DeclUpdate.second) {
  4006. DeclUpdateKind Kind = (DeclUpdateKind)Update.getKind();
  4007. Record.push_back(Kind);
  4008. switch (Kind) {
  4009. case UPD_CXX_ADDED_IMPLICIT_MEMBER:
  4010. case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
  4011. case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE:
  4012. assert(Update.getDecl() && "no decl to add?");
  4013. Record.push_back(GetDeclRef(Update.getDecl()));
  4014. break;
  4015. case UPD_CXX_ADDED_FUNCTION_DEFINITION:
  4016. // An updated body is emitted last, so that the reader doesn't need
  4017. // to skip over the lazy body to reach statements for other records.
  4018. Record.pop_back();
  4019. HasUpdatedBody = true;
  4020. break;
  4021. case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
  4022. AddSourceLocation(Update.getLoc(), Record);
  4023. break;
  4024. case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
  4025. auto *RD = cast<CXXRecordDecl>(D);
  4026. UpdatedDeclContexts.insert(RD->getPrimaryContext());
  4027. AddCXXDefinitionData(RD, Record);
  4028. Record.push_back(WriteDeclContextLexicalBlock(
  4029. *Context, const_cast<CXXRecordDecl *>(RD)));
  4030. // This state is sometimes updated by template instantiation, when we
  4031. // switch from the specialization referring to the template declaration
  4032. // to it referring to the template definition.
  4033. if (auto *MSInfo = RD->getMemberSpecializationInfo()) {
  4034. Record.push_back(MSInfo->getTemplateSpecializationKind());
  4035. AddSourceLocation(MSInfo->getPointOfInstantiation(), Record);
  4036. } else {
  4037. auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
  4038. Record.push_back(Spec->getTemplateSpecializationKind());
  4039. AddSourceLocation(Spec->getPointOfInstantiation(), Record);
  4040. // The instantiation might have been resolved to a partial
  4041. // specialization. If so, record which one.
  4042. auto From = Spec->getInstantiatedFrom();
  4043. if (auto PartialSpec =
  4044. From.dyn_cast<ClassTemplatePartialSpecializationDecl*>()) {
  4045. Record.push_back(true);
  4046. AddDeclRef(PartialSpec, Record);
  4047. AddTemplateArgumentList(&Spec->getTemplateInstantiationArgs(),
  4048. Record);
  4049. } else {
  4050. Record.push_back(false);
  4051. }
  4052. }
  4053. Record.push_back(RD->getTagKind());
  4054. AddSourceLocation(RD->getLocation(), Record);
  4055. AddSourceLocation(RD->getLocStart(), Record);
  4056. AddSourceLocation(RD->getRBraceLoc(), Record);
  4057. // Instantiation may change attributes; write them all out afresh.
  4058. Record.push_back(D->hasAttrs());
  4059. if (Record.back())
  4060. WriteAttributes(llvm::makeArrayRef(D->getAttrs().begin(),
  4061. D->getAttrs().size()), Record);
  4062. // FIXME: Ensure we don't get here for explicit instantiations.
  4063. break;
  4064. }
  4065. case UPD_CXX_RESOLVED_DTOR_DELETE:
  4066. AddDeclRef(Update.getDecl(), Record);
  4067. break;
  4068. case UPD_CXX_RESOLVED_EXCEPTION_SPEC:
  4069. addExceptionSpec(
  4070. *this,
  4071. cast<FunctionDecl>(D)->getType()->castAs<FunctionProtoType>(),
  4072. Record);
  4073. break;
  4074. case UPD_CXX_DEDUCED_RETURN_TYPE:
  4075. Record.push_back(GetOrCreateTypeID(Update.getType()));
  4076. break;
  4077. case UPD_DECL_MARKED_USED:
  4078. break;
  4079. case UPD_MANGLING_NUMBER:
  4080. case UPD_STATIC_LOCAL_NUMBER:
  4081. Record.push_back(Update.getNumber());
  4082. break;
  4083. case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
  4084. AddSourceRange(D->getAttr<OMPThreadPrivateDeclAttr>()->getRange(),
  4085. Record);
  4086. break;
  4087. case UPD_DECL_EXPORTED:
  4088. Record.push_back(getSubmoduleID(Update.getModule()));
  4089. break;
  4090. case UPD_ADDED_ATTR_TO_RECORD:
  4091. WriteAttributes(llvm::makeArrayRef(Update.getAttr()), Record);
  4092. break;
  4093. }
  4094. }
  4095. if (HasUpdatedBody) {
  4096. const FunctionDecl *Def = cast<FunctionDecl>(D);
  4097. Record.push_back(UPD_CXX_ADDED_FUNCTION_DEFINITION);
  4098. Record.push_back(Def->isInlined());
  4099. AddSourceLocation(Def->getInnerLocStart(), Record);
  4100. AddFunctionDefinition(Def, Record);
  4101. }
  4102. OffsetsRecord.push_back(GetDeclRef(D));
  4103. OffsetsRecord.push_back(Stream.GetCurrentBitNo());
  4104. Stream.EmitRecord(DECL_UPDATES, Record);
  4105. FlushPendingAfterDecl();
  4106. }
  4107. }
  4108. void ASTWriter::WriteDeclReplacementsBlock() {
  4109. if (ReplacedDecls.empty())
  4110. return;
  4111. RecordData Record;
  4112. for (SmallVectorImpl<ReplacedDeclInfo>::iterator
  4113. I = ReplacedDecls.begin(), E = ReplacedDecls.end(); I != E; ++I) {
  4114. Record.push_back(I->ID);
  4115. Record.push_back(I->Offset);
  4116. Record.push_back(I->Loc);
  4117. }
  4118. Stream.EmitRecord(DECL_REPLACEMENTS, Record);
  4119. }
  4120. void ASTWriter::AddSourceLocation(SourceLocation Loc, RecordDataImpl &Record) {
  4121. Record.push_back(Loc.getRawEncoding());
  4122. }
  4123. void ASTWriter::AddSourceRange(SourceRange Range, RecordDataImpl &Record) {
  4124. AddSourceLocation(Range.getBegin(), Record);
  4125. AddSourceLocation(Range.getEnd(), Record);
  4126. }
  4127. void ASTWriter::AddAPInt(const llvm::APInt &Value, RecordDataImpl &Record) {
  4128. Record.push_back(Value.getBitWidth());
  4129. const uint64_t *Words = Value.getRawData();
  4130. Record.append(Words, Words + Value.getNumWords());
  4131. }
  4132. void ASTWriter::AddAPSInt(const llvm::APSInt &Value, RecordDataImpl &Record) {
  4133. Record.push_back(Value.isUnsigned());
  4134. AddAPInt(Value, Record);
  4135. }
  4136. void ASTWriter::AddAPFloat(const llvm::APFloat &Value, RecordDataImpl &Record) {
  4137. AddAPInt(Value.bitcastToAPInt(), Record);
  4138. }
  4139. void ASTWriter::AddIdentifierRef(const IdentifierInfo *II, RecordDataImpl &Record) {
  4140. Record.push_back(getIdentifierRef(II));
  4141. }
  4142. IdentID ASTWriter::getIdentifierRef(const IdentifierInfo *II) {
  4143. if (!II)
  4144. return 0;
  4145. IdentID &ID = IdentifierIDs[II];
  4146. if (ID == 0)
  4147. ID = NextIdentID++;
  4148. return ID;
  4149. }
  4150. MacroID ASTWriter::getMacroRef(MacroInfo *MI, const IdentifierInfo *Name) {
  4151. // Don't emit builtin macros like __LINE__ to the AST file unless they
  4152. // have been redefined by the header (in which case they are not
  4153. // isBuiltinMacro).
  4154. if (!MI || MI->isBuiltinMacro())
  4155. return 0;
  4156. MacroID &ID = MacroIDs[MI];
  4157. if (ID == 0) {
  4158. ID = NextMacroID++;
  4159. MacroInfoToEmitData Info = { Name, MI, ID };
  4160. MacroInfosToEmit.push_back(Info);
  4161. }
  4162. return ID;
  4163. }
  4164. MacroID ASTWriter::getMacroID(MacroInfo *MI) {
  4165. if (!MI || MI->isBuiltinMacro())
  4166. return 0;
  4167. assert(MacroIDs.find(MI) != MacroIDs.end() && "Macro not emitted!");
  4168. return MacroIDs[MI];
  4169. }
  4170. uint64_t ASTWriter::getMacroDirectivesOffset(const IdentifierInfo *Name) {
  4171. return IdentMacroDirectivesOffsetMap.lookup(Name);
  4172. }
  4173. void ASTWriter::AddSelectorRef(const Selector SelRef, RecordDataImpl &Record) {
  4174. Record.push_back(getSelectorRef(SelRef));
  4175. }
  4176. SelectorID ASTWriter::getSelectorRef(Selector Sel) {
  4177. if (Sel.getAsOpaquePtr() == nullptr) {
  4178. return 0;
  4179. }
  4180. SelectorID SID = SelectorIDs[Sel];
  4181. if (SID == 0 && Chain) {
  4182. // This might trigger a ReadSelector callback, which will set the ID for
  4183. // this selector.
  4184. Chain->LoadSelector(Sel);
  4185. SID = SelectorIDs[Sel];
  4186. }
  4187. if (SID == 0) {
  4188. SID = NextSelectorID++;
  4189. SelectorIDs[Sel] = SID;
  4190. }
  4191. return SID;
  4192. }
  4193. void ASTWriter::AddCXXTemporary(const CXXTemporary *Temp, RecordDataImpl &Record) {
  4194. AddDeclRef(Temp->getDestructor(), Record);
  4195. }
  4196. void ASTWriter::AddCXXCtorInitializersRef(ArrayRef<CXXCtorInitializer *> Inits,
  4197. RecordDataImpl &Record) {
  4198. assert(!Inits.empty() && "Empty ctor initializer sets are not recorded");
  4199. CXXCtorInitializersToWrite.push_back(
  4200. QueuedCXXCtorInitializers(NextCXXCtorInitializersID, Inits));
  4201. Record.push_back(NextCXXCtorInitializersID++);
  4202. }
  4203. void ASTWriter::AddCXXBaseSpecifiersRef(CXXBaseSpecifier const *Bases,
  4204. CXXBaseSpecifier const *BasesEnd,
  4205. RecordDataImpl &Record) {
  4206. assert(Bases != BasesEnd && "Empty base-specifier sets are not recorded");
  4207. CXXBaseSpecifiersToWrite.push_back(
  4208. QueuedCXXBaseSpecifiers(NextCXXBaseSpecifiersID,
  4209. Bases, BasesEnd));
  4210. Record.push_back(NextCXXBaseSpecifiersID++);
  4211. }
  4212. void ASTWriter::AddTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind,
  4213. const TemplateArgumentLocInfo &Arg,
  4214. RecordDataImpl &Record) {
  4215. switch (Kind) {
  4216. case TemplateArgument::Expression:
  4217. AddStmt(Arg.getAsExpr());
  4218. break;
  4219. case TemplateArgument::Type:
  4220. AddTypeSourceInfo(Arg.getAsTypeSourceInfo(), Record);
  4221. break;
  4222. case TemplateArgument::Template:
  4223. AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
  4224. AddSourceLocation(Arg.getTemplateNameLoc(), Record);
  4225. break;
  4226. case TemplateArgument::TemplateExpansion:
  4227. AddNestedNameSpecifierLoc(Arg.getTemplateQualifierLoc(), Record);
  4228. AddSourceLocation(Arg.getTemplateNameLoc(), Record);
  4229. AddSourceLocation(Arg.getTemplateEllipsisLoc(), Record);
  4230. break;
  4231. case TemplateArgument::Null:
  4232. case TemplateArgument::Integral:
  4233. case TemplateArgument::Declaration:
  4234. case TemplateArgument::NullPtr:
  4235. case TemplateArgument::Pack:
  4236. // FIXME: Is this right?
  4237. break;
  4238. }
  4239. }
  4240. void ASTWriter::AddTemplateArgumentLoc(const TemplateArgumentLoc &Arg,
  4241. RecordDataImpl &Record) {
  4242. AddTemplateArgument(Arg.getArgument(), Record);
  4243. if (Arg.getArgument().getKind() == TemplateArgument::Expression) {
  4244. bool InfoHasSameExpr
  4245. = Arg.getArgument().getAsExpr() == Arg.getLocInfo().getAsExpr();
  4246. Record.push_back(InfoHasSameExpr);
  4247. if (InfoHasSameExpr)
  4248. return; // Avoid storing the same expr twice.
  4249. }
  4250. AddTemplateArgumentLocInfo(Arg.getArgument().getKind(), Arg.getLocInfo(),
  4251. Record);
  4252. }
  4253. void ASTWriter::AddTypeSourceInfo(TypeSourceInfo *TInfo,
  4254. RecordDataImpl &Record) {
  4255. if (!TInfo) {
  4256. AddTypeRef(QualType(), Record);
  4257. return;
  4258. }
  4259. AddTypeLoc(TInfo->getTypeLoc(), Record);
  4260. }
  4261. void ASTWriter::AddTypeLoc(TypeLoc TL, RecordDataImpl &Record) {
  4262. AddTypeRef(TL.getType(), Record);
  4263. TypeLocWriter TLW(*this, Record);
  4264. for (; !TL.isNull(); TL = TL.getNextTypeLoc())
  4265. TLW.Visit(TL);
  4266. }
  4267. void ASTWriter::AddTypeRef(QualType T, RecordDataImpl &Record) {
  4268. Record.push_back(GetOrCreateTypeID(T));
  4269. }
  4270. TypeID ASTWriter::GetOrCreateTypeID(QualType T) {
  4271. assert(Context);
  4272. return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
  4273. if (T.isNull())
  4274. return TypeIdx();
  4275. assert(!T.getLocalFastQualifiers());
  4276. TypeIdx &Idx = TypeIdxs[T];
  4277. if (Idx.getIndex() == 0) {
  4278. if (DoneWritingDeclsAndTypes) {
  4279. assert(0 && "New type seen after serializing all the types to emit!");
  4280. return TypeIdx();
  4281. }
  4282. // We haven't seen this type before. Assign it a new ID and put it
  4283. // into the queue of types to emit.
  4284. Idx = TypeIdx(NextTypeID++);
  4285. DeclTypesToEmit.push(T);
  4286. }
  4287. return Idx;
  4288. });
  4289. }
  4290. TypeID ASTWriter::getTypeID(QualType T) const {
  4291. assert(Context);
  4292. return MakeTypeID(*Context, T, [&](QualType T) -> TypeIdx {
  4293. if (T.isNull())
  4294. return TypeIdx();
  4295. assert(!T.getLocalFastQualifiers());
  4296. TypeIdxMap::const_iterator I = TypeIdxs.find(T);
  4297. assert(I != TypeIdxs.end() && "Type not emitted!");
  4298. return I->second;
  4299. });
  4300. }
  4301. void ASTWriter::AddDeclRef(const Decl *D, RecordDataImpl &Record) {
  4302. Record.push_back(GetDeclRef(D));
  4303. }
  4304. DeclID ASTWriter::GetDeclRef(const Decl *D) {
  4305. assert(WritingAST && "Cannot request a declaration ID before AST writing");
  4306. if (!D) {
  4307. return 0;
  4308. }
  4309. // If D comes from an AST file, its declaration ID is already known and
  4310. // fixed.
  4311. if (D->isFromASTFile())
  4312. return D->getGlobalID();
  4313. assert(!(reinterpret_cast<uintptr_t>(D) & 0x01) && "Invalid decl pointer");
  4314. DeclID &ID = DeclIDs[D];
  4315. if (ID == 0) {
  4316. if (DoneWritingDeclsAndTypes) {
  4317. assert(0 && "New decl seen after serializing all the decls to emit!");
  4318. return 0;
  4319. }
  4320. // We haven't seen this declaration before. Give it a new ID and
  4321. // enqueue it in the list of declarations to emit.
  4322. ID = NextDeclID++;
  4323. DeclTypesToEmit.push(const_cast<Decl *>(D));
  4324. }
  4325. return ID;
  4326. }
  4327. DeclID ASTWriter::getDeclID(const Decl *D) {
  4328. if (!D)
  4329. return 0;
  4330. // If D comes from an AST file, its declaration ID is already known and
  4331. // fixed.
  4332. if (D->isFromASTFile())
  4333. return D->getGlobalID();
  4334. assert(DeclIDs.find(D) != DeclIDs.end() && "Declaration not emitted!");
  4335. return DeclIDs[D];
  4336. }
  4337. void ASTWriter::associateDeclWithFile(const Decl *D, DeclID ID) {
  4338. assert(ID);
  4339. assert(D);
  4340. SourceLocation Loc = D->getLocation();
  4341. if (Loc.isInvalid())
  4342. return;
  4343. // We only keep track of the file-level declarations of each file.
  4344. if (!D->getLexicalDeclContext()->isFileContext())
  4345. return;
  4346. // FIXME: ParmVarDecls that are part of a function type of a parameter of
  4347. // a function/objc method, should not have TU as lexical context.
  4348. if (isa<ParmVarDecl>(D))
  4349. return;
  4350. SourceManager &SM = Context->getSourceManager();
  4351. SourceLocation FileLoc = SM.getFileLoc(Loc);
  4352. assert(SM.isLocalSourceLocation(FileLoc));
  4353. FileID FID;
  4354. unsigned Offset;
  4355. std::tie(FID, Offset) = SM.getDecomposedLoc(FileLoc);
  4356. if (FID.isInvalid())
  4357. return;
  4358. assert(SM.getSLocEntry(FID).isFile());
  4359. DeclIDInFileInfo *&Info = FileDeclIDs[FID];
  4360. if (!Info)
  4361. Info = new DeclIDInFileInfo();
  4362. std::pair<unsigned, serialization::DeclID> LocDecl(Offset, ID);
  4363. LocDeclIDsTy &Decls = Info->DeclIDs;
  4364. if (Decls.empty() || Decls.back().first <= Offset) {
  4365. Decls.push_back(LocDecl);
  4366. return;
  4367. }
  4368. LocDeclIDsTy::iterator I =
  4369. std::upper_bound(Decls.begin(), Decls.end(), LocDecl, llvm::less_first());
  4370. Decls.insert(I, LocDecl);
  4371. }
  4372. void ASTWriter::AddDeclarationName(DeclarationName Name, RecordDataImpl &Record) {
  4373. // FIXME: Emit a stable enum for NameKind. 0 = Identifier etc.
  4374. Record.push_back(Name.getNameKind());
  4375. switch (Name.getNameKind()) {
  4376. case DeclarationName::Identifier:
  4377. AddIdentifierRef(Name.getAsIdentifierInfo(), Record);
  4378. break;
  4379. case DeclarationName::ObjCZeroArgSelector:
  4380. case DeclarationName::ObjCOneArgSelector:
  4381. case DeclarationName::ObjCMultiArgSelector:
  4382. AddSelectorRef(Name.getObjCSelector(), Record);
  4383. break;
  4384. case DeclarationName::CXXConstructorName:
  4385. case DeclarationName::CXXDestructorName:
  4386. case DeclarationName::CXXConversionFunctionName:
  4387. AddTypeRef(Name.getCXXNameType(), Record);
  4388. break;
  4389. case DeclarationName::CXXOperatorName:
  4390. Record.push_back(Name.getCXXOverloadedOperator());
  4391. break;
  4392. case DeclarationName::CXXLiteralOperatorName:
  4393. AddIdentifierRef(Name.getCXXLiteralIdentifier(), Record);
  4394. break;
  4395. case DeclarationName::CXXUsingDirective:
  4396. // No extra data to emit
  4397. break;
  4398. }
  4399. }
  4400. unsigned ASTWriter::getAnonymousDeclarationNumber(const NamedDecl *D) {
  4401. assert(needsAnonymousDeclarationNumber(D) &&
  4402. "expected an anonymous declaration");
  4403. // Number the anonymous declarations within this context, if we've not
  4404. // already done so.
  4405. auto It = AnonymousDeclarationNumbers.find(D);
  4406. if (It == AnonymousDeclarationNumbers.end()) {
  4407. auto *DC = D->getLexicalDeclContext();
  4408. numberAnonymousDeclsWithin(DC, [&](const NamedDecl *ND, unsigned Number) {
  4409. AnonymousDeclarationNumbers[ND] = Number;
  4410. });
  4411. It = AnonymousDeclarationNumbers.find(D);
  4412. assert(It != AnonymousDeclarationNumbers.end() &&
  4413. "declaration not found within its lexical context");
  4414. }
  4415. return It->second;
  4416. }
  4417. void ASTWriter::AddDeclarationNameLoc(const DeclarationNameLoc &DNLoc,
  4418. DeclarationName Name, RecordDataImpl &Record) {
  4419. switch (Name.getNameKind()) {
  4420. case DeclarationName::CXXConstructorName:
  4421. case DeclarationName::CXXDestructorName:
  4422. case DeclarationName::CXXConversionFunctionName:
  4423. AddTypeSourceInfo(DNLoc.NamedType.TInfo, Record);
  4424. break;
  4425. case DeclarationName::CXXOperatorName:
  4426. AddSourceLocation(
  4427. SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.BeginOpNameLoc),
  4428. Record);
  4429. AddSourceLocation(
  4430. SourceLocation::getFromRawEncoding(DNLoc.CXXOperatorName.EndOpNameLoc),
  4431. Record);
  4432. break;
  4433. case DeclarationName::CXXLiteralOperatorName:
  4434. AddSourceLocation(
  4435. SourceLocation::getFromRawEncoding(DNLoc.CXXLiteralOperatorName.OpNameLoc),
  4436. Record);
  4437. break;
  4438. case DeclarationName::Identifier:
  4439. case DeclarationName::ObjCZeroArgSelector:
  4440. case DeclarationName::ObjCOneArgSelector:
  4441. case DeclarationName::ObjCMultiArgSelector:
  4442. case DeclarationName::CXXUsingDirective:
  4443. break;
  4444. }
  4445. }
  4446. void ASTWriter::AddDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
  4447. RecordDataImpl &Record) {
  4448. AddDeclarationName(NameInfo.getName(), Record);
  4449. AddSourceLocation(NameInfo.getLoc(), Record);
  4450. AddDeclarationNameLoc(NameInfo.getInfo(), NameInfo.getName(), Record);
  4451. }
  4452. void ASTWriter::AddQualifierInfo(const QualifierInfo &Info,
  4453. RecordDataImpl &Record) {
  4454. AddNestedNameSpecifierLoc(Info.QualifierLoc, Record);
  4455. Record.push_back(Info.NumTemplParamLists);
  4456. for (unsigned i=0, e=Info.NumTemplParamLists; i != e; ++i)
  4457. AddTemplateParameterList(Info.TemplParamLists[i], Record);
  4458. }
  4459. void ASTWriter::AddNestedNameSpecifier(NestedNameSpecifier *NNS,
  4460. RecordDataImpl &Record) {
  4461. // Nested name specifiers usually aren't too long. I think that 8 would
  4462. // typically accommodate the vast majority.
  4463. SmallVector<NestedNameSpecifier *, 8> NestedNames;
  4464. // Push each of the NNS's onto a stack for serialization in reverse order.
  4465. while (NNS) {
  4466. NestedNames.push_back(NNS);
  4467. NNS = NNS->getPrefix();
  4468. }
  4469. Record.push_back(NestedNames.size());
  4470. while(!NestedNames.empty()) {
  4471. NNS = NestedNames.pop_back_val();
  4472. NestedNameSpecifier::SpecifierKind Kind = NNS->getKind();
  4473. Record.push_back(Kind);
  4474. switch (Kind) {
  4475. case NestedNameSpecifier::Identifier:
  4476. AddIdentifierRef(NNS->getAsIdentifier(), Record);
  4477. break;
  4478. case NestedNameSpecifier::Namespace:
  4479. AddDeclRef(NNS->getAsNamespace(), Record);
  4480. break;
  4481. case NestedNameSpecifier::NamespaceAlias:
  4482. AddDeclRef(NNS->getAsNamespaceAlias(), Record);
  4483. break;
  4484. case NestedNameSpecifier::TypeSpec:
  4485. case NestedNameSpecifier::TypeSpecWithTemplate:
  4486. AddTypeRef(QualType(NNS->getAsType(), 0), Record);
  4487. Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
  4488. break;
  4489. case NestedNameSpecifier::Global:
  4490. // Don't need to write an associated value.
  4491. break;
  4492. case NestedNameSpecifier::Super:
  4493. AddDeclRef(NNS->getAsRecordDecl(), Record);
  4494. break;
  4495. }
  4496. }
  4497. }
  4498. void ASTWriter::AddNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
  4499. RecordDataImpl &Record) {
  4500. // Nested name specifiers usually aren't too long. I think that 8 would
  4501. // typically accommodate the vast majority.
  4502. SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
  4503. // Push each of the nested-name-specifiers's onto a stack for
  4504. // serialization in reverse order.
  4505. while (NNS) {
  4506. NestedNames.push_back(NNS);
  4507. NNS = NNS.getPrefix();
  4508. }
  4509. Record.push_back(NestedNames.size());
  4510. while(!NestedNames.empty()) {
  4511. NNS = NestedNames.pop_back_val();
  4512. NestedNameSpecifier::SpecifierKind Kind
  4513. = NNS.getNestedNameSpecifier()->getKind();
  4514. Record.push_back(Kind);
  4515. switch (Kind) {
  4516. case NestedNameSpecifier::Identifier:
  4517. AddIdentifierRef(NNS.getNestedNameSpecifier()->getAsIdentifier(), Record);
  4518. AddSourceRange(NNS.getLocalSourceRange(), Record);
  4519. break;
  4520. case NestedNameSpecifier::Namespace:
  4521. AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespace(), Record);
  4522. AddSourceRange(NNS.getLocalSourceRange(), Record);
  4523. break;
  4524. case NestedNameSpecifier::NamespaceAlias:
  4525. AddDeclRef(NNS.getNestedNameSpecifier()->getAsNamespaceAlias(), Record);
  4526. AddSourceRange(NNS.getLocalSourceRange(), Record);
  4527. break;
  4528. case NestedNameSpecifier::TypeSpec:
  4529. case NestedNameSpecifier::TypeSpecWithTemplate:
  4530. Record.push_back(Kind == NestedNameSpecifier::TypeSpecWithTemplate);
  4531. AddTypeLoc(NNS.getTypeLoc(), Record);
  4532. AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
  4533. break;
  4534. case NestedNameSpecifier::Global:
  4535. AddSourceLocation(NNS.getLocalSourceRange().getEnd(), Record);
  4536. break;
  4537. case NestedNameSpecifier::Super:
  4538. AddDeclRef(NNS.getNestedNameSpecifier()->getAsRecordDecl(), Record);
  4539. AddSourceRange(NNS.getLocalSourceRange(), Record);
  4540. break;
  4541. }
  4542. }
  4543. }
  4544. void ASTWriter::AddTemplateName(TemplateName Name, RecordDataImpl &Record) {
  4545. TemplateName::NameKind Kind = Name.getKind();
  4546. Record.push_back(Kind);
  4547. switch (Kind) {
  4548. case TemplateName::Template:
  4549. AddDeclRef(Name.getAsTemplateDecl(), Record);
  4550. break;
  4551. case TemplateName::OverloadedTemplate: {
  4552. OverloadedTemplateStorage *OvT = Name.getAsOverloadedTemplate();
  4553. Record.push_back(OvT->size());
  4554. for (OverloadedTemplateStorage::iterator I = OvT->begin(), E = OvT->end();
  4555. I != E; ++I)
  4556. AddDeclRef(*I, Record);
  4557. break;
  4558. }
  4559. case TemplateName::QualifiedTemplate: {
  4560. QualifiedTemplateName *QualT = Name.getAsQualifiedTemplateName();
  4561. AddNestedNameSpecifier(QualT->getQualifier(), Record);
  4562. Record.push_back(QualT->hasTemplateKeyword());
  4563. AddDeclRef(QualT->getTemplateDecl(), Record);
  4564. break;
  4565. }
  4566. case TemplateName::DependentTemplate: {
  4567. DependentTemplateName *DepT = Name.getAsDependentTemplateName();
  4568. AddNestedNameSpecifier(DepT->getQualifier(), Record);
  4569. Record.push_back(DepT->isIdentifier());
  4570. if (DepT->isIdentifier())
  4571. AddIdentifierRef(DepT->getIdentifier(), Record);
  4572. else
  4573. Record.push_back(DepT->getOperator());
  4574. break;
  4575. }
  4576. case TemplateName::SubstTemplateTemplateParm: {
  4577. SubstTemplateTemplateParmStorage *subst
  4578. = Name.getAsSubstTemplateTemplateParm();
  4579. AddDeclRef(subst->getParameter(), Record);
  4580. AddTemplateName(subst->getReplacement(), Record);
  4581. break;
  4582. }
  4583. case TemplateName::SubstTemplateTemplateParmPack: {
  4584. SubstTemplateTemplateParmPackStorage *SubstPack
  4585. = Name.getAsSubstTemplateTemplateParmPack();
  4586. AddDeclRef(SubstPack->getParameterPack(), Record);
  4587. AddTemplateArgument(SubstPack->getArgumentPack(), Record);
  4588. break;
  4589. }
  4590. }
  4591. }
  4592. void ASTWriter::AddTemplateArgument(const TemplateArgument &Arg,
  4593. RecordDataImpl &Record) {
  4594. Record.push_back(Arg.getKind());
  4595. switch (Arg.getKind()) {
  4596. case TemplateArgument::Null:
  4597. break;
  4598. case TemplateArgument::Type:
  4599. AddTypeRef(Arg.getAsType(), Record);
  4600. break;
  4601. case TemplateArgument::Declaration:
  4602. AddDeclRef(Arg.getAsDecl(), Record);
  4603. AddTypeRef(Arg.getParamTypeForDecl(), Record);
  4604. break;
  4605. case TemplateArgument::NullPtr:
  4606. AddTypeRef(Arg.getNullPtrType(), Record);
  4607. break;
  4608. case TemplateArgument::Integral:
  4609. AddAPSInt(Arg.getAsIntegral(), Record);
  4610. AddTypeRef(Arg.getIntegralType(), Record);
  4611. break;
  4612. case TemplateArgument::Template:
  4613. AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
  4614. break;
  4615. case TemplateArgument::TemplateExpansion:
  4616. AddTemplateName(Arg.getAsTemplateOrTemplatePattern(), Record);
  4617. if (Optional<unsigned> NumExpansions = Arg.getNumTemplateExpansions())
  4618. Record.push_back(*NumExpansions + 1);
  4619. else
  4620. Record.push_back(0);
  4621. break;
  4622. case TemplateArgument::Expression:
  4623. AddStmt(Arg.getAsExpr());
  4624. break;
  4625. case TemplateArgument::Pack:
  4626. Record.push_back(Arg.pack_size());
  4627. for (const auto &P : Arg.pack_elements())
  4628. AddTemplateArgument(P, Record);
  4629. break;
  4630. }
  4631. }
  4632. void
  4633. ASTWriter::AddTemplateParameterList(const TemplateParameterList *TemplateParams,
  4634. RecordDataImpl &Record) {
  4635. assert(TemplateParams && "No TemplateParams!");
  4636. AddSourceLocation(TemplateParams->getTemplateLoc(), Record);
  4637. AddSourceLocation(TemplateParams->getLAngleLoc(), Record);
  4638. AddSourceLocation(TemplateParams->getRAngleLoc(), Record);
  4639. Record.push_back(TemplateParams->size());
  4640. for (TemplateParameterList::const_iterator
  4641. P = TemplateParams->begin(), PEnd = TemplateParams->end();
  4642. P != PEnd; ++P)
  4643. AddDeclRef(*P, Record);
  4644. }
  4645. /// \brief Emit a template argument list.
  4646. void
  4647. ASTWriter::AddTemplateArgumentList(const TemplateArgumentList *TemplateArgs,
  4648. RecordDataImpl &Record) {
  4649. assert(TemplateArgs && "No TemplateArgs!");
  4650. Record.push_back(TemplateArgs->size());
  4651. for (int i=0, e = TemplateArgs->size(); i != e; ++i)
  4652. AddTemplateArgument(TemplateArgs->get(i), Record);
  4653. }
  4654. void
  4655. ASTWriter::AddASTTemplateArgumentListInfo
  4656. (const ASTTemplateArgumentListInfo *ASTTemplArgList, RecordDataImpl &Record) {
  4657. assert(ASTTemplArgList && "No ASTTemplArgList!");
  4658. AddSourceLocation(ASTTemplArgList->LAngleLoc, Record);
  4659. AddSourceLocation(ASTTemplArgList->RAngleLoc, Record);
  4660. Record.push_back(ASTTemplArgList->NumTemplateArgs);
  4661. const TemplateArgumentLoc *TemplArgs = ASTTemplArgList->getTemplateArgs();
  4662. for (int i=0, e = ASTTemplArgList->NumTemplateArgs; i != e; ++i)
  4663. AddTemplateArgumentLoc(TemplArgs[i], Record);
  4664. }
  4665. void
  4666. ASTWriter::AddUnresolvedSet(const ASTUnresolvedSet &Set, RecordDataImpl &Record) {
  4667. Record.push_back(Set.size());
  4668. for (ASTUnresolvedSet::const_iterator
  4669. I = Set.begin(), E = Set.end(); I != E; ++I) {
  4670. AddDeclRef(I.getDecl(), Record);
  4671. Record.push_back(I.getAccess());
  4672. }
  4673. }
  4674. void ASTWriter::AddCXXBaseSpecifier(const CXXBaseSpecifier &Base,
  4675. RecordDataImpl &Record) {
  4676. Record.push_back(Base.isVirtual());
  4677. Record.push_back(Base.isBaseOfClass());
  4678. Record.push_back(Base.getAccessSpecifierAsWritten());
  4679. Record.push_back(Base.getInheritConstructors());
  4680. AddTypeSourceInfo(Base.getTypeSourceInfo(), Record);
  4681. AddSourceRange(Base.getSourceRange(), Record);
  4682. AddSourceLocation(Base.isPackExpansion()? Base.getEllipsisLoc()
  4683. : SourceLocation(),
  4684. Record);
  4685. }
  4686. void ASTWriter::FlushCXXBaseSpecifiers() {
  4687. RecordData Record;
  4688. unsigned N = CXXBaseSpecifiersToWrite.size();
  4689. for (unsigned I = 0; I != N; ++I) {
  4690. Record.clear();
  4691. // Record the offset of this base-specifier set.
  4692. unsigned Index = CXXBaseSpecifiersToWrite[I].ID - 1;
  4693. if (Index == CXXBaseSpecifiersOffsets.size())
  4694. CXXBaseSpecifiersOffsets.push_back(Stream.GetCurrentBitNo());
  4695. else {
  4696. if (Index > CXXBaseSpecifiersOffsets.size())
  4697. CXXBaseSpecifiersOffsets.resize(Index + 1);
  4698. CXXBaseSpecifiersOffsets[Index] = Stream.GetCurrentBitNo();
  4699. }
  4700. const CXXBaseSpecifier *B = CXXBaseSpecifiersToWrite[I].Bases,
  4701. *BEnd = CXXBaseSpecifiersToWrite[I].BasesEnd;
  4702. Record.push_back(BEnd - B);
  4703. for (; B != BEnd; ++B)
  4704. AddCXXBaseSpecifier(*B, Record);
  4705. Stream.EmitRecord(serialization::DECL_CXX_BASE_SPECIFIERS, Record);
  4706. // Flush any expressions that were written as part of the base specifiers.
  4707. FlushStmts();
  4708. }
  4709. assert(N == CXXBaseSpecifiersToWrite.size() &&
  4710. "added more base specifiers while writing base specifiers");
  4711. CXXBaseSpecifiersToWrite.clear();
  4712. }
  4713. void ASTWriter::AddCXXCtorInitializers(
  4714. const CXXCtorInitializer * const *CtorInitializers,
  4715. unsigned NumCtorInitializers,
  4716. RecordDataImpl &Record) {
  4717. Record.push_back(NumCtorInitializers);
  4718. for (unsigned i=0; i != NumCtorInitializers; ++i) {
  4719. const CXXCtorInitializer *Init = CtorInitializers[i];
  4720. if (Init->isBaseInitializer()) {
  4721. Record.push_back(CTOR_INITIALIZER_BASE);
  4722. AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
  4723. Record.push_back(Init->isBaseVirtual());
  4724. } else if (Init->isDelegatingInitializer()) {
  4725. Record.push_back(CTOR_INITIALIZER_DELEGATING);
  4726. AddTypeSourceInfo(Init->getTypeSourceInfo(), Record);
  4727. } else if (Init->isMemberInitializer()){
  4728. Record.push_back(CTOR_INITIALIZER_MEMBER);
  4729. AddDeclRef(Init->getMember(), Record);
  4730. } else {
  4731. Record.push_back(CTOR_INITIALIZER_INDIRECT_MEMBER);
  4732. AddDeclRef(Init->getIndirectMember(), Record);
  4733. }
  4734. AddSourceLocation(Init->getMemberLocation(), Record);
  4735. AddStmt(Init->getInit());
  4736. AddSourceLocation(Init->getLParenLoc(), Record);
  4737. AddSourceLocation(Init->getRParenLoc(), Record);
  4738. Record.push_back(Init->isWritten());
  4739. if (Init->isWritten()) {
  4740. Record.push_back(Init->getSourceOrder());
  4741. } else {
  4742. Record.push_back(Init->getNumArrayIndices());
  4743. for (unsigned i=0, e=Init->getNumArrayIndices(); i != e; ++i)
  4744. AddDeclRef(Init->getArrayIndex(i), Record);
  4745. }
  4746. }
  4747. }
  4748. void ASTWriter::FlushCXXCtorInitializers() {
  4749. RecordData Record;
  4750. unsigned N = CXXCtorInitializersToWrite.size();
  4751. (void)N; // Silence unused warning in non-assert builds.
  4752. for (auto &Init : CXXCtorInitializersToWrite) {
  4753. Record.clear();
  4754. // Record the offset of this mem-initializer list.
  4755. unsigned Index = Init.ID - 1;
  4756. if (Index == CXXCtorInitializersOffsets.size())
  4757. CXXCtorInitializersOffsets.push_back(Stream.GetCurrentBitNo());
  4758. else {
  4759. if (Index > CXXCtorInitializersOffsets.size())
  4760. CXXCtorInitializersOffsets.resize(Index + 1);
  4761. CXXCtorInitializersOffsets[Index] = Stream.GetCurrentBitNo();
  4762. }
  4763. AddCXXCtorInitializers(Init.Inits.data(), Init.Inits.size(), Record);
  4764. Stream.EmitRecord(serialization::DECL_CXX_CTOR_INITIALIZERS, Record);
  4765. // Flush any expressions that were written as part of the initializers.
  4766. FlushStmts();
  4767. }
  4768. assert(N == CXXCtorInitializersToWrite.size() &&
  4769. "added more ctor initializers while writing ctor initializers");
  4770. CXXCtorInitializersToWrite.clear();
  4771. }
  4772. void ASTWriter::AddCXXDefinitionData(const CXXRecordDecl *D, RecordDataImpl &Record) {
  4773. auto &Data = D->data();
  4774. Record.push_back(Data.IsLambda);
  4775. Record.push_back(Data.UserDeclaredConstructor);
  4776. Record.push_back(Data.UserDeclaredSpecialMembers);
  4777. Record.push_back(Data.Aggregate);
  4778. Record.push_back(Data.PlainOldData);
  4779. Record.push_back(Data.Empty);
  4780. Record.push_back(Data.Polymorphic);
  4781. Record.push_back(Data.Abstract);
  4782. Record.push_back(Data.IsStandardLayout);
  4783. Record.push_back(Data.HasNoNonEmptyBases);
  4784. Record.push_back(Data.HasPrivateFields);
  4785. Record.push_back(Data.HasProtectedFields);
  4786. Record.push_back(Data.HasPublicFields);
  4787. Record.push_back(Data.HasMutableFields);
  4788. Record.push_back(Data.HasVariantMembers);
  4789. Record.push_back(Data.HasOnlyCMembers);
  4790. Record.push_back(Data.HasInClassInitializer);
  4791. Record.push_back(Data.HasUninitializedReferenceMember);
  4792. Record.push_back(Data.NeedOverloadResolutionForMoveConstructor);
  4793. Record.push_back(Data.NeedOverloadResolutionForMoveAssignment);
  4794. Record.push_back(Data.NeedOverloadResolutionForDestructor);
  4795. Record.push_back(Data.DefaultedMoveConstructorIsDeleted);
  4796. Record.push_back(Data.DefaultedMoveAssignmentIsDeleted);
  4797. Record.push_back(Data.DefaultedDestructorIsDeleted);
  4798. Record.push_back(Data.HasTrivialSpecialMembers);
  4799. Record.push_back(Data.DeclaredNonTrivialSpecialMembers);
  4800. Record.push_back(Data.HasIrrelevantDestructor);
  4801. Record.push_back(Data.HasConstexprNonCopyMoveConstructor);
  4802. Record.push_back(Data.DefaultedDefaultConstructorIsConstexpr);
  4803. Record.push_back(Data.HasConstexprDefaultConstructor);
  4804. Record.push_back(Data.HasNonLiteralTypeFieldsOrBases);
  4805. Record.push_back(Data.ComputedVisibleConversions);
  4806. Record.push_back(Data.UserProvidedDefaultConstructor);
  4807. Record.push_back(Data.DeclaredSpecialMembers);
  4808. Record.push_back(Data.ImplicitCopyConstructorHasConstParam);
  4809. Record.push_back(Data.ImplicitCopyAssignmentHasConstParam);
  4810. Record.push_back(Data.HasDeclaredCopyConstructorWithConstParam);
  4811. Record.push_back(Data.HasDeclaredCopyAssignmentWithConstParam);
  4812. // IsLambda bit is already saved.
  4813. Record.push_back(Data.NumBases);
  4814. if (Data.NumBases > 0)
  4815. AddCXXBaseSpecifiersRef(Data.getBases(), Data.getBases() + Data.NumBases,
  4816. Record);
  4817. // FIXME: Make VBases lazily computed when needed to avoid storing them.
  4818. Record.push_back(Data.NumVBases);
  4819. if (Data.NumVBases > 0)
  4820. AddCXXBaseSpecifiersRef(Data.getVBases(), Data.getVBases() + Data.NumVBases,
  4821. Record);
  4822. AddUnresolvedSet(Data.Conversions.get(*Context), Record);
  4823. AddUnresolvedSet(Data.VisibleConversions.get(*Context), Record);
  4824. // Data.Definition is the owning decl, no need to write it.
  4825. AddDeclRef(D->getFirstFriend(), Record);
  4826. // Add lambda-specific data.
  4827. if (Data.IsLambda) {
  4828. auto &Lambda = D->getLambdaData();
  4829. Record.push_back(Lambda.Dependent);
  4830. Record.push_back(Lambda.IsGenericLambda);
  4831. Record.push_back(Lambda.CaptureDefault);
  4832. Record.push_back(Lambda.NumCaptures);
  4833. Record.push_back(Lambda.NumExplicitCaptures);
  4834. Record.push_back(Lambda.ManglingNumber);
  4835. AddDeclRef(Lambda.ContextDecl, Record);
  4836. AddTypeSourceInfo(Lambda.MethodTyInfo, Record);
  4837. for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
  4838. const LambdaCapture &Capture = Lambda.Captures[I];
  4839. AddSourceLocation(Capture.getLocation(), Record);
  4840. Record.push_back(Capture.isImplicit());
  4841. Record.push_back(Capture.getCaptureKind());
  4842. switch (Capture.getCaptureKind()) {
  4843. case LCK_This:
  4844. case LCK_VLAType:
  4845. break;
  4846. case LCK_ByCopy:
  4847. case LCK_ByRef:
  4848. VarDecl *Var =
  4849. Capture.capturesVariable() ? Capture.getCapturedVar() : nullptr;
  4850. AddDeclRef(Var, Record);
  4851. AddSourceLocation(Capture.isPackExpansion() ? Capture.getEllipsisLoc()
  4852. : SourceLocation(),
  4853. Record);
  4854. break;
  4855. }
  4856. }
  4857. }
  4858. }
  4859. void ASTWriter::ReaderInitialized(ASTReader *Reader) {
  4860. assert(Reader && "Cannot remove chain");
  4861. assert((!Chain || Chain == Reader) && "Cannot replace chain");
  4862. assert(FirstDeclID == NextDeclID &&
  4863. FirstTypeID == NextTypeID &&
  4864. FirstIdentID == NextIdentID &&
  4865. FirstMacroID == NextMacroID &&
  4866. FirstSubmoduleID == NextSubmoduleID &&
  4867. FirstSelectorID == NextSelectorID &&
  4868. "Setting chain after writing has started.");
  4869. Chain = Reader;
  4870. // Note, this will get called multiple times, once one the reader starts up
  4871. // and again each time it's done reading a PCH or module.
  4872. FirstDeclID = NUM_PREDEF_DECL_IDS + Chain->getTotalNumDecls();
  4873. FirstTypeID = NUM_PREDEF_TYPE_IDS + Chain->getTotalNumTypes();
  4874. FirstIdentID = NUM_PREDEF_IDENT_IDS + Chain->getTotalNumIdentifiers();
  4875. FirstMacroID = NUM_PREDEF_MACRO_IDS + Chain->getTotalNumMacros();
  4876. FirstSubmoduleID = NUM_PREDEF_SUBMODULE_IDS + Chain->getTotalNumSubmodules();
  4877. FirstSelectorID = NUM_PREDEF_SELECTOR_IDS + Chain->getTotalNumSelectors();
  4878. NextDeclID = FirstDeclID;
  4879. NextTypeID = FirstTypeID;
  4880. NextIdentID = FirstIdentID;
  4881. NextMacroID = FirstMacroID;
  4882. NextSelectorID = FirstSelectorID;
  4883. NextSubmoduleID = FirstSubmoduleID;
  4884. }
  4885. void ASTWriter::IdentifierRead(IdentID ID, IdentifierInfo *II) {
  4886. // Always keep the highest ID. See \p TypeRead() for more information.
  4887. IdentID &StoredID = IdentifierIDs[II];
  4888. if (ID > StoredID)
  4889. StoredID = ID;
  4890. }
  4891. void ASTWriter::MacroRead(serialization::MacroID ID, MacroInfo *MI) {
  4892. // Always keep the highest ID. See \p TypeRead() for more information.
  4893. MacroID &StoredID = MacroIDs[MI];
  4894. if (ID > StoredID)
  4895. StoredID = ID;
  4896. }
  4897. void ASTWriter::TypeRead(TypeIdx Idx, QualType T) {
  4898. // Always take the highest-numbered type index. This copes with an interesting
  4899. // case for chained AST writing where we schedule writing the type and then,
  4900. // later, deserialize the type from another AST. In this case, we want to
  4901. // keep the higher-numbered entry so that we can properly write it out to
  4902. // the AST file.
  4903. TypeIdx &StoredIdx = TypeIdxs[T];
  4904. if (Idx.getIndex() >= StoredIdx.getIndex())
  4905. StoredIdx = Idx;
  4906. }
  4907. void ASTWriter::SelectorRead(SelectorID ID, Selector S) {
  4908. // Always keep the highest ID. See \p TypeRead() for more information.
  4909. SelectorID &StoredID = SelectorIDs[S];
  4910. if (ID > StoredID)
  4911. StoredID = ID;
  4912. }
  4913. void ASTWriter::MacroDefinitionRead(serialization::PreprocessedEntityID ID,
  4914. MacroDefinitionRecord *MD) {
  4915. assert(MacroDefinitions.find(MD) == MacroDefinitions.end());
  4916. MacroDefinitions[MD] = ID;
  4917. }
  4918. void ASTWriter::ModuleRead(serialization::SubmoduleID ID, Module *Mod) {
  4919. assert(SubmoduleIDs.find(Mod) == SubmoduleIDs.end());
  4920. SubmoduleIDs[Mod] = ID;
  4921. }
  4922. void ASTWriter::CompletedTagDefinition(const TagDecl *D) {
  4923. assert(D->isCompleteDefinition());
  4924. assert(!WritingAST && "Already writing the AST!");
  4925. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  4926. // We are interested when a PCH decl is modified.
  4927. if (RD->isFromASTFile()) {
  4928. // A forward reference was mutated into a definition. Rewrite it.
  4929. // FIXME: This happens during template instantiation, should we
  4930. // have created a new definition decl instead ?
  4931. assert(isTemplateInstantiation(RD->getTemplateSpecializationKind()) &&
  4932. "completed a tag from another module but not by instantiation?");
  4933. DeclUpdates[RD].push_back(
  4934. DeclUpdate(UPD_CXX_INSTANTIATED_CLASS_DEFINITION));
  4935. }
  4936. }
  4937. }
  4938. void ASTWriter::AddedVisibleDecl(const DeclContext *DC, const Decl *D) {
  4939. // TU and namespaces are handled elsewhere.
  4940. if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC))
  4941. return;
  4942. if (!(!D->isFromASTFile() && cast<Decl>(DC)->isFromASTFile()))
  4943. return; // Not a source decl added to a DeclContext from PCH.
  4944. assert(!getDefinitiveDeclContext(DC) && "DeclContext not definitive!");
  4945. assert(!WritingAST && "Already writing the AST!");
  4946. UpdatedDeclContexts.insert(DC);
  4947. UpdatingVisibleDecls.push_back(D);
  4948. }
  4949. void ASTWriter::AddedCXXImplicitMember(const CXXRecordDecl *RD, const Decl *D) {
  4950. assert(D->isImplicit());
  4951. if (!(!D->isFromASTFile() && RD->isFromASTFile()))
  4952. return; // Not a source member added to a class from PCH.
  4953. if (!isa<CXXMethodDecl>(D))
  4954. return; // We are interested in lazily declared implicit methods.
  4955. // A decl coming from PCH was modified.
  4956. assert(RD->isCompleteDefinition());
  4957. assert(!WritingAST && "Already writing the AST!");
  4958. DeclUpdates[RD].push_back(DeclUpdate(UPD_CXX_ADDED_IMPLICIT_MEMBER, D));
  4959. }
  4960. void ASTWriter::AddedCXXTemplateSpecialization(const ClassTemplateDecl *TD,
  4961. const ClassTemplateSpecializationDecl *D) {
  4962. // The specializations set is kept in the canonical template.
  4963. TD = TD->getCanonicalDecl();
  4964. if (!(!D->isFromASTFile() && TD->isFromASTFile()))
  4965. return; // Not a source specialization added to a template from PCH.
  4966. assert(!WritingAST && "Already writing the AST!");
  4967. DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
  4968. D));
  4969. }
  4970. void ASTWriter::AddedCXXTemplateSpecialization(
  4971. const VarTemplateDecl *TD, const VarTemplateSpecializationDecl *D) {
  4972. // The specializations set is kept in the canonical template.
  4973. TD = TD->getCanonicalDecl();
  4974. if (!(!D->isFromASTFile() && TD->isFromASTFile()))
  4975. return; // Not a source specialization added to a template from PCH.
  4976. assert(!WritingAST && "Already writing the AST!");
  4977. DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
  4978. D));
  4979. }
  4980. void ASTWriter::AddedCXXTemplateSpecialization(const FunctionTemplateDecl *TD,
  4981. const FunctionDecl *D) {
  4982. // The specializations set is kept in the canonical template.
  4983. TD = TD->getCanonicalDecl();
  4984. if (!(!D->isFromASTFile() && TD->isFromASTFile()))
  4985. return; // Not a source specialization added to a template from PCH.
  4986. assert(!WritingAST && "Already writing the AST!");
  4987. DeclUpdates[TD].push_back(DeclUpdate(UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION,
  4988. D));
  4989. }
  4990. void ASTWriter::ResolvedExceptionSpec(const FunctionDecl *FD) {
  4991. assert(!DoneWritingDeclsAndTypes && "Already done writing updates!");
  4992. if (!Chain) return;
  4993. Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
  4994. // If we don't already know the exception specification for this redecl
  4995. // chain, add an update record for it.
  4996. if (isUnresolvedExceptionSpec(cast<FunctionDecl>(D)
  4997. ->getType()
  4998. ->castAs<FunctionProtoType>()
  4999. ->getExceptionSpecType()))
  5000. DeclUpdates[D].push_back(UPD_CXX_RESOLVED_EXCEPTION_SPEC);
  5001. });
  5002. }
  5003. void ASTWriter::DeducedReturnType(const FunctionDecl *FD, QualType ReturnType) {
  5004. assert(!WritingAST && "Already writing the AST!");
  5005. if (!Chain) return;
  5006. Chain->forEachImportedKeyDecl(FD, [&](const Decl *D) {
  5007. DeclUpdates[D].push_back(
  5008. DeclUpdate(UPD_CXX_DEDUCED_RETURN_TYPE, ReturnType));
  5009. });
  5010. }
  5011. void ASTWriter::ResolvedOperatorDelete(const CXXDestructorDecl *DD,
  5012. const FunctionDecl *Delete) {
  5013. assert(!WritingAST && "Already writing the AST!");
  5014. assert(Delete && "Not given an operator delete");
  5015. if (!Chain) return;
  5016. Chain->forEachImportedKeyDecl(DD, [&](const Decl *D) {
  5017. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_RESOLVED_DTOR_DELETE, Delete));
  5018. });
  5019. }
  5020. void ASTWriter::CompletedImplicitDefinition(const FunctionDecl *D) {
  5021. assert(!WritingAST && "Already writing the AST!");
  5022. if (!D->isFromASTFile())
  5023. return; // Declaration not imported from PCH.
  5024. // Implicit function decl from a PCH was defined.
  5025. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
  5026. }
  5027. void ASTWriter::FunctionDefinitionInstantiated(const FunctionDecl *D) {
  5028. assert(!WritingAST && "Already writing the AST!");
  5029. if (!D->isFromASTFile())
  5030. return;
  5031. DeclUpdates[D].push_back(DeclUpdate(UPD_CXX_ADDED_FUNCTION_DEFINITION));
  5032. }
  5033. void ASTWriter::StaticDataMemberInstantiated(const VarDecl *D) {
  5034. assert(!WritingAST && "Already writing the AST!");
  5035. if (!D->isFromASTFile())
  5036. return;
  5037. // Since the actual instantiation is delayed, this really means that we need
  5038. // to update the instantiation location.
  5039. DeclUpdates[D].push_back(
  5040. DeclUpdate(UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER,
  5041. D->getMemberSpecializationInfo()->getPointOfInstantiation()));
  5042. }
  5043. void ASTWriter::AddedObjCCategoryToInterface(const ObjCCategoryDecl *CatD,
  5044. const ObjCInterfaceDecl *IFD) {
  5045. assert(!WritingAST && "Already writing the AST!");
  5046. if (!IFD->isFromASTFile())
  5047. return; // Declaration not imported from PCH.
  5048. assert(IFD->getDefinition() && "Category on a class without a definition?");
  5049. ObjCClassesWithCategories.insert(
  5050. const_cast<ObjCInterfaceDecl *>(IFD->getDefinition()));
  5051. }
  5052. void ASTWriter::AddedObjCPropertyInClassExtension(const ObjCPropertyDecl *Prop,
  5053. const ObjCPropertyDecl *OrigProp,
  5054. const ObjCCategoryDecl *ClassExt) {
  5055. const ObjCInterfaceDecl *D = ClassExt->getClassInterface();
  5056. if (!D)
  5057. return;
  5058. assert(!WritingAST && "Already writing the AST!");
  5059. if (!D->isFromASTFile())
  5060. return; // Declaration not imported from PCH.
  5061. RewriteDecl(D);
  5062. }
  5063. void ASTWriter::DeclarationMarkedUsed(const Decl *D) {
  5064. assert(!WritingAST && "Already writing the AST!");
  5065. if (!D->isFromASTFile())
  5066. return;
  5067. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_USED));
  5068. }
  5069. void ASTWriter::DeclarationMarkedOpenMPThreadPrivate(const Decl *D) {
  5070. assert(!WritingAST && "Already writing the AST!");
  5071. if (!D->isFromASTFile())
  5072. return;
  5073. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_MARKED_OPENMP_THREADPRIVATE));
  5074. }
  5075. void ASTWriter::RedefinedHiddenDefinition(const NamedDecl *D, Module *M) {
  5076. assert(!WritingAST && "Already writing the AST!");
  5077. assert(D->isHidden() && "expected a hidden declaration");
  5078. DeclUpdates[D].push_back(DeclUpdate(UPD_DECL_EXPORTED, M));
  5079. }
  5080. void ASTWriter::AddedAttributeToRecord(const Attr *Attr,
  5081. const RecordDecl *Record) {
  5082. assert(!WritingAST && "Already writing the AST!");
  5083. if (!Record->isFromASTFile())
  5084. return;
  5085. DeclUpdates[Record].push_back(DeclUpdate(UPD_ADDED_ATTR_TO_RECORD, Attr));
  5086. }