ASTReader.cpp 376 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606
  1. //===- ASTReader.cpp - AST File Reader ------------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines the ASTReader class, which reads AST files.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Serialization/ASTReader.h"
  14. #include "ASTCommon.h"
  15. #include "ASTReaderInternals.h"
  16. #include "clang/AST/ASTConsumer.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/AST/ASTMutationListener.h"
  19. #include "clang/AST/ASTUnresolvedSet.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclBase.h"
  22. #include "clang/AST/DeclCXX.h"
  23. #include "clang/AST/DeclFriend.h"
  24. #include "clang/AST/DeclGroup.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/AST/DeclTemplate.h"
  27. #include "clang/AST/DeclarationName.h"
  28. #include "clang/AST/Expr.h"
  29. #include "clang/AST/ExprCXX.h"
  30. #include "clang/AST/ExternalASTSource.h"
  31. #include "clang/AST/NestedNameSpecifier.h"
  32. #include "clang/AST/ODRHash.h"
  33. #include "clang/AST/RawCommentList.h"
  34. #include "clang/AST/TemplateBase.h"
  35. #include "clang/AST/TemplateName.h"
  36. #include "clang/AST/Type.h"
  37. #include "clang/AST/TypeLoc.h"
  38. #include "clang/AST/TypeLocVisitor.h"
  39. #include "clang/AST/UnresolvedSet.h"
  40. #include "clang/Basic/CommentOptions.h"
  41. #include "clang/Basic/Diagnostic.h"
  42. #include "clang/Basic/DiagnosticOptions.h"
  43. #include "clang/Basic/ExceptionSpecificationType.h"
  44. #include "clang/Basic/FileManager.h"
  45. #include "clang/Basic/FileSystemOptions.h"
  46. #include "clang/Basic/IdentifierTable.h"
  47. #include "clang/Basic/LLVM.h"
  48. #include "clang/Basic/LangOptions.h"
  49. #include "clang/Basic/MemoryBufferCache.h"
  50. #include "clang/Basic/Module.h"
  51. #include "clang/Basic/ObjCRuntime.h"
  52. #include "clang/Basic/OperatorKinds.h"
  53. #include "clang/Basic/PragmaKinds.h"
  54. #include "clang/Basic/Sanitizers.h"
  55. #include "clang/Basic/SourceLocation.h"
  56. #include "clang/Basic/SourceManager.h"
  57. #include "clang/Basic/SourceManagerInternals.h"
  58. #include "clang/Basic/Specifiers.h"
  59. #include "clang/Basic/TargetInfo.h"
  60. #include "clang/Basic/TargetOptions.h"
  61. #include "clang/Basic/TokenKinds.h"
  62. #include "clang/Basic/Version.h"
  63. #include "clang/Basic/VersionTuple.h"
  64. #include "clang/Frontend/PCHContainerOperations.h"
  65. #include "clang/Lex/HeaderSearch.h"
  66. #include "clang/Lex/HeaderSearchOptions.h"
  67. #include "clang/Lex/MacroInfo.h"
  68. #include "clang/Lex/ModuleMap.h"
  69. #include "clang/Lex/PreprocessingRecord.h"
  70. #include "clang/Lex/Preprocessor.h"
  71. #include "clang/Lex/PreprocessorOptions.h"
  72. #include "clang/Lex/Token.h"
  73. #include "clang/Sema/ObjCMethodList.h"
  74. #include "clang/Sema/Scope.h"
  75. #include "clang/Sema/Sema.h"
  76. #include "clang/Sema/Weak.h"
  77. #include "clang/Serialization/ASTBitCodes.h"
  78. #include "clang/Serialization/ASTDeserializationListener.h"
  79. #include "clang/Serialization/ContinuousRangeMap.h"
  80. #include "clang/Serialization/GlobalModuleIndex.h"
  81. #include "clang/Serialization/Module.h"
  82. #include "clang/Serialization/ModuleFileExtension.h"
  83. #include "clang/Serialization/ModuleManager.h"
  84. #include "clang/Serialization/SerializationDiagnostic.h"
  85. #include "llvm/ADT/APFloat.h"
  86. #include "llvm/ADT/APInt.h"
  87. #include "llvm/ADT/APSInt.h"
  88. #include "llvm/ADT/ArrayRef.h"
  89. #include "llvm/ADT/DenseMap.h"
  90. #include "llvm/ADT/FoldingSet.h"
  91. #include "llvm/ADT/Hashing.h"
  92. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  93. #include "llvm/ADT/None.h"
  94. #include "llvm/ADT/Optional.h"
  95. #include "llvm/ADT/STLExtras.h"
  96. #include "llvm/ADT/SmallPtrSet.h"
  97. #include "llvm/ADT/SmallString.h"
  98. #include "llvm/ADT/SmallVector.h"
  99. #include "llvm/ADT/StringExtras.h"
  100. #include "llvm/ADT/StringMap.h"
  101. #include "llvm/ADT/StringRef.h"
  102. #include "llvm/ADT/Triple.h"
  103. #include "llvm/ADT/iterator_range.h"
  104. #include "llvm/Bitcode/BitstreamReader.h"
  105. #include "llvm/Support/Casting.h"
  106. #include "llvm/Support/Compression.h"
  107. #include "llvm/Support/Compiler.h"
  108. #include "llvm/Support/Endian.h"
  109. #include "llvm/Support/Error.h"
  110. #include "llvm/Support/ErrorHandling.h"
  111. #include "llvm/Support/FileSystem.h"
  112. #include "llvm/Support/MemoryBuffer.h"
  113. #include "llvm/Support/Path.h"
  114. #include "llvm/Support/SaveAndRestore.h"
  115. #include "llvm/Support/Timer.h"
  116. #include "llvm/Support/raw_ostream.h"
  117. #include <algorithm>
  118. #include <cassert>
  119. #include <cstddef>
  120. #include <cstdint>
  121. #include <cstdio>
  122. #include <ctime>
  123. #include <iterator>
  124. #include <limits>
  125. #include <map>
  126. #include <memory>
  127. #include <string>
  128. #include <system_error>
  129. #include <tuple>
  130. #include <utility>
  131. #include <vector>
  132. using namespace clang;
  133. using namespace clang::serialization;
  134. using namespace clang::serialization::reader;
  135. using llvm::BitstreamCursor;
  136. //===----------------------------------------------------------------------===//
  137. // ChainedASTReaderListener implementation
  138. //===----------------------------------------------------------------------===//
  139. bool
  140. ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
  141. return First->ReadFullVersionInformation(FullVersion) ||
  142. Second->ReadFullVersionInformation(FullVersion);
  143. }
  144. void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
  145. First->ReadModuleName(ModuleName);
  146. Second->ReadModuleName(ModuleName);
  147. }
  148. void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
  149. First->ReadModuleMapFile(ModuleMapPath);
  150. Second->ReadModuleMapFile(ModuleMapPath);
  151. }
  152. bool
  153. ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
  154. bool Complain,
  155. bool AllowCompatibleDifferences) {
  156. return First->ReadLanguageOptions(LangOpts, Complain,
  157. AllowCompatibleDifferences) ||
  158. Second->ReadLanguageOptions(LangOpts, Complain,
  159. AllowCompatibleDifferences);
  160. }
  161. bool ChainedASTReaderListener::ReadTargetOptions(
  162. const TargetOptions &TargetOpts, bool Complain,
  163. bool AllowCompatibleDifferences) {
  164. return First->ReadTargetOptions(TargetOpts, Complain,
  165. AllowCompatibleDifferences) ||
  166. Second->ReadTargetOptions(TargetOpts, Complain,
  167. AllowCompatibleDifferences);
  168. }
  169. bool ChainedASTReaderListener::ReadDiagnosticOptions(
  170. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  171. return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
  172. Second->ReadDiagnosticOptions(DiagOpts, Complain);
  173. }
  174. bool
  175. ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
  176. bool Complain) {
  177. return First->ReadFileSystemOptions(FSOpts, Complain) ||
  178. Second->ReadFileSystemOptions(FSOpts, Complain);
  179. }
  180. bool ChainedASTReaderListener::ReadHeaderSearchOptions(
  181. const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
  182. bool Complain) {
  183. return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  184. Complain) ||
  185. Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  186. Complain);
  187. }
  188. bool ChainedASTReaderListener::ReadPreprocessorOptions(
  189. const PreprocessorOptions &PPOpts, bool Complain,
  190. std::string &SuggestedPredefines) {
  191. return First->ReadPreprocessorOptions(PPOpts, Complain,
  192. SuggestedPredefines) ||
  193. Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
  194. }
  195. void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
  196. unsigned Value) {
  197. First->ReadCounter(M, Value);
  198. Second->ReadCounter(M, Value);
  199. }
  200. bool ChainedASTReaderListener::needsInputFileVisitation() {
  201. return First->needsInputFileVisitation() ||
  202. Second->needsInputFileVisitation();
  203. }
  204. bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
  205. return First->needsSystemInputFileVisitation() ||
  206. Second->needsSystemInputFileVisitation();
  207. }
  208. void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
  209. ModuleKind Kind) {
  210. First->visitModuleFile(Filename, Kind);
  211. Second->visitModuleFile(Filename, Kind);
  212. }
  213. bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
  214. bool isSystem,
  215. bool isOverridden,
  216. bool isExplicitModule) {
  217. bool Continue = false;
  218. if (First->needsInputFileVisitation() &&
  219. (!isSystem || First->needsSystemInputFileVisitation()))
  220. Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
  221. isExplicitModule);
  222. if (Second->needsInputFileVisitation() &&
  223. (!isSystem || Second->needsSystemInputFileVisitation()))
  224. Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
  225. isExplicitModule);
  226. return Continue;
  227. }
  228. void ChainedASTReaderListener::readModuleFileExtension(
  229. const ModuleFileExtensionMetadata &Metadata) {
  230. First->readModuleFileExtension(Metadata);
  231. Second->readModuleFileExtension(Metadata);
  232. }
  233. //===----------------------------------------------------------------------===//
  234. // PCH validator implementation
  235. //===----------------------------------------------------------------------===//
  236. ASTReaderListener::~ASTReaderListener() = default;
  237. /// \brief Compare the given set of language options against an existing set of
  238. /// language options.
  239. ///
  240. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  241. /// \param AllowCompatibleDifferences If true, differences between compatible
  242. /// language options will be permitted.
  243. ///
  244. /// \returns true if the languagae options mis-match, false otherwise.
  245. static bool checkLanguageOptions(const LangOptions &LangOpts,
  246. const LangOptions &ExistingLangOpts,
  247. DiagnosticsEngine *Diags,
  248. bool AllowCompatibleDifferences = true) {
  249. #define LANGOPT(Name, Bits, Default, Description) \
  250. if (ExistingLangOpts.Name != LangOpts.Name) { \
  251. if (Diags) \
  252. Diags->Report(diag::err_pch_langopt_mismatch) \
  253. << Description << LangOpts.Name << ExistingLangOpts.Name; \
  254. return true; \
  255. }
  256. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  257. if (ExistingLangOpts.Name != LangOpts.Name) { \
  258. if (Diags) \
  259. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  260. << Description; \
  261. return true; \
  262. }
  263. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  264. if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
  265. if (Diags) \
  266. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  267. << Description; \
  268. return true; \
  269. }
  270. #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
  271. if (!AllowCompatibleDifferences) \
  272. LANGOPT(Name, Bits, Default, Description)
  273. #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
  274. if (!AllowCompatibleDifferences) \
  275. ENUM_LANGOPT(Name, Bits, Default, Description)
  276. #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
  277. if (!AllowCompatibleDifferences) \
  278. VALUE_LANGOPT(Name, Bits, Default, Description)
  279. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  280. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  281. #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
  282. #include "clang/Basic/LangOptions.def"
  283. if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
  284. if (Diags)
  285. Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
  286. return true;
  287. }
  288. if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
  289. if (Diags)
  290. Diags->Report(diag::err_pch_langopt_value_mismatch)
  291. << "target Objective-C runtime";
  292. return true;
  293. }
  294. if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
  295. LangOpts.CommentOpts.BlockCommandNames) {
  296. if (Diags)
  297. Diags->Report(diag::err_pch_langopt_value_mismatch)
  298. << "block command names";
  299. return true;
  300. }
  301. // Sanitizer feature mismatches are treated as compatible differences. If
  302. // compatible differences aren't allowed, we still only want to check for
  303. // mismatches of non-modular sanitizers (the only ones which can affect AST
  304. // generation).
  305. if (!AllowCompatibleDifferences) {
  306. SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
  307. SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
  308. SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
  309. ExistingSanitizers.clear(ModularSanitizers);
  310. ImportedSanitizers.clear(ModularSanitizers);
  311. if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
  312. const std::string Flag = "-fsanitize=";
  313. if (Diags) {
  314. #define SANITIZER(NAME, ID) \
  315. { \
  316. bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
  317. bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
  318. if (InExistingModule != InImportedModule) \
  319. Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
  320. << InExistingModule << (Flag + NAME); \
  321. }
  322. #include "clang/Basic/Sanitizers.def"
  323. }
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. /// \brief Compare the given set of target options against an existing set of
  330. /// target options.
  331. ///
  332. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  333. ///
  334. /// \returns true if the target options mis-match, false otherwise.
  335. static bool checkTargetOptions(const TargetOptions &TargetOpts,
  336. const TargetOptions &ExistingTargetOpts,
  337. DiagnosticsEngine *Diags,
  338. bool AllowCompatibleDifferences = true) {
  339. #define CHECK_TARGET_OPT(Field, Name) \
  340. if (TargetOpts.Field != ExistingTargetOpts.Field) { \
  341. if (Diags) \
  342. Diags->Report(diag::err_pch_targetopt_mismatch) \
  343. << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
  344. return true; \
  345. }
  346. // The triple and ABI must match exactly.
  347. CHECK_TARGET_OPT(Triple, "target");
  348. CHECK_TARGET_OPT(ABI, "target ABI");
  349. // We can tolerate different CPUs in many cases, notably when one CPU
  350. // supports a strict superset of another. When allowing compatible
  351. // differences skip this check.
  352. if (!AllowCompatibleDifferences)
  353. CHECK_TARGET_OPT(CPU, "target CPU");
  354. #undef CHECK_TARGET_OPT
  355. // Compare feature sets.
  356. SmallVector<StringRef, 4> ExistingFeatures(
  357. ExistingTargetOpts.FeaturesAsWritten.begin(),
  358. ExistingTargetOpts.FeaturesAsWritten.end());
  359. SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
  360. TargetOpts.FeaturesAsWritten.end());
  361. std::sort(ExistingFeatures.begin(), ExistingFeatures.end());
  362. std::sort(ReadFeatures.begin(), ReadFeatures.end());
  363. // We compute the set difference in both directions explicitly so that we can
  364. // diagnose the differences differently.
  365. SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
  366. std::set_difference(
  367. ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
  368. ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
  369. std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
  370. ExistingFeatures.begin(), ExistingFeatures.end(),
  371. std::back_inserter(UnmatchedReadFeatures));
  372. // If we are allowing compatible differences and the read feature set is
  373. // a strict subset of the existing feature set, there is nothing to diagnose.
  374. if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
  375. return false;
  376. if (Diags) {
  377. for (StringRef Feature : UnmatchedReadFeatures)
  378. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  379. << /* is-existing-feature */ false << Feature;
  380. for (StringRef Feature : UnmatchedExistingFeatures)
  381. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  382. << /* is-existing-feature */ true << Feature;
  383. }
  384. return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
  385. }
  386. bool
  387. PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
  388. bool Complain,
  389. bool AllowCompatibleDifferences) {
  390. const LangOptions &ExistingLangOpts = PP.getLangOpts();
  391. return checkLanguageOptions(LangOpts, ExistingLangOpts,
  392. Complain ? &Reader.Diags : nullptr,
  393. AllowCompatibleDifferences);
  394. }
  395. bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
  396. bool Complain,
  397. bool AllowCompatibleDifferences) {
  398. const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
  399. return checkTargetOptions(TargetOpts, ExistingTargetOpts,
  400. Complain ? &Reader.Diags : nullptr,
  401. AllowCompatibleDifferences);
  402. }
  403. namespace {
  404. using MacroDefinitionsMap =
  405. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
  406. using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
  407. } // namespace
  408. static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
  409. DiagnosticsEngine &Diags,
  410. bool Complain) {
  411. using Level = DiagnosticsEngine::Level;
  412. // Check current mappings for new -Werror mappings, and the stored mappings
  413. // for cases that were explicitly mapped to *not* be errors that are now
  414. // errors because of options like -Werror.
  415. DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
  416. for (DiagnosticsEngine *MappingSource : MappingSources) {
  417. for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
  418. diag::kind DiagID = DiagIDMappingPair.first;
  419. Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
  420. if (CurLevel < DiagnosticsEngine::Error)
  421. continue; // not significant
  422. Level StoredLevel =
  423. StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
  424. if (StoredLevel < DiagnosticsEngine::Error) {
  425. if (Complain)
  426. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
  427. Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
  428. return true;
  429. }
  430. }
  431. }
  432. return false;
  433. }
  434. static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
  435. diag::Severity Ext = Diags.getExtensionHandlingBehavior();
  436. if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
  437. return true;
  438. return Ext >= diag::Severity::Error;
  439. }
  440. static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
  441. DiagnosticsEngine &Diags,
  442. bool IsSystem, bool Complain) {
  443. // Top-level options
  444. if (IsSystem) {
  445. if (Diags.getSuppressSystemWarnings())
  446. return false;
  447. // If -Wsystem-headers was not enabled before, be conservative
  448. if (StoredDiags.getSuppressSystemWarnings()) {
  449. if (Complain)
  450. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
  451. return true;
  452. }
  453. }
  454. if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
  455. if (Complain)
  456. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
  457. return true;
  458. }
  459. if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
  460. !StoredDiags.getEnableAllWarnings()) {
  461. if (Complain)
  462. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
  463. return true;
  464. }
  465. if (isExtHandlingFromDiagsError(Diags) &&
  466. !isExtHandlingFromDiagsError(StoredDiags)) {
  467. if (Complain)
  468. Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
  469. return true;
  470. }
  471. return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
  472. }
  473. /// Return the top import module if it is implicit, nullptr otherwise.
  474. static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
  475. Preprocessor &PP) {
  476. // If the original import came from a file explicitly generated by the user,
  477. // don't check the diagnostic mappings.
  478. // FIXME: currently this is approximated by checking whether this is not a
  479. // module import of an implicitly-loaded module file.
  480. // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
  481. // the transitive closure of its imports, since unrelated modules cannot be
  482. // imported until after this module finishes validation.
  483. ModuleFile *TopImport = &*ModuleMgr.rbegin();
  484. while (!TopImport->ImportedBy.empty())
  485. TopImport = TopImport->ImportedBy[0];
  486. if (TopImport->Kind != MK_ImplicitModule)
  487. return nullptr;
  488. StringRef ModuleName = TopImport->ModuleName;
  489. assert(!ModuleName.empty() && "diagnostic options read before module name");
  490. Module *M = PP.getHeaderSearchInfo().lookupModule(ModuleName);
  491. assert(M && "missing module");
  492. return M;
  493. }
  494. bool PCHValidator::ReadDiagnosticOptions(
  495. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  496. DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
  497. IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
  498. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
  499. new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
  500. // This should never fail, because we would have processed these options
  501. // before writing them to an ASTFile.
  502. ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
  503. ModuleManager &ModuleMgr = Reader.getModuleManager();
  504. assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
  505. Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
  506. if (!TopM)
  507. return false;
  508. // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
  509. // contains the union of their flags.
  510. return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
  511. Complain);
  512. }
  513. /// \brief Collect the macro definitions provided by the given preprocessor
  514. /// options.
  515. static void
  516. collectMacroDefinitions(const PreprocessorOptions &PPOpts,
  517. MacroDefinitionsMap &Macros,
  518. SmallVectorImpl<StringRef> *MacroNames = nullptr) {
  519. for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
  520. StringRef Macro = PPOpts.Macros[I].first;
  521. bool IsUndef = PPOpts.Macros[I].second;
  522. std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
  523. StringRef MacroName = MacroPair.first;
  524. StringRef MacroBody = MacroPair.second;
  525. // For an #undef'd macro, we only care about the name.
  526. if (IsUndef) {
  527. if (MacroNames && !Macros.count(MacroName))
  528. MacroNames->push_back(MacroName);
  529. Macros[MacroName] = std::make_pair("", true);
  530. continue;
  531. }
  532. // For a #define'd macro, figure out the actual definition.
  533. if (MacroName.size() == Macro.size())
  534. MacroBody = "1";
  535. else {
  536. // Note: GCC drops anything following an end-of-line character.
  537. StringRef::size_type End = MacroBody.find_first_of("\n\r");
  538. MacroBody = MacroBody.substr(0, End);
  539. }
  540. if (MacroNames && !Macros.count(MacroName))
  541. MacroNames->push_back(MacroName);
  542. Macros[MacroName] = std::make_pair(MacroBody, false);
  543. }
  544. }
  545. /// \brief Check the preprocessor options deserialized from the control block
  546. /// against the preprocessor options in an existing preprocessor.
  547. ///
  548. /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
  549. /// \param Validate If true, validate preprocessor options. If false, allow
  550. /// macros defined by \p ExistingPPOpts to override those defined by
  551. /// \p PPOpts in SuggestedPredefines.
  552. static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
  553. const PreprocessorOptions &ExistingPPOpts,
  554. DiagnosticsEngine *Diags,
  555. FileManager &FileMgr,
  556. std::string &SuggestedPredefines,
  557. const LangOptions &LangOpts,
  558. bool Validate = true) {
  559. // Check macro definitions.
  560. MacroDefinitionsMap ASTFileMacros;
  561. collectMacroDefinitions(PPOpts, ASTFileMacros);
  562. MacroDefinitionsMap ExistingMacros;
  563. SmallVector<StringRef, 4> ExistingMacroNames;
  564. collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
  565. for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
  566. // Dig out the macro definition in the existing preprocessor options.
  567. StringRef MacroName = ExistingMacroNames[I];
  568. std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
  569. // Check whether we know anything about this macro name or not.
  570. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
  571. ASTFileMacros.find(MacroName);
  572. if (!Validate || Known == ASTFileMacros.end()) {
  573. // FIXME: Check whether this identifier was referenced anywhere in the
  574. // AST file. If so, we should reject the AST file. Unfortunately, this
  575. // information isn't in the control block. What shall we do about it?
  576. if (Existing.second) {
  577. SuggestedPredefines += "#undef ";
  578. SuggestedPredefines += MacroName.str();
  579. SuggestedPredefines += '\n';
  580. } else {
  581. SuggestedPredefines += "#define ";
  582. SuggestedPredefines += MacroName.str();
  583. SuggestedPredefines += ' ';
  584. SuggestedPredefines += Existing.first.str();
  585. SuggestedPredefines += '\n';
  586. }
  587. continue;
  588. }
  589. // If the macro was defined in one but undef'd in the other, we have a
  590. // conflict.
  591. if (Existing.second != Known->second.second) {
  592. if (Diags) {
  593. Diags->Report(diag::err_pch_macro_def_undef)
  594. << MacroName << Known->second.second;
  595. }
  596. return true;
  597. }
  598. // If the macro was #undef'd in both, or if the macro bodies are identical,
  599. // it's fine.
  600. if (Existing.second || Existing.first == Known->second.first)
  601. continue;
  602. // The macro bodies differ; complain.
  603. if (Diags) {
  604. Diags->Report(diag::err_pch_macro_def_conflict)
  605. << MacroName << Known->second.first << Existing.first;
  606. }
  607. return true;
  608. }
  609. // Check whether we're using predefines.
  610. if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
  611. if (Diags) {
  612. Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
  613. }
  614. return true;
  615. }
  616. // Detailed record is important since it is used for the module cache hash.
  617. if (LangOpts.Modules &&
  618. PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
  619. if (Diags) {
  620. Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
  621. }
  622. return true;
  623. }
  624. // Compute the #include and #include_macros lines we need.
  625. for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
  626. StringRef File = ExistingPPOpts.Includes[I];
  627. if (File == ExistingPPOpts.ImplicitPCHInclude)
  628. continue;
  629. if (std::find(PPOpts.Includes.begin(), PPOpts.Includes.end(), File)
  630. != PPOpts.Includes.end())
  631. continue;
  632. SuggestedPredefines += "#include \"";
  633. SuggestedPredefines += File;
  634. SuggestedPredefines += "\"\n";
  635. }
  636. for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
  637. StringRef File = ExistingPPOpts.MacroIncludes[I];
  638. if (std::find(PPOpts.MacroIncludes.begin(), PPOpts.MacroIncludes.end(),
  639. File)
  640. != PPOpts.MacroIncludes.end())
  641. continue;
  642. SuggestedPredefines += "#__include_macros \"";
  643. SuggestedPredefines += File;
  644. SuggestedPredefines += "\"\n##\n";
  645. }
  646. return false;
  647. }
  648. bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  649. bool Complain,
  650. std::string &SuggestedPredefines) {
  651. const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
  652. return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
  653. Complain? &Reader.Diags : nullptr,
  654. PP.getFileManager(),
  655. SuggestedPredefines,
  656. PP.getLangOpts());
  657. }
  658. bool SimpleASTReaderListener::ReadPreprocessorOptions(
  659. const PreprocessorOptions &PPOpts,
  660. bool Complain,
  661. std::string &SuggestedPredefines) {
  662. return checkPreprocessorOptions(PPOpts,
  663. PP.getPreprocessorOpts(),
  664. nullptr,
  665. PP.getFileManager(),
  666. SuggestedPredefines,
  667. PP.getLangOpts(),
  668. false);
  669. }
  670. /// Check the header search options deserialized from the control block
  671. /// against the header search options in an existing preprocessor.
  672. ///
  673. /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
  674. static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  675. StringRef SpecificModuleCachePath,
  676. StringRef ExistingModuleCachePath,
  677. DiagnosticsEngine *Diags,
  678. const LangOptions &LangOpts) {
  679. if (LangOpts.Modules) {
  680. if (SpecificModuleCachePath != ExistingModuleCachePath) {
  681. if (Diags)
  682. Diags->Report(diag::err_pch_modulecache_mismatch)
  683. << SpecificModuleCachePath << ExistingModuleCachePath;
  684. return true;
  685. }
  686. }
  687. return false;
  688. }
  689. bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  690. StringRef SpecificModuleCachePath,
  691. bool Complain) {
  692. return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  693. PP.getHeaderSearchInfo().getModuleCachePath(),
  694. Complain ? &Reader.Diags : nullptr,
  695. PP.getLangOpts());
  696. }
  697. void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
  698. PP.setCounterValue(Value);
  699. }
  700. //===----------------------------------------------------------------------===//
  701. // AST reader implementation
  702. //===----------------------------------------------------------------------===//
  703. void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
  704. bool TakeOwnership) {
  705. DeserializationListener = Listener;
  706. OwnsDeserializationListener = TakeOwnership;
  707. }
  708. unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
  709. return serialization::ComputeHash(Sel);
  710. }
  711. std::pair<unsigned, unsigned>
  712. ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
  713. using namespace llvm::support;
  714. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  715. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  716. return std::make_pair(KeyLen, DataLen);
  717. }
  718. ASTSelectorLookupTrait::internal_key_type
  719. ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
  720. using namespace llvm::support;
  721. SelectorTable &SelTable = Reader.getContext().Selectors;
  722. unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
  723. IdentifierInfo *FirstII = Reader.getLocalIdentifier(
  724. F, endian::readNext<uint32_t, little, unaligned>(d));
  725. if (N == 0)
  726. return SelTable.getNullarySelector(FirstII);
  727. else if (N == 1)
  728. return SelTable.getUnarySelector(FirstII);
  729. SmallVector<IdentifierInfo *, 16> Args;
  730. Args.push_back(FirstII);
  731. for (unsigned I = 1; I != N; ++I)
  732. Args.push_back(Reader.getLocalIdentifier(
  733. F, endian::readNext<uint32_t, little, unaligned>(d)));
  734. return SelTable.getSelector(N, Args.data());
  735. }
  736. ASTSelectorLookupTrait::data_type
  737. ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
  738. unsigned DataLen) {
  739. using namespace llvm::support;
  740. data_type Result;
  741. Result.ID = Reader.getGlobalSelectorID(
  742. F, endian::readNext<uint32_t, little, unaligned>(d));
  743. unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
  744. unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
  745. Result.InstanceBits = FullInstanceBits & 0x3;
  746. Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
  747. Result.FactoryBits = FullFactoryBits & 0x3;
  748. Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
  749. unsigned NumInstanceMethods = FullInstanceBits >> 3;
  750. unsigned NumFactoryMethods = FullFactoryBits >> 3;
  751. // Load instance methods
  752. for (unsigned I = 0; I != NumInstanceMethods; ++I) {
  753. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  754. F, endian::readNext<uint32_t, little, unaligned>(d)))
  755. Result.Instance.push_back(Method);
  756. }
  757. // Load factory methods
  758. for (unsigned I = 0; I != NumFactoryMethods; ++I) {
  759. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  760. F, endian::readNext<uint32_t, little, unaligned>(d)))
  761. Result.Factory.push_back(Method);
  762. }
  763. return Result;
  764. }
  765. unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
  766. return llvm::HashString(a);
  767. }
  768. std::pair<unsigned, unsigned>
  769. ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
  770. using namespace llvm::support;
  771. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  772. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  773. return std::make_pair(KeyLen, DataLen);
  774. }
  775. ASTIdentifierLookupTraitBase::internal_key_type
  776. ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
  777. assert(n >= 2 && d[n-1] == '\0');
  778. return StringRef((const char*) d, n-1);
  779. }
  780. /// \brief Whether the given identifier is "interesting".
  781. static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
  782. bool IsModule) {
  783. return II.hadMacroDefinition() ||
  784. II.isPoisoned() ||
  785. (IsModule ? II.hasRevertedBuiltin() : II.getObjCOrBuiltinID()) ||
  786. II.hasRevertedTokenIDToIdentifier() ||
  787. (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
  788. II.getFETokenInfo<void>());
  789. }
  790. static bool readBit(unsigned &Bits) {
  791. bool Value = Bits & 0x1;
  792. Bits >>= 1;
  793. return Value;
  794. }
  795. IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
  796. using namespace llvm::support;
  797. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  798. return Reader.getGlobalIdentifierID(F, RawID >> 1);
  799. }
  800. static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
  801. if (!II.isFromAST()) {
  802. II.setIsFromAST();
  803. bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
  804. if (isInterestingIdentifier(Reader, II, IsModule))
  805. II.setChangedSinceDeserialization();
  806. }
  807. }
  808. IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
  809. const unsigned char* d,
  810. unsigned DataLen) {
  811. using namespace llvm::support;
  812. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  813. bool IsInteresting = RawID & 0x01;
  814. // Wipe out the "is interesting" bit.
  815. RawID = RawID >> 1;
  816. // Build the IdentifierInfo and link the identifier ID with it.
  817. IdentifierInfo *II = KnownII;
  818. if (!II) {
  819. II = &Reader.getIdentifierTable().getOwn(k);
  820. KnownII = II;
  821. }
  822. markIdentifierFromAST(Reader, *II);
  823. Reader.markIdentifierUpToDate(II);
  824. IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
  825. if (!IsInteresting) {
  826. // For uninteresting identifiers, there's nothing else to do. Just notify
  827. // the reader that we've finished loading this identifier.
  828. Reader.SetIdentifierInfo(ID, II);
  829. return II;
  830. }
  831. unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
  832. unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
  833. bool CPlusPlusOperatorKeyword = readBit(Bits);
  834. bool HasRevertedTokenIDToIdentifier = readBit(Bits);
  835. bool HasRevertedBuiltin = readBit(Bits);
  836. bool Poisoned = readBit(Bits);
  837. bool ExtensionToken = readBit(Bits);
  838. bool HadMacroDefinition = readBit(Bits);
  839. assert(Bits == 0 && "Extra bits in the identifier?");
  840. DataLen -= 8;
  841. // Set or check the various bits in the IdentifierInfo structure.
  842. // Token IDs are read-only.
  843. if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
  844. II->revertTokenIDToIdentifier();
  845. if (!F.isModule())
  846. II->setObjCOrBuiltinID(ObjCOrBuiltinID);
  847. else if (HasRevertedBuiltin && II->getBuiltinID()) {
  848. II->revertBuiltin();
  849. assert((II->hasRevertedBuiltin() ||
  850. II->getObjCOrBuiltinID() == ObjCOrBuiltinID) &&
  851. "Incorrect ObjC keyword or builtin ID");
  852. }
  853. assert(II->isExtensionToken() == ExtensionToken &&
  854. "Incorrect extension token flag");
  855. (void)ExtensionToken;
  856. if (Poisoned)
  857. II->setIsPoisoned(true);
  858. assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
  859. "Incorrect C++ operator keyword flag");
  860. (void)CPlusPlusOperatorKeyword;
  861. // If this identifier is a macro, deserialize the macro
  862. // definition.
  863. if (HadMacroDefinition) {
  864. uint32_t MacroDirectivesOffset =
  865. endian::readNext<uint32_t, little, unaligned>(d);
  866. DataLen -= 4;
  867. Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
  868. }
  869. Reader.SetIdentifierInfo(ID, II);
  870. // Read all of the declarations visible at global scope with this
  871. // name.
  872. if (DataLen > 0) {
  873. SmallVector<uint32_t, 4> DeclIDs;
  874. for (; DataLen > 0; DataLen -= 4)
  875. DeclIDs.push_back(Reader.getGlobalDeclID(
  876. F, endian::readNext<uint32_t, little, unaligned>(d)));
  877. Reader.SetGloballyVisibleDecls(II, DeclIDs);
  878. }
  879. return II;
  880. }
  881. DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
  882. : Kind(Name.getNameKind()) {
  883. switch (Kind) {
  884. case DeclarationName::Identifier:
  885. Data = (uint64_t)Name.getAsIdentifierInfo();
  886. break;
  887. case DeclarationName::ObjCZeroArgSelector:
  888. case DeclarationName::ObjCOneArgSelector:
  889. case DeclarationName::ObjCMultiArgSelector:
  890. Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
  891. break;
  892. case DeclarationName::CXXOperatorName:
  893. Data = Name.getCXXOverloadedOperator();
  894. break;
  895. case DeclarationName::CXXLiteralOperatorName:
  896. Data = (uint64_t)Name.getCXXLiteralIdentifier();
  897. break;
  898. case DeclarationName::CXXDeductionGuideName:
  899. Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
  900. ->getDeclName().getAsIdentifierInfo();
  901. break;
  902. case DeclarationName::CXXConstructorName:
  903. case DeclarationName::CXXDestructorName:
  904. case DeclarationName::CXXConversionFunctionName:
  905. case DeclarationName::CXXUsingDirective:
  906. Data = 0;
  907. break;
  908. }
  909. }
  910. unsigned DeclarationNameKey::getHash() const {
  911. llvm::FoldingSetNodeID ID;
  912. ID.AddInteger(Kind);
  913. switch (Kind) {
  914. case DeclarationName::Identifier:
  915. case DeclarationName::CXXLiteralOperatorName:
  916. case DeclarationName::CXXDeductionGuideName:
  917. ID.AddString(((IdentifierInfo*)Data)->getName());
  918. break;
  919. case DeclarationName::ObjCZeroArgSelector:
  920. case DeclarationName::ObjCOneArgSelector:
  921. case DeclarationName::ObjCMultiArgSelector:
  922. ID.AddInteger(serialization::ComputeHash(Selector(Data)));
  923. break;
  924. case DeclarationName::CXXOperatorName:
  925. ID.AddInteger((OverloadedOperatorKind)Data);
  926. break;
  927. case DeclarationName::CXXConstructorName:
  928. case DeclarationName::CXXDestructorName:
  929. case DeclarationName::CXXConversionFunctionName:
  930. case DeclarationName::CXXUsingDirective:
  931. break;
  932. }
  933. return ID.ComputeHash();
  934. }
  935. ModuleFile *
  936. ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
  937. using namespace llvm::support;
  938. uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
  939. return Reader.getLocalModuleFile(F, ModuleFileID);
  940. }
  941. std::pair<unsigned, unsigned>
  942. ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
  943. using namespace llvm::support;
  944. unsigned KeyLen = endian::readNext<uint16_t, little, unaligned>(d);
  945. unsigned DataLen = endian::readNext<uint16_t, little, unaligned>(d);
  946. return std::make_pair(KeyLen, DataLen);
  947. }
  948. ASTDeclContextNameLookupTrait::internal_key_type
  949. ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
  950. using namespace llvm::support;
  951. auto Kind = (DeclarationName::NameKind)*d++;
  952. uint64_t Data;
  953. switch (Kind) {
  954. case DeclarationName::Identifier:
  955. case DeclarationName::CXXLiteralOperatorName:
  956. case DeclarationName::CXXDeductionGuideName:
  957. Data = (uint64_t)Reader.getLocalIdentifier(
  958. F, endian::readNext<uint32_t, little, unaligned>(d));
  959. break;
  960. case DeclarationName::ObjCZeroArgSelector:
  961. case DeclarationName::ObjCOneArgSelector:
  962. case DeclarationName::ObjCMultiArgSelector:
  963. Data =
  964. (uint64_t)Reader.getLocalSelector(
  965. F, endian::readNext<uint32_t, little, unaligned>(
  966. d)).getAsOpaquePtr();
  967. break;
  968. case DeclarationName::CXXOperatorName:
  969. Data = *d++; // OverloadedOperatorKind
  970. break;
  971. case DeclarationName::CXXConstructorName:
  972. case DeclarationName::CXXDestructorName:
  973. case DeclarationName::CXXConversionFunctionName:
  974. case DeclarationName::CXXUsingDirective:
  975. Data = 0;
  976. break;
  977. }
  978. return DeclarationNameKey(Kind, Data);
  979. }
  980. void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
  981. const unsigned char *d,
  982. unsigned DataLen,
  983. data_type_builder &Val) {
  984. using namespace llvm::support;
  985. for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
  986. uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
  987. Val.insert(Reader.getGlobalDeclID(F, LocalID));
  988. }
  989. }
  990. bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
  991. BitstreamCursor &Cursor,
  992. uint64_t Offset,
  993. DeclContext *DC) {
  994. assert(Offset != 0);
  995. SavedStreamPosition SavedPosition(Cursor);
  996. Cursor.JumpToBit(Offset);
  997. RecordData Record;
  998. StringRef Blob;
  999. unsigned Code = Cursor.ReadCode();
  1000. unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
  1001. if (RecCode != DECL_CONTEXT_LEXICAL) {
  1002. Error("Expected lexical block");
  1003. return true;
  1004. }
  1005. assert(!isa<TranslationUnitDecl>(DC) &&
  1006. "expected a TU_UPDATE_LEXICAL record for TU");
  1007. // If we are handling a C++ class template instantiation, we can see multiple
  1008. // lexical updates for the same record. It's important that we select only one
  1009. // of them, so that field numbering works properly. Just pick the first one we
  1010. // see.
  1011. auto &Lex = LexicalDecls[DC];
  1012. if (!Lex.first) {
  1013. Lex = std::make_pair(
  1014. &M, llvm::makeArrayRef(
  1015. reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
  1016. Blob.data()),
  1017. Blob.size() / 4));
  1018. }
  1019. DC->setHasExternalLexicalStorage(true);
  1020. return false;
  1021. }
  1022. bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
  1023. BitstreamCursor &Cursor,
  1024. uint64_t Offset,
  1025. DeclID ID) {
  1026. assert(Offset != 0);
  1027. SavedStreamPosition SavedPosition(Cursor);
  1028. Cursor.JumpToBit(Offset);
  1029. RecordData Record;
  1030. StringRef Blob;
  1031. unsigned Code = Cursor.ReadCode();
  1032. unsigned RecCode = Cursor.readRecord(Code, Record, &Blob);
  1033. if (RecCode != DECL_CONTEXT_VISIBLE) {
  1034. Error("Expected visible lookup table block");
  1035. return true;
  1036. }
  1037. // We can't safely determine the primary context yet, so delay attaching the
  1038. // lookup table until we're done with recursive deserialization.
  1039. auto *Data = (const unsigned char*)Blob.data();
  1040. PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
  1041. return false;
  1042. }
  1043. void ASTReader::Error(StringRef Msg) const {
  1044. Error(diag::err_fe_pch_malformed, Msg);
  1045. if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
  1046. !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
  1047. Diag(diag::note_module_cache_path)
  1048. << PP.getHeaderSearchInfo().getModuleCachePath();
  1049. }
  1050. }
  1051. void ASTReader::Error(unsigned DiagID,
  1052. StringRef Arg1, StringRef Arg2) const {
  1053. if (Diags.isDiagnosticInFlight())
  1054. Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2);
  1055. else
  1056. Diag(DiagID) << Arg1 << Arg2;
  1057. }
  1058. //===----------------------------------------------------------------------===//
  1059. // Source Manager Deserialization
  1060. //===----------------------------------------------------------------------===//
  1061. /// \brief Read the line table in the source manager block.
  1062. /// \returns true if there was an error.
  1063. bool ASTReader::ParseLineTable(ModuleFile &F,
  1064. const RecordData &Record) {
  1065. unsigned Idx = 0;
  1066. LineTableInfo &LineTable = SourceMgr.getLineTable();
  1067. // Parse the file names
  1068. std::map<int, int> FileIDs;
  1069. for (unsigned I = 0; Record[Idx]; ++I) {
  1070. // Extract the file name
  1071. auto Filename = ReadPath(F, Record, Idx);
  1072. FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
  1073. }
  1074. ++Idx;
  1075. // Parse the line entries
  1076. std::vector<LineEntry> Entries;
  1077. while (Idx < Record.size()) {
  1078. int FID = Record[Idx++];
  1079. assert(FID >= 0 && "Serialized line entries for non-local file.");
  1080. // Remap FileID from 1-based old view.
  1081. FID += F.SLocEntryBaseID - 1;
  1082. // Extract the line entries
  1083. unsigned NumEntries = Record[Idx++];
  1084. assert(NumEntries && "no line entries for file ID");
  1085. Entries.clear();
  1086. Entries.reserve(NumEntries);
  1087. for (unsigned I = 0; I != NumEntries; ++I) {
  1088. unsigned FileOffset = Record[Idx++];
  1089. unsigned LineNo = Record[Idx++];
  1090. int FilenameID = FileIDs[Record[Idx++]];
  1091. SrcMgr::CharacteristicKind FileKind
  1092. = (SrcMgr::CharacteristicKind)Record[Idx++];
  1093. unsigned IncludeOffset = Record[Idx++];
  1094. Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
  1095. FileKind, IncludeOffset));
  1096. }
  1097. LineTable.AddEntry(FileID::get(FID), Entries);
  1098. }
  1099. return false;
  1100. }
  1101. /// \brief Read a source manager block
  1102. bool ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
  1103. using namespace SrcMgr;
  1104. BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
  1105. // Set the source-location entry cursor to the current position in
  1106. // the stream. This cursor will be used to read the contents of the
  1107. // source manager block initially, and then lazily read
  1108. // source-location entries as needed.
  1109. SLocEntryCursor = F.Stream;
  1110. // The stream itself is going to skip over the source manager block.
  1111. if (F.Stream.SkipBlock()) {
  1112. Error("malformed block record in AST file");
  1113. return true;
  1114. }
  1115. // Enter the source manager block.
  1116. if (SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID)) {
  1117. Error("malformed source manager block record in AST file");
  1118. return true;
  1119. }
  1120. RecordData Record;
  1121. while (true) {
  1122. llvm::BitstreamEntry E = SLocEntryCursor.advanceSkippingSubblocks();
  1123. switch (E.Kind) {
  1124. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1125. case llvm::BitstreamEntry::Error:
  1126. Error("malformed block record in AST file");
  1127. return true;
  1128. case llvm::BitstreamEntry::EndBlock:
  1129. return false;
  1130. case llvm::BitstreamEntry::Record:
  1131. // The interesting case.
  1132. break;
  1133. }
  1134. // Read a record.
  1135. Record.clear();
  1136. StringRef Blob;
  1137. switch (SLocEntryCursor.readRecord(E.ID, Record, &Blob)) {
  1138. default: // Default behavior: ignore.
  1139. break;
  1140. case SM_SLOC_FILE_ENTRY:
  1141. case SM_SLOC_BUFFER_ENTRY:
  1142. case SM_SLOC_EXPANSION_ENTRY:
  1143. // Once we hit one of the source location entries, we're done.
  1144. return false;
  1145. }
  1146. }
  1147. }
  1148. /// \brief If a header file is not found at the path that we expect it to be
  1149. /// and the PCH file was moved from its original location, try to resolve the
  1150. /// file by assuming that header+PCH were moved together and the header is in
  1151. /// the same place relative to the PCH.
  1152. static std::string
  1153. resolveFileRelativeToOriginalDir(const std::string &Filename,
  1154. const std::string &OriginalDir,
  1155. const std::string &CurrDir) {
  1156. assert(OriginalDir != CurrDir &&
  1157. "No point trying to resolve the file if the PCH dir didn't change");
  1158. using namespace llvm::sys;
  1159. SmallString<128> filePath(Filename);
  1160. fs::make_absolute(filePath);
  1161. assert(path::is_absolute(OriginalDir));
  1162. SmallString<128> currPCHPath(CurrDir);
  1163. path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
  1164. fileDirE = path::end(path::parent_path(filePath));
  1165. path::const_iterator origDirI = path::begin(OriginalDir),
  1166. origDirE = path::end(OriginalDir);
  1167. // Skip the common path components from filePath and OriginalDir.
  1168. while (fileDirI != fileDirE && origDirI != origDirE &&
  1169. *fileDirI == *origDirI) {
  1170. ++fileDirI;
  1171. ++origDirI;
  1172. }
  1173. for (; origDirI != origDirE; ++origDirI)
  1174. path::append(currPCHPath, "..");
  1175. path::append(currPCHPath, fileDirI, fileDirE);
  1176. path::append(currPCHPath, path::filename(Filename));
  1177. return currPCHPath.str();
  1178. }
  1179. bool ASTReader::ReadSLocEntry(int ID) {
  1180. if (ID == 0)
  1181. return false;
  1182. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1183. Error("source location entry ID out-of-range for AST file");
  1184. return true;
  1185. }
  1186. // Local helper to read the (possibly-compressed) buffer data following the
  1187. // entry record.
  1188. auto ReadBuffer = [this](
  1189. BitstreamCursor &SLocEntryCursor,
  1190. StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
  1191. RecordData Record;
  1192. StringRef Blob;
  1193. unsigned Code = SLocEntryCursor.ReadCode();
  1194. unsigned RecCode = SLocEntryCursor.readRecord(Code, Record, &Blob);
  1195. if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
  1196. if (!llvm::zlib::isAvailable()) {
  1197. Error("zlib is not available");
  1198. return nullptr;
  1199. }
  1200. SmallString<0> Uncompressed;
  1201. if (llvm::Error E =
  1202. llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
  1203. Error("could not decompress embedded file contents: " +
  1204. llvm::toString(std::move(E)));
  1205. return nullptr;
  1206. }
  1207. return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
  1208. } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
  1209. return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
  1210. } else {
  1211. Error("AST record has invalid code");
  1212. return nullptr;
  1213. }
  1214. };
  1215. ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
  1216. F->SLocEntryCursor.JumpToBit(F->SLocEntryOffsets[ID - F->SLocEntryBaseID]);
  1217. BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
  1218. unsigned BaseOffset = F->SLocEntryBaseOffset;
  1219. ++NumSLocEntriesRead;
  1220. llvm::BitstreamEntry Entry = SLocEntryCursor.advance();
  1221. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1222. Error("incorrectly-formatted source location entry in AST file");
  1223. return true;
  1224. }
  1225. RecordData Record;
  1226. StringRef Blob;
  1227. switch (SLocEntryCursor.readRecord(Entry.ID, Record, &Blob)) {
  1228. default:
  1229. Error("incorrectly-formatted source location entry in AST file");
  1230. return true;
  1231. case SM_SLOC_FILE_ENTRY: {
  1232. // We will detect whether a file changed and return 'Failure' for it, but
  1233. // we will also try to fail gracefully by setting up the SLocEntry.
  1234. unsigned InputID = Record[4];
  1235. InputFile IF = getInputFile(*F, InputID);
  1236. const FileEntry *File = IF.getFile();
  1237. bool OverriddenBuffer = IF.isOverridden();
  1238. // Note that we only check if a File was returned. If it was out-of-date
  1239. // we have complained but we will continue creating a FileID to recover
  1240. // gracefully.
  1241. if (!File)
  1242. return true;
  1243. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1244. if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
  1245. // This is the module's main file.
  1246. IncludeLoc = getImportLocation(F);
  1247. }
  1248. SrcMgr::CharacteristicKind
  1249. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1250. FileID FID = SourceMgr.createFileID(File, IncludeLoc, FileCharacter,
  1251. ID, BaseOffset + Record[0]);
  1252. SrcMgr::FileInfo &FileInfo =
  1253. const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
  1254. FileInfo.NumCreatedFIDs = Record[5];
  1255. if (Record[3])
  1256. FileInfo.setHasLineDirectives();
  1257. const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
  1258. unsigned NumFileDecls = Record[7];
  1259. if (NumFileDecls && ContextObj) {
  1260. assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
  1261. FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
  1262. NumFileDecls));
  1263. }
  1264. const SrcMgr::ContentCache *ContentCache
  1265. = SourceMgr.getOrCreateContentCache(File, isSystem(FileCharacter));
  1266. if (OverriddenBuffer && !ContentCache->BufferOverridden &&
  1267. ContentCache->ContentsEntry == ContentCache->OrigEntry &&
  1268. !ContentCache->getRawBuffer()) {
  1269. auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
  1270. if (!Buffer)
  1271. return true;
  1272. SourceMgr.overrideFileContents(File, std::move(Buffer));
  1273. }
  1274. break;
  1275. }
  1276. case SM_SLOC_BUFFER_ENTRY: {
  1277. const char *Name = Blob.data();
  1278. unsigned Offset = Record[0];
  1279. SrcMgr::CharacteristicKind
  1280. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1281. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1282. if (IncludeLoc.isInvalid() && F->isModule()) {
  1283. IncludeLoc = getImportLocation(F);
  1284. }
  1285. auto Buffer = ReadBuffer(SLocEntryCursor, Name);
  1286. if (!Buffer)
  1287. return true;
  1288. SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
  1289. BaseOffset + Offset, IncludeLoc);
  1290. break;
  1291. }
  1292. case SM_SLOC_EXPANSION_ENTRY: {
  1293. SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
  1294. SourceMgr.createExpansionLoc(SpellingLoc,
  1295. ReadSourceLocation(*F, Record[2]),
  1296. ReadSourceLocation(*F, Record[3]),
  1297. Record[4],
  1298. ID,
  1299. BaseOffset + Record[0]);
  1300. break;
  1301. }
  1302. }
  1303. return false;
  1304. }
  1305. std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
  1306. if (ID == 0)
  1307. return std::make_pair(SourceLocation(), "");
  1308. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1309. Error("source location entry ID out-of-range for AST file");
  1310. return std::make_pair(SourceLocation(), "");
  1311. }
  1312. // Find which module file this entry lands in.
  1313. ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
  1314. if (!M->isModule())
  1315. return std::make_pair(SourceLocation(), "");
  1316. // FIXME: Can we map this down to a particular submodule? That would be
  1317. // ideal.
  1318. return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
  1319. }
  1320. /// \brief Find the location where the module F is imported.
  1321. SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
  1322. if (F->ImportLoc.isValid())
  1323. return F->ImportLoc;
  1324. // Otherwise we have a PCH. It's considered to be "imported" at the first
  1325. // location of its includer.
  1326. if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
  1327. // Main file is the importer.
  1328. assert(SourceMgr.getMainFileID().isValid() && "missing main file");
  1329. return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  1330. }
  1331. return F->ImportedBy[0]->FirstLoc;
  1332. }
  1333. /// ReadBlockAbbrevs - Enter a subblock of the specified BlockID with the
  1334. /// specified cursor. Read the abbreviations that are at the top of the block
  1335. /// and then leave the cursor pointing into the block.
  1336. bool ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor, unsigned BlockID) {
  1337. if (Cursor.EnterSubBlock(BlockID))
  1338. return true;
  1339. while (true) {
  1340. uint64_t Offset = Cursor.GetCurrentBitNo();
  1341. unsigned Code = Cursor.ReadCode();
  1342. // We expect all abbrevs to be at the start of the block.
  1343. if (Code != llvm::bitc::DEFINE_ABBREV) {
  1344. Cursor.JumpToBit(Offset);
  1345. return false;
  1346. }
  1347. Cursor.ReadAbbrevRecord();
  1348. }
  1349. }
  1350. Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
  1351. unsigned &Idx) {
  1352. Token Tok;
  1353. Tok.startToken();
  1354. Tok.setLocation(ReadSourceLocation(F, Record, Idx));
  1355. Tok.setLength(Record[Idx++]);
  1356. if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
  1357. Tok.setIdentifierInfo(II);
  1358. Tok.setKind((tok::TokenKind)Record[Idx++]);
  1359. Tok.setFlag((Token::TokenFlags)Record[Idx++]);
  1360. return Tok;
  1361. }
  1362. MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
  1363. BitstreamCursor &Stream = F.MacroCursor;
  1364. // Keep track of where we are in the stream, then jump back there
  1365. // after reading this macro.
  1366. SavedStreamPosition SavedPosition(Stream);
  1367. Stream.JumpToBit(Offset);
  1368. RecordData Record;
  1369. SmallVector<IdentifierInfo*, 16> MacroParams;
  1370. MacroInfo *Macro = nullptr;
  1371. while (true) {
  1372. // Advance to the next record, but if we get to the end of the block, don't
  1373. // pop it (removing all the abbreviations from the cursor) since we want to
  1374. // be able to reseek within the block and read entries.
  1375. unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
  1376. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks(Flags);
  1377. switch (Entry.Kind) {
  1378. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1379. case llvm::BitstreamEntry::Error:
  1380. Error("malformed block record in AST file");
  1381. return Macro;
  1382. case llvm::BitstreamEntry::EndBlock:
  1383. return Macro;
  1384. case llvm::BitstreamEntry::Record:
  1385. // The interesting case.
  1386. break;
  1387. }
  1388. // Read a record.
  1389. Record.clear();
  1390. PreprocessorRecordTypes RecType =
  1391. (PreprocessorRecordTypes)Stream.readRecord(Entry.ID, Record);
  1392. switch (RecType) {
  1393. case PP_MODULE_MACRO:
  1394. case PP_MACRO_DIRECTIVE_HISTORY:
  1395. return Macro;
  1396. case PP_MACRO_OBJECT_LIKE:
  1397. case PP_MACRO_FUNCTION_LIKE: {
  1398. // If we already have a macro, that means that we've hit the end
  1399. // of the definition of the macro we were looking for. We're
  1400. // done.
  1401. if (Macro)
  1402. return Macro;
  1403. unsigned NextIndex = 1; // Skip identifier ID.
  1404. SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
  1405. MacroInfo *MI = PP.AllocateMacroInfo(Loc);
  1406. MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
  1407. MI->setIsUsed(Record[NextIndex++]);
  1408. MI->setUsedForHeaderGuard(Record[NextIndex++]);
  1409. if (RecType == PP_MACRO_FUNCTION_LIKE) {
  1410. // Decode function-like macro info.
  1411. bool isC99VarArgs = Record[NextIndex++];
  1412. bool isGNUVarArgs = Record[NextIndex++];
  1413. bool hasCommaPasting = Record[NextIndex++];
  1414. MacroParams.clear();
  1415. unsigned NumArgs = Record[NextIndex++];
  1416. for (unsigned i = 0; i != NumArgs; ++i)
  1417. MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
  1418. // Install function-like macro info.
  1419. MI->setIsFunctionLike();
  1420. if (isC99VarArgs) MI->setIsC99Varargs();
  1421. if (isGNUVarArgs) MI->setIsGNUVarargs();
  1422. if (hasCommaPasting) MI->setHasCommaPasting();
  1423. MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
  1424. }
  1425. // Remember that we saw this macro last so that we add the tokens that
  1426. // form its body to it.
  1427. Macro = MI;
  1428. if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
  1429. Record[NextIndex]) {
  1430. // We have a macro definition. Register the association
  1431. PreprocessedEntityID
  1432. GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
  1433. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  1434. PreprocessingRecord::PPEntityID PPID =
  1435. PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
  1436. MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
  1437. PPRec.getPreprocessedEntity(PPID));
  1438. if (PPDef)
  1439. PPRec.RegisterMacroDefinition(Macro, PPDef);
  1440. }
  1441. ++NumMacrosRead;
  1442. break;
  1443. }
  1444. case PP_TOKEN: {
  1445. // If we see a TOKEN before a PP_MACRO_*, then the file is
  1446. // erroneous, just pretend we didn't see this.
  1447. if (!Macro) break;
  1448. unsigned Idx = 0;
  1449. Token Tok = ReadToken(F, Record, Idx);
  1450. Macro->AddTokenToBody(Tok);
  1451. break;
  1452. }
  1453. }
  1454. }
  1455. }
  1456. PreprocessedEntityID
  1457. ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
  1458. unsigned LocalID) const {
  1459. if (!M.ModuleOffsetMap.empty())
  1460. ReadModuleOffsetMap(M);
  1461. ContinuousRangeMap<uint32_t, int, 2>::const_iterator
  1462. I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
  1463. assert(I != M.PreprocessedEntityRemap.end()
  1464. && "Invalid index into preprocessed entity index remap");
  1465. return LocalID + I->second;
  1466. }
  1467. unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
  1468. return llvm::hash_combine(ikey.Size, ikey.ModTime);
  1469. }
  1470. HeaderFileInfoTrait::internal_key_type
  1471. HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
  1472. internal_key_type ikey = {FE->getSize(),
  1473. M.HasTimestamps ? FE->getModificationTime() : 0,
  1474. FE->getName(), /*Imported*/ false};
  1475. return ikey;
  1476. }
  1477. bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
  1478. if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
  1479. return false;
  1480. if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
  1481. return true;
  1482. // Determine whether the actual files are equivalent.
  1483. FileManager &FileMgr = Reader.getFileManager();
  1484. auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
  1485. if (!Key.Imported)
  1486. return FileMgr.getFile(Key.Filename);
  1487. std::string Resolved = Key.Filename;
  1488. Reader.ResolveImportedPath(M, Resolved);
  1489. return FileMgr.getFile(Resolved);
  1490. };
  1491. const FileEntry *FEA = GetFile(a);
  1492. const FileEntry *FEB = GetFile(b);
  1493. return FEA && FEA == FEB;
  1494. }
  1495. std::pair<unsigned, unsigned>
  1496. HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
  1497. using namespace llvm::support;
  1498. unsigned KeyLen = (unsigned) endian::readNext<uint16_t, little, unaligned>(d);
  1499. unsigned DataLen = (unsigned) *d++;
  1500. return std::make_pair(KeyLen, DataLen);
  1501. }
  1502. HeaderFileInfoTrait::internal_key_type
  1503. HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
  1504. using namespace llvm::support;
  1505. internal_key_type ikey;
  1506. ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
  1507. ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
  1508. ikey.Filename = (const char *)d;
  1509. ikey.Imported = true;
  1510. return ikey;
  1511. }
  1512. HeaderFileInfoTrait::data_type
  1513. HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
  1514. unsigned DataLen) {
  1515. using namespace llvm::support;
  1516. const unsigned char *End = d + DataLen;
  1517. HeaderFileInfo HFI;
  1518. unsigned Flags = *d++;
  1519. // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
  1520. HFI.isImport |= (Flags >> 5) & 0x01;
  1521. HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
  1522. HFI.DirInfo = (Flags >> 1) & 0x07;
  1523. HFI.IndexHeaderMapHeader = Flags & 0x01;
  1524. // FIXME: Find a better way to handle this. Maybe just store a
  1525. // "has been included" flag?
  1526. HFI.NumIncludes = std::max(endian::readNext<uint16_t, little, unaligned>(d),
  1527. HFI.NumIncludes);
  1528. HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
  1529. M, endian::readNext<uint32_t, little, unaligned>(d));
  1530. if (unsigned FrameworkOffset =
  1531. endian::readNext<uint32_t, little, unaligned>(d)) {
  1532. // The framework offset is 1 greater than the actual offset,
  1533. // since 0 is used as an indicator for "no framework name".
  1534. StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
  1535. HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
  1536. }
  1537. assert((End - d) % 4 == 0 &&
  1538. "Wrong data length in HeaderFileInfo deserialization");
  1539. while (d != End) {
  1540. uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
  1541. auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
  1542. LocalSMID >>= 2;
  1543. // This header is part of a module. Associate it with the module to enable
  1544. // implicit module import.
  1545. SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
  1546. Module *Mod = Reader.getSubmodule(GlobalSMID);
  1547. FileManager &FileMgr = Reader.getFileManager();
  1548. ModuleMap &ModMap =
  1549. Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1550. std::string Filename = key.Filename;
  1551. if (key.Imported)
  1552. Reader.ResolveImportedPath(M, Filename);
  1553. // FIXME: This is not always the right filename-as-written, but we're not
  1554. // going to use this information to rebuild the module, so it doesn't make
  1555. // a lot of difference.
  1556. Module::Header H = { key.Filename, FileMgr.getFile(Filename) };
  1557. ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
  1558. HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
  1559. }
  1560. // This HeaderFileInfo was externally loaded.
  1561. HFI.External = true;
  1562. HFI.IsValid = true;
  1563. return HFI;
  1564. }
  1565. void ASTReader::addPendingMacro(IdentifierInfo *II,
  1566. ModuleFile *M,
  1567. uint64_t MacroDirectivesOffset) {
  1568. assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
  1569. PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
  1570. }
  1571. void ASTReader::ReadDefinedMacros() {
  1572. // Note that we are loading defined macros.
  1573. Deserializing Macros(this);
  1574. for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
  1575. BitstreamCursor &MacroCursor = I.MacroCursor;
  1576. // If there was no preprocessor block, skip this file.
  1577. if (MacroCursor.getBitcodeBytes().empty())
  1578. continue;
  1579. BitstreamCursor Cursor = MacroCursor;
  1580. Cursor.JumpToBit(I.MacroStartOffset);
  1581. RecordData Record;
  1582. while (true) {
  1583. llvm::BitstreamEntry E = Cursor.advanceSkippingSubblocks();
  1584. switch (E.Kind) {
  1585. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1586. case llvm::BitstreamEntry::Error:
  1587. Error("malformed block record in AST file");
  1588. return;
  1589. case llvm::BitstreamEntry::EndBlock:
  1590. goto NextCursor;
  1591. case llvm::BitstreamEntry::Record:
  1592. Record.clear();
  1593. switch (Cursor.readRecord(E.ID, Record)) {
  1594. default: // Default behavior: ignore.
  1595. break;
  1596. case PP_MACRO_OBJECT_LIKE:
  1597. case PP_MACRO_FUNCTION_LIKE: {
  1598. IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
  1599. if (II->isOutOfDate())
  1600. updateOutOfDateIdentifier(*II);
  1601. break;
  1602. }
  1603. case PP_TOKEN:
  1604. // Ignore tokens.
  1605. break;
  1606. }
  1607. break;
  1608. }
  1609. }
  1610. NextCursor: ;
  1611. }
  1612. }
  1613. namespace {
  1614. /// \brief Visitor class used to look up identifirs in an AST file.
  1615. class IdentifierLookupVisitor {
  1616. StringRef Name;
  1617. unsigned NameHash;
  1618. unsigned PriorGeneration;
  1619. unsigned &NumIdentifierLookups;
  1620. unsigned &NumIdentifierLookupHits;
  1621. IdentifierInfo *Found = nullptr;
  1622. public:
  1623. IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
  1624. unsigned &NumIdentifierLookups,
  1625. unsigned &NumIdentifierLookupHits)
  1626. : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
  1627. PriorGeneration(PriorGeneration),
  1628. NumIdentifierLookups(NumIdentifierLookups),
  1629. NumIdentifierLookupHits(NumIdentifierLookupHits) {}
  1630. bool operator()(ModuleFile &M) {
  1631. // If we've already searched this module file, skip it now.
  1632. if (M.Generation <= PriorGeneration)
  1633. return true;
  1634. ASTIdentifierLookupTable *IdTable
  1635. = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
  1636. if (!IdTable)
  1637. return false;
  1638. ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
  1639. Found);
  1640. ++NumIdentifierLookups;
  1641. ASTIdentifierLookupTable::iterator Pos =
  1642. IdTable->find_hashed(Name, NameHash, &Trait);
  1643. if (Pos == IdTable->end())
  1644. return false;
  1645. // Dereferencing the iterator has the effect of building the
  1646. // IdentifierInfo node and populating it with the various
  1647. // declarations it needs.
  1648. ++NumIdentifierLookupHits;
  1649. Found = *Pos;
  1650. return true;
  1651. }
  1652. // \brief Retrieve the identifier info found within the module
  1653. // files.
  1654. IdentifierInfo *getIdentifierInfo() const { return Found; }
  1655. };
  1656. } // namespace
  1657. void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
  1658. // Note that we are loading an identifier.
  1659. Deserializing AnIdentifier(this);
  1660. unsigned PriorGeneration = 0;
  1661. if (getContext().getLangOpts().Modules)
  1662. PriorGeneration = IdentifierGeneration[&II];
  1663. // If there is a global index, look there first to determine which modules
  1664. // provably do not have any results for this identifier.
  1665. GlobalModuleIndex::HitSet Hits;
  1666. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  1667. if (!loadGlobalIndex()) {
  1668. if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
  1669. HitsPtr = &Hits;
  1670. }
  1671. }
  1672. IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
  1673. NumIdentifierLookups,
  1674. NumIdentifierLookupHits);
  1675. ModuleMgr.visit(Visitor, HitsPtr);
  1676. markIdentifierUpToDate(&II);
  1677. }
  1678. void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
  1679. if (!II)
  1680. return;
  1681. II->setOutOfDate(false);
  1682. // Update the generation for this identifier.
  1683. if (getContext().getLangOpts().Modules)
  1684. IdentifierGeneration[II] = getGeneration();
  1685. }
  1686. void ASTReader::resolvePendingMacro(IdentifierInfo *II,
  1687. const PendingMacroInfo &PMInfo) {
  1688. ModuleFile &M = *PMInfo.M;
  1689. BitstreamCursor &Cursor = M.MacroCursor;
  1690. SavedStreamPosition SavedPosition(Cursor);
  1691. Cursor.JumpToBit(PMInfo.MacroDirectivesOffset);
  1692. struct ModuleMacroRecord {
  1693. SubmoduleID SubModID;
  1694. MacroInfo *MI;
  1695. SmallVector<SubmoduleID, 8> Overrides;
  1696. };
  1697. llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
  1698. // We expect to see a sequence of PP_MODULE_MACRO records listing exported
  1699. // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
  1700. // macro histroy.
  1701. RecordData Record;
  1702. while (true) {
  1703. llvm::BitstreamEntry Entry =
  1704. Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  1705. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1706. Error("malformed block record in AST file");
  1707. return;
  1708. }
  1709. Record.clear();
  1710. switch ((PreprocessorRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
  1711. case PP_MACRO_DIRECTIVE_HISTORY:
  1712. break;
  1713. case PP_MODULE_MACRO: {
  1714. ModuleMacros.push_back(ModuleMacroRecord());
  1715. auto &Info = ModuleMacros.back();
  1716. Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
  1717. Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
  1718. for (int I = 2, N = Record.size(); I != N; ++I)
  1719. Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
  1720. continue;
  1721. }
  1722. default:
  1723. Error("malformed block record in AST file");
  1724. return;
  1725. }
  1726. // We found the macro directive history; that's the last record
  1727. // for this macro.
  1728. break;
  1729. }
  1730. // Module macros are listed in reverse dependency order.
  1731. {
  1732. std::reverse(ModuleMacros.begin(), ModuleMacros.end());
  1733. llvm::SmallVector<ModuleMacro*, 8> Overrides;
  1734. for (auto &MMR : ModuleMacros) {
  1735. Overrides.clear();
  1736. for (unsigned ModID : MMR.Overrides) {
  1737. Module *Mod = getSubmodule(ModID);
  1738. auto *Macro = PP.getModuleMacro(Mod, II);
  1739. assert(Macro && "missing definition for overridden macro");
  1740. Overrides.push_back(Macro);
  1741. }
  1742. bool Inserted = false;
  1743. Module *Owner = getSubmodule(MMR.SubModID);
  1744. PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
  1745. }
  1746. }
  1747. // Don't read the directive history for a module; we don't have anywhere
  1748. // to put it.
  1749. if (M.isModule())
  1750. return;
  1751. // Deserialize the macro directives history in reverse source-order.
  1752. MacroDirective *Latest = nullptr, *Earliest = nullptr;
  1753. unsigned Idx = 0, N = Record.size();
  1754. while (Idx < N) {
  1755. MacroDirective *MD = nullptr;
  1756. SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
  1757. MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
  1758. switch (K) {
  1759. case MacroDirective::MD_Define: {
  1760. MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
  1761. MD = PP.AllocateDefMacroDirective(MI, Loc);
  1762. break;
  1763. }
  1764. case MacroDirective::MD_Undefine:
  1765. MD = PP.AllocateUndefMacroDirective(Loc);
  1766. break;
  1767. case MacroDirective::MD_Visibility:
  1768. bool isPublic = Record[Idx++];
  1769. MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
  1770. break;
  1771. }
  1772. if (!Latest)
  1773. Latest = MD;
  1774. if (Earliest)
  1775. Earliest->setPrevious(MD);
  1776. Earliest = MD;
  1777. }
  1778. if (Latest)
  1779. PP.setLoadedMacroDirective(II, Earliest, Latest);
  1780. }
  1781. ASTReader::InputFileInfo
  1782. ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
  1783. // Go find this input file.
  1784. BitstreamCursor &Cursor = F.InputFilesCursor;
  1785. SavedStreamPosition SavedPosition(Cursor);
  1786. Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
  1787. unsigned Code = Cursor.ReadCode();
  1788. RecordData Record;
  1789. StringRef Blob;
  1790. unsigned Result = Cursor.readRecord(Code, Record, &Blob);
  1791. assert(static_cast<InputFileRecordTypes>(Result) == INPUT_FILE &&
  1792. "invalid record type for input file");
  1793. (void)Result;
  1794. assert(Record[0] == ID && "Bogus stored ID or offset");
  1795. InputFileInfo R;
  1796. R.StoredSize = static_cast<off_t>(Record[1]);
  1797. R.StoredTime = static_cast<time_t>(Record[2]);
  1798. R.Overridden = static_cast<bool>(Record[3]);
  1799. R.Transient = static_cast<bool>(Record[4]);
  1800. R.TopLevelModuleMap = static_cast<bool>(Record[5]);
  1801. R.Filename = Blob;
  1802. ResolveImportedPath(F, R.Filename);
  1803. return R;
  1804. }
  1805. static unsigned moduleKindForDiagnostic(ModuleKind Kind);
  1806. InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
  1807. // If this ID is bogus, just return an empty input file.
  1808. if (ID == 0 || ID > F.InputFilesLoaded.size())
  1809. return InputFile();
  1810. // If we've already loaded this input file, return it.
  1811. if (F.InputFilesLoaded[ID-1].getFile())
  1812. return F.InputFilesLoaded[ID-1];
  1813. if (F.InputFilesLoaded[ID-1].isNotFound())
  1814. return InputFile();
  1815. // Go find this input file.
  1816. BitstreamCursor &Cursor = F.InputFilesCursor;
  1817. SavedStreamPosition SavedPosition(Cursor);
  1818. Cursor.JumpToBit(F.InputFileOffsets[ID-1]);
  1819. InputFileInfo FI = readInputFileInfo(F, ID);
  1820. off_t StoredSize = FI.StoredSize;
  1821. time_t StoredTime = FI.StoredTime;
  1822. bool Overridden = FI.Overridden;
  1823. bool Transient = FI.Transient;
  1824. StringRef Filename = FI.Filename;
  1825. const FileEntry *File = FileMgr.getFile(Filename, /*OpenFile=*/false);
  1826. // If we didn't find the file, resolve it relative to the
  1827. // original directory from which this AST file was created.
  1828. if (File == nullptr && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
  1829. F.OriginalDir != F.BaseDirectory) {
  1830. std::string Resolved = resolveFileRelativeToOriginalDir(
  1831. Filename, F.OriginalDir, F.BaseDirectory);
  1832. if (!Resolved.empty())
  1833. File = FileMgr.getFile(Resolved);
  1834. }
  1835. // For an overridden file, create a virtual file with the stored
  1836. // size/timestamp.
  1837. if ((Overridden || Transient) && File == nullptr)
  1838. File = FileMgr.getVirtualFile(Filename, StoredSize, StoredTime);
  1839. if (File == nullptr) {
  1840. if (Complain) {
  1841. std::string ErrorStr = "could not find file '";
  1842. ErrorStr += Filename;
  1843. ErrorStr += "' referenced by AST file '";
  1844. ErrorStr += F.FileName;
  1845. ErrorStr += "'";
  1846. Error(ErrorStr);
  1847. }
  1848. // Record that we didn't find the file.
  1849. F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
  1850. return InputFile();
  1851. }
  1852. // Check if there was a request to override the contents of the file
  1853. // that was part of the precompiled header. Overridding such a file
  1854. // can lead to problems when lexing using the source locations from the
  1855. // PCH.
  1856. SourceManager &SM = getSourceManager();
  1857. // FIXME: Reject if the overrides are different.
  1858. if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
  1859. if (Complain)
  1860. Error(diag::err_fe_pch_file_overridden, Filename);
  1861. // After emitting the diagnostic, recover by disabling the override so
  1862. // that the original file will be used.
  1863. //
  1864. // FIXME: This recovery is just as broken as the original state; there may
  1865. // be another precompiled module that's using the overridden contents, or
  1866. // we might be half way through parsing it. Instead, we should treat the
  1867. // overridden contents as belonging to a separate FileEntry.
  1868. SM.disableFileContentsOverride(File);
  1869. // The FileEntry is a virtual file entry with the size of the contents
  1870. // that would override the original contents. Set it to the original's
  1871. // size/time.
  1872. FileMgr.modifyFileEntry(const_cast<FileEntry*>(File),
  1873. StoredSize, StoredTime);
  1874. }
  1875. bool IsOutOfDate = false;
  1876. // For an overridden file, there is nothing to validate.
  1877. if (!Overridden && //
  1878. (StoredSize != File->getSize() ||
  1879. (StoredTime && StoredTime != File->getModificationTime() &&
  1880. !DisableValidation)
  1881. )) {
  1882. if (Complain) {
  1883. // Build a list of the PCH imports that got us here (in reverse).
  1884. SmallVector<ModuleFile *, 4> ImportStack(1, &F);
  1885. while (!ImportStack.back()->ImportedBy.empty())
  1886. ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
  1887. // The top-level PCH is stale.
  1888. StringRef TopLevelPCHName(ImportStack.back()->FileName);
  1889. unsigned DiagnosticKind = moduleKindForDiagnostic(ImportStack.back()->Kind);
  1890. if (DiagnosticKind == 0)
  1891. Error(diag::err_fe_pch_file_modified, Filename, TopLevelPCHName);
  1892. else if (DiagnosticKind == 1)
  1893. Error(diag::err_fe_module_file_modified, Filename, TopLevelPCHName);
  1894. else
  1895. Error(diag::err_fe_ast_file_modified, Filename, TopLevelPCHName);
  1896. // Print the import stack.
  1897. if (ImportStack.size() > 1 && !Diags.isDiagnosticInFlight()) {
  1898. Diag(diag::note_pch_required_by)
  1899. << Filename << ImportStack[0]->FileName;
  1900. for (unsigned I = 1; I < ImportStack.size(); ++I)
  1901. Diag(diag::note_pch_required_by)
  1902. << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
  1903. }
  1904. if (!Diags.isDiagnosticInFlight())
  1905. Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
  1906. }
  1907. IsOutOfDate = true;
  1908. }
  1909. // FIXME: If the file is overridden and we've already opened it,
  1910. // issue an error (or split it into a separate FileEntry).
  1911. InputFile IF = InputFile(File, Overridden || Transient, IsOutOfDate);
  1912. // Note that we've loaded this input file.
  1913. F.InputFilesLoaded[ID-1] = IF;
  1914. return IF;
  1915. }
  1916. /// \brief If we are loading a relocatable PCH or module file, and the filename
  1917. /// is not an absolute path, add the system or module root to the beginning of
  1918. /// the file name.
  1919. void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
  1920. // Resolve relative to the base directory, if we have one.
  1921. if (!M.BaseDirectory.empty())
  1922. return ResolveImportedPath(Filename, M.BaseDirectory);
  1923. }
  1924. void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
  1925. if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
  1926. return;
  1927. SmallString<128> Buffer;
  1928. llvm::sys::path::append(Buffer, Prefix, Filename);
  1929. Filename.assign(Buffer.begin(), Buffer.end());
  1930. }
  1931. static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
  1932. switch (ARR) {
  1933. case ASTReader::Failure: return true;
  1934. case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
  1935. case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
  1936. case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
  1937. case ASTReader::ConfigurationMismatch:
  1938. return !(Caps & ASTReader::ARR_ConfigurationMismatch);
  1939. case ASTReader::HadErrors: return true;
  1940. case ASTReader::Success: return false;
  1941. }
  1942. llvm_unreachable("unknown ASTReadResult");
  1943. }
  1944. ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
  1945. BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
  1946. bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
  1947. std::string &SuggestedPredefines) {
  1948. if (Stream.EnterSubBlock(OPTIONS_BLOCK_ID))
  1949. return Failure;
  1950. // Read all of the records in the options block.
  1951. RecordData Record;
  1952. ASTReadResult Result = Success;
  1953. while (true) {
  1954. llvm::BitstreamEntry Entry = Stream.advance();
  1955. switch (Entry.Kind) {
  1956. case llvm::BitstreamEntry::Error:
  1957. case llvm::BitstreamEntry::SubBlock:
  1958. return Failure;
  1959. case llvm::BitstreamEntry::EndBlock:
  1960. return Result;
  1961. case llvm::BitstreamEntry::Record:
  1962. // The interesting case.
  1963. break;
  1964. }
  1965. // Read and process a record.
  1966. Record.clear();
  1967. switch ((OptionsRecordTypes)Stream.readRecord(Entry.ID, Record)) {
  1968. case LANGUAGE_OPTIONS: {
  1969. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  1970. if (ParseLanguageOptions(Record, Complain, Listener,
  1971. AllowCompatibleConfigurationMismatch))
  1972. Result = ConfigurationMismatch;
  1973. break;
  1974. }
  1975. case TARGET_OPTIONS: {
  1976. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  1977. if (ParseTargetOptions(Record, Complain, Listener,
  1978. AllowCompatibleConfigurationMismatch))
  1979. Result = ConfigurationMismatch;
  1980. break;
  1981. }
  1982. case FILE_SYSTEM_OPTIONS: {
  1983. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  1984. if (!AllowCompatibleConfigurationMismatch &&
  1985. ParseFileSystemOptions(Record, Complain, Listener))
  1986. Result = ConfigurationMismatch;
  1987. break;
  1988. }
  1989. case HEADER_SEARCH_OPTIONS: {
  1990. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  1991. if (!AllowCompatibleConfigurationMismatch &&
  1992. ParseHeaderSearchOptions(Record, Complain, Listener))
  1993. Result = ConfigurationMismatch;
  1994. break;
  1995. }
  1996. case PREPROCESSOR_OPTIONS:
  1997. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  1998. if (!AllowCompatibleConfigurationMismatch &&
  1999. ParsePreprocessorOptions(Record, Complain, Listener,
  2000. SuggestedPredefines))
  2001. Result = ConfigurationMismatch;
  2002. break;
  2003. }
  2004. }
  2005. }
  2006. ASTReader::ASTReadResult
  2007. ASTReader::ReadControlBlock(ModuleFile &F,
  2008. SmallVectorImpl<ImportedModule> &Loaded,
  2009. const ModuleFile *ImportedBy,
  2010. unsigned ClientLoadCapabilities) {
  2011. BitstreamCursor &Stream = F.Stream;
  2012. ASTReadResult Result = Success;
  2013. if (Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
  2014. Error("malformed block record in AST file");
  2015. return Failure;
  2016. }
  2017. // Lambda to read the unhashed control block the first time it's called.
  2018. //
  2019. // For PCM files, the unhashed control block cannot be read until after the
  2020. // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
  2021. // need to look ahead before reading the IMPORTS record. For consistency,
  2022. // this block is always read somehow (see BitstreamEntry::EndBlock).
  2023. bool HasReadUnhashedControlBlock = false;
  2024. auto readUnhashedControlBlockOnce = [&]() {
  2025. if (!HasReadUnhashedControlBlock) {
  2026. HasReadUnhashedControlBlock = true;
  2027. if (ASTReadResult Result =
  2028. readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
  2029. return Result;
  2030. }
  2031. return Success;
  2032. };
  2033. // Read all of the records and blocks in the control block.
  2034. RecordData Record;
  2035. unsigned NumInputs = 0;
  2036. unsigned NumUserInputs = 0;
  2037. while (true) {
  2038. llvm::BitstreamEntry Entry = Stream.advance();
  2039. switch (Entry.Kind) {
  2040. case llvm::BitstreamEntry::Error:
  2041. Error("malformed block record in AST file");
  2042. return Failure;
  2043. case llvm::BitstreamEntry::EndBlock: {
  2044. // Validate the module before returning. This call catches an AST with
  2045. // no module name and no imports.
  2046. if (ASTReadResult Result = readUnhashedControlBlockOnce())
  2047. return Result;
  2048. // Validate input files.
  2049. const HeaderSearchOptions &HSOpts =
  2050. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  2051. // All user input files reside at the index range [0, NumUserInputs), and
  2052. // system input files reside at [NumUserInputs, NumInputs). For explicitly
  2053. // loaded module files, ignore missing inputs.
  2054. if (!DisableValidation && F.Kind != MK_ExplicitModule &&
  2055. F.Kind != MK_PrebuiltModule) {
  2056. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
  2057. // If we are reading a module, we will create a verification timestamp,
  2058. // so we verify all input files. Otherwise, verify only user input
  2059. // files.
  2060. unsigned N = NumUserInputs;
  2061. if (ValidateSystemInputs ||
  2062. (HSOpts.ModulesValidateOncePerBuildSession &&
  2063. F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
  2064. F.Kind == MK_ImplicitModule))
  2065. N = NumInputs;
  2066. for (unsigned I = 0; I < N; ++I) {
  2067. InputFile IF = getInputFile(F, I+1, Complain);
  2068. if (!IF.getFile() || IF.isOutOfDate())
  2069. return OutOfDate;
  2070. }
  2071. }
  2072. if (Listener)
  2073. Listener->visitModuleFile(F.FileName, F.Kind);
  2074. if (Listener && Listener->needsInputFileVisitation()) {
  2075. unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
  2076. : NumUserInputs;
  2077. for (unsigned I = 0; I < N; ++I) {
  2078. bool IsSystem = I >= NumUserInputs;
  2079. InputFileInfo FI = readInputFileInfo(F, I+1);
  2080. Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
  2081. F.Kind == MK_ExplicitModule ||
  2082. F.Kind == MK_PrebuiltModule);
  2083. }
  2084. }
  2085. return Result;
  2086. }
  2087. case llvm::BitstreamEntry::SubBlock:
  2088. switch (Entry.ID) {
  2089. case INPUT_FILES_BLOCK_ID:
  2090. F.InputFilesCursor = Stream;
  2091. if (Stream.SkipBlock() || // Skip with the main cursor
  2092. // Read the abbreviations
  2093. ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
  2094. Error("malformed block record in AST file");
  2095. return Failure;
  2096. }
  2097. continue;
  2098. case OPTIONS_BLOCK_ID:
  2099. // If we're reading the first module for this group, check its options
  2100. // are compatible with ours. For modules it imports, no further checking
  2101. // is required, because we checked them when we built it.
  2102. if (Listener && !ImportedBy) {
  2103. // Should we allow the configuration of the module file to differ from
  2104. // the configuration of the current translation unit in a compatible
  2105. // way?
  2106. //
  2107. // FIXME: Allow this for files explicitly specified with -include-pch.
  2108. bool AllowCompatibleConfigurationMismatch =
  2109. F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
  2110. Result = ReadOptionsBlock(Stream, ClientLoadCapabilities,
  2111. AllowCompatibleConfigurationMismatch,
  2112. *Listener, SuggestedPredefines);
  2113. if (Result == Failure) {
  2114. Error("malformed block record in AST file");
  2115. return Result;
  2116. }
  2117. if (DisableValidation ||
  2118. (AllowConfigurationMismatch && Result == ConfigurationMismatch))
  2119. Result = Success;
  2120. // If we can't load the module, exit early since we likely
  2121. // will rebuild the module anyway. The stream may be in the
  2122. // middle of a block.
  2123. if (Result != Success)
  2124. return Result;
  2125. } else if (Stream.SkipBlock()) {
  2126. Error("malformed block record in AST file");
  2127. return Failure;
  2128. }
  2129. continue;
  2130. default:
  2131. if (Stream.SkipBlock()) {
  2132. Error("malformed block record in AST file");
  2133. return Failure;
  2134. }
  2135. continue;
  2136. }
  2137. case llvm::BitstreamEntry::Record:
  2138. // The interesting case.
  2139. break;
  2140. }
  2141. // Read and process a record.
  2142. Record.clear();
  2143. StringRef Blob;
  2144. switch ((ControlRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob)) {
  2145. case METADATA: {
  2146. if (Record[0] != VERSION_MAJOR && !DisableValidation) {
  2147. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  2148. Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
  2149. : diag::err_pch_version_too_new);
  2150. return VersionMismatch;
  2151. }
  2152. bool hasErrors = Record[6];
  2153. if (hasErrors && !DisableValidation && !AllowASTWithCompilerErrors) {
  2154. Diag(diag::err_pch_with_compiler_errors);
  2155. return HadErrors;
  2156. }
  2157. if (hasErrors) {
  2158. Diags.ErrorOccurred = true;
  2159. Diags.UncompilableErrorOccurred = true;
  2160. Diags.UnrecoverableErrorOccurred = true;
  2161. }
  2162. F.RelocatablePCH = Record[4];
  2163. // Relative paths in a relocatable PCH are relative to our sysroot.
  2164. if (F.RelocatablePCH)
  2165. F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
  2166. F.HasTimestamps = Record[5];
  2167. const std::string &CurBranch = getClangFullRepositoryVersion();
  2168. StringRef ASTBranch = Blob;
  2169. if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
  2170. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  2171. Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
  2172. return VersionMismatch;
  2173. }
  2174. break;
  2175. }
  2176. case IMPORTS: {
  2177. // Validate the AST before processing any imports (otherwise, untangling
  2178. // them can be error-prone and expensive). A module will have a name and
  2179. // will already have been validated, but this catches the PCH case.
  2180. if (ASTReadResult Result = readUnhashedControlBlockOnce())
  2181. return Result;
  2182. // Load each of the imported PCH files.
  2183. unsigned Idx = 0, N = Record.size();
  2184. while (Idx < N) {
  2185. // Read information about the AST file.
  2186. ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
  2187. // The import location will be the local one for now; we will adjust
  2188. // all import locations of module imports after the global source
  2189. // location info are setup, in ReadAST.
  2190. SourceLocation ImportLoc =
  2191. ReadUntranslatedSourceLocation(Record[Idx++]);
  2192. off_t StoredSize = (off_t)Record[Idx++];
  2193. time_t StoredModTime = (time_t)Record[Idx++];
  2194. ASTFileSignature StoredSignature = {
  2195. {{(uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
  2196. (uint32_t)Record[Idx++], (uint32_t)Record[Idx++],
  2197. (uint32_t)Record[Idx++]}}};
  2198. std::string ImportedName = ReadString(Record, Idx);
  2199. std::string ImportedFile;
  2200. // For prebuilt and explicit modules first consult the file map for
  2201. // an override. Note that here we don't search prebuilt module
  2202. // directories, only the explicit name to file mappings. Also, we will
  2203. // still verify the size/signature making sure it is essentially the
  2204. // same file but perhaps in a different location.
  2205. if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
  2206. ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
  2207. ImportedName, /*FileMapOnly*/ true);
  2208. if (ImportedFile.empty())
  2209. ImportedFile = ReadPath(F, Record, Idx);
  2210. else
  2211. SkipPath(Record, Idx);
  2212. // If our client can't cope with us being out of date, we can't cope with
  2213. // our dependency being missing.
  2214. unsigned Capabilities = ClientLoadCapabilities;
  2215. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2216. Capabilities &= ~ARR_Missing;
  2217. // Load the AST file.
  2218. auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
  2219. Loaded, StoredSize, StoredModTime,
  2220. StoredSignature, Capabilities);
  2221. // If we diagnosed a problem, produce a backtrace.
  2222. if (isDiagnosedResult(Result, Capabilities))
  2223. Diag(diag::note_module_file_imported_by)
  2224. << F.FileName << !F.ModuleName.empty() << F.ModuleName;
  2225. switch (Result) {
  2226. case Failure: return Failure;
  2227. // If we have to ignore the dependency, we'll have to ignore this too.
  2228. case Missing:
  2229. case OutOfDate: return OutOfDate;
  2230. case VersionMismatch: return VersionMismatch;
  2231. case ConfigurationMismatch: return ConfigurationMismatch;
  2232. case HadErrors: return HadErrors;
  2233. case Success: break;
  2234. }
  2235. }
  2236. break;
  2237. }
  2238. case ORIGINAL_FILE:
  2239. F.OriginalSourceFileID = FileID::get(Record[0]);
  2240. F.ActualOriginalSourceFileName = Blob;
  2241. F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
  2242. ResolveImportedPath(F, F.OriginalSourceFileName);
  2243. break;
  2244. case ORIGINAL_FILE_ID:
  2245. F.OriginalSourceFileID = FileID::get(Record[0]);
  2246. break;
  2247. case ORIGINAL_PCH_DIR:
  2248. F.OriginalDir = Blob;
  2249. break;
  2250. case MODULE_NAME:
  2251. F.ModuleName = Blob;
  2252. if (Listener)
  2253. Listener->ReadModuleName(F.ModuleName);
  2254. // Validate the AST as soon as we have a name so we can exit early on
  2255. // failure.
  2256. if (ASTReadResult Result = readUnhashedControlBlockOnce())
  2257. return Result;
  2258. break;
  2259. case MODULE_DIRECTORY: {
  2260. assert(!F.ModuleName.empty() &&
  2261. "MODULE_DIRECTORY found before MODULE_NAME");
  2262. // If we've already loaded a module map file covering this module, we may
  2263. // have a better path for it (relative to the current build).
  2264. Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
  2265. if (M && M->Directory) {
  2266. // If we're implicitly loading a module, the base directory can't
  2267. // change between the build and use.
  2268. if (F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
  2269. const DirectoryEntry *BuildDir =
  2270. PP.getFileManager().getDirectory(Blob);
  2271. if (!BuildDir || BuildDir != M->Directory) {
  2272. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2273. Diag(diag::err_imported_module_relocated)
  2274. << F.ModuleName << Blob << M->Directory->getName();
  2275. return OutOfDate;
  2276. }
  2277. }
  2278. F.BaseDirectory = M->Directory->getName();
  2279. } else {
  2280. F.BaseDirectory = Blob;
  2281. }
  2282. break;
  2283. }
  2284. case MODULE_MAP_FILE:
  2285. if (ASTReadResult Result =
  2286. ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
  2287. return Result;
  2288. break;
  2289. case INPUT_FILE_OFFSETS:
  2290. NumInputs = Record[0];
  2291. NumUserInputs = Record[1];
  2292. F.InputFileOffsets =
  2293. (const llvm::support::unaligned_uint64_t *)Blob.data();
  2294. F.InputFilesLoaded.resize(NumInputs);
  2295. F.NumUserInputFiles = NumUserInputs;
  2296. break;
  2297. }
  2298. }
  2299. }
  2300. ASTReader::ASTReadResult
  2301. ASTReader::ReadASTBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
  2302. BitstreamCursor &Stream = F.Stream;
  2303. if (Stream.EnterSubBlock(AST_BLOCK_ID)) {
  2304. Error("malformed block record in AST file");
  2305. return Failure;
  2306. }
  2307. // Read all of the records and blocks for the AST file.
  2308. RecordData Record;
  2309. while (true) {
  2310. llvm::BitstreamEntry Entry = Stream.advance();
  2311. switch (Entry.Kind) {
  2312. case llvm::BitstreamEntry::Error:
  2313. Error("error at end of module block in AST file");
  2314. return Failure;
  2315. case llvm::BitstreamEntry::EndBlock:
  2316. // Outside of C++, we do not store a lookup map for the translation unit.
  2317. // Instead, mark it as needing a lookup map to be built if this module
  2318. // contains any declarations lexically within it (which it always does!).
  2319. // This usually has no cost, since we very rarely need the lookup map for
  2320. // the translation unit outside C++.
  2321. if (ASTContext *Ctx = ContextObj) {
  2322. DeclContext *DC = Ctx->getTranslationUnitDecl();
  2323. if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
  2324. DC->setMustBuildLookupTable();
  2325. }
  2326. return Success;
  2327. case llvm::BitstreamEntry::SubBlock:
  2328. switch (Entry.ID) {
  2329. case DECLTYPES_BLOCK_ID:
  2330. // We lazily load the decls block, but we want to set up the
  2331. // DeclsCursor cursor to point into it. Clone our current bitcode
  2332. // cursor to it, enter the block and read the abbrevs in that block.
  2333. // With the main cursor, we just skip over it.
  2334. F.DeclsCursor = Stream;
  2335. if (Stream.SkipBlock() || // Skip with the main cursor.
  2336. // Read the abbrevs.
  2337. ReadBlockAbbrevs(F.DeclsCursor, DECLTYPES_BLOCK_ID)) {
  2338. Error("malformed block record in AST file");
  2339. return Failure;
  2340. }
  2341. break;
  2342. case PREPROCESSOR_BLOCK_ID:
  2343. F.MacroCursor = Stream;
  2344. if (!PP.getExternalSource())
  2345. PP.setExternalSource(this);
  2346. if (Stream.SkipBlock() ||
  2347. ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID)) {
  2348. Error("malformed block record in AST file");
  2349. return Failure;
  2350. }
  2351. F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
  2352. break;
  2353. case PREPROCESSOR_DETAIL_BLOCK_ID:
  2354. F.PreprocessorDetailCursor = Stream;
  2355. if (Stream.SkipBlock() ||
  2356. ReadBlockAbbrevs(F.PreprocessorDetailCursor,
  2357. PREPROCESSOR_DETAIL_BLOCK_ID)) {
  2358. Error("malformed preprocessor detail record in AST file");
  2359. return Failure;
  2360. }
  2361. F.PreprocessorDetailStartOffset
  2362. = F.PreprocessorDetailCursor.GetCurrentBitNo();
  2363. if (!PP.getPreprocessingRecord())
  2364. PP.createPreprocessingRecord();
  2365. if (!PP.getPreprocessingRecord()->getExternalSource())
  2366. PP.getPreprocessingRecord()->SetExternalSource(*this);
  2367. break;
  2368. case SOURCE_MANAGER_BLOCK_ID:
  2369. if (ReadSourceManagerBlock(F))
  2370. return Failure;
  2371. break;
  2372. case SUBMODULE_BLOCK_ID:
  2373. if (ASTReadResult Result =
  2374. ReadSubmoduleBlock(F, ClientLoadCapabilities))
  2375. return Result;
  2376. break;
  2377. case COMMENTS_BLOCK_ID: {
  2378. BitstreamCursor C = Stream;
  2379. if (Stream.SkipBlock() ||
  2380. ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID)) {
  2381. Error("malformed comments block in AST file");
  2382. return Failure;
  2383. }
  2384. CommentsCursors.push_back(std::make_pair(C, &F));
  2385. break;
  2386. }
  2387. default:
  2388. if (Stream.SkipBlock()) {
  2389. Error("malformed block record in AST file");
  2390. return Failure;
  2391. }
  2392. break;
  2393. }
  2394. continue;
  2395. case llvm::BitstreamEntry::Record:
  2396. // The interesting case.
  2397. break;
  2398. }
  2399. // Read and process a record.
  2400. Record.clear();
  2401. StringRef Blob;
  2402. auto RecordType =
  2403. (ASTRecordTypes)Stream.readRecord(Entry.ID, Record, &Blob);
  2404. // If we're not loading an AST context, we don't care about most records.
  2405. if (!ContextObj) {
  2406. switch (RecordType) {
  2407. case IDENTIFIER_TABLE:
  2408. case IDENTIFIER_OFFSET:
  2409. case INTERESTING_IDENTIFIERS:
  2410. case STATISTICS:
  2411. case PP_CONDITIONAL_STACK:
  2412. case PP_COUNTER_VALUE:
  2413. case SOURCE_LOCATION_OFFSETS:
  2414. case MODULE_OFFSET_MAP:
  2415. case SOURCE_MANAGER_LINE_TABLE:
  2416. case SOURCE_LOCATION_PRELOADS:
  2417. case PPD_ENTITIES_OFFSETS:
  2418. case HEADER_SEARCH_TABLE:
  2419. case IMPORTED_MODULES:
  2420. case MACRO_OFFSET:
  2421. break;
  2422. default:
  2423. continue;
  2424. }
  2425. }
  2426. switch (RecordType) {
  2427. default: // Default behavior: ignore.
  2428. break;
  2429. case TYPE_OFFSET: {
  2430. if (F.LocalNumTypes != 0) {
  2431. Error("duplicate TYPE_OFFSET record in AST file");
  2432. return Failure;
  2433. }
  2434. F.TypeOffsets = (const uint32_t *)Blob.data();
  2435. F.LocalNumTypes = Record[0];
  2436. unsigned LocalBaseTypeIndex = Record[1];
  2437. F.BaseTypeIndex = getTotalNumTypes();
  2438. if (F.LocalNumTypes > 0) {
  2439. // Introduce the global -> local mapping for types within this module.
  2440. GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
  2441. // Introduce the local -> global mapping for types within this module.
  2442. F.TypeRemap.insertOrReplace(
  2443. std::make_pair(LocalBaseTypeIndex,
  2444. F.BaseTypeIndex - LocalBaseTypeIndex));
  2445. TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
  2446. }
  2447. break;
  2448. }
  2449. case DECL_OFFSET: {
  2450. if (F.LocalNumDecls != 0) {
  2451. Error("duplicate DECL_OFFSET record in AST file");
  2452. return Failure;
  2453. }
  2454. F.DeclOffsets = (const DeclOffset *)Blob.data();
  2455. F.LocalNumDecls = Record[0];
  2456. unsigned LocalBaseDeclID = Record[1];
  2457. F.BaseDeclID = getTotalNumDecls();
  2458. if (F.LocalNumDecls > 0) {
  2459. // Introduce the global -> local mapping for declarations within this
  2460. // module.
  2461. GlobalDeclMap.insert(
  2462. std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
  2463. // Introduce the local -> global mapping for declarations within this
  2464. // module.
  2465. F.DeclRemap.insertOrReplace(
  2466. std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
  2467. // Introduce the global -> local mapping for declarations within this
  2468. // module.
  2469. F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
  2470. DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
  2471. }
  2472. break;
  2473. }
  2474. case TU_UPDATE_LEXICAL: {
  2475. DeclContext *TU = ContextObj->getTranslationUnitDecl();
  2476. LexicalContents Contents(
  2477. reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
  2478. Blob.data()),
  2479. static_cast<unsigned int>(Blob.size() / 4));
  2480. TULexicalDecls.push_back(std::make_pair(&F, Contents));
  2481. TU->setHasExternalLexicalStorage(true);
  2482. break;
  2483. }
  2484. case UPDATE_VISIBLE: {
  2485. unsigned Idx = 0;
  2486. serialization::DeclID ID = ReadDeclID(F, Record, Idx);
  2487. auto *Data = (const unsigned char*)Blob.data();
  2488. PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
  2489. // If we've already loaded the decl, perform the updates when we finish
  2490. // loading this block.
  2491. if (Decl *D = GetExistingDecl(ID))
  2492. PendingUpdateRecords.push_back(
  2493. PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
  2494. break;
  2495. }
  2496. case IDENTIFIER_TABLE:
  2497. F.IdentifierTableData = Blob.data();
  2498. if (Record[0]) {
  2499. F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
  2500. (const unsigned char *)F.IdentifierTableData + Record[0],
  2501. (const unsigned char *)F.IdentifierTableData + sizeof(uint32_t),
  2502. (const unsigned char *)F.IdentifierTableData,
  2503. ASTIdentifierLookupTrait(*this, F));
  2504. PP.getIdentifierTable().setExternalIdentifierLookup(this);
  2505. }
  2506. break;
  2507. case IDENTIFIER_OFFSET: {
  2508. if (F.LocalNumIdentifiers != 0) {
  2509. Error("duplicate IDENTIFIER_OFFSET record in AST file");
  2510. return Failure;
  2511. }
  2512. F.IdentifierOffsets = (const uint32_t *)Blob.data();
  2513. F.LocalNumIdentifiers = Record[0];
  2514. unsigned LocalBaseIdentifierID = Record[1];
  2515. F.BaseIdentifierID = getTotalNumIdentifiers();
  2516. if (F.LocalNumIdentifiers > 0) {
  2517. // Introduce the global -> local mapping for identifiers within this
  2518. // module.
  2519. GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
  2520. &F));
  2521. // Introduce the local -> global mapping for identifiers within this
  2522. // module.
  2523. F.IdentifierRemap.insertOrReplace(
  2524. std::make_pair(LocalBaseIdentifierID,
  2525. F.BaseIdentifierID - LocalBaseIdentifierID));
  2526. IdentifiersLoaded.resize(IdentifiersLoaded.size()
  2527. + F.LocalNumIdentifiers);
  2528. }
  2529. break;
  2530. }
  2531. case INTERESTING_IDENTIFIERS:
  2532. F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
  2533. break;
  2534. case EAGERLY_DESERIALIZED_DECLS:
  2535. // FIXME: Skip reading this record if our ASTConsumer doesn't care
  2536. // about "interesting" decls (for instance, if we're building a module).
  2537. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2538. EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2539. break;
  2540. case MODULAR_CODEGEN_DECLS:
  2541. // FIXME: Skip reading this record if our ASTConsumer doesn't care about
  2542. // them (ie: if we're not codegenerating this module).
  2543. if (F.Kind == MK_MainFile)
  2544. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2545. EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2546. break;
  2547. case SPECIAL_TYPES:
  2548. if (SpecialTypes.empty()) {
  2549. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2550. SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
  2551. break;
  2552. }
  2553. if (SpecialTypes.size() != Record.size()) {
  2554. Error("invalid special-types record");
  2555. return Failure;
  2556. }
  2557. for (unsigned I = 0, N = Record.size(); I != N; ++I) {
  2558. serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
  2559. if (!SpecialTypes[I])
  2560. SpecialTypes[I] = ID;
  2561. // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
  2562. // merge step?
  2563. }
  2564. break;
  2565. case STATISTICS:
  2566. TotalNumStatements += Record[0];
  2567. TotalNumMacros += Record[1];
  2568. TotalLexicalDeclContexts += Record[2];
  2569. TotalVisibleDeclContexts += Record[3];
  2570. break;
  2571. case UNUSED_FILESCOPED_DECLS:
  2572. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2573. UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2574. break;
  2575. case DELEGATING_CTORS:
  2576. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2577. DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
  2578. break;
  2579. case WEAK_UNDECLARED_IDENTIFIERS:
  2580. if (Record.size() % 4 != 0) {
  2581. Error("invalid weak identifiers record");
  2582. return Failure;
  2583. }
  2584. // FIXME: Ignore weak undeclared identifiers from non-original PCH
  2585. // files. This isn't the way to do it :)
  2586. WeakUndeclaredIdentifiers.clear();
  2587. // Translate the weak, undeclared identifiers into global IDs.
  2588. for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
  2589. WeakUndeclaredIdentifiers.push_back(
  2590. getGlobalIdentifierID(F, Record[I++]));
  2591. WeakUndeclaredIdentifiers.push_back(
  2592. getGlobalIdentifierID(F, Record[I++]));
  2593. WeakUndeclaredIdentifiers.push_back(
  2594. ReadSourceLocation(F, Record, I).getRawEncoding());
  2595. WeakUndeclaredIdentifiers.push_back(Record[I++]);
  2596. }
  2597. break;
  2598. case SELECTOR_OFFSETS: {
  2599. F.SelectorOffsets = (const uint32_t *)Blob.data();
  2600. F.LocalNumSelectors = Record[0];
  2601. unsigned LocalBaseSelectorID = Record[1];
  2602. F.BaseSelectorID = getTotalNumSelectors();
  2603. if (F.LocalNumSelectors > 0) {
  2604. // Introduce the global -> local mapping for selectors within this
  2605. // module.
  2606. GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
  2607. // Introduce the local -> global mapping for selectors within this
  2608. // module.
  2609. F.SelectorRemap.insertOrReplace(
  2610. std::make_pair(LocalBaseSelectorID,
  2611. F.BaseSelectorID - LocalBaseSelectorID));
  2612. SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
  2613. }
  2614. break;
  2615. }
  2616. case METHOD_POOL:
  2617. F.SelectorLookupTableData = (const unsigned char *)Blob.data();
  2618. if (Record[0])
  2619. F.SelectorLookupTable
  2620. = ASTSelectorLookupTable::Create(
  2621. F.SelectorLookupTableData + Record[0],
  2622. F.SelectorLookupTableData,
  2623. ASTSelectorLookupTrait(*this, F));
  2624. TotalNumMethodPoolEntries += Record[1];
  2625. break;
  2626. case REFERENCED_SELECTOR_POOL:
  2627. if (!Record.empty()) {
  2628. for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
  2629. ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
  2630. Record[Idx++]));
  2631. ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
  2632. getRawEncoding());
  2633. }
  2634. }
  2635. break;
  2636. case PP_CONDITIONAL_STACK:
  2637. if (!Record.empty()) {
  2638. unsigned Idx = 0, End = Record.size() - 1;
  2639. bool ReachedEOFWhileSkipping = Record[Idx++];
  2640. llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
  2641. if (ReachedEOFWhileSkipping) {
  2642. SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
  2643. SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
  2644. bool FoundNonSkipPortion = Record[Idx++];
  2645. bool FoundElse = Record[Idx++];
  2646. SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
  2647. SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
  2648. FoundElse, ElseLoc);
  2649. }
  2650. SmallVector<PPConditionalInfo, 4> ConditionalStack;
  2651. while (Idx < End) {
  2652. auto Loc = ReadSourceLocation(F, Record, Idx);
  2653. bool WasSkipping = Record[Idx++];
  2654. bool FoundNonSkip = Record[Idx++];
  2655. bool FoundElse = Record[Idx++];
  2656. ConditionalStack.push_back(
  2657. {Loc, WasSkipping, FoundNonSkip, FoundElse});
  2658. }
  2659. PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
  2660. }
  2661. break;
  2662. case PP_COUNTER_VALUE:
  2663. if (!Record.empty() && Listener)
  2664. Listener->ReadCounter(F, Record[0]);
  2665. break;
  2666. case FILE_SORTED_DECLS:
  2667. F.FileSortedDecls = (const DeclID *)Blob.data();
  2668. F.NumFileSortedDecls = Record[0];
  2669. break;
  2670. case SOURCE_LOCATION_OFFSETS: {
  2671. F.SLocEntryOffsets = (const uint32_t *)Blob.data();
  2672. F.LocalNumSLocEntries = Record[0];
  2673. unsigned SLocSpaceSize = Record[1];
  2674. std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
  2675. SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
  2676. SLocSpaceSize);
  2677. if (!F.SLocEntryBaseID) {
  2678. Error("ran out of source locations");
  2679. break;
  2680. }
  2681. // Make our entry in the range map. BaseID is negative and growing, so
  2682. // we invert it. Because we invert it, though, we need the other end of
  2683. // the range.
  2684. unsigned RangeStart =
  2685. unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
  2686. GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
  2687. F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
  2688. // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
  2689. assert((F.SLocEntryBaseOffset & (1U << 31U)) == 0);
  2690. GlobalSLocOffsetMap.insert(
  2691. std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
  2692. - SLocSpaceSize,&F));
  2693. // Initialize the remapping table.
  2694. // Invalid stays invalid.
  2695. F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
  2696. // This module. Base was 2 when being compiled.
  2697. F.SLocRemap.insertOrReplace(std::make_pair(2U,
  2698. static_cast<int>(F.SLocEntryBaseOffset - 2)));
  2699. TotalNumSLocEntries += F.LocalNumSLocEntries;
  2700. break;
  2701. }
  2702. case MODULE_OFFSET_MAP:
  2703. F.ModuleOffsetMap = Blob;
  2704. break;
  2705. case SOURCE_MANAGER_LINE_TABLE:
  2706. if (ParseLineTable(F, Record))
  2707. return Failure;
  2708. break;
  2709. case SOURCE_LOCATION_PRELOADS: {
  2710. // Need to transform from the local view (1-based IDs) to the global view,
  2711. // which is based off F.SLocEntryBaseID.
  2712. if (!F.PreloadSLocEntries.empty()) {
  2713. Error("Multiple SOURCE_LOCATION_PRELOADS records in AST file");
  2714. return Failure;
  2715. }
  2716. F.PreloadSLocEntries.swap(Record);
  2717. break;
  2718. }
  2719. case EXT_VECTOR_DECLS:
  2720. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2721. ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
  2722. break;
  2723. case VTABLE_USES:
  2724. if (Record.size() % 3 != 0) {
  2725. Error("Invalid VTABLE_USES record");
  2726. return Failure;
  2727. }
  2728. // Later tables overwrite earlier ones.
  2729. // FIXME: Modules will have some trouble with this. This is clearly not
  2730. // the right way to do this.
  2731. VTableUses.clear();
  2732. for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
  2733. VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
  2734. VTableUses.push_back(
  2735. ReadSourceLocation(F, Record, Idx).getRawEncoding());
  2736. VTableUses.push_back(Record[Idx++]);
  2737. }
  2738. break;
  2739. case PENDING_IMPLICIT_INSTANTIATIONS:
  2740. if (PendingInstantiations.size() % 2 != 0) {
  2741. Error("Invalid existing PendingInstantiations");
  2742. return Failure;
  2743. }
  2744. if (Record.size() % 2 != 0) {
  2745. Error("Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
  2746. return Failure;
  2747. }
  2748. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  2749. PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
  2750. PendingInstantiations.push_back(
  2751. ReadSourceLocation(F, Record, I).getRawEncoding());
  2752. }
  2753. break;
  2754. case SEMA_DECL_REFS:
  2755. if (Record.size() != 3) {
  2756. Error("Invalid SEMA_DECL_REFS block");
  2757. return Failure;
  2758. }
  2759. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2760. SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  2761. break;
  2762. case PPD_ENTITIES_OFFSETS: {
  2763. F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
  2764. assert(Blob.size() % sizeof(PPEntityOffset) == 0);
  2765. F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
  2766. unsigned LocalBasePreprocessedEntityID = Record[0];
  2767. unsigned StartingID;
  2768. if (!PP.getPreprocessingRecord())
  2769. PP.createPreprocessingRecord();
  2770. if (!PP.getPreprocessingRecord()->getExternalSource())
  2771. PP.getPreprocessingRecord()->SetExternalSource(*this);
  2772. StartingID
  2773. = PP.getPreprocessingRecord()
  2774. ->allocateLoadedEntities(F.NumPreprocessedEntities);
  2775. F.BasePreprocessedEntityID = StartingID;
  2776. if (F.NumPreprocessedEntities > 0) {
  2777. // Introduce the global -> local mapping for preprocessed entities in
  2778. // this module.
  2779. GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
  2780. // Introduce the local -> global mapping for preprocessed entities in
  2781. // this module.
  2782. F.PreprocessedEntityRemap.insertOrReplace(
  2783. std::make_pair(LocalBasePreprocessedEntityID,
  2784. F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
  2785. }
  2786. break;
  2787. }
  2788. case DECL_UPDATE_OFFSETS:
  2789. if (Record.size() % 2 != 0) {
  2790. Error("invalid DECL_UPDATE_OFFSETS block in AST file");
  2791. return Failure;
  2792. }
  2793. for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
  2794. GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
  2795. DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
  2796. // If we've already loaded the decl, perform the updates when we finish
  2797. // loading this block.
  2798. if (Decl *D = GetExistingDecl(ID))
  2799. PendingUpdateRecords.push_back(
  2800. PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
  2801. }
  2802. break;
  2803. case OBJC_CATEGORIES_MAP:
  2804. if (F.LocalNumObjCCategoriesInMap != 0) {
  2805. Error("duplicate OBJC_CATEGORIES_MAP record in AST file");
  2806. return Failure;
  2807. }
  2808. F.LocalNumObjCCategoriesInMap = Record[0];
  2809. F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
  2810. break;
  2811. case OBJC_CATEGORIES:
  2812. F.ObjCCategories.swap(Record);
  2813. break;
  2814. case CUDA_SPECIAL_DECL_REFS:
  2815. // Later tables overwrite earlier ones.
  2816. // FIXME: Modules will have trouble with this.
  2817. CUDASpecialDeclRefs.clear();
  2818. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2819. CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  2820. break;
  2821. case HEADER_SEARCH_TABLE:
  2822. F.HeaderFileInfoTableData = Blob.data();
  2823. F.LocalNumHeaderFileInfos = Record[1];
  2824. if (Record[0]) {
  2825. F.HeaderFileInfoTable
  2826. = HeaderFileInfoLookupTable::Create(
  2827. (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
  2828. (const unsigned char *)F.HeaderFileInfoTableData,
  2829. HeaderFileInfoTrait(*this, F,
  2830. &PP.getHeaderSearchInfo(),
  2831. Blob.data() + Record[2]));
  2832. PP.getHeaderSearchInfo().SetExternalSource(this);
  2833. if (!PP.getHeaderSearchInfo().getExternalLookup())
  2834. PP.getHeaderSearchInfo().SetExternalLookup(this);
  2835. }
  2836. break;
  2837. case FP_PRAGMA_OPTIONS:
  2838. // Later tables overwrite earlier ones.
  2839. FPPragmaOptions.swap(Record);
  2840. break;
  2841. case OPENCL_EXTENSIONS:
  2842. for (unsigned I = 0, E = Record.size(); I != E; ) {
  2843. auto Name = ReadString(Record, I);
  2844. auto &Opt = OpenCLExtensions.OptMap[Name];
  2845. Opt.Supported = Record[I++] != 0;
  2846. Opt.Enabled = Record[I++] != 0;
  2847. Opt.Avail = Record[I++];
  2848. Opt.Core = Record[I++];
  2849. }
  2850. break;
  2851. case OPENCL_EXTENSION_TYPES:
  2852. for (unsigned I = 0, E = Record.size(); I != E;) {
  2853. auto TypeID = static_cast<::TypeID>(Record[I++]);
  2854. auto *Type = GetType(TypeID).getTypePtr();
  2855. auto NumExt = static_cast<unsigned>(Record[I++]);
  2856. for (unsigned II = 0; II != NumExt; ++II) {
  2857. auto Ext = ReadString(Record, I);
  2858. OpenCLTypeExtMap[Type].insert(Ext);
  2859. }
  2860. }
  2861. break;
  2862. case OPENCL_EXTENSION_DECLS:
  2863. for (unsigned I = 0, E = Record.size(); I != E;) {
  2864. auto DeclID = static_cast<::DeclID>(Record[I++]);
  2865. auto *Decl = GetDecl(DeclID);
  2866. auto NumExt = static_cast<unsigned>(Record[I++]);
  2867. for (unsigned II = 0; II != NumExt; ++II) {
  2868. auto Ext = ReadString(Record, I);
  2869. OpenCLDeclExtMap[Decl].insert(Ext);
  2870. }
  2871. }
  2872. break;
  2873. case TENTATIVE_DEFINITIONS:
  2874. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2875. TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
  2876. break;
  2877. case KNOWN_NAMESPACES:
  2878. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2879. KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
  2880. break;
  2881. case UNDEFINED_BUT_USED:
  2882. if (UndefinedButUsed.size() % 2 != 0) {
  2883. Error("Invalid existing UndefinedButUsed");
  2884. return Failure;
  2885. }
  2886. if (Record.size() % 2 != 0) {
  2887. Error("invalid undefined-but-used record");
  2888. return Failure;
  2889. }
  2890. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  2891. UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
  2892. UndefinedButUsed.push_back(
  2893. ReadSourceLocation(F, Record, I).getRawEncoding());
  2894. }
  2895. break;
  2896. case DELETE_EXPRS_TO_ANALYZE:
  2897. for (unsigned I = 0, N = Record.size(); I != N;) {
  2898. DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
  2899. const uint64_t Count = Record[I++];
  2900. DelayedDeleteExprs.push_back(Count);
  2901. for (uint64_t C = 0; C < Count; ++C) {
  2902. DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
  2903. bool IsArrayForm = Record[I++] == 1;
  2904. DelayedDeleteExprs.push_back(IsArrayForm);
  2905. }
  2906. }
  2907. break;
  2908. case IMPORTED_MODULES:
  2909. if (!F.isModule()) {
  2910. // If we aren't loading a module (which has its own exports), make
  2911. // all of the imported modules visible.
  2912. // FIXME: Deal with macros-only imports.
  2913. for (unsigned I = 0, N = Record.size(); I != N; /**/) {
  2914. unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
  2915. SourceLocation Loc = ReadSourceLocation(F, Record, I);
  2916. if (GlobalID) {
  2917. ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
  2918. if (DeserializationListener)
  2919. DeserializationListener->ModuleImportRead(GlobalID, Loc);
  2920. }
  2921. }
  2922. }
  2923. break;
  2924. case MACRO_OFFSET: {
  2925. if (F.LocalNumMacros != 0) {
  2926. Error("duplicate MACRO_OFFSET record in AST file");
  2927. return Failure;
  2928. }
  2929. F.MacroOffsets = (const uint32_t *)Blob.data();
  2930. F.LocalNumMacros = Record[0];
  2931. unsigned LocalBaseMacroID = Record[1];
  2932. F.BaseMacroID = getTotalNumMacros();
  2933. if (F.LocalNumMacros > 0) {
  2934. // Introduce the global -> local mapping for macros within this module.
  2935. GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
  2936. // Introduce the local -> global mapping for macros within this module.
  2937. F.MacroRemap.insertOrReplace(
  2938. std::make_pair(LocalBaseMacroID,
  2939. F.BaseMacroID - LocalBaseMacroID));
  2940. MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
  2941. }
  2942. break;
  2943. }
  2944. case LATE_PARSED_TEMPLATE:
  2945. LateParsedTemplates.append(Record.begin(), Record.end());
  2946. break;
  2947. case OPTIMIZE_PRAGMA_OPTIONS:
  2948. if (Record.size() != 1) {
  2949. Error("invalid pragma optimize record");
  2950. return Failure;
  2951. }
  2952. OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
  2953. break;
  2954. case MSSTRUCT_PRAGMA_OPTIONS:
  2955. if (Record.size() != 1) {
  2956. Error("invalid pragma ms_struct record");
  2957. return Failure;
  2958. }
  2959. PragmaMSStructState = Record[0];
  2960. break;
  2961. case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
  2962. if (Record.size() != 2) {
  2963. Error("invalid pragma ms_struct record");
  2964. return Failure;
  2965. }
  2966. PragmaMSPointersToMembersState = Record[0];
  2967. PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
  2968. break;
  2969. case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
  2970. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2971. UnusedLocalTypedefNameCandidates.push_back(
  2972. getGlobalDeclID(F, Record[I]));
  2973. break;
  2974. case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
  2975. if (Record.size() != 1) {
  2976. Error("invalid cuda pragma options record");
  2977. return Failure;
  2978. }
  2979. ForceCUDAHostDeviceDepth = Record[0];
  2980. break;
  2981. case PACK_PRAGMA_OPTIONS: {
  2982. if (Record.size() < 3) {
  2983. Error("invalid pragma pack record");
  2984. return Failure;
  2985. }
  2986. PragmaPackCurrentValue = Record[0];
  2987. PragmaPackCurrentLocation = ReadSourceLocation(F, Record[1]);
  2988. unsigned NumStackEntries = Record[2];
  2989. unsigned Idx = 3;
  2990. // Reset the stack when importing a new module.
  2991. PragmaPackStack.clear();
  2992. for (unsigned I = 0; I < NumStackEntries; ++I) {
  2993. PragmaPackStackEntry Entry;
  2994. Entry.Value = Record[Idx++];
  2995. Entry.Location = ReadSourceLocation(F, Record[Idx++]);
  2996. Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
  2997. PragmaPackStrings.push_back(ReadString(Record, Idx));
  2998. Entry.SlotLabel = PragmaPackStrings.back();
  2999. PragmaPackStack.push_back(Entry);
  3000. }
  3001. break;
  3002. }
  3003. }
  3004. }
  3005. }
  3006. void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
  3007. assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
  3008. // Additional remapping information.
  3009. const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
  3010. const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
  3011. F.ModuleOffsetMap = StringRef();
  3012. // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
  3013. if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
  3014. F.SLocRemap.insert(std::make_pair(0U, 0));
  3015. F.SLocRemap.insert(std::make_pair(2U, 1));
  3016. }
  3017. // Continuous range maps we may be updating in our module.
  3018. using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
  3019. RemapBuilder SLocRemap(F.SLocRemap);
  3020. RemapBuilder IdentifierRemap(F.IdentifierRemap);
  3021. RemapBuilder MacroRemap(F.MacroRemap);
  3022. RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
  3023. RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
  3024. RemapBuilder SelectorRemap(F.SelectorRemap);
  3025. RemapBuilder DeclRemap(F.DeclRemap);
  3026. RemapBuilder TypeRemap(F.TypeRemap);
  3027. while (Data < DataEnd) {
  3028. // FIXME: Looking up dependency modules by filename is horrible. Let's
  3029. // start fixing this with prebuilt and explicit modules and see how it
  3030. // goes...
  3031. using namespace llvm::support;
  3032. ModuleKind Kind = static_cast<ModuleKind>(
  3033. endian::readNext<uint8_t, little, unaligned>(Data));
  3034. uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
  3035. StringRef Name = StringRef((const char*)Data, Len);
  3036. Data += Len;
  3037. ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule
  3038. ? ModuleMgr.lookupByModuleName(Name)
  3039. : ModuleMgr.lookupByFileName(Name));
  3040. if (!OM) {
  3041. std::string Msg =
  3042. "SourceLocation remap refers to unknown module, cannot find ";
  3043. Msg.append(Name);
  3044. Error(Msg);
  3045. return;
  3046. }
  3047. uint32_t SLocOffset =
  3048. endian::readNext<uint32_t, little, unaligned>(Data);
  3049. uint32_t IdentifierIDOffset =
  3050. endian::readNext<uint32_t, little, unaligned>(Data);
  3051. uint32_t MacroIDOffset =
  3052. endian::readNext<uint32_t, little, unaligned>(Data);
  3053. uint32_t PreprocessedEntityIDOffset =
  3054. endian::readNext<uint32_t, little, unaligned>(Data);
  3055. uint32_t SubmoduleIDOffset =
  3056. endian::readNext<uint32_t, little, unaligned>(Data);
  3057. uint32_t SelectorIDOffset =
  3058. endian::readNext<uint32_t, little, unaligned>(Data);
  3059. uint32_t DeclIDOffset =
  3060. endian::readNext<uint32_t, little, unaligned>(Data);
  3061. uint32_t TypeIndexOffset =
  3062. endian::readNext<uint32_t, little, unaligned>(Data);
  3063. uint32_t None = std::numeric_limits<uint32_t>::max();
  3064. auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
  3065. RemapBuilder &Remap) {
  3066. if (Offset != None)
  3067. Remap.insert(std::make_pair(Offset,
  3068. static_cast<int>(BaseOffset - Offset)));
  3069. };
  3070. mapOffset(SLocOffset, OM->SLocEntryBaseOffset, SLocRemap);
  3071. mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
  3072. mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
  3073. mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
  3074. PreprocessedEntityRemap);
  3075. mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
  3076. mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
  3077. mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
  3078. mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
  3079. // Global -> local mappings.
  3080. F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
  3081. }
  3082. }
  3083. ASTReader::ASTReadResult
  3084. ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
  3085. const ModuleFile *ImportedBy,
  3086. unsigned ClientLoadCapabilities) {
  3087. unsigned Idx = 0;
  3088. F.ModuleMapPath = ReadPath(F, Record, Idx);
  3089. // Try to resolve ModuleName in the current header search context and
  3090. // verify that it is found in the same module map file as we saved. If the
  3091. // top-level AST file is a main file, skip this check because there is no
  3092. // usable header search context.
  3093. assert(!F.ModuleName.empty() &&
  3094. "MODULE_NAME should come before MODULE_MAP_FILE");
  3095. if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
  3096. // An implicitly-loaded module file should have its module listed in some
  3097. // module map file that we've already loaded.
  3098. Module *M = PP.getHeaderSearchInfo().lookupModule(F.ModuleName);
  3099. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  3100. const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
  3101. if (!ModMap) {
  3102. assert(ImportedBy && "top-level import should be verified");
  3103. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0) {
  3104. if (auto *ASTFE = M ? M->getASTFile() : nullptr)
  3105. // This module was defined by an imported (explicit) module.
  3106. Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
  3107. << ASTFE->getName();
  3108. else
  3109. // This module was built with a different module map.
  3110. Diag(diag::err_imported_module_not_found)
  3111. << F.ModuleName << F.FileName << ImportedBy->FileName
  3112. << F.ModuleMapPath;
  3113. }
  3114. return OutOfDate;
  3115. }
  3116. assert(M->Name == F.ModuleName && "found module with different name");
  3117. // Check the primary module map file.
  3118. const FileEntry *StoredModMap = FileMgr.getFile(F.ModuleMapPath);
  3119. if (StoredModMap == nullptr || StoredModMap != ModMap) {
  3120. assert(ModMap && "found module is missing module map file");
  3121. assert(ImportedBy && "top-level import should be verified");
  3122. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  3123. Diag(diag::err_imported_module_modmap_changed)
  3124. << F.ModuleName << ImportedBy->FileName
  3125. << ModMap->getName() << F.ModuleMapPath;
  3126. return OutOfDate;
  3127. }
  3128. llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
  3129. for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
  3130. // FIXME: we should use input files rather than storing names.
  3131. std::string Filename = ReadPath(F, Record, Idx);
  3132. const FileEntry *F =
  3133. FileMgr.getFile(Filename, false, false);
  3134. if (F == nullptr) {
  3135. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  3136. Error("could not find file '" + Filename +"' referenced by AST file");
  3137. return OutOfDate;
  3138. }
  3139. AdditionalStoredMaps.insert(F);
  3140. }
  3141. // Check any additional module map files (e.g. module.private.modulemap)
  3142. // that are not in the pcm.
  3143. if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
  3144. for (const FileEntry *ModMap : *AdditionalModuleMaps) {
  3145. // Remove files that match
  3146. // Note: SmallPtrSet::erase is really remove
  3147. if (!AdditionalStoredMaps.erase(ModMap)) {
  3148. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  3149. Diag(diag::err_module_different_modmap)
  3150. << F.ModuleName << /*new*/0 << ModMap->getName();
  3151. return OutOfDate;
  3152. }
  3153. }
  3154. }
  3155. // Check any additional module map files that are in the pcm, but not
  3156. // found in header search. Cases that match are already removed.
  3157. for (const FileEntry *ModMap : AdditionalStoredMaps) {
  3158. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  3159. Diag(diag::err_module_different_modmap)
  3160. << F.ModuleName << /*not new*/1 << ModMap->getName();
  3161. return OutOfDate;
  3162. }
  3163. }
  3164. if (Listener)
  3165. Listener->ReadModuleMapFile(F.ModuleMapPath);
  3166. return Success;
  3167. }
  3168. /// \brief Move the given method to the back of the global list of methods.
  3169. static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
  3170. // Find the entry for this selector in the method pool.
  3171. Sema::GlobalMethodPool::iterator Known
  3172. = S.MethodPool.find(Method->getSelector());
  3173. if (Known == S.MethodPool.end())
  3174. return;
  3175. // Retrieve the appropriate method list.
  3176. ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
  3177. : Known->second.second;
  3178. bool Found = false;
  3179. for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
  3180. if (!Found) {
  3181. if (List->getMethod() == Method) {
  3182. Found = true;
  3183. } else {
  3184. // Keep searching.
  3185. continue;
  3186. }
  3187. }
  3188. if (List->getNext())
  3189. List->setMethod(List->getNext()->getMethod());
  3190. else
  3191. List->setMethod(Method);
  3192. }
  3193. }
  3194. void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
  3195. assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
  3196. for (Decl *D : Names) {
  3197. bool wasHidden = D->isHidden();
  3198. D->setVisibleDespiteOwningModule();
  3199. if (wasHidden && SemaObj) {
  3200. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
  3201. moveMethodToBackOfGlobalList(*SemaObj, Method);
  3202. }
  3203. }
  3204. }
  3205. }
  3206. void ASTReader::makeModuleVisible(Module *Mod,
  3207. Module::NameVisibilityKind NameVisibility,
  3208. SourceLocation ImportLoc) {
  3209. llvm::SmallPtrSet<Module *, 4> Visited;
  3210. SmallVector<Module *, 4> Stack;
  3211. Stack.push_back(Mod);
  3212. while (!Stack.empty()) {
  3213. Mod = Stack.pop_back_val();
  3214. if (NameVisibility <= Mod->NameVisibility) {
  3215. // This module already has this level of visibility (or greater), so
  3216. // there is nothing more to do.
  3217. continue;
  3218. }
  3219. if (!Mod->isAvailable()) {
  3220. // Modules that aren't available cannot be made visible.
  3221. continue;
  3222. }
  3223. // Update the module's name visibility.
  3224. Mod->NameVisibility = NameVisibility;
  3225. // If we've already deserialized any names from this module,
  3226. // mark them as visible.
  3227. HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
  3228. if (Hidden != HiddenNamesMap.end()) {
  3229. auto HiddenNames = std::move(*Hidden);
  3230. HiddenNamesMap.erase(Hidden);
  3231. makeNamesVisible(HiddenNames.second, HiddenNames.first);
  3232. assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
  3233. "making names visible added hidden names");
  3234. }
  3235. // Push any exported modules onto the stack to be marked as visible.
  3236. SmallVector<Module *, 16> Exports;
  3237. Mod->getExportedModules(Exports);
  3238. for (SmallVectorImpl<Module *>::iterator
  3239. I = Exports.begin(), E = Exports.end(); I != E; ++I) {
  3240. Module *Exported = *I;
  3241. if (Visited.insert(Exported).second)
  3242. Stack.push_back(Exported);
  3243. }
  3244. }
  3245. }
  3246. /// We've merged the definition \p MergedDef into the existing definition
  3247. /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
  3248. /// visible.
  3249. void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
  3250. NamedDecl *MergedDef) {
  3251. // FIXME: This doesn't correctly handle the case where MergedDef is visible
  3252. // in modules other than its owning module. We should instead give the
  3253. // ASTContext a list of merged definitions for Def.
  3254. if (Def->isHidden()) {
  3255. // If MergedDef is visible or becomes visible, make the definition visible.
  3256. if (!MergedDef->isHidden())
  3257. Def->setVisibleDespiteOwningModule();
  3258. else if (getContext().getLangOpts().ModulesLocalVisibility) {
  3259. getContext().mergeDefinitionIntoModule(
  3260. Def, MergedDef->getImportedOwningModule(),
  3261. /*NotifyListeners*/ false);
  3262. PendingMergedDefinitionsToDeduplicate.insert(Def);
  3263. } else {
  3264. auto SubmoduleID = MergedDef->getOwningModuleID();
  3265. assert(SubmoduleID && "hidden definition in no module");
  3266. HiddenNamesMap[getSubmodule(SubmoduleID)].push_back(Def);
  3267. }
  3268. }
  3269. }
  3270. bool ASTReader::loadGlobalIndex() {
  3271. if (GlobalIndex)
  3272. return false;
  3273. if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
  3274. !PP.getLangOpts().Modules)
  3275. return true;
  3276. // Try to load the global index.
  3277. TriedLoadingGlobalIndex = true;
  3278. StringRef ModuleCachePath
  3279. = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
  3280. std::pair<GlobalModuleIndex *, GlobalModuleIndex::ErrorCode> Result
  3281. = GlobalModuleIndex::readIndex(ModuleCachePath);
  3282. if (!Result.first)
  3283. return true;
  3284. GlobalIndex.reset(Result.first);
  3285. ModuleMgr.setGlobalIndex(GlobalIndex.get());
  3286. return false;
  3287. }
  3288. bool ASTReader::isGlobalIndexUnavailable() const {
  3289. return PP.getLangOpts().Modules && UseGlobalIndex &&
  3290. !hasGlobalIndex() && TriedLoadingGlobalIndex;
  3291. }
  3292. static void updateModuleTimestamp(ModuleFile &MF) {
  3293. // Overwrite the timestamp file contents so that file's mtime changes.
  3294. std::string TimestampFilename = MF.getTimestampFilename();
  3295. std::error_code EC;
  3296. llvm::raw_fd_ostream OS(TimestampFilename, EC, llvm::sys::fs::F_Text);
  3297. if (EC)
  3298. return;
  3299. OS << "Timestamp file\n";
  3300. OS.close();
  3301. OS.clear_error(); // Avoid triggering a fatal error.
  3302. }
  3303. /// \brief Given a cursor at the start of an AST file, scan ahead and drop the
  3304. /// cursor into the start of the given block ID, returning false on success and
  3305. /// true on failure.
  3306. static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
  3307. while (true) {
  3308. llvm::BitstreamEntry Entry = Cursor.advance();
  3309. switch (Entry.Kind) {
  3310. case llvm::BitstreamEntry::Error:
  3311. case llvm::BitstreamEntry::EndBlock:
  3312. return true;
  3313. case llvm::BitstreamEntry::Record:
  3314. // Ignore top-level records.
  3315. Cursor.skipRecord(Entry.ID);
  3316. break;
  3317. case llvm::BitstreamEntry::SubBlock:
  3318. if (Entry.ID == BlockID) {
  3319. if (Cursor.EnterSubBlock(BlockID))
  3320. return true;
  3321. // Found it!
  3322. return false;
  3323. }
  3324. if (Cursor.SkipBlock())
  3325. return true;
  3326. }
  3327. }
  3328. }
  3329. ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
  3330. ModuleKind Type,
  3331. SourceLocation ImportLoc,
  3332. unsigned ClientLoadCapabilities,
  3333. SmallVectorImpl<ImportedSubmodule> *Imported) {
  3334. llvm::SaveAndRestore<SourceLocation>
  3335. SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
  3336. // Defer any pending actions until we get to the end of reading the AST file.
  3337. Deserializing AnASTFile(this);
  3338. // Bump the generation number.
  3339. unsigned PreviousGeneration = 0;
  3340. if (ContextObj)
  3341. PreviousGeneration = incrementGeneration(*ContextObj);
  3342. unsigned NumModules = ModuleMgr.size();
  3343. SmallVector<ImportedModule, 4> Loaded;
  3344. switch (ASTReadResult ReadResult =
  3345. ReadASTCore(FileName, Type, ImportLoc,
  3346. /*ImportedBy=*/nullptr, Loaded, 0, 0,
  3347. ASTFileSignature(), ClientLoadCapabilities)) {
  3348. case Failure:
  3349. case Missing:
  3350. case OutOfDate:
  3351. case VersionMismatch:
  3352. case ConfigurationMismatch:
  3353. case HadErrors: {
  3354. llvm::SmallPtrSet<ModuleFile *, 4> LoadedSet;
  3355. for (const ImportedModule &IM : Loaded)
  3356. LoadedSet.insert(IM.Mod);
  3357. ModuleMgr.removeModules(ModuleMgr.begin() + NumModules, LoadedSet,
  3358. PP.getLangOpts().Modules
  3359. ? &PP.getHeaderSearchInfo().getModuleMap()
  3360. : nullptr);
  3361. // If we find that any modules are unusable, the global index is going
  3362. // to be out-of-date. Just remove it.
  3363. GlobalIndex.reset();
  3364. ModuleMgr.setGlobalIndex(nullptr);
  3365. return ReadResult;
  3366. }
  3367. case Success:
  3368. break;
  3369. }
  3370. // Here comes stuff that we only do once the entire chain is loaded.
  3371. // Load the AST blocks of all of the modules that we loaded.
  3372. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
  3373. MEnd = Loaded.end();
  3374. M != MEnd; ++M) {
  3375. ModuleFile &F = *M->Mod;
  3376. // Read the AST block.
  3377. if (ASTReadResult Result = ReadASTBlock(F, ClientLoadCapabilities))
  3378. return Result;
  3379. // Read the extension blocks.
  3380. while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
  3381. if (ASTReadResult Result = ReadExtensionBlock(F))
  3382. return Result;
  3383. }
  3384. // Once read, set the ModuleFile bit base offset and update the size in
  3385. // bits of all files we've seen.
  3386. F.GlobalBitOffset = TotalModulesSizeInBits;
  3387. TotalModulesSizeInBits += F.SizeInBits;
  3388. GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
  3389. // Preload SLocEntries.
  3390. for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
  3391. int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
  3392. // Load it through the SourceManager and don't call ReadSLocEntry()
  3393. // directly because the entry may have already been loaded in which case
  3394. // calling ReadSLocEntry() directly would trigger an assertion in
  3395. // SourceManager.
  3396. SourceMgr.getLoadedSLocEntryByID(Index);
  3397. }
  3398. // Map the original source file ID into the ID space of the current
  3399. // compilation.
  3400. if (F.OriginalSourceFileID.isValid()) {
  3401. F.OriginalSourceFileID = FileID::get(
  3402. F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
  3403. }
  3404. // Preload all the pending interesting identifiers by marking them out of
  3405. // date.
  3406. for (auto Offset : F.PreloadIdentifierOffsets) {
  3407. const unsigned char *Data = reinterpret_cast<const unsigned char *>(
  3408. F.IdentifierTableData + Offset);
  3409. ASTIdentifierLookupTrait Trait(*this, F);
  3410. auto KeyDataLen = Trait.ReadKeyDataLength(Data);
  3411. auto Key = Trait.ReadKey(Data, KeyDataLen.first);
  3412. auto &II = PP.getIdentifierTable().getOwn(Key);
  3413. II.setOutOfDate(true);
  3414. // Mark this identifier as being from an AST file so that we can track
  3415. // whether we need to serialize it.
  3416. markIdentifierFromAST(*this, II);
  3417. // Associate the ID with the identifier so that the writer can reuse it.
  3418. auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
  3419. SetIdentifierInfo(ID, &II);
  3420. }
  3421. }
  3422. // Setup the import locations and notify the module manager that we've
  3423. // committed to these module files.
  3424. for (SmallVectorImpl<ImportedModule>::iterator M = Loaded.begin(),
  3425. MEnd = Loaded.end();
  3426. M != MEnd; ++M) {
  3427. ModuleFile &F = *M->Mod;
  3428. ModuleMgr.moduleFileAccepted(&F);
  3429. // Set the import location.
  3430. F.DirectImportLoc = ImportLoc;
  3431. // FIXME: We assume that locations from PCH / preamble do not need
  3432. // any translation.
  3433. if (!M->ImportedBy)
  3434. F.ImportLoc = M->ImportLoc;
  3435. else
  3436. F.ImportLoc = TranslateSourceLocation(*M->ImportedBy, M->ImportLoc);
  3437. }
  3438. if (!PP.getLangOpts().CPlusPlus ||
  3439. (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
  3440. Type != MK_PrebuiltModule)) {
  3441. // Mark all of the identifiers in the identifier table as being out of date,
  3442. // so that various accessors know to check the loaded modules when the
  3443. // identifier is used.
  3444. //
  3445. // For C++ modules, we don't need information on many identifiers (just
  3446. // those that provide macros or are poisoned), so we mark all of
  3447. // the interesting ones via PreloadIdentifierOffsets.
  3448. for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
  3449. IdEnd = PP.getIdentifierTable().end();
  3450. Id != IdEnd; ++Id)
  3451. Id->second->setOutOfDate(true);
  3452. }
  3453. // Mark selectors as out of date.
  3454. for (auto Sel : SelectorGeneration)
  3455. SelectorOutOfDate[Sel.first] = true;
  3456. // Resolve any unresolved module exports.
  3457. for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
  3458. UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
  3459. SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
  3460. Module *ResolvedMod = getSubmodule(GlobalID);
  3461. switch (Unresolved.Kind) {
  3462. case UnresolvedModuleRef::Conflict:
  3463. if (ResolvedMod) {
  3464. Module::Conflict Conflict;
  3465. Conflict.Other = ResolvedMod;
  3466. Conflict.Message = Unresolved.String.str();
  3467. Unresolved.Mod->Conflicts.push_back(Conflict);
  3468. }
  3469. continue;
  3470. case UnresolvedModuleRef::Import:
  3471. if (ResolvedMod)
  3472. Unresolved.Mod->Imports.insert(ResolvedMod);
  3473. continue;
  3474. case UnresolvedModuleRef::Export:
  3475. if (ResolvedMod || Unresolved.IsWildcard)
  3476. Unresolved.Mod->Exports.push_back(
  3477. Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
  3478. continue;
  3479. }
  3480. }
  3481. UnresolvedModuleRefs.clear();
  3482. if (Imported)
  3483. Imported->append(ImportedModules.begin(),
  3484. ImportedModules.end());
  3485. // FIXME: How do we load the 'use'd modules? They may not be submodules.
  3486. // Might be unnecessary as use declarations are only used to build the
  3487. // module itself.
  3488. if (ContextObj)
  3489. InitializeContext();
  3490. if (SemaObj)
  3491. UpdateSema();
  3492. if (DeserializationListener)
  3493. DeserializationListener->ReaderInitialized(this);
  3494. ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
  3495. if (PrimaryModule.OriginalSourceFileID.isValid()) {
  3496. // If this AST file is a precompiled preamble, then set the
  3497. // preamble file ID of the source manager to the file source file
  3498. // from which the preamble was built.
  3499. if (Type == MK_Preamble) {
  3500. SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
  3501. } else if (Type == MK_MainFile) {
  3502. SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
  3503. }
  3504. }
  3505. // For any Objective-C class definitions we have already loaded, make sure
  3506. // that we load any additional categories.
  3507. if (ContextObj) {
  3508. for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
  3509. loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
  3510. ObjCClassesLoaded[I],
  3511. PreviousGeneration);
  3512. }
  3513. }
  3514. if (PP.getHeaderSearchInfo()
  3515. .getHeaderSearchOpts()
  3516. .ModulesValidateOncePerBuildSession) {
  3517. // Now we are certain that the module and all modules it depends on are
  3518. // up to date. Create or update timestamp files for modules that are
  3519. // located in the module cache (not for PCH files that could be anywhere
  3520. // in the filesystem).
  3521. for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
  3522. ImportedModule &M = Loaded[I];
  3523. if (M.Mod->Kind == MK_ImplicitModule) {
  3524. updateModuleTimestamp(*M.Mod);
  3525. }
  3526. }
  3527. }
  3528. return Success;
  3529. }
  3530. static ASTFileSignature readASTFileSignature(StringRef PCH);
  3531. /// \brief Whether \p Stream starts with the AST/PCH file magic number 'CPCH'.
  3532. static bool startsWithASTFileMagic(BitstreamCursor &Stream) {
  3533. return Stream.canSkipToPos(4) &&
  3534. Stream.Read(8) == 'C' &&
  3535. Stream.Read(8) == 'P' &&
  3536. Stream.Read(8) == 'C' &&
  3537. Stream.Read(8) == 'H';
  3538. }
  3539. static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
  3540. switch (Kind) {
  3541. case MK_PCH:
  3542. return 0; // PCH
  3543. case MK_ImplicitModule:
  3544. case MK_ExplicitModule:
  3545. case MK_PrebuiltModule:
  3546. return 1; // module
  3547. case MK_MainFile:
  3548. case MK_Preamble:
  3549. return 2; // main source file
  3550. }
  3551. llvm_unreachable("unknown module kind");
  3552. }
  3553. ASTReader::ASTReadResult
  3554. ASTReader::ReadASTCore(StringRef FileName,
  3555. ModuleKind Type,
  3556. SourceLocation ImportLoc,
  3557. ModuleFile *ImportedBy,
  3558. SmallVectorImpl<ImportedModule> &Loaded,
  3559. off_t ExpectedSize, time_t ExpectedModTime,
  3560. ASTFileSignature ExpectedSignature,
  3561. unsigned ClientLoadCapabilities) {
  3562. ModuleFile *M;
  3563. std::string ErrorStr;
  3564. ModuleManager::AddModuleResult AddResult
  3565. = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
  3566. getGeneration(), ExpectedSize, ExpectedModTime,
  3567. ExpectedSignature, readASTFileSignature,
  3568. M, ErrorStr);
  3569. switch (AddResult) {
  3570. case ModuleManager::AlreadyLoaded:
  3571. return Success;
  3572. case ModuleManager::NewlyLoaded:
  3573. // Load module file below.
  3574. break;
  3575. case ModuleManager::Missing:
  3576. // The module file was missing; if the client can handle that, return
  3577. // it.
  3578. if (ClientLoadCapabilities & ARR_Missing)
  3579. return Missing;
  3580. // Otherwise, return an error.
  3581. Diag(diag::err_module_file_not_found) << moduleKindForDiagnostic(Type)
  3582. << FileName << !ErrorStr.empty()
  3583. << ErrorStr;
  3584. return Failure;
  3585. case ModuleManager::OutOfDate:
  3586. // We couldn't load the module file because it is out-of-date. If the
  3587. // client can handle out-of-date, return it.
  3588. if (ClientLoadCapabilities & ARR_OutOfDate)
  3589. return OutOfDate;
  3590. // Otherwise, return an error.
  3591. Diag(diag::err_module_file_out_of_date) << moduleKindForDiagnostic(Type)
  3592. << FileName << !ErrorStr.empty()
  3593. << ErrorStr;
  3594. return Failure;
  3595. }
  3596. assert(M && "Missing module file");
  3597. ModuleFile &F = *M;
  3598. BitstreamCursor &Stream = F.Stream;
  3599. Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
  3600. F.SizeInBits = F.Buffer->getBufferSize() * 8;
  3601. // Sniff for the signature.
  3602. if (!startsWithASTFileMagic(Stream)) {
  3603. Diag(diag::err_module_file_invalid) << moduleKindForDiagnostic(Type)
  3604. << FileName;
  3605. return Failure;
  3606. }
  3607. // This is used for compatibility with older PCH formats.
  3608. bool HaveReadControlBlock = false;
  3609. while (true) {
  3610. llvm::BitstreamEntry Entry = Stream.advance();
  3611. switch (Entry.Kind) {
  3612. case llvm::BitstreamEntry::Error:
  3613. case llvm::BitstreamEntry::Record:
  3614. case llvm::BitstreamEntry::EndBlock:
  3615. Error("invalid record at top-level of AST file");
  3616. return Failure;
  3617. case llvm::BitstreamEntry::SubBlock:
  3618. break;
  3619. }
  3620. switch (Entry.ID) {
  3621. case CONTROL_BLOCK_ID:
  3622. HaveReadControlBlock = true;
  3623. switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
  3624. case Success:
  3625. // Check that we didn't try to load a non-module AST file as a module.
  3626. //
  3627. // FIXME: Should we also perform the converse check? Loading a module as
  3628. // a PCH file sort of works, but it's a bit wonky.
  3629. if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
  3630. Type == MK_PrebuiltModule) &&
  3631. F.ModuleName.empty()) {
  3632. auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
  3633. if (Result != OutOfDate ||
  3634. (ClientLoadCapabilities & ARR_OutOfDate) == 0)
  3635. Diag(diag::err_module_file_not_module) << FileName;
  3636. return Result;
  3637. }
  3638. break;
  3639. case Failure: return Failure;
  3640. case Missing: return Missing;
  3641. case OutOfDate: return OutOfDate;
  3642. case VersionMismatch: return VersionMismatch;
  3643. case ConfigurationMismatch: return ConfigurationMismatch;
  3644. case HadErrors: return HadErrors;
  3645. }
  3646. break;
  3647. case AST_BLOCK_ID:
  3648. if (!HaveReadControlBlock) {
  3649. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  3650. Diag(diag::err_pch_version_too_old);
  3651. return VersionMismatch;
  3652. }
  3653. // Record that we've loaded this module.
  3654. Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
  3655. return Success;
  3656. case UNHASHED_CONTROL_BLOCK_ID:
  3657. // This block is handled using look-ahead during ReadControlBlock. We
  3658. // shouldn't get here!
  3659. Error("malformed block record in AST file");
  3660. return Failure;
  3661. default:
  3662. if (Stream.SkipBlock()) {
  3663. Error("malformed block record in AST file");
  3664. return Failure;
  3665. }
  3666. break;
  3667. }
  3668. }
  3669. return Success;
  3670. }
  3671. ASTReader::ASTReadResult
  3672. ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
  3673. unsigned ClientLoadCapabilities) {
  3674. const HeaderSearchOptions &HSOpts =
  3675. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  3676. bool AllowCompatibleConfigurationMismatch =
  3677. F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
  3678. ASTReadResult Result = readUnhashedControlBlockImpl(
  3679. &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
  3680. Listener.get(),
  3681. WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
  3682. // If F was directly imported by another module, it's implicitly validated by
  3683. // the importing module.
  3684. if (DisableValidation || WasImportedBy ||
  3685. (AllowConfigurationMismatch && Result == ConfigurationMismatch))
  3686. return Success;
  3687. if (Result == Failure) {
  3688. Error("malformed block record in AST file");
  3689. return Failure;
  3690. }
  3691. if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
  3692. // If this module has already been finalized in the PCMCache, we're stuck
  3693. // with it; we can only load a single version of each module.
  3694. //
  3695. // This can happen when a module is imported in two contexts: in one, as a
  3696. // user module; in another, as a system module (due to an import from
  3697. // another module marked with the [system] flag). It usually indicates a
  3698. // bug in the module map: this module should also be marked with [system].
  3699. //
  3700. // If -Wno-system-headers (the default), and the first import is as a
  3701. // system module, then validation will fail during the as-user import,
  3702. // since -Werror flags won't have been validated. However, it's reasonable
  3703. // to treat this consistently as a system module.
  3704. //
  3705. // If -Wsystem-headers, the PCM on disk was built with
  3706. // -Wno-system-headers, and the first import is as a user module, then
  3707. // validation will fail during the as-system import since the PCM on disk
  3708. // doesn't guarantee that -Werror was respected. However, the -Werror
  3709. // flags were checked during the initial as-user import.
  3710. if (PCMCache.isBufferFinal(F.FileName)) {
  3711. Diag(diag::warn_module_system_bit_conflict) << F.FileName;
  3712. return Success;
  3713. }
  3714. }
  3715. return Result;
  3716. }
  3717. ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
  3718. ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
  3719. bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
  3720. bool ValidateDiagnosticOptions) {
  3721. // Initialize a stream.
  3722. BitstreamCursor Stream(StreamData);
  3723. // Sniff for the signature.
  3724. if (!startsWithASTFileMagic(Stream))
  3725. return Failure;
  3726. // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
  3727. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
  3728. return Failure;
  3729. // Read all of the records in the options block.
  3730. RecordData Record;
  3731. ASTReadResult Result = Success;
  3732. while (true) {
  3733. llvm::BitstreamEntry Entry = Stream.advance();
  3734. switch (Entry.Kind) {
  3735. case llvm::BitstreamEntry::Error:
  3736. case llvm::BitstreamEntry::SubBlock:
  3737. return Failure;
  3738. case llvm::BitstreamEntry::EndBlock:
  3739. return Result;
  3740. case llvm::BitstreamEntry::Record:
  3741. // The interesting case.
  3742. break;
  3743. }
  3744. // Read and process a record.
  3745. Record.clear();
  3746. switch (
  3747. (UnhashedControlBlockRecordTypes)Stream.readRecord(Entry.ID, Record)) {
  3748. case SIGNATURE:
  3749. if (F)
  3750. std::copy(Record.begin(), Record.end(), F->Signature.data());
  3751. break;
  3752. case DIAGNOSTIC_OPTIONS: {
  3753. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
  3754. if (Listener && ValidateDiagnosticOptions &&
  3755. !AllowCompatibleConfigurationMismatch &&
  3756. ParseDiagnosticOptions(Record, Complain, *Listener))
  3757. Result = OutOfDate; // Don't return early. Read the signature.
  3758. break;
  3759. }
  3760. case DIAG_PRAGMA_MAPPINGS:
  3761. if (!F)
  3762. break;
  3763. if (F->PragmaDiagMappings.empty())
  3764. F->PragmaDiagMappings.swap(Record);
  3765. else
  3766. F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
  3767. Record.begin(), Record.end());
  3768. break;
  3769. }
  3770. }
  3771. }
  3772. /// Parse a record and blob containing module file extension metadata.
  3773. static bool parseModuleFileExtensionMetadata(
  3774. const SmallVectorImpl<uint64_t> &Record,
  3775. StringRef Blob,
  3776. ModuleFileExtensionMetadata &Metadata) {
  3777. if (Record.size() < 4) return true;
  3778. Metadata.MajorVersion = Record[0];
  3779. Metadata.MinorVersion = Record[1];
  3780. unsigned BlockNameLen = Record[2];
  3781. unsigned UserInfoLen = Record[3];
  3782. if (BlockNameLen + UserInfoLen > Blob.size()) return true;
  3783. Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
  3784. Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
  3785. Blob.data() + BlockNameLen + UserInfoLen);
  3786. return false;
  3787. }
  3788. ASTReader::ASTReadResult ASTReader::ReadExtensionBlock(ModuleFile &F) {
  3789. BitstreamCursor &Stream = F.Stream;
  3790. RecordData Record;
  3791. while (true) {
  3792. llvm::BitstreamEntry Entry = Stream.advance();
  3793. switch (Entry.Kind) {
  3794. case llvm::BitstreamEntry::SubBlock:
  3795. if (Stream.SkipBlock())
  3796. return Failure;
  3797. continue;
  3798. case llvm::BitstreamEntry::EndBlock:
  3799. return Success;
  3800. case llvm::BitstreamEntry::Error:
  3801. return HadErrors;
  3802. case llvm::BitstreamEntry::Record:
  3803. break;
  3804. }
  3805. Record.clear();
  3806. StringRef Blob;
  3807. unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
  3808. switch (RecCode) {
  3809. case EXTENSION_METADATA: {
  3810. ModuleFileExtensionMetadata Metadata;
  3811. if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
  3812. return Failure;
  3813. // Find a module file extension with this block name.
  3814. auto Known = ModuleFileExtensions.find(Metadata.BlockName);
  3815. if (Known == ModuleFileExtensions.end()) break;
  3816. // Form a reader.
  3817. if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
  3818. F, Stream)) {
  3819. F.ExtensionReaders.push_back(std::move(Reader));
  3820. }
  3821. break;
  3822. }
  3823. }
  3824. }
  3825. return Success;
  3826. }
  3827. void ASTReader::InitializeContext() {
  3828. assert(ContextObj && "no context to initialize");
  3829. ASTContext &Context = *ContextObj;
  3830. // If there's a listener, notify them that we "read" the translation unit.
  3831. if (DeserializationListener)
  3832. DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
  3833. Context.getTranslationUnitDecl());
  3834. // FIXME: Find a better way to deal with collisions between these
  3835. // built-in types. Right now, we just ignore the problem.
  3836. // Load the special types.
  3837. if (SpecialTypes.size() >= NumSpecialTypeIDs) {
  3838. if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
  3839. if (!Context.CFConstantStringTypeDecl)
  3840. Context.setCFConstantStringType(GetType(String));
  3841. }
  3842. if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
  3843. QualType FileType = GetType(File);
  3844. if (FileType.isNull()) {
  3845. Error("FILE type is NULL");
  3846. return;
  3847. }
  3848. if (!Context.FILEDecl) {
  3849. if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
  3850. Context.setFILEDecl(Typedef->getDecl());
  3851. else {
  3852. const TagType *Tag = FileType->getAs<TagType>();
  3853. if (!Tag) {
  3854. Error("Invalid FILE type in AST file");
  3855. return;
  3856. }
  3857. Context.setFILEDecl(Tag->getDecl());
  3858. }
  3859. }
  3860. }
  3861. if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
  3862. QualType Jmp_bufType = GetType(Jmp_buf);
  3863. if (Jmp_bufType.isNull()) {
  3864. Error("jmp_buf type is NULL");
  3865. return;
  3866. }
  3867. if (!Context.jmp_bufDecl) {
  3868. if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
  3869. Context.setjmp_bufDecl(Typedef->getDecl());
  3870. else {
  3871. const TagType *Tag = Jmp_bufType->getAs<TagType>();
  3872. if (!Tag) {
  3873. Error("Invalid jmp_buf type in AST file");
  3874. return;
  3875. }
  3876. Context.setjmp_bufDecl(Tag->getDecl());
  3877. }
  3878. }
  3879. }
  3880. if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
  3881. QualType Sigjmp_bufType = GetType(Sigjmp_buf);
  3882. if (Sigjmp_bufType.isNull()) {
  3883. Error("sigjmp_buf type is NULL");
  3884. return;
  3885. }
  3886. if (!Context.sigjmp_bufDecl) {
  3887. if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
  3888. Context.setsigjmp_bufDecl(Typedef->getDecl());
  3889. else {
  3890. const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
  3891. assert(Tag && "Invalid sigjmp_buf type in AST file");
  3892. Context.setsigjmp_bufDecl(Tag->getDecl());
  3893. }
  3894. }
  3895. }
  3896. if (unsigned ObjCIdRedef
  3897. = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
  3898. if (Context.ObjCIdRedefinitionType.isNull())
  3899. Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
  3900. }
  3901. if (unsigned ObjCClassRedef
  3902. = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
  3903. if (Context.ObjCClassRedefinitionType.isNull())
  3904. Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
  3905. }
  3906. if (unsigned ObjCSelRedef
  3907. = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
  3908. if (Context.ObjCSelRedefinitionType.isNull())
  3909. Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
  3910. }
  3911. if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
  3912. QualType Ucontext_tType = GetType(Ucontext_t);
  3913. if (Ucontext_tType.isNull()) {
  3914. Error("ucontext_t type is NULL");
  3915. return;
  3916. }
  3917. if (!Context.ucontext_tDecl) {
  3918. if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
  3919. Context.setucontext_tDecl(Typedef->getDecl());
  3920. else {
  3921. const TagType *Tag = Ucontext_tType->getAs<TagType>();
  3922. assert(Tag && "Invalid ucontext_t type in AST file");
  3923. Context.setucontext_tDecl(Tag->getDecl());
  3924. }
  3925. }
  3926. }
  3927. }
  3928. ReadPragmaDiagnosticMappings(Context.getDiagnostics());
  3929. // If there were any CUDA special declarations, deserialize them.
  3930. if (!CUDASpecialDeclRefs.empty()) {
  3931. assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
  3932. Context.setcudaConfigureCallDecl(
  3933. cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
  3934. }
  3935. // Re-export any modules that were imported by a non-module AST file.
  3936. // FIXME: This does not make macro-only imports visible again.
  3937. for (auto &Import : ImportedModules) {
  3938. if (Module *Imported = getSubmodule(Import.ID)) {
  3939. makeModuleVisible(Imported, Module::AllVisible,
  3940. /*ImportLoc=*/Import.ImportLoc);
  3941. if (Import.ImportLoc.isValid())
  3942. PP.makeModuleVisible(Imported, Import.ImportLoc);
  3943. // FIXME: should we tell Sema to make the module visible too?
  3944. }
  3945. }
  3946. ImportedModules.clear();
  3947. }
  3948. void ASTReader::finalizeForWriting() {
  3949. // Nothing to do for now.
  3950. }
  3951. /// \brief Reads and return the signature record from \p PCH's control block, or
  3952. /// else returns 0.
  3953. static ASTFileSignature readASTFileSignature(StringRef PCH) {
  3954. BitstreamCursor Stream(PCH);
  3955. if (!startsWithASTFileMagic(Stream))
  3956. return ASTFileSignature();
  3957. // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
  3958. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
  3959. return ASTFileSignature();
  3960. // Scan for SIGNATURE inside the diagnostic options block.
  3961. ASTReader::RecordData Record;
  3962. while (true) {
  3963. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3964. if (Entry.Kind != llvm::BitstreamEntry::Record)
  3965. return ASTFileSignature();
  3966. Record.clear();
  3967. StringRef Blob;
  3968. if (SIGNATURE == Stream.readRecord(Entry.ID, Record, &Blob))
  3969. return {{{(uint32_t)Record[0], (uint32_t)Record[1], (uint32_t)Record[2],
  3970. (uint32_t)Record[3], (uint32_t)Record[4]}}};
  3971. }
  3972. }
  3973. /// \brief Retrieve the name of the original source file name
  3974. /// directly from the AST file, without actually loading the AST
  3975. /// file.
  3976. std::string ASTReader::getOriginalSourceFile(
  3977. const std::string &ASTFileName, FileManager &FileMgr,
  3978. const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
  3979. // Open the AST file.
  3980. auto Buffer = FileMgr.getBufferForFile(ASTFileName);
  3981. if (!Buffer) {
  3982. Diags.Report(diag::err_fe_unable_to_read_pch_file)
  3983. << ASTFileName << Buffer.getError().message();
  3984. return std::string();
  3985. }
  3986. // Initialize the stream
  3987. BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
  3988. // Sniff for the signature.
  3989. if (!startsWithASTFileMagic(Stream)) {
  3990. Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName;
  3991. return std::string();
  3992. }
  3993. // Scan for the CONTROL_BLOCK_ID block.
  3994. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
  3995. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  3996. return std::string();
  3997. }
  3998. // Scan for ORIGINAL_FILE inside the control block.
  3999. RecordData Record;
  4000. while (true) {
  4001. llvm::BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  4002. if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
  4003. return std::string();
  4004. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  4005. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  4006. return std::string();
  4007. }
  4008. Record.clear();
  4009. StringRef Blob;
  4010. if (Stream.readRecord(Entry.ID, Record, &Blob) == ORIGINAL_FILE)
  4011. return Blob.str();
  4012. }
  4013. }
  4014. namespace {
  4015. class SimplePCHValidator : public ASTReaderListener {
  4016. const LangOptions &ExistingLangOpts;
  4017. const TargetOptions &ExistingTargetOpts;
  4018. const PreprocessorOptions &ExistingPPOpts;
  4019. std::string ExistingModuleCachePath;
  4020. FileManager &FileMgr;
  4021. public:
  4022. SimplePCHValidator(const LangOptions &ExistingLangOpts,
  4023. const TargetOptions &ExistingTargetOpts,
  4024. const PreprocessorOptions &ExistingPPOpts,
  4025. StringRef ExistingModuleCachePath,
  4026. FileManager &FileMgr)
  4027. : ExistingLangOpts(ExistingLangOpts),
  4028. ExistingTargetOpts(ExistingTargetOpts),
  4029. ExistingPPOpts(ExistingPPOpts),
  4030. ExistingModuleCachePath(ExistingModuleCachePath),
  4031. FileMgr(FileMgr) {}
  4032. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  4033. bool AllowCompatibleDifferences) override {
  4034. return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
  4035. AllowCompatibleDifferences);
  4036. }
  4037. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  4038. bool AllowCompatibleDifferences) override {
  4039. return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
  4040. AllowCompatibleDifferences);
  4041. }
  4042. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  4043. StringRef SpecificModuleCachePath,
  4044. bool Complain) override {
  4045. return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  4046. ExistingModuleCachePath,
  4047. nullptr, ExistingLangOpts);
  4048. }
  4049. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  4050. bool Complain,
  4051. std::string &SuggestedPredefines) override {
  4052. return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
  4053. SuggestedPredefines, ExistingLangOpts);
  4054. }
  4055. };
  4056. } // namespace
  4057. bool ASTReader::readASTFileControlBlock(
  4058. StringRef Filename, FileManager &FileMgr,
  4059. const PCHContainerReader &PCHContainerRdr,
  4060. bool FindModuleFileExtensions,
  4061. ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
  4062. // Open the AST file.
  4063. // FIXME: This allows use of the VFS; we do not allow use of the
  4064. // VFS when actually loading a module.
  4065. auto Buffer = FileMgr.getBufferForFile(Filename);
  4066. if (!Buffer) {
  4067. return true;
  4068. }
  4069. // Initialize the stream
  4070. StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
  4071. BitstreamCursor Stream(Bytes);
  4072. // Sniff for the signature.
  4073. if (!startsWithASTFileMagic(Stream))
  4074. return true;
  4075. // Scan for the CONTROL_BLOCK_ID block.
  4076. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
  4077. return true;
  4078. bool NeedsInputFiles = Listener.needsInputFileVisitation();
  4079. bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
  4080. bool NeedsImports = Listener.needsImportVisitation();
  4081. BitstreamCursor InputFilesCursor;
  4082. RecordData Record;
  4083. std::string ModuleDir;
  4084. bool DoneWithControlBlock = false;
  4085. while (!DoneWithControlBlock) {
  4086. llvm::BitstreamEntry Entry = Stream.advance();
  4087. switch (Entry.Kind) {
  4088. case llvm::BitstreamEntry::SubBlock: {
  4089. switch (Entry.ID) {
  4090. case OPTIONS_BLOCK_ID: {
  4091. std::string IgnoredSuggestedPredefines;
  4092. if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
  4093. /*AllowCompatibleConfigurationMismatch*/ false,
  4094. Listener, IgnoredSuggestedPredefines) != Success)
  4095. return true;
  4096. break;
  4097. }
  4098. case INPUT_FILES_BLOCK_ID:
  4099. InputFilesCursor = Stream;
  4100. if (Stream.SkipBlock() ||
  4101. (NeedsInputFiles &&
  4102. ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID)))
  4103. return true;
  4104. break;
  4105. default:
  4106. if (Stream.SkipBlock())
  4107. return true;
  4108. break;
  4109. }
  4110. continue;
  4111. }
  4112. case llvm::BitstreamEntry::EndBlock:
  4113. DoneWithControlBlock = true;
  4114. break;
  4115. case llvm::BitstreamEntry::Error:
  4116. return true;
  4117. case llvm::BitstreamEntry::Record:
  4118. break;
  4119. }
  4120. if (DoneWithControlBlock) break;
  4121. Record.clear();
  4122. StringRef Blob;
  4123. unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
  4124. switch ((ControlRecordTypes)RecCode) {
  4125. case METADATA:
  4126. if (Record[0] != VERSION_MAJOR)
  4127. return true;
  4128. if (Listener.ReadFullVersionInformation(Blob))
  4129. return true;
  4130. break;
  4131. case MODULE_NAME:
  4132. Listener.ReadModuleName(Blob);
  4133. break;
  4134. case MODULE_DIRECTORY:
  4135. ModuleDir = Blob;
  4136. break;
  4137. case MODULE_MAP_FILE: {
  4138. unsigned Idx = 0;
  4139. auto Path = ReadString(Record, Idx);
  4140. ResolveImportedPath(Path, ModuleDir);
  4141. Listener.ReadModuleMapFile(Path);
  4142. break;
  4143. }
  4144. case INPUT_FILE_OFFSETS: {
  4145. if (!NeedsInputFiles)
  4146. break;
  4147. unsigned NumInputFiles = Record[0];
  4148. unsigned NumUserFiles = Record[1];
  4149. const uint64_t *InputFileOffs = (const uint64_t *)Blob.data();
  4150. for (unsigned I = 0; I != NumInputFiles; ++I) {
  4151. // Go find this input file.
  4152. bool isSystemFile = I >= NumUserFiles;
  4153. if (isSystemFile && !NeedsSystemInputFiles)
  4154. break; // the rest are system input files
  4155. BitstreamCursor &Cursor = InputFilesCursor;
  4156. SavedStreamPosition SavedPosition(Cursor);
  4157. Cursor.JumpToBit(InputFileOffs[I]);
  4158. unsigned Code = Cursor.ReadCode();
  4159. RecordData Record;
  4160. StringRef Blob;
  4161. bool shouldContinue = false;
  4162. switch ((InputFileRecordTypes)Cursor.readRecord(Code, Record, &Blob)) {
  4163. case INPUT_FILE:
  4164. bool Overridden = static_cast<bool>(Record[3]);
  4165. std::string Filename = Blob;
  4166. ResolveImportedPath(Filename, ModuleDir);
  4167. shouldContinue = Listener.visitInputFile(
  4168. Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
  4169. break;
  4170. }
  4171. if (!shouldContinue)
  4172. break;
  4173. }
  4174. break;
  4175. }
  4176. case IMPORTS: {
  4177. if (!NeedsImports)
  4178. break;
  4179. unsigned Idx = 0, N = Record.size();
  4180. while (Idx < N) {
  4181. // Read information about the AST file.
  4182. Idx += 5; // ImportLoc, Size, ModTime, Signature
  4183. SkipString(Record, Idx); // Module name; FIXME: pass to listener?
  4184. std::string Filename = ReadString(Record, Idx);
  4185. ResolveImportedPath(Filename, ModuleDir);
  4186. Listener.visitImport(Filename);
  4187. }
  4188. break;
  4189. }
  4190. default:
  4191. // No other validation to perform.
  4192. break;
  4193. }
  4194. }
  4195. // Look for module file extension blocks, if requested.
  4196. if (FindModuleFileExtensions) {
  4197. BitstreamCursor SavedStream = Stream;
  4198. while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
  4199. bool DoneWithExtensionBlock = false;
  4200. while (!DoneWithExtensionBlock) {
  4201. llvm::BitstreamEntry Entry = Stream.advance();
  4202. switch (Entry.Kind) {
  4203. case llvm::BitstreamEntry::SubBlock:
  4204. if (Stream.SkipBlock())
  4205. return true;
  4206. continue;
  4207. case llvm::BitstreamEntry::EndBlock:
  4208. DoneWithExtensionBlock = true;
  4209. continue;
  4210. case llvm::BitstreamEntry::Error:
  4211. return true;
  4212. case llvm::BitstreamEntry::Record:
  4213. break;
  4214. }
  4215. Record.clear();
  4216. StringRef Blob;
  4217. unsigned RecCode = Stream.readRecord(Entry.ID, Record, &Blob);
  4218. switch (RecCode) {
  4219. case EXTENSION_METADATA: {
  4220. ModuleFileExtensionMetadata Metadata;
  4221. if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
  4222. return true;
  4223. Listener.readModuleFileExtension(Metadata);
  4224. break;
  4225. }
  4226. }
  4227. }
  4228. }
  4229. Stream = SavedStream;
  4230. }
  4231. // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
  4232. if (readUnhashedControlBlockImpl(
  4233. nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
  4234. /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
  4235. ValidateDiagnosticOptions) != Success)
  4236. return true;
  4237. return false;
  4238. }
  4239. bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
  4240. const PCHContainerReader &PCHContainerRdr,
  4241. const LangOptions &LangOpts,
  4242. const TargetOptions &TargetOpts,
  4243. const PreprocessorOptions &PPOpts,
  4244. StringRef ExistingModuleCachePath) {
  4245. SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
  4246. ExistingModuleCachePath, FileMgr);
  4247. return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
  4248. /*FindModuleFileExtensions=*/false,
  4249. validator,
  4250. /*ValidateDiagnosticOptions=*/true);
  4251. }
  4252. ASTReader::ASTReadResult
  4253. ASTReader::ReadSubmoduleBlock(ModuleFile &F, unsigned ClientLoadCapabilities) {
  4254. // Enter the submodule block.
  4255. if (F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID)) {
  4256. Error("malformed submodule block record in AST file");
  4257. return Failure;
  4258. }
  4259. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  4260. bool First = true;
  4261. Module *CurrentModule = nullptr;
  4262. RecordData Record;
  4263. while (true) {
  4264. llvm::BitstreamEntry Entry = F.Stream.advanceSkippingSubblocks();
  4265. switch (Entry.Kind) {
  4266. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  4267. case llvm::BitstreamEntry::Error:
  4268. Error("malformed block record in AST file");
  4269. return Failure;
  4270. case llvm::BitstreamEntry::EndBlock:
  4271. return Success;
  4272. case llvm::BitstreamEntry::Record:
  4273. // The interesting case.
  4274. break;
  4275. }
  4276. // Read a record.
  4277. StringRef Blob;
  4278. Record.clear();
  4279. auto Kind = F.Stream.readRecord(Entry.ID, Record, &Blob);
  4280. if ((Kind == SUBMODULE_METADATA) != First) {
  4281. Error("submodule metadata record should be at beginning of block");
  4282. return Failure;
  4283. }
  4284. First = false;
  4285. // Submodule information is only valid if we have a current module.
  4286. // FIXME: Should we error on these cases?
  4287. if (!CurrentModule && Kind != SUBMODULE_METADATA &&
  4288. Kind != SUBMODULE_DEFINITION)
  4289. continue;
  4290. switch (Kind) {
  4291. default: // Default behavior: ignore.
  4292. break;
  4293. case SUBMODULE_DEFINITION: {
  4294. if (Record.size() < 8) {
  4295. Error("malformed module definition");
  4296. return Failure;
  4297. }
  4298. StringRef Name = Blob;
  4299. unsigned Idx = 0;
  4300. SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
  4301. SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
  4302. Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
  4303. bool IsFramework = Record[Idx++];
  4304. bool IsExplicit = Record[Idx++];
  4305. bool IsSystem = Record[Idx++];
  4306. bool IsExternC = Record[Idx++];
  4307. bool InferSubmodules = Record[Idx++];
  4308. bool InferExplicitSubmodules = Record[Idx++];
  4309. bool InferExportWildcard = Record[Idx++];
  4310. bool ConfigMacrosExhaustive = Record[Idx++];
  4311. Module *ParentModule = nullptr;
  4312. if (Parent)
  4313. ParentModule = getSubmodule(Parent);
  4314. // Retrieve this (sub)module from the module map, creating it if
  4315. // necessary.
  4316. CurrentModule =
  4317. ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
  4318. .first;
  4319. // FIXME: set the definition loc for CurrentModule, or call
  4320. // ModMap.setInferredModuleAllowedBy()
  4321. SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
  4322. if (GlobalIndex >= SubmodulesLoaded.size() ||
  4323. SubmodulesLoaded[GlobalIndex]) {
  4324. Error("too many submodules");
  4325. return Failure;
  4326. }
  4327. if (!ParentModule) {
  4328. if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
  4329. if (CurFile != F.File) {
  4330. if (!Diags.isDiagnosticInFlight()) {
  4331. Diag(diag::err_module_file_conflict)
  4332. << CurrentModule->getTopLevelModuleName()
  4333. << CurFile->getName()
  4334. << F.File->getName();
  4335. }
  4336. return Failure;
  4337. }
  4338. }
  4339. CurrentModule->setASTFile(F.File);
  4340. CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
  4341. }
  4342. CurrentModule->Kind = Kind;
  4343. CurrentModule->Signature = F.Signature;
  4344. CurrentModule->IsFromModuleFile = true;
  4345. CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
  4346. CurrentModule->IsExternC = IsExternC;
  4347. CurrentModule->InferSubmodules = InferSubmodules;
  4348. CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
  4349. CurrentModule->InferExportWildcard = InferExportWildcard;
  4350. CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
  4351. if (DeserializationListener)
  4352. DeserializationListener->ModuleRead(GlobalID, CurrentModule);
  4353. SubmodulesLoaded[GlobalIndex] = CurrentModule;
  4354. // Clear out data that will be replaced by what is in the module file.
  4355. CurrentModule->LinkLibraries.clear();
  4356. CurrentModule->ConfigMacros.clear();
  4357. CurrentModule->UnresolvedConflicts.clear();
  4358. CurrentModule->Conflicts.clear();
  4359. // The module is available unless it's missing a requirement; relevant
  4360. // requirements will be (re-)added by SUBMODULE_REQUIRES records.
  4361. // Missing headers that were present when the module was built do not
  4362. // make it unavailable -- if we got this far, this must be an explicitly
  4363. // imported module file.
  4364. CurrentModule->Requirements.clear();
  4365. CurrentModule->MissingHeaders.clear();
  4366. CurrentModule->IsMissingRequirement =
  4367. ParentModule && ParentModule->IsMissingRequirement;
  4368. CurrentModule->IsAvailable = !CurrentModule->IsMissingRequirement;
  4369. break;
  4370. }
  4371. case SUBMODULE_UMBRELLA_HEADER: {
  4372. std::string Filename = Blob;
  4373. ResolveImportedPath(F, Filename);
  4374. if (auto *Umbrella = PP.getFileManager().getFile(Filename)) {
  4375. if (!CurrentModule->getUmbrellaHeader())
  4376. ModMap.setUmbrellaHeader(CurrentModule, Umbrella, Blob);
  4377. else if (CurrentModule->getUmbrellaHeader().Entry != Umbrella) {
  4378. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  4379. Error("mismatched umbrella headers in submodule");
  4380. return OutOfDate;
  4381. }
  4382. }
  4383. break;
  4384. }
  4385. case SUBMODULE_HEADER:
  4386. case SUBMODULE_EXCLUDED_HEADER:
  4387. case SUBMODULE_PRIVATE_HEADER:
  4388. // We lazily associate headers with their modules via the HeaderInfo table.
  4389. // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
  4390. // of complete filenames or remove it entirely.
  4391. break;
  4392. case SUBMODULE_TEXTUAL_HEADER:
  4393. case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
  4394. // FIXME: Textual headers are not marked in the HeaderInfo table. Load
  4395. // them here.
  4396. break;
  4397. case SUBMODULE_TOPHEADER:
  4398. CurrentModule->addTopHeaderFilename(Blob);
  4399. break;
  4400. case SUBMODULE_UMBRELLA_DIR: {
  4401. std::string Dirname = Blob;
  4402. ResolveImportedPath(F, Dirname);
  4403. if (auto *Umbrella = PP.getFileManager().getDirectory(Dirname)) {
  4404. if (!CurrentModule->getUmbrellaDir())
  4405. ModMap.setUmbrellaDir(CurrentModule, Umbrella, Blob);
  4406. else if (CurrentModule->getUmbrellaDir().Entry != Umbrella) {
  4407. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  4408. Error("mismatched umbrella directories in submodule");
  4409. return OutOfDate;
  4410. }
  4411. }
  4412. break;
  4413. }
  4414. case SUBMODULE_METADATA: {
  4415. F.BaseSubmoduleID = getTotalNumSubmodules();
  4416. F.LocalNumSubmodules = Record[0];
  4417. unsigned LocalBaseSubmoduleID = Record[1];
  4418. if (F.LocalNumSubmodules > 0) {
  4419. // Introduce the global -> local mapping for submodules within this
  4420. // module.
  4421. GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
  4422. // Introduce the local -> global mapping for submodules within this
  4423. // module.
  4424. F.SubmoduleRemap.insertOrReplace(
  4425. std::make_pair(LocalBaseSubmoduleID,
  4426. F.BaseSubmoduleID - LocalBaseSubmoduleID));
  4427. SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
  4428. }
  4429. break;
  4430. }
  4431. case SUBMODULE_IMPORTS:
  4432. for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
  4433. UnresolvedModuleRef Unresolved;
  4434. Unresolved.File = &F;
  4435. Unresolved.Mod = CurrentModule;
  4436. Unresolved.ID = Record[Idx];
  4437. Unresolved.Kind = UnresolvedModuleRef::Import;
  4438. Unresolved.IsWildcard = false;
  4439. UnresolvedModuleRefs.push_back(Unresolved);
  4440. }
  4441. break;
  4442. case SUBMODULE_EXPORTS:
  4443. for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
  4444. UnresolvedModuleRef Unresolved;
  4445. Unresolved.File = &F;
  4446. Unresolved.Mod = CurrentModule;
  4447. Unresolved.ID = Record[Idx];
  4448. Unresolved.Kind = UnresolvedModuleRef::Export;
  4449. Unresolved.IsWildcard = Record[Idx + 1];
  4450. UnresolvedModuleRefs.push_back(Unresolved);
  4451. }
  4452. // Once we've loaded the set of exports, there's no reason to keep
  4453. // the parsed, unresolved exports around.
  4454. CurrentModule->UnresolvedExports.clear();
  4455. break;
  4456. case SUBMODULE_REQUIRES:
  4457. CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
  4458. PP.getTargetInfo());
  4459. break;
  4460. case SUBMODULE_LINK_LIBRARY:
  4461. CurrentModule->LinkLibraries.push_back(
  4462. Module::LinkLibrary(Blob, Record[0]));
  4463. break;
  4464. case SUBMODULE_CONFIG_MACRO:
  4465. CurrentModule->ConfigMacros.push_back(Blob.str());
  4466. break;
  4467. case SUBMODULE_CONFLICT: {
  4468. UnresolvedModuleRef Unresolved;
  4469. Unresolved.File = &F;
  4470. Unresolved.Mod = CurrentModule;
  4471. Unresolved.ID = Record[0];
  4472. Unresolved.Kind = UnresolvedModuleRef::Conflict;
  4473. Unresolved.IsWildcard = false;
  4474. Unresolved.String = Blob;
  4475. UnresolvedModuleRefs.push_back(Unresolved);
  4476. break;
  4477. }
  4478. case SUBMODULE_INITIALIZERS: {
  4479. if (!ContextObj)
  4480. break;
  4481. SmallVector<uint32_t, 16> Inits;
  4482. for (auto &ID : Record)
  4483. Inits.push_back(getGlobalDeclID(F, ID));
  4484. ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
  4485. break;
  4486. }
  4487. case SUBMODULE_EXPORT_AS:
  4488. CurrentModule->ExportAsModule = Blob.str();
  4489. break;
  4490. }
  4491. }
  4492. }
  4493. /// \brief Parse the record that corresponds to a LangOptions data
  4494. /// structure.
  4495. ///
  4496. /// This routine parses the language options from the AST file and then gives
  4497. /// them to the AST listener if one is set.
  4498. ///
  4499. /// \returns true if the listener deems the file unacceptable, false otherwise.
  4500. bool ASTReader::ParseLanguageOptions(const RecordData &Record,
  4501. bool Complain,
  4502. ASTReaderListener &Listener,
  4503. bool AllowCompatibleDifferences) {
  4504. LangOptions LangOpts;
  4505. unsigned Idx = 0;
  4506. #define LANGOPT(Name, Bits, Default, Description) \
  4507. LangOpts.Name = Record[Idx++];
  4508. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  4509. LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
  4510. #include "clang/Basic/LangOptions.def"
  4511. #define SANITIZER(NAME, ID) \
  4512. LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
  4513. #include "clang/Basic/Sanitizers.def"
  4514. for (unsigned N = Record[Idx++]; N; --N)
  4515. LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
  4516. ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
  4517. VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
  4518. LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
  4519. LangOpts.CurrentModule = ReadString(Record, Idx);
  4520. // Comment options.
  4521. for (unsigned N = Record[Idx++]; N; --N) {
  4522. LangOpts.CommentOpts.BlockCommandNames.push_back(
  4523. ReadString(Record, Idx));
  4524. }
  4525. LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
  4526. // OpenMP offloading options.
  4527. for (unsigned N = Record[Idx++]; N; --N) {
  4528. LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
  4529. }
  4530. LangOpts.OMPHostIRFile = ReadString(Record, Idx);
  4531. return Listener.ReadLanguageOptions(LangOpts, Complain,
  4532. AllowCompatibleDifferences);
  4533. }
  4534. bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
  4535. ASTReaderListener &Listener,
  4536. bool AllowCompatibleDifferences) {
  4537. unsigned Idx = 0;
  4538. TargetOptions TargetOpts;
  4539. TargetOpts.Triple = ReadString(Record, Idx);
  4540. TargetOpts.CPU = ReadString(Record, Idx);
  4541. TargetOpts.ABI = ReadString(Record, Idx);
  4542. for (unsigned N = Record[Idx++]; N; --N) {
  4543. TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
  4544. }
  4545. for (unsigned N = Record[Idx++]; N; --N) {
  4546. TargetOpts.Features.push_back(ReadString(Record, Idx));
  4547. }
  4548. return Listener.ReadTargetOptions(TargetOpts, Complain,
  4549. AllowCompatibleDifferences);
  4550. }
  4551. bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
  4552. ASTReaderListener &Listener) {
  4553. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
  4554. unsigned Idx = 0;
  4555. #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
  4556. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  4557. DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
  4558. #include "clang/Basic/DiagnosticOptions.def"
  4559. for (unsigned N = Record[Idx++]; N; --N)
  4560. DiagOpts->Warnings.push_back(ReadString(Record, Idx));
  4561. for (unsigned N = Record[Idx++]; N; --N)
  4562. DiagOpts->Remarks.push_back(ReadString(Record, Idx));
  4563. return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
  4564. }
  4565. bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
  4566. ASTReaderListener &Listener) {
  4567. FileSystemOptions FSOpts;
  4568. unsigned Idx = 0;
  4569. FSOpts.WorkingDir = ReadString(Record, Idx);
  4570. return Listener.ReadFileSystemOptions(FSOpts, Complain);
  4571. }
  4572. bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
  4573. bool Complain,
  4574. ASTReaderListener &Listener) {
  4575. HeaderSearchOptions HSOpts;
  4576. unsigned Idx = 0;
  4577. HSOpts.Sysroot = ReadString(Record, Idx);
  4578. // Include entries.
  4579. for (unsigned N = Record[Idx++]; N; --N) {
  4580. std::string Path = ReadString(Record, Idx);
  4581. frontend::IncludeDirGroup Group
  4582. = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
  4583. bool IsFramework = Record[Idx++];
  4584. bool IgnoreSysRoot = Record[Idx++];
  4585. HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
  4586. IgnoreSysRoot);
  4587. }
  4588. // System header prefixes.
  4589. for (unsigned N = Record[Idx++]; N; --N) {
  4590. std::string Prefix = ReadString(Record, Idx);
  4591. bool IsSystemHeader = Record[Idx++];
  4592. HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
  4593. }
  4594. HSOpts.ResourceDir = ReadString(Record, Idx);
  4595. HSOpts.ModuleCachePath = ReadString(Record, Idx);
  4596. HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
  4597. HSOpts.DisableModuleHash = Record[Idx++];
  4598. HSOpts.ImplicitModuleMaps = Record[Idx++];
  4599. HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
  4600. HSOpts.UseBuiltinIncludes = Record[Idx++];
  4601. HSOpts.UseStandardSystemIncludes = Record[Idx++];
  4602. HSOpts.UseStandardCXXIncludes = Record[Idx++];
  4603. HSOpts.UseLibcxx = Record[Idx++];
  4604. std::string SpecificModuleCachePath = ReadString(Record, Idx);
  4605. return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  4606. Complain);
  4607. }
  4608. bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
  4609. bool Complain,
  4610. ASTReaderListener &Listener,
  4611. std::string &SuggestedPredefines) {
  4612. PreprocessorOptions PPOpts;
  4613. unsigned Idx = 0;
  4614. // Macro definitions/undefs
  4615. for (unsigned N = Record[Idx++]; N; --N) {
  4616. std::string Macro = ReadString(Record, Idx);
  4617. bool IsUndef = Record[Idx++];
  4618. PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
  4619. }
  4620. // Includes
  4621. for (unsigned N = Record[Idx++]; N; --N) {
  4622. PPOpts.Includes.push_back(ReadString(Record, Idx));
  4623. }
  4624. // Macro Includes
  4625. for (unsigned N = Record[Idx++]; N; --N) {
  4626. PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
  4627. }
  4628. PPOpts.UsePredefines = Record[Idx++];
  4629. PPOpts.DetailedRecord = Record[Idx++];
  4630. PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
  4631. PPOpts.ImplicitPTHInclude = ReadString(Record, Idx);
  4632. PPOpts.ObjCXXARCStandardLibrary =
  4633. static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
  4634. SuggestedPredefines.clear();
  4635. return Listener.ReadPreprocessorOptions(PPOpts, Complain,
  4636. SuggestedPredefines);
  4637. }
  4638. std::pair<ModuleFile *, unsigned>
  4639. ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
  4640. GlobalPreprocessedEntityMapType::iterator
  4641. I = GlobalPreprocessedEntityMap.find(GlobalIndex);
  4642. assert(I != GlobalPreprocessedEntityMap.end() &&
  4643. "Corrupted global preprocessed entity map");
  4644. ModuleFile *M = I->second;
  4645. unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
  4646. return std::make_pair(M, LocalIndex);
  4647. }
  4648. llvm::iterator_range<PreprocessingRecord::iterator>
  4649. ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
  4650. if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
  4651. return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
  4652. Mod.NumPreprocessedEntities);
  4653. return llvm::make_range(PreprocessingRecord::iterator(),
  4654. PreprocessingRecord::iterator());
  4655. }
  4656. llvm::iterator_range<ASTReader::ModuleDeclIterator>
  4657. ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
  4658. return llvm::make_range(
  4659. ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
  4660. ModuleDeclIterator(this, &Mod,
  4661. Mod.FileSortedDecls + Mod.NumFileSortedDecls));
  4662. }
  4663. PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
  4664. PreprocessedEntityID PPID = Index+1;
  4665. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  4666. ModuleFile &M = *PPInfo.first;
  4667. unsigned LocalIndex = PPInfo.second;
  4668. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  4669. if (!PP.getPreprocessingRecord()) {
  4670. Error("no preprocessing record");
  4671. return nullptr;
  4672. }
  4673. SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
  4674. M.PreprocessorDetailCursor.JumpToBit(PPOffs.BitOffset);
  4675. llvm::BitstreamEntry Entry =
  4676. M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  4677. if (Entry.Kind != llvm::BitstreamEntry::Record)
  4678. return nullptr;
  4679. // Read the record.
  4680. SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
  4681. TranslateSourceLocation(M, PPOffs.getEnd()));
  4682. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  4683. StringRef Blob;
  4684. RecordData Record;
  4685. PreprocessorDetailRecordTypes RecType =
  4686. (PreprocessorDetailRecordTypes)M.PreprocessorDetailCursor.readRecord(
  4687. Entry.ID, Record, &Blob);
  4688. switch (RecType) {
  4689. case PPD_MACRO_EXPANSION: {
  4690. bool isBuiltin = Record[0];
  4691. IdentifierInfo *Name = nullptr;
  4692. MacroDefinitionRecord *Def = nullptr;
  4693. if (isBuiltin)
  4694. Name = getLocalIdentifier(M, Record[1]);
  4695. else {
  4696. PreprocessedEntityID GlobalID =
  4697. getGlobalPreprocessedEntityID(M, Record[1]);
  4698. Def = cast<MacroDefinitionRecord>(
  4699. PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
  4700. }
  4701. MacroExpansion *ME;
  4702. if (isBuiltin)
  4703. ME = new (PPRec) MacroExpansion(Name, Range);
  4704. else
  4705. ME = new (PPRec) MacroExpansion(Def, Range);
  4706. return ME;
  4707. }
  4708. case PPD_MACRO_DEFINITION: {
  4709. // Decode the identifier info and then check again; if the macro is
  4710. // still defined and associated with the identifier,
  4711. IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
  4712. MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
  4713. if (DeserializationListener)
  4714. DeserializationListener->MacroDefinitionRead(PPID, MD);
  4715. return MD;
  4716. }
  4717. case PPD_INCLUSION_DIRECTIVE: {
  4718. const char *FullFileNameStart = Blob.data() + Record[0];
  4719. StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
  4720. const FileEntry *File = nullptr;
  4721. if (!FullFileName.empty())
  4722. File = PP.getFileManager().getFile(FullFileName);
  4723. // FIXME: Stable encoding
  4724. InclusionDirective::InclusionKind Kind
  4725. = static_cast<InclusionDirective::InclusionKind>(Record[2]);
  4726. InclusionDirective *ID
  4727. = new (PPRec) InclusionDirective(PPRec, Kind,
  4728. StringRef(Blob.data(), Record[0]),
  4729. Record[1], Record[3],
  4730. File,
  4731. Range);
  4732. return ID;
  4733. }
  4734. }
  4735. llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
  4736. }
  4737. /// \brief Find the next module that contains entities and return the ID
  4738. /// of the first entry.
  4739. ///
  4740. /// \param SLocMapI points at a chunk of a module that contains no
  4741. /// preprocessed entities or the entities it contains are not the ones we are
  4742. /// looking for.
  4743. PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
  4744. GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
  4745. ++SLocMapI;
  4746. for (GlobalSLocOffsetMapType::const_iterator
  4747. EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
  4748. ModuleFile &M = *SLocMapI->second;
  4749. if (M.NumPreprocessedEntities)
  4750. return M.BasePreprocessedEntityID;
  4751. }
  4752. return getTotalNumPreprocessedEntities();
  4753. }
  4754. namespace {
  4755. struct PPEntityComp {
  4756. const ASTReader &Reader;
  4757. ModuleFile &M;
  4758. PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
  4759. bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
  4760. SourceLocation LHS = getLoc(L);
  4761. SourceLocation RHS = getLoc(R);
  4762. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  4763. }
  4764. bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
  4765. SourceLocation LHS = getLoc(L);
  4766. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  4767. }
  4768. bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
  4769. SourceLocation RHS = getLoc(R);
  4770. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  4771. }
  4772. SourceLocation getLoc(const PPEntityOffset &PPE) const {
  4773. return Reader.TranslateSourceLocation(M, PPE.getBegin());
  4774. }
  4775. };
  4776. } // namespace
  4777. PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
  4778. bool EndsAfter) const {
  4779. if (SourceMgr.isLocalSourceLocation(Loc))
  4780. return getTotalNumPreprocessedEntities();
  4781. GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
  4782. SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
  4783. assert(SLocMapI != GlobalSLocOffsetMap.end() &&
  4784. "Corrupted global sloc offset map");
  4785. if (SLocMapI->second->NumPreprocessedEntities == 0)
  4786. return findNextPreprocessedEntity(SLocMapI);
  4787. ModuleFile &M = *SLocMapI->second;
  4788. using pp_iterator = const PPEntityOffset *;
  4789. pp_iterator pp_begin = M.PreprocessedEntityOffsets;
  4790. pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
  4791. size_t Count = M.NumPreprocessedEntities;
  4792. size_t Half;
  4793. pp_iterator First = pp_begin;
  4794. pp_iterator PPI;
  4795. if (EndsAfter) {
  4796. PPI = std::upper_bound(pp_begin, pp_end, Loc,
  4797. PPEntityComp(*this, M));
  4798. } else {
  4799. // Do a binary search manually instead of using std::lower_bound because
  4800. // The end locations of entities may be unordered (when a macro expansion
  4801. // is inside another macro argument), but for this case it is not important
  4802. // whether we get the first macro expansion or its containing macro.
  4803. while (Count > 0) {
  4804. Half = Count / 2;
  4805. PPI = First;
  4806. std::advance(PPI, Half);
  4807. if (SourceMgr.isBeforeInTranslationUnit(
  4808. TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
  4809. First = PPI;
  4810. ++First;
  4811. Count = Count - Half - 1;
  4812. } else
  4813. Count = Half;
  4814. }
  4815. }
  4816. if (PPI == pp_end)
  4817. return findNextPreprocessedEntity(SLocMapI);
  4818. return M.BasePreprocessedEntityID + (PPI - pp_begin);
  4819. }
  4820. /// \brief Returns a pair of [Begin, End) indices of preallocated
  4821. /// preprocessed entities that \arg Range encompasses.
  4822. std::pair<unsigned, unsigned>
  4823. ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
  4824. if (Range.isInvalid())
  4825. return std::make_pair(0,0);
  4826. assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
  4827. PreprocessedEntityID BeginID =
  4828. findPreprocessedEntity(Range.getBegin(), false);
  4829. PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
  4830. return std::make_pair(BeginID, EndID);
  4831. }
  4832. /// \brief Optionally returns true or false if the preallocated preprocessed
  4833. /// entity with index \arg Index came from file \arg FID.
  4834. Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
  4835. FileID FID) {
  4836. if (FID.isInvalid())
  4837. return false;
  4838. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  4839. ModuleFile &M = *PPInfo.first;
  4840. unsigned LocalIndex = PPInfo.second;
  4841. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  4842. SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
  4843. if (Loc.isInvalid())
  4844. return false;
  4845. if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
  4846. return true;
  4847. else
  4848. return false;
  4849. }
  4850. namespace {
  4851. /// \brief Visitor used to search for information about a header file.
  4852. class HeaderFileInfoVisitor {
  4853. const FileEntry *FE;
  4854. Optional<HeaderFileInfo> HFI;
  4855. public:
  4856. explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
  4857. bool operator()(ModuleFile &M) {
  4858. HeaderFileInfoLookupTable *Table
  4859. = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
  4860. if (!Table)
  4861. return false;
  4862. // Look in the on-disk hash table for an entry for this file name.
  4863. HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
  4864. if (Pos == Table->end())
  4865. return false;
  4866. HFI = *Pos;
  4867. return true;
  4868. }
  4869. Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
  4870. };
  4871. } // namespace
  4872. HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
  4873. HeaderFileInfoVisitor Visitor(FE);
  4874. ModuleMgr.visit(Visitor);
  4875. if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
  4876. return *HFI;
  4877. return HeaderFileInfo();
  4878. }
  4879. void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
  4880. using DiagState = DiagnosticsEngine::DiagState;
  4881. SmallVector<DiagState *, 32> DiagStates;
  4882. for (ModuleFile &F : ModuleMgr) {
  4883. unsigned Idx = 0;
  4884. auto &Record = F.PragmaDiagMappings;
  4885. if (Record.empty())
  4886. continue;
  4887. DiagStates.clear();
  4888. auto ReadDiagState =
  4889. [&](const DiagState &BasedOn, SourceLocation Loc,
  4890. bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
  4891. unsigned BackrefID = Record[Idx++];
  4892. if (BackrefID != 0)
  4893. return DiagStates[BackrefID - 1];
  4894. // A new DiagState was created here.
  4895. Diag.DiagStates.push_back(BasedOn);
  4896. DiagState *NewState = &Diag.DiagStates.back();
  4897. DiagStates.push_back(NewState);
  4898. unsigned Size = Record[Idx++];
  4899. assert(Idx + Size * 2 <= Record.size() &&
  4900. "Invalid data, not enough diag/map pairs");
  4901. while (Size--) {
  4902. unsigned DiagID = Record[Idx++];
  4903. DiagnosticMapping NewMapping =
  4904. DiagnosticMapping::deserialize(Record[Idx++]);
  4905. if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
  4906. continue;
  4907. DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
  4908. // If this mapping was specified as a warning but the severity was
  4909. // upgraded due to diagnostic settings, simulate the current diagnostic
  4910. // settings (and use a warning).
  4911. if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
  4912. NewMapping.setSeverity(diag::Severity::Warning);
  4913. NewMapping.setUpgradedFromWarning(false);
  4914. }
  4915. Mapping = NewMapping;
  4916. }
  4917. return NewState;
  4918. };
  4919. // Read the first state.
  4920. DiagState *FirstState;
  4921. if (F.Kind == MK_ImplicitModule) {
  4922. // Implicitly-built modules are reused with different diagnostic
  4923. // settings. Use the initial diagnostic state from Diag to simulate this
  4924. // compilation's diagnostic settings.
  4925. FirstState = Diag.DiagStatesByLoc.FirstDiagState;
  4926. DiagStates.push_back(FirstState);
  4927. // Skip the initial diagnostic state from the serialized module.
  4928. assert(Record[1] == 0 &&
  4929. "Invalid data, unexpected backref in initial state");
  4930. Idx = 3 + Record[2] * 2;
  4931. assert(Idx < Record.size() &&
  4932. "Invalid data, not enough state change pairs in initial state");
  4933. } else if (F.isModule()) {
  4934. // For an explicit module, preserve the flags from the module build
  4935. // command line (-w, -Weverything, -Werror, ...) along with any explicit
  4936. // -Wblah flags.
  4937. unsigned Flags = Record[Idx++];
  4938. DiagState Initial;
  4939. Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
  4940. Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
  4941. Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
  4942. Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
  4943. Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
  4944. Initial.ExtBehavior = (diag::Severity)Flags;
  4945. FirstState = ReadDiagState(Initial, SourceLocation(), true);
  4946. // Set up the root buffer of the module to start with the initial
  4947. // diagnostic state of the module itself, to cover files that contain no
  4948. // explicit transitions (for which we did not serialize anything).
  4949. Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
  4950. .StateTransitions.push_back({FirstState, 0});
  4951. } else {
  4952. // For prefix ASTs, start with whatever the user configured on the
  4953. // command line.
  4954. Idx++; // Skip flags.
  4955. FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
  4956. SourceLocation(), false);
  4957. }
  4958. // Read the state transitions.
  4959. unsigned NumLocations = Record[Idx++];
  4960. while (NumLocations--) {
  4961. assert(Idx < Record.size() &&
  4962. "Invalid data, missing pragma diagnostic states");
  4963. SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
  4964. auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
  4965. assert(IDAndOffset.second == 0 && "not a start location for a FileID");
  4966. unsigned Transitions = Record[Idx++];
  4967. // Note that we don't need to set up Parent/ParentOffset here, because
  4968. // we won't be changing the diagnostic state within imported FileIDs
  4969. // (other than perhaps appending to the main source file, which has no
  4970. // parent).
  4971. auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
  4972. F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
  4973. for (unsigned I = 0; I != Transitions; ++I) {
  4974. unsigned Offset = Record[Idx++];
  4975. auto *State =
  4976. ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
  4977. F.StateTransitions.push_back({State, Offset});
  4978. }
  4979. }
  4980. // Read the final state.
  4981. assert(Idx < Record.size() &&
  4982. "Invalid data, missing final pragma diagnostic state");
  4983. SourceLocation CurStateLoc =
  4984. ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
  4985. auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
  4986. if (!F.isModule()) {
  4987. Diag.DiagStatesByLoc.CurDiagState = CurState;
  4988. Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
  4989. // Preserve the property that the imaginary root file describes the
  4990. // current state.
  4991. FileID NullFile;
  4992. auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
  4993. if (T.empty())
  4994. T.push_back({CurState, 0});
  4995. else
  4996. T[0].State = CurState;
  4997. }
  4998. // Don't try to read these mappings again.
  4999. Record.clear();
  5000. }
  5001. }
  5002. /// \brief Get the correct cursor and offset for loading a type.
  5003. ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
  5004. GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
  5005. assert(I != GlobalTypeMap.end() && "Corrupted global type map");
  5006. ModuleFile *M = I->second;
  5007. return RecordLocation(M, M->TypeOffsets[Index - M->BaseTypeIndex]);
  5008. }
  5009. /// \brief Read and return the type with the given index..
  5010. ///
  5011. /// The index is the type ID, shifted and minus the number of predefs. This
  5012. /// routine actually reads the record corresponding to the type at the given
  5013. /// location. It is a helper routine for GetType, which deals with reading type
  5014. /// IDs.
  5015. QualType ASTReader::readTypeRecord(unsigned Index) {
  5016. assert(ContextObj && "reading type with no AST context");
  5017. ASTContext &Context = *ContextObj;
  5018. RecordLocation Loc = TypeCursorForIndex(Index);
  5019. BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
  5020. // Keep track of where we are in the stream, then jump back there
  5021. // after reading this type.
  5022. SavedStreamPosition SavedPosition(DeclsCursor);
  5023. ReadingKindTracker ReadingKind(Read_Type, *this);
  5024. // Note that we are loading a type record.
  5025. Deserializing AType(this);
  5026. unsigned Idx = 0;
  5027. DeclsCursor.JumpToBit(Loc.Offset);
  5028. RecordData Record;
  5029. unsigned Code = DeclsCursor.ReadCode();
  5030. switch ((TypeCode)DeclsCursor.readRecord(Code, Record)) {
  5031. case TYPE_EXT_QUAL: {
  5032. if (Record.size() != 2) {
  5033. Error("Incorrect encoding of extended qualifier type");
  5034. return QualType();
  5035. }
  5036. QualType Base = readType(*Loc.F, Record, Idx);
  5037. Qualifiers Quals = Qualifiers::fromOpaqueValue(Record[Idx++]);
  5038. return Context.getQualifiedType(Base, Quals);
  5039. }
  5040. case TYPE_COMPLEX: {
  5041. if (Record.size() != 1) {
  5042. Error("Incorrect encoding of complex type");
  5043. return QualType();
  5044. }
  5045. QualType ElemType = readType(*Loc.F, Record, Idx);
  5046. return Context.getComplexType(ElemType);
  5047. }
  5048. case TYPE_POINTER: {
  5049. if (Record.size() != 1) {
  5050. Error("Incorrect encoding of pointer type");
  5051. return QualType();
  5052. }
  5053. QualType PointeeType = readType(*Loc.F, Record, Idx);
  5054. return Context.getPointerType(PointeeType);
  5055. }
  5056. case TYPE_DECAYED: {
  5057. if (Record.size() != 1) {
  5058. Error("Incorrect encoding of decayed type");
  5059. return QualType();
  5060. }
  5061. QualType OriginalType = readType(*Loc.F, Record, Idx);
  5062. QualType DT = Context.getAdjustedParameterType(OriginalType);
  5063. if (!isa<DecayedType>(DT))
  5064. Error("Decayed type does not decay");
  5065. return DT;
  5066. }
  5067. case TYPE_ADJUSTED: {
  5068. if (Record.size() != 2) {
  5069. Error("Incorrect encoding of adjusted type");
  5070. return QualType();
  5071. }
  5072. QualType OriginalTy = readType(*Loc.F, Record, Idx);
  5073. QualType AdjustedTy = readType(*Loc.F, Record, Idx);
  5074. return Context.getAdjustedType(OriginalTy, AdjustedTy);
  5075. }
  5076. case TYPE_BLOCK_POINTER: {
  5077. if (Record.size() != 1) {
  5078. Error("Incorrect encoding of block pointer type");
  5079. return QualType();
  5080. }
  5081. QualType PointeeType = readType(*Loc.F, Record, Idx);
  5082. return Context.getBlockPointerType(PointeeType);
  5083. }
  5084. case TYPE_LVALUE_REFERENCE: {
  5085. if (Record.size() != 2) {
  5086. Error("Incorrect encoding of lvalue reference type");
  5087. return QualType();
  5088. }
  5089. QualType PointeeType = readType(*Loc.F, Record, Idx);
  5090. return Context.getLValueReferenceType(PointeeType, Record[1]);
  5091. }
  5092. case TYPE_RVALUE_REFERENCE: {
  5093. if (Record.size() != 1) {
  5094. Error("Incorrect encoding of rvalue reference type");
  5095. return QualType();
  5096. }
  5097. QualType PointeeType = readType(*Loc.F, Record, Idx);
  5098. return Context.getRValueReferenceType(PointeeType);
  5099. }
  5100. case TYPE_MEMBER_POINTER: {
  5101. if (Record.size() != 2) {
  5102. Error("Incorrect encoding of member pointer type");
  5103. return QualType();
  5104. }
  5105. QualType PointeeType = readType(*Loc.F, Record, Idx);
  5106. QualType ClassType = readType(*Loc.F, Record, Idx);
  5107. if (PointeeType.isNull() || ClassType.isNull())
  5108. return QualType();
  5109. return Context.getMemberPointerType(PointeeType, ClassType.getTypePtr());
  5110. }
  5111. case TYPE_CONSTANT_ARRAY: {
  5112. QualType ElementType = readType(*Loc.F, Record, Idx);
  5113. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  5114. unsigned IndexTypeQuals = Record[2];
  5115. unsigned Idx = 3;
  5116. llvm::APInt Size = ReadAPInt(Record, Idx);
  5117. return Context.getConstantArrayType(ElementType, Size,
  5118. ASM, IndexTypeQuals);
  5119. }
  5120. case TYPE_INCOMPLETE_ARRAY: {
  5121. QualType ElementType = readType(*Loc.F, Record, Idx);
  5122. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  5123. unsigned IndexTypeQuals = Record[2];
  5124. return Context.getIncompleteArrayType(ElementType, ASM, IndexTypeQuals);
  5125. }
  5126. case TYPE_VARIABLE_ARRAY: {
  5127. QualType ElementType = readType(*Loc.F, Record, Idx);
  5128. ArrayType::ArraySizeModifier ASM = (ArrayType::ArraySizeModifier)Record[1];
  5129. unsigned IndexTypeQuals = Record[2];
  5130. SourceLocation LBLoc = ReadSourceLocation(*Loc.F, Record[3]);
  5131. SourceLocation RBLoc = ReadSourceLocation(*Loc.F, Record[4]);
  5132. return Context.getVariableArrayType(ElementType, ReadExpr(*Loc.F),
  5133. ASM, IndexTypeQuals,
  5134. SourceRange(LBLoc, RBLoc));
  5135. }
  5136. case TYPE_VECTOR: {
  5137. if (Record.size() != 3) {
  5138. Error("incorrect encoding of vector type in AST file");
  5139. return QualType();
  5140. }
  5141. QualType ElementType = readType(*Loc.F, Record, Idx);
  5142. unsigned NumElements = Record[1];
  5143. unsigned VecKind = Record[2];
  5144. return Context.getVectorType(ElementType, NumElements,
  5145. (VectorType::VectorKind)VecKind);
  5146. }
  5147. case TYPE_EXT_VECTOR: {
  5148. if (Record.size() != 3) {
  5149. Error("incorrect encoding of extended vector type in AST file");
  5150. return QualType();
  5151. }
  5152. QualType ElementType = readType(*Loc.F, Record, Idx);
  5153. unsigned NumElements = Record[1];
  5154. return Context.getExtVectorType(ElementType, NumElements);
  5155. }
  5156. case TYPE_FUNCTION_NO_PROTO: {
  5157. if (Record.size() != 7) {
  5158. Error("incorrect encoding of no-proto function type");
  5159. return QualType();
  5160. }
  5161. QualType ResultType = readType(*Loc.F, Record, Idx);
  5162. FunctionType::ExtInfo Info(Record[1], Record[2], Record[3],
  5163. (CallingConv)Record[4], Record[5], Record[6]);
  5164. return Context.getFunctionNoProtoType(ResultType, Info);
  5165. }
  5166. case TYPE_FUNCTION_PROTO: {
  5167. QualType ResultType = readType(*Loc.F, Record, Idx);
  5168. FunctionProtoType::ExtProtoInfo EPI;
  5169. EPI.ExtInfo = FunctionType::ExtInfo(/*noreturn*/ Record[1],
  5170. /*hasregparm*/ Record[2],
  5171. /*regparm*/ Record[3],
  5172. static_cast<CallingConv>(Record[4]),
  5173. /*produces*/ Record[5],
  5174. /*nocallersavedregs*/ Record[6]);
  5175. unsigned Idx = 7;
  5176. EPI.Variadic = Record[Idx++];
  5177. EPI.HasTrailingReturn = Record[Idx++];
  5178. EPI.TypeQuals = Record[Idx++];
  5179. EPI.RefQualifier = static_cast<RefQualifierKind>(Record[Idx++]);
  5180. SmallVector<QualType, 8> ExceptionStorage;
  5181. readExceptionSpec(*Loc.F, ExceptionStorage, EPI.ExceptionSpec, Record, Idx);
  5182. unsigned NumParams = Record[Idx++];
  5183. SmallVector<QualType, 16> ParamTypes;
  5184. for (unsigned I = 0; I != NumParams; ++I)
  5185. ParamTypes.push_back(readType(*Loc.F, Record, Idx));
  5186. SmallVector<FunctionProtoType::ExtParameterInfo, 4> ExtParameterInfos;
  5187. if (Idx != Record.size()) {
  5188. for (unsigned I = 0; I != NumParams; ++I)
  5189. ExtParameterInfos.push_back(
  5190. FunctionProtoType::ExtParameterInfo
  5191. ::getFromOpaqueValue(Record[Idx++]));
  5192. EPI.ExtParameterInfos = ExtParameterInfos.data();
  5193. }
  5194. assert(Idx == Record.size());
  5195. return Context.getFunctionType(ResultType, ParamTypes, EPI);
  5196. }
  5197. case TYPE_UNRESOLVED_USING: {
  5198. unsigned Idx = 0;
  5199. return Context.getTypeDeclType(
  5200. ReadDeclAs<UnresolvedUsingTypenameDecl>(*Loc.F, Record, Idx));
  5201. }
  5202. case TYPE_TYPEDEF: {
  5203. if (Record.size() != 2) {
  5204. Error("incorrect encoding of typedef type");
  5205. return QualType();
  5206. }
  5207. unsigned Idx = 0;
  5208. TypedefNameDecl *Decl = ReadDeclAs<TypedefNameDecl>(*Loc.F, Record, Idx);
  5209. QualType Canonical = readType(*Loc.F, Record, Idx);
  5210. if (!Canonical.isNull())
  5211. Canonical = Context.getCanonicalType(Canonical);
  5212. return Context.getTypedefType(Decl, Canonical);
  5213. }
  5214. case TYPE_TYPEOF_EXPR:
  5215. return Context.getTypeOfExprType(ReadExpr(*Loc.F));
  5216. case TYPE_TYPEOF: {
  5217. if (Record.size() != 1) {
  5218. Error("incorrect encoding of typeof(type) in AST file");
  5219. return QualType();
  5220. }
  5221. QualType UnderlyingType = readType(*Loc.F, Record, Idx);
  5222. return Context.getTypeOfType(UnderlyingType);
  5223. }
  5224. case TYPE_DECLTYPE: {
  5225. QualType UnderlyingType = readType(*Loc.F, Record, Idx);
  5226. return Context.getDecltypeType(ReadExpr(*Loc.F), UnderlyingType);
  5227. }
  5228. case TYPE_UNARY_TRANSFORM: {
  5229. QualType BaseType = readType(*Loc.F, Record, Idx);
  5230. QualType UnderlyingType = readType(*Loc.F, Record, Idx);
  5231. UnaryTransformType::UTTKind UKind = (UnaryTransformType::UTTKind)Record[2];
  5232. return Context.getUnaryTransformType(BaseType, UnderlyingType, UKind);
  5233. }
  5234. case TYPE_AUTO: {
  5235. QualType Deduced = readType(*Loc.F, Record, Idx);
  5236. AutoTypeKeyword Keyword = (AutoTypeKeyword)Record[Idx++];
  5237. bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
  5238. return Context.getAutoType(Deduced, Keyword, IsDependent);
  5239. }
  5240. case TYPE_DEDUCED_TEMPLATE_SPECIALIZATION: {
  5241. TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
  5242. QualType Deduced = readType(*Loc.F, Record, Idx);
  5243. bool IsDependent = Deduced.isNull() ? Record[Idx++] : false;
  5244. return Context.getDeducedTemplateSpecializationType(Name, Deduced,
  5245. IsDependent);
  5246. }
  5247. case TYPE_RECORD: {
  5248. if (Record.size() != 2) {
  5249. Error("incorrect encoding of record type");
  5250. return QualType();
  5251. }
  5252. unsigned Idx = 0;
  5253. bool IsDependent = Record[Idx++];
  5254. RecordDecl *RD = ReadDeclAs<RecordDecl>(*Loc.F, Record, Idx);
  5255. RD = cast_or_null<RecordDecl>(RD->getCanonicalDecl());
  5256. QualType T = Context.getRecordType(RD);
  5257. const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
  5258. return T;
  5259. }
  5260. case TYPE_ENUM: {
  5261. if (Record.size() != 2) {
  5262. Error("incorrect encoding of enum type");
  5263. return QualType();
  5264. }
  5265. unsigned Idx = 0;
  5266. bool IsDependent = Record[Idx++];
  5267. QualType T
  5268. = Context.getEnumType(ReadDeclAs<EnumDecl>(*Loc.F, Record, Idx));
  5269. const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
  5270. return T;
  5271. }
  5272. case TYPE_ATTRIBUTED: {
  5273. if (Record.size() != 3) {
  5274. Error("incorrect encoding of attributed type");
  5275. return QualType();
  5276. }
  5277. QualType modifiedType = readType(*Loc.F, Record, Idx);
  5278. QualType equivalentType = readType(*Loc.F, Record, Idx);
  5279. AttributedType::Kind kind = static_cast<AttributedType::Kind>(Record[2]);
  5280. return Context.getAttributedType(kind, modifiedType, equivalentType);
  5281. }
  5282. case TYPE_PAREN: {
  5283. if (Record.size() != 1) {
  5284. Error("incorrect encoding of paren type");
  5285. return QualType();
  5286. }
  5287. QualType InnerType = readType(*Loc.F, Record, Idx);
  5288. return Context.getParenType(InnerType);
  5289. }
  5290. case TYPE_PACK_EXPANSION: {
  5291. if (Record.size() != 2) {
  5292. Error("incorrect encoding of pack expansion type");
  5293. return QualType();
  5294. }
  5295. QualType Pattern = readType(*Loc.F, Record, Idx);
  5296. if (Pattern.isNull())
  5297. return QualType();
  5298. Optional<unsigned> NumExpansions;
  5299. if (Record[1])
  5300. NumExpansions = Record[1] - 1;
  5301. return Context.getPackExpansionType(Pattern, NumExpansions);
  5302. }
  5303. case TYPE_ELABORATED: {
  5304. unsigned Idx = 0;
  5305. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  5306. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
  5307. QualType NamedType = readType(*Loc.F, Record, Idx);
  5308. return Context.getElaboratedType(Keyword, NNS, NamedType);
  5309. }
  5310. case TYPE_OBJC_INTERFACE: {
  5311. unsigned Idx = 0;
  5312. ObjCInterfaceDecl *ItfD
  5313. = ReadDeclAs<ObjCInterfaceDecl>(*Loc.F, Record, Idx);
  5314. return Context.getObjCInterfaceType(ItfD->getCanonicalDecl());
  5315. }
  5316. case TYPE_OBJC_TYPE_PARAM: {
  5317. unsigned Idx = 0;
  5318. ObjCTypeParamDecl *Decl
  5319. = ReadDeclAs<ObjCTypeParamDecl>(*Loc.F, Record, Idx);
  5320. unsigned NumProtos = Record[Idx++];
  5321. SmallVector<ObjCProtocolDecl*, 4> Protos;
  5322. for (unsigned I = 0; I != NumProtos; ++I)
  5323. Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
  5324. return Context.getObjCTypeParamType(Decl, Protos);
  5325. }
  5326. case TYPE_OBJC_OBJECT: {
  5327. unsigned Idx = 0;
  5328. QualType Base = readType(*Loc.F, Record, Idx);
  5329. unsigned NumTypeArgs = Record[Idx++];
  5330. SmallVector<QualType, 4> TypeArgs;
  5331. for (unsigned I = 0; I != NumTypeArgs; ++I)
  5332. TypeArgs.push_back(readType(*Loc.F, Record, Idx));
  5333. unsigned NumProtos = Record[Idx++];
  5334. SmallVector<ObjCProtocolDecl*, 4> Protos;
  5335. for (unsigned I = 0; I != NumProtos; ++I)
  5336. Protos.push_back(ReadDeclAs<ObjCProtocolDecl>(*Loc.F, Record, Idx));
  5337. bool IsKindOf = Record[Idx++];
  5338. return Context.getObjCObjectType(Base, TypeArgs, Protos, IsKindOf);
  5339. }
  5340. case TYPE_OBJC_OBJECT_POINTER: {
  5341. unsigned Idx = 0;
  5342. QualType Pointee = readType(*Loc.F, Record, Idx);
  5343. return Context.getObjCObjectPointerType(Pointee);
  5344. }
  5345. case TYPE_SUBST_TEMPLATE_TYPE_PARM: {
  5346. unsigned Idx = 0;
  5347. QualType Parm = readType(*Loc.F, Record, Idx);
  5348. QualType Replacement = readType(*Loc.F, Record, Idx);
  5349. return Context.getSubstTemplateTypeParmType(
  5350. cast<TemplateTypeParmType>(Parm),
  5351. Context.getCanonicalType(Replacement));
  5352. }
  5353. case TYPE_SUBST_TEMPLATE_TYPE_PARM_PACK: {
  5354. unsigned Idx = 0;
  5355. QualType Parm = readType(*Loc.F, Record, Idx);
  5356. TemplateArgument ArgPack = ReadTemplateArgument(*Loc.F, Record, Idx);
  5357. return Context.getSubstTemplateTypeParmPackType(
  5358. cast<TemplateTypeParmType>(Parm),
  5359. ArgPack);
  5360. }
  5361. case TYPE_INJECTED_CLASS_NAME: {
  5362. CXXRecordDecl *D = ReadDeclAs<CXXRecordDecl>(*Loc.F, Record, Idx);
  5363. QualType TST = readType(*Loc.F, Record, Idx); // probably derivable
  5364. // FIXME: ASTContext::getInjectedClassNameType is not currently suitable
  5365. // for AST reading, too much interdependencies.
  5366. const Type *T = nullptr;
  5367. for (auto *DI = D; DI; DI = DI->getPreviousDecl()) {
  5368. if (const Type *Existing = DI->getTypeForDecl()) {
  5369. T = Existing;
  5370. break;
  5371. }
  5372. }
  5373. if (!T) {
  5374. T = new (Context, TypeAlignment) InjectedClassNameType(D, TST);
  5375. for (auto *DI = D; DI; DI = DI->getPreviousDecl())
  5376. DI->setTypeForDecl(T);
  5377. }
  5378. return QualType(T, 0);
  5379. }
  5380. case TYPE_TEMPLATE_TYPE_PARM: {
  5381. unsigned Idx = 0;
  5382. unsigned Depth = Record[Idx++];
  5383. unsigned Index = Record[Idx++];
  5384. bool Pack = Record[Idx++];
  5385. TemplateTypeParmDecl *D
  5386. = ReadDeclAs<TemplateTypeParmDecl>(*Loc.F, Record, Idx);
  5387. return Context.getTemplateTypeParmType(Depth, Index, Pack, D);
  5388. }
  5389. case TYPE_DEPENDENT_NAME: {
  5390. unsigned Idx = 0;
  5391. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  5392. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
  5393. const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
  5394. QualType Canon = readType(*Loc.F, Record, Idx);
  5395. if (!Canon.isNull())
  5396. Canon = Context.getCanonicalType(Canon);
  5397. return Context.getDependentNameType(Keyword, NNS, Name, Canon);
  5398. }
  5399. case TYPE_DEPENDENT_TEMPLATE_SPECIALIZATION: {
  5400. unsigned Idx = 0;
  5401. ElaboratedTypeKeyword Keyword = (ElaboratedTypeKeyword)Record[Idx++];
  5402. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(*Loc.F, Record, Idx);
  5403. const IdentifierInfo *Name = GetIdentifierInfo(*Loc.F, Record, Idx);
  5404. unsigned NumArgs = Record[Idx++];
  5405. SmallVector<TemplateArgument, 8> Args;
  5406. Args.reserve(NumArgs);
  5407. while (NumArgs--)
  5408. Args.push_back(ReadTemplateArgument(*Loc.F, Record, Idx));
  5409. return Context.getDependentTemplateSpecializationType(Keyword, NNS, Name,
  5410. Args);
  5411. }
  5412. case TYPE_DEPENDENT_SIZED_ARRAY: {
  5413. unsigned Idx = 0;
  5414. // ArrayType
  5415. QualType ElementType = readType(*Loc.F, Record, Idx);
  5416. ArrayType::ArraySizeModifier ASM
  5417. = (ArrayType::ArraySizeModifier)Record[Idx++];
  5418. unsigned IndexTypeQuals = Record[Idx++];
  5419. // DependentSizedArrayType
  5420. Expr *NumElts = ReadExpr(*Loc.F);
  5421. SourceRange Brackets = ReadSourceRange(*Loc.F, Record, Idx);
  5422. return Context.getDependentSizedArrayType(ElementType, NumElts, ASM,
  5423. IndexTypeQuals, Brackets);
  5424. }
  5425. case TYPE_TEMPLATE_SPECIALIZATION: {
  5426. unsigned Idx = 0;
  5427. bool IsDependent = Record[Idx++];
  5428. TemplateName Name = ReadTemplateName(*Loc.F, Record, Idx);
  5429. SmallVector<TemplateArgument, 8> Args;
  5430. ReadTemplateArgumentList(Args, *Loc.F, Record, Idx);
  5431. QualType Underlying = readType(*Loc.F, Record, Idx);
  5432. QualType T;
  5433. if (Underlying.isNull())
  5434. T = Context.getCanonicalTemplateSpecializationType(Name, Args);
  5435. else
  5436. T = Context.getTemplateSpecializationType(Name, Args, Underlying);
  5437. const_cast<Type*>(T.getTypePtr())->setDependent(IsDependent);
  5438. return T;
  5439. }
  5440. case TYPE_ATOMIC: {
  5441. if (Record.size() != 1) {
  5442. Error("Incorrect encoding of atomic type");
  5443. return QualType();
  5444. }
  5445. QualType ValueType = readType(*Loc.F, Record, Idx);
  5446. return Context.getAtomicType(ValueType);
  5447. }
  5448. case TYPE_PIPE: {
  5449. if (Record.size() != 2) {
  5450. Error("Incorrect encoding of pipe type");
  5451. return QualType();
  5452. }
  5453. // Reading the pipe element type.
  5454. QualType ElementType = readType(*Loc.F, Record, Idx);
  5455. unsigned ReadOnly = Record[1];
  5456. return Context.getPipeType(ElementType, ReadOnly);
  5457. }
  5458. case TYPE_DEPENDENT_SIZED_EXT_VECTOR: {
  5459. unsigned Idx = 0;
  5460. // DependentSizedExtVectorType
  5461. QualType ElementType = readType(*Loc.F, Record, Idx);
  5462. Expr *SizeExpr = ReadExpr(*Loc.F);
  5463. SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
  5464. return Context.getDependentSizedExtVectorType(ElementType, SizeExpr,
  5465. AttrLoc);
  5466. }
  5467. case TYPE_DEPENDENT_ADDRESS_SPACE: {
  5468. unsigned Idx = 0;
  5469. // DependentAddressSpaceType
  5470. QualType PointeeType = readType(*Loc.F, Record, Idx);
  5471. Expr *AddrSpaceExpr = ReadExpr(*Loc.F);
  5472. SourceLocation AttrLoc = ReadSourceLocation(*Loc.F, Record, Idx);
  5473. return Context.getDependentAddressSpaceType(PointeeType, AddrSpaceExpr,
  5474. AttrLoc);
  5475. }
  5476. }
  5477. llvm_unreachable("Invalid TypeCode!");
  5478. }
  5479. void ASTReader::readExceptionSpec(ModuleFile &ModuleFile,
  5480. SmallVectorImpl<QualType> &Exceptions,
  5481. FunctionProtoType::ExceptionSpecInfo &ESI,
  5482. const RecordData &Record, unsigned &Idx) {
  5483. ExceptionSpecificationType EST =
  5484. static_cast<ExceptionSpecificationType>(Record[Idx++]);
  5485. ESI.Type = EST;
  5486. if (EST == EST_Dynamic) {
  5487. for (unsigned I = 0, N = Record[Idx++]; I != N; ++I)
  5488. Exceptions.push_back(readType(ModuleFile, Record, Idx));
  5489. ESI.Exceptions = Exceptions;
  5490. } else if (EST == EST_ComputedNoexcept) {
  5491. ESI.NoexceptExpr = ReadExpr(ModuleFile);
  5492. } else if (EST == EST_Uninstantiated) {
  5493. ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
  5494. ESI.SourceTemplate = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
  5495. } else if (EST == EST_Unevaluated) {
  5496. ESI.SourceDecl = ReadDeclAs<FunctionDecl>(ModuleFile, Record, Idx);
  5497. }
  5498. }
  5499. namespace clang {
  5500. class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
  5501. ModuleFile *F;
  5502. ASTReader *Reader;
  5503. const ASTReader::RecordData &Record;
  5504. unsigned &Idx;
  5505. SourceLocation ReadSourceLocation() {
  5506. return Reader->ReadSourceLocation(*F, Record, Idx);
  5507. }
  5508. TypeSourceInfo *GetTypeSourceInfo() {
  5509. return Reader->GetTypeSourceInfo(*F, Record, Idx);
  5510. }
  5511. NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
  5512. return Reader->ReadNestedNameSpecifierLoc(*F, Record, Idx);
  5513. }
  5514. public:
  5515. TypeLocReader(ModuleFile &F, ASTReader &Reader,
  5516. const ASTReader::RecordData &Record, unsigned &Idx)
  5517. : F(&F), Reader(&Reader), Record(Record), Idx(Idx) {}
  5518. // We want compile-time assurance that we've enumerated all of
  5519. // these, so unfortunately we have to declare them first, then
  5520. // define them out-of-line.
  5521. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  5522. #define TYPELOC(CLASS, PARENT) \
  5523. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  5524. #include "clang/AST/TypeLocNodes.def"
  5525. void VisitFunctionTypeLoc(FunctionTypeLoc);
  5526. void VisitArrayTypeLoc(ArrayTypeLoc);
  5527. };
  5528. } // namespace clang
  5529. void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  5530. // nothing to do
  5531. }
  5532. void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  5533. TL.setBuiltinLoc(ReadSourceLocation());
  5534. if (TL.needsExtraLocalData()) {
  5535. TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Record[Idx++]));
  5536. TL.setWrittenSignSpec(static_cast<DeclSpec::TSS>(Record[Idx++]));
  5537. TL.setWrittenWidthSpec(static_cast<DeclSpec::TSW>(Record[Idx++]));
  5538. TL.setModeAttr(Record[Idx++]);
  5539. }
  5540. }
  5541. void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  5542. TL.setNameLoc(ReadSourceLocation());
  5543. }
  5544. void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
  5545. TL.setStarLoc(ReadSourceLocation());
  5546. }
  5547. void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  5548. // nothing to do
  5549. }
  5550. void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  5551. // nothing to do
  5552. }
  5553. void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  5554. TL.setCaretLoc(ReadSourceLocation());
  5555. }
  5556. void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  5557. TL.setAmpLoc(ReadSourceLocation());
  5558. }
  5559. void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  5560. TL.setAmpAmpLoc(ReadSourceLocation());
  5561. }
  5562. void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  5563. TL.setStarLoc(ReadSourceLocation());
  5564. TL.setClassTInfo(GetTypeSourceInfo());
  5565. }
  5566. void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  5567. TL.setLBracketLoc(ReadSourceLocation());
  5568. TL.setRBracketLoc(ReadSourceLocation());
  5569. if (Record[Idx++])
  5570. TL.setSizeExpr(Reader->ReadExpr(*F));
  5571. else
  5572. TL.setSizeExpr(nullptr);
  5573. }
  5574. void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  5575. VisitArrayTypeLoc(TL);
  5576. }
  5577. void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  5578. VisitArrayTypeLoc(TL);
  5579. }
  5580. void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  5581. VisitArrayTypeLoc(TL);
  5582. }
  5583. void TypeLocReader::VisitDependentSizedArrayTypeLoc(
  5584. DependentSizedArrayTypeLoc TL) {
  5585. VisitArrayTypeLoc(TL);
  5586. }
  5587. void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
  5588. DependentAddressSpaceTypeLoc TL) {
  5589. TL.setAttrNameLoc(ReadSourceLocation());
  5590. SourceRange range;
  5591. range.setBegin(ReadSourceLocation());
  5592. range.setEnd(ReadSourceLocation());
  5593. TL.setAttrOperandParensRange(range);
  5594. TL.setAttrExprOperand(Reader->ReadExpr(*F));
  5595. }
  5596. void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
  5597. DependentSizedExtVectorTypeLoc TL) {
  5598. TL.setNameLoc(ReadSourceLocation());
  5599. }
  5600. void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
  5601. TL.setNameLoc(ReadSourceLocation());
  5602. }
  5603. void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  5604. TL.setNameLoc(ReadSourceLocation());
  5605. }
  5606. void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  5607. TL.setLocalRangeBegin(ReadSourceLocation());
  5608. TL.setLParenLoc(ReadSourceLocation());
  5609. TL.setRParenLoc(ReadSourceLocation());
  5610. TL.setExceptionSpecRange(SourceRange(Reader->ReadSourceLocation(*F, Record, Idx),
  5611. Reader->ReadSourceLocation(*F, Record, Idx)));
  5612. TL.setLocalRangeEnd(ReadSourceLocation());
  5613. for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
  5614. TL.setParam(i, Reader->ReadDeclAs<ParmVarDecl>(*F, Record, Idx));
  5615. }
  5616. }
  5617. void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  5618. VisitFunctionTypeLoc(TL);
  5619. }
  5620. void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  5621. VisitFunctionTypeLoc(TL);
  5622. }
  5623. void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  5624. TL.setNameLoc(ReadSourceLocation());
  5625. }
  5626. void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  5627. TL.setNameLoc(ReadSourceLocation());
  5628. }
  5629. void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  5630. TL.setTypeofLoc(ReadSourceLocation());
  5631. TL.setLParenLoc(ReadSourceLocation());
  5632. TL.setRParenLoc(ReadSourceLocation());
  5633. }
  5634. void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  5635. TL.setTypeofLoc(ReadSourceLocation());
  5636. TL.setLParenLoc(ReadSourceLocation());
  5637. TL.setRParenLoc(ReadSourceLocation());
  5638. TL.setUnderlyingTInfo(GetTypeSourceInfo());
  5639. }
  5640. void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  5641. TL.setNameLoc(ReadSourceLocation());
  5642. }
  5643. void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  5644. TL.setKWLoc(ReadSourceLocation());
  5645. TL.setLParenLoc(ReadSourceLocation());
  5646. TL.setRParenLoc(ReadSourceLocation());
  5647. TL.setUnderlyingTInfo(GetTypeSourceInfo());
  5648. }
  5649. void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
  5650. TL.setNameLoc(ReadSourceLocation());
  5651. }
  5652. void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
  5653. DeducedTemplateSpecializationTypeLoc TL) {
  5654. TL.setTemplateNameLoc(ReadSourceLocation());
  5655. }
  5656. void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
  5657. TL.setNameLoc(ReadSourceLocation());
  5658. }
  5659. void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
  5660. TL.setNameLoc(ReadSourceLocation());
  5661. }
  5662. void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  5663. TL.setAttrNameLoc(ReadSourceLocation());
  5664. if (TL.hasAttrOperand()) {
  5665. SourceRange range;
  5666. range.setBegin(ReadSourceLocation());
  5667. range.setEnd(ReadSourceLocation());
  5668. TL.setAttrOperandParensRange(range);
  5669. }
  5670. if (TL.hasAttrExprOperand()) {
  5671. if (Record[Idx++])
  5672. TL.setAttrExprOperand(Reader->ReadExpr(*F));
  5673. else
  5674. TL.setAttrExprOperand(nullptr);
  5675. } else if (TL.hasAttrEnumOperand())
  5676. TL.setAttrEnumOperandLoc(ReadSourceLocation());
  5677. }
  5678. void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  5679. TL.setNameLoc(ReadSourceLocation());
  5680. }
  5681. void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
  5682. SubstTemplateTypeParmTypeLoc TL) {
  5683. TL.setNameLoc(ReadSourceLocation());
  5684. }
  5685. void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
  5686. SubstTemplateTypeParmPackTypeLoc TL) {
  5687. TL.setNameLoc(ReadSourceLocation());
  5688. }
  5689. void TypeLocReader::VisitTemplateSpecializationTypeLoc(
  5690. TemplateSpecializationTypeLoc TL) {
  5691. TL.setTemplateKeywordLoc(ReadSourceLocation());
  5692. TL.setTemplateNameLoc(ReadSourceLocation());
  5693. TL.setLAngleLoc(ReadSourceLocation());
  5694. TL.setRAngleLoc(ReadSourceLocation());
  5695. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  5696. TL.setArgLocInfo(
  5697. i,
  5698. Reader->GetTemplateArgumentLocInfo(
  5699. *F, TL.getTypePtr()->getArg(i).getKind(), Record, Idx));
  5700. }
  5701. void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
  5702. TL.setLParenLoc(ReadSourceLocation());
  5703. TL.setRParenLoc(ReadSourceLocation());
  5704. }
  5705. void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  5706. TL.setElaboratedKeywordLoc(ReadSourceLocation());
  5707. TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
  5708. }
  5709. void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  5710. TL.setNameLoc(ReadSourceLocation());
  5711. }
  5712. void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  5713. TL.setElaboratedKeywordLoc(ReadSourceLocation());
  5714. TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
  5715. TL.setNameLoc(ReadSourceLocation());
  5716. }
  5717. void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
  5718. DependentTemplateSpecializationTypeLoc TL) {
  5719. TL.setElaboratedKeywordLoc(ReadSourceLocation());
  5720. TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
  5721. TL.setTemplateKeywordLoc(ReadSourceLocation());
  5722. TL.setTemplateNameLoc(ReadSourceLocation());
  5723. TL.setLAngleLoc(ReadSourceLocation());
  5724. TL.setRAngleLoc(ReadSourceLocation());
  5725. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  5726. TL.setArgLocInfo(
  5727. I,
  5728. Reader->GetTemplateArgumentLocInfo(
  5729. *F, TL.getTypePtr()->getArg(I).getKind(), Record, Idx));
  5730. }
  5731. void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  5732. TL.setEllipsisLoc(ReadSourceLocation());
  5733. }
  5734. void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  5735. TL.setNameLoc(ReadSourceLocation());
  5736. }
  5737. void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
  5738. if (TL.getNumProtocols()) {
  5739. TL.setProtocolLAngleLoc(ReadSourceLocation());
  5740. TL.setProtocolRAngleLoc(ReadSourceLocation());
  5741. }
  5742. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  5743. TL.setProtocolLoc(i, ReadSourceLocation());
  5744. }
  5745. void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  5746. TL.setHasBaseTypeAsWritten(Record[Idx++]);
  5747. TL.setTypeArgsLAngleLoc(ReadSourceLocation());
  5748. TL.setTypeArgsRAngleLoc(ReadSourceLocation());
  5749. for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
  5750. TL.setTypeArgTInfo(i, GetTypeSourceInfo());
  5751. TL.setProtocolLAngleLoc(ReadSourceLocation());
  5752. TL.setProtocolRAngleLoc(ReadSourceLocation());
  5753. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  5754. TL.setProtocolLoc(i, ReadSourceLocation());
  5755. }
  5756. void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  5757. TL.setStarLoc(ReadSourceLocation());
  5758. }
  5759. void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  5760. TL.setKWLoc(ReadSourceLocation());
  5761. TL.setLParenLoc(ReadSourceLocation());
  5762. TL.setRParenLoc(ReadSourceLocation());
  5763. }
  5764. void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
  5765. TL.setKWLoc(ReadSourceLocation());
  5766. }
  5767. TypeSourceInfo *
  5768. ASTReader::GetTypeSourceInfo(ModuleFile &F, const ASTReader::RecordData &Record,
  5769. unsigned &Idx) {
  5770. QualType InfoTy = readType(F, Record, Idx);
  5771. if (InfoTy.isNull())
  5772. return nullptr;
  5773. TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
  5774. TypeLocReader TLR(F, *this, Record, Idx);
  5775. for (TypeLoc TL = TInfo->getTypeLoc(); !TL.isNull(); TL = TL.getNextTypeLoc())
  5776. TLR.Visit(TL);
  5777. return TInfo;
  5778. }
  5779. QualType ASTReader::GetType(TypeID ID) {
  5780. assert(ContextObj && "reading type with no AST context");
  5781. ASTContext &Context = *ContextObj;
  5782. unsigned FastQuals = ID & Qualifiers::FastMask;
  5783. unsigned Index = ID >> Qualifiers::FastWidth;
  5784. if (Index < NUM_PREDEF_TYPE_IDS) {
  5785. QualType T;
  5786. switch ((PredefinedTypeIDs)Index) {
  5787. case PREDEF_TYPE_NULL_ID:
  5788. return QualType();
  5789. case PREDEF_TYPE_VOID_ID:
  5790. T = Context.VoidTy;
  5791. break;
  5792. case PREDEF_TYPE_BOOL_ID:
  5793. T = Context.BoolTy;
  5794. break;
  5795. case PREDEF_TYPE_CHAR_U_ID:
  5796. case PREDEF_TYPE_CHAR_S_ID:
  5797. // FIXME: Check that the signedness of CharTy is correct!
  5798. T = Context.CharTy;
  5799. break;
  5800. case PREDEF_TYPE_UCHAR_ID:
  5801. T = Context.UnsignedCharTy;
  5802. break;
  5803. case PREDEF_TYPE_USHORT_ID:
  5804. T = Context.UnsignedShortTy;
  5805. break;
  5806. case PREDEF_TYPE_UINT_ID:
  5807. T = Context.UnsignedIntTy;
  5808. break;
  5809. case PREDEF_TYPE_ULONG_ID:
  5810. T = Context.UnsignedLongTy;
  5811. break;
  5812. case PREDEF_TYPE_ULONGLONG_ID:
  5813. T = Context.UnsignedLongLongTy;
  5814. break;
  5815. case PREDEF_TYPE_UINT128_ID:
  5816. T = Context.UnsignedInt128Ty;
  5817. break;
  5818. case PREDEF_TYPE_SCHAR_ID:
  5819. T = Context.SignedCharTy;
  5820. break;
  5821. case PREDEF_TYPE_WCHAR_ID:
  5822. T = Context.WCharTy;
  5823. break;
  5824. case PREDEF_TYPE_SHORT_ID:
  5825. T = Context.ShortTy;
  5826. break;
  5827. case PREDEF_TYPE_INT_ID:
  5828. T = Context.IntTy;
  5829. break;
  5830. case PREDEF_TYPE_LONG_ID:
  5831. T = Context.LongTy;
  5832. break;
  5833. case PREDEF_TYPE_LONGLONG_ID:
  5834. T = Context.LongLongTy;
  5835. break;
  5836. case PREDEF_TYPE_INT128_ID:
  5837. T = Context.Int128Ty;
  5838. break;
  5839. case PREDEF_TYPE_HALF_ID:
  5840. T = Context.HalfTy;
  5841. break;
  5842. case PREDEF_TYPE_FLOAT_ID:
  5843. T = Context.FloatTy;
  5844. break;
  5845. case PREDEF_TYPE_DOUBLE_ID:
  5846. T = Context.DoubleTy;
  5847. break;
  5848. case PREDEF_TYPE_LONGDOUBLE_ID:
  5849. T = Context.LongDoubleTy;
  5850. break;
  5851. case PREDEF_TYPE_FLOAT16_ID:
  5852. T = Context.Float16Ty;
  5853. break;
  5854. case PREDEF_TYPE_FLOAT128_ID:
  5855. T = Context.Float128Ty;
  5856. break;
  5857. case PREDEF_TYPE_OVERLOAD_ID:
  5858. T = Context.OverloadTy;
  5859. break;
  5860. case PREDEF_TYPE_BOUND_MEMBER:
  5861. T = Context.BoundMemberTy;
  5862. break;
  5863. case PREDEF_TYPE_PSEUDO_OBJECT:
  5864. T = Context.PseudoObjectTy;
  5865. break;
  5866. case PREDEF_TYPE_DEPENDENT_ID:
  5867. T = Context.DependentTy;
  5868. break;
  5869. case PREDEF_TYPE_UNKNOWN_ANY:
  5870. T = Context.UnknownAnyTy;
  5871. break;
  5872. case PREDEF_TYPE_NULLPTR_ID:
  5873. T = Context.NullPtrTy;
  5874. break;
  5875. case PREDEF_TYPE_CHAR16_ID:
  5876. T = Context.Char16Ty;
  5877. break;
  5878. case PREDEF_TYPE_CHAR32_ID:
  5879. T = Context.Char32Ty;
  5880. break;
  5881. case PREDEF_TYPE_OBJC_ID:
  5882. T = Context.ObjCBuiltinIdTy;
  5883. break;
  5884. case PREDEF_TYPE_OBJC_CLASS:
  5885. T = Context.ObjCBuiltinClassTy;
  5886. break;
  5887. case PREDEF_TYPE_OBJC_SEL:
  5888. T = Context.ObjCBuiltinSelTy;
  5889. break;
  5890. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  5891. case PREDEF_TYPE_##Id##_ID: \
  5892. T = Context.SingletonId; \
  5893. break;
  5894. #include "clang/Basic/OpenCLImageTypes.def"
  5895. case PREDEF_TYPE_SAMPLER_ID:
  5896. T = Context.OCLSamplerTy;
  5897. break;
  5898. case PREDEF_TYPE_EVENT_ID:
  5899. T = Context.OCLEventTy;
  5900. break;
  5901. case PREDEF_TYPE_CLK_EVENT_ID:
  5902. T = Context.OCLClkEventTy;
  5903. break;
  5904. case PREDEF_TYPE_QUEUE_ID:
  5905. T = Context.OCLQueueTy;
  5906. break;
  5907. case PREDEF_TYPE_RESERVE_ID_ID:
  5908. T = Context.OCLReserveIDTy;
  5909. break;
  5910. case PREDEF_TYPE_AUTO_DEDUCT:
  5911. T = Context.getAutoDeductType();
  5912. break;
  5913. case PREDEF_TYPE_AUTO_RREF_DEDUCT:
  5914. T = Context.getAutoRRefDeductType();
  5915. break;
  5916. case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
  5917. T = Context.ARCUnbridgedCastTy;
  5918. break;
  5919. case PREDEF_TYPE_BUILTIN_FN:
  5920. T = Context.BuiltinFnTy;
  5921. break;
  5922. case PREDEF_TYPE_OMP_ARRAY_SECTION:
  5923. T = Context.OMPArraySectionTy;
  5924. break;
  5925. }
  5926. assert(!T.isNull() && "Unknown predefined type");
  5927. return T.withFastQualifiers(FastQuals);
  5928. }
  5929. Index -= NUM_PREDEF_TYPE_IDS;
  5930. assert(Index < TypesLoaded.size() && "Type index out-of-range");
  5931. if (TypesLoaded[Index].isNull()) {
  5932. TypesLoaded[Index] = readTypeRecord(Index);
  5933. if (TypesLoaded[Index].isNull())
  5934. return QualType();
  5935. TypesLoaded[Index]->setFromAST();
  5936. if (DeserializationListener)
  5937. DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
  5938. TypesLoaded[Index]);
  5939. }
  5940. return TypesLoaded[Index].withFastQualifiers(FastQuals);
  5941. }
  5942. QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
  5943. return GetType(getGlobalTypeID(F, LocalID));
  5944. }
  5945. serialization::TypeID
  5946. ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
  5947. unsigned FastQuals = LocalID & Qualifiers::FastMask;
  5948. unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
  5949. if (LocalIndex < NUM_PREDEF_TYPE_IDS)
  5950. return LocalID;
  5951. if (!F.ModuleOffsetMap.empty())
  5952. ReadModuleOffsetMap(F);
  5953. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  5954. = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
  5955. assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
  5956. unsigned GlobalIndex = LocalIndex + I->second;
  5957. return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
  5958. }
  5959. TemplateArgumentLocInfo
  5960. ASTReader::GetTemplateArgumentLocInfo(ModuleFile &F,
  5961. TemplateArgument::ArgKind Kind,
  5962. const RecordData &Record,
  5963. unsigned &Index) {
  5964. switch (Kind) {
  5965. case TemplateArgument::Expression:
  5966. return ReadExpr(F);
  5967. case TemplateArgument::Type:
  5968. return GetTypeSourceInfo(F, Record, Index);
  5969. case TemplateArgument::Template: {
  5970. NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
  5971. Index);
  5972. SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
  5973. return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
  5974. SourceLocation());
  5975. }
  5976. case TemplateArgument::TemplateExpansion: {
  5977. NestedNameSpecifierLoc QualifierLoc = ReadNestedNameSpecifierLoc(F, Record,
  5978. Index);
  5979. SourceLocation TemplateNameLoc = ReadSourceLocation(F, Record, Index);
  5980. SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Index);
  5981. return TemplateArgumentLocInfo(QualifierLoc, TemplateNameLoc,
  5982. EllipsisLoc);
  5983. }
  5984. case TemplateArgument::Null:
  5985. case TemplateArgument::Integral:
  5986. case TemplateArgument::Declaration:
  5987. case TemplateArgument::NullPtr:
  5988. case TemplateArgument::Pack:
  5989. // FIXME: Is this right?
  5990. return TemplateArgumentLocInfo();
  5991. }
  5992. llvm_unreachable("unexpected template argument loc");
  5993. }
  5994. TemplateArgumentLoc
  5995. ASTReader::ReadTemplateArgumentLoc(ModuleFile &F,
  5996. const RecordData &Record, unsigned &Index) {
  5997. TemplateArgument Arg = ReadTemplateArgument(F, Record, Index);
  5998. if (Arg.getKind() == TemplateArgument::Expression) {
  5999. if (Record[Index++]) // bool InfoHasSameExpr.
  6000. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
  6001. }
  6002. return TemplateArgumentLoc(Arg, GetTemplateArgumentLocInfo(F, Arg.getKind(),
  6003. Record, Index));
  6004. }
  6005. const ASTTemplateArgumentListInfo*
  6006. ASTReader::ReadASTTemplateArgumentListInfo(ModuleFile &F,
  6007. const RecordData &Record,
  6008. unsigned &Index) {
  6009. SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Index);
  6010. SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Index);
  6011. unsigned NumArgsAsWritten = Record[Index++];
  6012. TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
  6013. for (unsigned i = 0; i != NumArgsAsWritten; ++i)
  6014. TemplArgsInfo.addArgument(ReadTemplateArgumentLoc(F, Record, Index));
  6015. return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
  6016. }
  6017. Decl *ASTReader::GetExternalDecl(uint32_t ID) {
  6018. return GetDecl(ID);
  6019. }
  6020. void ASTReader::CompleteRedeclChain(const Decl *D) {
  6021. if (NumCurrentElementsDeserializing) {
  6022. // We arrange to not care about the complete redeclaration chain while we're
  6023. // deserializing. Just remember that the AST has marked this one as complete
  6024. // but that it's not actually complete yet, so we know we still need to
  6025. // complete it later.
  6026. PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
  6027. return;
  6028. }
  6029. const DeclContext *DC = D->getDeclContext()->getRedeclContext();
  6030. // If this is a named declaration, complete it by looking it up
  6031. // within its context.
  6032. //
  6033. // FIXME: Merging a function definition should merge
  6034. // all mergeable entities within it.
  6035. if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
  6036. isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
  6037. if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
  6038. if (!getContext().getLangOpts().CPlusPlus &&
  6039. isa<TranslationUnitDecl>(DC)) {
  6040. // Outside of C++, we don't have a lookup table for the TU, so update
  6041. // the identifier instead. (For C++ modules, we don't store decls
  6042. // in the serialized identifier table, so we do the lookup in the TU.)
  6043. auto *II = Name.getAsIdentifierInfo();
  6044. assert(II && "non-identifier name in C?");
  6045. if (II->isOutOfDate())
  6046. updateOutOfDateIdentifier(*II);
  6047. } else
  6048. DC->lookup(Name);
  6049. } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
  6050. // Find all declarations of this kind from the relevant context.
  6051. for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
  6052. auto *DC = cast<DeclContext>(DCDecl);
  6053. SmallVector<Decl*, 8> Decls;
  6054. FindExternalLexicalDecls(
  6055. DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
  6056. }
  6057. }
  6058. }
  6059. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
  6060. CTSD->getSpecializedTemplate()->LoadLazySpecializations();
  6061. if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
  6062. VTSD->getSpecializedTemplate()->LoadLazySpecializations();
  6063. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  6064. if (auto *Template = FD->getPrimaryTemplate())
  6065. Template->LoadLazySpecializations();
  6066. }
  6067. }
  6068. CXXCtorInitializer **
  6069. ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
  6070. RecordLocation Loc = getLocalBitOffset(Offset);
  6071. BitstreamCursor &Cursor = Loc.F->DeclsCursor;
  6072. SavedStreamPosition SavedPosition(Cursor);
  6073. Cursor.JumpToBit(Loc.Offset);
  6074. ReadingKindTracker ReadingKind(Read_Decl, *this);
  6075. RecordData Record;
  6076. unsigned Code = Cursor.ReadCode();
  6077. unsigned RecCode = Cursor.readRecord(Code, Record);
  6078. if (RecCode != DECL_CXX_CTOR_INITIALIZERS) {
  6079. Error("malformed AST file: missing C++ ctor initializers");
  6080. return nullptr;
  6081. }
  6082. unsigned Idx = 0;
  6083. return ReadCXXCtorInitializers(*Loc.F, Record, Idx);
  6084. }
  6085. CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
  6086. assert(ContextObj && "reading base specifiers with no AST context");
  6087. ASTContext &Context = *ContextObj;
  6088. RecordLocation Loc = getLocalBitOffset(Offset);
  6089. BitstreamCursor &Cursor = Loc.F->DeclsCursor;
  6090. SavedStreamPosition SavedPosition(Cursor);
  6091. Cursor.JumpToBit(Loc.Offset);
  6092. ReadingKindTracker ReadingKind(Read_Decl, *this);
  6093. RecordData Record;
  6094. unsigned Code = Cursor.ReadCode();
  6095. unsigned RecCode = Cursor.readRecord(Code, Record);
  6096. if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
  6097. Error("malformed AST file: missing C++ base specifiers");
  6098. return nullptr;
  6099. }
  6100. unsigned Idx = 0;
  6101. unsigned NumBases = Record[Idx++];
  6102. void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
  6103. CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
  6104. for (unsigned I = 0; I != NumBases; ++I)
  6105. Bases[I] = ReadCXXBaseSpecifier(*Loc.F, Record, Idx);
  6106. return Bases;
  6107. }
  6108. serialization::DeclID
  6109. ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
  6110. if (LocalID < NUM_PREDEF_DECL_IDS)
  6111. return LocalID;
  6112. if (!F.ModuleOffsetMap.empty())
  6113. ReadModuleOffsetMap(F);
  6114. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6115. = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
  6116. assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
  6117. return LocalID + I->second;
  6118. }
  6119. bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
  6120. ModuleFile &M) const {
  6121. // Predefined decls aren't from any module.
  6122. if (ID < NUM_PREDEF_DECL_IDS)
  6123. return false;
  6124. return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
  6125. ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
  6126. }
  6127. ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
  6128. if (!D->isFromASTFile())
  6129. return nullptr;
  6130. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
  6131. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  6132. return I->second;
  6133. }
  6134. SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
  6135. if (ID < NUM_PREDEF_DECL_IDS)
  6136. return SourceLocation();
  6137. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  6138. if (Index > DeclsLoaded.size()) {
  6139. Error("declaration ID out-of-range for AST file");
  6140. return SourceLocation();
  6141. }
  6142. if (Decl *D = DeclsLoaded[Index])
  6143. return D->getLocation();
  6144. SourceLocation Loc;
  6145. DeclCursorForID(ID, Loc);
  6146. return Loc;
  6147. }
  6148. static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
  6149. switch (ID) {
  6150. case PREDEF_DECL_NULL_ID:
  6151. return nullptr;
  6152. case PREDEF_DECL_TRANSLATION_UNIT_ID:
  6153. return Context.getTranslationUnitDecl();
  6154. case PREDEF_DECL_OBJC_ID_ID:
  6155. return Context.getObjCIdDecl();
  6156. case PREDEF_DECL_OBJC_SEL_ID:
  6157. return Context.getObjCSelDecl();
  6158. case PREDEF_DECL_OBJC_CLASS_ID:
  6159. return Context.getObjCClassDecl();
  6160. case PREDEF_DECL_OBJC_PROTOCOL_ID:
  6161. return Context.getObjCProtocolDecl();
  6162. case PREDEF_DECL_INT_128_ID:
  6163. return Context.getInt128Decl();
  6164. case PREDEF_DECL_UNSIGNED_INT_128_ID:
  6165. return Context.getUInt128Decl();
  6166. case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
  6167. return Context.getObjCInstanceTypeDecl();
  6168. case PREDEF_DECL_BUILTIN_VA_LIST_ID:
  6169. return Context.getBuiltinVaListDecl();
  6170. case PREDEF_DECL_VA_LIST_TAG:
  6171. return Context.getVaListTagDecl();
  6172. case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
  6173. return Context.getBuiltinMSVaListDecl();
  6174. case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
  6175. return Context.getExternCContextDecl();
  6176. case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
  6177. return Context.getMakeIntegerSeqDecl();
  6178. case PREDEF_DECL_CF_CONSTANT_STRING_ID:
  6179. return Context.getCFConstantStringDecl();
  6180. case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
  6181. return Context.getCFConstantStringTagDecl();
  6182. case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
  6183. return Context.getTypePackElementDecl();
  6184. }
  6185. llvm_unreachable("PredefinedDeclIDs unknown enum value");
  6186. }
  6187. Decl *ASTReader::GetExistingDecl(DeclID ID) {
  6188. assert(ContextObj && "reading decl with no AST context");
  6189. if (ID < NUM_PREDEF_DECL_IDS) {
  6190. Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
  6191. if (D) {
  6192. // Track that we have merged the declaration with ID \p ID into the
  6193. // pre-existing predefined declaration \p D.
  6194. auto &Merged = KeyDecls[D->getCanonicalDecl()];
  6195. if (Merged.empty())
  6196. Merged.push_back(ID);
  6197. }
  6198. return D;
  6199. }
  6200. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  6201. if (Index >= DeclsLoaded.size()) {
  6202. assert(0 && "declaration ID out-of-range for AST file");
  6203. Error("declaration ID out-of-range for AST file");
  6204. return nullptr;
  6205. }
  6206. return DeclsLoaded[Index];
  6207. }
  6208. Decl *ASTReader::GetDecl(DeclID ID) {
  6209. if (ID < NUM_PREDEF_DECL_IDS)
  6210. return GetExistingDecl(ID);
  6211. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  6212. if (Index >= DeclsLoaded.size()) {
  6213. assert(0 && "declaration ID out-of-range for AST file");
  6214. Error("declaration ID out-of-range for AST file");
  6215. return nullptr;
  6216. }
  6217. if (!DeclsLoaded[Index]) {
  6218. ReadDeclRecord(ID);
  6219. if (DeserializationListener)
  6220. DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
  6221. }
  6222. return DeclsLoaded[Index];
  6223. }
  6224. DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
  6225. DeclID GlobalID) {
  6226. if (GlobalID < NUM_PREDEF_DECL_IDS)
  6227. return GlobalID;
  6228. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
  6229. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  6230. ModuleFile *Owner = I->second;
  6231. llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
  6232. = M.GlobalToLocalDeclIDs.find(Owner);
  6233. if (Pos == M.GlobalToLocalDeclIDs.end())
  6234. return 0;
  6235. return GlobalID - Owner->BaseDeclID + Pos->second;
  6236. }
  6237. serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
  6238. const RecordData &Record,
  6239. unsigned &Idx) {
  6240. if (Idx >= Record.size()) {
  6241. Error("Corrupted AST file");
  6242. return 0;
  6243. }
  6244. return getGlobalDeclID(F, Record[Idx++]);
  6245. }
  6246. /// \brief Resolve the offset of a statement into a statement.
  6247. ///
  6248. /// This operation will read a new statement from the external
  6249. /// source each time it is called, and is meant to be used via a
  6250. /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
  6251. Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
  6252. // Switch case IDs are per Decl.
  6253. ClearSwitchCaseIDs();
  6254. // Offset here is a global offset across the entire chain.
  6255. RecordLocation Loc = getLocalBitOffset(Offset);
  6256. Loc.F->DeclsCursor.JumpToBit(Loc.Offset);
  6257. assert(NumCurrentElementsDeserializing == 0 &&
  6258. "should not be called while already deserializing");
  6259. Deserializing D(this);
  6260. return ReadStmtFromStream(*Loc.F);
  6261. }
  6262. void ASTReader::FindExternalLexicalDecls(
  6263. const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
  6264. SmallVectorImpl<Decl *> &Decls) {
  6265. bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
  6266. auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
  6267. assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
  6268. for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
  6269. auto K = (Decl::Kind)+LexicalDecls[I];
  6270. if (!IsKindWeWant(K))
  6271. continue;
  6272. auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
  6273. // Don't add predefined declarations to the lexical context more
  6274. // than once.
  6275. if (ID < NUM_PREDEF_DECL_IDS) {
  6276. if (PredefsVisited[ID])
  6277. continue;
  6278. PredefsVisited[ID] = true;
  6279. }
  6280. if (Decl *D = GetLocalDecl(*M, ID)) {
  6281. assert(D->getKind() == K && "wrong kind for lexical decl");
  6282. if (!DC->isDeclInLexicalTraversal(D))
  6283. Decls.push_back(D);
  6284. }
  6285. }
  6286. };
  6287. if (isa<TranslationUnitDecl>(DC)) {
  6288. for (auto Lexical : TULexicalDecls)
  6289. Visit(Lexical.first, Lexical.second);
  6290. } else {
  6291. auto I = LexicalDecls.find(DC);
  6292. if (I != LexicalDecls.end())
  6293. Visit(I->second.first, I->second.second);
  6294. }
  6295. ++NumLexicalDeclContextsRead;
  6296. }
  6297. namespace {
  6298. class DeclIDComp {
  6299. ASTReader &Reader;
  6300. ModuleFile &Mod;
  6301. public:
  6302. DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
  6303. bool operator()(LocalDeclID L, LocalDeclID R) const {
  6304. SourceLocation LHS = getLocation(L);
  6305. SourceLocation RHS = getLocation(R);
  6306. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  6307. }
  6308. bool operator()(SourceLocation LHS, LocalDeclID R) const {
  6309. SourceLocation RHS = getLocation(R);
  6310. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  6311. }
  6312. bool operator()(LocalDeclID L, SourceLocation RHS) const {
  6313. SourceLocation LHS = getLocation(L);
  6314. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  6315. }
  6316. SourceLocation getLocation(LocalDeclID ID) const {
  6317. return Reader.getSourceManager().getFileLoc(
  6318. Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
  6319. }
  6320. };
  6321. } // namespace
  6322. void ASTReader::FindFileRegionDecls(FileID File,
  6323. unsigned Offset, unsigned Length,
  6324. SmallVectorImpl<Decl *> &Decls) {
  6325. SourceManager &SM = getSourceManager();
  6326. llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
  6327. if (I == FileDeclIDs.end())
  6328. return;
  6329. FileDeclsInfo &DInfo = I->second;
  6330. if (DInfo.Decls.empty())
  6331. return;
  6332. SourceLocation
  6333. BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
  6334. SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
  6335. DeclIDComp DIDComp(*this, *DInfo.Mod);
  6336. ArrayRef<serialization::LocalDeclID>::iterator
  6337. BeginIt = std::lower_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
  6338. BeginLoc, DIDComp);
  6339. if (BeginIt != DInfo.Decls.begin())
  6340. --BeginIt;
  6341. // If we are pointing at a top-level decl inside an objc container, we need
  6342. // to backtrack until we find it otherwise we will fail to report that the
  6343. // region overlaps with an objc container.
  6344. while (BeginIt != DInfo.Decls.begin() &&
  6345. GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
  6346. ->isTopLevelDeclInObjCContainer())
  6347. --BeginIt;
  6348. ArrayRef<serialization::LocalDeclID>::iterator
  6349. EndIt = std::upper_bound(DInfo.Decls.begin(), DInfo.Decls.end(),
  6350. EndLoc, DIDComp);
  6351. if (EndIt != DInfo.Decls.end())
  6352. ++EndIt;
  6353. for (ArrayRef<serialization::LocalDeclID>::iterator
  6354. DIt = BeginIt; DIt != EndIt; ++DIt)
  6355. Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
  6356. }
  6357. bool
  6358. ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
  6359. DeclarationName Name) {
  6360. assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
  6361. "DeclContext has no visible decls in storage");
  6362. if (!Name)
  6363. return false;
  6364. auto It = Lookups.find(DC);
  6365. if (It == Lookups.end())
  6366. return false;
  6367. Deserializing LookupResults(this);
  6368. // Load the list of declarations.
  6369. SmallVector<NamedDecl *, 64> Decls;
  6370. for (DeclID ID : It->second.Table.find(Name)) {
  6371. NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
  6372. if (ND->getDeclName() == Name)
  6373. Decls.push_back(ND);
  6374. }
  6375. ++NumVisibleDeclContextsRead;
  6376. SetExternalVisibleDeclsForName(DC, Name, Decls);
  6377. return !Decls.empty();
  6378. }
  6379. void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
  6380. if (!DC->hasExternalVisibleStorage())
  6381. return;
  6382. auto It = Lookups.find(DC);
  6383. assert(It != Lookups.end() &&
  6384. "have external visible storage but no lookup tables");
  6385. DeclsMap Decls;
  6386. for (DeclID ID : It->second.Table.findAll()) {
  6387. NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
  6388. Decls[ND->getDeclName()].push_back(ND);
  6389. }
  6390. ++NumVisibleDeclContextsRead;
  6391. for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
  6392. SetExternalVisibleDeclsForName(DC, I->first, I->second);
  6393. }
  6394. const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
  6395. }
  6396. const serialization::reader::DeclContextLookupTable *
  6397. ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
  6398. auto I = Lookups.find(Primary);
  6399. return I == Lookups.end() ? nullptr : &I->second;
  6400. }
  6401. /// \brief Under non-PCH compilation the consumer receives the objc methods
  6402. /// before receiving the implementation, and codegen depends on this.
  6403. /// We simulate this by deserializing and passing to consumer the methods of the
  6404. /// implementation before passing the deserialized implementation decl.
  6405. static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
  6406. ASTConsumer *Consumer) {
  6407. assert(ImplD && Consumer);
  6408. for (auto *I : ImplD->methods())
  6409. Consumer->HandleInterestingDecl(DeclGroupRef(I));
  6410. Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
  6411. }
  6412. void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
  6413. if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
  6414. PassObjCImplDeclToConsumer(ImplD, Consumer);
  6415. else
  6416. Consumer->HandleInterestingDecl(DeclGroupRef(D));
  6417. }
  6418. void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
  6419. this->Consumer = Consumer;
  6420. if (Consumer)
  6421. PassInterestingDeclsToConsumer();
  6422. if (DeserializationListener)
  6423. DeserializationListener->ReaderInitialized(this);
  6424. }
  6425. void ASTReader::PrintStats() {
  6426. std::fprintf(stderr, "*** AST File Statistics:\n");
  6427. unsigned NumTypesLoaded
  6428. = TypesLoaded.size() - std::count(TypesLoaded.begin(), TypesLoaded.end(),
  6429. QualType());
  6430. unsigned NumDeclsLoaded
  6431. = DeclsLoaded.size() - std::count(DeclsLoaded.begin(), DeclsLoaded.end(),
  6432. (Decl *)nullptr);
  6433. unsigned NumIdentifiersLoaded
  6434. = IdentifiersLoaded.size() - std::count(IdentifiersLoaded.begin(),
  6435. IdentifiersLoaded.end(),
  6436. (IdentifierInfo *)nullptr);
  6437. unsigned NumMacrosLoaded
  6438. = MacrosLoaded.size() - std::count(MacrosLoaded.begin(),
  6439. MacrosLoaded.end(),
  6440. (MacroInfo *)nullptr);
  6441. unsigned NumSelectorsLoaded
  6442. = SelectorsLoaded.size() - std::count(SelectorsLoaded.begin(),
  6443. SelectorsLoaded.end(),
  6444. Selector());
  6445. if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
  6446. std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
  6447. NumSLocEntriesRead, TotalNumSLocEntries,
  6448. ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
  6449. if (!TypesLoaded.empty())
  6450. std::fprintf(stderr, " %u/%u types read (%f%%)\n",
  6451. NumTypesLoaded, (unsigned)TypesLoaded.size(),
  6452. ((float)NumTypesLoaded/TypesLoaded.size() * 100));
  6453. if (!DeclsLoaded.empty())
  6454. std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
  6455. NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
  6456. ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
  6457. if (!IdentifiersLoaded.empty())
  6458. std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
  6459. NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
  6460. ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
  6461. if (!MacrosLoaded.empty())
  6462. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  6463. NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
  6464. ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
  6465. if (!SelectorsLoaded.empty())
  6466. std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
  6467. NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
  6468. ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
  6469. if (TotalNumStatements)
  6470. std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
  6471. NumStatementsRead, TotalNumStatements,
  6472. ((float)NumStatementsRead/TotalNumStatements * 100));
  6473. if (TotalNumMacros)
  6474. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  6475. NumMacrosRead, TotalNumMacros,
  6476. ((float)NumMacrosRead/TotalNumMacros * 100));
  6477. if (TotalLexicalDeclContexts)
  6478. std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
  6479. NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
  6480. ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
  6481. * 100));
  6482. if (TotalVisibleDeclContexts)
  6483. std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
  6484. NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
  6485. ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
  6486. * 100));
  6487. if (TotalNumMethodPoolEntries)
  6488. std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
  6489. NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
  6490. ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
  6491. * 100));
  6492. if (NumMethodPoolLookups)
  6493. std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
  6494. NumMethodPoolHits, NumMethodPoolLookups,
  6495. ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
  6496. if (NumMethodPoolTableLookups)
  6497. std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
  6498. NumMethodPoolTableHits, NumMethodPoolTableLookups,
  6499. ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
  6500. * 100.0));
  6501. if (NumIdentifierLookupHits)
  6502. std::fprintf(stderr,
  6503. " %u / %u identifier table lookups succeeded (%f%%)\n",
  6504. NumIdentifierLookupHits, NumIdentifierLookups,
  6505. (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
  6506. if (GlobalIndex) {
  6507. std::fprintf(stderr, "\n");
  6508. GlobalIndex->printStats();
  6509. }
  6510. std::fprintf(stderr, "\n");
  6511. dump();
  6512. std::fprintf(stderr, "\n");
  6513. }
  6514. template<typename Key, typename ModuleFile, unsigned InitialCapacity>
  6515. LLVM_DUMP_METHOD static void
  6516. dumpModuleIDMap(StringRef Name,
  6517. const ContinuousRangeMap<Key, ModuleFile *,
  6518. InitialCapacity> &Map) {
  6519. if (Map.begin() == Map.end())
  6520. return;
  6521. using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
  6522. llvm::errs() << Name << ":\n";
  6523. for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
  6524. I != IEnd; ++I) {
  6525. llvm::errs() << " " << I->first << " -> " << I->second->FileName
  6526. << "\n";
  6527. }
  6528. }
  6529. LLVM_DUMP_METHOD void ASTReader::dump() {
  6530. llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
  6531. dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
  6532. dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
  6533. dumpModuleIDMap("Global type map", GlobalTypeMap);
  6534. dumpModuleIDMap("Global declaration map", GlobalDeclMap);
  6535. dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
  6536. dumpModuleIDMap("Global macro map", GlobalMacroMap);
  6537. dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
  6538. dumpModuleIDMap("Global selector map", GlobalSelectorMap);
  6539. dumpModuleIDMap("Global preprocessed entity map",
  6540. GlobalPreprocessedEntityMap);
  6541. llvm::errs() << "\n*** PCH/Modules Loaded:";
  6542. for (ModuleFile &M : ModuleMgr)
  6543. M.dump();
  6544. }
  6545. /// Return the amount of memory used by memory buffers, breaking down
  6546. /// by heap-backed versus mmap'ed memory.
  6547. void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
  6548. for (ModuleFile &I : ModuleMgr) {
  6549. if (llvm::MemoryBuffer *buf = I.Buffer) {
  6550. size_t bytes = buf->getBufferSize();
  6551. switch (buf->getBufferKind()) {
  6552. case llvm::MemoryBuffer::MemoryBuffer_Malloc:
  6553. sizes.malloc_bytes += bytes;
  6554. break;
  6555. case llvm::MemoryBuffer::MemoryBuffer_MMap:
  6556. sizes.mmap_bytes += bytes;
  6557. break;
  6558. }
  6559. }
  6560. }
  6561. }
  6562. void ASTReader::InitializeSema(Sema &S) {
  6563. SemaObj = &S;
  6564. S.addExternalSource(this);
  6565. // Makes sure any declarations that were deserialized "too early"
  6566. // still get added to the identifier's declaration chains.
  6567. for (uint64_t ID : PreloadedDeclIDs) {
  6568. NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
  6569. pushExternalDeclIntoScope(D, D->getDeclName());
  6570. }
  6571. PreloadedDeclIDs.clear();
  6572. // FIXME: What happens if these are changed by a module import?
  6573. if (!FPPragmaOptions.empty()) {
  6574. assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
  6575. SemaObj->FPFeatures = FPOptions(FPPragmaOptions[0]);
  6576. }
  6577. SemaObj->OpenCLFeatures.copy(OpenCLExtensions);
  6578. SemaObj->OpenCLTypeExtMap = OpenCLTypeExtMap;
  6579. SemaObj->OpenCLDeclExtMap = OpenCLDeclExtMap;
  6580. UpdateSema();
  6581. }
  6582. void ASTReader::UpdateSema() {
  6583. assert(SemaObj && "no Sema to update");
  6584. // Load the offsets of the declarations that Sema references.
  6585. // They will be lazily deserialized when needed.
  6586. if (!SemaDeclRefs.empty()) {
  6587. assert(SemaDeclRefs.size() % 3 == 0);
  6588. for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
  6589. if (!SemaObj->StdNamespace)
  6590. SemaObj->StdNamespace = SemaDeclRefs[I];
  6591. if (!SemaObj->StdBadAlloc)
  6592. SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
  6593. if (!SemaObj->StdAlignValT)
  6594. SemaObj->StdAlignValT = SemaDeclRefs[I+2];
  6595. }
  6596. SemaDeclRefs.clear();
  6597. }
  6598. // Update the state of pragmas. Use the same API as if we had encountered the
  6599. // pragma in the source.
  6600. if(OptimizeOffPragmaLocation.isValid())
  6601. SemaObj->ActOnPragmaOptimize(/* IsOn = */ false, OptimizeOffPragmaLocation);
  6602. if (PragmaMSStructState != -1)
  6603. SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
  6604. if (PointersToMembersPragmaLocation.isValid()) {
  6605. SemaObj->ActOnPragmaMSPointersToMembers(
  6606. (LangOptions::PragmaMSPointersToMembersKind)
  6607. PragmaMSPointersToMembersState,
  6608. PointersToMembersPragmaLocation);
  6609. }
  6610. SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
  6611. if (PragmaPackCurrentValue) {
  6612. // The bottom of the stack might have a default value. It must be adjusted
  6613. // to the current value to ensure that the packing state is preserved after
  6614. // popping entries that were included/imported from a PCH/module.
  6615. bool DropFirst = false;
  6616. if (!PragmaPackStack.empty() &&
  6617. PragmaPackStack.front().Location.isInvalid()) {
  6618. assert(PragmaPackStack.front().Value == SemaObj->PackStack.DefaultValue &&
  6619. "Expected a default alignment value");
  6620. SemaObj->PackStack.Stack.emplace_back(
  6621. PragmaPackStack.front().SlotLabel, SemaObj->PackStack.CurrentValue,
  6622. SemaObj->PackStack.CurrentPragmaLocation,
  6623. PragmaPackStack.front().PushLocation);
  6624. DropFirst = true;
  6625. }
  6626. for (const auto &Entry :
  6627. llvm::makeArrayRef(PragmaPackStack).drop_front(DropFirst ? 1 : 0))
  6628. SemaObj->PackStack.Stack.emplace_back(Entry.SlotLabel, Entry.Value,
  6629. Entry.Location, Entry.PushLocation);
  6630. if (PragmaPackCurrentLocation.isInvalid()) {
  6631. assert(*PragmaPackCurrentValue == SemaObj->PackStack.DefaultValue &&
  6632. "Expected a default alignment value");
  6633. // Keep the current values.
  6634. } else {
  6635. SemaObj->PackStack.CurrentValue = *PragmaPackCurrentValue;
  6636. SemaObj->PackStack.CurrentPragmaLocation = PragmaPackCurrentLocation;
  6637. }
  6638. }
  6639. }
  6640. IdentifierInfo *ASTReader::get(StringRef Name) {
  6641. // Note that we are loading an identifier.
  6642. Deserializing AnIdentifier(this);
  6643. IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
  6644. NumIdentifierLookups,
  6645. NumIdentifierLookupHits);
  6646. // We don't need to do identifier table lookups in C++ modules (we preload
  6647. // all interesting declarations, and don't need to use the scope for name
  6648. // lookups). Perform the lookup in PCH files, though, since we don't build
  6649. // a complete initial identifier table if we're carrying on from a PCH.
  6650. if (PP.getLangOpts().CPlusPlus) {
  6651. for (auto F : ModuleMgr.pch_modules())
  6652. if (Visitor(*F))
  6653. break;
  6654. } else {
  6655. // If there is a global index, look there first to determine which modules
  6656. // provably do not have any results for this identifier.
  6657. GlobalModuleIndex::HitSet Hits;
  6658. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  6659. if (!loadGlobalIndex()) {
  6660. if (GlobalIndex->lookupIdentifier(Name, Hits)) {
  6661. HitsPtr = &Hits;
  6662. }
  6663. }
  6664. ModuleMgr.visit(Visitor, HitsPtr);
  6665. }
  6666. IdentifierInfo *II = Visitor.getIdentifierInfo();
  6667. markIdentifierUpToDate(II);
  6668. return II;
  6669. }
  6670. namespace clang {
  6671. /// \brief An identifier-lookup iterator that enumerates all of the
  6672. /// identifiers stored within a set of AST files.
  6673. class ASTIdentifierIterator : public IdentifierIterator {
  6674. /// \brief The AST reader whose identifiers are being enumerated.
  6675. const ASTReader &Reader;
  6676. /// \brief The current index into the chain of AST files stored in
  6677. /// the AST reader.
  6678. unsigned Index;
  6679. /// \brief The current position within the identifier lookup table
  6680. /// of the current AST file.
  6681. ASTIdentifierLookupTable::key_iterator Current;
  6682. /// \brief The end position within the identifier lookup table of
  6683. /// the current AST file.
  6684. ASTIdentifierLookupTable::key_iterator End;
  6685. /// \brief Whether to skip any modules in the ASTReader.
  6686. bool SkipModules;
  6687. public:
  6688. explicit ASTIdentifierIterator(const ASTReader &Reader,
  6689. bool SkipModules = false);
  6690. StringRef Next() override;
  6691. };
  6692. } // namespace clang
  6693. ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
  6694. bool SkipModules)
  6695. : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
  6696. }
  6697. StringRef ASTIdentifierIterator::Next() {
  6698. while (Current == End) {
  6699. // If we have exhausted all of our AST files, we're done.
  6700. if (Index == 0)
  6701. return StringRef();
  6702. --Index;
  6703. ModuleFile &F = Reader.ModuleMgr[Index];
  6704. if (SkipModules && F.isModule())
  6705. continue;
  6706. ASTIdentifierLookupTable *IdTable =
  6707. (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
  6708. Current = IdTable->key_begin();
  6709. End = IdTable->key_end();
  6710. }
  6711. // We have any identifiers remaining in the current AST file; return
  6712. // the next one.
  6713. StringRef Result = *Current;
  6714. ++Current;
  6715. return Result;
  6716. }
  6717. namespace {
  6718. /// A utility for appending two IdentifierIterators.
  6719. class ChainedIdentifierIterator : public IdentifierIterator {
  6720. std::unique_ptr<IdentifierIterator> Current;
  6721. std::unique_ptr<IdentifierIterator> Queued;
  6722. public:
  6723. ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
  6724. std::unique_ptr<IdentifierIterator> Second)
  6725. : Current(std::move(First)), Queued(std::move(Second)) {}
  6726. StringRef Next() override {
  6727. if (!Current)
  6728. return StringRef();
  6729. StringRef result = Current->Next();
  6730. if (!result.empty())
  6731. return result;
  6732. // Try the queued iterator, which may itself be empty.
  6733. Current.reset();
  6734. std::swap(Current, Queued);
  6735. return Next();
  6736. }
  6737. };
  6738. } // namespace
  6739. IdentifierIterator *ASTReader::getIdentifiers() {
  6740. if (!loadGlobalIndex()) {
  6741. std::unique_ptr<IdentifierIterator> ReaderIter(
  6742. new ASTIdentifierIterator(*this, /*SkipModules=*/true));
  6743. std::unique_ptr<IdentifierIterator> ModulesIter(
  6744. GlobalIndex->createIdentifierIterator());
  6745. return new ChainedIdentifierIterator(std::move(ReaderIter),
  6746. std::move(ModulesIter));
  6747. }
  6748. return new ASTIdentifierIterator(*this);
  6749. }
  6750. namespace clang {
  6751. namespace serialization {
  6752. class ReadMethodPoolVisitor {
  6753. ASTReader &Reader;
  6754. Selector Sel;
  6755. unsigned PriorGeneration;
  6756. unsigned InstanceBits = 0;
  6757. unsigned FactoryBits = 0;
  6758. bool InstanceHasMoreThanOneDecl = false;
  6759. bool FactoryHasMoreThanOneDecl = false;
  6760. SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
  6761. SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
  6762. public:
  6763. ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
  6764. unsigned PriorGeneration)
  6765. : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
  6766. bool operator()(ModuleFile &M) {
  6767. if (!M.SelectorLookupTable)
  6768. return false;
  6769. // If we've already searched this module file, skip it now.
  6770. if (M.Generation <= PriorGeneration)
  6771. return true;
  6772. ++Reader.NumMethodPoolTableLookups;
  6773. ASTSelectorLookupTable *PoolTable
  6774. = (ASTSelectorLookupTable*)M.SelectorLookupTable;
  6775. ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
  6776. if (Pos == PoolTable->end())
  6777. return false;
  6778. ++Reader.NumMethodPoolTableHits;
  6779. ++Reader.NumSelectorsRead;
  6780. // FIXME: Not quite happy with the statistics here. We probably should
  6781. // disable this tracking when called via LoadSelector.
  6782. // Also, should entries without methods count as misses?
  6783. ++Reader.NumMethodPoolEntriesRead;
  6784. ASTSelectorLookupTrait::data_type Data = *Pos;
  6785. if (Reader.DeserializationListener)
  6786. Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
  6787. InstanceMethods.append(Data.Instance.begin(), Data.Instance.end());
  6788. FactoryMethods.append(Data.Factory.begin(), Data.Factory.end());
  6789. InstanceBits = Data.InstanceBits;
  6790. FactoryBits = Data.FactoryBits;
  6791. InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
  6792. FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
  6793. return true;
  6794. }
  6795. /// \brief Retrieve the instance methods found by this visitor.
  6796. ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
  6797. return InstanceMethods;
  6798. }
  6799. /// \brief Retrieve the instance methods found by this visitor.
  6800. ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
  6801. return FactoryMethods;
  6802. }
  6803. unsigned getInstanceBits() const { return InstanceBits; }
  6804. unsigned getFactoryBits() const { return FactoryBits; }
  6805. bool instanceHasMoreThanOneDecl() const {
  6806. return InstanceHasMoreThanOneDecl;
  6807. }
  6808. bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
  6809. };
  6810. } // namespace serialization
  6811. } // namespace clang
  6812. /// \brief Add the given set of methods to the method list.
  6813. static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
  6814. ObjCMethodList &List) {
  6815. for (unsigned I = 0, N = Methods.size(); I != N; ++I) {
  6816. S.addMethodToGlobalList(&List, Methods[I]);
  6817. }
  6818. }
  6819. void ASTReader::ReadMethodPool(Selector Sel) {
  6820. // Get the selector generation and update it to the current generation.
  6821. unsigned &Generation = SelectorGeneration[Sel];
  6822. unsigned PriorGeneration = Generation;
  6823. Generation = getGeneration();
  6824. SelectorOutOfDate[Sel] = false;
  6825. // Search for methods defined with this selector.
  6826. ++NumMethodPoolLookups;
  6827. ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
  6828. ModuleMgr.visit(Visitor);
  6829. if (Visitor.getInstanceMethods().empty() &&
  6830. Visitor.getFactoryMethods().empty())
  6831. return;
  6832. ++NumMethodPoolHits;
  6833. if (!getSema())
  6834. return;
  6835. Sema &S = *getSema();
  6836. Sema::GlobalMethodPool::iterator Pos
  6837. = S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethods())).first;
  6838. Pos->second.first.setBits(Visitor.getInstanceBits());
  6839. Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
  6840. Pos->second.second.setBits(Visitor.getFactoryBits());
  6841. Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
  6842. // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
  6843. // when building a module we keep every method individually and may need to
  6844. // update hasMoreThanOneDecl as we add the methods.
  6845. addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
  6846. addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
  6847. }
  6848. void ASTReader::updateOutOfDateSelector(Selector Sel) {
  6849. if (SelectorOutOfDate[Sel])
  6850. ReadMethodPool(Sel);
  6851. }
  6852. void ASTReader::ReadKnownNamespaces(
  6853. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  6854. Namespaces.clear();
  6855. for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
  6856. if (NamespaceDecl *Namespace
  6857. = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
  6858. Namespaces.push_back(Namespace);
  6859. }
  6860. }
  6861. void ASTReader::ReadUndefinedButUsed(
  6862. llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
  6863. for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
  6864. NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
  6865. SourceLocation Loc =
  6866. SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
  6867. Undefined.insert(std::make_pair(D, Loc));
  6868. }
  6869. }
  6870. void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
  6871. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
  6872. Exprs) {
  6873. for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
  6874. FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
  6875. uint64_t Count = DelayedDeleteExprs[Idx++];
  6876. for (uint64_t C = 0; C < Count; ++C) {
  6877. SourceLocation DeleteLoc =
  6878. SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
  6879. const bool IsArrayForm = DelayedDeleteExprs[Idx++];
  6880. Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
  6881. }
  6882. }
  6883. }
  6884. void ASTReader::ReadTentativeDefinitions(
  6885. SmallVectorImpl<VarDecl *> &TentativeDefs) {
  6886. for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
  6887. VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
  6888. if (Var)
  6889. TentativeDefs.push_back(Var);
  6890. }
  6891. TentativeDefinitions.clear();
  6892. }
  6893. void ASTReader::ReadUnusedFileScopedDecls(
  6894. SmallVectorImpl<const DeclaratorDecl *> &Decls) {
  6895. for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
  6896. DeclaratorDecl *D
  6897. = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
  6898. if (D)
  6899. Decls.push_back(D);
  6900. }
  6901. UnusedFileScopedDecls.clear();
  6902. }
  6903. void ASTReader::ReadDelegatingConstructors(
  6904. SmallVectorImpl<CXXConstructorDecl *> &Decls) {
  6905. for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
  6906. CXXConstructorDecl *D
  6907. = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
  6908. if (D)
  6909. Decls.push_back(D);
  6910. }
  6911. DelegatingCtorDecls.clear();
  6912. }
  6913. void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
  6914. for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
  6915. TypedefNameDecl *D
  6916. = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
  6917. if (D)
  6918. Decls.push_back(D);
  6919. }
  6920. ExtVectorDecls.clear();
  6921. }
  6922. void ASTReader::ReadUnusedLocalTypedefNameCandidates(
  6923. llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
  6924. for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
  6925. ++I) {
  6926. TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
  6927. GetDecl(UnusedLocalTypedefNameCandidates[I]));
  6928. if (D)
  6929. Decls.insert(D);
  6930. }
  6931. UnusedLocalTypedefNameCandidates.clear();
  6932. }
  6933. void ASTReader::ReadReferencedSelectors(
  6934. SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
  6935. if (ReferencedSelectorsData.empty())
  6936. return;
  6937. // If there are @selector references added them to its pool. This is for
  6938. // implementation of -Wselector.
  6939. unsigned int DataSize = ReferencedSelectorsData.size()-1;
  6940. unsigned I = 0;
  6941. while (I < DataSize) {
  6942. Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
  6943. SourceLocation SelLoc
  6944. = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
  6945. Sels.push_back(std::make_pair(Sel, SelLoc));
  6946. }
  6947. ReferencedSelectorsData.clear();
  6948. }
  6949. void ASTReader::ReadWeakUndeclaredIdentifiers(
  6950. SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
  6951. if (WeakUndeclaredIdentifiers.empty())
  6952. return;
  6953. for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
  6954. IdentifierInfo *WeakId
  6955. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  6956. IdentifierInfo *AliasId
  6957. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  6958. SourceLocation Loc
  6959. = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
  6960. bool Used = WeakUndeclaredIdentifiers[I++];
  6961. WeakInfo WI(AliasId, Loc);
  6962. WI.setUsed(Used);
  6963. WeakIDs.push_back(std::make_pair(WeakId, WI));
  6964. }
  6965. WeakUndeclaredIdentifiers.clear();
  6966. }
  6967. void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
  6968. for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
  6969. ExternalVTableUse VT;
  6970. VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
  6971. VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
  6972. VT.DefinitionRequired = VTableUses[Idx++];
  6973. VTables.push_back(VT);
  6974. }
  6975. VTableUses.clear();
  6976. }
  6977. void ASTReader::ReadPendingInstantiations(
  6978. SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
  6979. for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
  6980. ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
  6981. SourceLocation Loc
  6982. = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
  6983. Pending.push_back(std::make_pair(D, Loc));
  6984. }
  6985. PendingInstantiations.clear();
  6986. }
  6987. void ASTReader::ReadLateParsedTemplates(
  6988. llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
  6989. &LPTMap) {
  6990. for (unsigned Idx = 0, N = LateParsedTemplates.size(); Idx < N;
  6991. /* In loop */) {
  6992. FunctionDecl *FD = cast<FunctionDecl>(GetDecl(LateParsedTemplates[Idx++]));
  6993. auto LT = llvm::make_unique<LateParsedTemplate>();
  6994. LT->D = GetDecl(LateParsedTemplates[Idx++]);
  6995. ModuleFile *F = getOwningModuleFile(LT->D);
  6996. assert(F && "No module");
  6997. unsigned TokN = LateParsedTemplates[Idx++];
  6998. LT->Toks.reserve(TokN);
  6999. for (unsigned T = 0; T < TokN; ++T)
  7000. LT->Toks.push_back(ReadToken(*F, LateParsedTemplates, Idx));
  7001. LPTMap.insert(std::make_pair(FD, std::move(LT)));
  7002. }
  7003. LateParsedTemplates.clear();
  7004. }
  7005. void ASTReader::LoadSelector(Selector Sel) {
  7006. // It would be complicated to avoid reading the methods anyway. So don't.
  7007. ReadMethodPool(Sel);
  7008. }
  7009. void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
  7010. assert(ID && "Non-zero identifier ID required");
  7011. assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
  7012. IdentifiersLoaded[ID - 1] = II;
  7013. if (DeserializationListener)
  7014. DeserializationListener->IdentifierRead(ID, II);
  7015. }
  7016. /// \brief Set the globally-visible declarations associated with the given
  7017. /// identifier.
  7018. ///
  7019. /// If the AST reader is currently in a state where the given declaration IDs
  7020. /// cannot safely be resolved, they are queued until it is safe to resolve
  7021. /// them.
  7022. ///
  7023. /// \param II an IdentifierInfo that refers to one or more globally-visible
  7024. /// declarations.
  7025. ///
  7026. /// \param DeclIDs the set of declaration IDs with the name @p II that are
  7027. /// visible at global scope.
  7028. ///
  7029. /// \param Decls if non-null, this vector will be populated with the set of
  7030. /// deserialized declarations. These declarations will not be pushed into
  7031. /// scope.
  7032. void
  7033. ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
  7034. const SmallVectorImpl<uint32_t> &DeclIDs,
  7035. SmallVectorImpl<Decl *> *Decls) {
  7036. if (NumCurrentElementsDeserializing && !Decls) {
  7037. PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
  7038. return;
  7039. }
  7040. for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
  7041. if (!SemaObj) {
  7042. // Queue this declaration so that it will be added to the
  7043. // translation unit scope and identifier's declaration chain
  7044. // once a Sema object is known.
  7045. PreloadedDeclIDs.push_back(DeclIDs[I]);
  7046. continue;
  7047. }
  7048. NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
  7049. // If we're simply supposed to record the declarations, do so now.
  7050. if (Decls) {
  7051. Decls->push_back(D);
  7052. continue;
  7053. }
  7054. // Introduce this declaration into the translation-unit scope
  7055. // and add it to the declaration chain for this identifier, so
  7056. // that (unqualified) name lookup will find it.
  7057. pushExternalDeclIntoScope(D, II);
  7058. }
  7059. }
  7060. IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
  7061. if (ID == 0)
  7062. return nullptr;
  7063. if (IdentifiersLoaded.empty()) {
  7064. Error("no identifier table in AST file");
  7065. return nullptr;
  7066. }
  7067. ID -= 1;
  7068. if (!IdentifiersLoaded[ID]) {
  7069. GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
  7070. assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
  7071. ModuleFile *M = I->second;
  7072. unsigned Index = ID - M->BaseIdentifierID;
  7073. const char *Str = M->IdentifierTableData + M->IdentifierOffsets[Index];
  7074. // All of the strings in the AST file are preceded by a 16-bit length.
  7075. // Extract that 16-bit length to avoid having to execute strlen().
  7076. // NOTE: 'StrLenPtr' is an 'unsigned char*' so that we load bytes as
  7077. // unsigned integers. This is important to avoid integer overflow when
  7078. // we cast them to 'unsigned'.
  7079. const unsigned char *StrLenPtr = (const unsigned char*) Str - 2;
  7080. unsigned StrLen = (((unsigned) StrLenPtr[0])
  7081. | (((unsigned) StrLenPtr[1]) << 8)) - 1;
  7082. auto &II = PP.getIdentifierTable().get(StringRef(Str, StrLen));
  7083. IdentifiersLoaded[ID] = &II;
  7084. markIdentifierFromAST(*this, II);
  7085. if (DeserializationListener)
  7086. DeserializationListener->IdentifierRead(ID + 1, &II);
  7087. }
  7088. return IdentifiersLoaded[ID];
  7089. }
  7090. IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
  7091. return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
  7092. }
  7093. IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
  7094. if (LocalID < NUM_PREDEF_IDENT_IDS)
  7095. return LocalID;
  7096. if (!M.ModuleOffsetMap.empty())
  7097. ReadModuleOffsetMap(M);
  7098. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7099. = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
  7100. assert(I != M.IdentifierRemap.end()
  7101. && "Invalid index into identifier index remap");
  7102. return LocalID + I->second;
  7103. }
  7104. MacroInfo *ASTReader::getMacro(MacroID ID) {
  7105. if (ID == 0)
  7106. return nullptr;
  7107. if (MacrosLoaded.empty()) {
  7108. Error("no macro table in AST file");
  7109. return nullptr;
  7110. }
  7111. ID -= NUM_PREDEF_MACRO_IDS;
  7112. if (!MacrosLoaded[ID]) {
  7113. GlobalMacroMapType::iterator I
  7114. = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
  7115. assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
  7116. ModuleFile *M = I->second;
  7117. unsigned Index = ID - M->BaseMacroID;
  7118. MacrosLoaded[ID] = ReadMacroRecord(*M, M->MacroOffsets[Index]);
  7119. if (DeserializationListener)
  7120. DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
  7121. MacrosLoaded[ID]);
  7122. }
  7123. return MacrosLoaded[ID];
  7124. }
  7125. MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
  7126. if (LocalID < NUM_PREDEF_MACRO_IDS)
  7127. return LocalID;
  7128. if (!M.ModuleOffsetMap.empty())
  7129. ReadModuleOffsetMap(M);
  7130. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7131. = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
  7132. assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
  7133. return LocalID + I->second;
  7134. }
  7135. serialization::SubmoduleID
  7136. ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
  7137. if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
  7138. return LocalID;
  7139. if (!M.ModuleOffsetMap.empty())
  7140. ReadModuleOffsetMap(M);
  7141. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7142. = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
  7143. assert(I != M.SubmoduleRemap.end()
  7144. && "Invalid index into submodule index remap");
  7145. return LocalID + I->second;
  7146. }
  7147. Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
  7148. if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
  7149. assert(GlobalID == 0 && "Unhandled global submodule ID");
  7150. return nullptr;
  7151. }
  7152. if (GlobalID > SubmodulesLoaded.size()) {
  7153. Error("submodule ID out of range in AST file");
  7154. return nullptr;
  7155. }
  7156. return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
  7157. }
  7158. Module *ASTReader::getModule(unsigned ID) {
  7159. return getSubmodule(ID);
  7160. }
  7161. ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
  7162. if (ID & 1) {
  7163. // It's a module, look it up by submodule ID.
  7164. auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
  7165. return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
  7166. } else {
  7167. // It's a prefix (preamble, PCH, ...). Look it up by index.
  7168. unsigned IndexFromEnd = ID >> 1;
  7169. assert(IndexFromEnd && "got reference to unknown module file");
  7170. return getModuleManager().pch_modules().end()[-IndexFromEnd];
  7171. }
  7172. }
  7173. unsigned ASTReader::getModuleFileID(ModuleFile *F) {
  7174. if (!F)
  7175. return 1;
  7176. // For a file representing a module, use the submodule ID of the top-level
  7177. // module as the file ID. For any other kind of file, the number of such
  7178. // files loaded beforehand will be the same on reload.
  7179. // FIXME: Is this true even if we have an explicit module file and a PCH?
  7180. if (F->isModule())
  7181. return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
  7182. auto PCHModules = getModuleManager().pch_modules();
  7183. auto I = std::find(PCHModules.begin(), PCHModules.end(), F);
  7184. assert(I != PCHModules.end() && "emitting reference to unknown file");
  7185. return (I - PCHModules.end()) << 1;
  7186. }
  7187. llvm::Optional<ExternalASTSource::ASTSourceDescriptor>
  7188. ASTReader::getSourceDescriptor(unsigned ID) {
  7189. if (const Module *M = getSubmodule(ID))
  7190. return ExternalASTSource::ASTSourceDescriptor(*M);
  7191. // If there is only a single PCH, return it instead.
  7192. // Chained PCH are not supported.
  7193. const auto &PCHChain = ModuleMgr.pch_modules();
  7194. if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
  7195. ModuleFile &MF = ModuleMgr.getPrimaryModule();
  7196. StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
  7197. StringRef FileName = llvm::sys::path::filename(MF.FileName);
  7198. return ASTReader::ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
  7199. MF.Signature);
  7200. }
  7201. return None;
  7202. }
  7203. ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
  7204. auto I = DefinitionSource.find(FD);
  7205. if (I == DefinitionSource.end())
  7206. return EK_ReplyHazy;
  7207. return I->second ? EK_Never : EK_Always;
  7208. }
  7209. Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
  7210. return DecodeSelector(getGlobalSelectorID(M, LocalID));
  7211. }
  7212. Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
  7213. if (ID == 0)
  7214. return Selector();
  7215. if (ID > SelectorsLoaded.size()) {
  7216. Error("selector ID out of range in AST file");
  7217. return Selector();
  7218. }
  7219. if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
  7220. // Load this selector from the selector table.
  7221. GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
  7222. assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
  7223. ModuleFile &M = *I->second;
  7224. ASTSelectorLookupTrait Trait(*this, M);
  7225. unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
  7226. SelectorsLoaded[ID - 1] =
  7227. Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
  7228. if (DeserializationListener)
  7229. DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
  7230. }
  7231. return SelectorsLoaded[ID - 1];
  7232. }
  7233. Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
  7234. return DecodeSelector(ID);
  7235. }
  7236. uint32_t ASTReader::GetNumExternalSelectors() {
  7237. // ID 0 (the null selector) is considered an external selector.
  7238. return getTotalNumSelectors() + 1;
  7239. }
  7240. serialization::SelectorID
  7241. ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
  7242. if (LocalID < NUM_PREDEF_SELECTOR_IDS)
  7243. return LocalID;
  7244. if (!M.ModuleOffsetMap.empty())
  7245. ReadModuleOffsetMap(M);
  7246. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7247. = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
  7248. assert(I != M.SelectorRemap.end()
  7249. && "Invalid index into selector index remap");
  7250. return LocalID + I->second;
  7251. }
  7252. DeclarationName
  7253. ASTReader::ReadDeclarationName(ModuleFile &F,
  7254. const RecordData &Record, unsigned &Idx) {
  7255. ASTContext &Context = getContext();
  7256. DeclarationName::NameKind Kind = (DeclarationName::NameKind)Record[Idx++];
  7257. switch (Kind) {
  7258. case DeclarationName::Identifier:
  7259. return DeclarationName(GetIdentifierInfo(F, Record, Idx));
  7260. case DeclarationName::ObjCZeroArgSelector:
  7261. case DeclarationName::ObjCOneArgSelector:
  7262. case DeclarationName::ObjCMultiArgSelector:
  7263. return DeclarationName(ReadSelector(F, Record, Idx));
  7264. case DeclarationName::CXXConstructorName:
  7265. return Context.DeclarationNames.getCXXConstructorName(
  7266. Context.getCanonicalType(readType(F, Record, Idx)));
  7267. case DeclarationName::CXXDestructorName:
  7268. return Context.DeclarationNames.getCXXDestructorName(
  7269. Context.getCanonicalType(readType(F, Record, Idx)));
  7270. case DeclarationName::CXXDeductionGuideName:
  7271. return Context.DeclarationNames.getCXXDeductionGuideName(
  7272. ReadDeclAs<TemplateDecl>(F, Record, Idx));
  7273. case DeclarationName::CXXConversionFunctionName:
  7274. return Context.DeclarationNames.getCXXConversionFunctionName(
  7275. Context.getCanonicalType(readType(F, Record, Idx)));
  7276. case DeclarationName::CXXOperatorName:
  7277. return Context.DeclarationNames.getCXXOperatorName(
  7278. (OverloadedOperatorKind)Record[Idx++]);
  7279. case DeclarationName::CXXLiteralOperatorName:
  7280. return Context.DeclarationNames.getCXXLiteralOperatorName(
  7281. GetIdentifierInfo(F, Record, Idx));
  7282. case DeclarationName::CXXUsingDirective:
  7283. return DeclarationName::getUsingDirectiveName();
  7284. }
  7285. llvm_unreachable("Invalid NameKind!");
  7286. }
  7287. void ASTReader::ReadDeclarationNameLoc(ModuleFile &F,
  7288. DeclarationNameLoc &DNLoc,
  7289. DeclarationName Name,
  7290. const RecordData &Record, unsigned &Idx) {
  7291. switch (Name.getNameKind()) {
  7292. case DeclarationName::CXXConstructorName:
  7293. case DeclarationName::CXXDestructorName:
  7294. case DeclarationName::CXXConversionFunctionName:
  7295. DNLoc.NamedType.TInfo = GetTypeSourceInfo(F, Record, Idx);
  7296. break;
  7297. case DeclarationName::CXXOperatorName:
  7298. DNLoc.CXXOperatorName.BeginOpNameLoc
  7299. = ReadSourceLocation(F, Record, Idx).getRawEncoding();
  7300. DNLoc.CXXOperatorName.EndOpNameLoc
  7301. = ReadSourceLocation(F, Record, Idx).getRawEncoding();
  7302. break;
  7303. case DeclarationName::CXXLiteralOperatorName:
  7304. DNLoc.CXXLiteralOperatorName.OpNameLoc
  7305. = ReadSourceLocation(F, Record, Idx).getRawEncoding();
  7306. break;
  7307. case DeclarationName::Identifier:
  7308. case DeclarationName::ObjCZeroArgSelector:
  7309. case DeclarationName::ObjCOneArgSelector:
  7310. case DeclarationName::ObjCMultiArgSelector:
  7311. case DeclarationName::CXXUsingDirective:
  7312. case DeclarationName::CXXDeductionGuideName:
  7313. break;
  7314. }
  7315. }
  7316. void ASTReader::ReadDeclarationNameInfo(ModuleFile &F,
  7317. DeclarationNameInfo &NameInfo,
  7318. const RecordData &Record, unsigned &Idx) {
  7319. NameInfo.setName(ReadDeclarationName(F, Record, Idx));
  7320. NameInfo.setLoc(ReadSourceLocation(F, Record, Idx));
  7321. DeclarationNameLoc DNLoc;
  7322. ReadDeclarationNameLoc(F, DNLoc, NameInfo.getName(), Record, Idx);
  7323. NameInfo.setInfo(DNLoc);
  7324. }
  7325. void ASTReader::ReadQualifierInfo(ModuleFile &F, QualifierInfo &Info,
  7326. const RecordData &Record, unsigned &Idx) {
  7327. Info.QualifierLoc = ReadNestedNameSpecifierLoc(F, Record, Idx);
  7328. unsigned NumTPLists = Record[Idx++];
  7329. Info.NumTemplParamLists = NumTPLists;
  7330. if (NumTPLists) {
  7331. Info.TemplParamLists =
  7332. new (getContext()) TemplateParameterList *[NumTPLists];
  7333. for (unsigned i = 0; i != NumTPLists; ++i)
  7334. Info.TemplParamLists[i] = ReadTemplateParameterList(F, Record, Idx);
  7335. }
  7336. }
  7337. TemplateName
  7338. ASTReader::ReadTemplateName(ModuleFile &F, const RecordData &Record,
  7339. unsigned &Idx) {
  7340. ASTContext &Context = getContext();
  7341. TemplateName::NameKind Kind = (TemplateName::NameKind)Record[Idx++];
  7342. switch (Kind) {
  7343. case TemplateName::Template:
  7344. return TemplateName(ReadDeclAs<TemplateDecl>(F, Record, Idx));
  7345. case TemplateName::OverloadedTemplate: {
  7346. unsigned size = Record[Idx++];
  7347. UnresolvedSet<8> Decls;
  7348. while (size--)
  7349. Decls.addDecl(ReadDeclAs<NamedDecl>(F, Record, Idx));
  7350. return Context.getOverloadedTemplateName(Decls.begin(), Decls.end());
  7351. }
  7352. case TemplateName::QualifiedTemplate: {
  7353. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
  7354. bool hasTemplKeyword = Record[Idx++];
  7355. TemplateDecl *Template = ReadDeclAs<TemplateDecl>(F, Record, Idx);
  7356. return Context.getQualifiedTemplateName(NNS, hasTemplKeyword, Template);
  7357. }
  7358. case TemplateName::DependentTemplate: {
  7359. NestedNameSpecifier *NNS = ReadNestedNameSpecifier(F, Record, Idx);
  7360. if (Record[Idx++]) // isIdentifier
  7361. return Context.getDependentTemplateName(NNS,
  7362. GetIdentifierInfo(F, Record,
  7363. Idx));
  7364. return Context.getDependentTemplateName(NNS,
  7365. (OverloadedOperatorKind)Record[Idx++]);
  7366. }
  7367. case TemplateName::SubstTemplateTemplateParm: {
  7368. TemplateTemplateParmDecl *param
  7369. = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
  7370. if (!param) return TemplateName();
  7371. TemplateName replacement = ReadTemplateName(F, Record, Idx);
  7372. return Context.getSubstTemplateTemplateParm(param, replacement);
  7373. }
  7374. case TemplateName::SubstTemplateTemplateParmPack: {
  7375. TemplateTemplateParmDecl *Param
  7376. = ReadDeclAs<TemplateTemplateParmDecl>(F, Record, Idx);
  7377. if (!Param)
  7378. return TemplateName();
  7379. TemplateArgument ArgPack = ReadTemplateArgument(F, Record, Idx);
  7380. if (ArgPack.getKind() != TemplateArgument::Pack)
  7381. return TemplateName();
  7382. return Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
  7383. }
  7384. }
  7385. llvm_unreachable("Unhandled template name kind!");
  7386. }
  7387. TemplateArgument ASTReader::ReadTemplateArgument(ModuleFile &F,
  7388. const RecordData &Record,
  7389. unsigned &Idx,
  7390. bool Canonicalize) {
  7391. ASTContext &Context = getContext();
  7392. if (Canonicalize) {
  7393. // The caller wants a canonical template argument. Sometimes the AST only
  7394. // wants template arguments in canonical form (particularly as the template
  7395. // argument lists of template specializations) so ensure we preserve that
  7396. // canonical form across serialization.
  7397. TemplateArgument Arg = ReadTemplateArgument(F, Record, Idx, false);
  7398. return Context.getCanonicalTemplateArgument(Arg);
  7399. }
  7400. TemplateArgument::ArgKind Kind = (TemplateArgument::ArgKind)Record[Idx++];
  7401. switch (Kind) {
  7402. case TemplateArgument::Null:
  7403. return TemplateArgument();
  7404. case TemplateArgument::Type:
  7405. return TemplateArgument(readType(F, Record, Idx));
  7406. case TemplateArgument::Declaration: {
  7407. ValueDecl *D = ReadDeclAs<ValueDecl>(F, Record, Idx);
  7408. return TemplateArgument(D, readType(F, Record, Idx));
  7409. }
  7410. case TemplateArgument::NullPtr:
  7411. return TemplateArgument(readType(F, Record, Idx), /*isNullPtr*/true);
  7412. case TemplateArgument::Integral: {
  7413. llvm::APSInt Value = ReadAPSInt(Record, Idx);
  7414. QualType T = readType(F, Record, Idx);
  7415. return TemplateArgument(Context, Value, T);
  7416. }
  7417. case TemplateArgument::Template:
  7418. return TemplateArgument(ReadTemplateName(F, Record, Idx));
  7419. case TemplateArgument::TemplateExpansion: {
  7420. TemplateName Name = ReadTemplateName(F, Record, Idx);
  7421. Optional<unsigned> NumTemplateExpansions;
  7422. if (unsigned NumExpansions = Record[Idx++])
  7423. NumTemplateExpansions = NumExpansions - 1;
  7424. return TemplateArgument(Name, NumTemplateExpansions);
  7425. }
  7426. case TemplateArgument::Expression:
  7427. return TemplateArgument(ReadExpr(F));
  7428. case TemplateArgument::Pack: {
  7429. unsigned NumArgs = Record[Idx++];
  7430. TemplateArgument *Args = new (Context) TemplateArgument[NumArgs];
  7431. for (unsigned I = 0; I != NumArgs; ++I)
  7432. Args[I] = ReadTemplateArgument(F, Record, Idx);
  7433. return TemplateArgument(llvm::makeArrayRef(Args, NumArgs));
  7434. }
  7435. }
  7436. llvm_unreachable("Unhandled template argument kind!");
  7437. }
  7438. TemplateParameterList *
  7439. ASTReader::ReadTemplateParameterList(ModuleFile &F,
  7440. const RecordData &Record, unsigned &Idx) {
  7441. SourceLocation TemplateLoc = ReadSourceLocation(F, Record, Idx);
  7442. SourceLocation LAngleLoc = ReadSourceLocation(F, Record, Idx);
  7443. SourceLocation RAngleLoc = ReadSourceLocation(F, Record, Idx);
  7444. unsigned NumParams = Record[Idx++];
  7445. SmallVector<NamedDecl *, 16> Params;
  7446. Params.reserve(NumParams);
  7447. while (NumParams--)
  7448. Params.push_back(ReadDeclAs<NamedDecl>(F, Record, Idx));
  7449. // TODO: Concepts
  7450. TemplateParameterList *TemplateParams = TemplateParameterList::Create(
  7451. getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, nullptr);
  7452. return TemplateParams;
  7453. }
  7454. void
  7455. ASTReader::
  7456. ReadTemplateArgumentList(SmallVectorImpl<TemplateArgument> &TemplArgs,
  7457. ModuleFile &F, const RecordData &Record,
  7458. unsigned &Idx, bool Canonicalize) {
  7459. unsigned NumTemplateArgs = Record[Idx++];
  7460. TemplArgs.reserve(NumTemplateArgs);
  7461. while (NumTemplateArgs--)
  7462. TemplArgs.push_back(ReadTemplateArgument(F, Record, Idx, Canonicalize));
  7463. }
  7464. /// \brief Read a UnresolvedSet structure.
  7465. void ASTReader::ReadUnresolvedSet(ModuleFile &F, LazyASTUnresolvedSet &Set,
  7466. const RecordData &Record, unsigned &Idx) {
  7467. unsigned NumDecls = Record[Idx++];
  7468. Set.reserve(getContext(), NumDecls);
  7469. while (NumDecls--) {
  7470. DeclID ID = ReadDeclID(F, Record, Idx);
  7471. AccessSpecifier AS = (AccessSpecifier)Record[Idx++];
  7472. Set.addLazyDecl(getContext(), ID, AS);
  7473. }
  7474. }
  7475. CXXBaseSpecifier
  7476. ASTReader::ReadCXXBaseSpecifier(ModuleFile &F,
  7477. const RecordData &Record, unsigned &Idx) {
  7478. bool isVirtual = static_cast<bool>(Record[Idx++]);
  7479. bool isBaseOfClass = static_cast<bool>(Record[Idx++]);
  7480. AccessSpecifier AS = static_cast<AccessSpecifier>(Record[Idx++]);
  7481. bool inheritConstructors = static_cast<bool>(Record[Idx++]);
  7482. TypeSourceInfo *TInfo = GetTypeSourceInfo(F, Record, Idx);
  7483. SourceRange Range = ReadSourceRange(F, Record, Idx);
  7484. SourceLocation EllipsisLoc = ReadSourceLocation(F, Record, Idx);
  7485. CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
  7486. EllipsisLoc);
  7487. Result.setInheritConstructors(inheritConstructors);
  7488. return Result;
  7489. }
  7490. CXXCtorInitializer **
  7491. ASTReader::ReadCXXCtorInitializers(ModuleFile &F, const RecordData &Record,
  7492. unsigned &Idx) {
  7493. ASTContext &Context = getContext();
  7494. unsigned NumInitializers = Record[Idx++];
  7495. assert(NumInitializers && "wrote ctor initializers but have no inits");
  7496. auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
  7497. for (unsigned i = 0; i != NumInitializers; ++i) {
  7498. TypeSourceInfo *TInfo = nullptr;
  7499. bool IsBaseVirtual = false;
  7500. FieldDecl *Member = nullptr;
  7501. IndirectFieldDecl *IndirectMember = nullptr;
  7502. CtorInitializerType Type = (CtorInitializerType)Record[Idx++];
  7503. switch (Type) {
  7504. case CTOR_INITIALIZER_BASE:
  7505. TInfo = GetTypeSourceInfo(F, Record, Idx);
  7506. IsBaseVirtual = Record[Idx++];
  7507. break;
  7508. case CTOR_INITIALIZER_DELEGATING:
  7509. TInfo = GetTypeSourceInfo(F, Record, Idx);
  7510. break;
  7511. case CTOR_INITIALIZER_MEMBER:
  7512. Member = ReadDeclAs<FieldDecl>(F, Record, Idx);
  7513. break;
  7514. case CTOR_INITIALIZER_INDIRECT_MEMBER:
  7515. IndirectMember = ReadDeclAs<IndirectFieldDecl>(F, Record, Idx);
  7516. break;
  7517. }
  7518. SourceLocation MemberOrEllipsisLoc = ReadSourceLocation(F, Record, Idx);
  7519. Expr *Init = ReadExpr(F);
  7520. SourceLocation LParenLoc = ReadSourceLocation(F, Record, Idx);
  7521. SourceLocation RParenLoc = ReadSourceLocation(F, Record, Idx);
  7522. CXXCtorInitializer *BOMInit;
  7523. if (Type == CTOR_INITIALIZER_BASE)
  7524. BOMInit = new (Context)
  7525. CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
  7526. RParenLoc, MemberOrEllipsisLoc);
  7527. else if (Type == CTOR_INITIALIZER_DELEGATING)
  7528. BOMInit = new (Context)
  7529. CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
  7530. else if (Member)
  7531. BOMInit = new (Context)
  7532. CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
  7533. Init, RParenLoc);
  7534. else
  7535. BOMInit = new (Context)
  7536. CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
  7537. LParenLoc, Init, RParenLoc);
  7538. if (/*IsWritten*/Record[Idx++]) {
  7539. unsigned SourceOrder = Record[Idx++];
  7540. BOMInit->setSourceOrder(SourceOrder);
  7541. }
  7542. CtorInitializers[i] = BOMInit;
  7543. }
  7544. return CtorInitializers;
  7545. }
  7546. NestedNameSpecifier *
  7547. ASTReader::ReadNestedNameSpecifier(ModuleFile &F,
  7548. const RecordData &Record, unsigned &Idx) {
  7549. ASTContext &Context = getContext();
  7550. unsigned N = Record[Idx++];
  7551. NestedNameSpecifier *NNS = nullptr, *Prev = nullptr;
  7552. for (unsigned I = 0; I != N; ++I) {
  7553. NestedNameSpecifier::SpecifierKind Kind
  7554. = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
  7555. switch (Kind) {
  7556. case NestedNameSpecifier::Identifier: {
  7557. IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
  7558. NNS = NestedNameSpecifier::Create(Context, Prev, II);
  7559. break;
  7560. }
  7561. case NestedNameSpecifier::Namespace: {
  7562. NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
  7563. NNS = NestedNameSpecifier::Create(Context, Prev, NS);
  7564. break;
  7565. }
  7566. case NestedNameSpecifier::NamespaceAlias: {
  7567. NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
  7568. NNS = NestedNameSpecifier::Create(Context, Prev, Alias);
  7569. break;
  7570. }
  7571. case NestedNameSpecifier::TypeSpec:
  7572. case NestedNameSpecifier::TypeSpecWithTemplate: {
  7573. const Type *T = readType(F, Record, Idx).getTypePtrOrNull();
  7574. if (!T)
  7575. return nullptr;
  7576. bool Template = Record[Idx++];
  7577. NNS = NestedNameSpecifier::Create(Context, Prev, Template, T);
  7578. break;
  7579. }
  7580. case NestedNameSpecifier::Global:
  7581. NNS = NestedNameSpecifier::GlobalSpecifier(Context);
  7582. // No associated value, and there can't be a prefix.
  7583. break;
  7584. case NestedNameSpecifier::Super: {
  7585. CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
  7586. NNS = NestedNameSpecifier::SuperSpecifier(Context, RD);
  7587. break;
  7588. }
  7589. }
  7590. Prev = NNS;
  7591. }
  7592. return NNS;
  7593. }
  7594. NestedNameSpecifierLoc
  7595. ASTReader::ReadNestedNameSpecifierLoc(ModuleFile &F, const RecordData &Record,
  7596. unsigned &Idx) {
  7597. ASTContext &Context = getContext();
  7598. unsigned N = Record[Idx++];
  7599. NestedNameSpecifierLocBuilder Builder;
  7600. for (unsigned I = 0; I != N; ++I) {
  7601. NestedNameSpecifier::SpecifierKind Kind
  7602. = (NestedNameSpecifier::SpecifierKind)Record[Idx++];
  7603. switch (Kind) {
  7604. case NestedNameSpecifier::Identifier: {
  7605. IdentifierInfo *II = GetIdentifierInfo(F, Record, Idx);
  7606. SourceRange Range = ReadSourceRange(F, Record, Idx);
  7607. Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
  7608. break;
  7609. }
  7610. case NestedNameSpecifier::Namespace: {
  7611. NamespaceDecl *NS = ReadDeclAs<NamespaceDecl>(F, Record, Idx);
  7612. SourceRange Range = ReadSourceRange(F, Record, Idx);
  7613. Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
  7614. break;
  7615. }
  7616. case NestedNameSpecifier::NamespaceAlias: {
  7617. NamespaceAliasDecl *Alias =ReadDeclAs<NamespaceAliasDecl>(F, Record, Idx);
  7618. SourceRange Range = ReadSourceRange(F, Record, Idx);
  7619. Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
  7620. break;
  7621. }
  7622. case NestedNameSpecifier::TypeSpec:
  7623. case NestedNameSpecifier::TypeSpecWithTemplate: {
  7624. bool Template = Record[Idx++];
  7625. TypeSourceInfo *T = GetTypeSourceInfo(F, Record, Idx);
  7626. if (!T)
  7627. return NestedNameSpecifierLoc();
  7628. SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
  7629. // FIXME: 'template' keyword location not saved anywhere, so we fake it.
  7630. Builder.Extend(Context,
  7631. Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
  7632. T->getTypeLoc(), ColonColonLoc);
  7633. break;
  7634. }
  7635. case NestedNameSpecifier::Global: {
  7636. SourceLocation ColonColonLoc = ReadSourceLocation(F, Record, Idx);
  7637. Builder.MakeGlobal(Context, ColonColonLoc);
  7638. break;
  7639. }
  7640. case NestedNameSpecifier::Super: {
  7641. CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(F, Record, Idx);
  7642. SourceRange Range = ReadSourceRange(F, Record, Idx);
  7643. Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
  7644. break;
  7645. }
  7646. }
  7647. }
  7648. return Builder.getWithLocInContext(Context);
  7649. }
  7650. SourceRange
  7651. ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
  7652. unsigned &Idx) {
  7653. SourceLocation beg = ReadSourceLocation(F, Record, Idx);
  7654. SourceLocation end = ReadSourceLocation(F, Record, Idx);
  7655. return SourceRange(beg, end);
  7656. }
  7657. /// \brief Read an integral value
  7658. llvm::APInt ASTReader::ReadAPInt(const RecordData &Record, unsigned &Idx) {
  7659. unsigned BitWidth = Record[Idx++];
  7660. unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
  7661. llvm::APInt Result(BitWidth, NumWords, &Record[Idx]);
  7662. Idx += NumWords;
  7663. return Result;
  7664. }
  7665. /// \brief Read a signed integral value
  7666. llvm::APSInt ASTReader::ReadAPSInt(const RecordData &Record, unsigned &Idx) {
  7667. bool isUnsigned = Record[Idx++];
  7668. return llvm::APSInt(ReadAPInt(Record, Idx), isUnsigned);
  7669. }
  7670. /// \brief Read a floating-point value
  7671. llvm::APFloat ASTReader::ReadAPFloat(const RecordData &Record,
  7672. const llvm::fltSemantics &Sem,
  7673. unsigned &Idx) {
  7674. return llvm::APFloat(Sem, ReadAPInt(Record, Idx));
  7675. }
  7676. // \brief Read a string
  7677. std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
  7678. unsigned Len = Record[Idx++];
  7679. std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
  7680. Idx += Len;
  7681. return Result;
  7682. }
  7683. std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
  7684. unsigned &Idx) {
  7685. std::string Filename = ReadString(Record, Idx);
  7686. ResolveImportedPath(F, Filename);
  7687. return Filename;
  7688. }
  7689. VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
  7690. unsigned &Idx) {
  7691. unsigned Major = Record[Idx++];
  7692. unsigned Minor = Record[Idx++];
  7693. unsigned Subminor = Record[Idx++];
  7694. if (Minor == 0)
  7695. return VersionTuple(Major);
  7696. if (Subminor == 0)
  7697. return VersionTuple(Major, Minor - 1);
  7698. return VersionTuple(Major, Minor - 1, Subminor - 1);
  7699. }
  7700. CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
  7701. const RecordData &Record,
  7702. unsigned &Idx) {
  7703. CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
  7704. return CXXTemporary::Create(getContext(), Decl);
  7705. }
  7706. DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
  7707. return Diag(CurrentImportLoc, DiagID);
  7708. }
  7709. DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
  7710. return Diags.Report(Loc, DiagID);
  7711. }
  7712. /// \brief Retrieve the identifier table associated with the
  7713. /// preprocessor.
  7714. IdentifierTable &ASTReader::getIdentifierTable() {
  7715. return PP.getIdentifierTable();
  7716. }
  7717. /// \brief Record that the given ID maps to the given switch-case
  7718. /// statement.
  7719. void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
  7720. assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
  7721. "Already have a SwitchCase with this ID");
  7722. (*CurrSwitchCaseStmts)[ID] = SC;
  7723. }
  7724. /// \brief Retrieve the switch-case statement with the given ID.
  7725. SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
  7726. assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
  7727. return (*CurrSwitchCaseStmts)[ID];
  7728. }
  7729. void ASTReader::ClearSwitchCaseIDs() {
  7730. CurrSwitchCaseStmts->clear();
  7731. }
  7732. void ASTReader::ReadComments() {
  7733. ASTContext &Context = getContext();
  7734. std::vector<RawComment *> Comments;
  7735. for (SmallVectorImpl<std::pair<BitstreamCursor,
  7736. serialization::ModuleFile *>>::iterator
  7737. I = CommentsCursors.begin(),
  7738. E = CommentsCursors.end();
  7739. I != E; ++I) {
  7740. Comments.clear();
  7741. BitstreamCursor &Cursor = I->first;
  7742. serialization::ModuleFile &F = *I->second;
  7743. SavedStreamPosition SavedPosition(Cursor);
  7744. RecordData Record;
  7745. while (true) {
  7746. llvm::BitstreamEntry Entry =
  7747. Cursor.advanceSkippingSubblocks(BitstreamCursor::AF_DontPopBlockAtEnd);
  7748. switch (Entry.Kind) {
  7749. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  7750. case llvm::BitstreamEntry::Error:
  7751. Error("malformed block record in AST file");
  7752. return;
  7753. case llvm::BitstreamEntry::EndBlock:
  7754. goto NextCursor;
  7755. case llvm::BitstreamEntry::Record:
  7756. // The interesting case.
  7757. break;
  7758. }
  7759. // Read a record.
  7760. Record.clear();
  7761. switch ((CommentRecordTypes)Cursor.readRecord(Entry.ID, Record)) {
  7762. case COMMENTS_RAW_COMMENT: {
  7763. unsigned Idx = 0;
  7764. SourceRange SR = ReadSourceRange(F, Record, Idx);
  7765. RawComment::CommentKind Kind =
  7766. (RawComment::CommentKind) Record[Idx++];
  7767. bool IsTrailingComment = Record[Idx++];
  7768. bool IsAlmostTrailingComment = Record[Idx++];
  7769. Comments.push_back(new (Context) RawComment(
  7770. SR, Kind, IsTrailingComment, IsAlmostTrailingComment,
  7771. Context.getLangOpts().CommentOpts.ParseAllComments));
  7772. break;
  7773. }
  7774. }
  7775. }
  7776. NextCursor:
  7777. // De-serialized SourceLocations get negative FileIDs for other modules,
  7778. // potentially invalidating the original order. Sort it again.
  7779. std::sort(Comments.begin(), Comments.end(),
  7780. BeforeThanCompare<RawComment>(SourceMgr));
  7781. Context.Comments.addDeserializedComments(Comments);
  7782. }
  7783. }
  7784. void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
  7785. bool IncludeSystem, bool Complain,
  7786. llvm::function_ref<void(const serialization::InputFile &IF,
  7787. bool isSystem)> Visitor) {
  7788. unsigned NumUserInputs = MF.NumUserInputFiles;
  7789. unsigned NumInputs = MF.InputFilesLoaded.size();
  7790. assert(NumUserInputs <= NumInputs);
  7791. unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
  7792. for (unsigned I = 0; I < N; ++I) {
  7793. bool IsSystem = I >= NumUserInputs;
  7794. InputFile IF = getInputFile(MF, I+1, Complain);
  7795. Visitor(IF, IsSystem);
  7796. }
  7797. }
  7798. void ASTReader::visitTopLevelModuleMaps(
  7799. serialization::ModuleFile &MF,
  7800. llvm::function_ref<void(const FileEntry *FE)> Visitor) {
  7801. unsigned NumInputs = MF.InputFilesLoaded.size();
  7802. for (unsigned I = 0; I < NumInputs; ++I) {
  7803. InputFileInfo IFI = readInputFileInfo(MF, I + 1);
  7804. if (IFI.TopLevelModuleMap)
  7805. // FIXME: This unnecessarily re-reads the InputFileInfo.
  7806. if (auto *FE = getInputFile(MF, I + 1).getFile())
  7807. Visitor(FE);
  7808. }
  7809. }
  7810. std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
  7811. // If we know the owning module, use it.
  7812. if (Module *M = D->getImportedOwningModule())
  7813. return M->getFullModuleName();
  7814. // Otherwise, use the name of the top-level module the decl is within.
  7815. if (ModuleFile *M = getOwningModuleFile(D))
  7816. return M->ModuleName;
  7817. // Not from a module.
  7818. return {};
  7819. }
  7820. void ASTReader::finishPendingActions() {
  7821. while (!PendingIdentifierInfos.empty() ||
  7822. !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
  7823. !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
  7824. !PendingUpdateRecords.empty()) {
  7825. // If any identifiers with corresponding top-level declarations have
  7826. // been loaded, load those declarations now.
  7827. using TopLevelDeclsMap =
  7828. llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
  7829. TopLevelDeclsMap TopLevelDecls;
  7830. while (!PendingIdentifierInfos.empty()) {
  7831. IdentifierInfo *II = PendingIdentifierInfos.back().first;
  7832. SmallVector<uint32_t, 4> DeclIDs =
  7833. std::move(PendingIdentifierInfos.back().second);
  7834. PendingIdentifierInfos.pop_back();
  7835. SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
  7836. }
  7837. // For each decl chain that we wanted to complete while deserializing, mark
  7838. // it as "still needs to be completed".
  7839. for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
  7840. markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
  7841. }
  7842. PendingIncompleteDeclChains.clear();
  7843. // Load pending declaration chains.
  7844. for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
  7845. loadPendingDeclChain(PendingDeclChains[I].first, PendingDeclChains[I].second);
  7846. PendingDeclChains.clear();
  7847. // Make the most recent of the top-level declarations visible.
  7848. for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
  7849. TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
  7850. IdentifierInfo *II = TLD->first;
  7851. for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
  7852. pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
  7853. }
  7854. }
  7855. // Load any pending macro definitions.
  7856. for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
  7857. IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
  7858. SmallVector<PendingMacroInfo, 2> GlobalIDs;
  7859. GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
  7860. // Initialize the macro history from chained-PCHs ahead of module imports.
  7861. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  7862. ++IDIdx) {
  7863. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  7864. if (!Info.M->isModule())
  7865. resolvePendingMacro(II, Info);
  7866. }
  7867. // Handle module imports.
  7868. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  7869. ++IDIdx) {
  7870. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  7871. if (Info.M->isModule())
  7872. resolvePendingMacro(II, Info);
  7873. }
  7874. }
  7875. PendingMacroIDs.clear();
  7876. // Wire up the DeclContexts for Decls that we delayed setting until
  7877. // recursive loading is completed.
  7878. while (!PendingDeclContextInfos.empty()) {
  7879. PendingDeclContextInfo Info = PendingDeclContextInfos.front();
  7880. PendingDeclContextInfos.pop_front();
  7881. DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
  7882. DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
  7883. Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
  7884. }
  7885. // Perform any pending declaration updates.
  7886. while (!PendingUpdateRecords.empty()) {
  7887. auto Update = PendingUpdateRecords.pop_back_val();
  7888. ReadingKindTracker ReadingKind(Read_Decl, *this);
  7889. loadDeclUpdateRecords(Update);
  7890. }
  7891. }
  7892. // At this point, all update records for loaded decls are in place, so any
  7893. // fake class definitions should have become real.
  7894. assert(PendingFakeDefinitionData.empty() &&
  7895. "faked up a class definition but never saw the real one");
  7896. // If we deserialized any C++ or Objective-C class definitions, any
  7897. // Objective-C protocol definitions, or any redeclarable templates, make sure
  7898. // that all redeclarations point to the definitions. Note that this can only
  7899. // happen now, after the redeclaration chains have been fully wired.
  7900. for (Decl *D : PendingDefinitions) {
  7901. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  7902. if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
  7903. // Make sure that the TagType points at the definition.
  7904. const_cast<TagType*>(TagT)->decl = TD;
  7905. }
  7906. if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
  7907. for (auto *R = getMostRecentExistingDecl(RD); R;
  7908. R = R->getPreviousDecl()) {
  7909. assert((R == D) ==
  7910. cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
  7911. "declaration thinks it's the definition but it isn't");
  7912. cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
  7913. }
  7914. }
  7915. continue;
  7916. }
  7917. if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
  7918. // Make sure that the ObjCInterfaceType points at the definition.
  7919. const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
  7920. ->Decl = ID;
  7921. for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
  7922. cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
  7923. continue;
  7924. }
  7925. if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
  7926. for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
  7927. cast<ObjCProtocolDecl>(R)->Data = PD->Data;
  7928. continue;
  7929. }
  7930. auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
  7931. for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
  7932. cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
  7933. }
  7934. PendingDefinitions.clear();
  7935. // Load the bodies of any functions or methods we've encountered. We do
  7936. // this now (delayed) so that we can be sure that the declaration chains
  7937. // have been fully wired up (hasBody relies on this).
  7938. // FIXME: We shouldn't require complete redeclaration chains here.
  7939. for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
  7940. PBEnd = PendingBodies.end();
  7941. PB != PBEnd; ++PB) {
  7942. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
  7943. // FIXME: Check for =delete/=default?
  7944. // FIXME: Complain about ODR violations here?
  7945. const FunctionDecl *Defn = nullptr;
  7946. if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
  7947. FD->setLazyBody(PB->second);
  7948. } else
  7949. mergeDefinitionVisibility(const_cast<FunctionDecl*>(Defn), FD);
  7950. continue;
  7951. }
  7952. ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
  7953. if (!getContext().getLangOpts().Modules || !MD->hasBody())
  7954. MD->setLazyBody(PB->second);
  7955. }
  7956. PendingBodies.clear();
  7957. // Do some cleanup.
  7958. for (auto *ND : PendingMergedDefinitionsToDeduplicate)
  7959. getContext().deduplicateMergedDefinitonsFor(ND);
  7960. PendingMergedDefinitionsToDeduplicate.clear();
  7961. }
  7962. void ASTReader::diagnoseOdrViolations() {
  7963. if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty())
  7964. return;
  7965. // Trigger the import of the full definition of each class that had any
  7966. // odr-merging problems, so we can produce better diagnostics for them.
  7967. // These updates may in turn find and diagnose some ODR failures, so take
  7968. // ownership of the set first.
  7969. auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
  7970. PendingOdrMergeFailures.clear();
  7971. for (auto &Merge : OdrMergeFailures) {
  7972. Merge.first->buildLookup();
  7973. Merge.first->decls_begin();
  7974. Merge.first->bases_begin();
  7975. Merge.first->vbases_begin();
  7976. for (auto &RecordPair : Merge.second) {
  7977. auto *RD = RecordPair.first;
  7978. RD->decls_begin();
  7979. RD->bases_begin();
  7980. RD->vbases_begin();
  7981. }
  7982. }
  7983. // For each declaration from a merged context, check that the canonical
  7984. // definition of that context also contains a declaration of the same
  7985. // entity.
  7986. //
  7987. // Caution: this loop does things that might invalidate iterators into
  7988. // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
  7989. while (!PendingOdrMergeChecks.empty()) {
  7990. NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
  7991. // FIXME: Skip over implicit declarations for now. This matters for things
  7992. // like implicitly-declared special member functions. This isn't entirely
  7993. // correct; we can end up with multiple unmerged declarations of the same
  7994. // implicit entity.
  7995. if (D->isImplicit())
  7996. continue;
  7997. DeclContext *CanonDef = D->getDeclContext();
  7998. bool Found = false;
  7999. const Decl *DCanon = D->getCanonicalDecl();
  8000. for (auto RI : D->redecls()) {
  8001. if (RI->getLexicalDeclContext() == CanonDef) {
  8002. Found = true;
  8003. break;
  8004. }
  8005. }
  8006. if (Found)
  8007. continue;
  8008. // Quick check failed, time to do the slow thing. Note, we can't just
  8009. // look up the name of D in CanonDef here, because the member that is
  8010. // in CanonDef might not be found by name lookup (it might have been
  8011. // replaced by a more recent declaration in the lookup table), and we
  8012. // can't necessarily find it in the redeclaration chain because it might
  8013. // be merely mergeable, not redeclarable.
  8014. llvm::SmallVector<const NamedDecl*, 4> Candidates;
  8015. for (auto *CanonMember : CanonDef->decls()) {
  8016. if (CanonMember->getCanonicalDecl() == DCanon) {
  8017. // This can happen if the declaration is merely mergeable and not
  8018. // actually redeclarable (we looked for redeclarations earlier).
  8019. //
  8020. // FIXME: We should be able to detect this more efficiently, without
  8021. // pulling in all of the members of CanonDef.
  8022. Found = true;
  8023. break;
  8024. }
  8025. if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
  8026. if (ND->getDeclName() == D->getDeclName())
  8027. Candidates.push_back(ND);
  8028. }
  8029. if (!Found) {
  8030. // The AST doesn't like TagDecls becoming invalid after they've been
  8031. // completed. We only really need to mark FieldDecls as invalid here.
  8032. if (!isa<TagDecl>(D))
  8033. D->setInvalidDecl();
  8034. // Ensure we don't accidentally recursively enter deserialization while
  8035. // we're producing our diagnostic.
  8036. Deserializing RecursionGuard(this);
  8037. std::string CanonDefModule =
  8038. getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
  8039. Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
  8040. << D << getOwningModuleNameForDiagnostic(D)
  8041. << CanonDef << CanonDefModule.empty() << CanonDefModule;
  8042. if (Candidates.empty())
  8043. Diag(cast<Decl>(CanonDef)->getLocation(),
  8044. diag::note_module_odr_violation_no_possible_decls) << D;
  8045. else {
  8046. for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
  8047. Diag(Candidates[I]->getLocation(),
  8048. diag::note_module_odr_violation_possible_decl)
  8049. << Candidates[I];
  8050. }
  8051. DiagnosedOdrMergeFailures.insert(CanonDef);
  8052. }
  8053. }
  8054. if (OdrMergeFailures.empty())
  8055. return;
  8056. // Ensure we don't accidentally recursively enter deserialization while
  8057. // we're producing our diagnostics.
  8058. Deserializing RecursionGuard(this);
  8059. // Issue any pending ODR-failure diagnostics.
  8060. for (auto &Merge : OdrMergeFailures) {
  8061. // If we've already pointed out a specific problem with this class, don't
  8062. // bother issuing a general "something's different" diagnostic.
  8063. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
  8064. continue;
  8065. bool Diagnosed = false;
  8066. CXXRecordDecl *FirstRecord = Merge.first;
  8067. std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
  8068. for (auto &RecordPair : Merge.second) {
  8069. CXXRecordDecl *SecondRecord = RecordPair.first;
  8070. // Multiple different declarations got merged together; tell the user
  8071. // where they came from.
  8072. if (FirstRecord == SecondRecord)
  8073. continue;
  8074. std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
  8075. auto *FirstDD = FirstRecord->DefinitionData;
  8076. auto *SecondDD = RecordPair.second;
  8077. assert(FirstDD && SecondDD && "Definitions without DefinitionData");
  8078. // Diagnostics from DefinitionData are emitted here.
  8079. if (FirstDD != SecondDD) {
  8080. enum ODRDefinitionDataDifference {
  8081. NumBases,
  8082. NumVBases,
  8083. BaseType,
  8084. BaseVirtual,
  8085. BaseAccess,
  8086. };
  8087. auto ODRDiagError = [FirstRecord, &FirstModule,
  8088. this](SourceLocation Loc, SourceRange Range,
  8089. ODRDefinitionDataDifference DiffType) {
  8090. return Diag(Loc, diag::err_module_odr_violation_definition_data)
  8091. << FirstRecord << FirstModule.empty() << FirstModule << Range
  8092. << DiffType;
  8093. };
  8094. auto ODRDiagNote = [&SecondModule,
  8095. this](SourceLocation Loc, SourceRange Range,
  8096. ODRDefinitionDataDifference DiffType) {
  8097. return Diag(Loc, diag::note_module_odr_violation_definition_data)
  8098. << SecondModule << Range << DiffType;
  8099. };
  8100. ODRHash Hash;
  8101. auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
  8102. Hash.clear();
  8103. Hash.AddQualType(Ty);
  8104. return Hash.CalculateHash();
  8105. };
  8106. unsigned FirstNumBases = FirstDD->NumBases;
  8107. unsigned FirstNumVBases = FirstDD->NumVBases;
  8108. unsigned SecondNumBases = SecondDD->NumBases;
  8109. unsigned SecondNumVBases = SecondDD->NumVBases;
  8110. auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
  8111. unsigned NumBases = DD->NumBases;
  8112. if (NumBases == 0) return SourceRange();
  8113. auto bases = DD->bases();
  8114. return SourceRange(bases[0].getLocStart(),
  8115. bases[NumBases - 1].getLocEnd());
  8116. };
  8117. if (FirstNumBases != SecondNumBases) {
  8118. ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
  8119. NumBases)
  8120. << FirstNumBases;
  8121. ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
  8122. NumBases)
  8123. << SecondNumBases;
  8124. Diagnosed = true;
  8125. break;
  8126. }
  8127. if (FirstNumVBases != SecondNumVBases) {
  8128. ODRDiagError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
  8129. NumVBases)
  8130. << FirstNumVBases;
  8131. ODRDiagNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
  8132. NumVBases)
  8133. << SecondNumVBases;
  8134. Diagnosed = true;
  8135. break;
  8136. }
  8137. auto FirstBases = FirstDD->bases();
  8138. auto SecondBases = SecondDD->bases();
  8139. unsigned i = 0;
  8140. for (i = 0; i < FirstNumBases; ++i) {
  8141. auto FirstBase = FirstBases[i];
  8142. auto SecondBase = SecondBases[i];
  8143. if (ComputeQualTypeODRHash(FirstBase.getType()) !=
  8144. ComputeQualTypeODRHash(SecondBase.getType())) {
  8145. ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
  8146. BaseType)
  8147. << (i + 1) << FirstBase.getType();
  8148. ODRDiagNote(SecondRecord->getLocation(),
  8149. SecondBase.getSourceRange(), BaseType)
  8150. << (i + 1) << SecondBase.getType();
  8151. break;
  8152. }
  8153. if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
  8154. ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
  8155. BaseVirtual)
  8156. << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
  8157. ODRDiagNote(SecondRecord->getLocation(),
  8158. SecondBase.getSourceRange(), BaseVirtual)
  8159. << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
  8160. break;
  8161. }
  8162. if (FirstBase.getAccessSpecifierAsWritten() !=
  8163. SecondBase.getAccessSpecifierAsWritten()) {
  8164. ODRDiagError(FirstRecord->getLocation(), FirstBase.getSourceRange(),
  8165. BaseAccess)
  8166. << (i + 1) << FirstBase.getType()
  8167. << (int)FirstBase.getAccessSpecifierAsWritten();
  8168. ODRDiagNote(SecondRecord->getLocation(),
  8169. SecondBase.getSourceRange(), BaseAccess)
  8170. << (i + 1) << SecondBase.getType()
  8171. << (int)SecondBase.getAccessSpecifierAsWritten();
  8172. break;
  8173. }
  8174. }
  8175. if (i != FirstNumBases) {
  8176. Diagnosed = true;
  8177. break;
  8178. }
  8179. }
  8180. using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
  8181. const ClassTemplateDecl *FirstTemplate =
  8182. FirstRecord->getDescribedClassTemplate();
  8183. const ClassTemplateDecl *SecondTemplate =
  8184. SecondRecord->getDescribedClassTemplate();
  8185. assert(!FirstTemplate == !SecondTemplate &&
  8186. "Both pointers should be null or non-null");
  8187. enum ODRTemplateDifference {
  8188. ParamEmptyName,
  8189. ParamName,
  8190. ParamSingleDefaultArgument,
  8191. ParamDifferentDefaultArgument,
  8192. };
  8193. if (FirstTemplate && SecondTemplate) {
  8194. DeclHashes FirstTemplateHashes;
  8195. DeclHashes SecondTemplateHashes;
  8196. ODRHash Hash;
  8197. auto PopulateTemplateParameterHashs =
  8198. [&Hash](DeclHashes &Hashes, const ClassTemplateDecl *TD) {
  8199. for (auto *D : TD->getTemplateParameters()->asArray()) {
  8200. Hash.clear();
  8201. Hash.AddSubDecl(D);
  8202. Hashes.emplace_back(D, Hash.CalculateHash());
  8203. }
  8204. };
  8205. PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
  8206. PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
  8207. assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
  8208. "Number of template parameters should be equal.");
  8209. auto FirstIt = FirstTemplateHashes.begin();
  8210. auto FirstEnd = FirstTemplateHashes.end();
  8211. auto SecondIt = SecondTemplateHashes.begin();
  8212. for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
  8213. if (FirstIt->second == SecondIt->second)
  8214. continue;
  8215. auto ODRDiagError = [FirstRecord, &FirstModule,
  8216. this](SourceLocation Loc, SourceRange Range,
  8217. ODRTemplateDifference DiffType) {
  8218. return Diag(Loc, diag::err_module_odr_violation_template_parameter)
  8219. << FirstRecord << FirstModule.empty() << FirstModule << Range
  8220. << DiffType;
  8221. };
  8222. auto ODRDiagNote = [&SecondModule,
  8223. this](SourceLocation Loc, SourceRange Range,
  8224. ODRTemplateDifference DiffType) {
  8225. return Diag(Loc, diag::note_module_odr_violation_template_parameter)
  8226. << SecondModule << Range << DiffType;
  8227. };
  8228. const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
  8229. const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
  8230. assert(FirstDecl->getKind() == SecondDecl->getKind() &&
  8231. "Parameter Decl's should be the same kind.");
  8232. DeclarationName FirstName = FirstDecl->getDeclName();
  8233. DeclarationName SecondName = SecondDecl->getDeclName();
  8234. if (FirstName != SecondName) {
  8235. const bool FirstNameEmpty =
  8236. FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
  8237. const bool SecondNameEmpty =
  8238. SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
  8239. assert((!FirstNameEmpty || !SecondNameEmpty) &&
  8240. "Both template parameters cannot be unnamed.");
  8241. ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
  8242. FirstNameEmpty ? ParamEmptyName : ParamName)
  8243. << FirstName;
  8244. ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
  8245. SecondNameEmpty ? ParamEmptyName : ParamName)
  8246. << SecondName;
  8247. break;
  8248. }
  8249. switch (FirstDecl->getKind()) {
  8250. default:
  8251. llvm_unreachable("Invalid template parameter type.");
  8252. case Decl::TemplateTypeParm: {
  8253. const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
  8254. const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
  8255. const bool HasFirstDefaultArgument =
  8256. FirstParam->hasDefaultArgument() &&
  8257. !FirstParam->defaultArgumentWasInherited();
  8258. const bool HasSecondDefaultArgument =
  8259. SecondParam->hasDefaultArgument() &&
  8260. !SecondParam->defaultArgumentWasInherited();
  8261. if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
  8262. ODRDiagError(FirstDecl->getLocation(),
  8263. FirstDecl->getSourceRange(),
  8264. ParamSingleDefaultArgument)
  8265. << HasFirstDefaultArgument;
  8266. ODRDiagNote(SecondDecl->getLocation(),
  8267. SecondDecl->getSourceRange(),
  8268. ParamSingleDefaultArgument)
  8269. << HasSecondDefaultArgument;
  8270. break;
  8271. }
  8272. assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
  8273. "Expecting default arguments.");
  8274. ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
  8275. ParamDifferentDefaultArgument);
  8276. ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
  8277. ParamDifferentDefaultArgument);
  8278. break;
  8279. }
  8280. case Decl::NonTypeTemplateParm: {
  8281. const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
  8282. const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
  8283. const bool HasFirstDefaultArgument =
  8284. FirstParam->hasDefaultArgument() &&
  8285. !FirstParam->defaultArgumentWasInherited();
  8286. const bool HasSecondDefaultArgument =
  8287. SecondParam->hasDefaultArgument() &&
  8288. !SecondParam->defaultArgumentWasInherited();
  8289. if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
  8290. ODRDiagError(FirstDecl->getLocation(),
  8291. FirstDecl->getSourceRange(),
  8292. ParamSingleDefaultArgument)
  8293. << HasFirstDefaultArgument;
  8294. ODRDiagNote(SecondDecl->getLocation(),
  8295. SecondDecl->getSourceRange(),
  8296. ParamSingleDefaultArgument)
  8297. << HasSecondDefaultArgument;
  8298. break;
  8299. }
  8300. assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
  8301. "Expecting default arguments.");
  8302. ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
  8303. ParamDifferentDefaultArgument);
  8304. ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
  8305. ParamDifferentDefaultArgument);
  8306. break;
  8307. }
  8308. case Decl::TemplateTemplateParm: {
  8309. const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
  8310. const auto *SecondParam =
  8311. cast<TemplateTemplateParmDecl>(SecondDecl);
  8312. const bool HasFirstDefaultArgument =
  8313. FirstParam->hasDefaultArgument() &&
  8314. !FirstParam->defaultArgumentWasInherited();
  8315. const bool HasSecondDefaultArgument =
  8316. SecondParam->hasDefaultArgument() &&
  8317. !SecondParam->defaultArgumentWasInherited();
  8318. if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
  8319. ODRDiagError(FirstDecl->getLocation(),
  8320. FirstDecl->getSourceRange(),
  8321. ParamSingleDefaultArgument)
  8322. << HasFirstDefaultArgument;
  8323. ODRDiagNote(SecondDecl->getLocation(),
  8324. SecondDecl->getSourceRange(),
  8325. ParamSingleDefaultArgument)
  8326. << HasSecondDefaultArgument;
  8327. break;
  8328. }
  8329. assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
  8330. "Expecting default arguments.");
  8331. ODRDiagError(FirstDecl->getLocation(), FirstDecl->getSourceRange(),
  8332. ParamDifferentDefaultArgument);
  8333. ODRDiagNote(SecondDecl->getLocation(), SecondDecl->getSourceRange(),
  8334. ParamDifferentDefaultArgument);
  8335. break;
  8336. }
  8337. }
  8338. break;
  8339. }
  8340. if (FirstIt != FirstEnd) {
  8341. Diagnosed = true;
  8342. break;
  8343. }
  8344. }
  8345. DeclHashes FirstHashes;
  8346. DeclHashes SecondHashes;
  8347. ODRHash Hash;
  8348. auto PopulateHashes = [&Hash, FirstRecord](DeclHashes &Hashes,
  8349. CXXRecordDecl *Record) {
  8350. for (auto *D : Record->decls()) {
  8351. // Due to decl merging, the first CXXRecordDecl is the parent of
  8352. // Decls in both records.
  8353. if (!ODRHash::isWhitelistedDecl(D, FirstRecord))
  8354. continue;
  8355. Hash.clear();
  8356. Hash.AddSubDecl(D);
  8357. Hashes.emplace_back(D, Hash.CalculateHash());
  8358. }
  8359. };
  8360. PopulateHashes(FirstHashes, FirstRecord);
  8361. PopulateHashes(SecondHashes, SecondRecord);
  8362. // Used with err_module_odr_violation_mismatch_decl and
  8363. // note_module_odr_violation_mismatch_decl
  8364. // This list should be the same Decl's as in ODRHash::isWhiteListedDecl
  8365. enum {
  8366. EndOfClass,
  8367. PublicSpecifer,
  8368. PrivateSpecifer,
  8369. ProtectedSpecifer,
  8370. StaticAssert,
  8371. Field,
  8372. CXXMethod,
  8373. TypeAlias,
  8374. TypeDef,
  8375. Var,
  8376. Friend,
  8377. Other
  8378. } FirstDiffType = Other,
  8379. SecondDiffType = Other;
  8380. auto DifferenceSelector = [](Decl *D) {
  8381. assert(D && "valid Decl required");
  8382. switch (D->getKind()) {
  8383. default:
  8384. return Other;
  8385. case Decl::AccessSpec:
  8386. switch (D->getAccess()) {
  8387. case AS_public:
  8388. return PublicSpecifer;
  8389. case AS_private:
  8390. return PrivateSpecifer;
  8391. case AS_protected:
  8392. return ProtectedSpecifer;
  8393. case AS_none:
  8394. break;
  8395. }
  8396. llvm_unreachable("Invalid access specifier");
  8397. case Decl::StaticAssert:
  8398. return StaticAssert;
  8399. case Decl::Field:
  8400. return Field;
  8401. case Decl::CXXMethod:
  8402. case Decl::CXXConstructor:
  8403. case Decl::CXXDestructor:
  8404. return CXXMethod;
  8405. case Decl::TypeAlias:
  8406. return TypeAlias;
  8407. case Decl::Typedef:
  8408. return TypeDef;
  8409. case Decl::Var:
  8410. return Var;
  8411. case Decl::Friend:
  8412. return Friend;
  8413. }
  8414. };
  8415. Decl *FirstDecl = nullptr;
  8416. Decl *SecondDecl = nullptr;
  8417. auto FirstIt = FirstHashes.begin();
  8418. auto SecondIt = SecondHashes.begin();
  8419. // If there is a diagnoseable difference, FirstDiffType and
  8420. // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
  8421. // filled in if not EndOfClass.
  8422. while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
  8423. if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
  8424. FirstIt->second == SecondIt->second) {
  8425. ++FirstIt;
  8426. ++SecondIt;
  8427. continue;
  8428. }
  8429. FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
  8430. SecondDecl = SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
  8431. FirstDiffType = FirstDecl ? DifferenceSelector(FirstDecl) : EndOfClass;
  8432. SecondDiffType =
  8433. SecondDecl ? DifferenceSelector(SecondDecl) : EndOfClass;
  8434. break;
  8435. }
  8436. if (FirstDiffType == Other || SecondDiffType == Other) {
  8437. // Reaching this point means an unexpected Decl was encountered
  8438. // or no difference was detected. This causes a generic error
  8439. // message to be emitted.
  8440. Diag(FirstRecord->getLocation(),
  8441. diag::err_module_odr_violation_different_definitions)
  8442. << FirstRecord << FirstModule.empty() << FirstModule;
  8443. if (FirstDecl) {
  8444. Diag(FirstDecl->getLocation(), diag::note_first_module_difference)
  8445. << FirstRecord << FirstDecl->getSourceRange();
  8446. }
  8447. Diag(SecondRecord->getLocation(),
  8448. diag::note_module_odr_violation_different_definitions)
  8449. << SecondModule;
  8450. if (SecondDecl) {
  8451. Diag(SecondDecl->getLocation(), diag::note_second_module_difference)
  8452. << SecondDecl->getSourceRange();
  8453. }
  8454. Diagnosed = true;
  8455. break;
  8456. }
  8457. if (FirstDiffType != SecondDiffType) {
  8458. SourceLocation FirstLoc;
  8459. SourceRange FirstRange;
  8460. if (FirstDiffType == EndOfClass) {
  8461. FirstLoc = FirstRecord->getBraceRange().getEnd();
  8462. } else {
  8463. FirstLoc = FirstIt->first->getLocation();
  8464. FirstRange = FirstIt->first->getSourceRange();
  8465. }
  8466. Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
  8467. << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
  8468. << FirstDiffType;
  8469. SourceLocation SecondLoc;
  8470. SourceRange SecondRange;
  8471. if (SecondDiffType == EndOfClass) {
  8472. SecondLoc = SecondRecord->getBraceRange().getEnd();
  8473. } else {
  8474. SecondLoc = SecondDecl->getLocation();
  8475. SecondRange = SecondDecl->getSourceRange();
  8476. }
  8477. Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
  8478. << SecondModule << SecondRange << SecondDiffType;
  8479. Diagnosed = true;
  8480. break;
  8481. }
  8482. assert(FirstDiffType == SecondDiffType);
  8483. // Used with err_module_odr_violation_mismatch_decl_diff and
  8484. // note_module_odr_violation_mismatch_decl_diff
  8485. enum ODRDeclDifference{
  8486. StaticAssertCondition,
  8487. StaticAssertMessage,
  8488. StaticAssertOnlyMessage,
  8489. FieldName,
  8490. FieldTypeName,
  8491. FieldSingleBitField,
  8492. FieldDifferentWidthBitField,
  8493. FieldSingleMutable,
  8494. FieldSingleInitializer,
  8495. FieldDifferentInitializers,
  8496. MethodName,
  8497. MethodDeleted,
  8498. MethodVirtual,
  8499. MethodStatic,
  8500. MethodVolatile,
  8501. MethodConst,
  8502. MethodInline,
  8503. MethodNumberParameters,
  8504. MethodParameterType,
  8505. MethodParameterName,
  8506. MethodParameterSingleDefaultArgument,
  8507. MethodParameterDifferentDefaultArgument,
  8508. TypedefName,
  8509. TypedefType,
  8510. VarName,
  8511. VarType,
  8512. VarSingleInitializer,
  8513. VarDifferentInitializer,
  8514. VarConstexpr,
  8515. FriendTypeFunction,
  8516. FriendType,
  8517. FriendFunction,
  8518. };
  8519. // These lambdas have the common portions of the ODR diagnostics. This
  8520. // has the same return as Diag(), so addition parameters can be passed
  8521. // in with operator<<
  8522. auto ODRDiagError = [FirstRecord, &FirstModule, this](
  8523. SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
  8524. return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
  8525. << FirstRecord << FirstModule.empty() << FirstModule << Range
  8526. << DiffType;
  8527. };
  8528. auto ODRDiagNote = [&SecondModule, this](
  8529. SourceLocation Loc, SourceRange Range, ODRDeclDifference DiffType) {
  8530. return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
  8531. << SecondModule << Range << DiffType;
  8532. };
  8533. auto ComputeODRHash = [&Hash](const Stmt* S) {
  8534. assert(S);
  8535. Hash.clear();
  8536. Hash.AddStmt(S);
  8537. return Hash.CalculateHash();
  8538. };
  8539. auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
  8540. Hash.clear();
  8541. Hash.AddQualType(Ty);
  8542. return Hash.CalculateHash();
  8543. };
  8544. switch (FirstDiffType) {
  8545. case Other:
  8546. case EndOfClass:
  8547. case PublicSpecifer:
  8548. case PrivateSpecifer:
  8549. case ProtectedSpecifer:
  8550. llvm_unreachable("Invalid diff type");
  8551. case StaticAssert: {
  8552. StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
  8553. StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
  8554. Expr *FirstExpr = FirstSA->getAssertExpr();
  8555. Expr *SecondExpr = SecondSA->getAssertExpr();
  8556. unsigned FirstODRHash = ComputeODRHash(FirstExpr);
  8557. unsigned SecondODRHash = ComputeODRHash(SecondExpr);
  8558. if (FirstODRHash != SecondODRHash) {
  8559. ODRDiagError(FirstExpr->getLocStart(), FirstExpr->getSourceRange(),
  8560. StaticAssertCondition);
  8561. ODRDiagNote(SecondExpr->getLocStart(),
  8562. SecondExpr->getSourceRange(), StaticAssertCondition);
  8563. Diagnosed = true;
  8564. break;
  8565. }
  8566. StringLiteral *FirstStr = FirstSA->getMessage();
  8567. StringLiteral *SecondStr = SecondSA->getMessage();
  8568. assert((FirstStr || SecondStr) && "Both messages cannot be empty");
  8569. if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
  8570. SourceLocation FirstLoc, SecondLoc;
  8571. SourceRange FirstRange, SecondRange;
  8572. if (FirstStr) {
  8573. FirstLoc = FirstStr->getLocStart();
  8574. FirstRange = FirstStr->getSourceRange();
  8575. } else {
  8576. FirstLoc = FirstSA->getLocStart();
  8577. FirstRange = FirstSA->getSourceRange();
  8578. }
  8579. if (SecondStr) {
  8580. SecondLoc = SecondStr->getLocStart();
  8581. SecondRange = SecondStr->getSourceRange();
  8582. } else {
  8583. SecondLoc = SecondSA->getLocStart();
  8584. SecondRange = SecondSA->getSourceRange();
  8585. }
  8586. ODRDiagError(FirstLoc, FirstRange, StaticAssertOnlyMessage)
  8587. << (FirstStr == nullptr);
  8588. ODRDiagNote(SecondLoc, SecondRange, StaticAssertOnlyMessage)
  8589. << (SecondStr == nullptr);
  8590. Diagnosed = true;
  8591. break;
  8592. }
  8593. if (FirstStr && SecondStr &&
  8594. FirstStr->getString() != SecondStr->getString()) {
  8595. ODRDiagError(FirstStr->getLocStart(), FirstStr->getSourceRange(),
  8596. StaticAssertMessage);
  8597. ODRDiagNote(SecondStr->getLocStart(), SecondStr->getSourceRange(),
  8598. StaticAssertMessage);
  8599. Diagnosed = true;
  8600. break;
  8601. }
  8602. break;
  8603. }
  8604. case Field: {
  8605. FieldDecl *FirstField = cast<FieldDecl>(FirstDecl);
  8606. FieldDecl *SecondField = cast<FieldDecl>(SecondDecl);
  8607. IdentifierInfo *FirstII = FirstField->getIdentifier();
  8608. IdentifierInfo *SecondII = SecondField->getIdentifier();
  8609. if (FirstII->getName() != SecondII->getName()) {
  8610. ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
  8611. FieldName)
  8612. << FirstII;
  8613. ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
  8614. FieldName)
  8615. << SecondII;
  8616. Diagnosed = true;
  8617. break;
  8618. }
  8619. assert(getContext().hasSameType(FirstField->getType(),
  8620. SecondField->getType()));
  8621. QualType FirstType = FirstField->getType();
  8622. QualType SecondType = SecondField->getType();
  8623. if (ComputeQualTypeODRHash(FirstType) !=
  8624. ComputeQualTypeODRHash(SecondType)) {
  8625. ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
  8626. FieldTypeName)
  8627. << FirstII << FirstType;
  8628. ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
  8629. FieldTypeName)
  8630. << SecondII << SecondType;
  8631. Diagnosed = true;
  8632. break;
  8633. }
  8634. const bool IsFirstBitField = FirstField->isBitField();
  8635. const bool IsSecondBitField = SecondField->isBitField();
  8636. if (IsFirstBitField != IsSecondBitField) {
  8637. ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
  8638. FieldSingleBitField)
  8639. << FirstII << IsFirstBitField;
  8640. ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
  8641. FieldSingleBitField)
  8642. << SecondII << IsSecondBitField;
  8643. Diagnosed = true;
  8644. break;
  8645. }
  8646. if (IsFirstBitField && IsSecondBitField) {
  8647. ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
  8648. FieldDifferentWidthBitField)
  8649. << FirstII << FirstField->getBitWidth()->getSourceRange();
  8650. ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
  8651. FieldDifferentWidthBitField)
  8652. << SecondII << SecondField->getBitWidth()->getSourceRange();
  8653. Diagnosed = true;
  8654. break;
  8655. }
  8656. const bool IsFirstMutable = FirstField->isMutable();
  8657. const bool IsSecondMutable = SecondField->isMutable();
  8658. if (IsFirstMutable != IsSecondMutable) {
  8659. ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
  8660. FieldSingleMutable)
  8661. << FirstII << IsFirstMutable;
  8662. ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
  8663. FieldSingleMutable)
  8664. << SecondII << IsSecondMutable;
  8665. Diagnosed = true;
  8666. break;
  8667. }
  8668. const Expr *FirstInitializer = FirstField->getInClassInitializer();
  8669. const Expr *SecondInitializer = SecondField->getInClassInitializer();
  8670. if ((!FirstInitializer && SecondInitializer) ||
  8671. (FirstInitializer && !SecondInitializer)) {
  8672. ODRDiagError(FirstField->getLocation(), FirstField->getSourceRange(),
  8673. FieldSingleInitializer)
  8674. << FirstII << (FirstInitializer != nullptr);
  8675. ODRDiagNote(SecondField->getLocation(), SecondField->getSourceRange(),
  8676. FieldSingleInitializer)
  8677. << SecondII << (SecondInitializer != nullptr);
  8678. Diagnosed = true;
  8679. break;
  8680. }
  8681. if (FirstInitializer && SecondInitializer) {
  8682. unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
  8683. unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
  8684. if (FirstInitHash != SecondInitHash) {
  8685. ODRDiagError(FirstField->getLocation(),
  8686. FirstField->getSourceRange(),
  8687. FieldDifferentInitializers)
  8688. << FirstII << FirstInitializer->getSourceRange();
  8689. ODRDiagNote(SecondField->getLocation(),
  8690. SecondField->getSourceRange(),
  8691. FieldDifferentInitializers)
  8692. << SecondII << SecondInitializer->getSourceRange();
  8693. Diagnosed = true;
  8694. break;
  8695. }
  8696. }
  8697. break;
  8698. }
  8699. case CXXMethod: {
  8700. enum {
  8701. DiagMethod,
  8702. DiagConstructor,
  8703. DiagDestructor,
  8704. } FirstMethodType,
  8705. SecondMethodType;
  8706. auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
  8707. if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
  8708. if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
  8709. return DiagMethod;
  8710. };
  8711. const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
  8712. const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
  8713. FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
  8714. SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
  8715. auto FirstName = FirstMethod->getDeclName();
  8716. auto SecondName = SecondMethod->getDeclName();
  8717. if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
  8718. ODRDiagError(FirstMethod->getLocation(),
  8719. FirstMethod->getSourceRange(), MethodName)
  8720. << FirstMethodType << FirstName;
  8721. ODRDiagNote(SecondMethod->getLocation(),
  8722. SecondMethod->getSourceRange(), MethodName)
  8723. << SecondMethodType << SecondName;
  8724. Diagnosed = true;
  8725. break;
  8726. }
  8727. const bool FirstDeleted = FirstMethod->isDeleted();
  8728. const bool SecondDeleted = SecondMethod->isDeleted();
  8729. if (FirstDeleted != SecondDeleted) {
  8730. ODRDiagError(FirstMethod->getLocation(),
  8731. FirstMethod->getSourceRange(), MethodDeleted)
  8732. << FirstMethodType << FirstName << FirstDeleted;
  8733. ODRDiagNote(SecondMethod->getLocation(),
  8734. SecondMethod->getSourceRange(), MethodDeleted)
  8735. << SecondMethodType << SecondName << SecondDeleted;
  8736. Diagnosed = true;
  8737. break;
  8738. }
  8739. const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
  8740. const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
  8741. const bool FirstPure = FirstMethod->isPure();
  8742. const bool SecondPure = SecondMethod->isPure();
  8743. if ((FirstVirtual || SecondVirtual) &&
  8744. (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
  8745. ODRDiagError(FirstMethod->getLocation(),
  8746. FirstMethod->getSourceRange(), MethodVirtual)
  8747. << FirstMethodType << FirstName << FirstPure << FirstVirtual;
  8748. ODRDiagNote(SecondMethod->getLocation(),
  8749. SecondMethod->getSourceRange(), MethodVirtual)
  8750. << SecondMethodType << SecondName << SecondPure << SecondVirtual;
  8751. Diagnosed = true;
  8752. break;
  8753. }
  8754. // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
  8755. // FirstDecl is the canonical Decl of SecondDecl, so the storage
  8756. // class needs to be checked instead.
  8757. const auto FirstStorage = FirstMethod->getStorageClass();
  8758. const auto SecondStorage = SecondMethod->getStorageClass();
  8759. const bool FirstStatic = FirstStorage == SC_Static;
  8760. const bool SecondStatic = SecondStorage == SC_Static;
  8761. if (FirstStatic != SecondStatic) {
  8762. ODRDiagError(FirstMethod->getLocation(),
  8763. FirstMethod->getSourceRange(), MethodStatic)
  8764. << FirstMethodType << FirstName << FirstStatic;
  8765. ODRDiagNote(SecondMethod->getLocation(),
  8766. SecondMethod->getSourceRange(), MethodStatic)
  8767. << SecondMethodType << SecondName << SecondStatic;
  8768. Diagnosed = true;
  8769. break;
  8770. }
  8771. const bool FirstVolatile = FirstMethod->isVolatile();
  8772. const bool SecondVolatile = SecondMethod->isVolatile();
  8773. if (FirstVolatile != SecondVolatile) {
  8774. ODRDiagError(FirstMethod->getLocation(),
  8775. FirstMethod->getSourceRange(), MethodVolatile)
  8776. << FirstMethodType << FirstName << FirstVolatile;
  8777. ODRDiagNote(SecondMethod->getLocation(),
  8778. SecondMethod->getSourceRange(), MethodVolatile)
  8779. << SecondMethodType << SecondName << SecondVolatile;
  8780. Diagnosed = true;
  8781. break;
  8782. }
  8783. const bool FirstConst = FirstMethod->isConst();
  8784. const bool SecondConst = SecondMethod->isConst();
  8785. if (FirstConst != SecondConst) {
  8786. ODRDiagError(FirstMethod->getLocation(),
  8787. FirstMethod->getSourceRange(), MethodConst)
  8788. << FirstMethodType << FirstName << FirstConst;
  8789. ODRDiagNote(SecondMethod->getLocation(),
  8790. SecondMethod->getSourceRange(), MethodConst)
  8791. << SecondMethodType << SecondName << SecondConst;
  8792. Diagnosed = true;
  8793. break;
  8794. }
  8795. const bool FirstInline = FirstMethod->isInlineSpecified();
  8796. const bool SecondInline = SecondMethod->isInlineSpecified();
  8797. if (FirstInline != SecondInline) {
  8798. ODRDiagError(FirstMethod->getLocation(),
  8799. FirstMethod->getSourceRange(), MethodInline)
  8800. << FirstMethodType << FirstName << FirstInline;
  8801. ODRDiagNote(SecondMethod->getLocation(),
  8802. SecondMethod->getSourceRange(), MethodInline)
  8803. << SecondMethodType << SecondName << SecondInline;
  8804. Diagnosed = true;
  8805. break;
  8806. }
  8807. const unsigned FirstNumParameters = FirstMethod->param_size();
  8808. const unsigned SecondNumParameters = SecondMethod->param_size();
  8809. if (FirstNumParameters != SecondNumParameters) {
  8810. ODRDiagError(FirstMethod->getLocation(),
  8811. FirstMethod->getSourceRange(), MethodNumberParameters)
  8812. << FirstMethodType << FirstName << FirstNumParameters;
  8813. ODRDiagNote(SecondMethod->getLocation(),
  8814. SecondMethod->getSourceRange(), MethodNumberParameters)
  8815. << SecondMethodType << SecondName << SecondNumParameters;
  8816. Diagnosed = true;
  8817. break;
  8818. }
  8819. // Need this status boolean to know when break out of the switch.
  8820. bool ParameterMismatch = false;
  8821. for (unsigned I = 0; I < FirstNumParameters; ++I) {
  8822. const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
  8823. const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
  8824. QualType FirstParamType = FirstParam->getType();
  8825. QualType SecondParamType = SecondParam->getType();
  8826. if (FirstParamType != SecondParamType &&
  8827. ComputeQualTypeODRHash(FirstParamType) !=
  8828. ComputeQualTypeODRHash(SecondParamType)) {
  8829. if (const DecayedType *ParamDecayedType =
  8830. FirstParamType->getAs<DecayedType>()) {
  8831. ODRDiagError(FirstMethod->getLocation(),
  8832. FirstMethod->getSourceRange(), MethodParameterType)
  8833. << FirstMethodType << FirstName << (I + 1) << FirstParamType
  8834. << true << ParamDecayedType->getOriginalType();
  8835. } else {
  8836. ODRDiagError(FirstMethod->getLocation(),
  8837. FirstMethod->getSourceRange(), MethodParameterType)
  8838. << FirstMethodType << FirstName << (I + 1) << FirstParamType
  8839. << false;
  8840. }
  8841. if (const DecayedType *ParamDecayedType =
  8842. SecondParamType->getAs<DecayedType>()) {
  8843. ODRDiagNote(SecondMethod->getLocation(),
  8844. SecondMethod->getSourceRange(), MethodParameterType)
  8845. << SecondMethodType << SecondName << (I + 1)
  8846. << SecondParamType << true
  8847. << ParamDecayedType->getOriginalType();
  8848. } else {
  8849. ODRDiagNote(SecondMethod->getLocation(),
  8850. SecondMethod->getSourceRange(), MethodParameterType)
  8851. << SecondMethodType << SecondName << (I + 1)
  8852. << SecondParamType << false;
  8853. }
  8854. ParameterMismatch = true;
  8855. break;
  8856. }
  8857. DeclarationName FirstParamName = FirstParam->getDeclName();
  8858. DeclarationName SecondParamName = SecondParam->getDeclName();
  8859. if (FirstParamName != SecondParamName) {
  8860. ODRDiagError(FirstMethod->getLocation(),
  8861. FirstMethod->getSourceRange(), MethodParameterName)
  8862. << FirstMethodType << FirstName << (I + 1) << FirstParamName;
  8863. ODRDiagNote(SecondMethod->getLocation(),
  8864. SecondMethod->getSourceRange(), MethodParameterName)
  8865. << SecondMethodType << SecondName << (I + 1) << SecondParamName;
  8866. ParameterMismatch = true;
  8867. break;
  8868. }
  8869. const Expr *FirstInit = FirstParam->getInit();
  8870. const Expr *SecondInit = SecondParam->getInit();
  8871. if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
  8872. ODRDiagError(FirstMethod->getLocation(),
  8873. FirstMethod->getSourceRange(),
  8874. MethodParameterSingleDefaultArgument)
  8875. << FirstMethodType << FirstName << (I + 1)
  8876. << (FirstInit == nullptr)
  8877. << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
  8878. ODRDiagNote(SecondMethod->getLocation(),
  8879. SecondMethod->getSourceRange(),
  8880. MethodParameterSingleDefaultArgument)
  8881. << SecondMethodType << SecondName << (I + 1)
  8882. << (SecondInit == nullptr)
  8883. << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
  8884. ParameterMismatch = true;
  8885. break;
  8886. }
  8887. if (FirstInit && SecondInit &&
  8888. ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
  8889. ODRDiagError(FirstMethod->getLocation(),
  8890. FirstMethod->getSourceRange(),
  8891. MethodParameterDifferentDefaultArgument)
  8892. << FirstMethodType << FirstName << (I + 1)
  8893. << FirstInit->getSourceRange();
  8894. ODRDiagNote(SecondMethod->getLocation(),
  8895. SecondMethod->getSourceRange(),
  8896. MethodParameterDifferentDefaultArgument)
  8897. << SecondMethodType << SecondName << (I + 1)
  8898. << SecondInit->getSourceRange();
  8899. ParameterMismatch = true;
  8900. break;
  8901. }
  8902. }
  8903. if (ParameterMismatch) {
  8904. Diagnosed = true;
  8905. break;
  8906. }
  8907. break;
  8908. }
  8909. case TypeAlias:
  8910. case TypeDef: {
  8911. TypedefNameDecl *FirstTD = cast<TypedefNameDecl>(FirstDecl);
  8912. TypedefNameDecl *SecondTD = cast<TypedefNameDecl>(SecondDecl);
  8913. auto FirstName = FirstTD->getDeclName();
  8914. auto SecondName = SecondTD->getDeclName();
  8915. if (FirstName != SecondName) {
  8916. ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
  8917. TypedefName)
  8918. << (FirstDiffType == TypeAlias) << FirstName;
  8919. ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
  8920. TypedefName)
  8921. << (FirstDiffType == TypeAlias) << SecondName;
  8922. Diagnosed = true;
  8923. break;
  8924. }
  8925. QualType FirstType = FirstTD->getUnderlyingType();
  8926. QualType SecondType = SecondTD->getUnderlyingType();
  8927. if (ComputeQualTypeODRHash(FirstType) !=
  8928. ComputeQualTypeODRHash(SecondType)) {
  8929. ODRDiagError(FirstTD->getLocation(), FirstTD->getSourceRange(),
  8930. TypedefType)
  8931. << (FirstDiffType == TypeAlias) << FirstName << FirstType;
  8932. ODRDiagNote(SecondTD->getLocation(), SecondTD->getSourceRange(),
  8933. TypedefType)
  8934. << (FirstDiffType == TypeAlias) << SecondName << SecondType;
  8935. Diagnosed = true;
  8936. break;
  8937. }
  8938. break;
  8939. }
  8940. case Var: {
  8941. VarDecl *FirstVD = cast<VarDecl>(FirstDecl);
  8942. VarDecl *SecondVD = cast<VarDecl>(SecondDecl);
  8943. auto FirstName = FirstVD->getDeclName();
  8944. auto SecondName = SecondVD->getDeclName();
  8945. if (FirstName != SecondName) {
  8946. ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
  8947. VarName)
  8948. << FirstName;
  8949. ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
  8950. VarName)
  8951. << SecondName;
  8952. Diagnosed = true;
  8953. break;
  8954. }
  8955. QualType FirstType = FirstVD->getType();
  8956. QualType SecondType = SecondVD->getType();
  8957. if (ComputeQualTypeODRHash(FirstType) !=
  8958. ComputeQualTypeODRHash(SecondType)) {
  8959. ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
  8960. VarType)
  8961. << FirstName << FirstType;
  8962. ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
  8963. VarType)
  8964. << SecondName << SecondType;
  8965. Diagnosed = true;
  8966. break;
  8967. }
  8968. const Expr *FirstInit = FirstVD->getInit();
  8969. const Expr *SecondInit = SecondVD->getInit();
  8970. if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
  8971. ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
  8972. VarSingleInitializer)
  8973. << FirstName << (FirstInit == nullptr)
  8974. << (FirstInit ? FirstInit->getSourceRange(): SourceRange());
  8975. ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
  8976. VarSingleInitializer)
  8977. << SecondName << (SecondInit == nullptr)
  8978. << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
  8979. Diagnosed = true;
  8980. break;
  8981. }
  8982. if (FirstInit && SecondInit &&
  8983. ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
  8984. ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
  8985. VarDifferentInitializer)
  8986. << FirstName << FirstInit->getSourceRange();
  8987. ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
  8988. VarDifferentInitializer)
  8989. << SecondName << SecondInit->getSourceRange();
  8990. Diagnosed = true;
  8991. break;
  8992. }
  8993. const bool FirstIsConstexpr = FirstVD->isConstexpr();
  8994. const bool SecondIsConstexpr = SecondVD->isConstexpr();
  8995. if (FirstIsConstexpr != SecondIsConstexpr) {
  8996. ODRDiagError(FirstVD->getLocation(), FirstVD->getSourceRange(),
  8997. VarConstexpr)
  8998. << FirstName << FirstIsConstexpr;
  8999. ODRDiagNote(SecondVD->getLocation(), SecondVD->getSourceRange(),
  9000. VarConstexpr)
  9001. << SecondName << SecondIsConstexpr;
  9002. Diagnosed = true;
  9003. break;
  9004. }
  9005. break;
  9006. }
  9007. case Friend: {
  9008. FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
  9009. FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
  9010. NamedDecl *FirstND = FirstFriend->getFriendDecl();
  9011. NamedDecl *SecondND = SecondFriend->getFriendDecl();
  9012. TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
  9013. TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
  9014. if (FirstND && SecondND) {
  9015. ODRDiagError(FirstFriend->getFriendLoc(),
  9016. FirstFriend->getSourceRange(), FriendFunction)
  9017. << FirstND;
  9018. ODRDiagNote(SecondFriend->getFriendLoc(),
  9019. SecondFriend->getSourceRange(), FriendFunction)
  9020. << SecondND;
  9021. Diagnosed = true;
  9022. break;
  9023. }
  9024. if (FirstTSI && SecondTSI) {
  9025. QualType FirstFriendType = FirstTSI->getType();
  9026. QualType SecondFriendType = SecondTSI->getType();
  9027. assert(ComputeQualTypeODRHash(FirstFriendType) !=
  9028. ComputeQualTypeODRHash(SecondFriendType));
  9029. ODRDiagError(FirstFriend->getFriendLoc(),
  9030. FirstFriend->getSourceRange(), FriendType)
  9031. << FirstFriendType;
  9032. ODRDiagNote(SecondFriend->getFriendLoc(),
  9033. SecondFriend->getSourceRange(), FriendType)
  9034. << SecondFriendType;
  9035. Diagnosed = true;
  9036. break;
  9037. }
  9038. ODRDiagError(FirstFriend->getFriendLoc(), FirstFriend->getSourceRange(),
  9039. FriendTypeFunction)
  9040. << (FirstTSI == nullptr);
  9041. ODRDiagNote(SecondFriend->getFriendLoc(),
  9042. SecondFriend->getSourceRange(), FriendTypeFunction)
  9043. << (SecondTSI == nullptr);
  9044. Diagnosed = true;
  9045. break;
  9046. }
  9047. }
  9048. if (Diagnosed)
  9049. continue;
  9050. Diag(FirstDecl->getLocation(),
  9051. diag::err_module_odr_violation_mismatch_decl_unknown)
  9052. << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
  9053. << FirstDecl->getSourceRange();
  9054. Diag(SecondDecl->getLocation(),
  9055. diag::note_module_odr_violation_mismatch_decl_unknown)
  9056. << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
  9057. Diagnosed = true;
  9058. }
  9059. if (!Diagnosed) {
  9060. // All definitions are updates to the same declaration. This happens if a
  9061. // module instantiates the declaration of a class template specialization
  9062. // and two or more other modules instantiate its definition.
  9063. //
  9064. // FIXME: Indicate which modules had instantiations of this definition.
  9065. // FIXME: How can this even happen?
  9066. Diag(Merge.first->getLocation(),
  9067. diag::err_module_odr_violation_different_instantiations)
  9068. << Merge.first;
  9069. }
  9070. }
  9071. }
  9072. void ASTReader::StartedDeserializing() {
  9073. if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
  9074. ReadTimer->startTimer();
  9075. }
  9076. void ASTReader::FinishedDeserializing() {
  9077. assert(NumCurrentElementsDeserializing &&
  9078. "FinishedDeserializing not paired with StartedDeserializing");
  9079. if (NumCurrentElementsDeserializing == 1) {
  9080. // We decrease NumCurrentElementsDeserializing only after pending actions
  9081. // are finished, to avoid recursively re-calling finishPendingActions().
  9082. finishPendingActions();
  9083. }
  9084. --NumCurrentElementsDeserializing;
  9085. if (NumCurrentElementsDeserializing == 0) {
  9086. // Propagate exception specification updates along redeclaration chains.
  9087. while (!PendingExceptionSpecUpdates.empty()) {
  9088. auto Updates = std::move(PendingExceptionSpecUpdates);
  9089. PendingExceptionSpecUpdates.clear();
  9090. for (auto Update : Updates) {
  9091. ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
  9092. auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
  9093. auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
  9094. if (auto *Listener = getContext().getASTMutationListener())
  9095. Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
  9096. for (auto *Redecl : Update.second->redecls())
  9097. getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
  9098. }
  9099. }
  9100. if (ReadTimer)
  9101. ReadTimer->stopTimer();
  9102. diagnoseOdrViolations();
  9103. // We are not in recursive loading, so it's safe to pass the "interesting"
  9104. // decls to the consumer.
  9105. if (Consumer)
  9106. PassInterestingDeclsToConsumer();
  9107. }
  9108. }
  9109. void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  9110. if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
  9111. // Remove any fake results before adding any real ones.
  9112. auto It = PendingFakeLookupResults.find(II);
  9113. if (It != PendingFakeLookupResults.end()) {
  9114. for (auto *ND : It->second)
  9115. SemaObj->IdResolver.RemoveDecl(ND);
  9116. // FIXME: this works around module+PCH performance issue.
  9117. // Rather than erase the result from the map, which is O(n), just clear
  9118. // the vector of NamedDecls.
  9119. It->second.clear();
  9120. }
  9121. }
  9122. if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
  9123. SemaObj->TUScope->AddDecl(D);
  9124. } else if (SemaObj->TUScope) {
  9125. // Adding the decl to IdResolver may have failed because it was already in
  9126. // (even though it was not added in scope). If it is already in, make sure
  9127. // it gets in the scope as well.
  9128. if (std::find(SemaObj->IdResolver.begin(Name),
  9129. SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
  9130. SemaObj->TUScope->AddDecl(D);
  9131. }
  9132. }
  9133. ASTReader::ASTReader(Preprocessor &PP, ASTContext *Context,
  9134. const PCHContainerReader &PCHContainerRdr,
  9135. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
  9136. StringRef isysroot, bool DisableValidation,
  9137. bool AllowASTWithCompilerErrors,
  9138. bool AllowConfigurationMismatch, bool ValidateSystemInputs,
  9139. bool UseGlobalIndex,
  9140. std::unique_ptr<llvm::Timer> ReadTimer)
  9141. : Listener(DisableValidation
  9142. ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
  9143. : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
  9144. SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
  9145. PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
  9146. ContextObj(Context),
  9147. ModuleMgr(PP.getFileManager(), PP.getPCMCache(), PCHContainerRdr,
  9148. PP.getHeaderSearchInfo()),
  9149. PCMCache(PP.getPCMCache()), DummyIdResolver(PP),
  9150. ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
  9151. DisableValidation(DisableValidation),
  9152. AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
  9153. AllowConfigurationMismatch(AllowConfigurationMismatch),
  9154. ValidateSystemInputs(ValidateSystemInputs),
  9155. UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
  9156. SourceMgr.setExternalSLocEntrySource(this);
  9157. for (const auto &Ext : Extensions) {
  9158. auto BlockName = Ext->getExtensionMetadata().BlockName;
  9159. auto Known = ModuleFileExtensions.find(BlockName);
  9160. if (Known != ModuleFileExtensions.end()) {
  9161. Diags.Report(diag::warn_duplicate_module_file_extension)
  9162. << BlockName;
  9163. continue;
  9164. }
  9165. ModuleFileExtensions.insert({BlockName, Ext});
  9166. }
  9167. }
  9168. ASTReader::~ASTReader() {
  9169. if (OwnsDeserializationListener)
  9170. delete DeserializationListener;
  9171. }
  9172. IdentifierResolver &ASTReader::getIdResolver() {
  9173. return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
  9174. }
  9175. unsigned ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
  9176. unsigned AbbrevID) {
  9177. Idx = 0;
  9178. Record.clear();
  9179. return Cursor.readRecord(AbbrevID, Record);
  9180. }