ASTWriter.cpp 247 KB

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