ASTWriter.cpp 252 KB

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