ASTWriter.cpp 252 KB

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