ASTWriter.cpp 252 KB

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