ASTWriter.cpp 231 KB

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