ASTWriter.cpp 246 KB

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