ASTReader.cpp 467 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036
  1. //===- ASTReader.cpp - AST File Reader ------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines the ASTReader class, which reads AST files.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "ASTCommon.h"
  13. #include "ASTReaderInternals.h"
  14. #include "clang/AST/ASTConsumer.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/AST/ASTMutationListener.h"
  17. #include "clang/AST/ASTUnresolvedSet.h"
  18. #include "clang/AST/AbstractTypeReader.h"
  19. #include "clang/AST/Decl.h"
  20. #include "clang/AST/DeclBase.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclFriend.h"
  23. #include "clang/AST/DeclGroup.h"
  24. #include "clang/AST/DeclObjC.h"
  25. #include "clang/AST/DeclTemplate.h"
  26. #include "clang/AST/DeclarationName.h"
  27. #include "clang/AST/Expr.h"
  28. #include "clang/AST/ExprCXX.h"
  29. #include "clang/AST/ExternalASTSource.h"
  30. #include "clang/AST/NestedNameSpecifier.h"
  31. #include "clang/AST/ODRHash.h"
  32. #include "clang/AST/OpenMPClause.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/DiagnosticError.h"
  43. #include "clang/Basic/DiagnosticOptions.h"
  44. #include "clang/Basic/ExceptionSpecificationType.h"
  45. #include "clang/Basic/FileManager.h"
  46. #include "clang/Basic/FileSystemOptions.h"
  47. #include "clang/Basic/IdentifierTable.h"
  48. #include "clang/Basic/LLVM.h"
  49. #include "clang/Basic/LangOptions.h"
  50. #include "clang/Basic/Module.h"
  51. #include "clang/Basic/ObjCRuntime.h"
  52. #include "clang/Basic/OpenMPKinds.h"
  53. #include "clang/Basic/OperatorKinds.h"
  54. #include "clang/Basic/PragmaKinds.h"
  55. #include "clang/Basic/Sanitizers.h"
  56. #include "clang/Basic/SourceLocation.h"
  57. #include "clang/Basic/SourceManager.h"
  58. #include "clang/Basic/SourceManagerInternals.h"
  59. #include "clang/Basic/Specifiers.h"
  60. #include "clang/Basic/TargetInfo.h"
  61. #include "clang/Basic/TargetOptions.h"
  62. #include "clang/Basic/TokenKinds.h"
  63. #include "clang/Basic/Version.h"
  64. #include "clang/Lex/HeaderSearch.h"
  65. #include "clang/Lex/HeaderSearchOptions.h"
  66. #include "clang/Lex/MacroInfo.h"
  67. #include "clang/Lex/ModuleMap.h"
  68. #include "clang/Lex/PreprocessingRecord.h"
  69. #include "clang/Lex/Preprocessor.h"
  70. #include "clang/Lex/PreprocessorOptions.h"
  71. #include "clang/Lex/Token.h"
  72. #include "clang/Sema/ObjCMethodList.h"
  73. #include "clang/Sema/Scope.h"
  74. #include "clang/Sema/Sema.h"
  75. #include "clang/Sema/Weak.h"
  76. #include "clang/Serialization/ASTBitCodes.h"
  77. #include "clang/Serialization/ASTDeserializationListener.h"
  78. #include "clang/Serialization/ASTRecordReader.h"
  79. #include "clang/Serialization/ContinuousRangeMap.h"
  80. #include "clang/Serialization/GlobalModuleIndex.h"
  81. #include "clang/Serialization/InMemoryModuleCache.h"
  82. #include "clang/Serialization/ModuleFile.h"
  83. #include "clang/Serialization/ModuleFileExtension.h"
  84. #include "clang/Serialization/ModuleManager.h"
  85. #include "clang/Serialization/PCHContainerOperations.h"
  86. #include "clang/Serialization/SerializationDiagnostic.h"
  87. #include "llvm/ADT/APFloat.h"
  88. #include "llvm/ADT/APInt.h"
  89. #include "llvm/ADT/APSInt.h"
  90. #include "llvm/ADT/ArrayRef.h"
  91. #include "llvm/ADT/DenseMap.h"
  92. #include "llvm/ADT/FloatingPointMode.h"
  93. #include "llvm/ADT/FoldingSet.h"
  94. #include "llvm/ADT/Hashing.h"
  95. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  96. #include "llvm/ADT/None.h"
  97. #include "llvm/ADT/Optional.h"
  98. #include "llvm/ADT/STLExtras.h"
  99. #include "llvm/ADT/ScopeExit.h"
  100. #include "llvm/ADT/SmallPtrSet.h"
  101. #include "llvm/ADT/SmallString.h"
  102. #include "llvm/ADT/SmallVector.h"
  103. #include "llvm/ADT/StringExtras.h"
  104. #include "llvm/ADT/StringMap.h"
  105. #include "llvm/ADT/StringRef.h"
  106. #include "llvm/ADT/Triple.h"
  107. #include "llvm/ADT/iterator_range.h"
  108. #include "llvm/Bitstream/BitstreamReader.h"
  109. #include "llvm/Support/Casting.h"
  110. #include "llvm/Support/Compiler.h"
  111. #include "llvm/Support/Compression.h"
  112. #include "llvm/Support/DJB.h"
  113. #include "llvm/Support/Endian.h"
  114. #include "llvm/Support/Error.h"
  115. #include "llvm/Support/ErrorHandling.h"
  116. #include "llvm/Support/FileSystem.h"
  117. #include "llvm/Support/LEB128.h"
  118. #include "llvm/Support/MemoryBuffer.h"
  119. #include "llvm/Support/Path.h"
  120. #include "llvm/Support/SaveAndRestore.h"
  121. #include "llvm/Support/Timer.h"
  122. #include "llvm/Support/VersionTuple.h"
  123. #include "llvm/Support/raw_ostream.h"
  124. #include <algorithm>
  125. #include <cassert>
  126. #include <cstddef>
  127. #include <cstdint>
  128. #include <cstdio>
  129. #include <ctime>
  130. #include <iterator>
  131. #include <limits>
  132. #include <map>
  133. #include <memory>
  134. #include <string>
  135. #include <system_error>
  136. #include <tuple>
  137. #include <utility>
  138. #include <vector>
  139. using namespace clang;
  140. using namespace clang::serialization;
  141. using namespace clang::serialization::reader;
  142. using llvm::BitstreamCursor;
  143. //===----------------------------------------------------------------------===//
  144. // ChainedASTReaderListener implementation
  145. //===----------------------------------------------------------------------===//
  146. bool
  147. ChainedASTReaderListener::ReadFullVersionInformation(StringRef FullVersion) {
  148. return First->ReadFullVersionInformation(FullVersion) ||
  149. Second->ReadFullVersionInformation(FullVersion);
  150. }
  151. void ChainedASTReaderListener::ReadModuleName(StringRef ModuleName) {
  152. First->ReadModuleName(ModuleName);
  153. Second->ReadModuleName(ModuleName);
  154. }
  155. void ChainedASTReaderListener::ReadModuleMapFile(StringRef ModuleMapPath) {
  156. First->ReadModuleMapFile(ModuleMapPath);
  157. Second->ReadModuleMapFile(ModuleMapPath);
  158. }
  159. bool
  160. ChainedASTReaderListener::ReadLanguageOptions(const LangOptions &LangOpts,
  161. bool Complain,
  162. bool AllowCompatibleDifferences) {
  163. return First->ReadLanguageOptions(LangOpts, Complain,
  164. AllowCompatibleDifferences) ||
  165. Second->ReadLanguageOptions(LangOpts, Complain,
  166. AllowCompatibleDifferences);
  167. }
  168. bool ChainedASTReaderListener::ReadTargetOptions(
  169. const TargetOptions &TargetOpts, bool Complain,
  170. bool AllowCompatibleDifferences) {
  171. return First->ReadTargetOptions(TargetOpts, Complain,
  172. AllowCompatibleDifferences) ||
  173. Second->ReadTargetOptions(TargetOpts, Complain,
  174. AllowCompatibleDifferences);
  175. }
  176. bool ChainedASTReaderListener::ReadDiagnosticOptions(
  177. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  178. return First->ReadDiagnosticOptions(DiagOpts, Complain) ||
  179. Second->ReadDiagnosticOptions(DiagOpts, Complain);
  180. }
  181. bool
  182. ChainedASTReaderListener::ReadFileSystemOptions(const FileSystemOptions &FSOpts,
  183. bool Complain) {
  184. return First->ReadFileSystemOptions(FSOpts, Complain) ||
  185. Second->ReadFileSystemOptions(FSOpts, Complain);
  186. }
  187. bool ChainedASTReaderListener::ReadHeaderSearchOptions(
  188. const HeaderSearchOptions &HSOpts, StringRef SpecificModuleCachePath,
  189. bool Complain) {
  190. return First->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  191. Complain) ||
  192. Second->ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  193. Complain);
  194. }
  195. bool ChainedASTReaderListener::ReadPreprocessorOptions(
  196. const PreprocessorOptions &PPOpts, bool Complain,
  197. std::string &SuggestedPredefines) {
  198. return First->ReadPreprocessorOptions(PPOpts, Complain,
  199. SuggestedPredefines) ||
  200. Second->ReadPreprocessorOptions(PPOpts, Complain, SuggestedPredefines);
  201. }
  202. void ChainedASTReaderListener::ReadCounter(const serialization::ModuleFile &M,
  203. unsigned Value) {
  204. First->ReadCounter(M, Value);
  205. Second->ReadCounter(M, Value);
  206. }
  207. bool ChainedASTReaderListener::needsInputFileVisitation() {
  208. return First->needsInputFileVisitation() ||
  209. Second->needsInputFileVisitation();
  210. }
  211. bool ChainedASTReaderListener::needsSystemInputFileVisitation() {
  212. return First->needsSystemInputFileVisitation() ||
  213. Second->needsSystemInputFileVisitation();
  214. }
  215. void ChainedASTReaderListener::visitModuleFile(StringRef Filename,
  216. ModuleKind Kind) {
  217. First->visitModuleFile(Filename, Kind);
  218. Second->visitModuleFile(Filename, Kind);
  219. }
  220. bool ChainedASTReaderListener::visitInputFile(StringRef Filename,
  221. bool isSystem,
  222. bool isOverridden,
  223. bool isExplicitModule) {
  224. bool Continue = false;
  225. if (First->needsInputFileVisitation() &&
  226. (!isSystem || First->needsSystemInputFileVisitation()))
  227. Continue |= First->visitInputFile(Filename, isSystem, isOverridden,
  228. isExplicitModule);
  229. if (Second->needsInputFileVisitation() &&
  230. (!isSystem || Second->needsSystemInputFileVisitation()))
  231. Continue |= Second->visitInputFile(Filename, isSystem, isOverridden,
  232. isExplicitModule);
  233. return Continue;
  234. }
  235. void ChainedASTReaderListener::readModuleFileExtension(
  236. const ModuleFileExtensionMetadata &Metadata) {
  237. First->readModuleFileExtension(Metadata);
  238. Second->readModuleFileExtension(Metadata);
  239. }
  240. //===----------------------------------------------------------------------===//
  241. // PCH validator implementation
  242. //===----------------------------------------------------------------------===//
  243. ASTReaderListener::~ASTReaderListener() = default;
  244. /// Compare the given set of language options against an existing set of
  245. /// language options.
  246. ///
  247. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  248. /// \param AllowCompatibleDifferences If true, differences between compatible
  249. /// language options will be permitted.
  250. ///
  251. /// \returns true if the languagae options mis-match, false otherwise.
  252. static bool checkLanguageOptions(const LangOptions &LangOpts,
  253. const LangOptions &ExistingLangOpts,
  254. DiagnosticsEngine *Diags,
  255. bool AllowCompatibleDifferences = true) {
  256. #define LANGOPT(Name, Bits, Default, Description) \
  257. if (ExistingLangOpts.Name != LangOpts.Name) { \
  258. if (Diags) \
  259. Diags->Report(diag::err_pch_langopt_mismatch) \
  260. << Description << LangOpts.Name << ExistingLangOpts.Name; \
  261. return true; \
  262. }
  263. #define VALUE_LANGOPT(Name, Bits, Default, Description) \
  264. if (ExistingLangOpts.Name != LangOpts.Name) { \
  265. if (Diags) \
  266. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  267. << Description; \
  268. return true; \
  269. }
  270. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  271. if (ExistingLangOpts.get##Name() != LangOpts.get##Name()) { \
  272. if (Diags) \
  273. Diags->Report(diag::err_pch_langopt_value_mismatch) \
  274. << Description; \
  275. return true; \
  276. }
  277. #define COMPATIBLE_LANGOPT(Name, Bits, Default, Description) \
  278. if (!AllowCompatibleDifferences) \
  279. LANGOPT(Name, Bits, Default, Description)
  280. #define COMPATIBLE_ENUM_LANGOPT(Name, Bits, Default, Description) \
  281. if (!AllowCompatibleDifferences) \
  282. ENUM_LANGOPT(Name, Bits, Default, Description)
  283. #define COMPATIBLE_VALUE_LANGOPT(Name, Bits, Default, Description) \
  284. if (!AllowCompatibleDifferences) \
  285. VALUE_LANGOPT(Name, Bits, Default, Description)
  286. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  287. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  288. #define BENIGN_VALUE_LANGOPT(Name, Type, Bits, Default, Description)
  289. #include "clang/Basic/LangOptions.def"
  290. if (ExistingLangOpts.ModuleFeatures != LangOpts.ModuleFeatures) {
  291. if (Diags)
  292. Diags->Report(diag::err_pch_langopt_value_mismatch) << "module features";
  293. return true;
  294. }
  295. if (ExistingLangOpts.ObjCRuntime != LangOpts.ObjCRuntime) {
  296. if (Diags)
  297. Diags->Report(diag::err_pch_langopt_value_mismatch)
  298. << "target Objective-C runtime";
  299. return true;
  300. }
  301. if (ExistingLangOpts.CommentOpts.BlockCommandNames !=
  302. LangOpts.CommentOpts.BlockCommandNames) {
  303. if (Diags)
  304. Diags->Report(diag::err_pch_langopt_value_mismatch)
  305. << "block command names";
  306. return true;
  307. }
  308. // Sanitizer feature mismatches are treated as compatible differences. If
  309. // compatible differences aren't allowed, we still only want to check for
  310. // mismatches of non-modular sanitizers (the only ones which can affect AST
  311. // generation).
  312. if (!AllowCompatibleDifferences) {
  313. SanitizerMask ModularSanitizers = getPPTransparentSanitizers();
  314. SanitizerSet ExistingSanitizers = ExistingLangOpts.Sanitize;
  315. SanitizerSet ImportedSanitizers = LangOpts.Sanitize;
  316. ExistingSanitizers.clear(ModularSanitizers);
  317. ImportedSanitizers.clear(ModularSanitizers);
  318. if (ExistingSanitizers.Mask != ImportedSanitizers.Mask) {
  319. const std::string Flag = "-fsanitize=";
  320. if (Diags) {
  321. #define SANITIZER(NAME, ID) \
  322. { \
  323. bool InExistingModule = ExistingSanitizers.has(SanitizerKind::ID); \
  324. bool InImportedModule = ImportedSanitizers.has(SanitizerKind::ID); \
  325. if (InExistingModule != InImportedModule) \
  326. Diags->Report(diag::err_pch_targetopt_feature_mismatch) \
  327. << InExistingModule << (Flag + NAME); \
  328. }
  329. #include "clang/Basic/Sanitizers.def"
  330. }
  331. return true;
  332. }
  333. }
  334. return false;
  335. }
  336. /// Compare the given set of target options against an existing set of
  337. /// target options.
  338. ///
  339. /// \param Diags If non-NULL, diagnostics will be emitted via this engine.
  340. ///
  341. /// \returns true if the target options mis-match, false otherwise.
  342. static bool checkTargetOptions(const TargetOptions &TargetOpts,
  343. const TargetOptions &ExistingTargetOpts,
  344. DiagnosticsEngine *Diags,
  345. bool AllowCompatibleDifferences = true) {
  346. #define CHECK_TARGET_OPT(Field, Name) \
  347. if (TargetOpts.Field != ExistingTargetOpts.Field) { \
  348. if (Diags) \
  349. Diags->Report(diag::err_pch_targetopt_mismatch) \
  350. << Name << TargetOpts.Field << ExistingTargetOpts.Field; \
  351. return true; \
  352. }
  353. // The triple and ABI must match exactly.
  354. CHECK_TARGET_OPT(Triple, "target");
  355. CHECK_TARGET_OPT(ABI, "target ABI");
  356. // We can tolerate different CPUs in many cases, notably when one CPU
  357. // supports a strict superset of another. When allowing compatible
  358. // differences skip this check.
  359. if (!AllowCompatibleDifferences) {
  360. CHECK_TARGET_OPT(CPU, "target CPU");
  361. CHECK_TARGET_OPT(TuneCPU, "tune CPU");
  362. }
  363. #undef CHECK_TARGET_OPT
  364. // Compare feature sets.
  365. SmallVector<StringRef, 4> ExistingFeatures(
  366. ExistingTargetOpts.FeaturesAsWritten.begin(),
  367. ExistingTargetOpts.FeaturesAsWritten.end());
  368. SmallVector<StringRef, 4> ReadFeatures(TargetOpts.FeaturesAsWritten.begin(),
  369. TargetOpts.FeaturesAsWritten.end());
  370. llvm::sort(ExistingFeatures);
  371. llvm::sort(ReadFeatures);
  372. // We compute the set difference in both directions explicitly so that we can
  373. // diagnose the differences differently.
  374. SmallVector<StringRef, 4> UnmatchedExistingFeatures, UnmatchedReadFeatures;
  375. std::set_difference(
  376. ExistingFeatures.begin(), ExistingFeatures.end(), ReadFeatures.begin(),
  377. ReadFeatures.end(), std::back_inserter(UnmatchedExistingFeatures));
  378. std::set_difference(ReadFeatures.begin(), ReadFeatures.end(),
  379. ExistingFeatures.begin(), ExistingFeatures.end(),
  380. std::back_inserter(UnmatchedReadFeatures));
  381. // If we are allowing compatible differences and the read feature set is
  382. // a strict subset of the existing feature set, there is nothing to diagnose.
  383. if (AllowCompatibleDifferences && UnmatchedReadFeatures.empty())
  384. return false;
  385. if (Diags) {
  386. for (StringRef Feature : UnmatchedReadFeatures)
  387. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  388. << /* is-existing-feature */ false << Feature;
  389. for (StringRef Feature : UnmatchedExistingFeatures)
  390. Diags->Report(diag::err_pch_targetopt_feature_mismatch)
  391. << /* is-existing-feature */ true << Feature;
  392. }
  393. return !UnmatchedReadFeatures.empty() || !UnmatchedExistingFeatures.empty();
  394. }
  395. bool
  396. PCHValidator::ReadLanguageOptions(const LangOptions &LangOpts,
  397. bool Complain,
  398. bool AllowCompatibleDifferences) {
  399. const LangOptions &ExistingLangOpts = PP.getLangOpts();
  400. return checkLanguageOptions(LangOpts, ExistingLangOpts,
  401. Complain ? &Reader.Diags : nullptr,
  402. AllowCompatibleDifferences);
  403. }
  404. bool PCHValidator::ReadTargetOptions(const TargetOptions &TargetOpts,
  405. bool Complain,
  406. bool AllowCompatibleDifferences) {
  407. const TargetOptions &ExistingTargetOpts = PP.getTargetInfo().getTargetOpts();
  408. return checkTargetOptions(TargetOpts, ExistingTargetOpts,
  409. Complain ? &Reader.Diags : nullptr,
  410. AllowCompatibleDifferences);
  411. }
  412. namespace {
  413. using MacroDefinitionsMap =
  414. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>;
  415. using DeclsMap = llvm::DenseMap<DeclarationName, SmallVector<NamedDecl *, 8>>;
  416. } // namespace
  417. static bool checkDiagnosticGroupMappings(DiagnosticsEngine &StoredDiags,
  418. DiagnosticsEngine &Diags,
  419. bool Complain) {
  420. using Level = DiagnosticsEngine::Level;
  421. // Check current mappings for new -Werror mappings, and the stored mappings
  422. // for cases that were explicitly mapped to *not* be errors that are now
  423. // errors because of options like -Werror.
  424. DiagnosticsEngine *MappingSources[] = { &Diags, &StoredDiags };
  425. for (DiagnosticsEngine *MappingSource : MappingSources) {
  426. for (auto DiagIDMappingPair : MappingSource->getDiagnosticMappings()) {
  427. diag::kind DiagID = DiagIDMappingPair.first;
  428. Level CurLevel = Diags.getDiagnosticLevel(DiagID, SourceLocation());
  429. if (CurLevel < DiagnosticsEngine::Error)
  430. continue; // not significant
  431. Level StoredLevel =
  432. StoredDiags.getDiagnosticLevel(DiagID, SourceLocation());
  433. if (StoredLevel < DiagnosticsEngine::Error) {
  434. if (Complain)
  435. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror=" +
  436. Diags.getDiagnosticIDs()->getWarningOptionForDiag(DiagID).str();
  437. return true;
  438. }
  439. }
  440. }
  441. return false;
  442. }
  443. static bool isExtHandlingFromDiagsError(DiagnosticsEngine &Diags) {
  444. diag::Severity Ext = Diags.getExtensionHandlingBehavior();
  445. if (Ext == diag::Severity::Warning && Diags.getWarningsAsErrors())
  446. return true;
  447. return Ext >= diag::Severity::Error;
  448. }
  449. static bool checkDiagnosticMappings(DiagnosticsEngine &StoredDiags,
  450. DiagnosticsEngine &Diags,
  451. bool IsSystem, bool Complain) {
  452. // Top-level options
  453. if (IsSystem) {
  454. if (Diags.getSuppressSystemWarnings())
  455. return false;
  456. // If -Wsystem-headers was not enabled before, be conservative
  457. if (StoredDiags.getSuppressSystemWarnings()) {
  458. if (Complain)
  459. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Wsystem-headers";
  460. return true;
  461. }
  462. }
  463. if (Diags.getWarningsAsErrors() && !StoredDiags.getWarningsAsErrors()) {
  464. if (Complain)
  465. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Werror";
  466. return true;
  467. }
  468. if (Diags.getWarningsAsErrors() && Diags.getEnableAllWarnings() &&
  469. !StoredDiags.getEnableAllWarnings()) {
  470. if (Complain)
  471. Diags.Report(diag::err_pch_diagopt_mismatch) << "-Weverything -Werror";
  472. return true;
  473. }
  474. if (isExtHandlingFromDiagsError(Diags) &&
  475. !isExtHandlingFromDiagsError(StoredDiags)) {
  476. if (Complain)
  477. Diags.Report(diag::err_pch_diagopt_mismatch) << "-pedantic-errors";
  478. return true;
  479. }
  480. return checkDiagnosticGroupMappings(StoredDiags, Diags, Complain);
  481. }
  482. /// Return the top import module if it is implicit, nullptr otherwise.
  483. static Module *getTopImportImplicitModule(ModuleManager &ModuleMgr,
  484. Preprocessor &PP) {
  485. // If the original import came from a file explicitly generated by the user,
  486. // don't check the diagnostic mappings.
  487. // FIXME: currently this is approximated by checking whether this is not a
  488. // module import of an implicitly-loaded module file.
  489. // Note: ModuleMgr.rbegin() may not be the current module, but it must be in
  490. // the transitive closure of its imports, since unrelated modules cannot be
  491. // imported until after this module finishes validation.
  492. ModuleFile *TopImport = &*ModuleMgr.rbegin();
  493. while (!TopImport->ImportedBy.empty())
  494. TopImport = TopImport->ImportedBy[0];
  495. if (TopImport->Kind != MK_ImplicitModule)
  496. return nullptr;
  497. StringRef ModuleName = TopImport->ModuleName;
  498. assert(!ModuleName.empty() && "diagnostic options read before module name");
  499. Module *M =
  500. PP.getHeaderSearchInfo().lookupModule(ModuleName, TopImport->ImportLoc);
  501. assert(M && "missing module");
  502. return M;
  503. }
  504. bool PCHValidator::ReadDiagnosticOptions(
  505. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts, bool Complain) {
  506. DiagnosticsEngine &ExistingDiags = PP.getDiagnostics();
  507. IntrusiveRefCntPtr<DiagnosticIDs> DiagIDs(ExistingDiags.getDiagnosticIDs());
  508. IntrusiveRefCntPtr<DiagnosticsEngine> Diags(
  509. new DiagnosticsEngine(DiagIDs, DiagOpts.get()));
  510. // This should never fail, because we would have processed these options
  511. // before writing them to an ASTFile.
  512. ProcessWarningOptions(*Diags, *DiagOpts, /*Report*/false);
  513. ModuleManager &ModuleMgr = Reader.getModuleManager();
  514. assert(ModuleMgr.size() >= 1 && "what ASTFile is this then");
  515. Module *TopM = getTopImportImplicitModule(ModuleMgr, PP);
  516. if (!TopM)
  517. return false;
  518. // FIXME: if the diagnostics are incompatible, save a DiagnosticOptions that
  519. // contains the union of their flags.
  520. return checkDiagnosticMappings(*Diags, ExistingDiags, TopM->IsSystem,
  521. Complain);
  522. }
  523. /// Collect the macro definitions provided by the given preprocessor
  524. /// options.
  525. static void
  526. collectMacroDefinitions(const PreprocessorOptions &PPOpts,
  527. MacroDefinitionsMap &Macros,
  528. SmallVectorImpl<StringRef> *MacroNames = nullptr) {
  529. for (unsigned I = 0, N = PPOpts.Macros.size(); I != N; ++I) {
  530. StringRef Macro = PPOpts.Macros[I].first;
  531. bool IsUndef = PPOpts.Macros[I].second;
  532. std::pair<StringRef, StringRef> MacroPair = Macro.split('=');
  533. StringRef MacroName = MacroPair.first;
  534. StringRef MacroBody = MacroPair.second;
  535. // For an #undef'd macro, we only care about the name.
  536. if (IsUndef) {
  537. if (MacroNames && !Macros.count(MacroName))
  538. MacroNames->push_back(MacroName);
  539. Macros[MacroName] = std::make_pair("", true);
  540. continue;
  541. }
  542. // For a #define'd macro, figure out the actual definition.
  543. if (MacroName.size() == Macro.size())
  544. MacroBody = "1";
  545. else {
  546. // Note: GCC drops anything following an end-of-line character.
  547. StringRef::size_type End = MacroBody.find_first_of("\n\r");
  548. MacroBody = MacroBody.substr(0, End);
  549. }
  550. if (MacroNames && !Macros.count(MacroName))
  551. MacroNames->push_back(MacroName);
  552. Macros[MacroName] = std::make_pair(MacroBody, false);
  553. }
  554. }
  555. /// Check the preprocessor options deserialized from the control block
  556. /// against the preprocessor options in an existing preprocessor.
  557. ///
  558. /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
  559. /// \param Validate If true, validate preprocessor options. If false, allow
  560. /// macros defined by \p ExistingPPOpts to override those defined by
  561. /// \p PPOpts in SuggestedPredefines.
  562. static bool checkPreprocessorOptions(const PreprocessorOptions &PPOpts,
  563. const PreprocessorOptions &ExistingPPOpts,
  564. DiagnosticsEngine *Diags,
  565. FileManager &FileMgr,
  566. std::string &SuggestedPredefines,
  567. const LangOptions &LangOpts,
  568. bool Validate = true) {
  569. // Check macro definitions.
  570. MacroDefinitionsMap ASTFileMacros;
  571. collectMacroDefinitions(PPOpts, ASTFileMacros);
  572. MacroDefinitionsMap ExistingMacros;
  573. SmallVector<StringRef, 4> ExistingMacroNames;
  574. collectMacroDefinitions(ExistingPPOpts, ExistingMacros, &ExistingMacroNames);
  575. for (unsigned I = 0, N = ExistingMacroNames.size(); I != N; ++I) {
  576. // Dig out the macro definition in the existing preprocessor options.
  577. StringRef MacroName = ExistingMacroNames[I];
  578. std::pair<StringRef, bool> Existing = ExistingMacros[MacroName];
  579. // Check whether we know anything about this macro name or not.
  580. llvm::StringMap<std::pair<StringRef, bool /*IsUndef*/>>::iterator Known =
  581. ASTFileMacros.find(MacroName);
  582. if (!Validate || Known == ASTFileMacros.end()) {
  583. // FIXME: Check whether this identifier was referenced anywhere in the
  584. // AST file. If so, we should reject the AST file. Unfortunately, this
  585. // information isn't in the control block. What shall we do about it?
  586. if (Existing.second) {
  587. SuggestedPredefines += "#undef ";
  588. SuggestedPredefines += MacroName.str();
  589. SuggestedPredefines += '\n';
  590. } else {
  591. SuggestedPredefines += "#define ";
  592. SuggestedPredefines += MacroName.str();
  593. SuggestedPredefines += ' ';
  594. SuggestedPredefines += Existing.first.str();
  595. SuggestedPredefines += '\n';
  596. }
  597. continue;
  598. }
  599. // If the macro was defined in one but undef'd in the other, we have a
  600. // conflict.
  601. if (Existing.second != Known->second.second) {
  602. if (Diags) {
  603. Diags->Report(diag::err_pch_macro_def_undef)
  604. << MacroName << Known->second.second;
  605. }
  606. return true;
  607. }
  608. // If the macro was #undef'd in both, or if the macro bodies are identical,
  609. // it's fine.
  610. if (Existing.second || Existing.first == Known->second.first)
  611. continue;
  612. // The macro bodies differ; complain.
  613. if (Diags) {
  614. Diags->Report(diag::err_pch_macro_def_conflict)
  615. << MacroName << Known->second.first << Existing.first;
  616. }
  617. return true;
  618. }
  619. // Check whether we're using predefines.
  620. if (PPOpts.UsePredefines != ExistingPPOpts.UsePredefines && Validate) {
  621. if (Diags) {
  622. Diags->Report(diag::err_pch_undef) << ExistingPPOpts.UsePredefines;
  623. }
  624. return true;
  625. }
  626. // Detailed record is important since it is used for the module cache hash.
  627. if (LangOpts.Modules &&
  628. PPOpts.DetailedRecord != ExistingPPOpts.DetailedRecord && Validate) {
  629. if (Diags) {
  630. Diags->Report(diag::err_pch_pp_detailed_record) << PPOpts.DetailedRecord;
  631. }
  632. return true;
  633. }
  634. // Compute the #include and #include_macros lines we need.
  635. for (unsigned I = 0, N = ExistingPPOpts.Includes.size(); I != N; ++I) {
  636. StringRef File = ExistingPPOpts.Includes[I];
  637. if (!ExistingPPOpts.ImplicitPCHInclude.empty() &&
  638. !ExistingPPOpts.PCHThroughHeader.empty()) {
  639. // In case the through header is an include, we must add all the includes
  640. // to the predefines so the start point can be determined.
  641. SuggestedPredefines += "#include \"";
  642. SuggestedPredefines += File;
  643. SuggestedPredefines += "\"\n";
  644. continue;
  645. }
  646. if (File == ExistingPPOpts.ImplicitPCHInclude)
  647. continue;
  648. if (llvm::is_contained(PPOpts.Includes, File))
  649. continue;
  650. SuggestedPredefines += "#include \"";
  651. SuggestedPredefines += File;
  652. SuggestedPredefines += "\"\n";
  653. }
  654. for (unsigned I = 0, N = ExistingPPOpts.MacroIncludes.size(); I != N; ++I) {
  655. StringRef File = ExistingPPOpts.MacroIncludes[I];
  656. if (llvm::is_contained(PPOpts.MacroIncludes, File))
  657. continue;
  658. SuggestedPredefines += "#__include_macros \"";
  659. SuggestedPredefines += File;
  660. SuggestedPredefines += "\"\n##\n";
  661. }
  662. return false;
  663. }
  664. bool PCHValidator::ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  665. bool Complain,
  666. std::string &SuggestedPredefines) {
  667. const PreprocessorOptions &ExistingPPOpts = PP.getPreprocessorOpts();
  668. return checkPreprocessorOptions(PPOpts, ExistingPPOpts,
  669. Complain? &Reader.Diags : nullptr,
  670. PP.getFileManager(),
  671. SuggestedPredefines,
  672. PP.getLangOpts());
  673. }
  674. bool SimpleASTReaderListener::ReadPreprocessorOptions(
  675. const PreprocessorOptions &PPOpts,
  676. bool Complain,
  677. std::string &SuggestedPredefines) {
  678. return checkPreprocessorOptions(PPOpts,
  679. PP.getPreprocessorOpts(),
  680. nullptr,
  681. PP.getFileManager(),
  682. SuggestedPredefines,
  683. PP.getLangOpts(),
  684. false);
  685. }
  686. /// Check the header search options deserialized from the control block
  687. /// against the header search options in an existing preprocessor.
  688. ///
  689. /// \param Diags If non-null, produce diagnostics for any mismatches incurred.
  690. static bool checkHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  691. StringRef SpecificModuleCachePath,
  692. StringRef ExistingModuleCachePath,
  693. DiagnosticsEngine *Diags,
  694. const LangOptions &LangOpts,
  695. const PreprocessorOptions &PPOpts) {
  696. if (LangOpts.Modules) {
  697. if (SpecificModuleCachePath != ExistingModuleCachePath &&
  698. !PPOpts.AllowPCHWithDifferentModulesCachePath) {
  699. if (Diags)
  700. Diags->Report(diag::err_pch_modulecache_mismatch)
  701. << SpecificModuleCachePath << ExistingModuleCachePath;
  702. return true;
  703. }
  704. }
  705. return false;
  706. }
  707. bool PCHValidator::ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  708. StringRef SpecificModuleCachePath,
  709. bool Complain) {
  710. return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  711. PP.getHeaderSearchInfo().getModuleCachePath(),
  712. Complain ? &Reader.Diags : nullptr,
  713. PP.getLangOpts(), PP.getPreprocessorOpts());
  714. }
  715. void PCHValidator::ReadCounter(const ModuleFile &M, unsigned Value) {
  716. PP.setCounterValue(Value);
  717. }
  718. //===----------------------------------------------------------------------===//
  719. // AST reader implementation
  720. //===----------------------------------------------------------------------===//
  721. static uint64_t readULEB(const unsigned char *&P) {
  722. unsigned Length = 0;
  723. const char *Error = nullptr;
  724. uint64_t Val = llvm::decodeULEB128(P, &Length, nullptr, &Error);
  725. if (Error)
  726. llvm::report_fatal_error(Error);
  727. P += Length;
  728. return Val;
  729. }
  730. /// Read ULEB-encoded key length and data length.
  731. static std::pair<unsigned, unsigned>
  732. readULEBKeyDataLength(const unsigned char *&P) {
  733. unsigned KeyLen = readULEB(P);
  734. if ((unsigned)KeyLen != KeyLen)
  735. llvm::report_fatal_error("key too large");
  736. unsigned DataLen = readULEB(P);
  737. if ((unsigned)DataLen != DataLen)
  738. llvm::report_fatal_error("data too large");
  739. return std::make_pair(KeyLen, DataLen);
  740. }
  741. void ASTReader::setDeserializationListener(ASTDeserializationListener *Listener,
  742. bool TakeOwnership) {
  743. DeserializationListener = Listener;
  744. OwnsDeserializationListener = TakeOwnership;
  745. }
  746. unsigned ASTSelectorLookupTrait::ComputeHash(Selector Sel) {
  747. return serialization::ComputeHash(Sel);
  748. }
  749. std::pair<unsigned, unsigned>
  750. ASTSelectorLookupTrait::ReadKeyDataLength(const unsigned char*& d) {
  751. return readULEBKeyDataLength(d);
  752. }
  753. ASTSelectorLookupTrait::internal_key_type
  754. ASTSelectorLookupTrait::ReadKey(const unsigned char* d, unsigned) {
  755. using namespace llvm::support;
  756. SelectorTable &SelTable = Reader.getContext().Selectors;
  757. unsigned N = endian::readNext<uint16_t, little, unaligned>(d);
  758. IdentifierInfo *FirstII = Reader.getLocalIdentifier(
  759. F, endian::readNext<uint32_t, little, unaligned>(d));
  760. if (N == 0)
  761. return SelTable.getNullarySelector(FirstII);
  762. else if (N == 1)
  763. return SelTable.getUnarySelector(FirstII);
  764. SmallVector<IdentifierInfo *, 16> Args;
  765. Args.push_back(FirstII);
  766. for (unsigned I = 1; I != N; ++I)
  767. Args.push_back(Reader.getLocalIdentifier(
  768. F, endian::readNext<uint32_t, little, unaligned>(d)));
  769. return SelTable.getSelector(N, Args.data());
  770. }
  771. ASTSelectorLookupTrait::data_type
  772. ASTSelectorLookupTrait::ReadData(Selector, const unsigned char* d,
  773. unsigned DataLen) {
  774. using namespace llvm::support;
  775. data_type Result;
  776. Result.ID = Reader.getGlobalSelectorID(
  777. F, endian::readNext<uint32_t, little, unaligned>(d));
  778. unsigned FullInstanceBits = endian::readNext<uint16_t, little, unaligned>(d);
  779. unsigned FullFactoryBits = endian::readNext<uint16_t, little, unaligned>(d);
  780. Result.InstanceBits = FullInstanceBits & 0x3;
  781. Result.InstanceHasMoreThanOneDecl = (FullInstanceBits >> 2) & 0x1;
  782. Result.FactoryBits = FullFactoryBits & 0x3;
  783. Result.FactoryHasMoreThanOneDecl = (FullFactoryBits >> 2) & 0x1;
  784. unsigned NumInstanceMethods = FullInstanceBits >> 3;
  785. unsigned NumFactoryMethods = FullFactoryBits >> 3;
  786. // Load instance methods
  787. for (unsigned I = 0; I != NumInstanceMethods; ++I) {
  788. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  789. F, endian::readNext<uint32_t, little, unaligned>(d)))
  790. Result.Instance.push_back(Method);
  791. }
  792. // Load factory methods
  793. for (unsigned I = 0; I != NumFactoryMethods; ++I) {
  794. if (ObjCMethodDecl *Method = Reader.GetLocalDeclAs<ObjCMethodDecl>(
  795. F, endian::readNext<uint32_t, little, unaligned>(d)))
  796. Result.Factory.push_back(Method);
  797. }
  798. return Result;
  799. }
  800. unsigned ASTIdentifierLookupTraitBase::ComputeHash(const internal_key_type& a) {
  801. return llvm::djbHash(a);
  802. }
  803. std::pair<unsigned, unsigned>
  804. ASTIdentifierLookupTraitBase::ReadKeyDataLength(const unsigned char*& d) {
  805. return readULEBKeyDataLength(d);
  806. }
  807. ASTIdentifierLookupTraitBase::internal_key_type
  808. ASTIdentifierLookupTraitBase::ReadKey(const unsigned char* d, unsigned n) {
  809. assert(n >= 2 && d[n-1] == '\0');
  810. return StringRef((const char*) d, n-1);
  811. }
  812. /// Whether the given identifier is "interesting".
  813. static bool isInterestingIdentifier(ASTReader &Reader, IdentifierInfo &II,
  814. bool IsModule) {
  815. return II.hadMacroDefinition() || II.isPoisoned() ||
  816. (!IsModule && II.getObjCOrBuiltinID()) ||
  817. II.hasRevertedTokenIDToIdentifier() ||
  818. (!(IsModule && Reader.getPreprocessor().getLangOpts().CPlusPlus) &&
  819. II.getFETokenInfo());
  820. }
  821. static bool readBit(unsigned &Bits) {
  822. bool Value = Bits & 0x1;
  823. Bits >>= 1;
  824. return Value;
  825. }
  826. IdentID ASTIdentifierLookupTrait::ReadIdentifierID(const unsigned char *d) {
  827. using namespace llvm::support;
  828. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  829. return Reader.getGlobalIdentifierID(F, RawID >> 1);
  830. }
  831. static void markIdentifierFromAST(ASTReader &Reader, IdentifierInfo &II) {
  832. if (!II.isFromAST()) {
  833. II.setIsFromAST();
  834. bool IsModule = Reader.getPreprocessor().getCurrentModule() != nullptr;
  835. if (isInterestingIdentifier(Reader, II, IsModule))
  836. II.setChangedSinceDeserialization();
  837. }
  838. }
  839. IdentifierInfo *ASTIdentifierLookupTrait::ReadData(const internal_key_type& k,
  840. const unsigned char* d,
  841. unsigned DataLen) {
  842. using namespace llvm::support;
  843. unsigned RawID = endian::readNext<uint32_t, little, unaligned>(d);
  844. bool IsInteresting = RawID & 0x01;
  845. // Wipe out the "is interesting" bit.
  846. RawID = RawID >> 1;
  847. // Build the IdentifierInfo and link the identifier ID with it.
  848. IdentifierInfo *II = KnownII;
  849. if (!II) {
  850. II = &Reader.getIdentifierTable().getOwn(k);
  851. KnownII = II;
  852. }
  853. markIdentifierFromAST(Reader, *II);
  854. Reader.markIdentifierUpToDate(II);
  855. IdentID ID = Reader.getGlobalIdentifierID(F, RawID);
  856. if (!IsInteresting) {
  857. // For uninteresting identifiers, there's nothing else to do. Just notify
  858. // the reader that we've finished loading this identifier.
  859. Reader.SetIdentifierInfo(ID, II);
  860. return II;
  861. }
  862. unsigned ObjCOrBuiltinID = endian::readNext<uint16_t, little, unaligned>(d);
  863. unsigned Bits = endian::readNext<uint16_t, little, unaligned>(d);
  864. bool CPlusPlusOperatorKeyword = readBit(Bits);
  865. bool HasRevertedTokenIDToIdentifier = readBit(Bits);
  866. bool Poisoned = readBit(Bits);
  867. bool ExtensionToken = readBit(Bits);
  868. bool HadMacroDefinition = readBit(Bits);
  869. assert(Bits == 0 && "Extra bits in the identifier?");
  870. DataLen -= 8;
  871. // Set or check the various bits in the IdentifierInfo structure.
  872. // Token IDs are read-only.
  873. if (HasRevertedTokenIDToIdentifier && II->getTokenID() != tok::identifier)
  874. II->revertTokenIDToIdentifier();
  875. if (!F.isModule())
  876. II->setObjCOrBuiltinID(ObjCOrBuiltinID);
  877. assert(II->isExtensionToken() == ExtensionToken &&
  878. "Incorrect extension token flag");
  879. (void)ExtensionToken;
  880. if (Poisoned)
  881. II->setIsPoisoned(true);
  882. assert(II->isCPlusPlusOperatorKeyword() == CPlusPlusOperatorKeyword &&
  883. "Incorrect C++ operator keyword flag");
  884. (void)CPlusPlusOperatorKeyword;
  885. // If this identifier is a macro, deserialize the macro
  886. // definition.
  887. if (HadMacroDefinition) {
  888. uint32_t MacroDirectivesOffset =
  889. endian::readNext<uint32_t, little, unaligned>(d);
  890. DataLen -= 4;
  891. Reader.addPendingMacro(II, &F, MacroDirectivesOffset);
  892. }
  893. Reader.SetIdentifierInfo(ID, II);
  894. // Read all of the declarations visible at global scope with this
  895. // name.
  896. if (DataLen > 0) {
  897. SmallVector<uint32_t, 4> DeclIDs;
  898. for (; DataLen > 0; DataLen -= 4)
  899. DeclIDs.push_back(Reader.getGlobalDeclID(
  900. F, endian::readNext<uint32_t, little, unaligned>(d)));
  901. Reader.SetGloballyVisibleDecls(II, DeclIDs);
  902. }
  903. return II;
  904. }
  905. DeclarationNameKey::DeclarationNameKey(DeclarationName Name)
  906. : Kind(Name.getNameKind()) {
  907. switch (Kind) {
  908. case DeclarationName::Identifier:
  909. Data = (uint64_t)Name.getAsIdentifierInfo();
  910. break;
  911. case DeclarationName::ObjCZeroArgSelector:
  912. case DeclarationName::ObjCOneArgSelector:
  913. case DeclarationName::ObjCMultiArgSelector:
  914. Data = (uint64_t)Name.getObjCSelector().getAsOpaquePtr();
  915. break;
  916. case DeclarationName::CXXOperatorName:
  917. Data = Name.getCXXOverloadedOperator();
  918. break;
  919. case DeclarationName::CXXLiteralOperatorName:
  920. Data = (uint64_t)Name.getCXXLiteralIdentifier();
  921. break;
  922. case DeclarationName::CXXDeductionGuideName:
  923. Data = (uint64_t)Name.getCXXDeductionGuideTemplate()
  924. ->getDeclName().getAsIdentifierInfo();
  925. break;
  926. case DeclarationName::CXXConstructorName:
  927. case DeclarationName::CXXDestructorName:
  928. case DeclarationName::CXXConversionFunctionName:
  929. case DeclarationName::CXXUsingDirective:
  930. Data = 0;
  931. break;
  932. }
  933. }
  934. unsigned DeclarationNameKey::getHash() const {
  935. llvm::FoldingSetNodeID ID;
  936. ID.AddInteger(Kind);
  937. switch (Kind) {
  938. case DeclarationName::Identifier:
  939. case DeclarationName::CXXLiteralOperatorName:
  940. case DeclarationName::CXXDeductionGuideName:
  941. ID.AddString(((IdentifierInfo*)Data)->getName());
  942. break;
  943. case DeclarationName::ObjCZeroArgSelector:
  944. case DeclarationName::ObjCOneArgSelector:
  945. case DeclarationName::ObjCMultiArgSelector:
  946. ID.AddInteger(serialization::ComputeHash(Selector(Data)));
  947. break;
  948. case DeclarationName::CXXOperatorName:
  949. ID.AddInteger((OverloadedOperatorKind)Data);
  950. break;
  951. case DeclarationName::CXXConstructorName:
  952. case DeclarationName::CXXDestructorName:
  953. case DeclarationName::CXXConversionFunctionName:
  954. case DeclarationName::CXXUsingDirective:
  955. break;
  956. }
  957. return ID.ComputeHash();
  958. }
  959. ModuleFile *
  960. ASTDeclContextNameLookupTrait::ReadFileRef(const unsigned char *&d) {
  961. using namespace llvm::support;
  962. uint32_t ModuleFileID = endian::readNext<uint32_t, little, unaligned>(d);
  963. return Reader.getLocalModuleFile(F, ModuleFileID);
  964. }
  965. std::pair<unsigned, unsigned>
  966. ASTDeclContextNameLookupTrait::ReadKeyDataLength(const unsigned char *&d) {
  967. return readULEBKeyDataLength(d);
  968. }
  969. ASTDeclContextNameLookupTrait::internal_key_type
  970. ASTDeclContextNameLookupTrait::ReadKey(const unsigned char *d, unsigned) {
  971. using namespace llvm::support;
  972. auto Kind = (DeclarationName::NameKind)*d++;
  973. uint64_t Data;
  974. switch (Kind) {
  975. case DeclarationName::Identifier:
  976. case DeclarationName::CXXLiteralOperatorName:
  977. case DeclarationName::CXXDeductionGuideName:
  978. Data = (uint64_t)Reader.getLocalIdentifier(
  979. F, endian::readNext<uint32_t, little, unaligned>(d));
  980. break;
  981. case DeclarationName::ObjCZeroArgSelector:
  982. case DeclarationName::ObjCOneArgSelector:
  983. case DeclarationName::ObjCMultiArgSelector:
  984. Data =
  985. (uint64_t)Reader.getLocalSelector(
  986. F, endian::readNext<uint32_t, little, unaligned>(
  987. d)).getAsOpaquePtr();
  988. break;
  989. case DeclarationName::CXXOperatorName:
  990. Data = *d++; // OverloadedOperatorKind
  991. break;
  992. case DeclarationName::CXXConstructorName:
  993. case DeclarationName::CXXDestructorName:
  994. case DeclarationName::CXXConversionFunctionName:
  995. case DeclarationName::CXXUsingDirective:
  996. Data = 0;
  997. break;
  998. }
  999. return DeclarationNameKey(Kind, Data);
  1000. }
  1001. void ASTDeclContextNameLookupTrait::ReadDataInto(internal_key_type,
  1002. const unsigned char *d,
  1003. unsigned DataLen,
  1004. data_type_builder &Val) {
  1005. using namespace llvm::support;
  1006. for (unsigned NumDecls = DataLen / 4; NumDecls; --NumDecls) {
  1007. uint32_t LocalID = endian::readNext<uint32_t, little, unaligned>(d);
  1008. Val.insert(Reader.getGlobalDeclID(F, LocalID));
  1009. }
  1010. }
  1011. bool ASTReader::ReadLexicalDeclContextStorage(ModuleFile &M,
  1012. BitstreamCursor &Cursor,
  1013. uint64_t Offset,
  1014. DeclContext *DC) {
  1015. assert(Offset != 0);
  1016. SavedStreamPosition SavedPosition(Cursor);
  1017. if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
  1018. Error(std::move(Err));
  1019. return true;
  1020. }
  1021. RecordData Record;
  1022. StringRef Blob;
  1023. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  1024. if (!MaybeCode) {
  1025. Error(MaybeCode.takeError());
  1026. return true;
  1027. }
  1028. unsigned Code = MaybeCode.get();
  1029. Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
  1030. if (!MaybeRecCode) {
  1031. Error(MaybeRecCode.takeError());
  1032. return true;
  1033. }
  1034. unsigned RecCode = MaybeRecCode.get();
  1035. if (RecCode != DECL_CONTEXT_LEXICAL) {
  1036. Error("Expected lexical block");
  1037. return true;
  1038. }
  1039. assert(!isa<TranslationUnitDecl>(DC) &&
  1040. "expected a TU_UPDATE_LEXICAL record for TU");
  1041. // If we are handling a C++ class template instantiation, we can see multiple
  1042. // lexical updates for the same record. It's important that we select only one
  1043. // of them, so that field numbering works properly. Just pick the first one we
  1044. // see.
  1045. auto &Lex = LexicalDecls[DC];
  1046. if (!Lex.first) {
  1047. Lex = std::make_pair(
  1048. &M, llvm::makeArrayRef(
  1049. reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
  1050. Blob.data()),
  1051. Blob.size() / 4));
  1052. }
  1053. DC->setHasExternalLexicalStorage(true);
  1054. return false;
  1055. }
  1056. bool ASTReader::ReadVisibleDeclContextStorage(ModuleFile &M,
  1057. BitstreamCursor &Cursor,
  1058. uint64_t Offset,
  1059. DeclID ID) {
  1060. assert(Offset != 0);
  1061. SavedStreamPosition SavedPosition(Cursor);
  1062. if (llvm::Error Err = Cursor.JumpToBit(Offset)) {
  1063. Error(std::move(Err));
  1064. return true;
  1065. }
  1066. RecordData Record;
  1067. StringRef Blob;
  1068. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  1069. if (!MaybeCode) {
  1070. Error(MaybeCode.takeError());
  1071. return true;
  1072. }
  1073. unsigned Code = MaybeCode.get();
  1074. Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record, &Blob);
  1075. if (!MaybeRecCode) {
  1076. Error(MaybeRecCode.takeError());
  1077. return true;
  1078. }
  1079. unsigned RecCode = MaybeRecCode.get();
  1080. if (RecCode != DECL_CONTEXT_VISIBLE) {
  1081. Error("Expected visible lookup table block");
  1082. return true;
  1083. }
  1084. // We can't safely determine the primary context yet, so delay attaching the
  1085. // lookup table until we're done with recursive deserialization.
  1086. auto *Data = (const unsigned char*)Blob.data();
  1087. PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&M, Data});
  1088. return false;
  1089. }
  1090. void ASTReader::Error(StringRef Msg) const {
  1091. Error(diag::err_fe_pch_malformed, Msg);
  1092. if (PP.getLangOpts().Modules && !Diags.isDiagnosticInFlight() &&
  1093. !PP.getHeaderSearchInfo().getModuleCachePath().empty()) {
  1094. Diag(diag::note_module_cache_path)
  1095. << PP.getHeaderSearchInfo().getModuleCachePath();
  1096. }
  1097. }
  1098. void ASTReader::Error(unsigned DiagID, StringRef Arg1, StringRef Arg2,
  1099. StringRef Arg3) const {
  1100. if (Diags.isDiagnosticInFlight())
  1101. Diags.SetDelayedDiagnostic(DiagID, Arg1, Arg2, Arg3);
  1102. else
  1103. Diag(DiagID) << Arg1 << Arg2 << Arg3;
  1104. }
  1105. void ASTReader::Error(llvm::Error &&Err) const {
  1106. llvm::Error RemainingErr =
  1107. handleErrors(std::move(Err), [this](const DiagnosticError &E) {
  1108. auto Diag = E.getDiagnostic().second;
  1109. // Ideally we'd just emit it, but have to handle a possible in-flight
  1110. // diagnostic. Note that the location is currently ignored as well.
  1111. auto NumArgs = Diag.getStorage()->NumDiagArgs;
  1112. assert(NumArgs <= 3 && "Can only have up to 3 arguments");
  1113. StringRef Arg1, Arg2, Arg3;
  1114. switch (NumArgs) {
  1115. case 3:
  1116. Arg3 = Diag.getStringArg(2);
  1117. LLVM_FALLTHROUGH;
  1118. case 2:
  1119. Arg2 = Diag.getStringArg(1);
  1120. LLVM_FALLTHROUGH;
  1121. case 1:
  1122. Arg1 = Diag.getStringArg(0);
  1123. }
  1124. Error(Diag.getDiagID(), Arg1, Arg2, Arg3);
  1125. });
  1126. if (RemainingErr)
  1127. Error(toString(std::move(RemainingErr)));
  1128. }
  1129. //===----------------------------------------------------------------------===//
  1130. // Source Manager Deserialization
  1131. //===----------------------------------------------------------------------===//
  1132. /// Read the line table in the source manager block.
  1133. void ASTReader::ParseLineTable(ModuleFile &F, const RecordData &Record) {
  1134. unsigned Idx = 0;
  1135. LineTableInfo &LineTable = SourceMgr.getLineTable();
  1136. // Parse the file names
  1137. std::map<int, int> FileIDs;
  1138. FileIDs[-1] = -1; // For unspecified filenames.
  1139. for (unsigned I = 0; Record[Idx]; ++I) {
  1140. // Extract the file name
  1141. auto Filename = ReadPath(F, Record, Idx);
  1142. FileIDs[I] = LineTable.getLineTableFilenameID(Filename);
  1143. }
  1144. ++Idx;
  1145. // Parse the line entries
  1146. std::vector<LineEntry> Entries;
  1147. while (Idx < Record.size()) {
  1148. int FID = Record[Idx++];
  1149. assert(FID >= 0 && "Serialized line entries for non-local file.");
  1150. // Remap FileID from 1-based old view.
  1151. FID += F.SLocEntryBaseID - 1;
  1152. // Extract the line entries
  1153. unsigned NumEntries = Record[Idx++];
  1154. assert(NumEntries && "no line entries for file ID");
  1155. Entries.clear();
  1156. Entries.reserve(NumEntries);
  1157. for (unsigned I = 0; I != NumEntries; ++I) {
  1158. unsigned FileOffset = Record[Idx++];
  1159. unsigned LineNo = Record[Idx++];
  1160. int FilenameID = FileIDs[Record[Idx++]];
  1161. SrcMgr::CharacteristicKind FileKind
  1162. = (SrcMgr::CharacteristicKind)Record[Idx++];
  1163. unsigned IncludeOffset = Record[Idx++];
  1164. Entries.push_back(LineEntry::get(FileOffset, LineNo, FilenameID,
  1165. FileKind, IncludeOffset));
  1166. }
  1167. LineTable.AddEntry(FileID::get(FID), Entries);
  1168. }
  1169. }
  1170. /// Read a source manager block
  1171. llvm::Error ASTReader::ReadSourceManagerBlock(ModuleFile &F) {
  1172. using namespace SrcMgr;
  1173. BitstreamCursor &SLocEntryCursor = F.SLocEntryCursor;
  1174. // Set the source-location entry cursor to the current position in
  1175. // the stream. This cursor will be used to read the contents of the
  1176. // source manager block initially, and then lazily read
  1177. // source-location entries as needed.
  1178. SLocEntryCursor = F.Stream;
  1179. // The stream itself is going to skip over the source manager block.
  1180. if (llvm::Error Err = F.Stream.SkipBlock())
  1181. return Err;
  1182. // Enter the source manager block.
  1183. if (llvm::Error Err = SLocEntryCursor.EnterSubBlock(SOURCE_MANAGER_BLOCK_ID))
  1184. return Err;
  1185. F.SourceManagerBlockStartOffset = SLocEntryCursor.GetCurrentBitNo();
  1186. RecordData Record;
  1187. while (true) {
  1188. Expected<llvm::BitstreamEntry> MaybeE =
  1189. SLocEntryCursor.advanceSkippingSubblocks();
  1190. if (!MaybeE)
  1191. return MaybeE.takeError();
  1192. llvm::BitstreamEntry E = MaybeE.get();
  1193. switch (E.Kind) {
  1194. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1195. case llvm::BitstreamEntry::Error:
  1196. return llvm::createStringError(std::errc::illegal_byte_sequence,
  1197. "malformed block record in AST file");
  1198. case llvm::BitstreamEntry::EndBlock:
  1199. return llvm::Error::success();
  1200. case llvm::BitstreamEntry::Record:
  1201. // The interesting case.
  1202. break;
  1203. }
  1204. // Read a record.
  1205. Record.clear();
  1206. StringRef Blob;
  1207. Expected<unsigned> MaybeRecord =
  1208. SLocEntryCursor.readRecord(E.ID, Record, &Blob);
  1209. if (!MaybeRecord)
  1210. return MaybeRecord.takeError();
  1211. switch (MaybeRecord.get()) {
  1212. default: // Default behavior: ignore.
  1213. break;
  1214. case SM_SLOC_FILE_ENTRY:
  1215. case SM_SLOC_BUFFER_ENTRY:
  1216. case SM_SLOC_EXPANSION_ENTRY:
  1217. // Once we hit one of the source location entries, we're done.
  1218. return llvm::Error::success();
  1219. }
  1220. }
  1221. }
  1222. /// If a header file is not found at the path that we expect it to be
  1223. /// and the PCH file was moved from its original location, try to resolve the
  1224. /// file by assuming that header+PCH were moved together and the header is in
  1225. /// the same place relative to the PCH.
  1226. static std::string
  1227. resolveFileRelativeToOriginalDir(const std::string &Filename,
  1228. const std::string &OriginalDir,
  1229. const std::string &CurrDir) {
  1230. assert(OriginalDir != CurrDir &&
  1231. "No point trying to resolve the file if the PCH dir didn't change");
  1232. using namespace llvm::sys;
  1233. SmallString<128> filePath(Filename);
  1234. fs::make_absolute(filePath);
  1235. assert(path::is_absolute(OriginalDir));
  1236. SmallString<128> currPCHPath(CurrDir);
  1237. path::const_iterator fileDirI = path::begin(path::parent_path(filePath)),
  1238. fileDirE = path::end(path::parent_path(filePath));
  1239. path::const_iterator origDirI = path::begin(OriginalDir),
  1240. origDirE = path::end(OriginalDir);
  1241. // Skip the common path components from filePath and OriginalDir.
  1242. while (fileDirI != fileDirE && origDirI != origDirE &&
  1243. *fileDirI == *origDirI) {
  1244. ++fileDirI;
  1245. ++origDirI;
  1246. }
  1247. for (; origDirI != origDirE; ++origDirI)
  1248. path::append(currPCHPath, "..");
  1249. path::append(currPCHPath, fileDirI, fileDirE);
  1250. path::append(currPCHPath, path::filename(Filename));
  1251. return std::string(currPCHPath.str());
  1252. }
  1253. bool ASTReader::ReadSLocEntry(int ID) {
  1254. if (ID == 0)
  1255. return false;
  1256. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1257. Error("source location entry ID out-of-range for AST file");
  1258. return true;
  1259. }
  1260. // Local helper to read the (possibly-compressed) buffer data following the
  1261. // entry record.
  1262. auto ReadBuffer = [this](
  1263. BitstreamCursor &SLocEntryCursor,
  1264. StringRef Name) -> std::unique_ptr<llvm::MemoryBuffer> {
  1265. RecordData Record;
  1266. StringRef Blob;
  1267. Expected<unsigned> MaybeCode = SLocEntryCursor.ReadCode();
  1268. if (!MaybeCode) {
  1269. Error(MaybeCode.takeError());
  1270. return nullptr;
  1271. }
  1272. unsigned Code = MaybeCode.get();
  1273. Expected<unsigned> MaybeRecCode =
  1274. SLocEntryCursor.readRecord(Code, Record, &Blob);
  1275. if (!MaybeRecCode) {
  1276. Error(MaybeRecCode.takeError());
  1277. return nullptr;
  1278. }
  1279. unsigned RecCode = MaybeRecCode.get();
  1280. if (RecCode == SM_SLOC_BUFFER_BLOB_COMPRESSED) {
  1281. if (!llvm::zlib::isAvailable()) {
  1282. Error("zlib is not available");
  1283. return nullptr;
  1284. }
  1285. SmallString<0> Uncompressed;
  1286. if (llvm::Error E =
  1287. llvm::zlib::uncompress(Blob, Uncompressed, Record[0])) {
  1288. Error("could not decompress embedded file contents: " +
  1289. llvm::toString(std::move(E)));
  1290. return nullptr;
  1291. }
  1292. return llvm::MemoryBuffer::getMemBufferCopy(Uncompressed, Name);
  1293. } else if (RecCode == SM_SLOC_BUFFER_BLOB) {
  1294. return llvm::MemoryBuffer::getMemBuffer(Blob.drop_back(1), Name, true);
  1295. } else {
  1296. Error("AST record has invalid code");
  1297. return nullptr;
  1298. }
  1299. };
  1300. ModuleFile *F = GlobalSLocEntryMap.find(-ID)->second;
  1301. if (llvm::Error Err = F->SLocEntryCursor.JumpToBit(
  1302. F->SLocEntryOffsetsBase +
  1303. F->SLocEntryOffsets[ID - F->SLocEntryBaseID])) {
  1304. Error(std::move(Err));
  1305. return true;
  1306. }
  1307. BitstreamCursor &SLocEntryCursor = F->SLocEntryCursor;
  1308. SourceLocation::UIntTy BaseOffset = F->SLocEntryBaseOffset;
  1309. ++NumSLocEntriesRead;
  1310. Expected<llvm::BitstreamEntry> MaybeEntry = SLocEntryCursor.advance();
  1311. if (!MaybeEntry) {
  1312. Error(MaybeEntry.takeError());
  1313. return true;
  1314. }
  1315. llvm::BitstreamEntry Entry = MaybeEntry.get();
  1316. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1317. Error("incorrectly-formatted source location entry in AST file");
  1318. return true;
  1319. }
  1320. RecordData Record;
  1321. StringRef Blob;
  1322. Expected<unsigned> MaybeSLOC =
  1323. SLocEntryCursor.readRecord(Entry.ID, Record, &Blob);
  1324. if (!MaybeSLOC) {
  1325. Error(MaybeSLOC.takeError());
  1326. return true;
  1327. }
  1328. switch (MaybeSLOC.get()) {
  1329. default:
  1330. Error("incorrectly-formatted source location entry in AST file");
  1331. return true;
  1332. case SM_SLOC_FILE_ENTRY: {
  1333. // We will detect whether a file changed and return 'Failure' for it, but
  1334. // we will also try to fail gracefully by setting up the SLocEntry.
  1335. unsigned InputID = Record[4];
  1336. InputFile IF = getInputFile(*F, InputID);
  1337. Optional<FileEntryRef> File = IF.getFile();
  1338. bool OverriddenBuffer = IF.isOverridden();
  1339. // Note that we only check if a File was returned. If it was out-of-date
  1340. // we have complained but we will continue creating a FileID to recover
  1341. // gracefully.
  1342. if (!File)
  1343. return true;
  1344. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1345. if (IncludeLoc.isInvalid() && F->Kind != MK_MainFile) {
  1346. // This is the module's main file.
  1347. IncludeLoc = getImportLocation(F);
  1348. }
  1349. SrcMgr::CharacteristicKind
  1350. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1351. FileID FID = SourceMgr.createFileID(*File, IncludeLoc, FileCharacter, ID,
  1352. BaseOffset + Record[0]);
  1353. SrcMgr::FileInfo &FileInfo =
  1354. const_cast<SrcMgr::FileInfo&>(SourceMgr.getSLocEntry(FID).getFile());
  1355. FileInfo.NumCreatedFIDs = Record[5];
  1356. if (Record[3])
  1357. FileInfo.setHasLineDirectives();
  1358. unsigned NumFileDecls = Record[7];
  1359. if (NumFileDecls && ContextObj) {
  1360. const DeclID *FirstDecl = F->FileSortedDecls + Record[6];
  1361. assert(F->FileSortedDecls && "FILE_SORTED_DECLS not encountered yet ?");
  1362. FileDeclIDs[FID] = FileDeclsInfo(F, llvm::makeArrayRef(FirstDecl,
  1363. NumFileDecls));
  1364. }
  1365. const SrcMgr::ContentCache &ContentCache =
  1366. SourceMgr.getOrCreateContentCache(*File, isSystem(FileCharacter));
  1367. if (OverriddenBuffer && !ContentCache.BufferOverridden &&
  1368. ContentCache.ContentsEntry == ContentCache.OrigEntry &&
  1369. !ContentCache.getBufferIfLoaded()) {
  1370. auto Buffer = ReadBuffer(SLocEntryCursor, File->getName());
  1371. if (!Buffer)
  1372. return true;
  1373. SourceMgr.overrideFileContents(*File, std::move(Buffer));
  1374. }
  1375. break;
  1376. }
  1377. case SM_SLOC_BUFFER_ENTRY: {
  1378. const char *Name = Blob.data();
  1379. unsigned Offset = Record[0];
  1380. SrcMgr::CharacteristicKind
  1381. FileCharacter = (SrcMgr::CharacteristicKind)Record[2];
  1382. SourceLocation IncludeLoc = ReadSourceLocation(*F, Record[1]);
  1383. if (IncludeLoc.isInvalid() && F->isModule()) {
  1384. IncludeLoc = getImportLocation(F);
  1385. }
  1386. auto Buffer = ReadBuffer(SLocEntryCursor, Name);
  1387. if (!Buffer)
  1388. return true;
  1389. SourceMgr.createFileID(std::move(Buffer), FileCharacter, ID,
  1390. BaseOffset + Offset, IncludeLoc);
  1391. break;
  1392. }
  1393. case SM_SLOC_EXPANSION_ENTRY: {
  1394. SourceLocation SpellingLoc = ReadSourceLocation(*F, Record[1]);
  1395. SourceMgr.createExpansionLoc(SpellingLoc,
  1396. ReadSourceLocation(*F, Record[2]),
  1397. ReadSourceLocation(*F, Record[3]),
  1398. Record[5],
  1399. Record[4],
  1400. ID,
  1401. BaseOffset + Record[0]);
  1402. break;
  1403. }
  1404. }
  1405. return false;
  1406. }
  1407. std::pair<SourceLocation, StringRef> ASTReader::getModuleImportLoc(int ID) {
  1408. if (ID == 0)
  1409. return std::make_pair(SourceLocation(), "");
  1410. if (unsigned(-ID) - 2 >= getTotalNumSLocs() || ID > 0) {
  1411. Error("source location entry ID out-of-range for AST file");
  1412. return std::make_pair(SourceLocation(), "");
  1413. }
  1414. // Find which module file this entry lands in.
  1415. ModuleFile *M = GlobalSLocEntryMap.find(-ID)->second;
  1416. if (!M->isModule())
  1417. return std::make_pair(SourceLocation(), "");
  1418. // FIXME: Can we map this down to a particular submodule? That would be
  1419. // ideal.
  1420. return std::make_pair(M->ImportLoc, StringRef(M->ModuleName));
  1421. }
  1422. /// Find the location where the module F is imported.
  1423. SourceLocation ASTReader::getImportLocation(ModuleFile *F) {
  1424. if (F->ImportLoc.isValid())
  1425. return F->ImportLoc;
  1426. // Otherwise we have a PCH. It's considered to be "imported" at the first
  1427. // location of its includer.
  1428. if (F->ImportedBy.empty() || !F->ImportedBy[0]) {
  1429. // Main file is the importer.
  1430. assert(SourceMgr.getMainFileID().isValid() && "missing main file");
  1431. return SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
  1432. }
  1433. return F->ImportedBy[0]->FirstLoc;
  1434. }
  1435. /// Enter a subblock of the specified BlockID with the specified cursor. Read
  1436. /// the abbreviations that are at the top of the block and then leave the cursor
  1437. /// pointing into the block.
  1438. llvm::Error ASTReader::ReadBlockAbbrevs(BitstreamCursor &Cursor,
  1439. unsigned BlockID,
  1440. uint64_t *StartOfBlockOffset) {
  1441. if (llvm::Error Err = Cursor.EnterSubBlock(BlockID))
  1442. return Err;
  1443. if (StartOfBlockOffset)
  1444. *StartOfBlockOffset = Cursor.GetCurrentBitNo();
  1445. while (true) {
  1446. uint64_t Offset = Cursor.GetCurrentBitNo();
  1447. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  1448. if (!MaybeCode)
  1449. return MaybeCode.takeError();
  1450. unsigned Code = MaybeCode.get();
  1451. // We expect all abbrevs to be at the start of the block.
  1452. if (Code != llvm::bitc::DEFINE_ABBREV) {
  1453. if (llvm::Error Err = Cursor.JumpToBit(Offset))
  1454. return Err;
  1455. return llvm::Error::success();
  1456. }
  1457. if (llvm::Error Err = Cursor.ReadAbbrevRecord())
  1458. return Err;
  1459. }
  1460. }
  1461. Token ASTReader::ReadToken(ModuleFile &F, const RecordDataImpl &Record,
  1462. unsigned &Idx) {
  1463. Token Tok;
  1464. Tok.startToken();
  1465. Tok.setLocation(ReadSourceLocation(F, Record, Idx));
  1466. Tok.setLength(Record[Idx++]);
  1467. if (IdentifierInfo *II = getLocalIdentifier(F, Record[Idx++]))
  1468. Tok.setIdentifierInfo(II);
  1469. Tok.setKind((tok::TokenKind)Record[Idx++]);
  1470. Tok.setFlag((Token::TokenFlags)Record[Idx++]);
  1471. return Tok;
  1472. }
  1473. MacroInfo *ASTReader::ReadMacroRecord(ModuleFile &F, uint64_t Offset) {
  1474. BitstreamCursor &Stream = F.MacroCursor;
  1475. // Keep track of where we are in the stream, then jump back there
  1476. // after reading this macro.
  1477. SavedStreamPosition SavedPosition(Stream);
  1478. if (llvm::Error Err = Stream.JumpToBit(Offset)) {
  1479. // FIXME this drops errors on the floor.
  1480. consumeError(std::move(Err));
  1481. return nullptr;
  1482. }
  1483. RecordData Record;
  1484. SmallVector<IdentifierInfo*, 16> MacroParams;
  1485. MacroInfo *Macro = nullptr;
  1486. while (true) {
  1487. // Advance to the next record, but if we get to the end of the block, don't
  1488. // pop it (removing all the abbreviations from the cursor) since we want to
  1489. // be able to reseek within the block and read entries.
  1490. unsigned Flags = BitstreamCursor::AF_DontPopBlockAtEnd;
  1491. Expected<llvm::BitstreamEntry> MaybeEntry =
  1492. Stream.advanceSkippingSubblocks(Flags);
  1493. if (!MaybeEntry) {
  1494. Error(MaybeEntry.takeError());
  1495. return Macro;
  1496. }
  1497. llvm::BitstreamEntry Entry = MaybeEntry.get();
  1498. switch (Entry.Kind) {
  1499. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1500. case llvm::BitstreamEntry::Error:
  1501. Error("malformed block record in AST file");
  1502. return Macro;
  1503. case llvm::BitstreamEntry::EndBlock:
  1504. return Macro;
  1505. case llvm::BitstreamEntry::Record:
  1506. // The interesting case.
  1507. break;
  1508. }
  1509. // Read a record.
  1510. Record.clear();
  1511. PreprocessorRecordTypes RecType;
  1512. if (Expected<unsigned> MaybeRecType = Stream.readRecord(Entry.ID, Record))
  1513. RecType = (PreprocessorRecordTypes)MaybeRecType.get();
  1514. else {
  1515. Error(MaybeRecType.takeError());
  1516. return Macro;
  1517. }
  1518. switch (RecType) {
  1519. case PP_MODULE_MACRO:
  1520. case PP_MACRO_DIRECTIVE_HISTORY:
  1521. return Macro;
  1522. case PP_MACRO_OBJECT_LIKE:
  1523. case PP_MACRO_FUNCTION_LIKE: {
  1524. // If we already have a macro, that means that we've hit the end
  1525. // of the definition of the macro we were looking for. We're
  1526. // done.
  1527. if (Macro)
  1528. return Macro;
  1529. unsigned NextIndex = 1; // Skip identifier ID.
  1530. SourceLocation Loc = ReadSourceLocation(F, Record, NextIndex);
  1531. MacroInfo *MI = PP.AllocateMacroInfo(Loc);
  1532. MI->setDefinitionEndLoc(ReadSourceLocation(F, Record, NextIndex));
  1533. MI->setIsUsed(Record[NextIndex++]);
  1534. MI->setUsedForHeaderGuard(Record[NextIndex++]);
  1535. if (RecType == PP_MACRO_FUNCTION_LIKE) {
  1536. // Decode function-like macro info.
  1537. bool isC99VarArgs = Record[NextIndex++];
  1538. bool isGNUVarArgs = Record[NextIndex++];
  1539. bool hasCommaPasting = Record[NextIndex++];
  1540. MacroParams.clear();
  1541. unsigned NumArgs = Record[NextIndex++];
  1542. for (unsigned i = 0; i != NumArgs; ++i)
  1543. MacroParams.push_back(getLocalIdentifier(F, Record[NextIndex++]));
  1544. // Install function-like macro info.
  1545. MI->setIsFunctionLike();
  1546. if (isC99VarArgs) MI->setIsC99Varargs();
  1547. if (isGNUVarArgs) MI->setIsGNUVarargs();
  1548. if (hasCommaPasting) MI->setHasCommaPasting();
  1549. MI->setParameterList(MacroParams, PP.getPreprocessorAllocator());
  1550. }
  1551. // Remember that we saw this macro last so that we add the tokens that
  1552. // form its body to it.
  1553. Macro = MI;
  1554. if (NextIndex + 1 == Record.size() && PP.getPreprocessingRecord() &&
  1555. Record[NextIndex]) {
  1556. // We have a macro definition. Register the association
  1557. PreprocessedEntityID
  1558. GlobalID = getGlobalPreprocessedEntityID(F, Record[NextIndex]);
  1559. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  1560. PreprocessingRecord::PPEntityID PPID =
  1561. PPRec.getPPEntityID(GlobalID - 1, /*isLoaded=*/true);
  1562. MacroDefinitionRecord *PPDef = cast_or_null<MacroDefinitionRecord>(
  1563. PPRec.getPreprocessedEntity(PPID));
  1564. if (PPDef)
  1565. PPRec.RegisterMacroDefinition(Macro, PPDef);
  1566. }
  1567. ++NumMacrosRead;
  1568. break;
  1569. }
  1570. case PP_TOKEN: {
  1571. // If we see a TOKEN before a PP_MACRO_*, then the file is
  1572. // erroneous, just pretend we didn't see this.
  1573. if (!Macro) break;
  1574. unsigned Idx = 0;
  1575. Token Tok = ReadToken(F, Record, Idx);
  1576. Macro->AddTokenToBody(Tok);
  1577. break;
  1578. }
  1579. }
  1580. }
  1581. }
  1582. PreprocessedEntityID
  1583. ASTReader::getGlobalPreprocessedEntityID(ModuleFile &M,
  1584. unsigned LocalID) const {
  1585. if (!M.ModuleOffsetMap.empty())
  1586. ReadModuleOffsetMap(M);
  1587. ContinuousRangeMap<uint32_t, int, 2>::const_iterator
  1588. I = M.PreprocessedEntityRemap.find(LocalID - NUM_PREDEF_PP_ENTITY_IDS);
  1589. assert(I != M.PreprocessedEntityRemap.end()
  1590. && "Invalid index into preprocessed entity index remap");
  1591. return LocalID + I->second;
  1592. }
  1593. unsigned HeaderFileInfoTrait::ComputeHash(internal_key_ref ikey) {
  1594. return llvm::hash_combine(ikey.Size, ikey.ModTime);
  1595. }
  1596. HeaderFileInfoTrait::internal_key_type
  1597. HeaderFileInfoTrait::GetInternalKey(const FileEntry *FE) {
  1598. internal_key_type ikey = {FE->getSize(),
  1599. M.HasTimestamps ? FE->getModificationTime() : 0,
  1600. FE->getName(), /*Imported*/ false};
  1601. return ikey;
  1602. }
  1603. bool HeaderFileInfoTrait::EqualKey(internal_key_ref a, internal_key_ref b) {
  1604. if (a.Size != b.Size || (a.ModTime && b.ModTime && a.ModTime != b.ModTime))
  1605. return false;
  1606. if (llvm::sys::path::is_absolute(a.Filename) && a.Filename == b.Filename)
  1607. return true;
  1608. // Determine whether the actual files are equivalent.
  1609. FileManager &FileMgr = Reader.getFileManager();
  1610. auto GetFile = [&](const internal_key_type &Key) -> const FileEntry* {
  1611. if (!Key.Imported) {
  1612. if (auto File = FileMgr.getFile(Key.Filename))
  1613. return *File;
  1614. return nullptr;
  1615. }
  1616. std::string Resolved = std::string(Key.Filename);
  1617. Reader.ResolveImportedPath(M, Resolved);
  1618. if (auto File = FileMgr.getFile(Resolved))
  1619. return *File;
  1620. return nullptr;
  1621. };
  1622. const FileEntry *FEA = GetFile(a);
  1623. const FileEntry *FEB = GetFile(b);
  1624. return FEA && FEA == FEB;
  1625. }
  1626. std::pair<unsigned, unsigned>
  1627. HeaderFileInfoTrait::ReadKeyDataLength(const unsigned char*& d) {
  1628. return readULEBKeyDataLength(d);
  1629. }
  1630. HeaderFileInfoTrait::internal_key_type
  1631. HeaderFileInfoTrait::ReadKey(const unsigned char *d, unsigned) {
  1632. using namespace llvm::support;
  1633. internal_key_type ikey;
  1634. ikey.Size = off_t(endian::readNext<uint64_t, little, unaligned>(d));
  1635. ikey.ModTime = time_t(endian::readNext<uint64_t, little, unaligned>(d));
  1636. ikey.Filename = (const char *)d;
  1637. ikey.Imported = true;
  1638. return ikey;
  1639. }
  1640. HeaderFileInfoTrait::data_type
  1641. HeaderFileInfoTrait::ReadData(internal_key_ref key, const unsigned char *d,
  1642. unsigned DataLen) {
  1643. using namespace llvm::support;
  1644. const unsigned char *End = d + DataLen;
  1645. HeaderFileInfo HFI;
  1646. unsigned Flags = *d++;
  1647. // FIXME: Refactor with mergeHeaderFileInfo in HeaderSearch.cpp.
  1648. HFI.isImport |= (Flags >> 5) & 0x01;
  1649. HFI.isPragmaOnce |= (Flags >> 4) & 0x01;
  1650. HFI.DirInfo = (Flags >> 1) & 0x07;
  1651. HFI.IndexHeaderMapHeader = Flags & 0x01;
  1652. HFI.ControllingMacroID = Reader.getGlobalIdentifierID(
  1653. M, endian::readNext<uint32_t, little, unaligned>(d));
  1654. if (unsigned FrameworkOffset =
  1655. endian::readNext<uint32_t, little, unaligned>(d)) {
  1656. // The framework offset is 1 greater than the actual offset,
  1657. // since 0 is used as an indicator for "no framework name".
  1658. StringRef FrameworkName(FrameworkStrings + FrameworkOffset - 1);
  1659. HFI.Framework = HS->getUniqueFrameworkName(FrameworkName);
  1660. }
  1661. assert((End - d) % 4 == 0 &&
  1662. "Wrong data length in HeaderFileInfo deserialization");
  1663. while (d != End) {
  1664. uint32_t LocalSMID = endian::readNext<uint32_t, little, unaligned>(d);
  1665. auto HeaderRole = static_cast<ModuleMap::ModuleHeaderRole>(LocalSMID & 3);
  1666. LocalSMID >>= 2;
  1667. // This header is part of a module. Associate it with the module to enable
  1668. // implicit module import.
  1669. SubmoduleID GlobalSMID = Reader.getGlobalSubmoduleID(M, LocalSMID);
  1670. Module *Mod = Reader.getSubmodule(GlobalSMID);
  1671. FileManager &FileMgr = Reader.getFileManager();
  1672. ModuleMap &ModMap =
  1673. Reader.getPreprocessor().getHeaderSearchInfo().getModuleMap();
  1674. std::string Filename = std::string(key.Filename);
  1675. if (key.Imported)
  1676. Reader.ResolveImportedPath(M, Filename);
  1677. // FIXME: NameAsWritten
  1678. Module::Header H = {std::string(key.Filename), "",
  1679. *FileMgr.getFile(Filename)};
  1680. ModMap.addHeader(Mod, H, HeaderRole, /*Imported*/true);
  1681. HFI.isModuleHeader |= !(HeaderRole & ModuleMap::TextualHeader);
  1682. }
  1683. // This HeaderFileInfo was externally loaded.
  1684. HFI.External = true;
  1685. HFI.IsValid = true;
  1686. return HFI;
  1687. }
  1688. void ASTReader::addPendingMacro(IdentifierInfo *II, ModuleFile *M,
  1689. uint32_t MacroDirectivesOffset) {
  1690. assert(NumCurrentElementsDeserializing > 0 &&"Missing deserialization guard");
  1691. PendingMacroIDs[II].push_back(PendingMacroInfo(M, MacroDirectivesOffset));
  1692. }
  1693. void ASTReader::ReadDefinedMacros() {
  1694. // Note that we are loading defined macros.
  1695. Deserializing Macros(this);
  1696. for (ModuleFile &I : llvm::reverse(ModuleMgr)) {
  1697. BitstreamCursor &MacroCursor = I.MacroCursor;
  1698. // If there was no preprocessor block, skip this file.
  1699. if (MacroCursor.getBitcodeBytes().empty())
  1700. continue;
  1701. BitstreamCursor Cursor = MacroCursor;
  1702. if (llvm::Error Err = Cursor.JumpToBit(I.MacroStartOffset)) {
  1703. Error(std::move(Err));
  1704. return;
  1705. }
  1706. RecordData Record;
  1707. while (true) {
  1708. Expected<llvm::BitstreamEntry> MaybeE = Cursor.advanceSkippingSubblocks();
  1709. if (!MaybeE) {
  1710. Error(MaybeE.takeError());
  1711. return;
  1712. }
  1713. llvm::BitstreamEntry E = MaybeE.get();
  1714. switch (E.Kind) {
  1715. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  1716. case llvm::BitstreamEntry::Error:
  1717. Error("malformed block record in AST file");
  1718. return;
  1719. case llvm::BitstreamEntry::EndBlock:
  1720. goto NextCursor;
  1721. case llvm::BitstreamEntry::Record: {
  1722. Record.clear();
  1723. Expected<unsigned> MaybeRecord = Cursor.readRecord(E.ID, Record);
  1724. if (!MaybeRecord) {
  1725. Error(MaybeRecord.takeError());
  1726. return;
  1727. }
  1728. switch (MaybeRecord.get()) {
  1729. default: // Default behavior: ignore.
  1730. break;
  1731. case PP_MACRO_OBJECT_LIKE:
  1732. case PP_MACRO_FUNCTION_LIKE: {
  1733. IdentifierInfo *II = getLocalIdentifier(I, Record[0]);
  1734. if (II->isOutOfDate())
  1735. updateOutOfDateIdentifier(*II);
  1736. break;
  1737. }
  1738. case PP_TOKEN:
  1739. // Ignore tokens.
  1740. break;
  1741. }
  1742. break;
  1743. }
  1744. }
  1745. }
  1746. NextCursor: ;
  1747. }
  1748. }
  1749. namespace {
  1750. /// Visitor class used to look up identifirs in an AST file.
  1751. class IdentifierLookupVisitor {
  1752. StringRef Name;
  1753. unsigned NameHash;
  1754. unsigned PriorGeneration;
  1755. unsigned &NumIdentifierLookups;
  1756. unsigned &NumIdentifierLookupHits;
  1757. IdentifierInfo *Found = nullptr;
  1758. public:
  1759. IdentifierLookupVisitor(StringRef Name, unsigned PriorGeneration,
  1760. unsigned &NumIdentifierLookups,
  1761. unsigned &NumIdentifierLookupHits)
  1762. : Name(Name), NameHash(ASTIdentifierLookupTrait::ComputeHash(Name)),
  1763. PriorGeneration(PriorGeneration),
  1764. NumIdentifierLookups(NumIdentifierLookups),
  1765. NumIdentifierLookupHits(NumIdentifierLookupHits) {}
  1766. bool operator()(ModuleFile &M) {
  1767. // If we've already searched this module file, skip it now.
  1768. if (M.Generation <= PriorGeneration)
  1769. return true;
  1770. ASTIdentifierLookupTable *IdTable
  1771. = (ASTIdentifierLookupTable *)M.IdentifierLookupTable;
  1772. if (!IdTable)
  1773. return false;
  1774. ASTIdentifierLookupTrait Trait(IdTable->getInfoObj().getReader(), M,
  1775. Found);
  1776. ++NumIdentifierLookups;
  1777. ASTIdentifierLookupTable::iterator Pos =
  1778. IdTable->find_hashed(Name, NameHash, &Trait);
  1779. if (Pos == IdTable->end())
  1780. return false;
  1781. // Dereferencing the iterator has the effect of building the
  1782. // IdentifierInfo node and populating it with the various
  1783. // declarations it needs.
  1784. ++NumIdentifierLookupHits;
  1785. Found = *Pos;
  1786. return true;
  1787. }
  1788. // Retrieve the identifier info found within the module
  1789. // files.
  1790. IdentifierInfo *getIdentifierInfo() const { return Found; }
  1791. };
  1792. } // namespace
  1793. void ASTReader::updateOutOfDateIdentifier(IdentifierInfo &II) {
  1794. // Note that we are loading an identifier.
  1795. Deserializing AnIdentifier(this);
  1796. unsigned PriorGeneration = 0;
  1797. if (getContext().getLangOpts().Modules)
  1798. PriorGeneration = IdentifierGeneration[&II];
  1799. // If there is a global index, look there first to determine which modules
  1800. // provably do not have any results for this identifier.
  1801. GlobalModuleIndex::HitSet Hits;
  1802. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  1803. if (!loadGlobalIndex()) {
  1804. if (GlobalIndex->lookupIdentifier(II.getName(), Hits)) {
  1805. HitsPtr = &Hits;
  1806. }
  1807. }
  1808. IdentifierLookupVisitor Visitor(II.getName(), PriorGeneration,
  1809. NumIdentifierLookups,
  1810. NumIdentifierLookupHits);
  1811. ModuleMgr.visit(Visitor, HitsPtr);
  1812. markIdentifierUpToDate(&II);
  1813. }
  1814. void ASTReader::markIdentifierUpToDate(IdentifierInfo *II) {
  1815. if (!II)
  1816. return;
  1817. II->setOutOfDate(false);
  1818. // Update the generation for this identifier.
  1819. if (getContext().getLangOpts().Modules)
  1820. IdentifierGeneration[II] = getGeneration();
  1821. }
  1822. void ASTReader::resolvePendingMacro(IdentifierInfo *II,
  1823. const PendingMacroInfo &PMInfo) {
  1824. ModuleFile &M = *PMInfo.M;
  1825. BitstreamCursor &Cursor = M.MacroCursor;
  1826. SavedStreamPosition SavedPosition(Cursor);
  1827. if (llvm::Error Err =
  1828. Cursor.JumpToBit(M.MacroOffsetsBase + PMInfo.MacroDirectivesOffset)) {
  1829. Error(std::move(Err));
  1830. return;
  1831. }
  1832. struct ModuleMacroRecord {
  1833. SubmoduleID SubModID;
  1834. MacroInfo *MI;
  1835. SmallVector<SubmoduleID, 8> Overrides;
  1836. };
  1837. llvm::SmallVector<ModuleMacroRecord, 8> ModuleMacros;
  1838. // We expect to see a sequence of PP_MODULE_MACRO records listing exported
  1839. // macros, followed by a PP_MACRO_DIRECTIVE_HISTORY record with the complete
  1840. // macro histroy.
  1841. RecordData Record;
  1842. while (true) {
  1843. Expected<llvm::BitstreamEntry> MaybeEntry =
  1844. Cursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  1845. if (!MaybeEntry) {
  1846. Error(MaybeEntry.takeError());
  1847. return;
  1848. }
  1849. llvm::BitstreamEntry Entry = MaybeEntry.get();
  1850. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  1851. Error("malformed block record in AST file");
  1852. return;
  1853. }
  1854. Record.clear();
  1855. Expected<unsigned> MaybePP = Cursor.readRecord(Entry.ID, Record);
  1856. if (!MaybePP) {
  1857. Error(MaybePP.takeError());
  1858. return;
  1859. }
  1860. switch ((PreprocessorRecordTypes)MaybePP.get()) {
  1861. case PP_MACRO_DIRECTIVE_HISTORY:
  1862. break;
  1863. case PP_MODULE_MACRO: {
  1864. ModuleMacros.push_back(ModuleMacroRecord());
  1865. auto &Info = ModuleMacros.back();
  1866. Info.SubModID = getGlobalSubmoduleID(M, Record[0]);
  1867. Info.MI = getMacro(getGlobalMacroID(M, Record[1]));
  1868. for (int I = 2, N = Record.size(); I != N; ++I)
  1869. Info.Overrides.push_back(getGlobalSubmoduleID(M, Record[I]));
  1870. continue;
  1871. }
  1872. default:
  1873. Error("malformed block record in AST file");
  1874. return;
  1875. }
  1876. // We found the macro directive history; that's the last record
  1877. // for this macro.
  1878. break;
  1879. }
  1880. // Module macros are listed in reverse dependency order.
  1881. {
  1882. std::reverse(ModuleMacros.begin(), ModuleMacros.end());
  1883. llvm::SmallVector<ModuleMacro*, 8> Overrides;
  1884. for (auto &MMR : ModuleMacros) {
  1885. Overrides.clear();
  1886. for (unsigned ModID : MMR.Overrides) {
  1887. Module *Mod = getSubmodule(ModID);
  1888. auto *Macro = PP.getModuleMacro(Mod, II);
  1889. assert(Macro && "missing definition for overridden macro");
  1890. Overrides.push_back(Macro);
  1891. }
  1892. bool Inserted = false;
  1893. Module *Owner = getSubmodule(MMR.SubModID);
  1894. PP.addModuleMacro(Owner, II, MMR.MI, Overrides, Inserted);
  1895. }
  1896. }
  1897. // Don't read the directive history for a module; we don't have anywhere
  1898. // to put it.
  1899. if (M.isModule())
  1900. return;
  1901. // Deserialize the macro directives history in reverse source-order.
  1902. MacroDirective *Latest = nullptr, *Earliest = nullptr;
  1903. unsigned Idx = 0, N = Record.size();
  1904. while (Idx < N) {
  1905. MacroDirective *MD = nullptr;
  1906. SourceLocation Loc = ReadSourceLocation(M, Record, Idx);
  1907. MacroDirective::Kind K = (MacroDirective::Kind)Record[Idx++];
  1908. switch (K) {
  1909. case MacroDirective::MD_Define: {
  1910. MacroInfo *MI = getMacro(getGlobalMacroID(M, Record[Idx++]));
  1911. MD = PP.AllocateDefMacroDirective(MI, Loc);
  1912. break;
  1913. }
  1914. case MacroDirective::MD_Undefine:
  1915. MD = PP.AllocateUndefMacroDirective(Loc);
  1916. break;
  1917. case MacroDirective::MD_Visibility:
  1918. bool isPublic = Record[Idx++];
  1919. MD = PP.AllocateVisibilityMacroDirective(Loc, isPublic);
  1920. break;
  1921. }
  1922. if (!Latest)
  1923. Latest = MD;
  1924. if (Earliest)
  1925. Earliest->setPrevious(MD);
  1926. Earliest = MD;
  1927. }
  1928. if (Latest)
  1929. PP.setLoadedMacroDirective(II, Earliest, Latest);
  1930. }
  1931. bool ASTReader::shouldDisableValidationForFile(
  1932. const serialization::ModuleFile &M) const {
  1933. if (DisableValidationKind == DisableValidationForModuleKind::None)
  1934. return false;
  1935. // If a PCH is loaded and validation is disabled for PCH then disable
  1936. // validation for the PCH and the modules it loads.
  1937. ModuleKind K = CurrentDeserializingModuleKind.getValueOr(M.Kind);
  1938. switch (K) {
  1939. case MK_MainFile:
  1940. case MK_Preamble:
  1941. case MK_PCH:
  1942. return bool(DisableValidationKind & DisableValidationForModuleKind::PCH);
  1943. case MK_ImplicitModule:
  1944. case MK_ExplicitModule:
  1945. case MK_PrebuiltModule:
  1946. return bool(DisableValidationKind & DisableValidationForModuleKind::Module);
  1947. }
  1948. return false;
  1949. }
  1950. ASTReader::InputFileInfo
  1951. ASTReader::readInputFileInfo(ModuleFile &F, unsigned ID) {
  1952. // Go find this input file.
  1953. BitstreamCursor &Cursor = F.InputFilesCursor;
  1954. SavedStreamPosition SavedPosition(Cursor);
  1955. if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
  1956. // FIXME this drops errors on the floor.
  1957. consumeError(std::move(Err));
  1958. }
  1959. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  1960. if (!MaybeCode) {
  1961. // FIXME this drops errors on the floor.
  1962. consumeError(MaybeCode.takeError());
  1963. }
  1964. unsigned Code = MaybeCode.get();
  1965. RecordData Record;
  1966. StringRef Blob;
  1967. if (Expected<unsigned> Maybe = Cursor.readRecord(Code, Record, &Blob))
  1968. assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE &&
  1969. "invalid record type for input file");
  1970. else {
  1971. // FIXME this drops errors on the floor.
  1972. consumeError(Maybe.takeError());
  1973. }
  1974. assert(Record[0] == ID && "Bogus stored ID or offset");
  1975. InputFileInfo R;
  1976. R.StoredSize = static_cast<off_t>(Record[1]);
  1977. R.StoredTime = static_cast<time_t>(Record[2]);
  1978. R.Overridden = static_cast<bool>(Record[3]);
  1979. R.Transient = static_cast<bool>(Record[4]);
  1980. R.TopLevelModuleMap = static_cast<bool>(Record[5]);
  1981. R.Filename = std::string(Blob);
  1982. ResolveImportedPath(F, R.Filename);
  1983. Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
  1984. if (!MaybeEntry) // FIXME this drops errors on the floor.
  1985. consumeError(MaybeEntry.takeError());
  1986. llvm::BitstreamEntry Entry = MaybeEntry.get();
  1987. assert(Entry.Kind == llvm::BitstreamEntry::Record &&
  1988. "expected record type for input file hash");
  1989. Record.clear();
  1990. if (Expected<unsigned> Maybe = Cursor.readRecord(Entry.ID, Record))
  1991. assert(static_cast<InputFileRecordTypes>(Maybe.get()) == INPUT_FILE_HASH &&
  1992. "invalid record type for input file hash");
  1993. else {
  1994. // FIXME this drops errors on the floor.
  1995. consumeError(Maybe.takeError());
  1996. }
  1997. R.ContentHash = (static_cast<uint64_t>(Record[1]) << 32) |
  1998. static_cast<uint64_t>(Record[0]);
  1999. return R;
  2000. }
  2001. static unsigned moduleKindForDiagnostic(ModuleKind Kind);
  2002. InputFile ASTReader::getInputFile(ModuleFile &F, unsigned ID, bool Complain) {
  2003. // If this ID is bogus, just return an empty input file.
  2004. if (ID == 0 || ID > F.InputFilesLoaded.size())
  2005. return InputFile();
  2006. // If we've already loaded this input file, return it.
  2007. if (F.InputFilesLoaded[ID-1].getFile())
  2008. return F.InputFilesLoaded[ID-1];
  2009. if (F.InputFilesLoaded[ID-1].isNotFound())
  2010. return InputFile();
  2011. // Go find this input file.
  2012. BitstreamCursor &Cursor = F.InputFilesCursor;
  2013. SavedStreamPosition SavedPosition(Cursor);
  2014. if (llvm::Error Err = Cursor.JumpToBit(F.InputFileOffsets[ID - 1])) {
  2015. // FIXME this drops errors on the floor.
  2016. consumeError(std::move(Err));
  2017. }
  2018. InputFileInfo FI = readInputFileInfo(F, ID);
  2019. off_t StoredSize = FI.StoredSize;
  2020. time_t StoredTime = FI.StoredTime;
  2021. bool Overridden = FI.Overridden;
  2022. bool Transient = FI.Transient;
  2023. StringRef Filename = FI.Filename;
  2024. uint64_t StoredContentHash = FI.ContentHash;
  2025. OptionalFileEntryRefDegradesToFileEntryPtr File =
  2026. expectedToOptional(FileMgr.getFileRef(Filename, /*OpenFile=*/false));
  2027. // If we didn't find the file, resolve it relative to the
  2028. // original directory from which this AST file was created.
  2029. if (!File && !F.OriginalDir.empty() && !F.BaseDirectory.empty() &&
  2030. F.OriginalDir != F.BaseDirectory) {
  2031. std::string Resolved = resolveFileRelativeToOriginalDir(
  2032. std::string(Filename), F.OriginalDir, F.BaseDirectory);
  2033. if (!Resolved.empty())
  2034. File = expectedToOptional(FileMgr.getFileRef(Resolved));
  2035. }
  2036. // For an overridden file, create a virtual file with the stored
  2037. // size/timestamp.
  2038. if ((Overridden || Transient) && !File)
  2039. File = FileMgr.getVirtualFileRef(Filename, StoredSize, StoredTime);
  2040. if (!File) {
  2041. if (Complain) {
  2042. std::string ErrorStr = "could not find file '";
  2043. ErrorStr += Filename;
  2044. ErrorStr += "' referenced by AST file '";
  2045. ErrorStr += F.FileName;
  2046. ErrorStr += "'";
  2047. Error(ErrorStr);
  2048. }
  2049. // Record that we didn't find the file.
  2050. F.InputFilesLoaded[ID-1] = InputFile::getNotFound();
  2051. return InputFile();
  2052. }
  2053. // Check if there was a request to override the contents of the file
  2054. // that was part of the precompiled header. Overriding such a file
  2055. // can lead to problems when lexing using the source locations from the
  2056. // PCH.
  2057. SourceManager &SM = getSourceManager();
  2058. // FIXME: Reject if the overrides are different.
  2059. if ((!Overridden && !Transient) && SM.isFileOverridden(File)) {
  2060. if (Complain)
  2061. Error(diag::err_fe_pch_file_overridden, Filename);
  2062. // After emitting the diagnostic, bypass the overriding file to recover
  2063. // (this creates a separate FileEntry).
  2064. File = SM.bypassFileContentsOverride(*File);
  2065. if (!File) {
  2066. F.InputFilesLoaded[ID - 1] = InputFile::getNotFound();
  2067. return InputFile();
  2068. }
  2069. }
  2070. struct Change {
  2071. enum ModificationKind {
  2072. Size,
  2073. ModTime,
  2074. Content,
  2075. None,
  2076. } Kind;
  2077. llvm::Optional<int64_t> Old = llvm::None;
  2078. llvm::Optional<int64_t> New = llvm::None;
  2079. };
  2080. auto HasInputFileChanged = [&]() {
  2081. if (StoredSize != File->getSize())
  2082. return Change{Change::Size, StoredSize, File->getSize()};
  2083. if (!shouldDisableValidationForFile(F) && StoredTime &&
  2084. StoredTime != File->getModificationTime()) {
  2085. Change MTimeChange = {Change::ModTime, StoredTime,
  2086. File->getModificationTime()};
  2087. // In case the modification time changes but not the content,
  2088. // accept the cached file as legit.
  2089. if (ValidateASTInputFilesContent &&
  2090. StoredContentHash != static_cast<uint64_t>(llvm::hash_code(-1))) {
  2091. auto MemBuffOrError = FileMgr.getBufferForFile(File);
  2092. if (!MemBuffOrError) {
  2093. if (!Complain)
  2094. return MTimeChange;
  2095. std::string ErrorStr = "could not get buffer for file '";
  2096. ErrorStr += File->getName();
  2097. ErrorStr += "'";
  2098. Error(ErrorStr);
  2099. return MTimeChange;
  2100. }
  2101. // FIXME: hash_value is not guaranteed to be stable!
  2102. auto ContentHash = hash_value(MemBuffOrError.get()->getBuffer());
  2103. if (StoredContentHash == static_cast<uint64_t>(ContentHash))
  2104. return Change{Change::None};
  2105. return Change{Change::Content};
  2106. }
  2107. return MTimeChange;
  2108. }
  2109. return Change{Change::None};
  2110. };
  2111. bool IsOutOfDate = false;
  2112. auto FileChange = HasInputFileChanged();
  2113. // For an overridden file, there is nothing to validate.
  2114. if (!Overridden && FileChange.Kind != Change::None) {
  2115. if (Complain && !Diags.isDiagnosticInFlight()) {
  2116. // Build a list of the PCH imports that got us here (in reverse).
  2117. SmallVector<ModuleFile *, 4> ImportStack(1, &F);
  2118. while (!ImportStack.back()->ImportedBy.empty())
  2119. ImportStack.push_back(ImportStack.back()->ImportedBy[0]);
  2120. // The top-level PCH is stale.
  2121. StringRef TopLevelPCHName(ImportStack.back()->FileName);
  2122. Diag(diag::err_fe_ast_file_modified)
  2123. << Filename << moduleKindForDiagnostic(ImportStack.back()->Kind)
  2124. << TopLevelPCHName << FileChange.Kind
  2125. << (FileChange.Old && FileChange.New)
  2126. << llvm::itostr(FileChange.Old.getValueOr(0))
  2127. << llvm::itostr(FileChange.New.getValueOr(0));
  2128. // Print the import stack.
  2129. if (ImportStack.size() > 1) {
  2130. Diag(diag::note_pch_required_by)
  2131. << Filename << ImportStack[0]->FileName;
  2132. for (unsigned I = 1; I < ImportStack.size(); ++I)
  2133. Diag(diag::note_pch_required_by)
  2134. << ImportStack[I-1]->FileName << ImportStack[I]->FileName;
  2135. }
  2136. Diag(diag::note_pch_rebuild_required) << TopLevelPCHName;
  2137. }
  2138. IsOutOfDate = true;
  2139. }
  2140. // FIXME: If the file is overridden and we've already opened it,
  2141. // issue an error (or split it into a separate FileEntry).
  2142. InputFile IF = InputFile(*File, Overridden || Transient, IsOutOfDate);
  2143. // Note that we've loaded this input file.
  2144. F.InputFilesLoaded[ID-1] = IF;
  2145. return IF;
  2146. }
  2147. /// If we are loading a relocatable PCH or module file, and the filename
  2148. /// is not an absolute path, add the system or module root to the beginning of
  2149. /// the file name.
  2150. void ASTReader::ResolveImportedPath(ModuleFile &M, std::string &Filename) {
  2151. // Resolve relative to the base directory, if we have one.
  2152. if (!M.BaseDirectory.empty())
  2153. return ResolveImportedPath(Filename, M.BaseDirectory);
  2154. }
  2155. void ASTReader::ResolveImportedPath(std::string &Filename, StringRef Prefix) {
  2156. if (Filename.empty() || llvm::sys::path::is_absolute(Filename))
  2157. return;
  2158. SmallString<128> Buffer;
  2159. llvm::sys::path::append(Buffer, Prefix, Filename);
  2160. Filename.assign(Buffer.begin(), Buffer.end());
  2161. }
  2162. static bool isDiagnosedResult(ASTReader::ASTReadResult ARR, unsigned Caps) {
  2163. switch (ARR) {
  2164. case ASTReader::Failure: return true;
  2165. case ASTReader::Missing: return !(Caps & ASTReader::ARR_Missing);
  2166. case ASTReader::OutOfDate: return !(Caps & ASTReader::ARR_OutOfDate);
  2167. case ASTReader::VersionMismatch: return !(Caps & ASTReader::ARR_VersionMismatch);
  2168. case ASTReader::ConfigurationMismatch:
  2169. return !(Caps & ASTReader::ARR_ConfigurationMismatch);
  2170. case ASTReader::HadErrors: return true;
  2171. case ASTReader::Success: return false;
  2172. }
  2173. llvm_unreachable("unknown ASTReadResult");
  2174. }
  2175. ASTReader::ASTReadResult ASTReader::ReadOptionsBlock(
  2176. BitstreamCursor &Stream, unsigned ClientLoadCapabilities,
  2177. bool AllowCompatibleConfigurationMismatch, ASTReaderListener &Listener,
  2178. std::string &SuggestedPredefines) {
  2179. if (llvm::Error Err = Stream.EnterSubBlock(OPTIONS_BLOCK_ID)) {
  2180. // FIXME this drops errors on the floor.
  2181. consumeError(std::move(Err));
  2182. return Failure;
  2183. }
  2184. // Read all of the records in the options block.
  2185. RecordData Record;
  2186. ASTReadResult Result = Success;
  2187. while (true) {
  2188. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  2189. if (!MaybeEntry) {
  2190. // FIXME this drops errors on the floor.
  2191. consumeError(MaybeEntry.takeError());
  2192. return Failure;
  2193. }
  2194. llvm::BitstreamEntry Entry = MaybeEntry.get();
  2195. switch (Entry.Kind) {
  2196. case llvm::BitstreamEntry::Error:
  2197. case llvm::BitstreamEntry::SubBlock:
  2198. return Failure;
  2199. case llvm::BitstreamEntry::EndBlock:
  2200. return Result;
  2201. case llvm::BitstreamEntry::Record:
  2202. // The interesting case.
  2203. break;
  2204. }
  2205. // Read and process a record.
  2206. Record.clear();
  2207. Expected<unsigned> MaybeRecordType = Stream.readRecord(Entry.ID, Record);
  2208. if (!MaybeRecordType) {
  2209. // FIXME this drops errors on the floor.
  2210. consumeError(MaybeRecordType.takeError());
  2211. return Failure;
  2212. }
  2213. switch ((OptionsRecordTypes)MaybeRecordType.get()) {
  2214. case LANGUAGE_OPTIONS: {
  2215. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2216. if (ParseLanguageOptions(Record, Complain, Listener,
  2217. AllowCompatibleConfigurationMismatch))
  2218. Result = ConfigurationMismatch;
  2219. break;
  2220. }
  2221. case TARGET_OPTIONS: {
  2222. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2223. if (ParseTargetOptions(Record, Complain, Listener,
  2224. AllowCompatibleConfigurationMismatch))
  2225. Result = ConfigurationMismatch;
  2226. break;
  2227. }
  2228. case FILE_SYSTEM_OPTIONS: {
  2229. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2230. if (!AllowCompatibleConfigurationMismatch &&
  2231. ParseFileSystemOptions(Record, Complain, Listener))
  2232. Result = ConfigurationMismatch;
  2233. break;
  2234. }
  2235. case HEADER_SEARCH_OPTIONS: {
  2236. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2237. if (!AllowCompatibleConfigurationMismatch &&
  2238. ParseHeaderSearchOptions(Record, Complain, Listener))
  2239. Result = ConfigurationMismatch;
  2240. break;
  2241. }
  2242. case PREPROCESSOR_OPTIONS:
  2243. bool Complain = (ClientLoadCapabilities & ARR_ConfigurationMismatch) == 0;
  2244. if (!AllowCompatibleConfigurationMismatch &&
  2245. ParsePreprocessorOptions(Record, Complain, Listener,
  2246. SuggestedPredefines))
  2247. Result = ConfigurationMismatch;
  2248. break;
  2249. }
  2250. }
  2251. }
  2252. ASTReader::ASTReadResult
  2253. ASTReader::ReadControlBlock(ModuleFile &F,
  2254. SmallVectorImpl<ImportedModule> &Loaded,
  2255. const ModuleFile *ImportedBy,
  2256. unsigned ClientLoadCapabilities) {
  2257. BitstreamCursor &Stream = F.Stream;
  2258. if (llvm::Error Err = Stream.EnterSubBlock(CONTROL_BLOCK_ID)) {
  2259. Error(std::move(Err));
  2260. return Failure;
  2261. }
  2262. // Lambda to read the unhashed control block the first time it's called.
  2263. //
  2264. // For PCM files, the unhashed control block cannot be read until after the
  2265. // MODULE_NAME record. However, PCH files have no MODULE_NAME, and yet still
  2266. // need to look ahead before reading the IMPORTS record. For consistency,
  2267. // this block is always read somehow (see BitstreamEntry::EndBlock).
  2268. bool HasReadUnhashedControlBlock = false;
  2269. auto readUnhashedControlBlockOnce = [&]() {
  2270. if (!HasReadUnhashedControlBlock) {
  2271. HasReadUnhashedControlBlock = true;
  2272. if (ASTReadResult Result =
  2273. readUnhashedControlBlock(F, ImportedBy, ClientLoadCapabilities))
  2274. return Result;
  2275. }
  2276. return Success;
  2277. };
  2278. bool DisableValidation = shouldDisableValidationForFile(F);
  2279. // Read all of the records and blocks in the control block.
  2280. RecordData Record;
  2281. unsigned NumInputs = 0;
  2282. unsigned NumUserInputs = 0;
  2283. StringRef BaseDirectoryAsWritten;
  2284. while (true) {
  2285. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  2286. if (!MaybeEntry) {
  2287. Error(MaybeEntry.takeError());
  2288. return Failure;
  2289. }
  2290. llvm::BitstreamEntry Entry = MaybeEntry.get();
  2291. switch (Entry.Kind) {
  2292. case llvm::BitstreamEntry::Error:
  2293. Error("malformed block record in AST file");
  2294. return Failure;
  2295. case llvm::BitstreamEntry::EndBlock: {
  2296. // Validate the module before returning. This call catches an AST with
  2297. // no module name and no imports.
  2298. if (ASTReadResult Result = readUnhashedControlBlockOnce())
  2299. return Result;
  2300. // Validate input files.
  2301. const HeaderSearchOptions &HSOpts =
  2302. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  2303. // All user input files reside at the index range [0, NumUserInputs), and
  2304. // system input files reside at [NumUserInputs, NumInputs). For explicitly
  2305. // loaded module files, ignore missing inputs.
  2306. if (!DisableValidation && F.Kind != MK_ExplicitModule &&
  2307. F.Kind != MK_PrebuiltModule) {
  2308. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
  2309. // If we are reading a module, we will create a verification timestamp,
  2310. // so we verify all input files. Otherwise, verify only user input
  2311. // files.
  2312. unsigned N = NumUserInputs;
  2313. if (ValidateSystemInputs ||
  2314. (HSOpts.ModulesValidateOncePerBuildSession &&
  2315. F.InputFilesValidationTimestamp <= HSOpts.BuildSessionTimestamp &&
  2316. F.Kind == MK_ImplicitModule))
  2317. N = NumInputs;
  2318. for (unsigned I = 0; I < N; ++I) {
  2319. InputFile IF = getInputFile(F, I+1, Complain);
  2320. if (!IF.getFile() || IF.isOutOfDate())
  2321. return OutOfDate;
  2322. }
  2323. }
  2324. if (Listener)
  2325. Listener->visitModuleFile(F.FileName, F.Kind);
  2326. if (Listener && Listener->needsInputFileVisitation()) {
  2327. unsigned N = Listener->needsSystemInputFileVisitation() ? NumInputs
  2328. : NumUserInputs;
  2329. for (unsigned I = 0; I < N; ++I) {
  2330. bool IsSystem = I >= NumUserInputs;
  2331. InputFileInfo FI = readInputFileInfo(F, I+1);
  2332. Listener->visitInputFile(FI.Filename, IsSystem, FI.Overridden,
  2333. F.Kind == MK_ExplicitModule ||
  2334. F.Kind == MK_PrebuiltModule);
  2335. }
  2336. }
  2337. return Success;
  2338. }
  2339. case llvm::BitstreamEntry::SubBlock:
  2340. switch (Entry.ID) {
  2341. case INPUT_FILES_BLOCK_ID:
  2342. F.InputFilesCursor = Stream;
  2343. if (llvm::Error Err = Stream.SkipBlock()) {
  2344. Error(std::move(Err));
  2345. return Failure;
  2346. }
  2347. if (ReadBlockAbbrevs(F.InputFilesCursor, INPUT_FILES_BLOCK_ID)) {
  2348. Error("malformed block record in AST file");
  2349. return Failure;
  2350. }
  2351. continue;
  2352. case OPTIONS_BLOCK_ID:
  2353. // If we're reading the first module for this group, check its options
  2354. // are compatible with ours. For modules it imports, no further checking
  2355. // is required, because we checked them when we built it.
  2356. if (Listener && !ImportedBy) {
  2357. // Should we allow the configuration of the module file to differ from
  2358. // the configuration of the current translation unit in a compatible
  2359. // way?
  2360. //
  2361. // FIXME: Allow this for files explicitly specified with -include-pch.
  2362. bool AllowCompatibleConfigurationMismatch =
  2363. F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
  2364. ASTReadResult Result =
  2365. ReadOptionsBlock(Stream, ClientLoadCapabilities,
  2366. AllowCompatibleConfigurationMismatch, *Listener,
  2367. SuggestedPredefines);
  2368. if (Result == Failure) {
  2369. Error("malformed block record in AST file");
  2370. return Result;
  2371. }
  2372. if (DisableValidation ||
  2373. (AllowConfigurationMismatch && Result == ConfigurationMismatch))
  2374. Result = Success;
  2375. // If we can't load the module, exit early since we likely
  2376. // will rebuild the module anyway. The stream may be in the
  2377. // middle of a block.
  2378. if (Result != Success)
  2379. return Result;
  2380. } else if (llvm::Error Err = Stream.SkipBlock()) {
  2381. Error(std::move(Err));
  2382. return Failure;
  2383. }
  2384. continue;
  2385. default:
  2386. if (llvm::Error Err = Stream.SkipBlock()) {
  2387. Error(std::move(Err));
  2388. return Failure;
  2389. }
  2390. continue;
  2391. }
  2392. case llvm::BitstreamEntry::Record:
  2393. // The interesting case.
  2394. break;
  2395. }
  2396. // Read and process a record.
  2397. Record.clear();
  2398. StringRef Blob;
  2399. Expected<unsigned> MaybeRecordType =
  2400. Stream.readRecord(Entry.ID, Record, &Blob);
  2401. if (!MaybeRecordType) {
  2402. Error(MaybeRecordType.takeError());
  2403. return Failure;
  2404. }
  2405. switch ((ControlRecordTypes)MaybeRecordType.get()) {
  2406. case METADATA: {
  2407. if (Record[0] != VERSION_MAJOR && !DisableValidation) {
  2408. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  2409. Diag(Record[0] < VERSION_MAJOR? diag::err_pch_version_too_old
  2410. : diag::err_pch_version_too_new);
  2411. return VersionMismatch;
  2412. }
  2413. bool hasErrors = Record[6];
  2414. if (hasErrors && !DisableValidation) {
  2415. // If requested by the caller and the module hasn't already been read
  2416. // or compiled, mark modules on error as out-of-date.
  2417. if ((ClientLoadCapabilities & ARR_TreatModuleWithErrorsAsOutOfDate) &&
  2418. canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  2419. return OutOfDate;
  2420. if (!AllowASTWithCompilerErrors) {
  2421. Diag(diag::err_pch_with_compiler_errors);
  2422. return HadErrors;
  2423. }
  2424. }
  2425. if (hasErrors) {
  2426. Diags.ErrorOccurred = true;
  2427. Diags.UncompilableErrorOccurred = true;
  2428. Diags.UnrecoverableErrorOccurred = true;
  2429. }
  2430. F.RelocatablePCH = Record[4];
  2431. // Relative paths in a relocatable PCH are relative to our sysroot.
  2432. if (F.RelocatablePCH)
  2433. F.BaseDirectory = isysroot.empty() ? "/" : isysroot;
  2434. F.HasTimestamps = Record[5];
  2435. const std::string &CurBranch = getClangFullRepositoryVersion();
  2436. StringRef ASTBranch = Blob;
  2437. if (StringRef(CurBranch) != ASTBranch && !DisableValidation) {
  2438. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  2439. Diag(diag::err_pch_different_branch) << ASTBranch << CurBranch;
  2440. return VersionMismatch;
  2441. }
  2442. break;
  2443. }
  2444. case IMPORTS: {
  2445. // Validate the AST before processing any imports (otherwise, untangling
  2446. // them can be error-prone and expensive). A module will have a name and
  2447. // will already have been validated, but this catches the PCH case.
  2448. if (ASTReadResult Result = readUnhashedControlBlockOnce())
  2449. return Result;
  2450. // Load each of the imported PCH files.
  2451. unsigned Idx = 0, N = Record.size();
  2452. while (Idx < N) {
  2453. // Read information about the AST file.
  2454. ModuleKind ImportedKind = (ModuleKind)Record[Idx++];
  2455. // The import location will be the local one for now; we will adjust
  2456. // all import locations of module imports after the global source
  2457. // location info are setup, in ReadAST.
  2458. SourceLocation ImportLoc =
  2459. ReadUntranslatedSourceLocation(Record[Idx++]);
  2460. off_t StoredSize = (off_t)Record[Idx++];
  2461. time_t StoredModTime = (time_t)Record[Idx++];
  2462. auto FirstSignatureByte = Record.begin() + Idx;
  2463. ASTFileSignature StoredSignature = ASTFileSignature::create(
  2464. FirstSignatureByte, FirstSignatureByte + ASTFileSignature::size);
  2465. Idx += ASTFileSignature::size;
  2466. std::string ImportedName = ReadString(Record, Idx);
  2467. std::string ImportedFile;
  2468. // For prebuilt and explicit modules first consult the file map for
  2469. // an override. Note that here we don't search prebuilt module
  2470. // directories, only the explicit name to file mappings. Also, we will
  2471. // still verify the size/signature making sure it is essentially the
  2472. // same file but perhaps in a different location.
  2473. if (ImportedKind == MK_PrebuiltModule || ImportedKind == MK_ExplicitModule)
  2474. ImportedFile = PP.getHeaderSearchInfo().getPrebuiltModuleFileName(
  2475. ImportedName, /*FileMapOnly*/ true);
  2476. if (ImportedFile.empty())
  2477. // Use BaseDirectoryAsWritten to ensure we use the same path in the
  2478. // ModuleCache as when writing.
  2479. ImportedFile = ReadPath(BaseDirectoryAsWritten, Record, Idx);
  2480. else
  2481. SkipPath(Record, Idx);
  2482. // If our client can't cope with us being out of date, we can't cope with
  2483. // our dependency being missing.
  2484. unsigned Capabilities = ClientLoadCapabilities;
  2485. if ((ClientLoadCapabilities & ARR_OutOfDate) == 0)
  2486. Capabilities &= ~ARR_Missing;
  2487. // Load the AST file.
  2488. auto Result = ReadASTCore(ImportedFile, ImportedKind, ImportLoc, &F,
  2489. Loaded, StoredSize, StoredModTime,
  2490. StoredSignature, Capabilities);
  2491. // If we diagnosed a problem, produce a backtrace.
  2492. bool recompilingFinalized =
  2493. Result == OutOfDate && (Capabilities & ARR_OutOfDate) &&
  2494. getModuleManager().getModuleCache().isPCMFinal(F.FileName);
  2495. if (isDiagnosedResult(Result, Capabilities) || recompilingFinalized)
  2496. Diag(diag::note_module_file_imported_by)
  2497. << F.FileName << !F.ModuleName.empty() << F.ModuleName;
  2498. if (recompilingFinalized)
  2499. Diag(diag::note_module_file_conflict);
  2500. switch (Result) {
  2501. case Failure: return Failure;
  2502. // If we have to ignore the dependency, we'll have to ignore this too.
  2503. case Missing:
  2504. case OutOfDate: return OutOfDate;
  2505. case VersionMismatch: return VersionMismatch;
  2506. case ConfigurationMismatch: return ConfigurationMismatch;
  2507. case HadErrors: return HadErrors;
  2508. case Success: break;
  2509. }
  2510. }
  2511. break;
  2512. }
  2513. case ORIGINAL_FILE:
  2514. F.OriginalSourceFileID = FileID::get(Record[0]);
  2515. F.ActualOriginalSourceFileName = std::string(Blob);
  2516. F.OriginalSourceFileName = F.ActualOriginalSourceFileName;
  2517. ResolveImportedPath(F, F.OriginalSourceFileName);
  2518. break;
  2519. case ORIGINAL_FILE_ID:
  2520. F.OriginalSourceFileID = FileID::get(Record[0]);
  2521. break;
  2522. case ORIGINAL_PCH_DIR:
  2523. F.OriginalDir = std::string(Blob);
  2524. break;
  2525. case MODULE_NAME:
  2526. F.ModuleName = std::string(Blob);
  2527. Diag(diag::remark_module_import)
  2528. << F.ModuleName << F.FileName << (ImportedBy ? true : false)
  2529. << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
  2530. if (Listener)
  2531. Listener->ReadModuleName(F.ModuleName);
  2532. // Validate the AST as soon as we have a name so we can exit early on
  2533. // failure.
  2534. if (ASTReadResult Result = readUnhashedControlBlockOnce())
  2535. return Result;
  2536. break;
  2537. case MODULE_DIRECTORY: {
  2538. // Save the BaseDirectory as written in the PCM for computing the module
  2539. // filename for the ModuleCache.
  2540. BaseDirectoryAsWritten = Blob;
  2541. assert(!F.ModuleName.empty() &&
  2542. "MODULE_DIRECTORY found before MODULE_NAME");
  2543. // If we've already loaded a module map file covering this module, we may
  2544. // have a better path for it (relative to the current build).
  2545. Module *M = PP.getHeaderSearchInfo().lookupModule(
  2546. F.ModuleName, SourceLocation(), /*AllowSearch*/ true,
  2547. /*AllowExtraModuleMapSearch*/ true);
  2548. if (M && M->Directory) {
  2549. // If we're implicitly loading a module, the base directory can't
  2550. // change between the build and use.
  2551. // Don't emit module relocation error if we have -fno-validate-pch
  2552. if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
  2553. DisableValidationForModuleKind::Module) &&
  2554. F.Kind != MK_ExplicitModule && F.Kind != MK_PrebuiltModule) {
  2555. auto BuildDir = PP.getFileManager().getDirectory(Blob);
  2556. if (!BuildDir || *BuildDir != M->Directory) {
  2557. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  2558. Diag(diag::err_imported_module_relocated)
  2559. << F.ModuleName << Blob << M->Directory->getName();
  2560. return OutOfDate;
  2561. }
  2562. }
  2563. F.BaseDirectory = std::string(M->Directory->getName());
  2564. } else {
  2565. F.BaseDirectory = std::string(Blob);
  2566. }
  2567. break;
  2568. }
  2569. case MODULE_MAP_FILE:
  2570. if (ASTReadResult Result =
  2571. ReadModuleMapFileBlock(Record, F, ImportedBy, ClientLoadCapabilities))
  2572. return Result;
  2573. break;
  2574. case INPUT_FILE_OFFSETS:
  2575. NumInputs = Record[0];
  2576. NumUserInputs = Record[1];
  2577. F.InputFileOffsets =
  2578. (const llvm::support::unaligned_uint64_t *)Blob.data();
  2579. F.InputFilesLoaded.resize(NumInputs);
  2580. F.NumUserInputFiles = NumUserInputs;
  2581. break;
  2582. }
  2583. }
  2584. }
  2585. void ASTReader::readIncludedFiles(ModuleFile &F, StringRef Blob,
  2586. Preprocessor &PP) {
  2587. using namespace llvm::support;
  2588. const unsigned char *D = (const unsigned char *)Blob.data();
  2589. unsigned FileCount = endian::readNext<uint32_t, little, unaligned>(D);
  2590. for (unsigned I = 0; I < FileCount; ++I) {
  2591. size_t ID = endian::readNext<uint32_t, little, unaligned>(D);
  2592. InputFileInfo IFI = readInputFileInfo(F, ID);
  2593. if (llvm::ErrorOr<const FileEntry *> File =
  2594. PP.getFileManager().getFile(IFI.Filename))
  2595. PP.getIncludedFiles().insert(*File);
  2596. }
  2597. }
  2598. llvm::Error ASTReader::ReadASTBlock(ModuleFile &F,
  2599. unsigned ClientLoadCapabilities) {
  2600. BitstreamCursor &Stream = F.Stream;
  2601. if (llvm::Error Err = Stream.EnterSubBlock(AST_BLOCK_ID))
  2602. return Err;
  2603. F.ASTBlockStartOffset = Stream.GetCurrentBitNo();
  2604. // Read all of the records and blocks for the AST file.
  2605. RecordData Record;
  2606. while (true) {
  2607. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  2608. if (!MaybeEntry)
  2609. return MaybeEntry.takeError();
  2610. llvm::BitstreamEntry Entry = MaybeEntry.get();
  2611. switch (Entry.Kind) {
  2612. case llvm::BitstreamEntry::Error:
  2613. return llvm::createStringError(
  2614. std::errc::illegal_byte_sequence,
  2615. "error at end of module block in AST file");
  2616. case llvm::BitstreamEntry::EndBlock:
  2617. // Outside of C++, we do not store a lookup map for the translation unit.
  2618. // Instead, mark it as needing a lookup map to be built if this module
  2619. // contains any declarations lexically within it (which it always does!).
  2620. // This usually has no cost, since we very rarely need the lookup map for
  2621. // the translation unit outside C++.
  2622. if (ASTContext *Ctx = ContextObj) {
  2623. DeclContext *DC = Ctx->getTranslationUnitDecl();
  2624. if (DC->hasExternalLexicalStorage() && !Ctx->getLangOpts().CPlusPlus)
  2625. DC->setMustBuildLookupTable();
  2626. }
  2627. return llvm::Error::success();
  2628. case llvm::BitstreamEntry::SubBlock:
  2629. switch (Entry.ID) {
  2630. case DECLTYPES_BLOCK_ID:
  2631. // We lazily load the decls block, but we want to set up the
  2632. // DeclsCursor cursor to point into it. Clone our current bitcode
  2633. // cursor to it, enter the block and read the abbrevs in that block.
  2634. // With the main cursor, we just skip over it.
  2635. F.DeclsCursor = Stream;
  2636. if (llvm::Error Err = Stream.SkipBlock())
  2637. return Err;
  2638. if (llvm::Error Err = ReadBlockAbbrevs(
  2639. F.DeclsCursor, DECLTYPES_BLOCK_ID, &F.DeclsBlockStartOffset))
  2640. return Err;
  2641. break;
  2642. case PREPROCESSOR_BLOCK_ID:
  2643. F.MacroCursor = Stream;
  2644. if (!PP.getExternalSource())
  2645. PP.setExternalSource(this);
  2646. if (llvm::Error Err = Stream.SkipBlock())
  2647. return Err;
  2648. if (llvm::Error Err =
  2649. ReadBlockAbbrevs(F.MacroCursor, PREPROCESSOR_BLOCK_ID))
  2650. return Err;
  2651. F.MacroStartOffset = F.MacroCursor.GetCurrentBitNo();
  2652. break;
  2653. case PREPROCESSOR_DETAIL_BLOCK_ID:
  2654. F.PreprocessorDetailCursor = Stream;
  2655. if (llvm::Error Err = Stream.SkipBlock()) {
  2656. return Err;
  2657. }
  2658. if (llvm::Error Err = ReadBlockAbbrevs(F.PreprocessorDetailCursor,
  2659. PREPROCESSOR_DETAIL_BLOCK_ID))
  2660. return Err;
  2661. F.PreprocessorDetailStartOffset
  2662. = F.PreprocessorDetailCursor.GetCurrentBitNo();
  2663. if (!PP.getPreprocessingRecord())
  2664. PP.createPreprocessingRecord();
  2665. if (!PP.getPreprocessingRecord()->getExternalSource())
  2666. PP.getPreprocessingRecord()->SetExternalSource(*this);
  2667. break;
  2668. case SOURCE_MANAGER_BLOCK_ID:
  2669. if (llvm::Error Err = ReadSourceManagerBlock(F))
  2670. return Err;
  2671. break;
  2672. case SUBMODULE_BLOCK_ID:
  2673. if (llvm::Error Err = ReadSubmoduleBlock(F, ClientLoadCapabilities))
  2674. return Err;
  2675. break;
  2676. case COMMENTS_BLOCK_ID: {
  2677. BitstreamCursor C = Stream;
  2678. if (llvm::Error Err = Stream.SkipBlock())
  2679. return Err;
  2680. if (llvm::Error Err = ReadBlockAbbrevs(C, COMMENTS_BLOCK_ID))
  2681. return Err;
  2682. CommentsCursors.push_back(std::make_pair(C, &F));
  2683. break;
  2684. }
  2685. default:
  2686. if (llvm::Error Err = Stream.SkipBlock())
  2687. return Err;
  2688. break;
  2689. }
  2690. continue;
  2691. case llvm::BitstreamEntry::Record:
  2692. // The interesting case.
  2693. break;
  2694. }
  2695. // Read and process a record.
  2696. Record.clear();
  2697. StringRef Blob;
  2698. Expected<unsigned> MaybeRecordType =
  2699. Stream.readRecord(Entry.ID, Record, &Blob);
  2700. if (!MaybeRecordType)
  2701. return MaybeRecordType.takeError();
  2702. ASTRecordTypes RecordType = (ASTRecordTypes)MaybeRecordType.get();
  2703. // If we're not loading an AST context, we don't care about most records.
  2704. if (!ContextObj) {
  2705. switch (RecordType) {
  2706. case IDENTIFIER_TABLE:
  2707. case IDENTIFIER_OFFSET:
  2708. case INTERESTING_IDENTIFIERS:
  2709. case STATISTICS:
  2710. case PP_CONDITIONAL_STACK:
  2711. case PP_COUNTER_VALUE:
  2712. case SOURCE_LOCATION_OFFSETS:
  2713. case MODULE_OFFSET_MAP:
  2714. case SOURCE_MANAGER_LINE_TABLE:
  2715. case SOURCE_LOCATION_PRELOADS:
  2716. case PPD_ENTITIES_OFFSETS:
  2717. case HEADER_SEARCH_TABLE:
  2718. case IMPORTED_MODULES:
  2719. case MACRO_OFFSET:
  2720. break;
  2721. default:
  2722. continue;
  2723. }
  2724. }
  2725. switch (RecordType) {
  2726. default: // Default behavior: ignore.
  2727. break;
  2728. case TYPE_OFFSET: {
  2729. if (F.LocalNumTypes != 0)
  2730. return llvm::createStringError(
  2731. std::errc::illegal_byte_sequence,
  2732. "duplicate TYPE_OFFSET record in AST file");
  2733. F.TypeOffsets = reinterpret_cast<const UnderalignedInt64 *>(Blob.data());
  2734. F.LocalNumTypes = Record[0];
  2735. unsigned LocalBaseTypeIndex = Record[1];
  2736. F.BaseTypeIndex = getTotalNumTypes();
  2737. if (F.LocalNumTypes > 0) {
  2738. // Introduce the global -> local mapping for types within this module.
  2739. GlobalTypeMap.insert(std::make_pair(getTotalNumTypes(), &F));
  2740. // Introduce the local -> global mapping for types within this module.
  2741. F.TypeRemap.insertOrReplace(
  2742. std::make_pair(LocalBaseTypeIndex,
  2743. F.BaseTypeIndex - LocalBaseTypeIndex));
  2744. TypesLoaded.resize(TypesLoaded.size() + F.LocalNumTypes);
  2745. }
  2746. break;
  2747. }
  2748. case DECL_OFFSET: {
  2749. if (F.LocalNumDecls != 0)
  2750. return llvm::createStringError(
  2751. std::errc::illegal_byte_sequence,
  2752. "duplicate DECL_OFFSET record in AST file");
  2753. F.DeclOffsets = (const DeclOffset *)Blob.data();
  2754. F.LocalNumDecls = Record[0];
  2755. unsigned LocalBaseDeclID = Record[1];
  2756. F.BaseDeclID = getTotalNumDecls();
  2757. if (F.LocalNumDecls > 0) {
  2758. // Introduce the global -> local mapping for declarations within this
  2759. // module.
  2760. GlobalDeclMap.insert(
  2761. std::make_pair(getTotalNumDecls() + NUM_PREDEF_DECL_IDS, &F));
  2762. // Introduce the local -> global mapping for declarations within this
  2763. // module.
  2764. F.DeclRemap.insertOrReplace(
  2765. std::make_pair(LocalBaseDeclID, F.BaseDeclID - LocalBaseDeclID));
  2766. // Introduce the global -> local mapping for declarations within this
  2767. // module.
  2768. F.GlobalToLocalDeclIDs[&F] = LocalBaseDeclID;
  2769. DeclsLoaded.resize(DeclsLoaded.size() + F.LocalNumDecls);
  2770. }
  2771. break;
  2772. }
  2773. case TU_UPDATE_LEXICAL: {
  2774. DeclContext *TU = ContextObj->getTranslationUnitDecl();
  2775. LexicalContents Contents(
  2776. reinterpret_cast<const llvm::support::unaligned_uint32_t *>(
  2777. Blob.data()),
  2778. static_cast<unsigned int>(Blob.size() / 4));
  2779. TULexicalDecls.push_back(std::make_pair(&F, Contents));
  2780. TU->setHasExternalLexicalStorage(true);
  2781. break;
  2782. }
  2783. case UPDATE_VISIBLE: {
  2784. unsigned Idx = 0;
  2785. serialization::DeclID ID = ReadDeclID(F, Record, Idx);
  2786. auto *Data = (const unsigned char*)Blob.data();
  2787. PendingVisibleUpdates[ID].push_back(PendingVisibleUpdate{&F, Data});
  2788. // If we've already loaded the decl, perform the updates when we finish
  2789. // loading this block.
  2790. if (Decl *D = GetExistingDecl(ID))
  2791. PendingUpdateRecords.push_back(
  2792. PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
  2793. break;
  2794. }
  2795. case IDENTIFIER_TABLE:
  2796. F.IdentifierTableData =
  2797. reinterpret_cast<const unsigned char *>(Blob.data());
  2798. if (Record[0]) {
  2799. F.IdentifierLookupTable = ASTIdentifierLookupTable::Create(
  2800. F.IdentifierTableData + Record[0],
  2801. F.IdentifierTableData + sizeof(uint32_t),
  2802. F.IdentifierTableData,
  2803. ASTIdentifierLookupTrait(*this, F));
  2804. PP.getIdentifierTable().setExternalIdentifierLookup(this);
  2805. }
  2806. break;
  2807. case IDENTIFIER_OFFSET: {
  2808. if (F.LocalNumIdentifiers != 0)
  2809. return llvm::createStringError(
  2810. std::errc::illegal_byte_sequence,
  2811. "duplicate IDENTIFIER_OFFSET record in AST file");
  2812. F.IdentifierOffsets = (const uint32_t *)Blob.data();
  2813. F.LocalNumIdentifiers = Record[0];
  2814. unsigned LocalBaseIdentifierID = Record[1];
  2815. F.BaseIdentifierID = getTotalNumIdentifiers();
  2816. if (F.LocalNumIdentifiers > 0) {
  2817. // Introduce the global -> local mapping for identifiers within this
  2818. // module.
  2819. GlobalIdentifierMap.insert(std::make_pair(getTotalNumIdentifiers() + 1,
  2820. &F));
  2821. // Introduce the local -> global mapping for identifiers within this
  2822. // module.
  2823. F.IdentifierRemap.insertOrReplace(
  2824. std::make_pair(LocalBaseIdentifierID,
  2825. F.BaseIdentifierID - LocalBaseIdentifierID));
  2826. IdentifiersLoaded.resize(IdentifiersLoaded.size()
  2827. + F.LocalNumIdentifiers);
  2828. }
  2829. break;
  2830. }
  2831. case INTERESTING_IDENTIFIERS:
  2832. F.PreloadIdentifierOffsets.assign(Record.begin(), Record.end());
  2833. break;
  2834. case EAGERLY_DESERIALIZED_DECLS:
  2835. // FIXME: Skip reading this record if our ASTConsumer doesn't care
  2836. // about "interesting" decls (for instance, if we're building a module).
  2837. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2838. EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2839. break;
  2840. case MODULAR_CODEGEN_DECLS:
  2841. // FIXME: Skip reading this record if our ASTConsumer doesn't care about
  2842. // them (ie: if we're not codegenerating this module).
  2843. if (F.Kind == MK_MainFile ||
  2844. getContext().getLangOpts().BuildingPCHWithObjectFile)
  2845. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2846. EagerlyDeserializedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2847. break;
  2848. case SPECIAL_TYPES:
  2849. if (SpecialTypes.empty()) {
  2850. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2851. SpecialTypes.push_back(getGlobalTypeID(F, Record[I]));
  2852. break;
  2853. }
  2854. if (SpecialTypes.size() != Record.size())
  2855. return llvm::createStringError(std::errc::illegal_byte_sequence,
  2856. "invalid special-types record");
  2857. for (unsigned I = 0, N = Record.size(); I != N; ++I) {
  2858. serialization::TypeID ID = getGlobalTypeID(F, Record[I]);
  2859. if (!SpecialTypes[I])
  2860. SpecialTypes[I] = ID;
  2861. // FIXME: If ID && SpecialTypes[I] != ID, do we need a separate
  2862. // merge step?
  2863. }
  2864. break;
  2865. case STATISTICS:
  2866. TotalNumStatements += Record[0];
  2867. TotalNumMacros += Record[1];
  2868. TotalLexicalDeclContexts += Record[2];
  2869. TotalVisibleDeclContexts += Record[3];
  2870. break;
  2871. case UNUSED_FILESCOPED_DECLS:
  2872. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2873. UnusedFileScopedDecls.push_back(getGlobalDeclID(F, Record[I]));
  2874. break;
  2875. case DELEGATING_CTORS:
  2876. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  2877. DelegatingCtorDecls.push_back(getGlobalDeclID(F, Record[I]));
  2878. break;
  2879. case WEAK_UNDECLARED_IDENTIFIERS:
  2880. if (Record.size() % 4 != 0)
  2881. return llvm::createStringError(std::errc::illegal_byte_sequence,
  2882. "invalid weak identifiers record");
  2883. // FIXME: Ignore weak undeclared identifiers from non-original PCH
  2884. // files. This isn't the way to do it :)
  2885. WeakUndeclaredIdentifiers.clear();
  2886. // Translate the weak, undeclared identifiers into global IDs.
  2887. for (unsigned I = 0, N = Record.size(); I < N; /* in loop */) {
  2888. WeakUndeclaredIdentifiers.push_back(
  2889. getGlobalIdentifierID(F, Record[I++]));
  2890. WeakUndeclaredIdentifiers.push_back(
  2891. getGlobalIdentifierID(F, Record[I++]));
  2892. WeakUndeclaredIdentifiers.push_back(
  2893. ReadSourceLocation(F, Record, I).getRawEncoding());
  2894. WeakUndeclaredIdentifiers.push_back(Record[I++]);
  2895. }
  2896. break;
  2897. case SELECTOR_OFFSETS: {
  2898. F.SelectorOffsets = (const uint32_t *)Blob.data();
  2899. F.LocalNumSelectors = Record[0];
  2900. unsigned LocalBaseSelectorID = Record[1];
  2901. F.BaseSelectorID = getTotalNumSelectors();
  2902. if (F.LocalNumSelectors > 0) {
  2903. // Introduce the global -> local mapping for selectors within this
  2904. // module.
  2905. GlobalSelectorMap.insert(std::make_pair(getTotalNumSelectors()+1, &F));
  2906. // Introduce the local -> global mapping for selectors within this
  2907. // module.
  2908. F.SelectorRemap.insertOrReplace(
  2909. std::make_pair(LocalBaseSelectorID,
  2910. F.BaseSelectorID - LocalBaseSelectorID));
  2911. SelectorsLoaded.resize(SelectorsLoaded.size() + F.LocalNumSelectors);
  2912. }
  2913. break;
  2914. }
  2915. case METHOD_POOL:
  2916. F.SelectorLookupTableData = (const unsigned char *)Blob.data();
  2917. if (Record[0])
  2918. F.SelectorLookupTable
  2919. = ASTSelectorLookupTable::Create(
  2920. F.SelectorLookupTableData + Record[0],
  2921. F.SelectorLookupTableData,
  2922. ASTSelectorLookupTrait(*this, F));
  2923. TotalNumMethodPoolEntries += Record[1];
  2924. break;
  2925. case REFERENCED_SELECTOR_POOL:
  2926. if (!Record.empty()) {
  2927. for (unsigned Idx = 0, N = Record.size() - 1; Idx < N; /* in loop */) {
  2928. ReferencedSelectorsData.push_back(getGlobalSelectorID(F,
  2929. Record[Idx++]));
  2930. ReferencedSelectorsData.push_back(ReadSourceLocation(F, Record, Idx).
  2931. getRawEncoding());
  2932. }
  2933. }
  2934. break;
  2935. case PP_CONDITIONAL_STACK:
  2936. if (!Record.empty()) {
  2937. unsigned Idx = 0, End = Record.size() - 1;
  2938. bool ReachedEOFWhileSkipping = Record[Idx++];
  2939. llvm::Optional<Preprocessor::PreambleSkipInfo> SkipInfo;
  2940. if (ReachedEOFWhileSkipping) {
  2941. SourceLocation HashToken = ReadSourceLocation(F, Record, Idx);
  2942. SourceLocation IfTokenLoc = ReadSourceLocation(F, Record, Idx);
  2943. bool FoundNonSkipPortion = Record[Idx++];
  2944. bool FoundElse = Record[Idx++];
  2945. SourceLocation ElseLoc = ReadSourceLocation(F, Record, Idx);
  2946. SkipInfo.emplace(HashToken, IfTokenLoc, FoundNonSkipPortion,
  2947. FoundElse, ElseLoc);
  2948. }
  2949. SmallVector<PPConditionalInfo, 4> ConditionalStack;
  2950. while (Idx < End) {
  2951. auto Loc = ReadSourceLocation(F, Record, Idx);
  2952. bool WasSkipping = Record[Idx++];
  2953. bool FoundNonSkip = Record[Idx++];
  2954. bool FoundElse = Record[Idx++];
  2955. ConditionalStack.push_back(
  2956. {Loc, WasSkipping, FoundNonSkip, FoundElse});
  2957. }
  2958. PP.setReplayablePreambleConditionalStack(ConditionalStack, SkipInfo);
  2959. }
  2960. break;
  2961. case PP_COUNTER_VALUE:
  2962. if (!Record.empty() && Listener)
  2963. Listener->ReadCounter(F, Record[0]);
  2964. break;
  2965. case FILE_SORTED_DECLS:
  2966. F.FileSortedDecls = (const DeclID *)Blob.data();
  2967. F.NumFileSortedDecls = Record[0];
  2968. break;
  2969. case SOURCE_LOCATION_OFFSETS: {
  2970. F.SLocEntryOffsets = (const uint32_t *)Blob.data();
  2971. F.LocalNumSLocEntries = Record[0];
  2972. SourceLocation::UIntTy SLocSpaceSize = Record[1];
  2973. F.SLocEntryOffsetsBase = Record[2] + F.SourceManagerBlockStartOffset;
  2974. std::tie(F.SLocEntryBaseID, F.SLocEntryBaseOffset) =
  2975. SourceMgr.AllocateLoadedSLocEntries(F.LocalNumSLocEntries,
  2976. SLocSpaceSize);
  2977. if (!F.SLocEntryBaseID)
  2978. return llvm::createStringError(std::errc::invalid_argument,
  2979. "ran out of source locations");
  2980. // Make our entry in the range map. BaseID is negative and growing, so
  2981. // we invert it. Because we invert it, though, we need the other end of
  2982. // the range.
  2983. unsigned RangeStart =
  2984. unsigned(-F.SLocEntryBaseID) - F.LocalNumSLocEntries + 1;
  2985. GlobalSLocEntryMap.insert(std::make_pair(RangeStart, &F));
  2986. F.FirstLoc = SourceLocation::getFromRawEncoding(F.SLocEntryBaseOffset);
  2987. // SLocEntryBaseOffset is lower than MaxLoadedOffset and decreasing.
  2988. assert((F.SLocEntryBaseOffset & SourceLocation::MacroIDBit) == 0);
  2989. GlobalSLocOffsetMap.insert(
  2990. std::make_pair(SourceManager::MaxLoadedOffset - F.SLocEntryBaseOffset
  2991. - SLocSpaceSize,&F));
  2992. // Initialize the remapping table.
  2993. // Invalid stays invalid.
  2994. F.SLocRemap.insertOrReplace(std::make_pair(0U, 0));
  2995. // This module. Base was 2 when being compiled.
  2996. F.SLocRemap.insertOrReplace(std::make_pair(
  2997. 2U, static_cast<SourceLocation::IntTy>(F.SLocEntryBaseOffset - 2)));
  2998. TotalNumSLocEntries += F.LocalNumSLocEntries;
  2999. break;
  3000. }
  3001. case MODULE_OFFSET_MAP:
  3002. F.ModuleOffsetMap = Blob;
  3003. break;
  3004. case SOURCE_MANAGER_LINE_TABLE:
  3005. ParseLineTable(F, Record);
  3006. break;
  3007. case SOURCE_LOCATION_PRELOADS: {
  3008. // Need to transform from the local view (1-based IDs) to the global view,
  3009. // which is based off F.SLocEntryBaseID.
  3010. if (!F.PreloadSLocEntries.empty())
  3011. return llvm::createStringError(
  3012. std::errc::illegal_byte_sequence,
  3013. "Multiple SOURCE_LOCATION_PRELOADS records in AST file");
  3014. F.PreloadSLocEntries.swap(Record);
  3015. break;
  3016. }
  3017. case EXT_VECTOR_DECLS:
  3018. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3019. ExtVectorDecls.push_back(getGlobalDeclID(F, Record[I]));
  3020. break;
  3021. case VTABLE_USES:
  3022. if (Record.size() % 3 != 0)
  3023. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3024. "Invalid VTABLE_USES record");
  3025. // Later tables overwrite earlier ones.
  3026. // FIXME: Modules will have some trouble with this. This is clearly not
  3027. // the right way to do this.
  3028. VTableUses.clear();
  3029. for (unsigned Idx = 0, N = Record.size(); Idx != N; /* In loop */) {
  3030. VTableUses.push_back(getGlobalDeclID(F, Record[Idx++]));
  3031. VTableUses.push_back(
  3032. ReadSourceLocation(F, Record, Idx).getRawEncoding());
  3033. VTableUses.push_back(Record[Idx++]);
  3034. }
  3035. break;
  3036. case PENDING_IMPLICIT_INSTANTIATIONS:
  3037. if (PendingInstantiations.size() % 2 != 0)
  3038. return llvm::createStringError(
  3039. std::errc::illegal_byte_sequence,
  3040. "Invalid existing PendingInstantiations");
  3041. if (Record.size() % 2 != 0)
  3042. return llvm::createStringError(
  3043. std::errc::illegal_byte_sequence,
  3044. "Invalid PENDING_IMPLICIT_INSTANTIATIONS block");
  3045. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  3046. PendingInstantiations.push_back(getGlobalDeclID(F, Record[I++]));
  3047. PendingInstantiations.push_back(
  3048. ReadSourceLocation(F, Record, I).getRawEncoding());
  3049. }
  3050. break;
  3051. case SEMA_DECL_REFS:
  3052. if (Record.size() != 3)
  3053. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3054. "Invalid SEMA_DECL_REFS block");
  3055. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3056. SemaDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  3057. break;
  3058. case PPD_ENTITIES_OFFSETS: {
  3059. F.PreprocessedEntityOffsets = (const PPEntityOffset *)Blob.data();
  3060. assert(Blob.size() % sizeof(PPEntityOffset) == 0);
  3061. F.NumPreprocessedEntities = Blob.size() / sizeof(PPEntityOffset);
  3062. unsigned LocalBasePreprocessedEntityID = Record[0];
  3063. unsigned StartingID;
  3064. if (!PP.getPreprocessingRecord())
  3065. PP.createPreprocessingRecord();
  3066. if (!PP.getPreprocessingRecord()->getExternalSource())
  3067. PP.getPreprocessingRecord()->SetExternalSource(*this);
  3068. StartingID
  3069. = PP.getPreprocessingRecord()
  3070. ->allocateLoadedEntities(F.NumPreprocessedEntities);
  3071. F.BasePreprocessedEntityID = StartingID;
  3072. if (F.NumPreprocessedEntities > 0) {
  3073. // Introduce the global -> local mapping for preprocessed entities in
  3074. // this module.
  3075. GlobalPreprocessedEntityMap.insert(std::make_pair(StartingID, &F));
  3076. // Introduce the local -> global mapping for preprocessed entities in
  3077. // this module.
  3078. F.PreprocessedEntityRemap.insertOrReplace(
  3079. std::make_pair(LocalBasePreprocessedEntityID,
  3080. F.BasePreprocessedEntityID - LocalBasePreprocessedEntityID));
  3081. }
  3082. break;
  3083. }
  3084. case PPD_SKIPPED_RANGES: {
  3085. F.PreprocessedSkippedRangeOffsets = (const PPSkippedRange*)Blob.data();
  3086. assert(Blob.size() % sizeof(PPSkippedRange) == 0);
  3087. F.NumPreprocessedSkippedRanges = Blob.size() / sizeof(PPSkippedRange);
  3088. if (!PP.getPreprocessingRecord())
  3089. PP.createPreprocessingRecord();
  3090. if (!PP.getPreprocessingRecord()->getExternalSource())
  3091. PP.getPreprocessingRecord()->SetExternalSource(*this);
  3092. F.BasePreprocessedSkippedRangeID = PP.getPreprocessingRecord()
  3093. ->allocateSkippedRanges(F.NumPreprocessedSkippedRanges);
  3094. if (F.NumPreprocessedSkippedRanges > 0)
  3095. GlobalSkippedRangeMap.insert(
  3096. std::make_pair(F.BasePreprocessedSkippedRangeID, &F));
  3097. break;
  3098. }
  3099. case DECL_UPDATE_OFFSETS:
  3100. if (Record.size() % 2 != 0)
  3101. return llvm::createStringError(
  3102. std::errc::illegal_byte_sequence,
  3103. "invalid DECL_UPDATE_OFFSETS block in AST file");
  3104. for (unsigned I = 0, N = Record.size(); I != N; I += 2) {
  3105. GlobalDeclID ID = getGlobalDeclID(F, Record[I]);
  3106. DeclUpdateOffsets[ID].push_back(std::make_pair(&F, Record[I + 1]));
  3107. // If we've already loaded the decl, perform the updates when we finish
  3108. // loading this block.
  3109. if (Decl *D = GetExistingDecl(ID))
  3110. PendingUpdateRecords.push_back(
  3111. PendingUpdateRecord(ID, D, /*JustLoaded=*/false));
  3112. }
  3113. break;
  3114. case OBJC_CATEGORIES_MAP:
  3115. if (F.LocalNumObjCCategoriesInMap != 0)
  3116. return llvm::createStringError(
  3117. std::errc::illegal_byte_sequence,
  3118. "duplicate OBJC_CATEGORIES_MAP record in AST file");
  3119. F.LocalNumObjCCategoriesInMap = Record[0];
  3120. F.ObjCCategoriesMap = (const ObjCCategoriesInfo *)Blob.data();
  3121. break;
  3122. case OBJC_CATEGORIES:
  3123. F.ObjCCategories.swap(Record);
  3124. break;
  3125. case CUDA_SPECIAL_DECL_REFS:
  3126. // Later tables overwrite earlier ones.
  3127. // FIXME: Modules will have trouble with this.
  3128. CUDASpecialDeclRefs.clear();
  3129. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3130. CUDASpecialDeclRefs.push_back(getGlobalDeclID(F, Record[I]));
  3131. break;
  3132. case HEADER_SEARCH_TABLE:
  3133. F.HeaderFileInfoTableData = Blob.data();
  3134. F.LocalNumHeaderFileInfos = Record[1];
  3135. if (Record[0]) {
  3136. F.HeaderFileInfoTable
  3137. = HeaderFileInfoLookupTable::Create(
  3138. (const unsigned char *)F.HeaderFileInfoTableData + Record[0],
  3139. (const unsigned char *)F.HeaderFileInfoTableData,
  3140. HeaderFileInfoTrait(*this, F,
  3141. &PP.getHeaderSearchInfo(),
  3142. Blob.data() + Record[2]));
  3143. PP.getHeaderSearchInfo().SetExternalSource(this);
  3144. if (!PP.getHeaderSearchInfo().getExternalLookup())
  3145. PP.getHeaderSearchInfo().SetExternalLookup(this);
  3146. }
  3147. break;
  3148. case FP_PRAGMA_OPTIONS:
  3149. // Later tables overwrite earlier ones.
  3150. FPPragmaOptions.swap(Record);
  3151. break;
  3152. case OPENCL_EXTENSIONS:
  3153. for (unsigned I = 0, E = Record.size(); I != E; ) {
  3154. auto Name = ReadString(Record, I);
  3155. auto &OptInfo = OpenCLExtensions.OptMap[Name];
  3156. OptInfo.Supported = Record[I++] != 0;
  3157. OptInfo.Enabled = Record[I++] != 0;
  3158. OptInfo.WithPragma = Record[I++] != 0;
  3159. OptInfo.Avail = Record[I++];
  3160. OptInfo.Core = Record[I++];
  3161. OptInfo.Opt = Record[I++];
  3162. }
  3163. break;
  3164. case TENTATIVE_DEFINITIONS:
  3165. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3166. TentativeDefinitions.push_back(getGlobalDeclID(F, Record[I]));
  3167. break;
  3168. case KNOWN_NAMESPACES:
  3169. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3170. KnownNamespaces.push_back(getGlobalDeclID(F, Record[I]));
  3171. break;
  3172. case UNDEFINED_BUT_USED:
  3173. if (UndefinedButUsed.size() % 2 != 0)
  3174. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3175. "Invalid existing UndefinedButUsed");
  3176. if (Record.size() % 2 != 0)
  3177. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3178. "invalid undefined-but-used record");
  3179. for (unsigned I = 0, N = Record.size(); I != N; /* in loop */) {
  3180. UndefinedButUsed.push_back(getGlobalDeclID(F, Record[I++]));
  3181. UndefinedButUsed.push_back(
  3182. ReadSourceLocation(F, Record, I).getRawEncoding());
  3183. }
  3184. break;
  3185. case DELETE_EXPRS_TO_ANALYZE:
  3186. for (unsigned I = 0, N = Record.size(); I != N;) {
  3187. DelayedDeleteExprs.push_back(getGlobalDeclID(F, Record[I++]));
  3188. const uint64_t Count = Record[I++];
  3189. DelayedDeleteExprs.push_back(Count);
  3190. for (uint64_t C = 0; C < Count; ++C) {
  3191. DelayedDeleteExprs.push_back(ReadSourceLocation(F, Record, I).getRawEncoding());
  3192. bool IsArrayForm = Record[I++] == 1;
  3193. DelayedDeleteExprs.push_back(IsArrayForm);
  3194. }
  3195. }
  3196. break;
  3197. case IMPORTED_MODULES:
  3198. if (!F.isModule()) {
  3199. // If we aren't loading a module (which has its own exports), make
  3200. // all of the imported modules visible.
  3201. // FIXME: Deal with macros-only imports.
  3202. for (unsigned I = 0, N = Record.size(); I != N; /**/) {
  3203. unsigned GlobalID = getGlobalSubmoduleID(F, Record[I++]);
  3204. SourceLocation Loc = ReadSourceLocation(F, Record, I);
  3205. if (GlobalID) {
  3206. ImportedModules.push_back(ImportedSubmodule(GlobalID, Loc));
  3207. if (DeserializationListener)
  3208. DeserializationListener->ModuleImportRead(GlobalID, Loc);
  3209. }
  3210. }
  3211. }
  3212. break;
  3213. case MACRO_OFFSET: {
  3214. if (F.LocalNumMacros != 0)
  3215. return llvm::createStringError(
  3216. std::errc::illegal_byte_sequence,
  3217. "duplicate MACRO_OFFSET record in AST file");
  3218. F.MacroOffsets = (const uint32_t *)Blob.data();
  3219. F.LocalNumMacros = Record[0];
  3220. unsigned LocalBaseMacroID = Record[1];
  3221. F.MacroOffsetsBase = Record[2] + F.ASTBlockStartOffset;
  3222. F.BaseMacroID = getTotalNumMacros();
  3223. if (F.LocalNumMacros > 0) {
  3224. // Introduce the global -> local mapping for macros within this module.
  3225. GlobalMacroMap.insert(std::make_pair(getTotalNumMacros() + 1, &F));
  3226. // Introduce the local -> global mapping for macros within this module.
  3227. F.MacroRemap.insertOrReplace(
  3228. std::make_pair(LocalBaseMacroID,
  3229. F.BaseMacroID - LocalBaseMacroID));
  3230. MacrosLoaded.resize(MacrosLoaded.size() + F.LocalNumMacros);
  3231. }
  3232. break;
  3233. }
  3234. case PP_INCLUDED_FILES:
  3235. readIncludedFiles(F, Blob, PP);
  3236. break;
  3237. case LATE_PARSED_TEMPLATE:
  3238. LateParsedTemplates.emplace_back(
  3239. std::piecewise_construct, std::forward_as_tuple(&F),
  3240. std::forward_as_tuple(Record.begin(), Record.end()));
  3241. break;
  3242. case OPTIMIZE_PRAGMA_OPTIONS:
  3243. if (Record.size() != 1)
  3244. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3245. "invalid pragma optimize record");
  3246. OptimizeOffPragmaLocation = ReadSourceLocation(F, Record[0]);
  3247. break;
  3248. case MSSTRUCT_PRAGMA_OPTIONS:
  3249. if (Record.size() != 1)
  3250. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3251. "invalid pragma ms_struct record");
  3252. PragmaMSStructState = Record[0];
  3253. break;
  3254. case POINTERS_TO_MEMBERS_PRAGMA_OPTIONS:
  3255. if (Record.size() != 2)
  3256. return llvm::createStringError(
  3257. std::errc::illegal_byte_sequence,
  3258. "invalid pragma pointers to members record");
  3259. PragmaMSPointersToMembersState = Record[0];
  3260. PointersToMembersPragmaLocation = ReadSourceLocation(F, Record[1]);
  3261. break;
  3262. case UNUSED_LOCAL_TYPEDEF_NAME_CANDIDATES:
  3263. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3264. UnusedLocalTypedefNameCandidates.push_back(
  3265. getGlobalDeclID(F, Record[I]));
  3266. break;
  3267. case CUDA_PRAGMA_FORCE_HOST_DEVICE_DEPTH:
  3268. if (Record.size() != 1)
  3269. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3270. "invalid cuda pragma options record");
  3271. ForceCUDAHostDeviceDepth = Record[0];
  3272. break;
  3273. case ALIGN_PACK_PRAGMA_OPTIONS: {
  3274. if (Record.size() < 3)
  3275. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3276. "invalid pragma pack record");
  3277. PragmaAlignPackCurrentValue = ReadAlignPackInfo(Record[0]);
  3278. PragmaAlignPackCurrentLocation = ReadSourceLocation(F, Record[1]);
  3279. unsigned NumStackEntries = Record[2];
  3280. unsigned Idx = 3;
  3281. // Reset the stack when importing a new module.
  3282. PragmaAlignPackStack.clear();
  3283. for (unsigned I = 0; I < NumStackEntries; ++I) {
  3284. PragmaAlignPackStackEntry Entry;
  3285. Entry.Value = ReadAlignPackInfo(Record[Idx++]);
  3286. Entry.Location = ReadSourceLocation(F, Record[Idx++]);
  3287. Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
  3288. PragmaAlignPackStrings.push_back(ReadString(Record, Idx));
  3289. Entry.SlotLabel = PragmaAlignPackStrings.back();
  3290. PragmaAlignPackStack.push_back(Entry);
  3291. }
  3292. break;
  3293. }
  3294. case FLOAT_CONTROL_PRAGMA_OPTIONS: {
  3295. if (Record.size() < 3)
  3296. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3297. "invalid pragma float control record");
  3298. FpPragmaCurrentValue = FPOptionsOverride::getFromOpaqueInt(Record[0]);
  3299. FpPragmaCurrentLocation = ReadSourceLocation(F, Record[1]);
  3300. unsigned NumStackEntries = Record[2];
  3301. unsigned Idx = 3;
  3302. // Reset the stack when importing a new module.
  3303. FpPragmaStack.clear();
  3304. for (unsigned I = 0; I < NumStackEntries; ++I) {
  3305. FpPragmaStackEntry Entry;
  3306. Entry.Value = FPOptionsOverride::getFromOpaqueInt(Record[Idx++]);
  3307. Entry.Location = ReadSourceLocation(F, Record[Idx++]);
  3308. Entry.PushLocation = ReadSourceLocation(F, Record[Idx++]);
  3309. FpPragmaStrings.push_back(ReadString(Record, Idx));
  3310. Entry.SlotLabel = FpPragmaStrings.back();
  3311. FpPragmaStack.push_back(Entry);
  3312. }
  3313. break;
  3314. }
  3315. case DECLS_TO_CHECK_FOR_DEFERRED_DIAGS:
  3316. for (unsigned I = 0, N = Record.size(); I != N; ++I)
  3317. DeclsToCheckForDeferredDiags.insert(getGlobalDeclID(F, Record[I]));
  3318. break;
  3319. }
  3320. }
  3321. }
  3322. void ASTReader::ReadModuleOffsetMap(ModuleFile &F) const {
  3323. assert(!F.ModuleOffsetMap.empty() && "no module offset map to read");
  3324. // Additional remapping information.
  3325. const unsigned char *Data = (const unsigned char*)F.ModuleOffsetMap.data();
  3326. const unsigned char *DataEnd = Data + F.ModuleOffsetMap.size();
  3327. F.ModuleOffsetMap = StringRef();
  3328. // If we see this entry before SOURCE_LOCATION_OFFSETS, add placeholders.
  3329. if (F.SLocRemap.find(0) == F.SLocRemap.end()) {
  3330. F.SLocRemap.insert(std::make_pair(0U, 0));
  3331. F.SLocRemap.insert(std::make_pair(2U, 1));
  3332. }
  3333. // Continuous range maps we may be updating in our module.
  3334. using SLocRemapBuilder =
  3335. ContinuousRangeMap<SourceLocation::UIntTy, SourceLocation::IntTy,
  3336. 2>::Builder;
  3337. using RemapBuilder = ContinuousRangeMap<uint32_t, int, 2>::Builder;
  3338. SLocRemapBuilder SLocRemap(F.SLocRemap);
  3339. RemapBuilder IdentifierRemap(F.IdentifierRemap);
  3340. RemapBuilder MacroRemap(F.MacroRemap);
  3341. RemapBuilder PreprocessedEntityRemap(F.PreprocessedEntityRemap);
  3342. RemapBuilder SubmoduleRemap(F.SubmoduleRemap);
  3343. RemapBuilder SelectorRemap(F.SelectorRemap);
  3344. RemapBuilder DeclRemap(F.DeclRemap);
  3345. RemapBuilder TypeRemap(F.TypeRemap);
  3346. while (Data < DataEnd) {
  3347. // FIXME: Looking up dependency modules by filename is horrible. Let's
  3348. // start fixing this with prebuilt, explicit and implicit modules and see
  3349. // how it goes...
  3350. using namespace llvm::support;
  3351. ModuleKind Kind = static_cast<ModuleKind>(
  3352. endian::readNext<uint8_t, little, unaligned>(Data));
  3353. uint16_t Len = endian::readNext<uint16_t, little, unaligned>(Data);
  3354. StringRef Name = StringRef((const char*)Data, Len);
  3355. Data += Len;
  3356. ModuleFile *OM = (Kind == MK_PrebuiltModule || Kind == MK_ExplicitModule ||
  3357. Kind == MK_ImplicitModule
  3358. ? ModuleMgr.lookupByModuleName(Name)
  3359. : ModuleMgr.lookupByFileName(Name));
  3360. if (!OM) {
  3361. std::string Msg =
  3362. "SourceLocation remap refers to unknown module, cannot find ";
  3363. Msg.append(std::string(Name));
  3364. Error(Msg);
  3365. return;
  3366. }
  3367. SourceLocation::UIntTy SLocOffset =
  3368. endian::readNext<uint32_t, little, unaligned>(Data);
  3369. uint32_t IdentifierIDOffset =
  3370. endian::readNext<uint32_t, little, unaligned>(Data);
  3371. uint32_t MacroIDOffset =
  3372. endian::readNext<uint32_t, little, unaligned>(Data);
  3373. uint32_t PreprocessedEntityIDOffset =
  3374. endian::readNext<uint32_t, little, unaligned>(Data);
  3375. uint32_t SubmoduleIDOffset =
  3376. endian::readNext<uint32_t, little, unaligned>(Data);
  3377. uint32_t SelectorIDOffset =
  3378. endian::readNext<uint32_t, little, unaligned>(Data);
  3379. uint32_t DeclIDOffset =
  3380. endian::readNext<uint32_t, little, unaligned>(Data);
  3381. uint32_t TypeIndexOffset =
  3382. endian::readNext<uint32_t, little, unaligned>(Data);
  3383. auto mapOffset = [&](uint32_t Offset, uint32_t BaseOffset,
  3384. RemapBuilder &Remap) {
  3385. constexpr uint32_t None = std::numeric_limits<uint32_t>::max();
  3386. if (Offset != None)
  3387. Remap.insert(std::make_pair(Offset,
  3388. static_cast<int>(BaseOffset - Offset)));
  3389. };
  3390. constexpr SourceLocation::UIntTy SLocNone =
  3391. std::numeric_limits<SourceLocation::UIntTy>::max();
  3392. if (SLocOffset != SLocNone)
  3393. SLocRemap.insert(std::make_pair(
  3394. SLocOffset, static_cast<SourceLocation::IntTy>(
  3395. OM->SLocEntryBaseOffset - SLocOffset)));
  3396. mapOffset(IdentifierIDOffset, OM->BaseIdentifierID, IdentifierRemap);
  3397. mapOffset(MacroIDOffset, OM->BaseMacroID, MacroRemap);
  3398. mapOffset(PreprocessedEntityIDOffset, OM->BasePreprocessedEntityID,
  3399. PreprocessedEntityRemap);
  3400. mapOffset(SubmoduleIDOffset, OM->BaseSubmoduleID, SubmoduleRemap);
  3401. mapOffset(SelectorIDOffset, OM->BaseSelectorID, SelectorRemap);
  3402. mapOffset(DeclIDOffset, OM->BaseDeclID, DeclRemap);
  3403. mapOffset(TypeIndexOffset, OM->BaseTypeIndex, TypeRemap);
  3404. // Global -> local mappings.
  3405. F.GlobalToLocalDeclIDs[OM] = DeclIDOffset;
  3406. }
  3407. }
  3408. ASTReader::ASTReadResult
  3409. ASTReader::ReadModuleMapFileBlock(RecordData &Record, ModuleFile &F,
  3410. const ModuleFile *ImportedBy,
  3411. unsigned ClientLoadCapabilities) {
  3412. unsigned Idx = 0;
  3413. F.ModuleMapPath = ReadPath(F, Record, Idx);
  3414. // Try to resolve ModuleName in the current header search context and
  3415. // verify that it is found in the same module map file as we saved. If the
  3416. // top-level AST file is a main file, skip this check because there is no
  3417. // usable header search context.
  3418. assert(!F.ModuleName.empty() &&
  3419. "MODULE_NAME should come before MODULE_MAP_FILE");
  3420. if (F.Kind == MK_ImplicitModule && ModuleMgr.begin()->Kind != MK_MainFile) {
  3421. // An implicitly-loaded module file should have its module listed in some
  3422. // module map file that we've already loaded.
  3423. Module *M =
  3424. PP.getHeaderSearchInfo().lookupModule(F.ModuleName, F.ImportLoc);
  3425. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  3426. const FileEntry *ModMap = M ? Map.getModuleMapFileForUniquing(M) : nullptr;
  3427. // Don't emit module relocation error if we have -fno-validate-pch
  3428. if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
  3429. DisableValidationForModuleKind::Module) &&
  3430. !ModMap) {
  3431. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities)) {
  3432. if (auto ASTFE = M ? M->getASTFile() : None) {
  3433. // This module was defined by an imported (explicit) module.
  3434. Diag(diag::err_module_file_conflict) << F.ModuleName << F.FileName
  3435. << ASTFE->getName();
  3436. } else {
  3437. // This module was built with a different module map.
  3438. Diag(diag::err_imported_module_not_found)
  3439. << F.ModuleName << F.FileName
  3440. << (ImportedBy ? ImportedBy->FileName : "") << F.ModuleMapPath
  3441. << !ImportedBy;
  3442. // In case it was imported by a PCH, there's a chance the user is
  3443. // just missing to include the search path to the directory containing
  3444. // the modulemap.
  3445. if (ImportedBy && ImportedBy->Kind == MK_PCH)
  3446. Diag(diag::note_imported_by_pch_module_not_found)
  3447. << llvm::sys::path::parent_path(F.ModuleMapPath);
  3448. }
  3449. }
  3450. return OutOfDate;
  3451. }
  3452. assert(M && M->Name == F.ModuleName && "found module with different name");
  3453. // Check the primary module map file.
  3454. auto StoredModMap = FileMgr.getFile(F.ModuleMapPath);
  3455. if (!StoredModMap || *StoredModMap != ModMap) {
  3456. assert(ModMap && "found module is missing module map file");
  3457. assert((ImportedBy || F.Kind == MK_ImplicitModule) &&
  3458. "top-level import should be verified");
  3459. bool NotImported = F.Kind == MK_ImplicitModule && !ImportedBy;
  3460. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  3461. Diag(diag::err_imported_module_modmap_changed)
  3462. << F.ModuleName << (NotImported ? F.FileName : ImportedBy->FileName)
  3463. << ModMap->getName() << F.ModuleMapPath << NotImported;
  3464. return OutOfDate;
  3465. }
  3466. llvm::SmallPtrSet<const FileEntry *, 1> AdditionalStoredMaps;
  3467. for (unsigned I = 0, N = Record[Idx++]; I < N; ++I) {
  3468. // FIXME: we should use input files rather than storing names.
  3469. std::string Filename = ReadPath(F, Record, Idx);
  3470. auto SF = FileMgr.getFile(Filename, false, false);
  3471. if (!SF) {
  3472. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  3473. Error("could not find file '" + Filename +"' referenced by AST file");
  3474. return OutOfDate;
  3475. }
  3476. AdditionalStoredMaps.insert(*SF);
  3477. }
  3478. // Check any additional module map files (e.g. module.private.modulemap)
  3479. // that are not in the pcm.
  3480. if (auto *AdditionalModuleMaps = Map.getAdditionalModuleMapFiles(M)) {
  3481. for (const FileEntry *ModMap : *AdditionalModuleMaps) {
  3482. // Remove files that match
  3483. // Note: SmallPtrSet::erase is really remove
  3484. if (!AdditionalStoredMaps.erase(ModMap)) {
  3485. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  3486. Diag(diag::err_module_different_modmap)
  3487. << F.ModuleName << /*new*/0 << ModMap->getName();
  3488. return OutOfDate;
  3489. }
  3490. }
  3491. }
  3492. // Check any additional module map files that are in the pcm, but not
  3493. // found in header search. Cases that match are already removed.
  3494. for (const FileEntry *ModMap : AdditionalStoredMaps) {
  3495. if (!canRecoverFromOutOfDate(F.FileName, ClientLoadCapabilities))
  3496. Diag(diag::err_module_different_modmap)
  3497. << F.ModuleName << /*not new*/1 << ModMap->getName();
  3498. return OutOfDate;
  3499. }
  3500. }
  3501. if (Listener)
  3502. Listener->ReadModuleMapFile(F.ModuleMapPath);
  3503. return Success;
  3504. }
  3505. /// Move the given method to the back of the global list of methods.
  3506. static void moveMethodToBackOfGlobalList(Sema &S, ObjCMethodDecl *Method) {
  3507. // Find the entry for this selector in the method pool.
  3508. Sema::GlobalMethodPool::iterator Known
  3509. = S.MethodPool.find(Method->getSelector());
  3510. if (Known == S.MethodPool.end())
  3511. return;
  3512. // Retrieve the appropriate method list.
  3513. ObjCMethodList &Start = Method->isInstanceMethod()? Known->second.first
  3514. : Known->second.second;
  3515. bool Found = false;
  3516. for (ObjCMethodList *List = &Start; List; List = List->getNext()) {
  3517. if (!Found) {
  3518. if (List->getMethod() == Method) {
  3519. Found = true;
  3520. } else {
  3521. // Keep searching.
  3522. continue;
  3523. }
  3524. }
  3525. if (List->getNext())
  3526. List->setMethod(List->getNext()->getMethod());
  3527. else
  3528. List->setMethod(Method);
  3529. }
  3530. }
  3531. void ASTReader::makeNamesVisible(const HiddenNames &Names, Module *Owner) {
  3532. assert(Owner->NameVisibility != Module::Hidden && "nothing to make visible?");
  3533. for (Decl *D : Names) {
  3534. bool wasHidden = !D->isUnconditionallyVisible();
  3535. D->setVisibleDespiteOwningModule();
  3536. if (wasHidden && SemaObj) {
  3537. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(D)) {
  3538. moveMethodToBackOfGlobalList(*SemaObj, Method);
  3539. }
  3540. }
  3541. }
  3542. }
  3543. void ASTReader::makeModuleVisible(Module *Mod,
  3544. Module::NameVisibilityKind NameVisibility,
  3545. SourceLocation ImportLoc) {
  3546. llvm::SmallPtrSet<Module *, 4> Visited;
  3547. SmallVector<Module *, 4> Stack;
  3548. Stack.push_back(Mod);
  3549. while (!Stack.empty()) {
  3550. Mod = Stack.pop_back_val();
  3551. if (NameVisibility <= Mod->NameVisibility) {
  3552. // This module already has this level of visibility (or greater), so
  3553. // there is nothing more to do.
  3554. continue;
  3555. }
  3556. if (Mod->isUnimportable()) {
  3557. // Modules that aren't importable cannot be made visible.
  3558. continue;
  3559. }
  3560. // Update the module's name visibility.
  3561. Mod->NameVisibility = NameVisibility;
  3562. // If we've already deserialized any names from this module,
  3563. // mark them as visible.
  3564. HiddenNamesMapType::iterator Hidden = HiddenNamesMap.find(Mod);
  3565. if (Hidden != HiddenNamesMap.end()) {
  3566. auto HiddenNames = std::move(*Hidden);
  3567. HiddenNamesMap.erase(Hidden);
  3568. makeNamesVisible(HiddenNames.second, HiddenNames.first);
  3569. assert(HiddenNamesMap.find(Mod) == HiddenNamesMap.end() &&
  3570. "making names visible added hidden names");
  3571. }
  3572. // Push any exported modules onto the stack to be marked as visible.
  3573. SmallVector<Module *, 16> Exports;
  3574. Mod->getExportedModules(Exports);
  3575. for (SmallVectorImpl<Module *>::iterator
  3576. I = Exports.begin(), E = Exports.end(); I != E; ++I) {
  3577. Module *Exported = *I;
  3578. if (Visited.insert(Exported).second)
  3579. Stack.push_back(Exported);
  3580. }
  3581. }
  3582. }
  3583. /// We've merged the definition \p MergedDef into the existing definition
  3584. /// \p Def. Ensure that \p Def is made visible whenever \p MergedDef is made
  3585. /// visible.
  3586. void ASTReader::mergeDefinitionVisibility(NamedDecl *Def,
  3587. NamedDecl *MergedDef) {
  3588. if (!Def->isUnconditionallyVisible()) {
  3589. // If MergedDef is visible or becomes visible, make the definition visible.
  3590. if (MergedDef->isUnconditionallyVisible())
  3591. Def->setVisibleDespiteOwningModule();
  3592. else {
  3593. getContext().mergeDefinitionIntoModule(
  3594. Def, MergedDef->getImportedOwningModule(),
  3595. /*NotifyListeners*/ false);
  3596. PendingMergedDefinitionsToDeduplicate.insert(Def);
  3597. }
  3598. }
  3599. }
  3600. bool ASTReader::loadGlobalIndex() {
  3601. if (GlobalIndex)
  3602. return false;
  3603. if (TriedLoadingGlobalIndex || !UseGlobalIndex ||
  3604. !PP.getLangOpts().Modules)
  3605. return true;
  3606. // Try to load the global index.
  3607. TriedLoadingGlobalIndex = true;
  3608. StringRef ModuleCachePath
  3609. = getPreprocessor().getHeaderSearchInfo().getModuleCachePath();
  3610. std::pair<GlobalModuleIndex *, llvm::Error> Result =
  3611. GlobalModuleIndex::readIndex(ModuleCachePath);
  3612. if (llvm::Error Err = std::move(Result.second)) {
  3613. assert(!Result.first);
  3614. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  3615. return true;
  3616. }
  3617. GlobalIndex.reset(Result.first);
  3618. ModuleMgr.setGlobalIndex(GlobalIndex.get());
  3619. return false;
  3620. }
  3621. bool ASTReader::isGlobalIndexUnavailable() const {
  3622. return PP.getLangOpts().Modules && UseGlobalIndex &&
  3623. !hasGlobalIndex() && TriedLoadingGlobalIndex;
  3624. }
  3625. static void updateModuleTimestamp(ModuleFile &MF) {
  3626. // Overwrite the timestamp file contents so that file's mtime changes.
  3627. std::string TimestampFilename = MF.getTimestampFilename();
  3628. std::error_code EC;
  3629. llvm::raw_fd_ostream OS(TimestampFilename, EC,
  3630. llvm::sys::fs::OF_TextWithCRLF);
  3631. if (EC)
  3632. return;
  3633. OS << "Timestamp file\n";
  3634. OS.close();
  3635. OS.clear_error(); // Avoid triggering a fatal error.
  3636. }
  3637. /// Given a cursor at the start of an AST file, scan ahead and drop the
  3638. /// cursor into the start of the given block ID, returning false on success and
  3639. /// true on failure.
  3640. static bool SkipCursorToBlock(BitstreamCursor &Cursor, unsigned BlockID) {
  3641. while (true) {
  3642. Expected<llvm::BitstreamEntry> MaybeEntry = Cursor.advance();
  3643. if (!MaybeEntry) {
  3644. // FIXME this drops errors on the floor.
  3645. consumeError(MaybeEntry.takeError());
  3646. return true;
  3647. }
  3648. llvm::BitstreamEntry Entry = MaybeEntry.get();
  3649. switch (Entry.Kind) {
  3650. case llvm::BitstreamEntry::Error:
  3651. case llvm::BitstreamEntry::EndBlock:
  3652. return true;
  3653. case llvm::BitstreamEntry::Record:
  3654. // Ignore top-level records.
  3655. if (Expected<unsigned> Skipped = Cursor.skipRecord(Entry.ID))
  3656. break;
  3657. else {
  3658. // FIXME this drops errors on the floor.
  3659. consumeError(Skipped.takeError());
  3660. return true;
  3661. }
  3662. case llvm::BitstreamEntry::SubBlock:
  3663. if (Entry.ID == BlockID) {
  3664. if (llvm::Error Err = Cursor.EnterSubBlock(BlockID)) {
  3665. // FIXME this drops the error on the floor.
  3666. consumeError(std::move(Err));
  3667. return true;
  3668. }
  3669. // Found it!
  3670. return false;
  3671. }
  3672. if (llvm::Error Err = Cursor.SkipBlock()) {
  3673. // FIXME this drops the error on the floor.
  3674. consumeError(std::move(Err));
  3675. return true;
  3676. }
  3677. }
  3678. }
  3679. }
  3680. ASTReader::ASTReadResult ASTReader::ReadAST(StringRef FileName,
  3681. ModuleKind Type,
  3682. SourceLocation ImportLoc,
  3683. unsigned ClientLoadCapabilities,
  3684. SmallVectorImpl<ImportedSubmodule> *Imported) {
  3685. llvm::SaveAndRestore<SourceLocation>
  3686. SetCurImportLocRAII(CurrentImportLoc, ImportLoc);
  3687. llvm::SaveAndRestore<Optional<ModuleKind>> SetCurModuleKindRAII(
  3688. CurrentDeserializingModuleKind, Type);
  3689. // Defer any pending actions until we get to the end of reading the AST file.
  3690. Deserializing AnASTFile(this);
  3691. // Bump the generation number.
  3692. unsigned PreviousGeneration = 0;
  3693. if (ContextObj)
  3694. PreviousGeneration = incrementGeneration(*ContextObj);
  3695. unsigned NumModules = ModuleMgr.size();
  3696. SmallVector<ImportedModule, 4> Loaded;
  3697. if (ASTReadResult ReadResult =
  3698. ReadASTCore(FileName, Type, ImportLoc,
  3699. /*ImportedBy=*/nullptr, Loaded, 0, 0, ASTFileSignature(),
  3700. ClientLoadCapabilities)) {
  3701. ModuleMgr.removeModules(ModuleMgr.begin() + NumModules,
  3702. PP.getLangOpts().Modules
  3703. ? &PP.getHeaderSearchInfo().getModuleMap()
  3704. : nullptr);
  3705. // If we find that any modules are unusable, the global index is going
  3706. // to be out-of-date. Just remove it.
  3707. GlobalIndex.reset();
  3708. ModuleMgr.setGlobalIndex(nullptr);
  3709. return ReadResult;
  3710. }
  3711. // Here comes stuff that we only do once the entire chain is loaded. Do *not*
  3712. // remove modules from this point. Various fields are updated during reading
  3713. // the AST block and removing the modules would result in dangling pointers.
  3714. // They are generally only incidentally dereferenced, ie. a binary search
  3715. // runs over `GlobalSLocEntryMap`, which could cause an invalid module to
  3716. // be dereferenced but it wouldn't actually be used.
  3717. // Load the AST blocks of all of the modules that we loaded. We can still
  3718. // hit errors parsing the ASTs at this point.
  3719. for (ImportedModule &M : Loaded) {
  3720. ModuleFile &F = *M.Mod;
  3721. // Read the AST block.
  3722. if (llvm::Error Err = ReadASTBlock(F, ClientLoadCapabilities)) {
  3723. Error(std::move(Err));
  3724. return Failure;
  3725. }
  3726. // The AST block should always have a definition for the main module.
  3727. if (F.isModule() && !F.DidReadTopLevelSubmodule) {
  3728. Error(diag::err_module_file_missing_top_level_submodule, F.FileName);
  3729. return Failure;
  3730. }
  3731. // Read the extension blocks.
  3732. while (!SkipCursorToBlock(F.Stream, EXTENSION_BLOCK_ID)) {
  3733. if (llvm::Error Err = ReadExtensionBlock(F)) {
  3734. Error(std::move(Err));
  3735. return Failure;
  3736. }
  3737. }
  3738. // Once read, set the ModuleFile bit base offset and update the size in
  3739. // bits of all files we've seen.
  3740. F.GlobalBitOffset = TotalModulesSizeInBits;
  3741. TotalModulesSizeInBits += F.SizeInBits;
  3742. GlobalBitOffsetsMap.insert(std::make_pair(F.GlobalBitOffset, &F));
  3743. }
  3744. // Preload source locations and interesting indentifiers.
  3745. for (ImportedModule &M : Loaded) {
  3746. ModuleFile &F = *M.Mod;
  3747. // Preload SLocEntries.
  3748. for (unsigned I = 0, N = F.PreloadSLocEntries.size(); I != N; ++I) {
  3749. int Index = int(F.PreloadSLocEntries[I] - 1) + F.SLocEntryBaseID;
  3750. // Load it through the SourceManager and don't call ReadSLocEntry()
  3751. // directly because the entry may have already been loaded in which case
  3752. // calling ReadSLocEntry() directly would trigger an assertion in
  3753. // SourceManager.
  3754. SourceMgr.getLoadedSLocEntryByID(Index);
  3755. }
  3756. // Map the original source file ID into the ID space of the current
  3757. // compilation.
  3758. if (F.OriginalSourceFileID.isValid()) {
  3759. F.OriginalSourceFileID = FileID::get(
  3760. F.SLocEntryBaseID + F.OriginalSourceFileID.getOpaqueValue() - 1);
  3761. }
  3762. // Preload all the pending interesting identifiers by marking them out of
  3763. // date.
  3764. for (auto Offset : F.PreloadIdentifierOffsets) {
  3765. const unsigned char *Data = F.IdentifierTableData + Offset;
  3766. ASTIdentifierLookupTrait Trait(*this, F);
  3767. auto KeyDataLen = Trait.ReadKeyDataLength(Data);
  3768. auto Key = Trait.ReadKey(Data, KeyDataLen.first);
  3769. auto &II = PP.getIdentifierTable().getOwn(Key);
  3770. II.setOutOfDate(true);
  3771. // Mark this identifier as being from an AST file so that we can track
  3772. // whether we need to serialize it.
  3773. markIdentifierFromAST(*this, II);
  3774. // Associate the ID with the identifier so that the writer can reuse it.
  3775. auto ID = Trait.ReadIdentifierID(Data + KeyDataLen.first);
  3776. SetIdentifierInfo(ID, &II);
  3777. }
  3778. }
  3779. // Setup the import locations and notify the module manager that we've
  3780. // committed to these module files.
  3781. for (ImportedModule &M : Loaded) {
  3782. ModuleFile &F = *M.Mod;
  3783. ModuleMgr.moduleFileAccepted(&F);
  3784. // Set the import location.
  3785. F.DirectImportLoc = ImportLoc;
  3786. // FIXME: We assume that locations from PCH / preamble do not need
  3787. // any translation.
  3788. if (!M.ImportedBy)
  3789. F.ImportLoc = M.ImportLoc;
  3790. else
  3791. F.ImportLoc = TranslateSourceLocation(*M.ImportedBy, M.ImportLoc);
  3792. }
  3793. if (!PP.getLangOpts().CPlusPlus ||
  3794. (Type != MK_ImplicitModule && Type != MK_ExplicitModule &&
  3795. Type != MK_PrebuiltModule)) {
  3796. // Mark all of the identifiers in the identifier table as being out of date,
  3797. // so that various accessors know to check the loaded modules when the
  3798. // identifier is used.
  3799. //
  3800. // For C++ modules, we don't need information on many identifiers (just
  3801. // those that provide macros or are poisoned), so we mark all of
  3802. // the interesting ones via PreloadIdentifierOffsets.
  3803. for (IdentifierTable::iterator Id = PP.getIdentifierTable().begin(),
  3804. IdEnd = PP.getIdentifierTable().end();
  3805. Id != IdEnd; ++Id)
  3806. Id->second->setOutOfDate(true);
  3807. }
  3808. // Mark selectors as out of date.
  3809. for (auto Sel : SelectorGeneration)
  3810. SelectorOutOfDate[Sel.first] = true;
  3811. // Resolve any unresolved module exports.
  3812. for (unsigned I = 0, N = UnresolvedModuleRefs.size(); I != N; ++I) {
  3813. UnresolvedModuleRef &Unresolved = UnresolvedModuleRefs[I];
  3814. SubmoduleID GlobalID = getGlobalSubmoduleID(*Unresolved.File,Unresolved.ID);
  3815. Module *ResolvedMod = getSubmodule(GlobalID);
  3816. switch (Unresolved.Kind) {
  3817. case UnresolvedModuleRef::Conflict:
  3818. if (ResolvedMod) {
  3819. Module::Conflict Conflict;
  3820. Conflict.Other = ResolvedMod;
  3821. Conflict.Message = Unresolved.String.str();
  3822. Unresolved.Mod->Conflicts.push_back(Conflict);
  3823. }
  3824. continue;
  3825. case UnresolvedModuleRef::Import:
  3826. if (ResolvedMod)
  3827. Unresolved.Mod->Imports.insert(ResolvedMod);
  3828. continue;
  3829. case UnresolvedModuleRef::Export:
  3830. if (ResolvedMod || Unresolved.IsWildcard)
  3831. Unresolved.Mod->Exports.push_back(
  3832. Module::ExportDecl(ResolvedMod, Unresolved.IsWildcard));
  3833. continue;
  3834. }
  3835. }
  3836. UnresolvedModuleRefs.clear();
  3837. if (Imported)
  3838. Imported->append(ImportedModules.begin(),
  3839. ImportedModules.end());
  3840. // FIXME: How do we load the 'use'd modules? They may not be submodules.
  3841. // Might be unnecessary as use declarations are only used to build the
  3842. // module itself.
  3843. if (ContextObj)
  3844. InitializeContext();
  3845. if (SemaObj)
  3846. UpdateSema();
  3847. if (DeserializationListener)
  3848. DeserializationListener->ReaderInitialized(this);
  3849. ModuleFile &PrimaryModule = ModuleMgr.getPrimaryModule();
  3850. if (PrimaryModule.OriginalSourceFileID.isValid()) {
  3851. // If this AST file is a precompiled preamble, then set the
  3852. // preamble file ID of the source manager to the file source file
  3853. // from which the preamble was built.
  3854. if (Type == MK_Preamble) {
  3855. SourceMgr.setPreambleFileID(PrimaryModule.OriginalSourceFileID);
  3856. } else if (Type == MK_MainFile) {
  3857. SourceMgr.setMainFileID(PrimaryModule.OriginalSourceFileID);
  3858. }
  3859. }
  3860. // For any Objective-C class definitions we have already loaded, make sure
  3861. // that we load any additional categories.
  3862. if (ContextObj) {
  3863. for (unsigned I = 0, N = ObjCClassesLoaded.size(); I != N; ++I) {
  3864. loadObjCCategories(ObjCClassesLoaded[I]->getGlobalID(),
  3865. ObjCClassesLoaded[I],
  3866. PreviousGeneration);
  3867. }
  3868. }
  3869. if (PP.getHeaderSearchInfo()
  3870. .getHeaderSearchOpts()
  3871. .ModulesValidateOncePerBuildSession) {
  3872. // Now we are certain that the module and all modules it depends on are
  3873. // up to date. Create or update timestamp files for modules that are
  3874. // located in the module cache (not for PCH files that could be anywhere
  3875. // in the filesystem).
  3876. for (unsigned I = 0, N = Loaded.size(); I != N; ++I) {
  3877. ImportedModule &M = Loaded[I];
  3878. if (M.Mod->Kind == MK_ImplicitModule) {
  3879. updateModuleTimestamp(*M.Mod);
  3880. }
  3881. }
  3882. }
  3883. return Success;
  3884. }
  3885. static ASTFileSignature readASTFileSignature(StringRef PCH);
  3886. /// Whether \p Stream doesn't start with the AST/PCH file magic number 'CPCH'.
  3887. static llvm::Error doesntStartWithASTFileMagic(BitstreamCursor &Stream) {
  3888. // FIXME checking magic headers is done in other places such as
  3889. // SerializedDiagnosticReader and GlobalModuleIndex, but error handling isn't
  3890. // always done the same. Unify it all with a helper.
  3891. if (!Stream.canSkipToPos(4))
  3892. return llvm::createStringError(std::errc::illegal_byte_sequence,
  3893. "file too small to contain AST file magic");
  3894. for (unsigned C : {'C', 'P', 'C', 'H'})
  3895. if (Expected<llvm::SimpleBitstreamCursor::word_t> Res = Stream.Read(8)) {
  3896. if (Res.get() != C)
  3897. return llvm::createStringError(
  3898. std::errc::illegal_byte_sequence,
  3899. "file doesn't start with AST file magic");
  3900. } else
  3901. return Res.takeError();
  3902. return llvm::Error::success();
  3903. }
  3904. static unsigned moduleKindForDiagnostic(ModuleKind Kind) {
  3905. switch (Kind) {
  3906. case MK_PCH:
  3907. return 0; // PCH
  3908. case MK_ImplicitModule:
  3909. case MK_ExplicitModule:
  3910. case MK_PrebuiltModule:
  3911. return 1; // module
  3912. case MK_MainFile:
  3913. case MK_Preamble:
  3914. return 2; // main source file
  3915. }
  3916. llvm_unreachable("unknown module kind");
  3917. }
  3918. ASTReader::ASTReadResult
  3919. ASTReader::ReadASTCore(StringRef FileName,
  3920. ModuleKind Type,
  3921. SourceLocation ImportLoc,
  3922. ModuleFile *ImportedBy,
  3923. SmallVectorImpl<ImportedModule> &Loaded,
  3924. off_t ExpectedSize, time_t ExpectedModTime,
  3925. ASTFileSignature ExpectedSignature,
  3926. unsigned ClientLoadCapabilities) {
  3927. ModuleFile *M;
  3928. std::string ErrorStr;
  3929. ModuleManager::AddModuleResult AddResult
  3930. = ModuleMgr.addModule(FileName, Type, ImportLoc, ImportedBy,
  3931. getGeneration(), ExpectedSize, ExpectedModTime,
  3932. ExpectedSignature, readASTFileSignature,
  3933. M, ErrorStr);
  3934. switch (AddResult) {
  3935. case ModuleManager::AlreadyLoaded:
  3936. Diag(diag::remark_module_import)
  3937. << M->ModuleName << M->FileName << (ImportedBy ? true : false)
  3938. << (ImportedBy ? StringRef(ImportedBy->ModuleName) : StringRef());
  3939. return Success;
  3940. case ModuleManager::NewlyLoaded:
  3941. // Load module file below.
  3942. break;
  3943. case ModuleManager::Missing:
  3944. // The module file was missing; if the client can handle that, return
  3945. // it.
  3946. if (ClientLoadCapabilities & ARR_Missing)
  3947. return Missing;
  3948. // Otherwise, return an error.
  3949. Diag(diag::err_ast_file_not_found)
  3950. << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
  3951. << ErrorStr;
  3952. return Failure;
  3953. case ModuleManager::OutOfDate:
  3954. // We couldn't load the module file because it is out-of-date. If the
  3955. // client can handle out-of-date, return it.
  3956. if (ClientLoadCapabilities & ARR_OutOfDate)
  3957. return OutOfDate;
  3958. // Otherwise, return an error.
  3959. Diag(diag::err_ast_file_out_of_date)
  3960. << moduleKindForDiagnostic(Type) << FileName << !ErrorStr.empty()
  3961. << ErrorStr;
  3962. return Failure;
  3963. }
  3964. assert(M && "Missing module file");
  3965. bool ShouldFinalizePCM = false;
  3966. auto FinalizeOrDropPCM = llvm::make_scope_exit([&]() {
  3967. auto &MC = getModuleManager().getModuleCache();
  3968. if (ShouldFinalizePCM)
  3969. MC.finalizePCM(FileName);
  3970. else
  3971. MC.tryToDropPCM(FileName);
  3972. });
  3973. ModuleFile &F = *M;
  3974. BitstreamCursor &Stream = F.Stream;
  3975. Stream = BitstreamCursor(PCHContainerRdr.ExtractPCH(*F.Buffer));
  3976. F.SizeInBits = F.Buffer->getBufferSize() * 8;
  3977. // Sniff for the signature.
  3978. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  3979. Diag(diag::err_ast_file_invalid)
  3980. << moduleKindForDiagnostic(Type) << FileName << std::move(Err);
  3981. return Failure;
  3982. }
  3983. // This is used for compatibility with older PCH formats.
  3984. bool HaveReadControlBlock = false;
  3985. while (true) {
  3986. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  3987. if (!MaybeEntry) {
  3988. Error(MaybeEntry.takeError());
  3989. return Failure;
  3990. }
  3991. llvm::BitstreamEntry Entry = MaybeEntry.get();
  3992. switch (Entry.Kind) {
  3993. case llvm::BitstreamEntry::Error:
  3994. case llvm::BitstreamEntry::Record:
  3995. case llvm::BitstreamEntry::EndBlock:
  3996. Error("invalid record at top-level of AST file");
  3997. return Failure;
  3998. case llvm::BitstreamEntry::SubBlock:
  3999. break;
  4000. }
  4001. switch (Entry.ID) {
  4002. case CONTROL_BLOCK_ID:
  4003. HaveReadControlBlock = true;
  4004. switch (ReadControlBlock(F, Loaded, ImportedBy, ClientLoadCapabilities)) {
  4005. case Success:
  4006. // Check that we didn't try to load a non-module AST file as a module.
  4007. //
  4008. // FIXME: Should we also perform the converse check? Loading a module as
  4009. // a PCH file sort of works, but it's a bit wonky.
  4010. if ((Type == MK_ImplicitModule || Type == MK_ExplicitModule ||
  4011. Type == MK_PrebuiltModule) &&
  4012. F.ModuleName.empty()) {
  4013. auto Result = (Type == MK_ImplicitModule) ? OutOfDate : Failure;
  4014. if (Result != OutOfDate ||
  4015. (ClientLoadCapabilities & ARR_OutOfDate) == 0)
  4016. Diag(diag::err_module_file_not_module) << FileName;
  4017. return Result;
  4018. }
  4019. break;
  4020. case Failure: return Failure;
  4021. case Missing: return Missing;
  4022. case OutOfDate: return OutOfDate;
  4023. case VersionMismatch: return VersionMismatch;
  4024. case ConfigurationMismatch: return ConfigurationMismatch;
  4025. case HadErrors: return HadErrors;
  4026. }
  4027. break;
  4028. case AST_BLOCK_ID:
  4029. if (!HaveReadControlBlock) {
  4030. if ((ClientLoadCapabilities & ARR_VersionMismatch) == 0)
  4031. Diag(diag::err_pch_version_too_old);
  4032. return VersionMismatch;
  4033. }
  4034. // Record that we've loaded this module.
  4035. Loaded.push_back(ImportedModule(M, ImportedBy, ImportLoc));
  4036. ShouldFinalizePCM = true;
  4037. return Success;
  4038. case UNHASHED_CONTROL_BLOCK_ID:
  4039. // This block is handled using look-ahead during ReadControlBlock. We
  4040. // shouldn't get here!
  4041. Error("malformed block record in AST file");
  4042. return Failure;
  4043. default:
  4044. if (llvm::Error Err = Stream.SkipBlock()) {
  4045. Error(std::move(Err));
  4046. return Failure;
  4047. }
  4048. break;
  4049. }
  4050. }
  4051. llvm_unreachable("unexpected break; expected return");
  4052. }
  4053. ASTReader::ASTReadResult
  4054. ASTReader::readUnhashedControlBlock(ModuleFile &F, bool WasImportedBy,
  4055. unsigned ClientLoadCapabilities) {
  4056. const HeaderSearchOptions &HSOpts =
  4057. PP.getHeaderSearchInfo().getHeaderSearchOpts();
  4058. bool AllowCompatibleConfigurationMismatch =
  4059. F.Kind == MK_ExplicitModule || F.Kind == MK_PrebuiltModule;
  4060. bool DisableValidation = shouldDisableValidationForFile(F);
  4061. ASTReadResult Result = readUnhashedControlBlockImpl(
  4062. &F, F.Data, ClientLoadCapabilities, AllowCompatibleConfigurationMismatch,
  4063. Listener.get(),
  4064. WasImportedBy ? false : HSOpts.ModulesValidateDiagnosticOptions);
  4065. // If F was directly imported by another module, it's implicitly validated by
  4066. // the importing module.
  4067. if (DisableValidation || WasImportedBy ||
  4068. (AllowConfigurationMismatch && Result == ConfigurationMismatch))
  4069. return Success;
  4070. if (Result == Failure) {
  4071. Error("malformed block record in AST file");
  4072. return Failure;
  4073. }
  4074. if (Result == OutOfDate && F.Kind == MK_ImplicitModule) {
  4075. // If this module has already been finalized in the ModuleCache, we're stuck
  4076. // with it; we can only load a single version of each module.
  4077. //
  4078. // This can happen when a module is imported in two contexts: in one, as a
  4079. // user module; in another, as a system module (due to an import from
  4080. // another module marked with the [system] flag). It usually indicates a
  4081. // bug in the module map: this module should also be marked with [system].
  4082. //
  4083. // If -Wno-system-headers (the default), and the first import is as a
  4084. // system module, then validation will fail during the as-user import,
  4085. // since -Werror flags won't have been validated. However, it's reasonable
  4086. // to treat this consistently as a system module.
  4087. //
  4088. // If -Wsystem-headers, the PCM on disk was built with
  4089. // -Wno-system-headers, and the first import is as a user module, then
  4090. // validation will fail during the as-system import since the PCM on disk
  4091. // doesn't guarantee that -Werror was respected. However, the -Werror
  4092. // flags were checked during the initial as-user import.
  4093. if (getModuleManager().getModuleCache().isPCMFinal(F.FileName)) {
  4094. Diag(diag::warn_module_system_bit_conflict) << F.FileName;
  4095. return Success;
  4096. }
  4097. }
  4098. return Result;
  4099. }
  4100. ASTReader::ASTReadResult ASTReader::readUnhashedControlBlockImpl(
  4101. ModuleFile *F, llvm::StringRef StreamData, unsigned ClientLoadCapabilities,
  4102. bool AllowCompatibleConfigurationMismatch, ASTReaderListener *Listener,
  4103. bool ValidateDiagnosticOptions) {
  4104. // Initialize a stream.
  4105. BitstreamCursor Stream(StreamData);
  4106. // Sniff for the signature.
  4107. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  4108. // FIXME this drops the error on the floor.
  4109. consumeError(std::move(Err));
  4110. return Failure;
  4111. }
  4112. // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
  4113. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
  4114. return Failure;
  4115. // Read all of the records in the options block.
  4116. RecordData Record;
  4117. ASTReadResult Result = Success;
  4118. while (true) {
  4119. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4120. if (!MaybeEntry) {
  4121. // FIXME this drops the error on the floor.
  4122. consumeError(MaybeEntry.takeError());
  4123. return Failure;
  4124. }
  4125. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4126. switch (Entry.Kind) {
  4127. case llvm::BitstreamEntry::Error:
  4128. case llvm::BitstreamEntry::SubBlock:
  4129. return Failure;
  4130. case llvm::BitstreamEntry::EndBlock:
  4131. return Result;
  4132. case llvm::BitstreamEntry::Record:
  4133. // The interesting case.
  4134. break;
  4135. }
  4136. // Read and process a record.
  4137. Record.clear();
  4138. StringRef Blob;
  4139. Expected<unsigned> MaybeRecordType =
  4140. Stream.readRecord(Entry.ID, Record, &Blob);
  4141. if (!MaybeRecordType) {
  4142. // FIXME this drops the error.
  4143. return Failure;
  4144. }
  4145. switch ((UnhashedControlBlockRecordTypes)MaybeRecordType.get()) {
  4146. case SIGNATURE:
  4147. if (F)
  4148. F->Signature = ASTFileSignature::create(Record.begin(), Record.end());
  4149. break;
  4150. case AST_BLOCK_HASH:
  4151. if (F)
  4152. F->ASTBlockHash =
  4153. ASTFileSignature::create(Record.begin(), Record.end());
  4154. break;
  4155. case DIAGNOSTIC_OPTIONS: {
  4156. bool Complain = (ClientLoadCapabilities & ARR_OutOfDate) == 0;
  4157. if (Listener && ValidateDiagnosticOptions &&
  4158. !AllowCompatibleConfigurationMismatch &&
  4159. ParseDiagnosticOptions(Record, Complain, *Listener))
  4160. Result = OutOfDate; // Don't return early. Read the signature.
  4161. break;
  4162. }
  4163. case DIAG_PRAGMA_MAPPINGS:
  4164. if (!F)
  4165. break;
  4166. if (F->PragmaDiagMappings.empty())
  4167. F->PragmaDiagMappings.swap(Record);
  4168. else
  4169. F->PragmaDiagMappings.insert(F->PragmaDiagMappings.end(),
  4170. Record.begin(), Record.end());
  4171. break;
  4172. case HEADER_SEARCH_ENTRY_USAGE:
  4173. if (!F)
  4174. break;
  4175. unsigned Count = Record[0];
  4176. const char *Byte = Blob.data();
  4177. F->SearchPathUsage = llvm::BitVector(Count, false);
  4178. for (unsigned I = 0; I < Count; ++Byte)
  4179. for (unsigned Bit = 0; Bit < 8 && I < Count; ++Bit, ++I)
  4180. if (*Byte & (1 << Bit))
  4181. F->SearchPathUsage[I] = true;
  4182. break;
  4183. }
  4184. }
  4185. }
  4186. /// Parse a record and blob containing module file extension metadata.
  4187. static bool parseModuleFileExtensionMetadata(
  4188. const SmallVectorImpl<uint64_t> &Record,
  4189. StringRef Blob,
  4190. ModuleFileExtensionMetadata &Metadata) {
  4191. if (Record.size() < 4) return true;
  4192. Metadata.MajorVersion = Record[0];
  4193. Metadata.MinorVersion = Record[1];
  4194. unsigned BlockNameLen = Record[2];
  4195. unsigned UserInfoLen = Record[3];
  4196. if (BlockNameLen + UserInfoLen > Blob.size()) return true;
  4197. Metadata.BlockName = std::string(Blob.data(), Blob.data() + BlockNameLen);
  4198. Metadata.UserInfo = std::string(Blob.data() + BlockNameLen,
  4199. Blob.data() + BlockNameLen + UserInfoLen);
  4200. return false;
  4201. }
  4202. llvm::Error ASTReader::ReadExtensionBlock(ModuleFile &F) {
  4203. BitstreamCursor &Stream = F.Stream;
  4204. RecordData Record;
  4205. while (true) {
  4206. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4207. if (!MaybeEntry)
  4208. return MaybeEntry.takeError();
  4209. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4210. switch (Entry.Kind) {
  4211. case llvm::BitstreamEntry::SubBlock:
  4212. if (llvm::Error Err = Stream.SkipBlock())
  4213. return Err;
  4214. continue;
  4215. case llvm::BitstreamEntry::EndBlock:
  4216. return llvm::Error::success();
  4217. case llvm::BitstreamEntry::Error:
  4218. return llvm::createStringError(std::errc::illegal_byte_sequence,
  4219. "malformed block record in AST file");
  4220. case llvm::BitstreamEntry::Record:
  4221. break;
  4222. }
  4223. Record.clear();
  4224. StringRef Blob;
  4225. Expected<unsigned> MaybeRecCode =
  4226. Stream.readRecord(Entry.ID, Record, &Blob);
  4227. if (!MaybeRecCode)
  4228. return MaybeRecCode.takeError();
  4229. switch (MaybeRecCode.get()) {
  4230. case EXTENSION_METADATA: {
  4231. ModuleFileExtensionMetadata Metadata;
  4232. if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
  4233. return llvm::createStringError(
  4234. std::errc::illegal_byte_sequence,
  4235. "malformed EXTENSION_METADATA in AST file");
  4236. // Find a module file extension with this block name.
  4237. auto Known = ModuleFileExtensions.find(Metadata.BlockName);
  4238. if (Known == ModuleFileExtensions.end()) break;
  4239. // Form a reader.
  4240. if (auto Reader = Known->second->createExtensionReader(Metadata, *this,
  4241. F, Stream)) {
  4242. F.ExtensionReaders.push_back(std::move(Reader));
  4243. }
  4244. break;
  4245. }
  4246. }
  4247. }
  4248. return llvm::Error::success();
  4249. }
  4250. void ASTReader::InitializeContext() {
  4251. assert(ContextObj && "no context to initialize");
  4252. ASTContext &Context = *ContextObj;
  4253. // If there's a listener, notify them that we "read" the translation unit.
  4254. if (DeserializationListener)
  4255. DeserializationListener->DeclRead(PREDEF_DECL_TRANSLATION_UNIT_ID,
  4256. Context.getTranslationUnitDecl());
  4257. // FIXME: Find a better way to deal with collisions between these
  4258. // built-in types. Right now, we just ignore the problem.
  4259. // Load the special types.
  4260. if (SpecialTypes.size() >= NumSpecialTypeIDs) {
  4261. if (unsigned String = SpecialTypes[SPECIAL_TYPE_CF_CONSTANT_STRING]) {
  4262. if (!Context.CFConstantStringTypeDecl)
  4263. Context.setCFConstantStringType(GetType(String));
  4264. }
  4265. if (unsigned File = SpecialTypes[SPECIAL_TYPE_FILE]) {
  4266. QualType FileType = GetType(File);
  4267. if (FileType.isNull()) {
  4268. Error("FILE type is NULL");
  4269. return;
  4270. }
  4271. if (!Context.FILEDecl) {
  4272. if (const TypedefType *Typedef = FileType->getAs<TypedefType>())
  4273. Context.setFILEDecl(Typedef->getDecl());
  4274. else {
  4275. const TagType *Tag = FileType->getAs<TagType>();
  4276. if (!Tag) {
  4277. Error("Invalid FILE type in AST file");
  4278. return;
  4279. }
  4280. Context.setFILEDecl(Tag->getDecl());
  4281. }
  4282. }
  4283. }
  4284. if (unsigned Jmp_buf = SpecialTypes[SPECIAL_TYPE_JMP_BUF]) {
  4285. QualType Jmp_bufType = GetType(Jmp_buf);
  4286. if (Jmp_bufType.isNull()) {
  4287. Error("jmp_buf type is NULL");
  4288. return;
  4289. }
  4290. if (!Context.jmp_bufDecl) {
  4291. if (const TypedefType *Typedef = Jmp_bufType->getAs<TypedefType>())
  4292. Context.setjmp_bufDecl(Typedef->getDecl());
  4293. else {
  4294. const TagType *Tag = Jmp_bufType->getAs<TagType>();
  4295. if (!Tag) {
  4296. Error("Invalid jmp_buf type in AST file");
  4297. return;
  4298. }
  4299. Context.setjmp_bufDecl(Tag->getDecl());
  4300. }
  4301. }
  4302. }
  4303. if (unsigned Sigjmp_buf = SpecialTypes[SPECIAL_TYPE_SIGJMP_BUF]) {
  4304. QualType Sigjmp_bufType = GetType(Sigjmp_buf);
  4305. if (Sigjmp_bufType.isNull()) {
  4306. Error("sigjmp_buf type is NULL");
  4307. return;
  4308. }
  4309. if (!Context.sigjmp_bufDecl) {
  4310. if (const TypedefType *Typedef = Sigjmp_bufType->getAs<TypedefType>())
  4311. Context.setsigjmp_bufDecl(Typedef->getDecl());
  4312. else {
  4313. const TagType *Tag = Sigjmp_bufType->getAs<TagType>();
  4314. assert(Tag && "Invalid sigjmp_buf type in AST file");
  4315. Context.setsigjmp_bufDecl(Tag->getDecl());
  4316. }
  4317. }
  4318. }
  4319. if (unsigned ObjCIdRedef
  4320. = SpecialTypes[SPECIAL_TYPE_OBJC_ID_REDEFINITION]) {
  4321. if (Context.ObjCIdRedefinitionType.isNull())
  4322. Context.ObjCIdRedefinitionType = GetType(ObjCIdRedef);
  4323. }
  4324. if (unsigned ObjCClassRedef
  4325. = SpecialTypes[SPECIAL_TYPE_OBJC_CLASS_REDEFINITION]) {
  4326. if (Context.ObjCClassRedefinitionType.isNull())
  4327. Context.ObjCClassRedefinitionType = GetType(ObjCClassRedef);
  4328. }
  4329. if (unsigned ObjCSelRedef
  4330. = SpecialTypes[SPECIAL_TYPE_OBJC_SEL_REDEFINITION]) {
  4331. if (Context.ObjCSelRedefinitionType.isNull())
  4332. Context.ObjCSelRedefinitionType = GetType(ObjCSelRedef);
  4333. }
  4334. if (unsigned Ucontext_t = SpecialTypes[SPECIAL_TYPE_UCONTEXT_T]) {
  4335. QualType Ucontext_tType = GetType(Ucontext_t);
  4336. if (Ucontext_tType.isNull()) {
  4337. Error("ucontext_t type is NULL");
  4338. return;
  4339. }
  4340. if (!Context.ucontext_tDecl) {
  4341. if (const TypedefType *Typedef = Ucontext_tType->getAs<TypedefType>())
  4342. Context.setucontext_tDecl(Typedef->getDecl());
  4343. else {
  4344. const TagType *Tag = Ucontext_tType->getAs<TagType>();
  4345. assert(Tag && "Invalid ucontext_t type in AST file");
  4346. Context.setucontext_tDecl(Tag->getDecl());
  4347. }
  4348. }
  4349. }
  4350. }
  4351. ReadPragmaDiagnosticMappings(Context.getDiagnostics());
  4352. // If there were any CUDA special declarations, deserialize them.
  4353. if (!CUDASpecialDeclRefs.empty()) {
  4354. assert(CUDASpecialDeclRefs.size() == 1 && "More decl refs than expected!");
  4355. Context.setcudaConfigureCallDecl(
  4356. cast<FunctionDecl>(GetDecl(CUDASpecialDeclRefs[0])));
  4357. }
  4358. // Re-export any modules that were imported by a non-module AST file.
  4359. // FIXME: This does not make macro-only imports visible again.
  4360. for (auto &Import : ImportedModules) {
  4361. if (Module *Imported = getSubmodule(Import.ID)) {
  4362. makeModuleVisible(Imported, Module::AllVisible,
  4363. /*ImportLoc=*/Import.ImportLoc);
  4364. if (Import.ImportLoc.isValid())
  4365. PP.makeModuleVisible(Imported, Import.ImportLoc);
  4366. // This updates visibility for Preprocessor only. For Sema, which can be
  4367. // nullptr here, we do the same later, in UpdateSema().
  4368. }
  4369. }
  4370. }
  4371. void ASTReader::finalizeForWriting() {
  4372. // Nothing to do for now.
  4373. }
  4374. /// Reads and return the signature record from \p PCH's control block, or
  4375. /// else returns 0.
  4376. static ASTFileSignature readASTFileSignature(StringRef PCH) {
  4377. BitstreamCursor Stream(PCH);
  4378. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  4379. // FIXME this drops the error on the floor.
  4380. consumeError(std::move(Err));
  4381. return ASTFileSignature();
  4382. }
  4383. // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
  4384. if (SkipCursorToBlock(Stream, UNHASHED_CONTROL_BLOCK_ID))
  4385. return ASTFileSignature();
  4386. // Scan for SIGNATURE inside the diagnostic options block.
  4387. ASTReader::RecordData Record;
  4388. while (true) {
  4389. Expected<llvm::BitstreamEntry> MaybeEntry =
  4390. Stream.advanceSkippingSubblocks();
  4391. if (!MaybeEntry) {
  4392. // FIXME this drops the error on the floor.
  4393. consumeError(MaybeEntry.takeError());
  4394. return ASTFileSignature();
  4395. }
  4396. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4397. if (Entry.Kind != llvm::BitstreamEntry::Record)
  4398. return ASTFileSignature();
  4399. Record.clear();
  4400. StringRef Blob;
  4401. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
  4402. if (!MaybeRecord) {
  4403. // FIXME this drops the error on the floor.
  4404. consumeError(MaybeRecord.takeError());
  4405. return ASTFileSignature();
  4406. }
  4407. if (SIGNATURE == MaybeRecord.get())
  4408. return ASTFileSignature::create(Record.begin(),
  4409. Record.begin() + ASTFileSignature::size);
  4410. }
  4411. }
  4412. /// Retrieve the name of the original source file name
  4413. /// directly from the AST file, without actually loading the AST
  4414. /// file.
  4415. std::string ASTReader::getOriginalSourceFile(
  4416. const std::string &ASTFileName, FileManager &FileMgr,
  4417. const PCHContainerReader &PCHContainerRdr, DiagnosticsEngine &Diags) {
  4418. // Open the AST file.
  4419. auto Buffer = FileMgr.getBufferForFile(ASTFileName);
  4420. if (!Buffer) {
  4421. Diags.Report(diag::err_fe_unable_to_read_pch_file)
  4422. << ASTFileName << Buffer.getError().message();
  4423. return std::string();
  4424. }
  4425. // Initialize the stream
  4426. BitstreamCursor Stream(PCHContainerRdr.ExtractPCH(**Buffer));
  4427. // Sniff for the signature.
  4428. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  4429. Diags.Report(diag::err_fe_not_a_pch_file) << ASTFileName << std::move(Err);
  4430. return std::string();
  4431. }
  4432. // Scan for the CONTROL_BLOCK_ID block.
  4433. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID)) {
  4434. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  4435. return std::string();
  4436. }
  4437. // Scan for ORIGINAL_FILE inside the control block.
  4438. RecordData Record;
  4439. while (true) {
  4440. Expected<llvm::BitstreamEntry> MaybeEntry =
  4441. Stream.advanceSkippingSubblocks();
  4442. if (!MaybeEntry) {
  4443. // FIXME this drops errors on the floor.
  4444. consumeError(MaybeEntry.takeError());
  4445. return std::string();
  4446. }
  4447. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4448. if (Entry.Kind == llvm::BitstreamEntry::EndBlock)
  4449. return std::string();
  4450. if (Entry.Kind != llvm::BitstreamEntry::Record) {
  4451. Diags.Report(diag::err_fe_pch_malformed_block) << ASTFileName;
  4452. return std::string();
  4453. }
  4454. Record.clear();
  4455. StringRef Blob;
  4456. Expected<unsigned> MaybeRecord = Stream.readRecord(Entry.ID, Record, &Blob);
  4457. if (!MaybeRecord) {
  4458. // FIXME this drops the errors on the floor.
  4459. consumeError(MaybeRecord.takeError());
  4460. return std::string();
  4461. }
  4462. if (ORIGINAL_FILE == MaybeRecord.get())
  4463. return Blob.str();
  4464. }
  4465. }
  4466. namespace {
  4467. class SimplePCHValidator : public ASTReaderListener {
  4468. const LangOptions &ExistingLangOpts;
  4469. const TargetOptions &ExistingTargetOpts;
  4470. const PreprocessorOptions &ExistingPPOpts;
  4471. std::string ExistingModuleCachePath;
  4472. FileManager &FileMgr;
  4473. public:
  4474. SimplePCHValidator(const LangOptions &ExistingLangOpts,
  4475. const TargetOptions &ExistingTargetOpts,
  4476. const PreprocessorOptions &ExistingPPOpts,
  4477. StringRef ExistingModuleCachePath, FileManager &FileMgr)
  4478. : ExistingLangOpts(ExistingLangOpts),
  4479. ExistingTargetOpts(ExistingTargetOpts),
  4480. ExistingPPOpts(ExistingPPOpts),
  4481. ExistingModuleCachePath(ExistingModuleCachePath), FileMgr(FileMgr) {}
  4482. bool ReadLanguageOptions(const LangOptions &LangOpts, bool Complain,
  4483. bool AllowCompatibleDifferences) override {
  4484. return checkLanguageOptions(ExistingLangOpts, LangOpts, nullptr,
  4485. AllowCompatibleDifferences);
  4486. }
  4487. bool ReadTargetOptions(const TargetOptions &TargetOpts, bool Complain,
  4488. bool AllowCompatibleDifferences) override {
  4489. return checkTargetOptions(ExistingTargetOpts, TargetOpts, nullptr,
  4490. AllowCompatibleDifferences);
  4491. }
  4492. bool ReadHeaderSearchOptions(const HeaderSearchOptions &HSOpts,
  4493. StringRef SpecificModuleCachePath,
  4494. bool Complain) override {
  4495. return checkHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  4496. ExistingModuleCachePath, nullptr,
  4497. ExistingLangOpts, ExistingPPOpts);
  4498. }
  4499. bool ReadPreprocessorOptions(const PreprocessorOptions &PPOpts,
  4500. bool Complain,
  4501. std::string &SuggestedPredefines) override {
  4502. return checkPreprocessorOptions(ExistingPPOpts, PPOpts, nullptr, FileMgr,
  4503. SuggestedPredefines, ExistingLangOpts);
  4504. }
  4505. };
  4506. } // namespace
  4507. bool ASTReader::readASTFileControlBlock(
  4508. StringRef Filename, FileManager &FileMgr,
  4509. const PCHContainerReader &PCHContainerRdr,
  4510. bool FindModuleFileExtensions,
  4511. ASTReaderListener &Listener, bool ValidateDiagnosticOptions) {
  4512. // Open the AST file.
  4513. // FIXME: This allows use of the VFS; we do not allow use of the
  4514. // VFS when actually loading a module.
  4515. auto Buffer = FileMgr.getBufferForFile(Filename);
  4516. if (!Buffer) {
  4517. return true;
  4518. }
  4519. // Initialize the stream
  4520. StringRef Bytes = PCHContainerRdr.ExtractPCH(**Buffer);
  4521. BitstreamCursor Stream(Bytes);
  4522. // Sniff for the signature.
  4523. if (llvm::Error Err = doesntStartWithASTFileMagic(Stream)) {
  4524. consumeError(std::move(Err)); // FIXME this drops errors on the floor.
  4525. return true;
  4526. }
  4527. // Scan for the CONTROL_BLOCK_ID block.
  4528. if (SkipCursorToBlock(Stream, CONTROL_BLOCK_ID))
  4529. return true;
  4530. bool NeedsInputFiles = Listener.needsInputFileVisitation();
  4531. bool NeedsSystemInputFiles = Listener.needsSystemInputFileVisitation();
  4532. bool NeedsImports = Listener.needsImportVisitation();
  4533. BitstreamCursor InputFilesCursor;
  4534. RecordData Record;
  4535. std::string ModuleDir;
  4536. bool DoneWithControlBlock = false;
  4537. while (!DoneWithControlBlock) {
  4538. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4539. if (!MaybeEntry) {
  4540. // FIXME this drops the error on the floor.
  4541. consumeError(MaybeEntry.takeError());
  4542. return true;
  4543. }
  4544. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4545. switch (Entry.Kind) {
  4546. case llvm::BitstreamEntry::SubBlock: {
  4547. switch (Entry.ID) {
  4548. case OPTIONS_BLOCK_ID: {
  4549. std::string IgnoredSuggestedPredefines;
  4550. if (ReadOptionsBlock(Stream, ARR_ConfigurationMismatch | ARR_OutOfDate,
  4551. /*AllowCompatibleConfigurationMismatch*/ false,
  4552. Listener, IgnoredSuggestedPredefines) != Success)
  4553. return true;
  4554. break;
  4555. }
  4556. case INPUT_FILES_BLOCK_ID:
  4557. InputFilesCursor = Stream;
  4558. if (llvm::Error Err = Stream.SkipBlock()) {
  4559. // FIXME this drops the error on the floor.
  4560. consumeError(std::move(Err));
  4561. return true;
  4562. }
  4563. if (NeedsInputFiles &&
  4564. ReadBlockAbbrevs(InputFilesCursor, INPUT_FILES_BLOCK_ID))
  4565. return true;
  4566. break;
  4567. default:
  4568. if (llvm::Error Err = Stream.SkipBlock()) {
  4569. // FIXME this drops the error on the floor.
  4570. consumeError(std::move(Err));
  4571. return true;
  4572. }
  4573. break;
  4574. }
  4575. continue;
  4576. }
  4577. case llvm::BitstreamEntry::EndBlock:
  4578. DoneWithControlBlock = true;
  4579. break;
  4580. case llvm::BitstreamEntry::Error:
  4581. return true;
  4582. case llvm::BitstreamEntry::Record:
  4583. break;
  4584. }
  4585. if (DoneWithControlBlock) break;
  4586. Record.clear();
  4587. StringRef Blob;
  4588. Expected<unsigned> MaybeRecCode =
  4589. Stream.readRecord(Entry.ID, Record, &Blob);
  4590. if (!MaybeRecCode) {
  4591. // FIXME this drops the error.
  4592. return Failure;
  4593. }
  4594. switch ((ControlRecordTypes)MaybeRecCode.get()) {
  4595. case METADATA:
  4596. if (Record[0] != VERSION_MAJOR)
  4597. return true;
  4598. if (Listener.ReadFullVersionInformation(Blob))
  4599. return true;
  4600. break;
  4601. case MODULE_NAME:
  4602. Listener.ReadModuleName(Blob);
  4603. break;
  4604. case MODULE_DIRECTORY:
  4605. ModuleDir = std::string(Blob);
  4606. break;
  4607. case MODULE_MAP_FILE: {
  4608. unsigned Idx = 0;
  4609. auto Path = ReadString(Record, Idx);
  4610. ResolveImportedPath(Path, ModuleDir);
  4611. Listener.ReadModuleMapFile(Path);
  4612. break;
  4613. }
  4614. case INPUT_FILE_OFFSETS: {
  4615. if (!NeedsInputFiles)
  4616. break;
  4617. unsigned NumInputFiles = Record[0];
  4618. unsigned NumUserFiles = Record[1];
  4619. const llvm::support::unaligned_uint64_t *InputFileOffs =
  4620. (const llvm::support::unaligned_uint64_t *)Blob.data();
  4621. for (unsigned I = 0; I != NumInputFiles; ++I) {
  4622. // Go find this input file.
  4623. bool isSystemFile = I >= NumUserFiles;
  4624. if (isSystemFile && !NeedsSystemInputFiles)
  4625. break; // the rest are system input files
  4626. BitstreamCursor &Cursor = InputFilesCursor;
  4627. SavedStreamPosition SavedPosition(Cursor);
  4628. if (llvm::Error Err = Cursor.JumpToBit(InputFileOffs[I])) {
  4629. // FIXME this drops errors on the floor.
  4630. consumeError(std::move(Err));
  4631. }
  4632. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  4633. if (!MaybeCode) {
  4634. // FIXME this drops errors on the floor.
  4635. consumeError(MaybeCode.takeError());
  4636. }
  4637. unsigned Code = MaybeCode.get();
  4638. RecordData Record;
  4639. StringRef Blob;
  4640. bool shouldContinue = false;
  4641. Expected<unsigned> MaybeRecordType =
  4642. Cursor.readRecord(Code, Record, &Blob);
  4643. if (!MaybeRecordType) {
  4644. // FIXME this drops errors on the floor.
  4645. consumeError(MaybeRecordType.takeError());
  4646. }
  4647. switch ((InputFileRecordTypes)MaybeRecordType.get()) {
  4648. case INPUT_FILE_HASH:
  4649. break;
  4650. case INPUT_FILE:
  4651. bool Overridden = static_cast<bool>(Record[3]);
  4652. std::string Filename = std::string(Blob);
  4653. ResolveImportedPath(Filename, ModuleDir);
  4654. shouldContinue = Listener.visitInputFile(
  4655. Filename, isSystemFile, Overridden, /*IsExplicitModule*/false);
  4656. break;
  4657. }
  4658. if (!shouldContinue)
  4659. break;
  4660. }
  4661. break;
  4662. }
  4663. case IMPORTS: {
  4664. if (!NeedsImports)
  4665. break;
  4666. unsigned Idx = 0, N = Record.size();
  4667. while (Idx < N) {
  4668. // Read information about the AST file.
  4669. Idx +=
  4670. 1 + 1 + 1 + 1 +
  4671. ASTFileSignature::size; // Kind, ImportLoc, Size, ModTime, Signature
  4672. std::string ModuleName = ReadString(Record, Idx);
  4673. std::string Filename = ReadString(Record, Idx);
  4674. ResolveImportedPath(Filename, ModuleDir);
  4675. Listener.visitImport(ModuleName, Filename);
  4676. }
  4677. break;
  4678. }
  4679. default:
  4680. // No other validation to perform.
  4681. break;
  4682. }
  4683. }
  4684. // Look for module file extension blocks, if requested.
  4685. if (FindModuleFileExtensions) {
  4686. BitstreamCursor SavedStream = Stream;
  4687. while (!SkipCursorToBlock(Stream, EXTENSION_BLOCK_ID)) {
  4688. bool DoneWithExtensionBlock = false;
  4689. while (!DoneWithExtensionBlock) {
  4690. Expected<llvm::BitstreamEntry> MaybeEntry = Stream.advance();
  4691. if (!MaybeEntry) {
  4692. // FIXME this drops the error.
  4693. return true;
  4694. }
  4695. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4696. switch (Entry.Kind) {
  4697. case llvm::BitstreamEntry::SubBlock:
  4698. if (llvm::Error Err = Stream.SkipBlock()) {
  4699. // FIXME this drops the error on the floor.
  4700. consumeError(std::move(Err));
  4701. return true;
  4702. }
  4703. continue;
  4704. case llvm::BitstreamEntry::EndBlock:
  4705. DoneWithExtensionBlock = true;
  4706. continue;
  4707. case llvm::BitstreamEntry::Error:
  4708. return true;
  4709. case llvm::BitstreamEntry::Record:
  4710. break;
  4711. }
  4712. Record.clear();
  4713. StringRef Blob;
  4714. Expected<unsigned> MaybeRecCode =
  4715. Stream.readRecord(Entry.ID, Record, &Blob);
  4716. if (!MaybeRecCode) {
  4717. // FIXME this drops the error.
  4718. return true;
  4719. }
  4720. switch (MaybeRecCode.get()) {
  4721. case EXTENSION_METADATA: {
  4722. ModuleFileExtensionMetadata Metadata;
  4723. if (parseModuleFileExtensionMetadata(Record, Blob, Metadata))
  4724. return true;
  4725. Listener.readModuleFileExtension(Metadata);
  4726. break;
  4727. }
  4728. }
  4729. }
  4730. }
  4731. Stream = SavedStream;
  4732. }
  4733. // Scan for the UNHASHED_CONTROL_BLOCK_ID block.
  4734. if (readUnhashedControlBlockImpl(
  4735. nullptr, Bytes, ARR_ConfigurationMismatch | ARR_OutOfDate,
  4736. /*AllowCompatibleConfigurationMismatch*/ false, &Listener,
  4737. ValidateDiagnosticOptions) != Success)
  4738. return true;
  4739. return false;
  4740. }
  4741. bool ASTReader::isAcceptableASTFile(StringRef Filename, FileManager &FileMgr,
  4742. const PCHContainerReader &PCHContainerRdr,
  4743. const LangOptions &LangOpts,
  4744. const TargetOptions &TargetOpts,
  4745. const PreprocessorOptions &PPOpts,
  4746. StringRef ExistingModuleCachePath) {
  4747. SimplePCHValidator validator(LangOpts, TargetOpts, PPOpts,
  4748. ExistingModuleCachePath, FileMgr);
  4749. return !readASTFileControlBlock(Filename, FileMgr, PCHContainerRdr,
  4750. /*FindModuleFileExtensions=*/false,
  4751. validator,
  4752. /*ValidateDiagnosticOptions=*/true);
  4753. }
  4754. llvm::Error ASTReader::ReadSubmoduleBlock(ModuleFile &F,
  4755. unsigned ClientLoadCapabilities) {
  4756. // Enter the submodule block.
  4757. if (llvm::Error Err = F.Stream.EnterSubBlock(SUBMODULE_BLOCK_ID))
  4758. return Err;
  4759. ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  4760. bool First = true;
  4761. Module *CurrentModule = nullptr;
  4762. RecordData Record;
  4763. while (true) {
  4764. Expected<llvm::BitstreamEntry> MaybeEntry =
  4765. F.Stream.advanceSkippingSubblocks();
  4766. if (!MaybeEntry)
  4767. return MaybeEntry.takeError();
  4768. llvm::BitstreamEntry Entry = MaybeEntry.get();
  4769. switch (Entry.Kind) {
  4770. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  4771. case llvm::BitstreamEntry::Error:
  4772. return llvm::createStringError(std::errc::illegal_byte_sequence,
  4773. "malformed block record in AST file");
  4774. case llvm::BitstreamEntry::EndBlock:
  4775. return llvm::Error::success();
  4776. case llvm::BitstreamEntry::Record:
  4777. // The interesting case.
  4778. break;
  4779. }
  4780. // Read a record.
  4781. StringRef Blob;
  4782. Record.clear();
  4783. Expected<unsigned> MaybeKind = F.Stream.readRecord(Entry.ID, Record, &Blob);
  4784. if (!MaybeKind)
  4785. return MaybeKind.takeError();
  4786. unsigned Kind = MaybeKind.get();
  4787. if ((Kind == SUBMODULE_METADATA) != First)
  4788. return llvm::createStringError(
  4789. std::errc::illegal_byte_sequence,
  4790. "submodule metadata record should be at beginning of block");
  4791. First = false;
  4792. // Submodule information is only valid if we have a current module.
  4793. // FIXME: Should we error on these cases?
  4794. if (!CurrentModule && Kind != SUBMODULE_METADATA &&
  4795. Kind != SUBMODULE_DEFINITION)
  4796. continue;
  4797. switch (Kind) {
  4798. default: // Default behavior: ignore.
  4799. break;
  4800. case SUBMODULE_DEFINITION: {
  4801. if (Record.size() < 12)
  4802. return llvm::createStringError(std::errc::illegal_byte_sequence,
  4803. "malformed module definition");
  4804. StringRef Name = Blob;
  4805. unsigned Idx = 0;
  4806. SubmoduleID GlobalID = getGlobalSubmoduleID(F, Record[Idx++]);
  4807. SubmoduleID Parent = getGlobalSubmoduleID(F, Record[Idx++]);
  4808. Module::ModuleKind Kind = (Module::ModuleKind)Record[Idx++];
  4809. bool IsFramework = Record[Idx++];
  4810. bool IsExplicit = Record[Idx++];
  4811. bool IsSystem = Record[Idx++];
  4812. bool IsExternC = Record[Idx++];
  4813. bool InferSubmodules = Record[Idx++];
  4814. bool InferExplicitSubmodules = Record[Idx++];
  4815. bool InferExportWildcard = Record[Idx++];
  4816. bool ConfigMacrosExhaustive = Record[Idx++];
  4817. bool ModuleMapIsPrivate = Record[Idx++];
  4818. Module *ParentModule = nullptr;
  4819. if (Parent)
  4820. ParentModule = getSubmodule(Parent);
  4821. // Retrieve this (sub)module from the module map, creating it if
  4822. // necessary.
  4823. CurrentModule =
  4824. ModMap.findOrCreateModule(Name, ParentModule, IsFramework, IsExplicit)
  4825. .first;
  4826. // FIXME: set the definition loc for CurrentModule, or call
  4827. // ModMap.setInferredModuleAllowedBy()
  4828. SubmoduleID GlobalIndex = GlobalID - NUM_PREDEF_SUBMODULE_IDS;
  4829. if (GlobalIndex >= SubmodulesLoaded.size() ||
  4830. SubmodulesLoaded[GlobalIndex])
  4831. return llvm::createStringError(std::errc::invalid_argument,
  4832. "too many submodules");
  4833. if (!ParentModule) {
  4834. if (const FileEntry *CurFile = CurrentModule->getASTFile()) {
  4835. // Don't emit module relocation error if we have -fno-validate-pch
  4836. if (!bool(PP.getPreprocessorOpts().DisablePCHOrModuleValidation &
  4837. DisableValidationForModuleKind::Module) &&
  4838. CurFile != F.File) {
  4839. auto ConflictError =
  4840. PartialDiagnostic(diag::err_module_file_conflict,
  4841. ContextObj->DiagAllocator)
  4842. << CurrentModule->getTopLevelModuleName() << CurFile->getName()
  4843. << F.File->getName();
  4844. return DiagnosticError::create(CurrentImportLoc, ConflictError);
  4845. }
  4846. }
  4847. F.DidReadTopLevelSubmodule = true;
  4848. CurrentModule->setASTFile(F.File);
  4849. CurrentModule->PresumedModuleMapFile = F.ModuleMapPath;
  4850. }
  4851. CurrentModule->Kind = Kind;
  4852. CurrentModule->Signature = F.Signature;
  4853. CurrentModule->IsFromModuleFile = true;
  4854. CurrentModule->IsSystem = IsSystem || CurrentModule->IsSystem;
  4855. CurrentModule->IsExternC = IsExternC;
  4856. CurrentModule->InferSubmodules = InferSubmodules;
  4857. CurrentModule->InferExplicitSubmodules = InferExplicitSubmodules;
  4858. CurrentModule->InferExportWildcard = InferExportWildcard;
  4859. CurrentModule->ConfigMacrosExhaustive = ConfigMacrosExhaustive;
  4860. CurrentModule->ModuleMapIsPrivate = ModuleMapIsPrivate;
  4861. if (DeserializationListener)
  4862. DeserializationListener->ModuleRead(GlobalID, CurrentModule);
  4863. SubmodulesLoaded[GlobalIndex] = CurrentModule;
  4864. // Clear out data that will be replaced by what is in the module file.
  4865. CurrentModule->LinkLibraries.clear();
  4866. CurrentModule->ConfigMacros.clear();
  4867. CurrentModule->UnresolvedConflicts.clear();
  4868. CurrentModule->Conflicts.clear();
  4869. // The module is available unless it's missing a requirement; relevant
  4870. // requirements will be (re-)added by SUBMODULE_REQUIRES records.
  4871. // Missing headers that were present when the module was built do not
  4872. // make it unavailable -- if we got this far, this must be an explicitly
  4873. // imported module file.
  4874. CurrentModule->Requirements.clear();
  4875. CurrentModule->MissingHeaders.clear();
  4876. CurrentModule->IsUnimportable =
  4877. ParentModule && ParentModule->IsUnimportable;
  4878. CurrentModule->IsAvailable = !CurrentModule->IsUnimportable;
  4879. break;
  4880. }
  4881. case SUBMODULE_UMBRELLA_HEADER: {
  4882. // FIXME: This doesn't work for framework modules as `Filename` is the
  4883. // name as written in the module file and does not include
  4884. // `Headers/`, so this path will never exist.
  4885. std::string Filename = std::string(Blob);
  4886. ResolveImportedPath(F, Filename);
  4887. if (auto Umbrella = PP.getFileManager().getFile(Filename)) {
  4888. if (!CurrentModule->getUmbrellaHeader()) {
  4889. // FIXME: NameAsWritten
  4890. ModMap.setUmbrellaHeader(CurrentModule, *Umbrella, Blob, "");
  4891. }
  4892. // Note that it's too late at this point to return out of date if the
  4893. // name from the PCM doesn't match up with the one in the module map,
  4894. // but also quite unlikely since we will have already checked the
  4895. // modification time and size of the module map file itself.
  4896. }
  4897. break;
  4898. }
  4899. case SUBMODULE_HEADER:
  4900. case SUBMODULE_EXCLUDED_HEADER:
  4901. case SUBMODULE_PRIVATE_HEADER:
  4902. // We lazily associate headers with their modules via the HeaderInfo table.
  4903. // FIXME: Re-evaluate this section; maybe only store InputFile IDs instead
  4904. // of complete filenames or remove it entirely.
  4905. break;
  4906. case SUBMODULE_TEXTUAL_HEADER:
  4907. case SUBMODULE_PRIVATE_TEXTUAL_HEADER:
  4908. // FIXME: Textual headers are not marked in the HeaderInfo table. Load
  4909. // them here.
  4910. break;
  4911. case SUBMODULE_TOPHEADER:
  4912. CurrentModule->addTopHeaderFilename(Blob);
  4913. break;
  4914. case SUBMODULE_UMBRELLA_DIR: {
  4915. // See comments in SUBMODULE_UMBRELLA_HEADER
  4916. std::string Dirname = std::string(Blob);
  4917. ResolveImportedPath(F, Dirname);
  4918. if (auto Umbrella = PP.getFileManager().getDirectory(Dirname)) {
  4919. if (!CurrentModule->getUmbrellaDir()) {
  4920. // FIXME: NameAsWritten
  4921. ModMap.setUmbrellaDir(CurrentModule, *Umbrella, Blob, "");
  4922. }
  4923. }
  4924. break;
  4925. }
  4926. case SUBMODULE_METADATA: {
  4927. F.BaseSubmoduleID = getTotalNumSubmodules();
  4928. F.LocalNumSubmodules = Record[0];
  4929. unsigned LocalBaseSubmoduleID = Record[1];
  4930. if (F.LocalNumSubmodules > 0) {
  4931. // Introduce the global -> local mapping for submodules within this
  4932. // module.
  4933. GlobalSubmoduleMap.insert(std::make_pair(getTotalNumSubmodules()+1,&F));
  4934. // Introduce the local -> global mapping for submodules within this
  4935. // module.
  4936. F.SubmoduleRemap.insertOrReplace(
  4937. std::make_pair(LocalBaseSubmoduleID,
  4938. F.BaseSubmoduleID - LocalBaseSubmoduleID));
  4939. SubmodulesLoaded.resize(SubmodulesLoaded.size() + F.LocalNumSubmodules);
  4940. }
  4941. break;
  4942. }
  4943. case SUBMODULE_IMPORTS:
  4944. for (unsigned Idx = 0; Idx != Record.size(); ++Idx) {
  4945. UnresolvedModuleRef Unresolved;
  4946. Unresolved.File = &F;
  4947. Unresolved.Mod = CurrentModule;
  4948. Unresolved.ID = Record[Idx];
  4949. Unresolved.Kind = UnresolvedModuleRef::Import;
  4950. Unresolved.IsWildcard = false;
  4951. UnresolvedModuleRefs.push_back(Unresolved);
  4952. }
  4953. break;
  4954. case SUBMODULE_EXPORTS:
  4955. for (unsigned Idx = 0; Idx + 1 < Record.size(); Idx += 2) {
  4956. UnresolvedModuleRef Unresolved;
  4957. Unresolved.File = &F;
  4958. Unresolved.Mod = CurrentModule;
  4959. Unresolved.ID = Record[Idx];
  4960. Unresolved.Kind = UnresolvedModuleRef::Export;
  4961. Unresolved.IsWildcard = Record[Idx + 1];
  4962. UnresolvedModuleRefs.push_back(Unresolved);
  4963. }
  4964. // Once we've loaded the set of exports, there's no reason to keep
  4965. // the parsed, unresolved exports around.
  4966. CurrentModule->UnresolvedExports.clear();
  4967. break;
  4968. case SUBMODULE_REQUIRES:
  4969. CurrentModule->addRequirement(Blob, Record[0], PP.getLangOpts(),
  4970. PP.getTargetInfo());
  4971. break;
  4972. case SUBMODULE_LINK_LIBRARY:
  4973. ModMap.resolveLinkAsDependencies(CurrentModule);
  4974. CurrentModule->LinkLibraries.push_back(
  4975. Module::LinkLibrary(std::string(Blob), Record[0]));
  4976. break;
  4977. case SUBMODULE_CONFIG_MACRO:
  4978. CurrentModule->ConfigMacros.push_back(Blob.str());
  4979. break;
  4980. case SUBMODULE_CONFLICT: {
  4981. UnresolvedModuleRef Unresolved;
  4982. Unresolved.File = &F;
  4983. Unresolved.Mod = CurrentModule;
  4984. Unresolved.ID = Record[0];
  4985. Unresolved.Kind = UnresolvedModuleRef::Conflict;
  4986. Unresolved.IsWildcard = false;
  4987. Unresolved.String = Blob;
  4988. UnresolvedModuleRefs.push_back(Unresolved);
  4989. break;
  4990. }
  4991. case SUBMODULE_INITIALIZERS: {
  4992. if (!ContextObj)
  4993. break;
  4994. SmallVector<uint32_t, 16> Inits;
  4995. for (auto &ID : Record)
  4996. Inits.push_back(getGlobalDeclID(F, ID));
  4997. ContextObj->addLazyModuleInitializers(CurrentModule, Inits);
  4998. break;
  4999. }
  5000. case SUBMODULE_EXPORT_AS:
  5001. CurrentModule->ExportAsModule = Blob.str();
  5002. ModMap.addLinkAsDependency(CurrentModule);
  5003. break;
  5004. }
  5005. }
  5006. }
  5007. /// Parse the record that corresponds to a LangOptions data
  5008. /// structure.
  5009. ///
  5010. /// This routine parses the language options from the AST file and then gives
  5011. /// them to the AST listener if one is set.
  5012. ///
  5013. /// \returns true if the listener deems the file unacceptable, false otherwise.
  5014. bool ASTReader::ParseLanguageOptions(const RecordData &Record,
  5015. bool Complain,
  5016. ASTReaderListener &Listener,
  5017. bool AllowCompatibleDifferences) {
  5018. LangOptions LangOpts;
  5019. unsigned Idx = 0;
  5020. #define LANGOPT(Name, Bits, Default, Description) \
  5021. LangOpts.Name = Record[Idx++];
  5022. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  5023. LangOpts.set##Name(static_cast<LangOptions::Type>(Record[Idx++]));
  5024. #include "clang/Basic/LangOptions.def"
  5025. #define SANITIZER(NAME, ID) \
  5026. LangOpts.Sanitize.set(SanitizerKind::ID, Record[Idx++]);
  5027. #include "clang/Basic/Sanitizers.def"
  5028. for (unsigned N = Record[Idx++]; N; --N)
  5029. LangOpts.ModuleFeatures.push_back(ReadString(Record, Idx));
  5030. ObjCRuntime::Kind runtimeKind = (ObjCRuntime::Kind) Record[Idx++];
  5031. VersionTuple runtimeVersion = ReadVersionTuple(Record, Idx);
  5032. LangOpts.ObjCRuntime = ObjCRuntime(runtimeKind, runtimeVersion);
  5033. LangOpts.CurrentModule = ReadString(Record, Idx);
  5034. // Comment options.
  5035. for (unsigned N = Record[Idx++]; N; --N) {
  5036. LangOpts.CommentOpts.BlockCommandNames.push_back(
  5037. ReadString(Record, Idx));
  5038. }
  5039. LangOpts.CommentOpts.ParseAllComments = Record[Idx++];
  5040. // OpenMP offloading options.
  5041. for (unsigned N = Record[Idx++]; N; --N) {
  5042. LangOpts.OMPTargetTriples.push_back(llvm::Triple(ReadString(Record, Idx)));
  5043. }
  5044. LangOpts.OMPHostIRFile = ReadString(Record, Idx);
  5045. return Listener.ReadLanguageOptions(LangOpts, Complain,
  5046. AllowCompatibleDifferences);
  5047. }
  5048. bool ASTReader::ParseTargetOptions(const RecordData &Record, bool Complain,
  5049. ASTReaderListener &Listener,
  5050. bool AllowCompatibleDifferences) {
  5051. unsigned Idx = 0;
  5052. TargetOptions TargetOpts;
  5053. TargetOpts.Triple = ReadString(Record, Idx);
  5054. TargetOpts.CPU = ReadString(Record, Idx);
  5055. TargetOpts.TuneCPU = ReadString(Record, Idx);
  5056. TargetOpts.ABI = ReadString(Record, Idx);
  5057. for (unsigned N = Record[Idx++]; N; --N) {
  5058. TargetOpts.FeaturesAsWritten.push_back(ReadString(Record, Idx));
  5059. }
  5060. for (unsigned N = Record[Idx++]; N; --N) {
  5061. TargetOpts.Features.push_back(ReadString(Record, Idx));
  5062. }
  5063. return Listener.ReadTargetOptions(TargetOpts, Complain,
  5064. AllowCompatibleDifferences);
  5065. }
  5066. bool ASTReader::ParseDiagnosticOptions(const RecordData &Record, bool Complain,
  5067. ASTReaderListener &Listener) {
  5068. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts(new DiagnosticOptions);
  5069. unsigned Idx = 0;
  5070. #define DIAGOPT(Name, Bits, Default) DiagOpts->Name = Record[Idx++];
  5071. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  5072. DiagOpts->set##Name(static_cast<Type>(Record[Idx++]));
  5073. #include "clang/Basic/DiagnosticOptions.def"
  5074. for (unsigned N = Record[Idx++]; N; --N)
  5075. DiagOpts->Warnings.push_back(ReadString(Record, Idx));
  5076. for (unsigned N = Record[Idx++]; N; --N)
  5077. DiagOpts->Remarks.push_back(ReadString(Record, Idx));
  5078. return Listener.ReadDiagnosticOptions(DiagOpts, Complain);
  5079. }
  5080. bool ASTReader::ParseFileSystemOptions(const RecordData &Record, bool Complain,
  5081. ASTReaderListener &Listener) {
  5082. FileSystemOptions FSOpts;
  5083. unsigned Idx = 0;
  5084. FSOpts.WorkingDir = ReadString(Record, Idx);
  5085. return Listener.ReadFileSystemOptions(FSOpts, Complain);
  5086. }
  5087. bool ASTReader::ParseHeaderSearchOptions(const RecordData &Record,
  5088. bool Complain,
  5089. ASTReaderListener &Listener) {
  5090. HeaderSearchOptions HSOpts;
  5091. unsigned Idx = 0;
  5092. HSOpts.Sysroot = ReadString(Record, Idx);
  5093. // Include entries.
  5094. for (unsigned N = Record[Idx++]; N; --N) {
  5095. std::string Path = ReadString(Record, Idx);
  5096. frontend::IncludeDirGroup Group
  5097. = static_cast<frontend::IncludeDirGroup>(Record[Idx++]);
  5098. bool IsFramework = Record[Idx++];
  5099. bool IgnoreSysRoot = Record[Idx++];
  5100. HSOpts.UserEntries.emplace_back(std::move(Path), Group, IsFramework,
  5101. IgnoreSysRoot);
  5102. }
  5103. // System header prefixes.
  5104. for (unsigned N = Record[Idx++]; N; --N) {
  5105. std::string Prefix = ReadString(Record, Idx);
  5106. bool IsSystemHeader = Record[Idx++];
  5107. HSOpts.SystemHeaderPrefixes.emplace_back(std::move(Prefix), IsSystemHeader);
  5108. }
  5109. HSOpts.ResourceDir = ReadString(Record, Idx);
  5110. HSOpts.ModuleCachePath = ReadString(Record, Idx);
  5111. HSOpts.ModuleUserBuildPath = ReadString(Record, Idx);
  5112. HSOpts.DisableModuleHash = Record[Idx++];
  5113. HSOpts.ImplicitModuleMaps = Record[Idx++];
  5114. HSOpts.ModuleMapFileHomeIsCwd = Record[Idx++];
  5115. HSOpts.EnablePrebuiltImplicitModules = Record[Idx++];
  5116. HSOpts.UseBuiltinIncludes = Record[Idx++];
  5117. HSOpts.UseStandardSystemIncludes = Record[Idx++];
  5118. HSOpts.UseStandardCXXIncludes = Record[Idx++];
  5119. HSOpts.UseLibcxx = Record[Idx++];
  5120. std::string SpecificModuleCachePath = ReadString(Record, Idx);
  5121. return Listener.ReadHeaderSearchOptions(HSOpts, SpecificModuleCachePath,
  5122. Complain);
  5123. }
  5124. bool ASTReader::ParsePreprocessorOptions(const RecordData &Record,
  5125. bool Complain,
  5126. ASTReaderListener &Listener,
  5127. std::string &SuggestedPredefines) {
  5128. PreprocessorOptions PPOpts;
  5129. unsigned Idx = 0;
  5130. // Macro definitions/undefs
  5131. for (unsigned N = Record[Idx++]; N; --N) {
  5132. std::string Macro = ReadString(Record, Idx);
  5133. bool IsUndef = Record[Idx++];
  5134. PPOpts.Macros.push_back(std::make_pair(Macro, IsUndef));
  5135. }
  5136. // Includes
  5137. for (unsigned N = Record[Idx++]; N; --N) {
  5138. PPOpts.Includes.push_back(ReadString(Record, Idx));
  5139. }
  5140. // Macro Includes
  5141. for (unsigned N = Record[Idx++]; N; --N) {
  5142. PPOpts.MacroIncludes.push_back(ReadString(Record, Idx));
  5143. }
  5144. PPOpts.UsePredefines = Record[Idx++];
  5145. PPOpts.DetailedRecord = Record[Idx++];
  5146. PPOpts.ImplicitPCHInclude = ReadString(Record, Idx);
  5147. PPOpts.ObjCXXARCStandardLibrary =
  5148. static_cast<ObjCXXARCStandardLibraryKind>(Record[Idx++]);
  5149. SuggestedPredefines.clear();
  5150. return Listener.ReadPreprocessorOptions(PPOpts, Complain,
  5151. SuggestedPredefines);
  5152. }
  5153. std::pair<ModuleFile *, unsigned>
  5154. ASTReader::getModulePreprocessedEntity(unsigned GlobalIndex) {
  5155. GlobalPreprocessedEntityMapType::iterator
  5156. I = GlobalPreprocessedEntityMap.find(GlobalIndex);
  5157. assert(I != GlobalPreprocessedEntityMap.end() &&
  5158. "Corrupted global preprocessed entity map");
  5159. ModuleFile *M = I->second;
  5160. unsigned LocalIndex = GlobalIndex - M->BasePreprocessedEntityID;
  5161. return std::make_pair(M, LocalIndex);
  5162. }
  5163. llvm::iterator_range<PreprocessingRecord::iterator>
  5164. ASTReader::getModulePreprocessedEntities(ModuleFile &Mod) const {
  5165. if (PreprocessingRecord *PPRec = PP.getPreprocessingRecord())
  5166. return PPRec->getIteratorsForLoadedRange(Mod.BasePreprocessedEntityID,
  5167. Mod.NumPreprocessedEntities);
  5168. return llvm::make_range(PreprocessingRecord::iterator(),
  5169. PreprocessingRecord::iterator());
  5170. }
  5171. bool ASTReader::canRecoverFromOutOfDate(StringRef ModuleFileName,
  5172. unsigned int ClientLoadCapabilities) {
  5173. return ClientLoadCapabilities & ARR_OutOfDate &&
  5174. !getModuleManager().getModuleCache().isPCMFinal(ModuleFileName);
  5175. }
  5176. llvm::iterator_range<ASTReader::ModuleDeclIterator>
  5177. ASTReader::getModuleFileLevelDecls(ModuleFile &Mod) {
  5178. return llvm::make_range(
  5179. ModuleDeclIterator(this, &Mod, Mod.FileSortedDecls),
  5180. ModuleDeclIterator(this, &Mod,
  5181. Mod.FileSortedDecls + Mod.NumFileSortedDecls));
  5182. }
  5183. SourceRange ASTReader::ReadSkippedRange(unsigned GlobalIndex) {
  5184. auto I = GlobalSkippedRangeMap.find(GlobalIndex);
  5185. assert(I != GlobalSkippedRangeMap.end() &&
  5186. "Corrupted global skipped range map");
  5187. ModuleFile *M = I->second;
  5188. unsigned LocalIndex = GlobalIndex - M->BasePreprocessedSkippedRangeID;
  5189. assert(LocalIndex < M->NumPreprocessedSkippedRanges);
  5190. PPSkippedRange RawRange = M->PreprocessedSkippedRangeOffsets[LocalIndex];
  5191. SourceRange Range(TranslateSourceLocation(*M, RawRange.getBegin()),
  5192. TranslateSourceLocation(*M, RawRange.getEnd()));
  5193. assert(Range.isValid());
  5194. return Range;
  5195. }
  5196. PreprocessedEntity *ASTReader::ReadPreprocessedEntity(unsigned Index) {
  5197. PreprocessedEntityID PPID = Index+1;
  5198. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  5199. ModuleFile &M = *PPInfo.first;
  5200. unsigned LocalIndex = PPInfo.second;
  5201. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  5202. if (!PP.getPreprocessingRecord()) {
  5203. Error("no preprocessing record");
  5204. return nullptr;
  5205. }
  5206. SavedStreamPosition SavedPosition(M.PreprocessorDetailCursor);
  5207. if (llvm::Error Err = M.PreprocessorDetailCursor.JumpToBit(
  5208. M.MacroOffsetsBase + PPOffs.BitOffset)) {
  5209. Error(std::move(Err));
  5210. return nullptr;
  5211. }
  5212. Expected<llvm::BitstreamEntry> MaybeEntry =
  5213. M.PreprocessorDetailCursor.advance(BitstreamCursor::AF_DontPopBlockAtEnd);
  5214. if (!MaybeEntry) {
  5215. Error(MaybeEntry.takeError());
  5216. return nullptr;
  5217. }
  5218. llvm::BitstreamEntry Entry = MaybeEntry.get();
  5219. if (Entry.Kind != llvm::BitstreamEntry::Record)
  5220. return nullptr;
  5221. // Read the record.
  5222. SourceRange Range(TranslateSourceLocation(M, PPOffs.getBegin()),
  5223. TranslateSourceLocation(M, PPOffs.getEnd()));
  5224. PreprocessingRecord &PPRec = *PP.getPreprocessingRecord();
  5225. StringRef Blob;
  5226. RecordData Record;
  5227. Expected<unsigned> MaybeRecType =
  5228. M.PreprocessorDetailCursor.readRecord(Entry.ID, Record, &Blob);
  5229. if (!MaybeRecType) {
  5230. Error(MaybeRecType.takeError());
  5231. return nullptr;
  5232. }
  5233. switch ((PreprocessorDetailRecordTypes)MaybeRecType.get()) {
  5234. case PPD_MACRO_EXPANSION: {
  5235. bool isBuiltin = Record[0];
  5236. IdentifierInfo *Name = nullptr;
  5237. MacroDefinitionRecord *Def = nullptr;
  5238. if (isBuiltin)
  5239. Name = getLocalIdentifier(M, Record[1]);
  5240. else {
  5241. PreprocessedEntityID GlobalID =
  5242. getGlobalPreprocessedEntityID(M, Record[1]);
  5243. Def = cast<MacroDefinitionRecord>(
  5244. PPRec.getLoadedPreprocessedEntity(GlobalID - 1));
  5245. }
  5246. MacroExpansion *ME;
  5247. if (isBuiltin)
  5248. ME = new (PPRec) MacroExpansion(Name, Range);
  5249. else
  5250. ME = new (PPRec) MacroExpansion(Def, Range);
  5251. return ME;
  5252. }
  5253. case PPD_MACRO_DEFINITION: {
  5254. // Decode the identifier info and then check again; if the macro is
  5255. // still defined and associated with the identifier,
  5256. IdentifierInfo *II = getLocalIdentifier(M, Record[0]);
  5257. MacroDefinitionRecord *MD = new (PPRec) MacroDefinitionRecord(II, Range);
  5258. if (DeserializationListener)
  5259. DeserializationListener->MacroDefinitionRead(PPID, MD);
  5260. return MD;
  5261. }
  5262. case PPD_INCLUSION_DIRECTIVE: {
  5263. const char *FullFileNameStart = Blob.data() + Record[0];
  5264. StringRef FullFileName(FullFileNameStart, Blob.size() - Record[0]);
  5265. const FileEntry *File = nullptr;
  5266. if (!FullFileName.empty())
  5267. if (auto FE = PP.getFileManager().getFile(FullFileName))
  5268. File = *FE;
  5269. // FIXME: Stable encoding
  5270. InclusionDirective::InclusionKind Kind
  5271. = static_cast<InclusionDirective::InclusionKind>(Record[2]);
  5272. InclusionDirective *ID
  5273. = new (PPRec) InclusionDirective(PPRec, Kind,
  5274. StringRef(Blob.data(), Record[0]),
  5275. Record[1], Record[3],
  5276. File,
  5277. Range);
  5278. return ID;
  5279. }
  5280. }
  5281. llvm_unreachable("Invalid PreprocessorDetailRecordTypes");
  5282. }
  5283. /// Find the next module that contains entities and return the ID
  5284. /// of the first entry.
  5285. ///
  5286. /// \param SLocMapI points at a chunk of a module that contains no
  5287. /// preprocessed entities or the entities it contains are not the ones we are
  5288. /// looking for.
  5289. PreprocessedEntityID ASTReader::findNextPreprocessedEntity(
  5290. GlobalSLocOffsetMapType::const_iterator SLocMapI) const {
  5291. ++SLocMapI;
  5292. for (GlobalSLocOffsetMapType::const_iterator
  5293. EndI = GlobalSLocOffsetMap.end(); SLocMapI != EndI; ++SLocMapI) {
  5294. ModuleFile &M = *SLocMapI->second;
  5295. if (M.NumPreprocessedEntities)
  5296. return M.BasePreprocessedEntityID;
  5297. }
  5298. return getTotalNumPreprocessedEntities();
  5299. }
  5300. namespace {
  5301. struct PPEntityComp {
  5302. const ASTReader &Reader;
  5303. ModuleFile &M;
  5304. PPEntityComp(const ASTReader &Reader, ModuleFile &M) : Reader(Reader), M(M) {}
  5305. bool operator()(const PPEntityOffset &L, const PPEntityOffset &R) const {
  5306. SourceLocation LHS = getLoc(L);
  5307. SourceLocation RHS = getLoc(R);
  5308. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5309. }
  5310. bool operator()(const PPEntityOffset &L, SourceLocation RHS) const {
  5311. SourceLocation LHS = getLoc(L);
  5312. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5313. }
  5314. bool operator()(SourceLocation LHS, const PPEntityOffset &R) const {
  5315. SourceLocation RHS = getLoc(R);
  5316. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  5317. }
  5318. SourceLocation getLoc(const PPEntityOffset &PPE) const {
  5319. return Reader.TranslateSourceLocation(M, PPE.getBegin());
  5320. }
  5321. };
  5322. } // namespace
  5323. PreprocessedEntityID ASTReader::findPreprocessedEntity(SourceLocation Loc,
  5324. bool EndsAfter) const {
  5325. if (SourceMgr.isLocalSourceLocation(Loc))
  5326. return getTotalNumPreprocessedEntities();
  5327. GlobalSLocOffsetMapType::const_iterator SLocMapI = GlobalSLocOffsetMap.find(
  5328. SourceManager::MaxLoadedOffset - Loc.getOffset() - 1);
  5329. assert(SLocMapI != GlobalSLocOffsetMap.end() &&
  5330. "Corrupted global sloc offset map");
  5331. if (SLocMapI->second->NumPreprocessedEntities == 0)
  5332. return findNextPreprocessedEntity(SLocMapI);
  5333. ModuleFile &M = *SLocMapI->second;
  5334. using pp_iterator = const PPEntityOffset *;
  5335. pp_iterator pp_begin = M.PreprocessedEntityOffsets;
  5336. pp_iterator pp_end = pp_begin + M.NumPreprocessedEntities;
  5337. size_t Count = M.NumPreprocessedEntities;
  5338. size_t Half;
  5339. pp_iterator First = pp_begin;
  5340. pp_iterator PPI;
  5341. if (EndsAfter) {
  5342. PPI = std::upper_bound(pp_begin, pp_end, Loc,
  5343. PPEntityComp(*this, M));
  5344. } else {
  5345. // Do a binary search manually instead of using std::lower_bound because
  5346. // The end locations of entities may be unordered (when a macro expansion
  5347. // is inside another macro argument), but for this case it is not important
  5348. // whether we get the first macro expansion or its containing macro.
  5349. while (Count > 0) {
  5350. Half = Count / 2;
  5351. PPI = First;
  5352. std::advance(PPI, Half);
  5353. if (SourceMgr.isBeforeInTranslationUnit(
  5354. TranslateSourceLocation(M, PPI->getEnd()), Loc)) {
  5355. First = PPI;
  5356. ++First;
  5357. Count = Count - Half - 1;
  5358. } else
  5359. Count = Half;
  5360. }
  5361. }
  5362. if (PPI == pp_end)
  5363. return findNextPreprocessedEntity(SLocMapI);
  5364. return M.BasePreprocessedEntityID + (PPI - pp_begin);
  5365. }
  5366. /// Returns a pair of [Begin, End) indices of preallocated
  5367. /// preprocessed entities that \arg Range encompasses.
  5368. std::pair<unsigned, unsigned>
  5369. ASTReader::findPreprocessedEntitiesInRange(SourceRange Range) {
  5370. if (Range.isInvalid())
  5371. return std::make_pair(0,0);
  5372. assert(!SourceMgr.isBeforeInTranslationUnit(Range.getEnd(),Range.getBegin()));
  5373. PreprocessedEntityID BeginID =
  5374. findPreprocessedEntity(Range.getBegin(), false);
  5375. PreprocessedEntityID EndID = findPreprocessedEntity(Range.getEnd(), true);
  5376. return std::make_pair(BeginID, EndID);
  5377. }
  5378. /// Optionally returns true or false if the preallocated preprocessed
  5379. /// entity with index \arg Index came from file \arg FID.
  5380. Optional<bool> ASTReader::isPreprocessedEntityInFileID(unsigned Index,
  5381. FileID FID) {
  5382. if (FID.isInvalid())
  5383. return false;
  5384. std::pair<ModuleFile *, unsigned> PPInfo = getModulePreprocessedEntity(Index);
  5385. ModuleFile &M = *PPInfo.first;
  5386. unsigned LocalIndex = PPInfo.second;
  5387. const PPEntityOffset &PPOffs = M.PreprocessedEntityOffsets[LocalIndex];
  5388. SourceLocation Loc = TranslateSourceLocation(M, PPOffs.getBegin());
  5389. if (Loc.isInvalid())
  5390. return false;
  5391. if (SourceMgr.isInFileID(SourceMgr.getFileLoc(Loc), FID))
  5392. return true;
  5393. else
  5394. return false;
  5395. }
  5396. namespace {
  5397. /// Visitor used to search for information about a header file.
  5398. class HeaderFileInfoVisitor {
  5399. const FileEntry *FE;
  5400. Optional<HeaderFileInfo> HFI;
  5401. public:
  5402. explicit HeaderFileInfoVisitor(const FileEntry *FE) : FE(FE) {}
  5403. bool operator()(ModuleFile &M) {
  5404. HeaderFileInfoLookupTable *Table
  5405. = static_cast<HeaderFileInfoLookupTable *>(M.HeaderFileInfoTable);
  5406. if (!Table)
  5407. return false;
  5408. // Look in the on-disk hash table for an entry for this file name.
  5409. HeaderFileInfoLookupTable::iterator Pos = Table->find(FE);
  5410. if (Pos == Table->end())
  5411. return false;
  5412. HFI = *Pos;
  5413. return true;
  5414. }
  5415. Optional<HeaderFileInfo> getHeaderFileInfo() const { return HFI; }
  5416. };
  5417. } // namespace
  5418. HeaderFileInfo ASTReader::GetHeaderFileInfo(const FileEntry *FE) {
  5419. HeaderFileInfoVisitor Visitor(FE);
  5420. ModuleMgr.visit(Visitor);
  5421. if (Optional<HeaderFileInfo> HFI = Visitor.getHeaderFileInfo())
  5422. return *HFI;
  5423. return HeaderFileInfo();
  5424. }
  5425. void ASTReader::ReadPragmaDiagnosticMappings(DiagnosticsEngine &Diag) {
  5426. using DiagState = DiagnosticsEngine::DiagState;
  5427. SmallVector<DiagState *, 32> DiagStates;
  5428. for (ModuleFile &F : ModuleMgr) {
  5429. unsigned Idx = 0;
  5430. auto &Record = F.PragmaDiagMappings;
  5431. if (Record.empty())
  5432. continue;
  5433. DiagStates.clear();
  5434. auto ReadDiagState =
  5435. [&](const DiagState &BasedOn, SourceLocation Loc,
  5436. bool IncludeNonPragmaStates) -> DiagnosticsEngine::DiagState * {
  5437. unsigned BackrefID = Record[Idx++];
  5438. if (BackrefID != 0)
  5439. return DiagStates[BackrefID - 1];
  5440. // A new DiagState was created here.
  5441. Diag.DiagStates.push_back(BasedOn);
  5442. DiagState *NewState = &Diag.DiagStates.back();
  5443. DiagStates.push_back(NewState);
  5444. unsigned Size = Record[Idx++];
  5445. assert(Idx + Size * 2 <= Record.size() &&
  5446. "Invalid data, not enough diag/map pairs");
  5447. while (Size--) {
  5448. unsigned DiagID = Record[Idx++];
  5449. DiagnosticMapping NewMapping =
  5450. DiagnosticMapping::deserialize(Record[Idx++]);
  5451. if (!NewMapping.isPragma() && !IncludeNonPragmaStates)
  5452. continue;
  5453. DiagnosticMapping &Mapping = NewState->getOrAddMapping(DiagID);
  5454. // If this mapping was specified as a warning but the severity was
  5455. // upgraded due to diagnostic settings, simulate the current diagnostic
  5456. // settings (and use a warning).
  5457. if (NewMapping.wasUpgradedFromWarning() && !Mapping.isErrorOrFatal()) {
  5458. NewMapping.setSeverity(diag::Severity::Warning);
  5459. NewMapping.setUpgradedFromWarning(false);
  5460. }
  5461. Mapping = NewMapping;
  5462. }
  5463. return NewState;
  5464. };
  5465. // Read the first state.
  5466. DiagState *FirstState;
  5467. if (F.Kind == MK_ImplicitModule) {
  5468. // Implicitly-built modules are reused with different diagnostic
  5469. // settings. Use the initial diagnostic state from Diag to simulate this
  5470. // compilation's diagnostic settings.
  5471. FirstState = Diag.DiagStatesByLoc.FirstDiagState;
  5472. DiagStates.push_back(FirstState);
  5473. // Skip the initial diagnostic state from the serialized module.
  5474. assert(Record[1] == 0 &&
  5475. "Invalid data, unexpected backref in initial state");
  5476. Idx = 3 + Record[2] * 2;
  5477. assert(Idx < Record.size() &&
  5478. "Invalid data, not enough state change pairs in initial state");
  5479. } else if (F.isModule()) {
  5480. // For an explicit module, preserve the flags from the module build
  5481. // command line (-w, -Weverything, -Werror, ...) along with any explicit
  5482. // -Wblah flags.
  5483. unsigned Flags = Record[Idx++];
  5484. DiagState Initial;
  5485. Initial.SuppressSystemWarnings = Flags & 1; Flags >>= 1;
  5486. Initial.ErrorsAsFatal = Flags & 1; Flags >>= 1;
  5487. Initial.WarningsAsErrors = Flags & 1; Flags >>= 1;
  5488. Initial.EnableAllWarnings = Flags & 1; Flags >>= 1;
  5489. Initial.IgnoreAllWarnings = Flags & 1; Flags >>= 1;
  5490. Initial.ExtBehavior = (diag::Severity)Flags;
  5491. FirstState = ReadDiagState(Initial, SourceLocation(), true);
  5492. assert(F.OriginalSourceFileID.isValid());
  5493. // Set up the root buffer of the module to start with the initial
  5494. // diagnostic state of the module itself, to cover files that contain no
  5495. // explicit transitions (for which we did not serialize anything).
  5496. Diag.DiagStatesByLoc.Files[F.OriginalSourceFileID]
  5497. .StateTransitions.push_back({FirstState, 0});
  5498. } else {
  5499. // For prefix ASTs, start with whatever the user configured on the
  5500. // command line.
  5501. Idx++; // Skip flags.
  5502. FirstState = ReadDiagState(*Diag.DiagStatesByLoc.CurDiagState,
  5503. SourceLocation(), false);
  5504. }
  5505. // Read the state transitions.
  5506. unsigned NumLocations = Record[Idx++];
  5507. while (NumLocations--) {
  5508. assert(Idx < Record.size() &&
  5509. "Invalid data, missing pragma diagnostic states");
  5510. SourceLocation Loc = ReadSourceLocation(F, Record[Idx++]);
  5511. auto IDAndOffset = SourceMgr.getDecomposedLoc(Loc);
  5512. assert(IDAndOffset.first.isValid() && "invalid FileID for transition");
  5513. assert(IDAndOffset.second == 0 && "not a start location for a FileID");
  5514. unsigned Transitions = Record[Idx++];
  5515. // Note that we don't need to set up Parent/ParentOffset here, because
  5516. // we won't be changing the diagnostic state within imported FileIDs
  5517. // (other than perhaps appending to the main source file, which has no
  5518. // parent).
  5519. auto &F = Diag.DiagStatesByLoc.Files[IDAndOffset.first];
  5520. F.StateTransitions.reserve(F.StateTransitions.size() + Transitions);
  5521. for (unsigned I = 0; I != Transitions; ++I) {
  5522. unsigned Offset = Record[Idx++];
  5523. auto *State =
  5524. ReadDiagState(*FirstState, Loc.getLocWithOffset(Offset), false);
  5525. F.StateTransitions.push_back({State, Offset});
  5526. }
  5527. }
  5528. // Read the final state.
  5529. assert(Idx < Record.size() &&
  5530. "Invalid data, missing final pragma diagnostic state");
  5531. SourceLocation CurStateLoc =
  5532. ReadSourceLocation(F, F.PragmaDiagMappings[Idx++]);
  5533. auto *CurState = ReadDiagState(*FirstState, CurStateLoc, false);
  5534. if (!F.isModule()) {
  5535. Diag.DiagStatesByLoc.CurDiagState = CurState;
  5536. Diag.DiagStatesByLoc.CurDiagStateLoc = CurStateLoc;
  5537. // Preserve the property that the imaginary root file describes the
  5538. // current state.
  5539. FileID NullFile;
  5540. auto &T = Diag.DiagStatesByLoc.Files[NullFile].StateTransitions;
  5541. if (T.empty())
  5542. T.push_back({CurState, 0});
  5543. else
  5544. T[0].State = CurState;
  5545. }
  5546. // Don't try to read these mappings again.
  5547. Record.clear();
  5548. }
  5549. }
  5550. /// Get the correct cursor and offset for loading a type.
  5551. ASTReader::RecordLocation ASTReader::TypeCursorForIndex(unsigned Index) {
  5552. GlobalTypeMapType::iterator I = GlobalTypeMap.find(Index);
  5553. assert(I != GlobalTypeMap.end() && "Corrupted global type map");
  5554. ModuleFile *M = I->second;
  5555. return RecordLocation(
  5556. M, M->TypeOffsets[Index - M->BaseTypeIndex].getBitOffset() +
  5557. M->DeclsBlockStartOffset);
  5558. }
  5559. static llvm::Optional<Type::TypeClass> getTypeClassForCode(TypeCode code) {
  5560. switch (code) {
  5561. #define TYPE_BIT_CODE(CLASS_ID, CODE_ID, CODE_VALUE) \
  5562. case TYPE_##CODE_ID: return Type::CLASS_ID;
  5563. #include "clang/Serialization/TypeBitCodes.def"
  5564. default: return llvm::None;
  5565. }
  5566. }
  5567. /// Read and return the type with the given index..
  5568. ///
  5569. /// The index is the type ID, shifted and minus the number of predefs. This
  5570. /// routine actually reads the record corresponding to the type at the given
  5571. /// location. It is a helper routine for GetType, which deals with reading type
  5572. /// IDs.
  5573. QualType ASTReader::readTypeRecord(unsigned Index) {
  5574. assert(ContextObj && "reading type with no AST context");
  5575. ASTContext &Context = *ContextObj;
  5576. RecordLocation Loc = TypeCursorForIndex(Index);
  5577. BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
  5578. // Keep track of where we are in the stream, then jump back there
  5579. // after reading this type.
  5580. SavedStreamPosition SavedPosition(DeclsCursor);
  5581. ReadingKindTracker ReadingKind(Read_Type, *this);
  5582. // Note that we are loading a type record.
  5583. Deserializing AType(this);
  5584. if (llvm::Error Err = DeclsCursor.JumpToBit(Loc.Offset)) {
  5585. Error(std::move(Err));
  5586. return QualType();
  5587. }
  5588. Expected<unsigned> RawCode = DeclsCursor.ReadCode();
  5589. if (!RawCode) {
  5590. Error(RawCode.takeError());
  5591. return QualType();
  5592. }
  5593. ASTRecordReader Record(*this, *Loc.F);
  5594. Expected<unsigned> Code = Record.readRecord(DeclsCursor, RawCode.get());
  5595. if (!Code) {
  5596. Error(Code.takeError());
  5597. return QualType();
  5598. }
  5599. if (Code.get() == TYPE_EXT_QUAL) {
  5600. QualType baseType = Record.readQualType();
  5601. Qualifiers quals = Record.readQualifiers();
  5602. return Context.getQualifiedType(baseType, quals);
  5603. }
  5604. auto maybeClass = getTypeClassForCode((TypeCode) Code.get());
  5605. if (!maybeClass) {
  5606. Error("Unexpected code for type");
  5607. return QualType();
  5608. }
  5609. serialization::AbstractTypeReader<ASTRecordReader> TypeReader(Record);
  5610. return TypeReader.read(*maybeClass);
  5611. }
  5612. namespace clang {
  5613. class TypeLocReader : public TypeLocVisitor<TypeLocReader> {
  5614. ASTRecordReader &Reader;
  5615. SourceLocation readSourceLocation() {
  5616. return Reader.readSourceLocation();
  5617. }
  5618. TypeSourceInfo *GetTypeSourceInfo() {
  5619. return Reader.readTypeSourceInfo();
  5620. }
  5621. NestedNameSpecifierLoc ReadNestedNameSpecifierLoc() {
  5622. return Reader.readNestedNameSpecifierLoc();
  5623. }
  5624. Attr *ReadAttr() {
  5625. return Reader.readAttr();
  5626. }
  5627. public:
  5628. TypeLocReader(ASTRecordReader &Reader) : Reader(Reader) {}
  5629. // We want compile-time assurance that we've enumerated all of
  5630. // these, so unfortunately we have to declare them first, then
  5631. // define them out-of-line.
  5632. #define ABSTRACT_TYPELOC(CLASS, PARENT)
  5633. #define TYPELOC(CLASS, PARENT) \
  5634. void Visit##CLASS##TypeLoc(CLASS##TypeLoc TyLoc);
  5635. #include "clang/AST/TypeLocNodes.def"
  5636. void VisitFunctionTypeLoc(FunctionTypeLoc);
  5637. void VisitArrayTypeLoc(ArrayTypeLoc);
  5638. };
  5639. } // namespace clang
  5640. void TypeLocReader::VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
  5641. // nothing to do
  5642. }
  5643. void TypeLocReader::VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
  5644. TL.setBuiltinLoc(readSourceLocation());
  5645. if (TL.needsExtraLocalData()) {
  5646. TL.setWrittenTypeSpec(static_cast<DeclSpec::TST>(Reader.readInt()));
  5647. TL.setWrittenSignSpec(static_cast<TypeSpecifierSign>(Reader.readInt()));
  5648. TL.setWrittenWidthSpec(static_cast<TypeSpecifierWidth>(Reader.readInt()));
  5649. TL.setModeAttr(Reader.readInt());
  5650. }
  5651. }
  5652. void TypeLocReader::VisitComplexTypeLoc(ComplexTypeLoc TL) {
  5653. TL.setNameLoc(readSourceLocation());
  5654. }
  5655. void TypeLocReader::VisitPointerTypeLoc(PointerTypeLoc TL) {
  5656. TL.setStarLoc(readSourceLocation());
  5657. }
  5658. void TypeLocReader::VisitDecayedTypeLoc(DecayedTypeLoc TL) {
  5659. // nothing to do
  5660. }
  5661. void TypeLocReader::VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
  5662. // nothing to do
  5663. }
  5664. void TypeLocReader::VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
  5665. TL.setExpansionLoc(readSourceLocation());
  5666. }
  5667. void TypeLocReader::VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
  5668. TL.setCaretLoc(readSourceLocation());
  5669. }
  5670. void TypeLocReader::VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
  5671. TL.setAmpLoc(readSourceLocation());
  5672. }
  5673. void TypeLocReader::VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
  5674. TL.setAmpAmpLoc(readSourceLocation());
  5675. }
  5676. void TypeLocReader::VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
  5677. TL.setStarLoc(readSourceLocation());
  5678. TL.setClassTInfo(GetTypeSourceInfo());
  5679. }
  5680. void TypeLocReader::VisitArrayTypeLoc(ArrayTypeLoc TL) {
  5681. TL.setLBracketLoc(readSourceLocation());
  5682. TL.setRBracketLoc(readSourceLocation());
  5683. if (Reader.readBool())
  5684. TL.setSizeExpr(Reader.readExpr());
  5685. else
  5686. TL.setSizeExpr(nullptr);
  5687. }
  5688. void TypeLocReader::VisitConstantArrayTypeLoc(ConstantArrayTypeLoc TL) {
  5689. VisitArrayTypeLoc(TL);
  5690. }
  5691. void TypeLocReader::VisitIncompleteArrayTypeLoc(IncompleteArrayTypeLoc TL) {
  5692. VisitArrayTypeLoc(TL);
  5693. }
  5694. void TypeLocReader::VisitVariableArrayTypeLoc(VariableArrayTypeLoc TL) {
  5695. VisitArrayTypeLoc(TL);
  5696. }
  5697. void TypeLocReader::VisitDependentSizedArrayTypeLoc(
  5698. DependentSizedArrayTypeLoc TL) {
  5699. VisitArrayTypeLoc(TL);
  5700. }
  5701. void TypeLocReader::VisitDependentAddressSpaceTypeLoc(
  5702. DependentAddressSpaceTypeLoc TL) {
  5703. TL.setAttrNameLoc(readSourceLocation());
  5704. TL.setAttrOperandParensRange(Reader.readSourceRange());
  5705. TL.setAttrExprOperand(Reader.readExpr());
  5706. }
  5707. void TypeLocReader::VisitDependentSizedExtVectorTypeLoc(
  5708. DependentSizedExtVectorTypeLoc TL) {
  5709. TL.setNameLoc(readSourceLocation());
  5710. }
  5711. void TypeLocReader::VisitVectorTypeLoc(VectorTypeLoc TL) {
  5712. TL.setNameLoc(readSourceLocation());
  5713. }
  5714. void TypeLocReader::VisitDependentVectorTypeLoc(
  5715. DependentVectorTypeLoc TL) {
  5716. TL.setNameLoc(readSourceLocation());
  5717. }
  5718. void TypeLocReader::VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
  5719. TL.setNameLoc(readSourceLocation());
  5720. }
  5721. void TypeLocReader::VisitConstantMatrixTypeLoc(ConstantMatrixTypeLoc TL) {
  5722. TL.setAttrNameLoc(readSourceLocation());
  5723. TL.setAttrOperandParensRange(Reader.readSourceRange());
  5724. TL.setAttrRowOperand(Reader.readExpr());
  5725. TL.setAttrColumnOperand(Reader.readExpr());
  5726. }
  5727. void TypeLocReader::VisitDependentSizedMatrixTypeLoc(
  5728. DependentSizedMatrixTypeLoc TL) {
  5729. TL.setAttrNameLoc(readSourceLocation());
  5730. TL.setAttrOperandParensRange(Reader.readSourceRange());
  5731. TL.setAttrRowOperand(Reader.readExpr());
  5732. TL.setAttrColumnOperand(Reader.readExpr());
  5733. }
  5734. void TypeLocReader::VisitFunctionTypeLoc(FunctionTypeLoc TL) {
  5735. TL.setLocalRangeBegin(readSourceLocation());
  5736. TL.setLParenLoc(readSourceLocation());
  5737. TL.setRParenLoc(readSourceLocation());
  5738. TL.setExceptionSpecRange(Reader.readSourceRange());
  5739. TL.setLocalRangeEnd(readSourceLocation());
  5740. for (unsigned i = 0, e = TL.getNumParams(); i != e; ++i) {
  5741. TL.setParam(i, Reader.readDeclAs<ParmVarDecl>());
  5742. }
  5743. }
  5744. void TypeLocReader::VisitFunctionProtoTypeLoc(FunctionProtoTypeLoc TL) {
  5745. VisitFunctionTypeLoc(TL);
  5746. }
  5747. void TypeLocReader::VisitFunctionNoProtoTypeLoc(FunctionNoProtoTypeLoc TL) {
  5748. VisitFunctionTypeLoc(TL);
  5749. }
  5750. void TypeLocReader::VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
  5751. TL.setNameLoc(readSourceLocation());
  5752. }
  5753. void TypeLocReader::VisitUsingTypeLoc(UsingTypeLoc TL) {
  5754. TL.setNameLoc(readSourceLocation());
  5755. }
  5756. void TypeLocReader::VisitTypedefTypeLoc(TypedefTypeLoc TL) {
  5757. TL.setNameLoc(readSourceLocation());
  5758. }
  5759. void TypeLocReader::VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
  5760. TL.setTypeofLoc(readSourceLocation());
  5761. TL.setLParenLoc(readSourceLocation());
  5762. TL.setRParenLoc(readSourceLocation());
  5763. }
  5764. void TypeLocReader::VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
  5765. TL.setTypeofLoc(readSourceLocation());
  5766. TL.setLParenLoc(readSourceLocation());
  5767. TL.setRParenLoc(readSourceLocation());
  5768. TL.setUnderlyingTInfo(GetTypeSourceInfo());
  5769. }
  5770. void TypeLocReader::VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
  5771. TL.setDecltypeLoc(readSourceLocation());
  5772. TL.setRParenLoc(readSourceLocation());
  5773. }
  5774. void TypeLocReader::VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
  5775. TL.setKWLoc(readSourceLocation());
  5776. TL.setLParenLoc(readSourceLocation());
  5777. TL.setRParenLoc(readSourceLocation());
  5778. TL.setUnderlyingTInfo(GetTypeSourceInfo());
  5779. }
  5780. void TypeLocReader::VisitAutoTypeLoc(AutoTypeLoc TL) {
  5781. TL.setNameLoc(readSourceLocation());
  5782. if (Reader.readBool()) {
  5783. TL.setNestedNameSpecifierLoc(ReadNestedNameSpecifierLoc());
  5784. TL.setTemplateKWLoc(readSourceLocation());
  5785. TL.setConceptNameLoc(readSourceLocation());
  5786. TL.setFoundDecl(Reader.readDeclAs<NamedDecl>());
  5787. TL.setLAngleLoc(readSourceLocation());
  5788. TL.setRAngleLoc(readSourceLocation());
  5789. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  5790. TL.setArgLocInfo(i, Reader.readTemplateArgumentLocInfo(
  5791. TL.getTypePtr()->getArg(i).getKind()));
  5792. }
  5793. if (Reader.readBool())
  5794. TL.setRParenLoc(readSourceLocation());
  5795. }
  5796. void TypeLocReader::VisitDeducedTemplateSpecializationTypeLoc(
  5797. DeducedTemplateSpecializationTypeLoc TL) {
  5798. TL.setTemplateNameLoc(readSourceLocation());
  5799. }
  5800. void TypeLocReader::VisitRecordTypeLoc(RecordTypeLoc TL) {
  5801. TL.setNameLoc(readSourceLocation());
  5802. }
  5803. void TypeLocReader::VisitEnumTypeLoc(EnumTypeLoc TL) {
  5804. TL.setNameLoc(readSourceLocation());
  5805. }
  5806. void TypeLocReader::VisitAttributedTypeLoc(AttributedTypeLoc TL) {
  5807. TL.setAttr(ReadAttr());
  5808. }
  5809. void TypeLocReader::VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
  5810. TL.setNameLoc(readSourceLocation());
  5811. }
  5812. void TypeLocReader::VisitSubstTemplateTypeParmTypeLoc(
  5813. SubstTemplateTypeParmTypeLoc TL) {
  5814. TL.setNameLoc(readSourceLocation());
  5815. }
  5816. void TypeLocReader::VisitSubstTemplateTypeParmPackTypeLoc(
  5817. SubstTemplateTypeParmPackTypeLoc TL) {
  5818. TL.setNameLoc(readSourceLocation());
  5819. }
  5820. void TypeLocReader::VisitTemplateSpecializationTypeLoc(
  5821. TemplateSpecializationTypeLoc TL) {
  5822. TL.setTemplateKeywordLoc(readSourceLocation());
  5823. TL.setTemplateNameLoc(readSourceLocation());
  5824. TL.setLAngleLoc(readSourceLocation());
  5825. TL.setRAngleLoc(readSourceLocation());
  5826. for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i)
  5827. TL.setArgLocInfo(
  5828. i,
  5829. Reader.readTemplateArgumentLocInfo(
  5830. TL.getTypePtr()->getArg(i).getKind()));
  5831. }
  5832. void TypeLocReader::VisitParenTypeLoc(ParenTypeLoc TL) {
  5833. TL.setLParenLoc(readSourceLocation());
  5834. TL.setRParenLoc(readSourceLocation());
  5835. }
  5836. void TypeLocReader::VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
  5837. TL.setElaboratedKeywordLoc(readSourceLocation());
  5838. TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
  5839. }
  5840. void TypeLocReader::VisitInjectedClassNameTypeLoc(InjectedClassNameTypeLoc TL) {
  5841. TL.setNameLoc(readSourceLocation());
  5842. }
  5843. void TypeLocReader::VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
  5844. TL.setElaboratedKeywordLoc(readSourceLocation());
  5845. TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
  5846. TL.setNameLoc(readSourceLocation());
  5847. }
  5848. void TypeLocReader::VisitDependentTemplateSpecializationTypeLoc(
  5849. DependentTemplateSpecializationTypeLoc TL) {
  5850. TL.setElaboratedKeywordLoc(readSourceLocation());
  5851. TL.setQualifierLoc(ReadNestedNameSpecifierLoc());
  5852. TL.setTemplateKeywordLoc(readSourceLocation());
  5853. TL.setTemplateNameLoc(readSourceLocation());
  5854. TL.setLAngleLoc(readSourceLocation());
  5855. TL.setRAngleLoc(readSourceLocation());
  5856. for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I)
  5857. TL.setArgLocInfo(
  5858. I,
  5859. Reader.readTemplateArgumentLocInfo(
  5860. TL.getTypePtr()->getArg(I).getKind()));
  5861. }
  5862. void TypeLocReader::VisitPackExpansionTypeLoc(PackExpansionTypeLoc TL) {
  5863. TL.setEllipsisLoc(readSourceLocation());
  5864. }
  5865. void TypeLocReader::VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
  5866. TL.setNameLoc(readSourceLocation());
  5867. }
  5868. void TypeLocReader::VisitObjCTypeParamTypeLoc(ObjCTypeParamTypeLoc TL) {
  5869. if (TL.getNumProtocols()) {
  5870. TL.setProtocolLAngleLoc(readSourceLocation());
  5871. TL.setProtocolRAngleLoc(readSourceLocation());
  5872. }
  5873. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  5874. TL.setProtocolLoc(i, readSourceLocation());
  5875. }
  5876. void TypeLocReader::VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
  5877. TL.setHasBaseTypeAsWritten(Reader.readBool());
  5878. TL.setTypeArgsLAngleLoc(readSourceLocation());
  5879. TL.setTypeArgsRAngleLoc(readSourceLocation());
  5880. for (unsigned i = 0, e = TL.getNumTypeArgs(); i != e; ++i)
  5881. TL.setTypeArgTInfo(i, GetTypeSourceInfo());
  5882. TL.setProtocolLAngleLoc(readSourceLocation());
  5883. TL.setProtocolRAngleLoc(readSourceLocation());
  5884. for (unsigned i = 0, e = TL.getNumProtocols(); i != e; ++i)
  5885. TL.setProtocolLoc(i, readSourceLocation());
  5886. }
  5887. void TypeLocReader::VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
  5888. TL.setStarLoc(readSourceLocation());
  5889. }
  5890. void TypeLocReader::VisitAtomicTypeLoc(AtomicTypeLoc TL) {
  5891. TL.setKWLoc(readSourceLocation());
  5892. TL.setLParenLoc(readSourceLocation());
  5893. TL.setRParenLoc(readSourceLocation());
  5894. }
  5895. void TypeLocReader::VisitPipeTypeLoc(PipeTypeLoc TL) {
  5896. TL.setKWLoc(readSourceLocation());
  5897. }
  5898. void TypeLocReader::VisitBitIntTypeLoc(clang::BitIntTypeLoc TL) {
  5899. TL.setNameLoc(readSourceLocation());
  5900. }
  5901. void TypeLocReader::VisitDependentBitIntTypeLoc(
  5902. clang::DependentBitIntTypeLoc TL) {
  5903. TL.setNameLoc(readSourceLocation());
  5904. }
  5905. void ASTRecordReader::readTypeLoc(TypeLoc TL) {
  5906. TypeLocReader TLR(*this);
  5907. for (; !TL.isNull(); TL = TL.getNextTypeLoc())
  5908. TLR.Visit(TL);
  5909. }
  5910. TypeSourceInfo *ASTRecordReader::readTypeSourceInfo() {
  5911. QualType InfoTy = readType();
  5912. if (InfoTy.isNull())
  5913. return nullptr;
  5914. TypeSourceInfo *TInfo = getContext().CreateTypeSourceInfo(InfoTy);
  5915. readTypeLoc(TInfo->getTypeLoc());
  5916. return TInfo;
  5917. }
  5918. QualType ASTReader::GetType(TypeID ID) {
  5919. assert(ContextObj && "reading type with no AST context");
  5920. ASTContext &Context = *ContextObj;
  5921. unsigned FastQuals = ID & Qualifiers::FastMask;
  5922. unsigned Index = ID >> Qualifiers::FastWidth;
  5923. if (Index < NUM_PREDEF_TYPE_IDS) {
  5924. QualType T;
  5925. switch ((PredefinedTypeIDs)Index) {
  5926. case PREDEF_TYPE_NULL_ID:
  5927. return QualType();
  5928. case PREDEF_TYPE_VOID_ID:
  5929. T = Context.VoidTy;
  5930. break;
  5931. case PREDEF_TYPE_BOOL_ID:
  5932. T = Context.BoolTy;
  5933. break;
  5934. case PREDEF_TYPE_CHAR_U_ID:
  5935. case PREDEF_TYPE_CHAR_S_ID:
  5936. // FIXME: Check that the signedness of CharTy is correct!
  5937. T = Context.CharTy;
  5938. break;
  5939. case PREDEF_TYPE_UCHAR_ID:
  5940. T = Context.UnsignedCharTy;
  5941. break;
  5942. case PREDEF_TYPE_USHORT_ID:
  5943. T = Context.UnsignedShortTy;
  5944. break;
  5945. case PREDEF_TYPE_UINT_ID:
  5946. T = Context.UnsignedIntTy;
  5947. break;
  5948. case PREDEF_TYPE_ULONG_ID:
  5949. T = Context.UnsignedLongTy;
  5950. break;
  5951. case PREDEF_TYPE_ULONGLONG_ID:
  5952. T = Context.UnsignedLongLongTy;
  5953. break;
  5954. case PREDEF_TYPE_UINT128_ID:
  5955. T = Context.UnsignedInt128Ty;
  5956. break;
  5957. case PREDEF_TYPE_SCHAR_ID:
  5958. T = Context.SignedCharTy;
  5959. break;
  5960. case PREDEF_TYPE_WCHAR_ID:
  5961. T = Context.WCharTy;
  5962. break;
  5963. case PREDEF_TYPE_SHORT_ID:
  5964. T = Context.ShortTy;
  5965. break;
  5966. case PREDEF_TYPE_INT_ID:
  5967. T = Context.IntTy;
  5968. break;
  5969. case PREDEF_TYPE_LONG_ID:
  5970. T = Context.LongTy;
  5971. break;
  5972. case PREDEF_TYPE_LONGLONG_ID:
  5973. T = Context.LongLongTy;
  5974. break;
  5975. case PREDEF_TYPE_INT128_ID:
  5976. T = Context.Int128Ty;
  5977. break;
  5978. case PREDEF_TYPE_BFLOAT16_ID:
  5979. T = Context.BFloat16Ty;
  5980. break;
  5981. case PREDEF_TYPE_HALF_ID:
  5982. T = Context.HalfTy;
  5983. break;
  5984. case PREDEF_TYPE_FLOAT_ID:
  5985. T = Context.FloatTy;
  5986. break;
  5987. case PREDEF_TYPE_DOUBLE_ID:
  5988. T = Context.DoubleTy;
  5989. break;
  5990. case PREDEF_TYPE_LONGDOUBLE_ID:
  5991. T = Context.LongDoubleTy;
  5992. break;
  5993. case PREDEF_TYPE_SHORT_ACCUM_ID:
  5994. T = Context.ShortAccumTy;
  5995. break;
  5996. case PREDEF_TYPE_ACCUM_ID:
  5997. T = Context.AccumTy;
  5998. break;
  5999. case PREDEF_TYPE_LONG_ACCUM_ID:
  6000. T = Context.LongAccumTy;
  6001. break;
  6002. case PREDEF_TYPE_USHORT_ACCUM_ID:
  6003. T = Context.UnsignedShortAccumTy;
  6004. break;
  6005. case PREDEF_TYPE_UACCUM_ID:
  6006. T = Context.UnsignedAccumTy;
  6007. break;
  6008. case PREDEF_TYPE_ULONG_ACCUM_ID:
  6009. T = Context.UnsignedLongAccumTy;
  6010. break;
  6011. case PREDEF_TYPE_SHORT_FRACT_ID:
  6012. T = Context.ShortFractTy;
  6013. break;
  6014. case PREDEF_TYPE_FRACT_ID:
  6015. T = Context.FractTy;
  6016. break;
  6017. case PREDEF_TYPE_LONG_FRACT_ID:
  6018. T = Context.LongFractTy;
  6019. break;
  6020. case PREDEF_TYPE_USHORT_FRACT_ID:
  6021. T = Context.UnsignedShortFractTy;
  6022. break;
  6023. case PREDEF_TYPE_UFRACT_ID:
  6024. T = Context.UnsignedFractTy;
  6025. break;
  6026. case PREDEF_TYPE_ULONG_FRACT_ID:
  6027. T = Context.UnsignedLongFractTy;
  6028. break;
  6029. case PREDEF_TYPE_SAT_SHORT_ACCUM_ID:
  6030. T = Context.SatShortAccumTy;
  6031. break;
  6032. case PREDEF_TYPE_SAT_ACCUM_ID:
  6033. T = Context.SatAccumTy;
  6034. break;
  6035. case PREDEF_TYPE_SAT_LONG_ACCUM_ID:
  6036. T = Context.SatLongAccumTy;
  6037. break;
  6038. case PREDEF_TYPE_SAT_USHORT_ACCUM_ID:
  6039. T = Context.SatUnsignedShortAccumTy;
  6040. break;
  6041. case PREDEF_TYPE_SAT_UACCUM_ID:
  6042. T = Context.SatUnsignedAccumTy;
  6043. break;
  6044. case PREDEF_TYPE_SAT_ULONG_ACCUM_ID:
  6045. T = Context.SatUnsignedLongAccumTy;
  6046. break;
  6047. case PREDEF_TYPE_SAT_SHORT_FRACT_ID:
  6048. T = Context.SatShortFractTy;
  6049. break;
  6050. case PREDEF_TYPE_SAT_FRACT_ID:
  6051. T = Context.SatFractTy;
  6052. break;
  6053. case PREDEF_TYPE_SAT_LONG_FRACT_ID:
  6054. T = Context.SatLongFractTy;
  6055. break;
  6056. case PREDEF_TYPE_SAT_USHORT_FRACT_ID:
  6057. T = Context.SatUnsignedShortFractTy;
  6058. break;
  6059. case PREDEF_TYPE_SAT_UFRACT_ID:
  6060. T = Context.SatUnsignedFractTy;
  6061. break;
  6062. case PREDEF_TYPE_SAT_ULONG_FRACT_ID:
  6063. T = Context.SatUnsignedLongFractTy;
  6064. break;
  6065. case PREDEF_TYPE_FLOAT16_ID:
  6066. T = Context.Float16Ty;
  6067. break;
  6068. case PREDEF_TYPE_FLOAT128_ID:
  6069. T = Context.Float128Ty;
  6070. break;
  6071. case PREDEF_TYPE_IBM128_ID:
  6072. T = Context.Ibm128Ty;
  6073. break;
  6074. case PREDEF_TYPE_OVERLOAD_ID:
  6075. T = Context.OverloadTy;
  6076. break;
  6077. case PREDEF_TYPE_BOUND_MEMBER:
  6078. T = Context.BoundMemberTy;
  6079. break;
  6080. case PREDEF_TYPE_PSEUDO_OBJECT:
  6081. T = Context.PseudoObjectTy;
  6082. break;
  6083. case PREDEF_TYPE_DEPENDENT_ID:
  6084. T = Context.DependentTy;
  6085. break;
  6086. case PREDEF_TYPE_UNKNOWN_ANY:
  6087. T = Context.UnknownAnyTy;
  6088. break;
  6089. case PREDEF_TYPE_NULLPTR_ID:
  6090. T = Context.NullPtrTy;
  6091. break;
  6092. case PREDEF_TYPE_CHAR8_ID:
  6093. T = Context.Char8Ty;
  6094. break;
  6095. case PREDEF_TYPE_CHAR16_ID:
  6096. T = Context.Char16Ty;
  6097. break;
  6098. case PREDEF_TYPE_CHAR32_ID:
  6099. T = Context.Char32Ty;
  6100. break;
  6101. case PREDEF_TYPE_OBJC_ID:
  6102. T = Context.ObjCBuiltinIdTy;
  6103. break;
  6104. case PREDEF_TYPE_OBJC_CLASS:
  6105. T = Context.ObjCBuiltinClassTy;
  6106. break;
  6107. case PREDEF_TYPE_OBJC_SEL:
  6108. T = Context.ObjCBuiltinSelTy;
  6109. break;
  6110. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  6111. case PREDEF_TYPE_##Id##_ID: \
  6112. T = Context.SingletonId; \
  6113. break;
  6114. #include "clang/Basic/OpenCLImageTypes.def"
  6115. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  6116. case PREDEF_TYPE_##Id##_ID: \
  6117. T = Context.Id##Ty; \
  6118. break;
  6119. #include "clang/Basic/OpenCLExtensionTypes.def"
  6120. case PREDEF_TYPE_SAMPLER_ID:
  6121. T = Context.OCLSamplerTy;
  6122. break;
  6123. case PREDEF_TYPE_EVENT_ID:
  6124. T = Context.OCLEventTy;
  6125. break;
  6126. case PREDEF_TYPE_CLK_EVENT_ID:
  6127. T = Context.OCLClkEventTy;
  6128. break;
  6129. case PREDEF_TYPE_QUEUE_ID:
  6130. T = Context.OCLQueueTy;
  6131. break;
  6132. case PREDEF_TYPE_RESERVE_ID_ID:
  6133. T = Context.OCLReserveIDTy;
  6134. break;
  6135. case PREDEF_TYPE_AUTO_DEDUCT:
  6136. T = Context.getAutoDeductType();
  6137. break;
  6138. case PREDEF_TYPE_AUTO_RREF_DEDUCT:
  6139. T = Context.getAutoRRefDeductType();
  6140. break;
  6141. case PREDEF_TYPE_ARC_UNBRIDGED_CAST:
  6142. T = Context.ARCUnbridgedCastTy;
  6143. break;
  6144. case PREDEF_TYPE_BUILTIN_FN:
  6145. T = Context.BuiltinFnTy;
  6146. break;
  6147. case PREDEF_TYPE_INCOMPLETE_MATRIX_IDX:
  6148. T = Context.IncompleteMatrixIdxTy;
  6149. break;
  6150. case PREDEF_TYPE_OMP_ARRAY_SECTION:
  6151. T = Context.OMPArraySectionTy;
  6152. break;
  6153. case PREDEF_TYPE_OMP_ARRAY_SHAPING:
  6154. T = Context.OMPArraySectionTy;
  6155. break;
  6156. case PREDEF_TYPE_OMP_ITERATOR:
  6157. T = Context.OMPIteratorTy;
  6158. break;
  6159. #define SVE_TYPE(Name, Id, SingletonId) \
  6160. case PREDEF_TYPE_##Id##_ID: \
  6161. T = Context.SingletonId; \
  6162. break;
  6163. #include "clang/Basic/AArch64SVEACLETypes.def"
  6164. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  6165. case PREDEF_TYPE_##Id##_ID: \
  6166. T = Context.Id##Ty; \
  6167. break;
  6168. #include "clang/Basic/PPCTypes.def"
  6169. #define RVV_TYPE(Name, Id, SingletonId) \
  6170. case PREDEF_TYPE_##Id##_ID: \
  6171. T = Context.SingletonId; \
  6172. break;
  6173. #include "clang/Basic/RISCVVTypes.def"
  6174. }
  6175. assert(!T.isNull() && "Unknown predefined type");
  6176. return T.withFastQualifiers(FastQuals);
  6177. }
  6178. Index -= NUM_PREDEF_TYPE_IDS;
  6179. assert(Index < TypesLoaded.size() && "Type index out-of-range");
  6180. if (TypesLoaded[Index].isNull()) {
  6181. TypesLoaded[Index] = readTypeRecord(Index);
  6182. if (TypesLoaded[Index].isNull())
  6183. return QualType();
  6184. TypesLoaded[Index]->setFromAST();
  6185. if (DeserializationListener)
  6186. DeserializationListener->TypeRead(TypeIdx::fromTypeID(ID),
  6187. TypesLoaded[Index]);
  6188. }
  6189. return TypesLoaded[Index].withFastQualifiers(FastQuals);
  6190. }
  6191. QualType ASTReader::getLocalType(ModuleFile &F, unsigned LocalID) {
  6192. return GetType(getGlobalTypeID(F, LocalID));
  6193. }
  6194. serialization::TypeID
  6195. ASTReader::getGlobalTypeID(ModuleFile &F, unsigned LocalID) const {
  6196. unsigned FastQuals = LocalID & Qualifiers::FastMask;
  6197. unsigned LocalIndex = LocalID >> Qualifiers::FastWidth;
  6198. if (LocalIndex < NUM_PREDEF_TYPE_IDS)
  6199. return LocalID;
  6200. if (!F.ModuleOffsetMap.empty())
  6201. ReadModuleOffsetMap(F);
  6202. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6203. = F.TypeRemap.find(LocalIndex - NUM_PREDEF_TYPE_IDS);
  6204. assert(I != F.TypeRemap.end() && "Invalid index into type index remap");
  6205. unsigned GlobalIndex = LocalIndex + I->second;
  6206. return (GlobalIndex << Qualifiers::FastWidth) | FastQuals;
  6207. }
  6208. TemplateArgumentLocInfo
  6209. ASTRecordReader::readTemplateArgumentLocInfo(TemplateArgument::ArgKind Kind) {
  6210. switch (Kind) {
  6211. case TemplateArgument::Expression:
  6212. return readExpr();
  6213. case TemplateArgument::Type:
  6214. return readTypeSourceInfo();
  6215. case TemplateArgument::Template: {
  6216. NestedNameSpecifierLoc QualifierLoc =
  6217. readNestedNameSpecifierLoc();
  6218. SourceLocation TemplateNameLoc = readSourceLocation();
  6219. return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
  6220. TemplateNameLoc, SourceLocation());
  6221. }
  6222. case TemplateArgument::TemplateExpansion: {
  6223. NestedNameSpecifierLoc QualifierLoc = readNestedNameSpecifierLoc();
  6224. SourceLocation TemplateNameLoc = readSourceLocation();
  6225. SourceLocation EllipsisLoc = readSourceLocation();
  6226. return TemplateArgumentLocInfo(getASTContext(), QualifierLoc,
  6227. TemplateNameLoc, EllipsisLoc);
  6228. }
  6229. case TemplateArgument::Null:
  6230. case TemplateArgument::Integral:
  6231. case TemplateArgument::Declaration:
  6232. case TemplateArgument::NullPtr:
  6233. case TemplateArgument::Pack:
  6234. // FIXME: Is this right?
  6235. return TemplateArgumentLocInfo();
  6236. }
  6237. llvm_unreachable("unexpected template argument loc");
  6238. }
  6239. TemplateArgumentLoc ASTRecordReader::readTemplateArgumentLoc() {
  6240. TemplateArgument Arg = readTemplateArgument();
  6241. if (Arg.getKind() == TemplateArgument::Expression) {
  6242. if (readBool()) // bool InfoHasSameExpr.
  6243. return TemplateArgumentLoc(Arg, TemplateArgumentLocInfo(Arg.getAsExpr()));
  6244. }
  6245. return TemplateArgumentLoc(Arg, readTemplateArgumentLocInfo(Arg.getKind()));
  6246. }
  6247. const ASTTemplateArgumentListInfo *
  6248. ASTRecordReader::readASTTemplateArgumentListInfo() {
  6249. SourceLocation LAngleLoc = readSourceLocation();
  6250. SourceLocation RAngleLoc = readSourceLocation();
  6251. unsigned NumArgsAsWritten = readInt();
  6252. TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
  6253. for (unsigned i = 0; i != NumArgsAsWritten; ++i)
  6254. TemplArgsInfo.addArgument(readTemplateArgumentLoc());
  6255. return ASTTemplateArgumentListInfo::Create(getContext(), TemplArgsInfo);
  6256. }
  6257. Decl *ASTReader::GetExternalDecl(uint32_t ID) {
  6258. return GetDecl(ID);
  6259. }
  6260. void ASTReader::CompleteRedeclChain(const Decl *D) {
  6261. if (NumCurrentElementsDeserializing) {
  6262. // We arrange to not care about the complete redeclaration chain while we're
  6263. // deserializing. Just remember that the AST has marked this one as complete
  6264. // but that it's not actually complete yet, so we know we still need to
  6265. // complete it later.
  6266. PendingIncompleteDeclChains.push_back(const_cast<Decl*>(D));
  6267. return;
  6268. }
  6269. if (!D->getDeclContext()) {
  6270. assert(isa<TranslationUnitDecl>(D) && "Not a TU?");
  6271. return;
  6272. }
  6273. const DeclContext *DC = D->getDeclContext()->getRedeclContext();
  6274. // If this is a named declaration, complete it by looking it up
  6275. // within its context.
  6276. //
  6277. // FIXME: Merging a function definition should merge
  6278. // all mergeable entities within it.
  6279. if (isa<TranslationUnitDecl>(DC) || isa<NamespaceDecl>(DC) ||
  6280. isa<CXXRecordDecl>(DC) || isa<EnumDecl>(DC)) {
  6281. if (DeclarationName Name = cast<NamedDecl>(D)->getDeclName()) {
  6282. if (!getContext().getLangOpts().CPlusPlus &&
  6283. isa<TranslationUnitDecl>(DC)) {
  6284. // Outside of C++, we don't have a lookup table for the TU, so update
  6285. // the identifier instead. (For C++ modules, we don't store decls
  6286. // in the serialized identifier table, so we do the lookup in the TU.)
  6287. auto *II = Name.getAsIdentifierInfo();
  6288. assert(II && "non-identifier name in C?");
  6289. if (II->isOutOfDate())
  6290. updateOutOfDateIdentifier(*II);
  6291. } else
  6292. DC->lookup(Name);
  6293. } else if (needsAnonymousDeclarationNumber(cast<NamedDecl>(D))) {
  6294. // Find all declarations of this kind from the relevant context.
  6295. for (auto *DCDecl : cast<Decl>(D->getLexicalDeclContext())->redecls()) {
  6296. auto *DC = cast<DeclContext>(DCDecl);
  6297. SmallVector<Decl*, 8> Decls;
  6298. FindExternalLexicalDecls(
  6299. DC, [&](Decl::Kind K) { return K == D->getKind(); }, Decls);
  6300. }
  6301. }
  6302. }
  6303. if (auto *CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
  6304. CTSD->getSpecializedTemplate()->LoadLazySpecializations();
  6305. if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
  6306. VTSD->getSpecializedTemplate()->LoadLazySpecializations();
  6307. if (auto *FD = dyn_cast<FunctionDecl>(D)) {
  6308. if (auto *Template = FD->getPrimaryTemplate())
  6309. Template->LoadLazySpecializations();
  6310. }
  6311. }
  6312. CXXCtorInitializer **
  6313. ASTReader::GetExternalCXXCtorInitializers(uint64_t Offset) {
  6314. RecordLocation Loc = getLocalBitOffset(Offset);
  6315. BitstreamCursor &Cursor = Loc.F->DeclsCursor;
  6316. SavedStreamPosition SavedPosition(Cursor);
  6317. if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
  6318. Error(std::move(Err));
  6319. return nullptr;
  6320. }
  6321. ReadingKindTracker ReadingKind(Read_Decl, *this);
  6322. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  6323. if (!MaybeCode) {
  6324. Error(MaybeCode.takeError());
  6325. return nullptr;
  6326. }
  6327. unsigned Code = MaybeCode.get();
  6328. ASTRecordReader Record(*this, *Loc.F);
  6329. Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
  6330. if (!MaybeRecCode) {
  6331. Error(MaybeRecCode.takeError());
  6332. return nullptr;
  6333. }
  6334. if (MaybeRecCode.get() != DECL_CXX_CTOR_INITIALIZERS) {
  6335. Error("malformed AST file: missing C++ ctor initializers");
  6336. return nullptr;
  6337. }
  6338. return Record.readCXXCtorInitializers();
  6339. }
  6340. CXXBaseSpecifier *ASTReader::GetExternalCXXBaseSpecifiers(uint64_t Offset) {
  6341. assert(ContextObj && "reading base specifiers with no AST context");
  6342. ASTContext &Context = *ContextObj;
  6343. RecordLocation Loc = getLocalBitOffset(Offset);
  6344. BitstreamCursor &Cursor = Loc.F->DeclsCursor;
  6345. SavedStreamPosition SavedPosition(Cursor);
  6346. if (llvm::Error Err = Cursor.JumpToBit(Loc.Offset)) {
  6347. Error(std::move(Err));
  6348. return nullptr;
  6349. }
  6350. ReadingKindTracker ReadingKind(Read_Decl, *this);
  6351. Expected<unsigned> MaybeCode = Cursor.ReadCode();
  6352. if (!MaybeCode) {
  6353. Error(MaybeCode.takeError());
  6354. return nullptr;
  6355. }
  6356. unsigned Code = MaybeCode.get();
  6357. ASTRecordReader Record(*this, *Loc.F);
  6358. Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code);
  6359. if (!MaybeRecCode) {
  6360. Error(MaybeCode.takeError());
  6361. return nullptr;
  6362. }
  6363. unsigned RecCode = MaybeRecCode.get();
  6364. if (RecCode != DECL_CXX_BASE_SPECIFIERS) {
  6365. Error("malformed AST file: missing C++ base specifiers");
  6366. return nullptr;
  6367. }
  6368. unsigned NumBases = Record.readInt();
  6369. void *Mem = Context.Allocate(sizeof(CXXBaseSpecifier) * NumBases);
  6370. CXXBaseSpecifier *Bases = new (Mem) CXXBaseSpecifier [NumBases];
  6371. for (unsigned I = 0; I != NumBases; ++I)
  6372. Bases[I] = Record.readCXXBaseSpecifier();
  6373. return Bases;
  6374. }
  6375. serialization::DeclID
  6376. ASTReader::getGlobalDeclID(ModuleFile &F, LocalDeclID LocalID) const {
  6377. if (LocalID < NUM_PREDEF_DECL_IDS)
  6378. return LocalID;
  6379. if (!F.ModuleOffsetMap.empty())
  6380. ReadModuleOffsetMap(F);
  6381. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  6382. = F.DeclRemap.find(LocalID - NUM_PREDEF_DECL_IDS);
  6383. assert(I != F.DeclRemap.end() && "Invalid index into decl index remap");
  6384. return LocalID + I->second;
  6385. }
  6386. bool ASTReader::isDeclIDFromModule(serialization::GlobalDeclID ID,
  6387. ModuleFile &M) const {
  6388. // Predefined decls aren't from any module.
  6389. if (ID < NUM_PREDEF_DECL_IDS)
  6390. return false;
  6391. return ID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
  6392. ID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls;
  6393. }
  6394. ModuleFile *ASTReader::getOwningModuleFile(const Decl *D) {
  6395. if (!D->isFromASTFile())
  6396. return nullptr;
  6397. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(D->getGlobalID());
  6398. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  6399. return I->second;
  6400. }
  6401. SourceLocation ASTReader::getSourceLocationForDeclID(GlobalDeclID ID) {
  6402. if (ID < NUM_PREDEF_DECL_IDS)
  6403. return SourceLocation();
  6404. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  6405. if (Index > DeclsLoaded.size()) {
  6406. Error("declaration ID out-of-range for AST file");
  6407. return SourceLocation();
  6408. }
  6409. if (Decl *D = DeclsLoaded[Index])
  6410. return D->getLocation();
  6411. SourceLocation Loc;
  6412. DeclCursorForID(ID, Loc);
  6413. return Loc;
  6414. }
  6415. static Decl *getPredefinedDecl(ASTContext &Context, PredefinedDeclIDs ID) {
  6416. switch (ID) {
  6417. case PREDEF_DECL_NULL_ID:
  6418. return nullptr;
  6419. case PREDEF_DECL_TRANSLATION_UNIT_ID:
  6420. return Context.getTranslationUnitDecl();
  6421. case PREDEF_DECL_OBJC_ID_ID:
  6422. return Context.getObjCIdDecl();
  6423. case PREDEF_DECL_OBJC_SEL_ID:
  6424. return Context.getObjCSelDecl();
  6425. case PREDEF_DECL_OBJC_CLASS_ID:
  6426. return Context.getObjCClassDecl();
  6427. case PREDEF_DECL_OBJC_PROTOCOL_ID:
  6428. return Context.getObjCProtocolDecl();
  6429. case PREDEF_DECL_INT_128_ID:
  6430. return Context.getInt128Decl();
  6431. case PREDEF_DECL_UNSIGNED_INT_128_ID:
  6432. return Context.getUInt128Decl();
  6433. case PREDEF_DECL_OBJC_INSTANCETYPE_ID:
  6434. return Context.getObjCInstanceTypeDecl();
  6435. case PREDEF_DECL_BUILTIN_VA_LIST_ID:
  6436. return Context.getBuiltinVaListDecl();
  6437. case PREDEF_DECL_VA_LIST_TAG:
  6438. return Context.getVaListTagDecl();
  6439. case PREDEF_DECL_BUILTIN_MS_VA_LIST_ID:
  6440. return Context.getBuiltinMSVaListDecl();
  6441. case PREDEF_DECL_BUILTIN_MS_GUID_ID:
  6442. return Context.getMSGuidTagDecl();
  6443. case PREDEF_DECL_EXTERN_C_CONTEXT_ID:
  6444. return Context.getExternCContextDecl();
  6445. case PREDEF_DECL_MAKE_INTEGER_SEQ_ID:
  6446. return Context.getMakeIntegerSeqDecl();
  6447. case PREDEF_DECL_CF_CONSTANT_STRING_ID:
  6448. return Context.getCFConstantStringDecl();
  6449. case PREDEF_DECL_CF_CONSTANT_STRING_TAG_ID:
  6450. return Context.getCFConstantStringTagDecl();
  6451. case PREDEF_DECL_TYPE_PACK_ELEMENT_ID:
  6452. return Context.getTypePackElementDecl();
  6453. }
  6454. llvm_unreachable("PredefinedDeclIDs unknown enum value");
  6455. }
  6456. Decl *ASTReader::GetExistingDecl(DeclID ID) {
  6457. assert(ContextObj && "reading decl with no AST context");
  6458. if (ID < NUM_PREDEF_DECL_IDS) {
  6459. Decl *D = getPredefinedDecl(*ContextObj, (PredefinedDeclIDs)ID);
  6460. if (D) {
  6461. // Track that we have merged the declaration with ID \p ID into the
  6462. // pre-existing predefined declaration \p D.
  6463. auto &Merged = KeyDecls[D->getCanonicalDecl()];
  6464. if (Merged.empty())
  6465. Merged.push_back(ID);
  6466. }
  6467. return D;
  6468. }
  6469. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  6470. if (Index >= DeclsLoaded.size()) {
  6471. assert(0 && "declaration ID out-of-range for AST file");
  6472. Error("declaration ID out-of-range for AST file");
  6473. return nullptr;
  6474. }
  6475. return DeclsLoaded[Index];
  6476. }
  6477. Decl *ASTReader::GetDecl(DeclID ID) {
  6478. if (ID < NUM_PREDEF_DECL_IDS)
  6479. return GetExistingDecl(ID);
  6480. unsigned Index = ID - NUM_PREDEF_DECL_IDS;
  6481. if (Index >= DeclsLoaded.size()) {
  6482. assert(0 && "declaration ID out-of-range for AST file");
  6483. Error("declaration ID out-of-range for AST file");
  6484. return nullptr;
  6485. }
  6486. if (!DeclsLoaded[Index]) {
  6487. ReadDeclRecord(ID);
  6488. if (DeserializationListener)
  6489. DeserializationListener->DeclRead(ID, DeclsLoaded[Index]);
  6490. }
  6491. return DeclsLoaded[Index];
  6492. }
  6493. DeclID ASTReader::mapGlobalIDToModuleFileGlobalID(ModuleFile &M,
  6494. DeclID GlobalID) {
  6495. if (GlobalID < NUM_PREDEF_DECL_IDS)
  6496. return GlobalID;
  6497. GlobalDeclMapType::const_iterator I = GlobalDeclMap.find(GlobalID);
  6498. assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
  6499. ModuleFile *Owner = I->second;
  6500. llvm::DenseMap<ModuleFile *, serialization::DeclID>::iterator Pos
  6501. = M.GlobalToLocalDeclIDs.find(Owner);
  6502. if (Pos == M.GlobalToLocalDeclIDs.end())
  6503. return 0;
  6504. return GlobalID - Owner->BaseDeclID + Pos->second;
  6505. }
  6506. serialization::DeclID ASTReader::ReadDeclID(ModuleFile &F,
  6507. const RecordData &Record,
  6508. unsigned &Idx) {
  6509. if (Idx >= Record.size()) {
  6510. Error("Corrupted AST file");
  6511. return 0;
  6512. }
  6513. return getGlobalDeclID(F, Record[Idx++]);
  6514. }
  6515. /// Resolve the offset of a statement into a statement.
  6516. ///
  6517. /// This operation will read a new statement from the external
  6518. /// source each time it is called, and is meant to be used via a
  6519. /// LazyOffsetPtr (which is used by Decls for the body of functions, etc).
  6520. Stmt *ASTReader::GetExternalDeclStmt(uint64_t Offset) {
  6521. // Switch case IDs are per Decl.
  6522. ClearSwitchCaseIDs();
  6523. // Offset here is a global offset across the entire chain.
  6524. RecordLocation Loc = getLocalBitOffset(Offset);
  6525. if (llvm::Error Err = Loc.F->DeclsCursor.JumpToBit(Loc.Offset)) {
  6526. Error(std::move(Err));
  6527. return nullptr;
  6528. }
  6529. assert(NumCurrentElementsDeserializing == 0 &&
  6530. "should not be called while already deserializing");
  6531. Deserializing D(this);
  6532. return ReadStmtFromStream(*Loc.F);
  6533. }
  6534. void ASTReader::FindExternalLexicalDecls(
  6535. const DeclContext *DC, llvm::function_ref<bool(Decl::Kind)> IsKindWeWant,
  6536. SmallVectorImpl<Decl *> &Decls) {
  6537. bool PredefsVisited[NUM_PREDEF_DECL_IDS] = {};
  6538. auto Visit = [&] (ModuleFile *M, LexicalContents LexicalDecls) {
  6539. assert(LexicalDecls.size() % 2 == 0 && "expected an even number of entries");
  6540. for (int I = 0, N = LexicalDecls.size(); I != N; I += 2) {
  6541. auto K = (Decl::Kind)+LexicalDecls[I];
  6542. if (!IsKindWeWant(K))
  6543. continue;
  6544. auto ID = (serialization::DeclID)+LexicalDecls[I + 1];
  6545. // Don't add predefined declarations to the lexical context more
  6546. // than once.
  6547. if (ID < NUM_PREDEF_DECL_IDS) {
  6548. if (PredefsVisited[ID])
  6549. continue;
  6550. PredefsVisited[ID] = true;
  6551. }
  6552. if (Decl *D = GetLocalDecl(*M, ID)) {
  6553. assert(D->getKind() == K && "wrong kind for lexical decl");
  6554. if (!DC->isDeclInLexicalTraversal(D))
  6555. Decls.push_back(D);
  6556. }
  6557. }
  6558. };
  6559. if (isa<TranslationUnitDecl>(DC)) {
  6560. for (auto Lexical : TULexicalDecls)
  6561. Visit(Lexical.first, Lexical.second);
  6562. } else {
  6563. auto I = LexicalDecls.find(DC);
  6564. if (I != LexicalDecls.end())
  6565. Visit(I->second.first, I->second.second);
  6566. }
  6567. ++NumLexicalDeclContextsRead;
  6568. }
  6569. namespace {
  6570. class DeclIDComp {
  6571. ASTReader &Reader;
  6572. ModuleFile &Mod;
  6573. public:
  6574. DeclIDComp(ASTReader &Reader, ModuleFile &M) : Reader(Reader), Mod(M) {}
  6575. bool operator()(LocalDeclID L, LocalDeclID R) const {
  6576. SourceLocation LHS = getLocation(L);
  6577. SourceLocation RHS = getLocation(R);
  6578. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  6579. }
  6580. bool operator()(SourceLocation LHS, LocalDeclID R) const {
  6581. SourceLocation RHS = getLocation(R);
  6582. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  6583. }
  6584. bool operator()(LocalDeclID L, SourceLocation RHS) const {
  6585. SourceLocation LHS = getLocation(L);
  6586. return Reader.getSourceManager().isBeforeInTranslationUnit(LHS, RHS);
  6587. }
  6588. SourceLocation getLocation(LocalDeclID ID) const {
  6589. return Reader.getSourceManager().getFileLoc(
  6590. Reader.getSourceLocationForDeclID(Reader.getGlobalDeclID(Mod, ID)));
  6591. }
  6592. };
  6593. } // namespace
  6594. void ASTReader::FindFileRegionDecls(FileID File,
  6595. unsigned Offset, unsigned Length,
  6596. SmallVectorImpl<Decl *> &Decls) {
  6597. SourceManager &SM = getSourceManager();
  6598. llvm::DenseMap<FileID, FileDeclsInfo>::iterator I = FileDeclIDs.find(File);
  6599. if (I == FileDeclIDs.end())
  6600. return;
  6601. FileDeclsInfo &DInfo = I->second;
  6602. if (DInfo.Decls.empty())
  6603. return;
  6604. SourceLocation
  6605. BeginLoc = SM.getLocForStartOfFile(File).getLocWithOffset(Offset);
  6606. SourceLocation EndLoc = BeginLoc.getLocWithOffset(Length);
  6607. DeclIDComp DIDComp(*this, *DInfo.Mod);
  6608. ArrayRef<serialization::LocalDeclID>::iterator BeginIt =
  6609. llvm::lower_bound(DInfo.Decls, BeginLoc, DIDComp);
  6610. if (BeginIt != DInfo.Decls.begin())
  6611. --BeginIt;
  6612. // If we are pointing at a top-level decl inside an objc container, we need
  6613. // to backtrack until we find it otherwise we will fail to report that the
  6614. // region overlaps with an objc container.
  6615. while (BeginIt != DInfo.Decls.begin() &&
  6616. GetDecl(getGlobalDeclID(*DInfo.Mod, *BeginIt))
  6617. ->isTopLevelDeclInObjCContainer())
  6618. --BeginIt;
  6619. ArrayRef<serialization::LocalDeclID>::iterator EndIt =
  6620. llvm::upper_bound(DInfo.Decls, EndLoc, DIDComp);
  6621. if (EndIt != DInfo.Decls.end())
  6622. ++EndIt;
  6623. for (ArrayRef<serialization::LocalDeclID>::iterator
  6624. DIt = BeginIt; DIt != EndIt; ++DIt)
  6625. Decls.push_back(GetDecl(getGlobalDeclID(*DInfo.Mod, *DIt)));
  6626. }
  6627. bool
  6628. ASTReader::FindExternalVisibleDeclsByName(const DeclContext *DC,
  6629. DeclarationName Name) {
  6630. assert(DC->hasExternalVisibleStorage() && DC == DC->getPrimaryContext() &&
  6631. "DeclContext has no visible decls in storage");
  6632. if (!Name)
  6633. return false;
  6634. auto It = Lookups.find(DC);
  6635. if (It == Lookups.end())
  6636. return false;
  6637. Deserializing LookupResults(this);
  6638. // Load the list of declarations.
  6639. SmallVector<NamedDecl *, 64> Decls;
  6640. llvm::SmallPtrSet<NamedDecl *, 8> Found;
  6641. for (DeclID ID : It->second.Table.find(Name)) {
  6642. NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
  6643. if (ND->getDeclName() == Name && Found.insert(ND).second)
  6644. Decls.push_back(ND);
  6645. }
  6646. ++NumVisibleDeclContextsRead;
  6647. SetExternalVisibleDeclsForName(DC, Name, Decls);
  6648. return !Decls.empty();
  6649. }
  6650. void ASTReader::completeVisibleDeclsMap(const DeclContext *DC) {
  6651. if (!DC->hasExternalVisibleStorage())
  6652. return;
  6653. auto It = Lookups.find(DC);
  6654. assert(It != Lookups.end() &&
  6655. "have external visible storage but no lookup tables");
  6656. DeclsMap Decls;
  6657. for (DeclID ID : It->second.Table.findAll()) {
  6658. NamedDecl *ND = cast<NamedDecl>(GetDecl(ID));
  6659. Decls[ND->getDeclName()].push_back(ND);
  6660. }
  6661. ++NumVisibleDeclContextsRead;
  6662. for (DeclsMap::iterator I = Decls.begin(), E = Decls.end(); I != E; ++I) {
  6663. SetExternalVisibleDeclsForName(DC, I->first, I->second);
  6664. }
  6665. const_cast<DeclContext *>(DC)->setHasExternalVisibleStorage(false);
  6666. }
  6667. const serialization::reader::DeclContextLookupTable *
  6668. ASTReader::getLoadedLookupTables(DeclContext *Primary) const {
  6669. auto I = Lookups.find(Primary);
  6670. return I == Lookups.end() ? nullptr : &I->second;
  6671. }
  6672. /// Under non-PCH compilation the consumer receives the objc methods
  6673. /// before receiving the implementation, and codegen depends on this.
  6674. /// We simulate this by deserializing and passing to consumer the methods of the
  6675. /// implementation before passing the deserialized implementation decl.
  6676. static void PassObjCImplDeclToConsumer(ObjCImplDecl *ImplD,
  6677. ASTConsumer *Consumer) {
  6678. assert(ImplD && Consumer);
  6679. for (auto *I : ImplD->methods())
  6680. Consumer->HandleInterestingDecl(DeclGroupRef(I));
  6681. Consumer->HandleInterestingDecl(DeclGroupRef(ImplD));
  6682. }
  6683. void ASTReader::PassInterestingDeclToConsumer(Decl *D) {
  6684. if (ObjCImplDecl *ImplD = dyn_cast<ObjCImplDecl>(D))
  6685. PassObjCImplDeclToConsumer(ImplD, Consumer);
  6686. else
  6687. Consumer->HandleInterestingDecl(DeclGroupRef(D));
  6688. }
  6689. void ASTReader::StartTranslationUnit(ASTConsumer *Consumer) {
  6690. this->Consumer = Consumer;
  6691. if (Consumer)
  6692. PassInterestingDeclsToConsumer();
  6693. if (DeserializationListener)
  6694. DeserializationListener->ReaderInitialized(this);
  6695. }
  6696. void ASTReader::PrintStats() {
  6697. std::fprintf(stderr, "*** AST File Statistics:\n");
  6698. unsigned NumTypesLoaded =
  6699. TypesLoaded.size() - llvm::count(TypesLoaded, QualType());
  6700. unsigned NumDeclsLoaded =
  6701. DeclsLoaded.size() - llvm::count(DeclsLoaded, (Decl *)nullptr);
  6702. unsigned NumIdentifiersLoaded =
  6703. IdentifiersLoaded.size() -
  6704. llvm::count(IdentifiersLoaded, (IdentifierInfo *)nullptr);
  6705. unsigned NumMacrosLoaded =
  6706. MacrosLoaded.size() - llvm::count(MacrosLoaded, (MacroInfo *)nullptr);
  6707. unsigned NumSelectorsLoaded =
  6708. SelectorsLoaded.size() - llvm::count(SelectorsLoaded, Selector());
  6709. if (unsigned TotalNumSLocEntries = getTotalNumSLocs())
  6710. std::fprintf(stderr, " %u/%u source location entries read (%f%%)\n",
  6711. NumSLocEntriesRead, TotalNumSLocEntries,
  6712. ((float)NumSLocEntriesRead/TotalNumSLocEntries * 100));
  6713. if (!TypesLoaded.empty())
  6714. std::fprintf(stderr, " %u/%u types read (%f%%)\n",
  6715. NumTypesLoaded, (unsigned)TypesLoaded.size(),
  6716. ((float)NumTypesLoaded/TypesLoaded.size() * 100));
  6717. if (!DeclsLoaded.empty())
  6718. std::fprintf(stderr, " %u/%u declarations read (%f%%)\n",
  6719. NumDeclsLoaded, (unsigned)DeclsLoaded.size(),
  6720. ((float)NumDeclsLoaded/DeclsLoaded.size() * 100));
  6721. if (!IdentifiersLoaded.empty())
  6722. std::fprintf(stderr, " %u/%u identifiers read (%f%%)\n",
  6723. NumIdentifiersLoaded, (unsigned)IdentifiersLoaded.size(),
  6724. ((float)NumIdentifiersLoaded/IdentifiersLoaded.size() * 100));
  6725. if (!MacrosLoaded.empty())
  6726. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  6727. NumMacrosLoaded, (unsigned)MacrosLoaded.size(),
  6728. ((float)NumMacrosLoaded/MacrosLoaded.size() * 100));
  6729. if (!SelectorsLoaded.empty())
  6730. std::fprintf(stderr, " %u/%u selectors read (%f%%)\n",
  6731. NumSelectorsLoaded, (unsigned)SelectorsLoaded.size(),
  6732. ((float)NumSelectorsLoaded/SelectorsLoaded.size() * 100));
  6733. if (TotalNumStatements)
  6734. std::fprintf(stderr, " %u/%u statements read (%f%%)\n",
  6735. NumStatementsRead, TotalNumStatements,
  6736. ((float)NumStatementsRead/TotalNumStatements * 100));
  6737. if (TotalNumMacros)
  6738. std::fprintf(stderr, " %u/%u macros read (%f%%)\n",
  6739. NumMacrosRead, TotalNumMacros,
  6740. ((float)NumMacrosRead/TotalNumMacros * 100));
  6741. if (TotalLexicalDeclContexts)
  6742. std::fprintf(stderr, " %u/%u lexical declcontexts read (%f%%)\n",
  6743. NumLexicalDeclContextsRead, TotalLexicalDeclContexts,
  6744. ((float)NumLexicalDeclContextsRead/TotalLexicalDeclContexts
  6745. * 100));
  6746. if (TotalVisibleDeclContexts)
  6747. std::fprintf(stderr, " %u/%u visible declcontexts read (%f%%)\n",
  6748. NumVisibleDeclContextsRead, TotalVisibleDeclContexts,
  6749. ((float)NumVisibleDeclContextsRead/TotalVisibleDeclContexts
  6750. * 100));
  6751. if (TotalNumMethodPoolEntries)
  6752. std::fprintf(stderr, " %u/%u method pool entries read (%f%%)\n",
  6753. NumMethodPoolEntriesRead, TotalNumMethodPoolEntries,
  6754. ((float)NumMethodPoolEntriesRead/TotalNumMethodPoolEntries
  6755. * 100));
  6756. if (NumMethodPoolLookups)
  6757. std::fprintf(stderr, " %u/%u method pool lookups succeeded (%f%%)\n",
  6758. NumMethodPoolHits, NumMethodPoolLookups,
  6759. ((float)NumMethodPoolHits/NumMethodPoolLookups * 100.0));
  6760. if (NumMethodPoolTableLookups)
  6761. std::fprintf(stderr, " %u/%u method pool table lookups succeeded (%f%%)\n",
  6762. NumMethodPoolTableHits, NumMethodPoolTableLookups,
  6763. ((float)NumMethodPoolTableHits/NumMethodPoolTableLookups
  6764. * 100.0));
  6765. if (NumIdentifierLookupHits)
  6766. std::fprintf(stderr,
  6767. " %u / %u identifier table lookups succeeded (%f%%)\n",
  6768. NumIdentifierLookupHits, NumIdentifierLookups,
  6769. (double)NumIdentifierLookupHits*100.0/NumIdentifierLookups);
  6770. if (GlobalIndex) {
  6771. std::fprintf(stderr, "\n");
  6772. GlobalIndex->printStats();
  6773. }
  6774. std::fprintf(stderr, "\n");
  6775. dump();
  6776. std::fprintf(stderr, "\n");
  6777. }
  6778. template<typename Key, typename ModuleFile, unsigned InitialCapacity>
  6779. LLVM_DUMP_METHOD static void
  6780. dumpModuleIDMap(StringRef Name,
  6781. const ContinuousRangeMap<Key, ModuleFile *,
  6782. InitialCapacity> &Map) {
  6783. if (Map.begin() == Map.end())
  6784. return;
  6785. using MapType = ContinuousRangeMap<Key, ModuleFile *, InitialCapacity>;
  6786. llvm::errs() << Name << ":\n";
  6787. for (typename MapType::const_iterator I = Map.begin(), IEnd = Map.end();
  6788. I != IEnd; ++I) {
  6789. llvm::errs() << " " << I->first << " -> " << I->second->FileName
  6790. << "\n";
  6791. }
  6792. }
  6793. LLVM_DUMP_METHOD void ASTReader::dump() {
  6794. llvm::errs() << "*** PCH/ModuleFile Remappings:\n";
  6795. dumpModuleIDMap("Global bit offset map", GlobalBitOffsetsMap);
  6796. dumpModuleIDMap("Global source location entry map", GlobalSLocEntryMap);
  6797. dumpModuleIDMap("Global type map", GlobalTypeMap);
  6798. dumpModuleIDMap("Global declaration map", GlobalDeclMap);
  6799. dumpModuleIDMap("Global identifier map", GlobalIdentifierMap);
  6800. dumpModuleIDMap("Global macro map", GlobalMacroMap);
  6801. dumpModuleIDMap("Global submodule map", GlobalSubmoduleMap);
  6802. dumpModuleIDMap("Global selector map", GlobalSelectorMap);
  6803. dumpModuleIDMap("Global preprocessed entity map",
  6804. GlobalPreprocessedEntityMap);
  6805. llvm::errs() << "\n*** PCH/Modules Loaded:";
  6806. for (ModuleFile &M : ModuleMgr)
  6807. M.dump();
  6808. }
  6809. /// Return the amount of memory used by memory buffers, breaking down
  6810. /// by heap-backed versus mmap'ed memory.
  6811. void ASTReader::getMemoryBufferSizes(MemoryBufferSizes &sizes) const {
  6812. for (ModuleFile &I : ModuleMgr) {
  6813. if (llvm::MemoryBuffer *buf = I.Buffer) {
  6814. size_t bytes = buf->getBufferSize();
  6815. switch (buf->getBufferKind()) {
  6816. case llvm::MemoryBuffer::MemoryBuffer_Malloc:
  6817. sizes.malloc_bytes += bytes;
  6818. break;
  6819. case llvm::MemoryBuffer::MemoryBuffer_MMap:
  6820. sizes.mmap_bytes += bytes;
  6821. break;
  6822. }
  6823. }
  6824. }
  6825. }
  6826. void ASTReader::InitializeSema(Sema &S) {
  6827. SemaObj = &S;
  6828. S.addExternalSource(this);
  6829. // Makes sure any declarations that were deserialized "too early"
  6830. // still get added to the identifier's declaration chains.
  6831. for (uint64_t ID : PreloadedDeclIDs) {
  6832. NamedDecl *D = cast<NamedDecl>(GetDecl(ID));
  6833. pushExternalDeclIntoScope(D, D->getDeclName());
  6834. }
  6835. PreloadedDeclIDs.clear();
  6836. // FIXME: What happens if these are changed by a module import?
  6837. if (!FPPragmaOptions.empty()) {
  6838. assert(FPPragmaOptions.size() == 1 && "Wrong number of FP_PRAGMA_OPTIONS");
  6839. FPOptionsOverride NewOverrides =
  6840. FPOptionsOverride::getFromOpaqueInt(FPPragmaOptions[0]);
  6841. SemaObj->CurFPFeatures =
  6842. NewOverrides.applyOverrides(SemaObj->getLangOpts());
  6843. }
  6844. SemaObj->OpenCLFeatures = OpenCLExtensions;
  6845. UpdateSema();
  6846. }
  6847. void ASTReader::UpdateSema() {
  6848. assert(SemaObj && "no Sema to update");
  6849. // Load the offsets of the declarations that Sema references.
  6850. // They will be lazily deserialized when needed.
  6851. if (!SemaDeclRefs.empty()) {
  6852. assert(SemaDeclRefs.size() % 3 == 0);
  6853. for (unsigned I = 0; I != SemaDeclRefs.size(); I += 3) {
  6854. if (!SemaObj->StdNamespace)
  6855. SemaObj->StdNamespace = SemaDeclRefs[I];
  6856. if (!SemaObj->StdBadAlloc)
  6857. SemaObj->StdBadAlloc = SemaDeclRefs[I+1];
  6858. if (!SemaObj->StdAlignValT)
  6859. SemaObj->StdAlignValT = SemaDeclRefs[I+2];
  6860. }
  6861. SemaDeclRefs.clear();
  6862. }
  6863. // Update the state of pragmas. Use the same API as if we had encountered the
  6864. // pragma in the source.
  6865. if(OptimizeOffPragmaLocation.isValid())
  6866. SemaObj->ActOnPragmaOptimize(/* On = */ false, OptimizeOffPragmaLocation);
  6867. if (PragmaMSStructState != -1)
  6868. SemaObj->ActOnPragmaMSStruct((PragmaMSStructKind)PragmaMSStructState);
  6869. if (PointersToMembersPragmaLocation.isValid()) {
  6870. SemaObj->ActOnPragmaMSPointersToMembers(
  6871. (LangOptions::PragmaMSPointersToMembersKind)
  6872. PragmaMSPointersToMembersState,
  6873. PointersToMembersPragmaLocation);
  6874. }
  6875. SemaObj->ForceCUDAHostDeviceDepth = ForceCUDAHostDeviceDepth;
  6876. if (PragmaAlignPackCurrentValue) {
  6877. // The bottom of the stack might have a default value. It must be adjusted
  6878. // to the current value to ensure that the packing state is preserved after
  6879. // popping entries that were included/imported from a PCH/module.
  6880. bool DropFirst = false;
  6881. if (!PragmaAlignPackStack.empty() &&
  6882. PragmaAlignPackStack.front().Location.isInvalid()) {
  6883. assert(PragmaAlignPackStack.front().Value ==
  6884. SemaObj->AlignPackStack.DefaultValue &&
  6885. "Expected a default alignment value");
  6886. SemaObj->AlignPackStack.Stack.emplace_back(
  6887. PragmaAlignPackStack.front().SlotLabel,
  6888. SemaObj->AlignPackStack.CurrentValue,
  6889. SemaObj->AlignPackStack.CurrentPragmaLocation,
  6890. PragmaAlignPackStack.front().PushLocation);
  6891. DropFirst = true;
  6892. }
  6893. for (const auto &Entry : llvm::makeArrayRef(PragmaAlignPackStack)
  6894. .drop_front(DropFirst ? 1 : 0)) {
  6895. SemaObj->AlignPackStack.Stack.emplace_back(
  6896. Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
  6897. }
  6898. if (PragmaAlignPackCurrentLocation.isInvalid()) {
  6899. assert(*PragmaAlignPackCurrentValue ==
  6900. SemaObj->AlignPackStack.DefaultValue &&
  6901. "Expected a default align and pack value");
  6902. // Keep the current values.
  6903. } else {
  6904. SemaObj->AlignPackStack.CurrentValue = *PragmaAlignPackCurrentValue;
  6905. SemaObj->AlignPackStack.CurrentPragmaLocation =
  6906. PragmaAlignPackCurrentLocation;
  6907. }
  6908. }
  6909. if (FpPragmaCurrentValue) {
  6910. // The bottom of the stack might have a default value. It must be adjusted
  6911. // to the current value to ensure that fp-pragma state is preserved after
  6912. // popping entries that were included/imported from a PCH/module.
  6913. bool DropFirst = false;
  6914. if (!FpPragmaStack.empty() && FpPragmaStack.front().Location.isInvalid()) {
  6915. assert(FpPragmaStack.front().Value ==
  6916. SemaObj->FpPragmaStack.DefaultValue &&
  6917. "Expected a default pragma float_control value");
  6918. SemaObj->FpPragmaStack.Stack.emplace_back(
  6919. FpPragmaStack.front().SlotLabel, SemaObj->FpPragmaStack.CurrentValue,
  6920. SemaObj->FpPragmaStack.CurrentPragmaLocation,
  6921. FpPragmaStack.front().PushLocation);
  6922. DropFirst = true;
  6923. }
  6924. for (const auto &Entry :
  6925. llvm::makeArrayRef(FpPragmaStack).drop_front(DropFirst ? 1 : 0))
  6926. SemaObj->FpPragmaStack.Stack.emplace_back(
  6927. Entry.SlotLabel, Entry.Value, Entry.Location, Entry.PushLocation);
  6928. if (FpPragmaCurrentLocation.isInvalid()) {
  6929. assert(*FpPragmaCurrentValue == SemaObj->FpPragmaStack.DefaultValue &&
  6930. "Expected a default pragma float_control value");
  6931. // Keep the current values.
  6932. } else {
  6933. SemaObj->FpPragmaStack.CurrentValue = *FpPragmaCurrentValue;
  6934. SemaObj->FpPragmaStack.CurrentPragmaLocation = FpPragmaCurrentLocation;
  6935. }
  6936. }
  6937. // For non-modular AST files, restore visiblity of modules.
  6938. for (auto &Import : ImportedModules) {
  6939. if (Import.ImportLoc.isInvalid())
  6940. continue;
  6941. if (Module *Imported = getSubmodule(Import.ID)) {
  6942. SemaObj->makeModuleVisible(Imported, Import.ImportLoc);
  6943. }
  6944. }
  6945. }
  6946. IdentifierInfo *ASTReader::get(StringRef Name) {
  6947. // Note that we are loading an identifier.
  6948. Deserializing AnIdentifier(this);
  6949. IdentifierLookupVisitor Visitor(Name, /*PriorGeneration=*/0,
  6950. NumIdentifierLookups,
  6951. NumIdentifierLookupHits);
  6952. // We don't need to do identifier table lookups in C++ modules (we preload
  6953. // all interesting declarations, and don't need to use the scope for name
  6954. // lookups). Perform the lookup in PCH files, though, since we don't build
  6955. // a complete initial identifier table if we're carrying on from a PCH.
  6956. if (PP.getLangOpts().CPlusPlus) {
  6957. for (auto F : ModuleMgr.pch_modules())
  6958. if (Visitor(*F))
  6959. break;
  6960. } else {
  6961. // If there is a global index, look there first to determine which modules
  6962. // provably do not have any results for this identifier.
  6963. GlobalModuleIndex::HitSet Hits;
  6964. GlobalModuleIndex::HitSet *HitsPtr = nullptr;
  6965. if (!loadGlobalIndex()) {
  6966. if (GlobalIndex->lookupIdentifier(Name, Hits)) {
  6967. HitsPtr = &Hits;
  6968. }
  6969. }
  6970. ModuleMgr.visit(Visitor, HitsPtr);
  6971. }
  6972. IdentifierInfo *II = Visitor.getIdentifierInfo();
  6973. markIdentifierUpToDate(II);
  6974. return II;
  6975. }
  6976. namespace clang {
  6977. /// An identifier-lookup iterator that enumerates all of the
  6978. /// identifiers stored within a set of AST files.
  6979. class ASTIdentifierIterator : public IdentifierIterator {
  6980. /// The AST reader whose identifiers are being enumerated.
  6981. const ASTReader &Reader;
  6982. /// The current index into the chain of AST files stored in
  6983. /// the AST reader.
  6984. unsigned Index;
  6985. /// The current position within the identifier lookup table
  6986. /// of the current AST file.
  6987. ASTIdentifierLookupTable::key_iterator Current;
  6988. /// The end position within the identifier lookup table of
  6989. /// the current AST file.
  6990. ASTIdentifierLookupTable::key_iterator End;
  6991. /// Whether to skip any modules in the ASTReader.
  6992. bool SkipModules;
  6993. public:
  6994. explicit ASTIdentifierIterator(const ASTReader &Reader,
  6995. bool SkipModules = false);
  6996. StringRef Next() override;
  6997. };
  6998. } // namespace clang
  6999. ASTIdentifierIterator::ASTIdentifierIterator(const ASTReader &Reader,
  7000. bool SkipModules)
  7001. : Reader(Reader), Index(Reader.ModuleMgr.size()), SkipModules(SkipModules) {
  7002. }
  7003. StringRef ASTIdentifierIterator::Next() {
  7004. while (Current == End) {
  7005. // If we have exhausted all of our AST files, we're done.
  7006. if (Index == 0)
  7007. return StringRef();
  7008. --Index;
  7009. ModuleFile &F = Reader.ModuleMgr[Index];
  7010. if (SkipModules && F.isModule())
  7011. continue;
  7012. ASTIdentifierLookupTable *IdTable =
  7013. (ASTIdentifierLookupTable *)F.IdentifierLookupTable;
  7014. Current = IdTable->key_begin();
  7015. End = IdTable->key_end();
  7016. }
  7017. // We have any identifiers remaining in the current AST file; return
  7018. // the next one.
  7019. StringRef Result = *Current;
  7020. ++Current;
  7021. return Result;
  7022. }
  7023. namespace {
  7024. /// A utility for appending two IdentifierIterators.
  7025. class ChainedIdentifierIterator : public IdentifierIterator {
  7026. std::unique_ptr<IdentifierIterator> Current;
  7027. std::unique_ptr<IdentifierIterator> Queued;
  7028. public:
  7029. ChainedIdentifierIterator(std::unique_ptr<IdentifierIterator> First,
  7030. std::unique_ptr<IdentifierIterator> Second)
  7031. : Current(std::move(First)), Queued(std::move(Second)) {}
  7032. StringRef Next() override {
  7033. if (!Current)
  7034. return StringRef();
  7035. StringRef result = Current->Next();
  7036. if (!result.empty())
  7037. return result;
  7038. // Try the queued iterator, which may itself be empty.
  7039. Current.reset();
  7040. std::swap(Current, Queued);
  7041. return Next();
  7042. }
  7043. };
  7044. } // namespace
  7045. IdentifierIterator *ASTReader::getIdentifiers() {
  7046. if (!loadGlobalIndex()) {
  7047. std::unique_ptr<IdentifierIterator> ReaderIter(
  7048. new ASTIdentifierIterator(*this, /*SkipModules=*/true));
  7049. std::unique_ptr<IdentifierIterator> ModulesIter(
  7050. GlobalIndex->createIdentifierIterator());
  7051. return new ChainedIdentifierIterator(std::move(ReaderIter),
  7052. std::move(ModulesIter));
  7053. }
  7054. return new ASTIdentifierIterator(*this);
  7055. }
  7056. namespace clang {
  7057. namespace serialization {
  7058. class ReadMethodPoolVisitor {
  7059. ASTReader &Reader;
  7060. Selector Sel;
  7061. unsigned PriorGeneration;
  7062. unsigned InstanceBits = 0;
  7063. unsigned FactoryBits = 0;
  7064. bool InstanceHasMoreThanOneDecl = false;
  7065. bool FactoryHasMoreThanOneDecl = false;
  7066. SmallVector<ObjCMethodDecl *, 4> InstanceMethods;
  7067. SmallVector<ObjCMethodDecl *, 4> FactoryMethods;
  7068. public:
  7069. ReadMethodPoolVisitor(ASTReader &Reader, Selector Sel,
  7070. unsigned PriorGeneration)
  7071. : Reader(Reader), Sel(Sel), PriorGeneration(PriorGeneration) {}
  7072. bool operator()(ModuleFile &M) {
  7073. if (!M.SelectorLookupTable)
  7074. return false;
  7075. // If we've already searched this module file, skip it now.
  7076. if (M.Generation <= PriorGeneration)
  7077. return true;
  7078. ++Reader.NumMethodPoolTableLookups;
  7079. ASTSelectorLookupTable *PoolTable
  7080. = (ASTSelectorLookupTable*)M.SelectorLookupTable;
  7081. ASTSelectorLookupTable::iterator Pos = PoolTable->find(Sel);
  7082. if (Pos == PoolTable->end())
  7083. return false;
  7084. ++Reader.NumMethodPoolTableHits;
  7085. ++Reader.NumSelectorsRead;
  7086. // FIXME: Not quite happy with the statistics here. We probably should
  7087. // disable this tracking when called via LoadSelector.
  7088. // Also, should entries without methods count as misses?
  7089. ++Reader.NumMethodPoolEntriesRead;
  7090. ASTSelectorLookupTrait::data_type Data = *Pos;
  7091. if (Reader.DeserializationListener)
  7092. Reader.DeserializationListener->SelectorRead(Data.ID, Sel);
  7093. // Append methods in the reverse order, so that later we can process them
  7094. // in the order they appear in the source code by iterating through
  7095. // the vector in the reverse order.
  7096. InstanceMethods.append(Data.Instance.rbegin(), Data.Instance.rend());
  7097. FactoryMethods.append(Data.Factory.rbegin(), Data.Factory.rend());
  7098. InstanceBits = Data.InstanceBits;
  7099. FactoryBits = Data.FactoryBits;
  7100. InstanceHasMoreThanOneDecl = Data.InstanceHasMoreThanOneDecl;
  7101. FactoryHasMoreThanOneDecl = Data.FactoryHasMoreThanOneDecl;
  7102. return false;
  7103. }
  7104. /// Retrieve the instance methods found by this visitor.
  7105. ArrayRef<ObjCMethodDecl *> getInstanceMethods() const {
  7106. return InstanceMethods;
  7107. }
  7108. /// Retrieve the instance methods found by this visitor.
  7109. ArrayRef<ObjCMethodDecl *> getFactoryMethods() const {
  7110. return FactoryMethods;
  7111. }
  7112. unsigned getInstanceBits() const { return InstanceBits; }
  7113. unsigned getFactoryBits() const { return FactoryBits; }
  7114. bool instanceHasMoreThanOneDecl() const {
  7115. return InstanceHasMoreThanOneDecl;
  7116. }
  7117. bool factoryHasMoreThanOneDecl() const { return FactoryHasMoreThanOneDecl; }
  7118. };
  7119. } // namespace serialization
  7120. } // namespace clang
  7121. /// Add the given set of methods to the method list.
  7122. static void addMethodsToPool(Sema &S, ArrayRef<ObjCMethodDecl *> Methods,
  7123. ObjCMethodList &List) {
  7124. for (auto I = Methods.rbegin(), E = Methods.rend(); I != E; ++I)
  7125. S.addMethodToGlobalList(&List, *I);
  7126. }
  7127. void ASTReader::ReadMethodPool(Selector Sel) {
  7128. // Get the selector generation and update it to the current generation.
  7129. unsigned &Generation = SelectorGeneration[Sel];
  7130. unsigned PriorGeneration = Generation;
  7131. Generation = getGeneration();
  7132. SelectorOutOfDate[Sel] = false;
  7133. // Search for methods defined with this selector.
  7134. ++NumMethodPoolLookups;
  7135. ReadMethodPoolVisitor Visitor(*this, Sel, PriorGeneration);
  7136. ModuleMgr.visit(Visitor);
  7137. if (Visitor.getInstanceMethods().empty() &&
  7138. Visitor.getFactoryMethods().empty())
  7139. return;
  7140. ++NumMethodPoolHits;
  7141. if (!getSema())
  7142. return;
  7143. Sema &S = *getSema();
  7144. Sema::GlobalMethodPool::iterator Pos =
  7145. S.MethodPool.insert(std::make_pair(Sel, Sema::GlobalMethodPool::Lists()))
  7146. .first;
  7147. Pos->second.first.setBits(Visitor.getInstanceBits());
  7148. Pos->second.first.setHasMoreThanOneDecl(Visitor.instanceHasMoreThanOneDecl());
  7149. Pos->second.second.setBits(Visitor.getFactoryBits());
  7150. Pos->second.second.setHasMoreThanOneDecl(Visitor.factoryHasMoreThanOneDecl());
  7151. // Add methods to the global pool *after* setting hasMoreThanOneDecl, since
  7152. // when building a module we keep every method individually and may need to
  7153. // update hasMoreThanOneDecl as we add the methods.
  7154. addMethodsToPool(S, Visitor.getInstanceMethods(), Pos->second.first);
  7155. addMethodsToPool(S, Visitor.getFactoryMethods(), Pos->second.second);
  7156. }
  7157. void ASTReader::updateOutOfDateSelector(Selector Sel) {
  7158. if (SelectorOutOfDate[Sel])
  7159. ReadMethodPool(Sel);
  7160. }
  7161. void ASTReader::ReadKnownNamespaces(
  7162. SmallVectorImpl<NamespaceDecl *> &Namespaces) {
  7163. Namespaces.clear();
  7164. for (unsigned I = 0, N = KnownNamespaces.size(); I != N; ++I) {
  7165. if (NamespaceDecl *Namespace
  7166. = dyn_cast_or_null<NamespaceDecl>(GetDecl(KnownNamespaces[I])))
  7167. Namespaces.push_back(Namespace);
  7168. }
  7169. }
  7170. void ASTReader::ReadUndefinedButUsed(
  7171. llvm::MapVector<NamedDecl *, SourceLocation> &Undefined) {
  7172. for (unsigned Idx = 0, N = UndefinedButUsed.size(); Idx != N;) {
  7173. NamedDecl *D = cast<NamedDecl>(GetDecl(UndefinedButUsed[Idx++]));
  7174. SourceLocation Loc =
  7175. SourceLocation::getFromRawEncoding(UndefinedButUsed[Idx++]);
  7176. Undefined.insert(std::make_pair(D, Loc));
  7177. }
  7178. }
  7179. void ASTReader::ReadMismatchingDeleteExpressions(llvm::MapVector<
  7180. FieldDecl *, llvm::SmallVector<std::pair<SourceLocation, bool>, 4>> &
  7181. Exprs) {
  7182. for (unsigned Idx = 0, N = DelayedDeleteExprs.size(); Idx != N;) {
  7183. FieldDecl *FD = cast<FieldDecl>(GetDecl(DelayedDeleteExprs[Idx++]));
  7184. uint64_t Count = DelayedDeleteExprs[Idx++];
  7185. for (uint64_t C = 0; C < Count; ++C) {
  7186. SourceLocation DeleteLoc =
  7187. SourceLocation::getFromRawEncoding(DelayedDeleteExprs[Idx++]);
  7188. const bool IsArrayForm = DelayedDeleteExprs[Idx++];
  7189. Exprs[FD].push_back(std::make_pair(DeleteLoc, IsArrayForm));
  7190. }
  7191. }
  7192. }
  7193. void ASTReader::ReadTentativeDefinitions(
  7194. SmallVectorImpl<VarDecl *> &TentativeDefs) {
  7195. for (unsigned I = 0, N = TentativeDefinitions.size(); I != N; ++I) {
  7196. VarDecl *Var = dyn_cast_or_null<VarDecl>(GetDecl(TentativeDefinitions[I]));
  7197. if (Var)
  7198. TentativeDefs.push_back(Var);
  7199. }
  7200. TentativeDefinitions.clear();
  7201. }
  7202. void ASTReader::ReadUnusedFileScopedDecls(
  7203. SmallVectorImpl<const DeclaratorDecl *> &Decls) {
  7204. for (unsigned I = 0, N = UnusedFileScopedDecls.size(); I != N; ++I) {
  7205. DeclaratorDecl *D
  7206. = dyn_cast_or_null<DeclaratorDecl>(GetDecl(UnusedFileScopedDecls[I]));
  7207. if (D)
  7208. Decls.push_back(D);
  7209. }
  7210. UnusedFileScopedDecls.clear();
  7211. }
  7212. void ASTReader::ReadDelegatingConstructors(
  7213. SmallVectorImpl<CXXConstructorDecl *> &Decls) {
  7214. for (unsigned I = 0, N = DelegatingCtorDecls.size(); I != N; ++I) {
  7215. CXXConstructorDecl *D
  7216. = dyn_cast_or_null<CXXConstructorDecl>(GetDecl(DelegatingCtorDecls[I]));
  7217. if (D)
  7218. Decls.push_back(D);
  7219. }
  7220. DelegatingCtorDecls.clear();
  7221. }
  7222. void ASTReader::ReadExtVectorDecls(SmallVectorImpl<TypedefNameDecl *> &Decls) {
  7223. for (unsigned I = 0, N = ExtVectorDecls.size(); I != N; ++I) {
  7224. TypedefNameDecl *D
  7225. = dyn_cast_or_null<TypedefNameDecl>(GetDecl(ExtVectorDecls[I]));
  7226. if (D)
  7227. Decls.push_back(D);
  7228. }
  7229. ExtVectorDecls.clear();
  7230. }
  7231. void ASTReader::ReadUnusedLocalTypedefNameCandidates(
  7232. llvm::SmallSetVector<const TypedefNameDecl *, 4> &Decls) {
  7233. for (unsigned I = 0, N = UnusedLocalTypedefNameCandidates.size(); I != N;
  7234. ++I) {
  7235. TypedefNameDecl *D = dyn_cast_or_null<TypedefNameDecl>(
  7236. GetDecl(UnusedLocalTypedefNameCandidates[I]));
  7237. if (D)
  7238. Decls.insert(D);
  7239. }
  7240. UnusedLocalTypedefNameCandidates.clear();
  7241. }
  7242. void ASTReader::ReadDeclsToCheckForDeferredDiags(
  7243. llvm::SmallSetVector<Decl *, 4> &Decls) {
  7244. for (auto I : DeclsToCheckForDeferredDiags) {
  7245. auto *D = dyn_cast_or_null<Decl>(GetDecl(I));
  7246. if (D)
  7247. Decls.insert(D);
  7248. }
  7249. DeclsToCheckForDeferredDiags.clear();
  7250. }
  7251. void ASTReader::ReadReferencedSelectors(
  7252. SmallVectorImpl<std::pair<Selector, SourceLocation>> &Sels) {
  7253. if (ReferencedSelectorsData.empty())
  7254. return;
  7255. // If there are @selector references added them to its pool. This is for
  7256. // implementation of -Wselector.
  7257. unsigned int DataSize = ReferencedSelectorsData.size()-1;
  7258. unsigned I = 0;
  7259. while (I < DataSize) {
  7260. Selector Sel = DecodeSelector(ReferencedSelectorsData[I++]);
  7261. SourceLocation SelLoc
  7262. = SourceLocation::getFromRawEncoding(ReferencedSelectorsData[I++]);
  7263. Sels.push_back(std::make_pair(Sel, SelLoc));
  7264. }
  7265. ReferencedSelectorsData.clear();
  7266. }
  7267. void ASTReader::ReadWeakUndeclaredIdentifiers(
  7268. SmallVectorImpl<std::pair<IdentifierInfo *, WeakInfo>> &WeakIDs) {
  7269. if (WeakUndeclaredIdentifiers.empty())
  7270. return;
  7271. for (unsigned I = 0, N = WeakUndeclaredIdentifiers.size(); I < N; /*none*/) {
  7272. IdentifierInfo *WeakId
  7273. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  7274. IdentifierInfo *AliasId
  7275. = DecodeIdentifierInfo(WeakUndeclaredIdentifiers[I++]);
  7276. SourceLocation Loc
  7277. = SourceLocation::getFromRawEncoding(WeakUndeclaredIdentifiers[I++]);
  7278. bool Used = WeakUndeclaredIdentifiers[I++];
  7279. WeakInfo WI(AliasId, Loc);
  7280. WI.setUsed(Used);
  7281. WeakIDs.push_back(std::make_pair(WeakId, WI));
  7282. }
  7283. WeakUndeclaredIdentifiers.clear();
  7284. }
  7285. void ASTReader::ReadUsedVTables(SmallVectorImpl<ExternalVTableUse> &VTables) {
  7286. for (unsigned Idx = 0, N = VTableUses.size(); Idx < N; /* In loop */) {
  7287. ExternalVTableUse VT;
  7288. VT.Record = dyn_cast_or_null<CXXRecordDecl>(GetDecl(VTableUses[Idx++]));
  7289. VT.Location = SourceLocation::getFromRawEncoding(VTableUses[Idx++]);
  7290. VT.DefinitionRequired = VTableUses[Idx++];
  7291. VTables.push_back(VT);
  7292. }
  7293. VTableUses.clear();
  7294. }
  7295. void ASTReader::ReadPendingInstantiations(
  7296. SmallVectorImpl<std::pair<ValueDecl *, SourceLocation>> &Pending) {
  7297. for (unsigned Idx = 0, N = PendingInstantiations.size(); Idx < N;) {
  7298. ValueDecl *D = cast<ValueDecl>(GetDecl(PendingInstantiations[Idx++]));
  7299. SourceLocation Loc
  7300. = SourceLocation::getFromRawEncoding(PendingInstantiations[Idx++]);
  7301. Pending.push_back(std::make_pair(D, Loc));
  7302. }
  7303. PendingInstantiations.clear();
  7304. }
  7305. void ASTReader::ReadLateParsedTemplates(
  7306. llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>>
  7307. &LPTMap) {
  7308. for (auto &LPT : LateParsedTemplates) {
  7309. ModuleFile *FMod = LPT.first;
  7310. RecordDataImpl &LateParsed = LPT.second;
  7311. for (unsigned Idx = 0, N = LateParsed.size(); Idx < N;
  7312. /* In loop */) {
  7313. FunctionDecl *FD =
  7314. cast<FunctionDecl>(GetLocalDecl(*FMod, LateParsed[Idx++]));
  7315. auto LT = std::make_unique<LateParsedTemplate>();
  7316. LT->D = GetLocalDecl(*FMod, LateParsed[Idx++]);
  7317. ModuleFile *F = getOwningModuleFile(LT->D);
  7318. assert(F && "No module");
  7319. unsigned TokN = LateParsed[Idx++];
  7320. LT->Toks.reserve(TokN);
  7321. for (unsigned T = 0; T < TokN; ++T)
  7322. LT->Toks.push_back(ReadToken(*F, LateParsed, Idx));
  7323. LPTMap.insert(std::make_pair(FD, std::move(LT)));
  7324. }
  7325. }
  7326. LateParsedTemplates.clear();
  7327. }
  7328. void ASTReader::LoadSelector(Selector Sel) {
  7329. // It would be complicated to avoid reading the methods anyway. So don't.
  7330. ReadMethodPool(Sel);
  7331. }
  7332. void ASTReader::SetIdentifierInfo(IdentifierID ID, IdentifierInfo *II) {
  7333. assert(ID && "Non-zero identifier ID required");
  7334. assert(ID <= IdentifiersLoaded.size() && "identifier ID out of range");
  7335. IdentifiersLoaded[ID - 1] = II;
  7336. if (DeserializationListener)
  7337. DeserializationListener->IdentifierRead(ID, II);
  7338. }
  7339. /// Set the globally-visible declarations associated with the given
  7340. /// identifier.
  7341. ///
  7342. /// If the AST reader is currently in a state where the given declaration IDs
  7343. /// cannot safely be resolved, they are queued until it is safe to resolve
  7344. /// them.
  7345. ///
  7346. /// \param II an IdentifierInfo that refers to one or more globally-visible
  7347. /// declarations.
  7348. ///
  7349. /// \param DeclIDs the set of declaration IDs with the name @p II that are
  7350. /// visible at global scope.
  7351. ///
  7352. /// \param Decls if non-null, this vector will be populated with the set of
  7353. /// deserialized declarations. These declarations will not be pushed into
  7354. /// scope.
  7355. void
  7356. ASTReader::SetGloballyVisibleDecls(IdentifierInfo *II,
  7357. const SmallVectorImpl<uint32_t> &DeclIDs,
  7358. SmallVectorImpl<Decl *> *Decls) {
  7359. if (NumCurrentElementsDeserializing && !Decls) {
  7360. PendingIdentifierInfos[II].append(DeclIDs.begin(), DeclIDs.end());
  7361. return;
  7362. }
  7363. for (unsigned I = 0, N = DeclIDs.size(); I != N; ++I) {
  7364. if (!SemaObj) {
  7365. // Queue this declaration so that it will be added to the
  7366. // translation unit scope and identifier's declaration chain
  7367. // once a Sema object is known.
  7368. PreloadedDeclIDs.push_back(DeclIDs[I]);
  7369. continue;
  7370. }
  7371. NamedDecl *D = cast<NamedDecl>(GetDecl(DeclIDs[I]));
  7372. // If we're simply supposed to record the declarations, do so now.
  7373. if (Decls) {
  7374. Decls->push_back(D);
  7375. continue;
  7376. }
  7377. // Introduce this declaration into the translation-unit scope
  7378. // and add it to the declaration chain for this identifier, so
  7379. // that (unqualified) name lookup will find it.
  7380. pushExternalDeclIntoScope(D, II);
  7381. }
  7382. }
  7383. IdentifierInfo *ASTReader::DecodeIdentifierInfo(IdentifierID ID) {
  7384. if (ID == 0)
  7385. return nullptr;
  7386. if (IdentifiersLoaded.empty()) {
  7387. Error("no identifier table in AST file");
  7388. return nullptr;
  7389. }
  7390. ID -= 1;
  7391. if (!IdentifiersLoaded[ID]) {
  7392. GlobalIdentifierMapType::iterator I = GlobalIdentifierMap.find(ID + 1);
  7393. assert(I != GlobalIdentifierMap.end() && "Corrupted global identifier map");
  7394. ModuleFile *M = I->second;
  7395. unsigned Index = ID - M->BaseIdentifierID;
  7396. const unsigned char *Data =
  7397. M->IdentifierTableData + M->IdentifierOffsets[Index];
  7398. ASTIdentifierLookupTrait Trait(*this, *M);
  7399. auto KeyDataLen = Trait.ReadKeyDataLength(Data);
  7400. auto Key = Trait.ReadKey(Data, KeyDataLen.first);
  7401. auto &II = PP.getIdentifierTable().get(Key);
  7402. IdentifiersLoaded[ID] = &II;
  7403. markIdentifierFromAST(*this, II);
  7404. if (DeserializationListener)
  7405. DeserializationListener->IdentifierRead(ID + 1, &II);
  7406. }
  7407. return IdentifiersLoaded[ID];
  7408. }
  7409. IdentifierInfo *ASTReader::getLocalIdentifier(ModuleFile &M, unsigned LocalID) {
  7410. return DecodeIdentifierInfo(getGlobalIdentifierID(M, LocalID));
  7411. }
  7412. IdentifierID ASTReader::getGlobalIdentifierID(ModuleFile &M, unsigned LocalID) {
  7413. if (LocalID < NUM_PREDEF_IDENT_IDS)
  7414. return LocalID;
  7415. if (!M.ModuleOffsetMap.empty())
  7416. ReadModuleOffsetMap(M);
  7417. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7418. = M.IdentifierRemap.find(LocalID - NUM_PREDEF_IDENT_IDS);
  7419. assert(I != M.IdentifierRemap.end()
  7420. && "Invalid index into identifier index remap");
  7421. return LocalID + I->second;
  7422. }
  7423. MacroInfo *ASTReader::getMacro(MacroID ID) {
  7424. if (ID == 0)
  7425. return nullptr;
  7426. if (MacrosLoaded.empty()) {
  7427. Error("no macro table in AST file");
  7428. return nullptr;
  7429. }
  7430. ID -= NUM_PREDEF_MACRO_IDS;
  7431. if (!MacrosLoaded[ID]) {
  7432. GlobalMacroMapType::iterator I
  7433. = GlobalMacroMap.find(ID + NUM_PREDEF_MACRO_IDS);
  7434. assert(I != GlobalMacroMap.end() && "Corrupted global macro map");
  7435. ModuleFile *M = I->second;
  7436. unsigned Index = ID - M->BaseMacroID;
  7437. MacrosLoaded[ID] =
  7438. ReadMacroRecord(*M, M->MacroOffsetsBase + M->MacroOffsets[Index]);
  7439. if (DeserializationListener)
  7440. DeserializationListener->MacroRead(ID + NUM_PREDEF_MACRO_IDS,
  7441. MacrosLoaded[ID]);
  7442. }
  7443. return MacrosLoaded[ID];
  7444. }
  7445. MacroID ASTReader::getGlobalMacroID(ModuleFile &M, unsigned LocalID) {
  7446. if (LocalID < NUM_PREDEF_MACRO_IDS)
  7447. return LocalID;
  7448. if (!M.ModuleOffsetMap.empty())
  7449. ReadModuleOffsetMap(M);
  7450. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7451. = M.MacroRemap.find(LocalID - NUM_PREDEF_MACRO_IDS);
  7452. assert(I != M.MacroRemap.end() && "Invalid index into macro index remap");
  7453. return LocalID + I->second;
  7454. }
  7455. serialization::SubmoduleID
  7456. ASTReader::getGlobalSubmoduleID(ModuleFile &M, unsigned LocalID) {
  7457. if (LocalID < NUM_PREDEF_SUBMODULE_IDS)
  7458. return LocalID;
  7459. if (!M.ModuleOffsetMap.empty())
  7460. ReadModuleOffsetMap(M);
  7461. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7462. = M.SubmoduleRemap.find(LocalID - NUM_PREDEF_SUBMODULE_IDS);
  7463. assert(I != M.SubmoduleRemap.end()
  7464. && "Invalid index into submodule index remap");
  7465. return LocalID + I->second;
  7466. }
  7467. Module *ASTReader::getSubmodule(SubmoduleID GlobalID) {
  7468. if (GlobalID < NUM_PREDEF_SUBMODULE_IDS) {
  7469. assert(GlobalID == 0 && "Unhandled global submodule ID");
  7470. return nullptr;
  7471. }
  7472. if (GlobalID > SubmodulesLoaded.size()) {
  7473. Error("submodule ID out of range in AST file");
  7474. return nullptr;
  7475. }
  7476. return SubmodulesLoaded[GlobalID - NUM_PREDEF_SUBMODULE_IDS];
  7477. }
  7478. Module *ASTReader::getModule(unsigned ID) {
  7479. return getSubmodule(ID);
  7480. }
  7481. ModuleFile *ASTReader::getLocalModuleFile(ModuleFile &F, unsigned ID) {
  7482. if (ID & 1) {
  7483. // It's a module, look it up by submodule ID.
  7484. auto I = GlobalSubmoduleMap.find(getGlobalSubmoduleID(F, ID >> 1));
  7485. return I == GlobalSubmoduleMap.end() ? nullptr : I->second;
  7486. } else {
  7487. // It's a prefix (preamble, PCH, ...). Look it up by index.
  7488. unsigned IndexFromEnd = ID >> 1;
  7489. assert(IndexFromEnd && "got reference to unknown module file");
  7490. return getModuleManager().pch_modules().end()[-IndexFromEnd];
  7491. }
  7492. }
  7493. unsigned ASTReader::getModuleFileID(ModuleFile *F) {
  7494. if (!F)
  7495. return 1;
  7496. // For a file representing a module, use the submodule ID of the top-level
  7497. // module as the file ID. For any other kind of file, the number of such
  7498. // files loaded beforehand will be the same on reload.
  7499. // FIXME: Is this true even if we have an explicit module file and a PCH?
  7500. if (F->isModule())
  7501. return ((F->BaseSubmoduleID + NUM_PREDEF_SUBMODULE_IDS) << 1) | 1;
  7502. auto PCHModules = getModuleManager().pch_modules();
  7503. auto I = llvm::find(PCHModules, F);
  7504. assert(I != PCHModules.end() && "emitting reference to unknown file");
  7505. return (I - PCHModules.end()) << 1;
  7506. }
  7507. llvm::Optional<ASTSourceDescriptor>
  7508. ASTReader::getSourceDescriptor(unsigned ID) {
  7509. if (Module *M = getSubmodule(ID))
  7510. return ASTSourceDescriptor(*M);
  7511. // If there is only a single PCH, return it instead.
  7512. // Chained PCH are not supported.
  7513. const auto &PCHChain = ModuleMgr.pch_modules();
  7514. if (std::distance(std::begin(PCHChain), std::end(PCHChain))) {
  7515. ModuleFile &MF = ModuleMgr.getPrimaryModule();
  7516. StringRef ModuleName = llvm::sys::path::filename(MF.OriginalSourceFileName);
  7517. StringRef FileName = llvm::sys::path::filename(MF.FileName);
  7518. return ASTSourceDescriptor(ModuleName, MF.OriginalDir, FileName,
  7519. MF.Signature);
  7520. }
  7521. return None;
  7522. }
  7523. ExternalASTSource::ExtKind ASTReader::hasExternalDefinitions(const Decl *FD) {
  7524. auto I = DefinitionSource.find(FD);
  7525. if (I == DefinitionSource.end())
  7526. return EK_ReplyHazy;
  7527. return I->second ? EK_Never : EK_Always;
  7528. }
  7529. Selector ASTReader::getLocalSelector(ModuleFile &M, unsigned LocalID) {
  7530. return DecodeSelector(getGlobalSelectorID(M, LocalID));
  7531. }
  7532. Selector ASTReader::DecodeSelector(serialization::SelectorID ID) {
  7533. if (ID == 0)
  7534. return Selector();
  7535. if (ID > SelectorsLoaded.size()) {
  7536. Error("selector ID out of range in AST file");
  7537. return Selector();
  7538. }
  7539. if (SelectorsLoaded[ID - 1].getAsOpaquePtr() == nullptr) {
  7540. // Load this selector from the selector table.
  7541. GlobalSelectorMapType::iterator I = GlobalSelectorMap.find(ID);
  7542. assert(I != GlobalSelectorMap.end() && "Corrupted global selector map");
  7543. ModuleFile &M = *I->second;
  7544. ASTSelectorLookupTrait Trait(*this, M);
  7545. unsigned Idx = ID - M.BaseSelectorID - NUM_PREDEF_SELECTOR_IDS;
  7546. SelectorsLoaded[ID - 1] =
  7547. Trait.ReadKey(M.SelectorLookupTableData + M.SelectorOffsets[Idx], 0);
  7548. if (DeserializationListener)
  7549. DeserializationListener->SelectorRead(ID, SelectorsLoaded[ID - 1]);
  7550. }
  7551. return SelectorsLoaded[ID - 1];
  7552. }
  7553. Selector ASTReader::GetExternalSelector(serialization::SelectorID ID) {
  7554. return DecodeSelector(ID);
  7555. }
  7556. uint32_t ASTReader::GetNumExternalSelectors() {
  7557. // ID 0 (the null selector) is considered an external selector.
  7558. return getTotalNumSelectors() + 1;
  7559. }
  7560. serialization::SelectorID
  7561. ASTReader::getGlobalSelectorID(ModuleFile &M, unsigned LocalID) const {
  7562. if (LocalID < NUM_PREDEF_SELECTOR_IDS)
  7563. return LocalID;
  7564. if (!M.ModuleOffsetMap.empty())
  7565. ReadModuleOffsetMap(M);
  7566. ContinuousRangeMap<uint32_t, int, 2>::iterator I
  7567. = M.SelectorRemap.find(LocalID - NUM_PREDEF_SELECTOR_IDS);
  7568. assert(I != M.SelectorRemap.end()
  7569. && "Invalid index into selector index remap");
  7570. return LocalID + I->second;
  7571. }
  7572. DeclarationNameLoc
  7573. ASTRecordReader::readDeclarationNameLoc(DeclarationName Name) {
  7574. switch (Name.getNameKind()) {
  7575. case DeclarationName::CXXConstructorName:
  7576. case DeclarationName::CXXDestructorName:
  7577. case DeclarationName::CXXConversionFunctionName:
  7578. return DeclarationNameLoc::makeNamedTypeLoc(readTypeSourceInfo());
  7579. case DeclarationName::CXXOperatorName:
  7580. return DeclarationNameLoc::makeCXXOperatorNameLoc(readSourceRange());
  7581. case DeclarationName::CXXLiteralOperatorName:
  7582. return DeclarationNameLoc::makeCXXLiteralOperatorNameLoc(
  7583. readSourceLocation());
  7584. case DeclarationName::Identifier:
  7585. case DeclarationName::ObjCZeroArgSelector:
  7586. case DeclarationName::ObjCOneArgSelector:
  7587. case DeclarationName::ObjCMultiArgSelector:
  7588. case DeclarationName::CXXUsingDirective:
  7589. case DeclarationName::CXXDeductionGuideName:
  7590. break;
  7591. }
  7592. return DeclarationNameLoc();
  7593. }
  7594. DeclarationNameInfo ASTRecordReader::readDeclarationNameInfo() {
  7595. DeclarationNameInfo NameInfo;
  7596. NameInfo.setName(readDeclarationName());
  7597. NameInfo.setLoc(readSourceLocation());
  7598. NameInfo.setInfo(readDeclarationNameLoc(NameInfo.getName()));
  7599. return NameInfo;
  7600. }
  7601. void ASTRecordReader::readQualifierInfo(QualifierInfo &Info) {
  7602. Info.QualifierLoc = readNestedNameSpecifierLoc();
  7603. unsigned NumTPLists = readInt();
  7604. Info.NumTemplParamLists = NumTPLists;
  7605. if (NumTPLists) {
  7606. Info.TemplParamLists =
  7607. new (getContext()) TemplateParameterList *[NumTPLists];
  7608. for (unsigned i = 0; i != NumTPLists; ++i)
  7609. Info.TemplParamLists[i] = readTemplateParameterList();
  7610. }
  7611. }
  7612. TemplateParameterList *
  7613. ASTRecordReader::readTemplateParameterList() {
  7614. SourceLocation TemplateLoc = readSourceLocation();
  7615. SourceLocation LAngleLoc = readSourceLocation();
  7616. SourceLocation RAngleLoc = readSourceLocation();
  7617. unsigned NumParams = readInt();
  7618. SmallVector<NamedDecl *, 16> Params;
  7619. Params.reserve(NumParams);
  7620. while (NumParams--)
  7621. Params.push_back(readDeclAs<NamedDecl>());
  7622. bool HasRequiresClause = readBool();
  7623. Expr *RequiresClause = HasRequiresClause ? readExpr() : nullptr;
  7624. TemplateParameterList *TemplateParams = TemplateParameterList::Create(
  7625. getContext(), TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause);
  7626. return TemplateParams;
  7627. }
  7628. void ASTRecordReader::readTemplateArgumentList(
  7629. SmallVectorImpl<TemplateArgument> &TemplArgs,
  7630. bool Canonicalize) {
  7631. unsigned NumTemplateArgs = readInt();
  7632. TemplArgs.reserve(NumTemplateArgs);
  7633. while (NumTemplateArgs--)
  7634. TemplArgs.push_back(readTemplateArgument(Canonicalize));
  7635. }
  7636. /// Read a UnresolvedSet structure.
  7637. void ASTRecordReader::readUnresolvedSet(LazyASTUnresolvedSet &Set) {
  7638. unsigned NumDecls = readInt();
  7639. Set.reserve(getContext(), NumDecls);
  7640. while (NumDecls--) {
  7641. DeclID ID = readDeclID();
  7642. AccessSpecifier AS = (AccessSpecifier) readInt();
  7643. Set.addLazyDecl(getContext(), ID, AS);
  7644. }
  7645. }
  7646. CXXBaseSpecifier
  7647. ASTRecordReader::readCXXBaseSpecifier() {
  7648. bool isVirtual = readBool();
  7649. bool isBaseOfClass = readBool();
  7650. AccessSpecifier AS = static_cast<AccessSpecifier>(readInt());
  7651. bool inheritConstructors = readBool();
  7652. TypeSourceInfo *TInfo = readTypeSourceInfo();
  7653. SourceRange Range = readSourceRange();
  7654. SourceLocation EllipsisLoc = readSourceLocation();
  7655. CXXBaseSpecifier Result(Range, isVirtual, isBaseOfClass, AS, TInfo,
  7656. EllipsisLoc);
  7657. Result.setInheritConstructors(inheritConstructors);
  7658. return Result;
  7659. }
  7660. CXXCtorInitializer **
  7661. ASTRecordReader::readCXXCtorInitializers() {
  7662. ASTContext &Context = getContext();
  7663. unsigned NumInitializers = readInt();
  7664. assert(NumInitializers && "wrote ctor initializers but have no inits");
  7665. auto **CtorInitializers = new (Context) CXXCtorInitializer*[NumInitializers];
  7666. for (unsigned i = 0; i != NumInitializers; ++i) {
  7667. TypeSourceInfo *TInfo = nullptr;
  7668. bool IsBaseVirtual = false;
  7669. FieldDecl *Member = nullptr;
  7670. IndirectFieldDecl *IndirectMember = nullptr;
  7671. CtorInitializerType Type = (CtorInitializerType) readInt();
  7672. switch (Type) {
  7673. case CTOR_INITIALIZER_BASE:
  7674. TInfo = readTypeSourceInfo();
  7675. IsBaseVirtual = readBool();
  7676. break;
  7677. case CTOR_INITIALIZER_DELEGATING:
  7678. TInfo = readTypeSourceInfo();
  7679. break;
  7680. case CTOR_INITIALIZER_MEMBER:
  7681. Member = readDeclAs<FieldDecl>();
  7682. break;
  7683. case CTOR_INITIALIZER_INDIRECT_MEMBER:
  7684. IndirectMember = readDeclAs<IndirectFieldDecl>();
  7685. break;
  7686. }
  7687. SourceLocation MemberOrEllipsisLoc = readSourceLocation();
  7688. Expr *Init = readExpr();
  7689. SourceLocation LParenLoc = readSourceLocation();
  7690. SourceLocation RParenLoc = readSourceLocation();
  7691. CXXCtorInitializer *BOMInit;
  7692. if (Type == CTOR_INITIALIZER_BASE)
  7693. BOMInit = new (Context)
  7694. CXXCtorInitializer(Context, TInfo, IsBaseVirtual, LParenLoc, Init,
  7695. RParenLoc, MemberOrEllipsisLoc);
  7696. else if (Type == CTOR_INITIALIZER_DELEGATING)
  7697. BOMInit = new (Context)
  7698. CXXCtorInitializer(Context, TInfo, LParenLoc, Init, RParenLoc);
  7699. else if (Member)
  7700. BOMInit = new (Context)
  7701. CXXCtorInitializer(Context, Member, MemberOrEllipsisLoc, LParenLoc,
  7702. Init, RParenLoc);
  7703. else
  7704. BOMInit = new (Context)
  7705. CXXCtorInitializer(Context, IndirectMember, MemberOrEllipsisLoc,
  7706. LParenLoc, Init, RParenLoc);
  7707. if (/*IsWritten*/readBool()) {
  7708. unsigned SourceOrder = readInt();
  7709. BOMInit->setSourceOrder(SourceOrder);
  7710. }
  7711. CtorInitializers[i] = BOMInit;
  7712. }
  7713. return CtorInitializers;
  7714. }
  7715. NestedNameSpecifierLoc
  7716. ASTRecordReader::readNestedNameSpecifierLoc() {
  7717. ASTContext &Context = getContext();
  7718. unsigned N = readInt();
  7719. NestedNameSpecifierLocBuilder Builder;
  7720. for (unsigned I = 0; I != N; ++I) {
  7721. auto Kind = readNestedNameSpecifierKind();
  7722. switch (Kind) {
  7723. case NestedNameSpecifier::Identifier: {
  7724. IdentifierInfo *II = readIdentifier();
  7725. SourceRange Range = readSourceRange();
  7726. Builder.Extend(Context, II, Range.getBegin(), Range.getEnd());
  7727. break;
  7728. }
  7729. case NestedNameSpecifier::Namespace: {
  7730. NamespaceDecl *NS = readDeclAs<NamespaceDecl>();
  7731. SourceRange Range = readSourceRange();
  7732. Builder.Extend(Context, NS, Range.getBegin(), Range.getEnd());
  7733. break;
  7734. }
  7735. case NestedNameSpecifier::NamespaceAlias: {
  7736. NamespaceAliasDecl *Alias = readDeclAs<NamespaceAliasDecl>();
  7737. SourceRange Range = readSourceRange();
  7738. Builder.Extend(Context, Alias, Range.getBegin(), Range.getEnd());
  7739. break;
  7740. }
  7741. case NestedNameSpecifier::TypeSpec:
  7742. case NestedNameSpecifier::TypeSpecWithTemplate: {
  7743. bool Template = readBool();
  7744. TypeSourceInfo *T = readTypeSourceInfo();
  7745. if (!T)
  7746. return NestedNameSpecifierLoc();
  7747. SourceLocation ColonColonLoc = readSourceLocation();
  7748. // FIXME: 'template' keyword location not saved anywhere, so we fake it.
  7749. Builder.Extend(Context,
  7750. Template? T->getTypeLoc().getBeginLoc() : SourceLocation(),
  7751. T->getTypeLoc(), ColonColonLoc);
  7752. break;
  7753. }
  7754. case NestedNameSpecifier::Global: {
  7755. SourceLocation ColonColonLoc = readSourceLocation();
  7756. Builder.MakeGlobal(Context, ColonColonLoc);
  7757. break;
  7758. }
  7759. case NestedNameSpecifier::Super: {
  7760. CXXRecordDecl *RD = readDeclAs<CXXRecordDecl>();
  7761. SourceRange Range = readSourceRange();
  7762. Builder.MakeSuper(Context, RD, Range.getBegin(), Range.getEnd());
  7763. break;
  7764. }
  7765. }
  7766. }
  7767. return Builder.getWithLocInContext(Context);
  7768. }
  7769. SourceRange
  7770. ASTReader::ReadSourceRange(ModuleFile &F, const RecordData &Record,
  7771. unsigned &Idx) {
  7772. SourceLocation beg = ReadSourceLocation(F, Record, Idx);
  7773. SourceLocation end = ReadSourceLocation(F, Record, Idx);
  7774. return SourceRange(beg, end);
  7775. }
  7776. /// Read a floating-point value
  7777. llvm::APFloat ASTRecordReader::readAPFloat(const llvm::fltSemantics &Sem) {
  7778. return llvm::APFloat(Sem, readAPInt());
  7779. }
  7780. // Read a string
  7781. std::string ASTReader::ReadString(const RecordData &Record, unsigned &Idx) {
  7782. unsigned Len = Record[Idx++];
  7783. std::string Result(Record.data() + Idx, Record.data() + Idx + Len);
  7784. Idx += Len;
  7785. return Result;
  7786. }
  7787. std::string ASTReader::ReadPath(ModuleFile &F, const RecordData &Record,
  7788. unsigned &Idx) {
  7789. std::string Filename = ReadString(Record, Idx);
  7790. ResolveImportedPath(F, Filename);
  7791. return Filename;
  7792. }
  7793. std::string ASTReader::ReadPath(StringRef BaseDirectory,
  7794. const RecordData &Record, unsigned &Idx) {
  7795. std::string Filename = ReadString(Record, Idx);
  7796. if (!BaseDirectory.empty())
  7797. ResolveImportedPath(Filename, BaseDirectory);
  7798. return Filename;
  7799. }
  7800. VersionTuple ASTReader::ReadVersionTuple(const RecordData &Record,
  7801. unsigned &Idx) {
  7802. unsigned Major = Record[Idx++];
  7803. unsigned Minor = Record[Idx++];
  7804. unsigned Subminor = Record[Idx++];
  7805. if (Minor == 0)
  7806. return VersionTuple(Major);
  7807. if (Subminor == 0)
  7808. return VersionTuple(Major, Minor - 1);
  7809. return VersionTuple(Major, Minor - 1, Subminor - 1);
  7810. }
  7811. CXXTemporary *ASTReader::ReadCXXTemporary(ModuleFile &F,
  7812. const RecordData &Record,
  7813. unsigned &Idx) {
  7814. CXXDestructorDecl *Decl = ReadDeclAs<CXXDestructorDecl>(F, Record, Idx);
  7815. return CXXTemporary::Create(getContext(), Decl);
  7816. }
  7817. DiagnosticBuilder ASTReader::Diag(unsigned DiagID) const {
  7818. return Diag(CurrentImportLoc, DiagID);
  7819. }
  7820. DiagnosticBuilder ASTReader::Diag(SourceLocation Loc, unsigned DiagID) const {
  7821. return Diags.Report(Loc, DiagID);
  7822. }
  7823. /// Retrieve the identifier table associated with the
  7824. /// preprocessor.
  7825. IdentifierTable &ASTReader::getIdentifierTable() {
  7826. return PP.getIdentifierTable();
  7827. }
  7828. /// Record that the given ID maps to the given switch-case
  7829. /// statement.
  7830. void ASTReader::RecordSwitchCaseID(SwitchCase *SC, unsigned ID) {
  7831. assert((*CurrSwitchCaseStmts)[ID] == nullptr &&
  7832. "Already have a SwitchCase with this ID");
  7833. (*CurrSwitchCaseStmts)[ID] = SC;
  7834. }
  7835. /// Retrieve the switch-case statement with the given ID.
  7836. SwitchCase *ASTReader::getSwitchCaseWithID(unsigned ID) {
  7837. assert((*CurrSwitchCaseStmts)[ID] != nullptr && "No SwitchCase with this ID");
  7838. return (*CurrSwitchCaseStmts)[ID];
  7839. }
  7840. void ASTReader::ClearSwitchCaseIDs() {
  7841. CurrSwitchCaseStmts->clear();
  7842. }
  7843. void ASTReader::ReadComments() {
  7844. ASTContext &Context = getContext();
  7845. std::vector<RawComment *> Comments;
  7846. for (SmallVectorImpl<std::pair<BitstreamCursor,
  7847. serialization::ModuleFile *>>::iterator
  7848. I = CommentsCursors.begin(),
  7849. E = CommentsCursors.end();
  7850. I != E; ++I) {
  7851. Comments.clear();
  7852. BitstreamCursor &Cursor = I->first;
  7853. serialization::ModuleFile &F = *I->second;
  7854. SavedStreamPosition SavedPosition(Cursor);
  7855. RecordData Record;
  7856. while (true) {
  7857. Expected<llvm::BitstreamEntry> MaybeEntry =
  7858. Cursor.advanceSkippingSubblocks(
  7859. BitstreamCursor::AF_DontPopBlockAtEnd);
  7860. if (!MaybeEntry) {
  7861. Error(MaybeEntry.takeError());
  7862. return;
  7863. }
  7864. llvm::BitstreamEntry Entry = MaybeEntry.get();
  7865. switch (Entry.Kind) {
  7866. case llvm::BitstreamEntry::SubBlock: // Handled for us already.
  7867. case llvm::BitstreamEntry::Error:
  7868. Error("malformed block record in AST file");
  7869. return;
  7870. case llvm::BitstreamEntry::EndBlock:
  7871. goto NextCursor;
  7872. case llvm::BitstreamEntry::Record:
  7873. // The interesting case.
  7874. break;
  7875. }
  7876. // Read a record.
  7877. Record.clear();
  7878. Expected<unsigned> MaybeComment = Cursor.readRecord(Entry.ID, Record);
  7879. if (!MaybeComment) {
  7880. Error(MaybeComment.takeError());
  7881. return;
  7882. }
  7883. switch ((CommentRecordTypes)MaybeComment.get()) {
  7884. case COMMENTS_RAW_COMMENT: {
  7885. unsigned Idx = 0;
  7886. SourceRange SR = ReadSourceRange(F, Record, Idx);
  7887. RawComment::CommentKind Kind =
  7888. (RawComment::CommentKind) Record[Idx++];
  7889. bool IsTrailingComment = Record[Idx++];
  7890. bool IsAlmostTrailingComment = Record[Idx++];
  7891. Comments.push_back(new (Context) RawComment(
  7892. SR, Kind, IsTrailingComment, IsAlmostTrailingComment));
  7893. break;
  7894. }
  7895. }
  7896. }
  7897. NextCursor:
  7898. llvm::DenseMap<FileID, std::map<unsigned, RawComment *>>
  7899. FileToOffsetToComment;
  7900. for (RawComment *C : Comments) {
  7901. SourceLocation CommentLoc = C->getBeginLoc();
  7902. if (CommentLoc.isValid()) {
  7903. std::pair<FileID, unsigned> Loc =
  7904. SourceMgr.getDecomposedLoc(CommentLoc);
  7905. if (Loc.first.isValid())
  7906. Context.Comments.OrderedComments[Loc.first].emplace(Loc.second, C);
  7907. }
  7908. }
  7909. }
  7910. }
  7911. void ASTReader::visitInputFiles(serialization::ModuleFile &MF,
  7912. bool IncludeSystem, bool Complain,
  7913. llvm::function_ref<void(const serialization::InputFile &IF,
  7914. bool isSystem)> Visitor) {
  7915. unsigned NumUserInputs = MF.NumUserInputFiles;
  7916. unsigned NumInputs = MF.InputFilesLoaded.size();
  7917. assert(NumUserInputs <= NumInputs);
  7918. unsigned N = IncludeSystem ? NumInputs : NumUserInputs;
  7919. for (unsigned I = 0; I < N; ++I) {
  7920. bool IsSystem = I >= NumUserInputs;
  7921. InputFile IF = getInputFile(MF, I+1, Complain);
  7922. Visitor(IF, IsSystem);
  7923. }
  7924. }
  7925. void ASTReader::visitTopLevelModuleMaps(
  7926. serialization::ModuleFile &MF,
  7927. llvm::function_ref<void(const FileEntry *FE)> Visitor) {
  7928. unsigned NumInputs = MF.InputFilesLoaded.size();
  7929. for (unsigned I = 0; I < NumInputs; ++I) {
  7930. InputFileInfo IFI = readInputFileInfo(MF, I + 1);
  7931. if (IFI.TopLevelModuleMap)
  7932. // FIXME: This unnecessarily re-reads the InputFileInfo.
  7933. if (auto FE = getInputFile(MF, I + 1).getFile())
  7934. Visitor(FE);
  7935. }
  7936. }
  7937. std::string ASTReader::getOwningModuleNameForDiagnostic(const Decl *D) {
  7938. // If we know the owning module, use it.
  7939. if (Module *M = D->getImportedOwningModule())
  7940. return M->getFullModuleName();
  7941. // Otherwise, use the name of the top-level module the decl is within.
  7942. if (ModuleFile *M = getOwningModuleFile(D))
  7943. return M->ModuleName;
  7944. // Not from a module.
  7945. return {};
  7946. }
  7947. void ASTReader::finishPendingActions() {
  7948. while (!PendingIdentifierInfos.empty() || !PendingFunctionTypes.empty() ||
  7949. !PendingIncompleteDeclChains.empty() || !PendingDeclChains.empty() ||
  7950. !PendingMacroIDs.empty() || !PendingDeclContextInfos.empty() ||
  7951. !PendingUpdateRecords.empty()) {
  7952. // If any identifiers with corresponding top-level declarations have
  7953. // been loaded, load those declarations now.
  7954. using TopLevelDeclsMap =
  7955. llvm::DenseMap<IdentifierInfo *, SmallVector<Decl *, 2>>;
  7956. TopLevelDeclsMap TopLevelDecls;
  7957. while (!PendingIdentifierInfos.empty()) {
  7958. IdentifierInfo *II = PendingIdentifierInfos.back().first;
  7959. SmallVector<uint32_t, 4> DeclIDs =
  7960. std::move(PendingIdentifierInfos.back().second);
  7961. PendingIdentifierInfos.pop_back();
  7962. SetGloballyVisibleDecls(II, DeclIDs, &TopLevelDecls[II]);
  7963. }
  7964. // Load each function type that we deferred loading because it was a
  7965. // deduced type that might refer to a local type declared within itself.
  7966. for (unsigned I = 0; I != PendingFunctionTypes.size(); ++I) {
  7967. auto *FD = PendingFunctionTypes[I].first;
  7968. FD->setType(GetType(PendingFunctionTypes[I].second));
  7969. // If we gave a function a deduced return type, remember that we need to
  7970. // propagate that along the redeclaration chain.
  7971. auto *DT = FD->getReturnType()->getContainedDeducedType();
  7972. if (DT && DT->isDeduced())
  7973. PendingDeducedTypeUpdates.insert(
  7974. {FD->getCanonicalDecl(), FD->getReturnType()});
  7975. }
  7976. PendingFunctionTypes.clear();
  7977. // For each decl chain that we wanted to complete while deserializing, mark
  7978. // it as "still needs to be completed".
  7979. for (unsigned I = 0; I != PendingIncompleteDeclChains.size(); ++I) {
  7980. markIncompleteDeclChain(PendingIncompleteDeclChains[I]);
  7981. }
  7982. PendingIncompleteDeclChains.clear();
  7983. // Load pending declaration chains.
  7984. for (unsigned I = 0; I != PendingDeclChains.size(); ++I)
  7985. loadPendingDeclChain(PendingDeclChains[I].first,
  7986. PendingDeclChains[I].second);
  7987. PendingDeclChains.clear();
  7988. // Make the most recent of the top-level declarations visible.
  7989. for (TopLevelDeclsMap::iterator TLD = TopLevelDecls.begin(),
  7990. TLDEnd = TopLevelDecls.end(); TLD != TLDEnd; ++TLD) {
  7991. IdentifierInfo *II = TLD->first;
  7992. for (unsigned I = 0, N = TLD->second.size(); I != N; ++I) {
  7993. pushExternalDeclIntoScope(cast<NamedDecl>(TLD->second[I]), II);
  7994. }
  7995. }
  7996. // Load any pending macro definitions.
  7997. for (unsigned I = 0; I != PendingMacroIDs.size(); ++I) {
  7998. IdentifierInfo *II = PendingMacroIDs.begin()[I].first;
  7999. SmallVector<PendingMacroInfo, 2> GlobalIDs;
  8000. GlobalIDs.swap(PendingMacroIDs.begin()[I].second);
  8001. // Initialize the macro history from chained-PCHs ahead of module imports.
  8002. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  8003. ++IDIdx) {
  8004. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  8005. if (!Info.M->isModule())
  8006. resolvePendingMacro(II, Info);
  8007. }
  8008. // Handle module imports.
  8009. for (unsigned IDIdx = 0, NumIDs = GlobalIDs.size(); IDIdx != NumIDs;
  8010. ++IDIdx) {
  8011. const PendingMacroInfo &Info = GlobalIDs[IDIdx];
  8012. if (Info.M->isModule())
  8013. resolvePendingMacro(II, Info);
  8014. }
  8015. }
  8016. PendingMacroIDs.clear();
  8017. // Wire up the DeclContexts for Decls that we delayed setting until
  8018. // recursive loading is completed.
  8019. while (!PendingDeclContextInfos.empty()) {
  8020. PendingDeclContextInfo Info = PendingDeclContextInfos.front();
  8021. PendingDeclContextInfos.pop_front();
  8022. DeclContext *SemaDC = cast<DeclContext>(GetDecl(Info.SemaDC));
  8023. DeclContext *LexicalDC = cast<DeclContext>(GetDecl(Info.LexicalDC));
  8024. Info.D->setDeclContextsImpl(SemaDC, LexicalDC, getContext());
  8025. }
  8026. // Perform any pending declaration updates.
  8027. while (!PendingUpdateRecords.empty()) {
  8028. auto Update = PendingUpdateRecords.pop_back_val();
  8029. ReadingKindTracker ReadingKind(Read_Decl, *this);
  8030. loadDeclUpdateRecords(Update);
  8031. }
  8032. }
  8033. // At this point, all update records for loaded decls are in place, so any
  8034. // fake class definitions should have become real.
  8035. assert(PendingFakeDefinitionData.empty() &&
  8036. "faked up a class definition but never saw the real one");
  8037. // If we deserialized any C++ or Objective-C class definitions, any
  8038. // Objective-C protocol definitions, or any redeclarable templates, make sure
  8039. // that all redeclarations point to the definitions. Note that this can only
  8040. // happen now, after the redeclaration chains have been fully wired.
  8041. for (Decl *D : PendingDefinitions) {
  8042. if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
  8043. if (const TagType *TagT = dyn_cast<TagType>(TD->getTypeForDecl())) {
  8044. // Make sure that the TagType points at the definition.
  8045. const_cast<TagType*>(TagT)->decl = TD;
  8046. }
  8047. if (auto RD = dyn_cast<CXXRecordDecl>(D)) {
  8048. for (auto *R = getMostRecentExistingDecl(RD); R;
  8049. R = R->getPreviousDecl()) {
  8050. assert((R == D) ==
  8051. cast<CXXRecordDecl>(R)->isThisDeclarationADefinition() &&
  8052. "declaration thinks it's the definition but it isn't");
  8053. cast<CXXRecordDecl>(R)->DefinitionData = RD->DefinitionData;
  8054. }
  8055. }
  8056. continue;
  8057. }
  8058. if (auto ID = dyn_cast<ObjCInterfaceDecl>(D)) {
  8059. // Make sure that the ObjCInterfaceType points at the definition.
  8060. const_cast<ObjCInterfaceType *>(cast<ObjCInterfaceType>(ID->TypeForDecl))
  8061. ->Decl = ID;
  8062. for (auto *R = getMostRecentExistingDecl(ID); R; R = R->getPreviousDecl())
  8063. cast<ObjCInterfaceDecl>(R)->Data = ID->Data;
  8064. continue;
  8065. }
  8066. if (auto PD = dyn_cast<ObjCProtocolDecl>(D)) {
  8067. for (auto *R = getMostRecentExistingDecl(PD); R; R = R->getPreviousDecl())
  8068. cast<ObjCProtocolDecl>(R)->Data = PD->Data;
  8069. continue;
  8070. }
  8071. auto RTD = cast<RedeclarableTemplateDecl>(D)->getCanonicalDecl();
  8072. for (auto *R = getMostRecentExistingDecl(RTD); R; R = R->getPreviousDecl())
  8073. cast<RedeclarableTemplateDecl>(R)->Common = RTD->Common;
  8074. }
  8075. PendingDefinitions.clear();
  8076. // Load the bodies of any functions or methods we've encountered. We do
  8077. // this now (delayed) so that we can be sure that the declaration chains
  8078. // have been fully wired up (hasBody relies on this).
  8079. // FIXME: We shouldn't require complete redeclaration chains here.
  8080. for (PendingBodiesMap::iterator PB = PendingBodies.begin(),
  8081. PBEnd = PendingBodies.end();
  8082. PB != PBEnd; ++PB) {
  8083. if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PB->first)) {
  8084. // For a function defined inline within a class template, force the
  8085. // canonical definition to be the one inside the canonical definition of
  8086. // the template. This ensures that we instantiate from a correct view
  8087. // of the template.
  8088. //
  8089. // Sadly we can't do this more generally: we can't be sure that all
  8090. // copies of an arbitrary class definition will have the same members
  8091. // defined (eg, some member functions may not be instantiated, and some
  8092. // special members may or may not have been implicitly defined).
  8093. if (auto *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalParent()))
  8094. if (RD->isDependentContext() && !RD->isThisDeclarationADefinition())
  8095. continue;
  8096. // FIXME: Check for =delete/=default?
  8097. // FIXME: Complain about ODR violations here?
  8098. const FunctionDecl *Defn = nullptr;
  8099. if (!getContext().getLangOpts().Modules || !FD->hasBody(Defn)) {
  8100. FD->setLazyBody(PB->second);
  8101. } else {
  8102. auto *NonConstDefn = const_cast<FunctionDecl*>(Defn);
  8103. mergeDefinitionVisibility(NonConstDefn, FD);
  8104. if (!FD->isLateTemplateParsed() &&
  8105. !NonConstDefn->isLateTemplateParsed() &&
  8106. FD->getODRHash() != NonConstDefn->getODRHash()) {
  8107. if (!isa<CXXMethodDecl>(FD)) {
  8108. PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
  8109. } else if (FD->getLexicalParent()->isFileContext() &&
  8110. NonConstDefn->getLexicalParent()->isFileContext()) {
  8111. // Only diagnose out-of-line method definitions. If they are
  8112. // in class definitions, then an error will be generated when
  8113. // processing the class bodies.
  8114. PendingFunctionOdrMergeFailures[FD].push_back(NonConstDefn);
  8115. }
  8116. }
  8117. }
  8118. continue;
  8119. }
  8120. ObjCMethodDecl *MD = cast<ObjCMethodDecl>(PB->first);
  8121. if (!getContext().getLangOpts().Modules || !MD->hasBody())
  8122. MD->setLazyBody(PB->second);
  8123. }
  8124. PendingBodies.clear();
  8125. // Do some cleanup.
  8126. for (auto *ND : PendingMergedDefinitionsToDeduplicate)
  8127. getContext().deduplicateMergedDefinitonsFor(ND);
  8128. PendingMergedDefinitionsToDeduplicate.clear();
  8129. }
  8130. void ASTReader::diagnoseOdrViolations() {
  8131. if (PendingOdrMergeFailures.empty() && PendingOdrMergeChecks.empty() &&
  8132. PendingFunctionOdrMergeFailures.empty() &&
  8133. PendingEnumOdrMergeFailures.empty())
  8134. return;
  8135. // Trigger the import of the full definition of each class that had any
  8136. // odr-merging problems, so we can produce better diagnostics for them.
  8137. // These updates may in turn find and diagnose some ODR failures, so take
  8138. // ownership of the set first.
  8139. auto OdrMergeFailures = std::move(PendingOdrMergeFailures);
  8140. PendingOdrMergeFailures.clear();
  8141. for (auto &Merge : OdrMergeFailures) {
  8142. Merge.first->buildLookup();
  8143. Merge.first->decls_begin();
  8144. Merge.first->bases_begin();
  8145. Merge.first->vbases_begin();
  8146. for (auto &RecordPair : Merge.second) {
  8147. auto *RD = RecordPair.first;
  8148. RD->decls_begin();
  8149. RD->bases_begin();
  8150. RD->vbases_begin();
  8151. }
  8152. }
  8153. // Trigger the import of functions.
  8154. auto FunctionOdrMergeFailures = std::move(PendingFunctionOdrMergeFailures);
  8155. PendingFunctionOdrMergeFailures.clear();
  8156. for (auto &Merge : FunctionOdrMergeFailures) {
  8157. Merge.first->buildLookup();
  8158. Merge.first->decls_begin();
  8159. Merge.first->getBody();
  8160. for (auto &FD : Merge.second) {
  8161. FD->buildLookup();
  8162. FD->decls_begin();
  8163. FD->getBody();
  8164. }
  8165. }
  8166. // Trigger the import of enums.
  8167. auto EnumOdrMergeFailures = std::move(PendingEnumOdrMergeFailures);
  8168. PendingEnumOdrMergeFailures.clear();
  8169. for (auto &Merge : EnumOdrMergeFailures) {
  8170. Merge.first->decls_begin();
  8171. for (auto &Enum : Merge.second) {
  8172. Enum->decls_begin();
  8173. }
  8174. }
  8175. // For each declaration from a merged context, check that the canonical
  8176. // definition of that context also contains a declaration of the same
  8177. // entity.
  8178. //
  8179. // Caution: this loop does things that might invalidate iterators into
  8180. // PendingOdrMergeChecks. Don't turn this into a range-based for loop!
  8181. while (!PendingOdrMergeChecks.empty()) {
  8182. NamedDecl *D = PendingOdrMergeChecks.pop_back_val();
  8183. // FIXME: Skip over implicit declarations for now. This matters for things
  8184. // like implicitly-declared special member functions. This isn't entirely
  8185. // correct; we can end up with multiple unmerged declarations of the same
  8186. // implicit entity.
  8187. if (D->isImplicit())
  8188. continue;
  8189. DeclContext *CanonDef = D->getDeclContext();
  8190. bool Found = false;
  8191. const Decl *DCanon = D->getCanonicalDecl();
  8192. for (auto RI : D->redecls()) {
  8193. if (RI->getLexicalDeclContext() == CanonDef) {
  8194. Found = true;
  8195. break;
  8196. }
  8197. }
  8198. if (Found)
  8199. continue;
  8200. // Quick check failed, time to do the slow thing. Note, we can't just
  8201. // look up the name of D in CanonDef here, because the member that is
  8202. // in CanonDef might not be found by name lookup (it might have been
  8203. // replaced by a more recent declaration in the lookup table), and we
  8204. // can't necessarily find it in the redeclaration chain because it might
  8205. // be merely mergeable, not redeclarable.
  8206. llvm::SmallVector<const NamedDecl*, 4> Candidates;
  8207. for (auto *CanonMember : CanonDef->decls()) {
  8208. if (CanonMember->getCanonicalDecl() == DCanon) {
  8209. // This can happen if the declaration is merely mergeable and not
  8210. // actually redeclarable (we looked for redeclarations earlier).
  8211. //
  8212. // FIXME: We should be able to detect this more efficiently, without
  8213. // pulling in all of the members of CanonDef.
  8214. Found = true;
  8215. break;
  8216. }
  8217. if (auto *ND = dyn_cast<NamedDecl>(CanonMember))
  8218. if (ND->getDeclName() == D->getDeclName())
  8219. Candidates.push_back(ND);
  8220. }
  8221. if (!Found) {
  8222. // The AST doesn't like TagDecls becoming invalid after they've been
  8223. // completed. We only really need to mark FieldDecls as invalid here.
  8224. if (!isa<TagDecl>(D))
  8225. D->setInvalidDecl();
  8226. // Ensure we don't accidentally recursively enter deserialization while
  8227. // we're producing our diagnostic.
  8228. Deserializing RecursionGuard(this);
  8229. std::string CanonDefModule =
  8230. getOwningModuleNameForDiagnostic(cast<Decl>(CanonDef));
  8231. Diag(D->getLocation(), diag::err_module_odr_violation_missing_decl)
  8232. << D << getOwningModuleNameForDiagnostic(D)
  8233. << CanonDef << CanonDefModule.empty() << CanonDefModule;
  8234. if (Candidates.empty())
  8235. Diag(cast<Decl>(CanonDef)->getLocation(),
  8236. diag::note_module_odr_violation_no_possible_decls) << D;
  8237. else {
  8238. for (unsigned I = 0, N = Candidates.size(); I != N; ++I)
  8239. Diag(Candidates[I]->getLocation(),
  8240. diag::note_module_odr_violation_possible_decl)
  8241. << Candidates[I];
  8242. }
  8243. DiagnosedOdrMergeFailures.insert(CanonDef);
  8244. }
  8245. }
  8246. if (OdrMergeFailures.empty() && FunctionOdrMergeFailures.empty() &&
  8247. EnumOdrMergeFailures.empty())
  8248. return;
  8249. // Ensure we don't accidentally recursively enter deserialization while
  8250. // we're producing our diagnostics.
  8251. Deserializing RecursionGuard(this);
  8252. // Common code for hashing helpers.
  8253. ODRHash Hash;
  8254. auto ComputeQualTypeODRHash = [&Hash](QualType Ty) {
  8255. Hash.clear();
  8256. Hash.AddQualType(Ty);
  8257. return Hash.CalculateHash();
  8258. };
  8259. auto ComputeODRHash = [&Hash](const Stmt *S) {
  8260. assert(S);
  8261. Hash.clear();
  8262. Hash.AddStmt(S);
  8263. return Hash.CalculateHash();
  8264. };
  8265. auto ComputeSubDeclODRHash = [&Hash](const Decl *D) {
  8266. assert(D);
  8267. Hash.clear();
  8268. Hash.AddSubDecl(D);
  8269. return Hash.CalculateHash();
  8270. };
  8271. auto ComputeTemplateArgumentODRHash = [&Hash](const TemplateArgument &TA) {
  8272. Hash.clear();
  8273. Hash.AddTemplateArgument(TA);
  8274. return Hash.CalculateHash();
  8275. };
  8276. auto ComputeTemplateParameterListODRHash =
  8277. [&Hash](const TemplateParameterList *TPL) {
  8278. assert(TPL);
  8279. Hash.clear();
  8280. Hash.AddTemplateParameterList(TPL);
  8281. return Hash.CalculateHash();
  8282. };
  8283. // Used with err_module_odr_violation_mismatch_decl and
  8284. // note_module_odr_violation_mismatch_decl
  8285. // This list should be the same Decl's as in ODRHash::isDeclToBeProcessed
  8286. enum ODRMismatchDecl {
  8287. EndOfClass,
  8288. PublicSpecifer,
  8289. PrivateSpecifer,
  8290. ProtectedSpecifer,
  8291. StaticAssert,
  8292. Field,
  8293. CXXMethod,
  8294. TypeAlias,
  8295. TypeDef,
  8296. Var,
  8297. Friend,
  8298. FunctionTemplate,
  8299. Other
  8300. };
  8301. // Used with err_module_odr_violation_mismatch_decl_diff and
  8302. // note_module_odr_violation_mismatch_decl_diff
  8303. enum ODRMismatchDeclDifference {
  8304. StaticAssertCondition,
  8305. StaticAssertMessage,
  8306. StaticAssertOnlyMessage,
  8307. FieldName,
  8308. FieldTypeName,
  8309. FieldSingleBitField,
  8310. FieldDifferentWidthBitField,
  8311. FieldSingleMutable,
  8312. FieldSingleInitializer,
  8313. FieldDifferentInitializers,
  8314. MethodName,
  8315. MethodDeleted,
  8316. MethodDefaulted,
  8317. MethodVirtual,
  8318. MethodStatic,
  8319. MethodVolatile,
  8320. MethodConst,
  8321. MethodInline,
  8322. MethodNumberParameters,
  8323. MethodParameterType,
  8324. MethodParameterName,
  8325. MethodParameterSingleDefaultArgument,
  8326. MethodParameterDifferentDefaultArgument,
  8327. MethodNoTemplateArguments,
  8328. MethodDifferentNumberTemplateArguments,
  8329. MethodDifferentTemplateArgument,
  8330. MethodSingleBody,
  8331. MethodDifferentBody,
  8332. TypedefName,
  8333. TypedefType,
  8334. VarName,
  8335. VarType,
  8336. VarSingleInitializer,
  8337. VarDifferentInitializer,
  8338. VarConstexpr,
  8339. FriendTypeFunction,
  8340. FriendType,
  8341. FriendFunction,
  8342. FunctionTemplateDifferentNumberParameters,
  8343. FunctionTemplateParameterDifferentKind,
  8344. FunctionTemplateParameterName,
  8345. FunctionTemplateParameterSingleDefaultArgument,
  8346. FunctionTemplateParameterDifferentDefaultArgument,
  8347. FunctionTemplateParameterDifferentType,
  8348. FunctionTemplatePackParameter,
  8349. };
  8350. // These lambdas have the common portions of the ODR diagnostics. This
  8351. // has the same return as Diag(), so addition parameters can be passed
  8352. // in with operator<<
  8353. auto ODRDiagDeclError = [this](NamedDecl *FirstRecord, StringRef FirstModule,
  8354. SourceLocation Loc, SourceRange Range,
  8355. ODRMismatchDeclDifference DiffType) {
  8356. return Diag(Loc, diag::err_module_odr_violation_mismatch_decl_diff)
  8357. << FirstRecord << FirstModule.empty() << FirstModule << Range
  8358. << DiffType;
  8359. };
  8360. auto ODRDiagDeclNote = [this](StringRef SecondModule, SourceLocation Loc,
  8361. SourceRange Range, ODRMismatchDeclDifference DiffType) {
  8362. return Diag(Loc, diag::note_module_odr_violation_mismatch_decl_diff)
  8363. << SecondModule << Range << DiffType;
  8364. };
  8365. auto ODRDiagField = [this, &ODRDiagDeclError, &ODRDiagDeclNote,
  8366. &ComputeQualTypeODRHash, &ComputeODRHash](
  8367. NamedDecl *FirstRecord, StringRef FirstModule,
  8368. StringRef SecondModule, FieldDecl *FirstField,
  8369. FieldDecl *SecondField) {
  8370. IdentifierInfo *FirstII = FirstField->getIdentifier();
  8371. IdentifierInfo *SecondII = SecondField->getIdentifier();
  8372. if (FirstII->getName() != SecondII->getName()) {
  8373. ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
  8374. FirstField->getSourceRange(), FieldName)
  8375. << FirstII;
  8376. ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
  8377. SecondField->getSourceRange(), FieldName)
  8378. << SecondII;
  8379. return true;
  8380. }
  8381. assert(getContext().hasSameType(FirstField->getType(),
  8382. SecondField->getType()));
  8383. QualType FirstType = FirstField->getType();
  8384. QualType SecondType = SecondField->getType();
  8385. if (ComputeQualTypeODRHash(FirstType) !=
  8386. ComputeQualTypeODRHash(SecondType)) {
  8387. ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
  8388. FirstField->getSourceRange(), FieldTypeName)
  8389. << FirstII << FirstType;
  8390. ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
  8391. SecondField->getSourceRange(), FieldTypeName)
  8392. << SecondII << SecondType;
  8393. return true;
  8394. }
  8395. const bool IsFirstBitField = FirstField->isBitField();
  8396. const bool IsSecondBitField = SecondField->isBitField();
  8397. if (IsFirstBitField != IsSecondBitField) {
  8398. ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
  8399. FirstField->getSourceRange(), FieldSingleBitField)
  8400. << FirstII << IsFirstBitField;
  8401. ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
  8402. SecondField->getSourceRange(), FieldSingleBitField)
  8403. << SecondII << IsSecondBitField;
  8404. return true;
  8405. }
  8406. if (IsFirstBitField && IsSecondBitField) {
  8407. unsigned FirstBitWidthHash =
  8408. ComputeODRHash(FirstField->getBitWidth());
  8409. unsigned SecondBitWidthHash =
  8410. ComputeODRHash(SecondField->getBitWidth());
  8411. if (FirstBitWidthHash != SecondBitWidthHash) {
  8412. ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
  8413. FirstField->getSourceRange(),
  8414. FieldDifferentWidthBitField)
  8415. << FirstII << FirstField->getBitWidth()->getSourceRange();
  8416. ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
  8417. SecondField->getSourceRange(),
  8418. FieldDifferentWidthBitField)
  8419. << SecondII << SecondField->getBitWidth()->getSourceRange();
  8420. return true;
  8421. }
  8422. }
  8423. if (!PP.getLangOpts().CPlusPlus)
  8424. return false;
  8425. const bool IsFirstMutable = FirstField->isMutable();
  8426. const bool IsSecondMutable = SecondField->isMutable();
  8427. if (IsFirstMutable != IsSecondMutable) {
  8428. ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
  8429. FirstField->getSourceRange(), FieldSingleMutable)
  8430. << FirstII << IsFirstMutable;
  8431. ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
  8432. SecondField->getSourceRange(), FieldSingleMutable)
  8433. << SecondII << IsSecondMutable;
  8434. return true;
  8435. }
  8436. const Expr *FirstInitializer = FirstField->getInClassInitializer();
  8437. const Expr *SecondInitializer = SecondField->getInClassInitializer();
  8438. if ((!FirstInitializer && SecondInitializer) ||
  8439. (FirstInitializer && !SecondInitializer)) {
  8440. ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
  8441. FirstField->getSourceRange(), FieldSingleInitializer)
  8442. << FirstII << (FirstInitializer != nullptr);
  8443. ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
  8444. SecondField->getSourceRange(), FieldSingleInitializer)
  8445. << SecondII << (SecondInitializer != nullptr);
  8446. return true;
  8447. }
  8448. if (FirstInitializer && SecondInitializer) {
  8449. unsigned FirstInitHash = ComputeODRHash(FirstInitializer);
  8450. unsigned SecondInitHash = ComputeODRHash(SecondInitializer);
  8451. if (FirstInitHash != SecondInitHash) {
  8452. ODRDiagDeclError(FirstRecord, FirstModule, FirstField->getLocation(),
  8453. FirstField->getSourceRange(),
  8454. FieldDifferentInitializers)
  8455. << FirstII << FirstInitializer->getSourceRange();
  8456. ODRDiagDeclNote(SecondModule, SecondField->getLocation(),
  8457. SecondField->getSourceRange(),
  8458. FieldDifferentInitializers)
  8459. << SecondII << SecondInitializer->getSourceRange();
  8460. return true;
  8461. }
  8462. }
  8463. return false;
  8464. };
  8465. auto ODRDiagTypeDefOrAlias =
  8466. [&ODRDiagDeclError, &ODRDiagDeclNote, &ComputeQualTypeODRHash](
  8467. NamedDecl *FirstRecord, StringRef FirstModule, StringRef SecondModule,
  8468. TypedefNameDecl *FirstTD, TypedefNameDecl *SecondTD,
  8469. bool IsTypeAlias) {
  8470. auto FirstName = FirstTD->getDeclName();
  8471. auto SecondName = SecondTD->getDeclName();
  8472. if (FirstName != SecondName) {
  8473. ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
  8474. FirstTD->getSourceRange(), TypedefName)
  8475. << IsTypeAlias << FirstName;
  8476. ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
  8477. SecondTD->getSourceRange(), TypedefName)
  8478. << IsTypeAlias << SecondName;
  8479. return true;
  8480. }
  8481. QualType FirstType = FirstTD->getUnderlyingType();
  8482. QualType SecondType = SecondTD->getUnderlyingType();
  8483. if (ComputeQualTypeODRHash(FirstType) !=
  8484. ComputeQualTypeODRHash(SecondType)) {
  8485. ODRDiagDeclError(FirstRecord, FirstModule, FirstTD->getLocation(),
  8486. FirstTD->getSourceRange(), TypedefType)
  8487. << IsTypeAlias << FirstName << FirstType;
  8488. ODRDiagDeclNote(SecondModule, SecondTD->getLocation(),
  8489. SecondTD->getSourceRange(), TypedefType)
  8490. << IsTypeAlias << SecondName << SecondType;
  8491. return true;
  8492. }
  8493. return false;
  8494. };
  8495. auto ODRDiagVar = [&ODRDiagDeclError, &ODRDiagDeclNote,
  8496. &ComputeQualTypeODRHash, &ComputeODRHash,
  8497. this](NamedDecl *FirstRecord, StringRef FirstModule,
  8498. StringRef SecondModule, VarDecl *FirstVD,
  8499. VarDecl *SecondVD) {
  8500. auto FirstName = FirstVD->getDeclName();
  8501. auto SecondName = SecondVD->getDeclName();
  8502. if (FirstName != SecondName) {
  8503. ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
  8504. FirstVD->getSourceRange(), VarName)
  8505. << FirstName;
  8506. ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
  8507. SecondVD->getSourceRange(), VarName)
  8508. << SecondName;
  8509. return true;
  8510. }
  8511. QualType FirstType = FirstVD->getType();
  8512. QualType SecondType = SecondVD->getType();
  8513. if (ComputeQualTypeODRHash(FirstType) !=
  8514. ComputeQualTypeODRHash(SecondType)) {
  8515. ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
  8516. FirstVD->getSourceRange(), VarType)
  8517. << FirstName << FirstType;
  8518. ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
  8519. SecondVD->getSourceRange(), VarType)
  8520. << SecondName << SecondType;
  8521. return true;
  8522. }
  8523. if (!PP.getLangOpts().CPlusPlus)
  8524. return false;
  8525. const Expr *FirstInit = FirstVD->getInit();
  8526. const Expr *SecondInit = SecondVD->getInit();
  8527. if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
  8528. ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
  8529. FirstVD->getSourceRange(), VarSingleInitializer)
  8530. << FirstName << (FirstInit == nullptr)
  8531. << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
  8532. ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
  8533. SecondVD->getSourceRange(), VarSingleInitializer)
  8534. << SecondName << (SecondInit == nullptr)
  8535. << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
  8536. return true;
  8537. }
  8538. if (FirstInit && SecondInit &&
  8539. ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
  8540. ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
  8541. FirstVD->getSourceRange(), VarDifferentInitializer)
  8542. << FirstName << FirstInit->getSourceRange();
  8543. ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
  8544. SecondVD->getSourceRange(), VarDifferentInitializer)
  8545. << SecondName << SecondInit->getSourceRange();
  8546. return true;
  8547. }
  8548. const bool FirstIsConstexpr = FirstVD->isConstexpr();
  8549. const bool SecondIsConstexpr = SecondVD->isConstexpr();
  8550. if (FirstIsConstexpr != SecondIsConstexpr) {
  8551. ODRDiagDeclError(FirstRecord, FirstModule, FirstVD->getLocation(),
  8552. FirstVD->getSourceRange(), VarConstexpr)
  8553. << FirstName << FirstIsConstexpr;
  8554. ODRDiagDeclNote(SecondModule, SecondVD->getLocation(),
  8555. SecondVD->getSourceRange(), VarConstexpr)
  8556. << SecondName << SecondIsConstexpr;
  8557. return true;
  8558. }
  8559. return false;
  8560. };
  8561. auto DifferenceSelector = [](Decl *D) {
  8562. assert(D && "valid Decl required");
  8563. switch (D->getKind()) {
  8564. default:
  8565. return Other;
  8566. case Decl::AccessSpec:
  8567. switch (D->getAccess()) {
  8568. case AS_public:
  8569. return PublicSpecifer;
  8570. case AS_private:
  8571. return PrivateSpecifer;
  8572. case AS_protected:
  8573. return ProtectedSpecifer;
  8574. case AS_none:
  8575. break;
  8576. }
  8577. llvm_unreachable("Invalid access specifier");
  8578. case Decl::StaticAssert:
  8579. return StaticAssert;
  8580. case Decl::Field:
  8581. return Field;
  8582. case Decl::CXXMethod:
  8583. case Decl::CXXConstructor:
  8584. case Decl::CXXDestructor:
  8585. return CXXMethod;
  8586. case Decl::TypeAlias:
  8587. return TypeAlias;
  8588. case Decl::Typedef:
  8589. return TypeDef;
  8590. case Decl::Var:
  8591. return Var;
  8592. case Decl::Friend:
  8593. return Friend;
  8594. case Decl::FunctionTemplate:
  8595. return FunctionTemplate;
  8596. }
  8597. };
  8598. using DeclHashes = llvm::SmallVector<std::pair<Decl *, unsigned>, 4>;
  8599. auto PopulateHashes = [&ComputeSubDeclODRHash](DeclHashes &Hashes,
  8600. RecordDecl *Record,
  8601. const DeclContext *DC) {
  8602. for (auto *D : Record->decls()) {
  8603. if (!ODRHash::isDeclToBeProcessed(D, DC))
  8604. continue;
  8605. Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
  8606. }
  8607. };
  8608. struct DiffResult {
  8609. Decl *FirstDecl = nullptr, *SecondDecl = nullptr;
  8610. ODRMismatchDecl FirstDiffType = Other, SecondDiffType = Other;
  8611. };
  8612. // If there is a diagnoseable difference, FirstDiffType and
  8613. // SecondDiffType will not be Other and FirstDecl and SecondDecl will be
  8614. // filled in if not EndOfClass.
  8615. auto FindTypeDiffs = [&DifferenceSelector](DeclHashes &FirstHashes,
  8616. DeclHashes &SecondHashes) {
  8617. DiffResult DR;
  8618. auto FirstIt = FirstHashes.begin();
  8619. auto SecondIt = SecondHashes.begin();
  8620. while (FirstIt != FirstHashes.end() || SecondIt != SecondHashes.end()) {
  8621. if (FirstIt != FirstHashes.end() && SecondIt != SecondHashes.end() &&
  8622. FirstIt->second == SecondIt->second) {
  8623. ++FirstIt;
  8624. ++SecondIt;
  8625. continue;
  8626. }
  8627. DR.FirstDecl = FirstIt == FirstHashes.end() ? nullptr : FirstIt->first;
  8628. DR.SecondDecl =
  8629. SecondIt == SecondHashes.end() ? nullptr : SecondIt->first;
  8630. DR.FirstDiffType =
  8631. DR.FirstDecl ? DifferenceSelector(DR.FirstDecl) : EndOfClass;
  8632. DR.SecondDiffType =
  8633. DR.SecondDecl ? DifferenceSelector(DR.SecondDecl) : EndOfClass;
  8634. return DR;
  8635. }
  8636. return DR;
  8637. };
  8638. // Use this to diagnose that an unexpected Decl was encountered
  8639. // or no difference was detected. This causes a generic error
  8640. // message to be emitted.
  8641. auto DiagnoseODRUnexpected = [this](DiffResult &DR, NamedDecl *FirstRecord,
  8642. StringRef FirstModule,
  8643. NamedDecl *SecondRecord,
  8644. StringRef SecondModule) {
  8645. Diag(FirstRecord->getLocation(),
  8646. diag::err_module_odr_violation_different_definitions)
  8647. << FirstRecord << FirstModule.empty() << FirstModule;
  8648. if (DR.FirstDecl) {
  8649. Diag(DR.FirstDecl->getLocation(), diag::note_first_module_difference)
  8650. << FirstRecord << DR.FirstDecl->getSourceRange();
  8651. }
  8652. Diag(SecondRecord->getLocation(),
  8653. diag::note_module_odr_violation_different_definitions)
  8654. << SecondModule;
  8655. if (DR.SecondDecl) {
  8656. Diag(DR.SecondDecl->getLocation(), diag::note_second_module_difference)
  8657. << DR.SecondDecl->getSourceRange();
  8658. }
  8659. };
  8660. auto DiagnoseODRMismatch =
  8661. [this](DiffResult &DR, NamedDecl *FirstRecord, StringRef FirstModule,
  8662. NamedDecl *SecondRecord, StringRef SecondModule) {
  8663. SourceLocation FirstLoc;
  8664. SourceRange FirstRange;
  8665. auto *FirstTag = dyn_cast<TagDecl>(FirstRecord);
  8666. if (DR.FirstDiffType == EndOfClass && FirstTag) {
  8667. FirstLoc = FirstTag->getBraceRange().getEnd();
  8668. } else {
  8669. FirstLoc = DR.FirstDecl->getLocation();
  8670. FirstRange = DR.FirstDecl->getSourceRange();
  8671. }
  8672. Diag(FirstLoc, diag::err_module_odr_violation_mismatch_decl)
  8673. << FirstRecord << FirstModule.empty() << FirstModule << FirstRange
  8674. << DR.FirstDiffType;
  8675. SourceLocation SecondLoc;
  8676. SourceRange SecondRange;
  8677. auto *SecondTag = dyn_cast<TagDecl>(SecondRecord);
  8678. if (DR.SecondDiffType == EndOfClass && SecondTag) {
  8679. SecondLoc = SecondTag->getBraceRange().getEnd();
  8680. } else {
  8681. SecondLoc = DR.SecondDecl->getLocation();
  8682. SecondRange = DR.SecondDecl->getSourceRange();
  8683. }
  8684. Diag(SecondLoc, diag::note_module_odr_violation_mismatch_decl)
  8685. << SecondModule << SecondRange << DR.SecondDiffType;
  8686. };
  8687. // Issue any pending ODR-failure diagnostics.
  8688. for (auto &Merge : OdrMergeFailures) {
  8689. // If we've already pointed out a specific problem with this class, don't
  8690. // bother issuing a general "something's different" diagnostic.
  8691. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
  8692. continue;
  8693. bool Diagnosed = false;
  8694. CXXRecordDecl *FirstRecord = Merge.first;
  8695. std::string FirstModule = getOwningModuleNameForDiagnostic(FirstRecord);
  8696. for (auto &RecordPair : Merge.second) {
  8697. CXXRecordDecl *SecondRecord = RecordPair.first;
  8698. // Multiple different declarations got merged together; tell the user
  8699. // where they came from.
  8700. if (FirstRecord == SecondRecord)
  8701. continue;
  8702. std::string SecondModule = getOwningModuleNameForDiagnostic(SecondRecord);
  8703. auto *FirstDD = FirstRecord->DefinitionData;
  8704. auto *SecondDD = RecordPair.second;
  8705. assert(FirstDD && SecondDD && "Definitions without DefinitionData");
  8706. // Diagnostics from DefinitionData are emitted here.
  8707. if (FirstDD != SecondDD) {
  8708. enum ODRDefinitionDataDifference {
  8709. NumBases,
  8710. NumVBases,
  8711. BaseType,
  8712. BaseVirtual,
  8713. BaseAccess,
  8714. };
  8715. auto ODRDiagBaseError = [FirstRecord, &FirstModule,
  8716. this](SourceLocation Loc, SourceRange Range,
  8717. ODRDefinitionDataDifference DiffType) {
  8718. return Diag(Loc, diag::err_module_odr_violation_definition_data)
  8719. << FirstRecord << FirstModule.empty() << FirstModule << Range
  8720. << DiffType;
  8721. };
  8722. auto ODRDiagBaseNote = [&SecondModule,
  8723. this](SourceLocation Loc, SourceRange Range,
  8724. ODRDefinitionDataDifference DiffType) {
  8725. return Diag(Loc, diag::note_module_odr_violation_definition_data)
  8726. << SecondModule << Range << DiffType;
  8727. };
  8728. unsigned FirstNumBases = FirstDD->NumBases;
  8729. unsigned FirstNumVBases = FirstDD->NumVBases;
  8730. unsigned SecondNumBases = SecondDD->NumBases;
  8731. unsigned SecondNumVBases = SecondDD->NumVBases;
  8732. auto GetSourceRange = [](struct CXXRecordDecl::DefinitionData *DD) {
  8733. unsigned NumBases = DD->NumBases;
  8734. if (NumBases == 0) return SourceRange();
  8735. auto bases = DD->bases();
  8736. return SourceRange(bases[0].getBeginLoc(),
  8737. bases[NumBases - 1].getEndLoc());
  8738. };
  8739. if (FirstNumBases != SecondNumBases) {
  8740. ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
  8741. NumBases)
  8742. << FirstNumBases;
  8743. ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
  8744. NumBases)
  8745. << SecondNumBases;
  8746. Diagnosed = true;
  8747. break;
  8748. }
  8749. if (FirstNumVBases != SecondNumVBases) {
  8750. ODRDiagBaseError(FirstRecord->getLocation(), GetSourceRange(FirstDD),
  8751. NumVBases)
  8752. << FirstNumVBases;
  8753. ODRDiagBaseNote(SecondRecord->getLocation(), GetSourceRange(SecondDD),
  8754. NumVBases)
  8755. << SecondNumVBases;
  8756. Diagnosed = true;
  8757. break;
  8758. }
  8759. auto FirstBases = FirstDD->bases();
  8760. auto SecondBases = SecondDD->bases();
  8761. unsigned i = 0;
  8762. for (i = 0; i < FirstNumBases; ++i) {
  8763. auto FirstBase = FirstBases[i];
  8764. auto SecondBase = SecondBases[i];
  8765. if (ComputeQualTypeODRHash(FirstBase.getType()) !=
  8766. ComputeQualTypeODRHash(SecondBase.getType())) {
  8767. ODRDiagBaseError(FirstRecord->getLocation(),
  8768. FirstBase.getSourceRange(), BaseType)
  8769. << (i + 1) << FirstBase.getType();
  8770. ODRDiagBaseNote(SecondRecord->getLocation(),
  8771. SecondBase.getSourceRange(), BaseType)
  8772. << (i + 1) << SecondBase.getType();
  8773. break;
  8774. }
  8775. if (FirstBase.isVirtual() != SecondBase.isVirtual()) {
  8776. ODRDiagBaseError(FirstRecord->getLocation(),
  8777. FirstBase.getSourceRange(), BaseVirtual)
  8778. << (i + 1) << FirstBase.isVirtual() << FirstBase.getType();
  8779. ODRDiagBaseNote(SecondRecord->getLocation(),
  8780. SecondBase.getSourceRange(), BaseVirtual)
  8781. << (i + 1) << SecondBase.isVirtual() << SecondBase.getType();
  8782. break;
  8783. }
  8784. if (FirstBase.getAccessSpecifierAsWritten() !=
  8785. SecondBase.getAccessSpecifierAsWritten()) {
  8786. ODRDiagBaseError(FirstRecord->getLocation(),
  8787. FirstBase.getSourceRange(), BaseAccess)
  8788. << (i + 1) << FirstBase.getType()
  8789. << (int)FirstBase.getAccessSpecifierAsWritten();
  8790. ODRDiagBaseNote(SecondRecord->getLocation(),
  8791. SecondBase.getSourceRange(), BaseAccess)
  8792. << (i + 1) << SecondBase.getType()
  8793. << (int)SecondBase.getAccessSpecifierAsWritten();
  8794. break;
  8795. }
  8796. }
  8797. if (i != FirstNumBases) {
  8798. Diagnosed = true;
  8799. break;
  8800. }
  8801. }
  8802. const ClassTemplateDecl *FirstTemplate =
  8803. FirstRecord->getDescribedClassTemplate();
  8804. const ClassTemplateDecl *SecondTemplate =
  8805. SecondRecord->getDescribedClassTemplate();
  8806. assert(!FirstTemplate == !SecondTemplate &&
  8807. "Both pointers should be null or non-null");
  8808. enum ODRTemplateDifference {
  8809. ParamEmptyName,
  8810. ParamName,
  8811. ParamSingleDefaultArgument,
  8812. ParamDifferentDefaultArgument,
  8813. };
  8814. if (FirstTemplate && SecondTemplate) {
  8815. DeclHashes FirstTemplateHashes;
  8816. DeclHashes SecondTemplateHashes;
  8817. auto PopulateTemplateParameterHashs =
  8818. [&ComputeSubDeclODRHash](DeclHashes &Hashes,
  8819. const ClassTemplateDecl *TD) {
  8820. for (auto *D : TD->getTemplateParameters()->asArray()) {
  8821. Hashes.emplace_back(D, ComputeSubDeclODRHash(D));
  8822. }
  8823. };
  8824. PopulateTemplateParameterHashs(FirstTemplateHashes, FirstTemplate);
  8825. PopulateTemplateParameterHashs(SecondTemplateHashes, SecondTemplate);
  8826. assert(FirstTemplateHashes.size() == SecondTemplateHashes.size() &&
  8827. "Number of template parameters should be equal.");
  8828. auto FirstIt = FirstTemplateHashes.begin();
  8829. auto FirstEnd = FirstTemplateHashes.end();
  8830. auto SecondIt = SecondTemplateHashes.begin();
  8831. for (; FirstIt != FirstEnd; ++FirstIt, ++SecondIt) {
  8832. if (FirstIt->second == SecondIt->second)
  8833. continue;
  8834. auto ODRDiagTemplateError = [FirstRecord, &FirstModule, this](
  8835. SourceLocation Loc, SourceRange Range,
  8836. ODRTemplateDifference DiffType) {
  8837. return Diag(Loc, diag::err_module_odr_violation_template_parameter)
  8838. << FirstRecord << FirstModule.empty() << FirstModule << Range
  8839. << DiffType;
  8840. };
  8841. auto ODRDiagTemplateNote = [&SecondModule, this](
  8842. SourceLocation Loc, SourceRange Range,
  8843. ODRTemplateDifference DiffType) {
  8844. return Diag(Loc, diag::note_module_odr_violation_template_parameter)
  8845. << SecondModule << Range << DiffType;
  8846. };
  8847. const NamedDecl* FirstDecl = cast<NamedDecl>(FirstIt->first);
  8848. const NamedDecl* SecondDecl = cast<NamedDecl>(SecondIt->first);
  8849. assert(FirstDecl->getKind() == SecondDecl->getKind() &&
  8850. "Parameter Decl's should be the same kind.");
  8851. DeclarationName FirstName = FirstDecl->getDeclName();
  8852. DeclarationName SecondName = SecondDecl->getDeclName();
  8853. if (FirstName != SecondName) {
  8854. const bool FirstNameEmpty =
  8855. FirstName.isIdentifier() && !FirstName.getAsIdentifierInfo();
  8856. const bool SecondNameEmpty =
  8857. SecondName.isIdentifier() && !SecondName.getAsIdentifierInfo();
  8858. assert((!FirstNameEmpty || !SecondNameEmpty) &&
  8859. "Both template parameters cannot be unnamed.");
  8860. ODRDiagTemplateError(FirstDecl->getLocation(),
  8861. FirstDecl->getSourceRange(),
  8862. FirstNameEmpty ? ParamEmptyName : ParamName)
  8863. << FirstName;
  8864. ODRDiagTemplateNote(SecondDecl->getLocation(),
  8865. SecondDecl->getSourceRange(),
  8866. SecondNameEmpty ? ParamEmptyName : ParamName)
  8867. << SecondName;
  8868. break;
  8869. }
  8870. switch (FirstDecl->getKind()) {
  8871. default:
  8872. llvm_unreachable("Invalid template parameter type.");
  8873. case Decl::TemplateTypeParm: {
  8874. const auto *FirstParam = cast<TemplateTypeParmDecl>(FirstDecl);
  8875. const auto *SecondParam = cast<TemplateTypeParmDecl>(SecondDecl);
  8876. const bool HasFirstDefaultArgument =
  8877. FirstParam->hasDefaultArgument() &&
  8878. !FirstParam->defaultArgumentWasInherited();
  8879. const bool HasSecondDefaultArgument =
  8880. SecondParam->hasDefaultArgument() &&
  8881. !SecondParam->defaultArgumentWasInherited();
  8882. if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
  8883. ODRDiagTemplateError(FirstDecl->getLocation(),
  8884. FirstDecl->getSourceRange(),
  8885. ParamSingleDefaultArgument)
  8886. << HasFirstDefaultArgument;
  8887. ODRDiagTemplateNote(SecondDecl->getLocation(),
  8888. SecondDecl->getSourceRange(),
  8889. ParamSingleDefaultArgument)
  8890. << HasSecondDefaultArgument;
  8891. break;
  8892. }
  8893. assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
  8894. "Expecting default arguments.");
  8895. ODRDiagTemplateError(FirstDecl->getLocation(),
  8896. FirstDecl->getSourceRange(),
  8897. ParamDifferentDefaultArgument);
  8898. ODRDiagTemplateNote(SecondDecl->getLocation(),
  8899. SecondDecl->getSourceRange(),
  8900. ParamDifferentDefaultArgument);
  8901. break;
  8902. }
  8903. case Decl::NonTypeTemplateParm: {
  8904. const auto *FirstParam = cast<NonTypeTemplateParmDecl>(FirstDecl);
  8905. const auto *SecondParam = cast<NonTypeTemplateParmDecl>(SecondDecl);
  8906. const bool HasFirstDefaultArgument =
  8907. FirstParam->hasDefaultArgument() &&
  8908. !FirstParam->defaultArgumentWasInherited();
  8909. const bool HasSecondDefaultArgument =
  8910. SecondParam->hasDefaultArgument() &&
  8911. !SecondParam->defaultArgumentWasInherited();
  8912. if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
  8913. ODRDiagTemplateError(FirstDecl->getLocation(),
  8914. FirstDecl->getSourceRange(),
  8915. ParamSingleDefaultArgument)
  8916. << HasFirstDefaultArgument;
  8917. ODRDiagTemplateNote(SecondDecl->getLocation(),
  8918. SecondDecl->getSourceRange(),
  8919. ParamSingleDefaultArgument)
  8920. << HasSecondDefaultArgument;
  8921. break;
  8922. }
  8923. assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
  8924. "Expecting default arguments.");
  8925. ODRDiagTemplateError(FirstDecl->getLocation(),
  8926. FirstDecl->getSourceRange(),
  8927. ParamDifferentDefaultArgument);
  8928. ODRDiagTemplateNote(SecondDecl->getLocation(),
  8929. SecondDecl->getSourceRange(),
  8930. ParamDifferentDefaultArgument);
  8931. break;
  8932. }
  8933. case Decl::TemplateTemplateParm: {
  8934. const auto *FirstParam = cast<TemplateTemplateParmDecl>(FirstDecl);
  8935. const auto *SecondParam =
  8936. cast<TemplateTemplateParmDecl>(SecondDecl);
  8937. const bool HasFirstDefaultArgument =
  8938. FirstParam->hasDefaultArgument() &&
  8939. !FirstParam->defaultArgumentWasInherited();
  8940. const bool HasSecondDefaultArgument =
  8941. SecondParam->hasDefaultArgument() &&
  8942. !SecondParam->defaultArgumentWasInherited();
  8943. if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
  8944. ODRDiagTemplateError(FirstDecl->getLocation(),
  8945. FirstDecl->getSourceRange(),
  8946. ParamSingleDefaultArgument)
  8947. << HasFirstDefaultArgument;
  8948. ODRDiagTemplateNote(SecondDecl->getLocation(),
  8949. SecondDecl->getSourceRange(),
  8950. ParamSingleDefaultArgument)
  8951. << HasSecondDefaultArgument;
  8952. break;
  8953. }
  8954. assert(HasFirstDefaultArgument && HasSecondDefaultArgument &&
  8955. "Expecting default arguments.");
  8956. ODRDiagTemplateError(FirstDecl->getLocation(),
  8957. FirstDecl->getSourceRange(),
  8958. ParamDifferentDefaultArgument);
  8959. ODRDiagTemplateNote(SecondDecl->getLocation(),
  8960. SecondDecl->getSourceRange(),
  8961. ParamDifferentDefaultArgument);
  8962. break;
  8963. }
  8964. }
  8965. break;
  8966. }
  8967. if (FirstIt != FirstEnd) {
  8968. Diagnosed = true;
  8969. break;
  8970. }
  8971. }
  8972. DeclHashes FirstHashes;
  8973. DeclHashes SecondHashes;
  8974. const DeclContext *DC = FirstRecord;
  8975. PopulateHashes(FirstHashes, FirstRecord, DC);
  8976. PopulateHashes(SecondHashes, SecondRecord, DC);
  8977. auto DR = FindTypeDiffs(FirstHashes, SecondHashes);
  8978. ODRMismatchDecl FirstDiffType = DR.FirstDiffType;
  8979. ODRMismatchDecl SecondDiffType = DR.SecondDiffType;
  8980. Decl *FirstDecl = DR.FirstDecl;
  8981. Decl *SecondDecl = DR.SecondDecl;
  8982. if (FirstDiffType == Other || SecondDiffType == Other) {
  8983. DiagnoseODRUnexpected(DR, FirstRecord, FirstModule, SecondRecord,
  8984. SecondModule);
  8985. Diagnosed = true;
  8986. break;
  8987. }
  8988. if (FirstDiffType != SecondDiffType) {
  8989. DiagnoseODRMismatch(DR, FirstRecord, FirstModule, SecondRecord,
  8990. SecondModule);
  8991. Diagnosed = true;
  8992. break;
  8993. }
  8994. assert(FirstDiffType == SecondDiffType);
  8995. switch (FirstDiffType) {
  8996. case Other:
  8997. case EndOfClass:
  8998. case PublicSpecifer:
  8999. case PrivateSpecifer:
  9000. case ProtectedSpecifer:
  9001. llvm_unreachable("Invalid diff type");
  9002. case StaticAssert: {
  9003. StaticAssertDecl *FirstSA = cast<StaticAssertDecl>(FirstDecl);
  9004. StaticAssertDecl *SecondSA = cast<StaticAssertDecl>(SecondDecl);
  9005. Expr *FirstExpr = FirstSA->getAssertExpr();
  9006. Expr *SecondExpr = SecondSA->getAssertExpr();
  9007. unsigned FirstODRHash = ComputeODRHash(FirstExpr);
  9008. unsigned SecondODRHash = ComputeODRHash(SecondExpr);
  9009. if (FirstODRHash != SecondODRHash) {
  9010. ODRDiagDeclError(FirstRecord, FirstModule, FirstExpr->getBeginLoc(),
  9011. FirstExpr->getSourceRange(), StaticAssertCondition);
  9012. ODRDiagDeclNote(SecondModule, SecondExpr->getBeginLoc(),
  9013. SecondExpr->getSourceRange(), StaticAssertCondition);
  9014. Diagnosed = true;
  9015. break;
  9016. }
  9017. StringLiteral *FirstStr = FirstSA->getMessage();
  9018. StringLiteral *SecondStr = SecondSA->getMessage();
  9019. assert((FirstStr || SecondStr) && "Both messages cannot be empty");
  9020. if ((FirstStr && !SecondStr) || (!FirstStr && SecondStr)) {
  9021. SourceLocation FirstLoc, SecondLoc;
  9022. SourceRange FirstRange, SecondRange;
  9023. if (FirstStr) {
  9024. FirstLoc = FirstStr->getBeginLoc();
  9025. FirstRange = FirstStr->getSourceRange();
  9026. } else {
  9027. FirstLoc = FirstSA->getBeginLoc();
  9028. FirstRange = FirstSA->getSourceRange();
  9029. }
  9030. if (SecondStr) {
  9031. SecondLoc = SecondStr->getBeginLoc();
  9032. SecondRange = SecondStr->getSourceRange();
  9033. } else {
  9034. SecondLoc = SecondSA->getBeginLoc();
  9035. SecondRange = SecondSA->getSourceRange();
  9036. }
  9037. ODRDiagDeclError(FirstRecord, FirstModule, FirstLoc, FirstRange,
  9038. StaticAssertOnlyMessage)
  9039. << (FirstStr == nullptr);
  9040. ODRDiagDeclNote(SecondModule, SecondLoc, SecondRange,
  9041. StaticAssertOnlyMessage)
  9042. << (SecondStr == nullptr);
  9043. Diagnosed = true;
  9044. break;
  9045. }
  9046. if (FirstStr && SecondStr &&
  9047. FirstStr->getString() != SecondStr->getString()) {
  9048. ODRDiagDeclError(FirstRecord, FirstModule, FirstStr->getBeginLoc(),
  9049. FirstStr->getSourceRange(), StaticAssertMessage);
  9050. ODRDiagDeclNote(SecondModule, SecondStr->getBeginLoc(),
  9051. SecondStr->getSourceRange(), StaticAssertMessage);
  9052. Diagnosed = true;
  9053. break;
  9054. }
  9055. break;
  9056. }
  9057. case Field: {
  9058. Diagnosed = ODRDiagField(FirstRecord, FirstModule, SecondModule,
  9059. cast<FieldDecl>(FirstDecl),
  9060. cast<FieldDecl>(SecondDecl));
  9061. break;
  9062. }
  9063. case CXXMethod: {
  9064. enum {
  9065. DiagMethod,
  9066. DiagConstructor,
  9067. DiagDestructor,
  9068. } FirstMethodType,
  9069. SecondMethodType;
  9070. auto GetMethodTypeForDiagnostics = [](const CXXMethodDecl* D) {
  9071. if (isa<CXXConstructorDecl>(D)) return DiagConstructor;
  9072. if (isa<CXXDestructorDecl>(D)) return DiagDestructor;
  9073. return DiagMethod;
  9074. };
  9075. const CXXMethodDecl *FirstMethod = cast<CXXMethodDecl>(FirstDecl);
  9076. const CXXMethodDecl *SecondMethod = cast<CXXMethodDecl>(SecondDecl);
  9077. FirstMethodType = GetMethodTypeForDiagnostics(FirstMethod);
  9078. SecondMethodType = GetMethodTypeForDiagnostics(SecondMethod);
  9079. auto FirstName = FirstMethod->getDeclName();
  9080. auto SecondName = SecondMethod->getDeclName();
  9081. if (FirstMethodType != SecondMethodType || FirstName != SecondName) {
  9082. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9083. FirstMethod->getSourceRange(), MethodName)
  9084. << FirstMethodType << FirstName;
  9085. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9086. SecondMethod->getSourceRange(), MethodName)
  9087. << SecondMethodType << SecondName;
  9088. Diagnosed = true;
  9089. break;
  9090. }
  9091. const bool FirstDeleted = FirstMethod->isDeletedAsWritten();
  9092. const bool SecondDeleted = SecondMethod->isDeletedAsWritten();
  9093. if (FirstDeleted != SecondDeleted) {
  9094. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9095. FirstMethod->getSourceRange(), MethodDeleted)
  9096. << FirstMethodType << FirstName << FirstDeleted;
  9097. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9098. SecondMethod->getSourceRange(), MethodDeleted)
  9099. << SecondMethodType << SecondName << SecondDeleted;
  9100. Diagnosed = true;
  9101. break;
  9102. }
  9103. const bool FirstDefaulted = FirstMethod->isExplicitlyDefaulted();
  9104. const bool SecondDefaulted = SecondMethod->isExplicitlyDefaulted();
  9105. if (FirstDefaulted != SecondDefaulted) {
  9106. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9107. FirstMethod->getSourceRange(), MethodDefaulted)
  9108. << FirstMethodType << FirstName << FirstDefaulted;
  9109. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9110. SecondMethod->getSourceRange(), MethodDefaulted)
  9111. << SecondMethodType << SecondName << SecondDefaulted;
  9112. Diagnosed = true;
  9113. break;
  9114. }
  9115. const bool FirstVirtual = FirstMethod->isVirtualAsWritten();
  9116. const bool SecondVirtual = SecondMethod->isVirtualAsWritten();
  9117. const bool FirstPure = FirstMethod->isPure();
  9118. const bool SecondPure = SecondMethod->isPure();
  9119. if ((FirstVirtual || SecondVirtual) &&
  9120. (FirstVirtual != SecondVirtual || FirstPure != SecondPure)) {
  9121. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9122. FirstMethod->getSourceRange(), MethodVirtual)
  9123. << FirstMethodType << FirstName << FirstPure << FirstVirtual;
  9124. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9125. SecondMethod->getSourceRange(), MethodVirtual)
  9126. << SecondMethodType << SecondName << SecondPure << SecondVirtual;
  9127. Diagnosed = true;
  9128. break;
  9129. }
  9130. // CXXMethodDecl::isStatic uses the canonical Decl. With Decl merging,
  9131. // FirstDecl is the canonical Decl of SecondDecl, so the storage
  9132. // class needs to be checked instead.
  9133. const auto FirstStorage = FirstMethod->getStorageClass();
  9134. const auto SecondStorage = SecondMethod->getStorageClass();
  9135. const bool FirstStatic = FirstStorage == SC_Static;
  9136. const bool SecondStatic = SecondStorage == SC_Static;
  9137. if (FirstStatic != SecondStatic) {
  9138. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9139. FirstMethod->getSourceRange(), MethodStatic)
  9140. << FirstMethodType << FirstName << FirstStatic;
  9141. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9142. SecondMethod->getSourceRange(), MethodStatic)
  9143. << SecondMethodType << SecondName << SecondStatic;
  9144. Diagnosed = true;
  9145. break;
  9146. }
  9147. const bool FirstVolatile = FirstMethod->isVolatile();
  9148. const bool SecondVolatile = SecondMethod->isVolatile();
  9149. if (FirstVolatile != SecondVolatile) {
  9150. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9151. FirstMethod->getSourceRange(), MethodVolatile)
  9152. << FirstMethodType << FirstName << FirstVolatile;
  9153. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9154. SecondMethod->getSourceRange(), MethodVolatile)
  9155. << SecondMethodType << SecondName << SecondVolatile;
  9156. Diagnosed = true;
  9157. break;
  9158. }
  9159. const bool FirstConst = FirstMethod->isConst();
  9160. const bool SecondConst = SecondMethod->isConst();
  9161. if (FirstConst != SecondConst) {
  9162. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9163. FirstMethod->getSourceRange(), MethodConst)
  9164. << FirstMethodType << FirstName << FirstConst;
  9165. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9166. SecondMethod->getSourceRange(), MethodConst)
  9167. << SecondMethodType << SecondName << SecondConst;
  9168. Diagnosed = true;
  9169. break;
  9170. }
  9171. const bool FirstInline = FirstMethod->isInlineSpecified();
  9172. const bool SecondInline = SecondMethod->isInlineSpecified();
  9173. if (FirstInline != SecondInline) {
  9174. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9175. FirstMethod->getSourceRange(), MethodInline)
  9176. << FirstMethodType << FirstName << FirstInline;
  9177. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9178. SecondMethod->getSourceRange(), MethodInline)
  9179. << SecondMethodType << SecondName << SecondInline;
  9180. Diagnosed = true;
  9181. break;
  9182. }
  9183. const unsigned FirstNumParameters = FirstMethod->param_size();
  9184. const unsigned SecondNumParameters = SecondMethod->param_size();
  9185. if (FirstNumParameters != SecondNumParameters) {
  9186. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9187. FirstMethod->getSourceRange(),
  9188. MethodNumberParameters)
  9189. << FirstMethodType << FirstName << FirstNumParameters;
  9190. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9191. SecondMethod->getSourceRange(),
  9192. MethodNumberParameters)
  9193. << SecondMethodType << SecondName << SecondNumParameters;
  9194. Diagnosed = true;
  9195. break;
  9196. }
  9197. // Need this status boolean to know when break out of the switch.
  9198. bool ParameterMismatch = false;
  9199. for (unsigned I = 0; I < FirstNumParameters; ++I) {
  9200. const ParmVarDecl *FirstParam = FirstMethod->getParamDecl(I);
  9201. const ParmVarDecl *SecondParam = SecondMethod->getParamDecl(I);
  9202. QualType FirstParamType = FirstParam->getType();
  9203. QualType SecondParamType = SecondParam->getType();
  9204. if (FirstParamType != SecondParamType &&
  9205. ComputeQualTypeODRHash(FirstParamType) !=
  9206. ComputeQualTypeODRHash(SecondParamType)) {
  9207. if (const DecayedType *ParamDecayedType =
  9208. FirstParamType->getAs<DecayedType>()) {
  9209. ODRDiagDeclError(
  9210. FirstRecord, FirstModule, FirstMethod->getLocation(),
  9211. FirstMethod->getSourceRange(), MethodParameterType)
  9212. << FirstMethodType << FirstName << (I + 1) << FirstParamType
  9213. << true << ParamDecayedType->getOriginalType();
  9214. } else {
  9215. ODRDiagDeclError(
  9216. FirstRecord, FirstModule, FirstMethod->getLocation(),
  9217. FirstMethod->getSourceRange(), MethodParameterType)
  9218. << FirstMethodType << FirstName << (I + 1) << FirstParamType
  9219. << false;
  9220. }
  9221. if (const DecayedType *ParamDecayedType =
  9222. SecondParamType->getAs<DecayedType>()) {
  9223. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9224. SecondMethod->getSourceRange(),
  9225. MethodParameterType)
  9226. << SecondMethodType << SecondName << (I + 1)
  9227. << SecondParamType << true
  9228. << ParamDecayedType->getOriginalType();
  9229. } else {
  9230. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9231. SecondMethod->getSourceRange(),
  9232. MethodParameterType)
  9233. << SecondMethodType << SecondName << (I + 1)
  9234. << SecondParamType << false;
  9235. }
  9236. ParameterMismatch = true;
  9237. break;
  9238. }
  9239. DeclarationName FirstParamName = FirstParam->getDeclName();
  9240. DeclarationName SecondParamName = SecondParam->getDeclName();
  9241. if (FirstParamName != SecondParamName) {
  9242. ODRDiagDeclError(FirstRecord, FirstModule,
  9243. FirstMethod->getLocation(),
  9244. FirstMethod->getSourceRange(), MethodParameterName)
  9245. << FirstMethodType << FirstName << (I + 1) << FirstParamName;
  9246. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9247. SecondMethod->getSourceRange(), MethodParameterName)
  9248. << SecondMethodType << SecondName << (I + 1) << SecondParamName;
  9249. ParameterMismatch = true;
  9250. break;
  9251. }
  9252. const Expr *FirstInit = FirstParam->getInit();
  9253. const Expr *SecondInit = SecondParam->getInit();
  9254. if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
  9255. ODRDiagDeclError(FirstRecord, FirstModule,
  9256. FirstMethod->getLocation(),
  9257. FirstMethod->getSourceRange(),
  9258. MethodParameterSingleDefaultArgument)
  9259. << FirstMethodType << FirstName << (I + 1)
  9260. << (FirstInit == nullptr)
  9261. << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
  9262. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9263. SecondMethod->getSourceRange(),
  9264. MethodParameterSingleDefaultArgument)
  9265. << SecondMethodType << SecondName << (I + 1)
  9266. << (SecondInit == nullptr)
  9267. << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
  9268. ParameterMismatch = true;
  9269. break;
  9270. }
  9271. if (FirstInit && SecondInit &&
  9272. ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
  9273. ODRDiagDeclError(FirstRecord, FirstModule,
  9274. FirstMethod->getLocation(),
  9275. FirstMethod->getSourceRange(),
  9276. MethodParameterDifferentDefaultArgument)
  9277. << FirstMethodType << FirstName << (I + 1)
  9278. << FirstInit->getSourceRange();
  9279. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9280. SecondMethod->getSourceRange(),
  9281. MethodParameterDifferentDefaultArgument)
  9282. << SecondMethodType << SecondName << (I + 1)
  9283. << SecondInit->getSourceRange();
  9284. ParameterMismatch = true;
  9285. break;
  9286. }
  9287. }
  9288. if (ParameterMismatch) {
  9289. Diagnosed = true;
  9290. break;
  9291. }
  9292. const auto *FirstTemplateArgs =
  9293. FirstMethod->getTemplateSpecializationArgs();
  9294. const auto *SecondTemplateArgs =
  9295. SecondMethod->getTemplateSpecializationArgs();
  9296. if ((FirstTemplateArgs && !SecondTemplateArgs) ||
  9297. (!FirstTemplateArgs && SecondTemplateArgs)) {
  9298. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9299. FirstMethod->getSourceRange(),
  9300. MethodNoTemplateArguments)
  9301. << FirstMethodType << FirstName << (FirstTemplateArgs != nullptr);
  9302. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9303. SecondMethod->getSourceRange(),
  9304. MethodNoTemplateArguments)
  9305. << SecondMethodType << SecondName
  9306. << (SecondTemplateArgs != nullptr);
  9307. Diagnosed = true;
  9308. break;
  9309. }
  9310. if (FirstTemplateArgs && SecondTemplateArgs) {
  9311. // Remove pack expansions from argument list.
  9312. auto ExpandTemplateArgumentList =
  9313. [](const TemplateArgumentList *TAL) {
  9314. llvm::SmallVector<const TemplateArgument *, 8> ExpandedList;
  9315. for (const TemplateArgument &TA : TAL->asArray()) {
  9316. if (TA.getKind() != TemplateArgument::Pack) {
  9317. ExpandedList.push_back(&TA);
  9318. continue;
  9319. }
  9320. for (const TemplateArgument &PackTA : TA.getPackAsArray()) {
  9321. ExpandedList.push_back(&PackTA);
  9322. }
  9323. }
  9324. return ExpandedList;
  9325. };
  9326. llvm::SmallVector<const TemplateArgument *, 8> FirstExpandedList =
  9327. ExpandTemplateArgumentList(FirstTemplateArgs);
  9328. llvm::SmallVector<const TemplateArgument *, 8> SecondExpandedList =
  9329. ExpandTemplateArgumentList(SecondTemplateArgs);
  9330. if (FirstExpandedList.size() != SecondExpandedList.size()) {
  9331. ODRDiagDeclError(FirstRecord, FirstModule,
  9332. FirstMethod->getLocation(),
  9333. FirstMethod->getSourceRange(),
  9334. MethodDifferentNumberTemplateArguments)
  9335. << FirstMethodType << FirstName
  9336. << (unsigned)FirstExpandedList.size();
  9337. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9338. SecondMethod->getSourceRange(),
  9339. MethodDifferentNumberTemplateArguments)
  9340. << SecondMethodType << SecondName
  9341. << (unsigned)SecondExpandedList.size();
  9342. Diagnosed = true;
  9343. break;
  9344. }
  9345. bool TemplateArgumentMismatch = false;
  9346. for (unsigned i = 0, e = FirstExpandedList.size(); i != e; ++i) {
  9347. const TemplateArgument &FirstTA = *FirstExpandedList[i],
  9348. &SecondTA = *SecondExpandedList[i];
  9349. if (ComputeTemplateArgumentODRHash(FirstTA) ==
  9350. ComputeTemplateArgumentODRHash(SecondTA)) {
  9351. continue;
  9352. }
  9353. ODRDiagDeclError(
  9354. FirstRecord, FirstModule, FirstMethod->getLocation(),
  9355. FirstMethod->getSourceRange(), MethodDifferentTemplateArgument)
  9356. << FirstMethodType << FirstName << FirstTA << i + 1;
  9357. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9358. SecondMethod->getSourceRange(),
  9359. MethodDifferentTemplateArgument)
  9360. << SecondMethodType << SecondName << SecondTA << i + 1;
  9361. TemplateArgumentMismatch = true;
  9362. break;
  9363. }
  9364. if (TemplateArgumentMismatch) {
  9365. Diagnosed = true;
  9366. break;
  9367. }
  9368. }
  9369. // Compute the hash of the method as if it has no body.
  9370. auto ComputeCXXMethodODRHash = [&Hash](const CXXMethodDecl *D) {
  9371. Hash.clear();
  9372. Hash.AddFunctionDecl(D, true /*SkipBody*/);
  9373. return Hash.CalculateHash();
  9374. };
  9375. // Compare the hash generated to the hash stored. A difference means
  9376. // that a body was present in the original source. Due to merging,
  9377. // the stardard way of detecting a body will not work.
  9378. const bool HasFirstBody =
  9379. ComputeCXXMethodODRHash(FirstMethod) != FirstMethod->getODRHash();
  9380. const bool HasSecondBody =
  9381. ComputeCXXMethodODRHash(SecondMethod) != SecondMethod->getODRHash();
  9382. if (HasFirstBody != HasSecondBody) {
  9383. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9384. FirstMethod->getSourceRange(), MethodSingleBody)
  9385. << FirstMethodType << FirstName << HasFirstBody;
  9386. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9387. SecondMethod->getSourceRange(), MethodSingleBody)
  9388. << SecondMethodType << SecondName << HasSecondBody;
  9389. Diagnosed = true;
  9390. break;
  9391. }
  9392. if (HasFirstBody && HasSecondBody) {
  9393. ODRDiagDeclError(FirstRecord, FirstModule, FirstMethod->getLocation(),
  9394. FirstMethod->getSourceRange(), MethodDifferentBody)
  9395. << FirstMethodType << FirstName;
  9396. ODRDiagDeclNote(SecondModule, SecondMethod->getLocation(),
  9397. SecondMethod->getSourceRange(), MethodDifferentBody)
  9398. << SecondMethodType << SecondName;
  9399. Diagnosed = true;
  9400. break;
  9401. }
  9402. break;
  9403. }
  9404. case TypeAlias:
  9405. case TypeDef: {
  9406. Diagnosed = ODRDiagTypeDefOrAlias(
  9407. FirstRecord, FirstModule, SecondModule,
  9408. cast<TypedefNameDecl>(FirstDecl), cast<TypedefNameDecl>(SecondDecl),
  9409. FirstDiffType == TypeAlias);
  9410. break;
  9411. }
  9412. case Var: {
  9413. Diagnosed =
  9414. ODRDiagVar(FirstRecord, FirstModule, SecondModule,
  9415. cast<VarDecl>(FirstDecl), cast<VarDecl>(SecondDecl));
  9416. break;
  9417. }
  9418. case Friend: {
  9419. FriendDecl *FirstFriend = cast<FriendDecl>(FirstDecl);
  9420. FriendDecl *SecondFriend = cast<FriendDecl>(SecondDecl);
  9421. NamedDecl *FirstND = FirstFriend->getFriendDecl();
  9422. NamedDecl *SecondND = SecondFriend->getFriendDecl();
  9423. TypeSourceInfo *FirstTSI = FirstFriend->getFriendType();
  9424. TypeSourceInfo *SecondTSI = SecondFriend->getFriendType();
  9425. if (FirstND && SecondND) {
  9426. ODRDiagDeclError(FirstRecord, FirstModule,
  9427. FirstFriend->getFriendLoc(),
  9428. FirstFriend->getSourceRange(), FriendFunction)
  9429. << FirstND;
  9430. ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
  9431. SecondFriend->getSourceRange(), FriendFunction)
  9432. << SecondND;
  9433. Diagnosed = true;
  9434. break;
  9435. }
  9436. if (FirstTSI && SecondTSI) {
  9437. QualType FirstFriendType = FirstTSI->getType();
  9438. QualType SecondFriendType = SecondTSI->getType();
  9439. assert(ComputeQualTypeODRHash(FirstFriendType) !=
  9440. ComputeQualTypeODRHash(SecondFriendType));
  9441. ODRDiagDeclError(FirstRecord, FirstModule,
  9442. FirstFriend->getFriendLoc(),
  9443. FirstFriend->getSourceRange(), FriendType)
  9444. << FirstFriendType;
  9445. ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
  9446. SecondFriend->getSourceRange(), FriendType)
  9447. << SecondFriendType;
  9448. Diagnosed = true;
  9449. break;
  9450. }
  9451. ODRDiagDeclError(FirstRecord, FirstModule, FirstFriend->getFriendLoc(),
  9452. FirstFriend->getSourceRange(), FriendTypeFunction)
  9453. << (FirstTSI == nullptr);
  9454. ODRDiagDeclNote(SecondModule, SecondFriend->getFriendLoc(),
  9455. SecondFriend->getSourceRange(), FriendTypeFunction)
  9456. << (SecondTSI == nullptr);
  9457. Diagnosed = true;
  9458. break;
  9459. }
  9460. case FunctionTemplate: {
  9461. FunctionTemplateDecl *FirstTemplate =
  9462. cast<FunctionTemplateDecl>(FirstDecl);
  9463. FunctionTemplateDecl *SecondTemplate =
  9464. cast<FunctionTemplateDecl>(SecondDecl);
  9465. TemplateParameterList *FirstTPL =
  9466. FirstTemplate->getTemplateParameters();
  9467. TemplateParameterList *SecondTPL =
  9468. SecondTemplate->getTemplateParameters();
  9469. if (FirstTPL->size() != SecondTPL->size()) {
  9470. ODRDiagDeclError(FirstRecord, FirstModule,
  9471. FirstTemplate->getLocation(),
  9472. FirstTemplate->getSourceRange(),
  9473. FunctionTemplateDifferentNumberParameters)
  9474. << FirstTemplate << FirstTPL->size();
  9475. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9476. SecondTemplate->getSourceRange(),
  9477. FunctionTemplateDifferentNumberParameters)
  9478. << SecondTemplate << SecondTPL->size();
  9479. Diagnosed = true;
  9480. break;
  9481. }
  9482. bool ParameterMismatch = false;
  9483. for (unsigned i = 0, e = FirstTPL->size(); i != e; ++i) {
  9484. NamedDecl *FirstParam = FirstTPL->getParam(i);
  9485. NamedDecl *SecondParam = SecondTPL->getParam(i);
  9486. if (FirstParam->getKind() != SecondParam->getKind()) {
  9487. enum {
  9488. TemplateTypeParameter,
  9489. NonTypeTemplateParameter,
  9490. TemplateTemplateParameter,
  9491. };
  9492. auto GetParamType = [](NamedDecl *D) {
  9493. switch (D->getKind()) {
  9494. default:
  9495. llvm_unreachable("Unexpected template parameter type");
  9496. case Decl::TemplateTypeParm:
  9497. return TemplateTypeParameter;
  9498. case Decl::NonTypeTemplateParm:
  9499. return NonTypeTemplateParameter;
  9500. case Decl::TemplateTemplateParm:
  9501. return TemplateTemplateParameter;
  9502. }
  9503. };
  9504. ODRDiagDeclError(FirstRecord, FirstModule,
  9505. FirstTemplate->getLocation(),
  9506. FirstTemplate->getSourceRange(),
  9507. FunctionTemplateParameterDifferentKind)
  9508. << FirstTemplate << (i + 1) << GetParamType(FirstParam);
  9509. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9510. SecondTemplate->getSourceRange(),
  9511. FunctionTemplateParameterDifferentKind)
  9512. << SecondTemplate << (i + 1) << GetParamType(SecondParam);
  9513. ParameterMismatch = true;
  9514. break;
  9515. }
  9516. if (FirstParam->getName() != SecondParam->getName()) {
  9517. ODRDiagDeclError(
  9518. FirstRecord, FirstModule, FirstTemplate->getLocation(),
  9519. FirstTemplate->getSourceRange(), FunctionTemplateParameterName)
  9520. << FirstTemplate << (i + 1) << (bool)FirstParam->getIdentifier()
  9521. << FirstParam;
  9522. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9523. SecondTemplate->getSourceRange(),
  9524. FunctionTemplateParameterName)
  9525. << SecondTemplate << (i + 1)
  9526. << (bool)SecondParam->getIdentifier() << SecondParam;
  9527. ParameterMismatch = true;
  9528. break;
  9529. }
  9530. if (isa<TemplateTypeParmDecl>(FirstParam) &&
  9531. isa<TemplateTypeParmDecl>(SecondParam)) {
  9532. TemplateTypeParmDecl *FirstTTPD =
  9533. cast<TemplateTypeParmDecl>(FirstParam);
  9534. TemplateTypeParmDecl *SecondTTPD =
  9535. cast<TemplateTypeParmDecl>(SecondParam);
  9536. bool HasFirstDefaultArgument =
  9537. FirstTTPD->hasDefaultArgument() &&
  9538. !FirstTTPD->defaultArgumentWasInherited();
  9539. bool HasSecondDefaultArgument =
  9540. SecondTTPD->hasDefaultArgument() &&
  9541. !SecondTTPD->defaultArgumentWasInherited();
  9542. if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
  9543. ODRDiagDeclError(FirstRecord, FirstModule,
  9544. FirstTemplate->getLocation(),
  9545. FirstTemplate->getSourceRange(),
  9546. FunctionTemplateParameterSingleDefaultArgument)
  9547. << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
  9548. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9549. SecondTemplate->getSourceRange(),
  9550. FunctionTemplateParameterSingleDefaultArgument)
  9551. << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
  9552. ParameterMismatch = true;
  9553. break;
  9554. }
  9555. if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
  9556. QualType FirstType = FirstTTPD->getDefaultArgument();
  9557. QualType SecondType = SecondTTPD->getDefaultArgument();
  9558. if (ComputeQualTypeODRHash(FirstType) !=
  9559. ComputeQualTypeODRHash(SecondType)) {
  9560. ODRDiagDeclError(
  9561. FirstRecord, FirstModule, FirstTemplate->getLocation(),
  9562. FirstTemplate->getSourceRange(),
  9563. FunctionTemplateParameterDifferentDefaultArgument)
  9564. << FirstTemplate << (i + 1) << FirstType;
  9565. ODRDiagDeclNote(
  9566. SecondModule, SecondTemplate->getLocation(),
  9567. SecondTemplate->getSourceRange(),
  9568. FunctionTemplateParameterDifferentDefaultArgument)
  9569. << SecondTemplate << (i + 1) << SecondType;
  9570. ParameterMismatch = true;
  9571. break;
  9572. }
  9573. }
  9574. if (FirstTTPD->isParameterPack() !=
  9575. SecondTTPD->isParameterPack()) {
  9576. ODRDiagDeclError(FirstRecord, FirstModule,
  9577. FirstTemplate->getLocation(),
  9578. FirstTemplate->getSourceRange(),
  9579. FunctionTemplatePackParameter)
  9580. << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
  9581. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9582. SecondTemplate->getSourceRange(),
  9583. FunctionTemplatePackParameter)
  9584. << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
  9585. ParameterMismatch = true;
  9586. break;
  9587. }
  9588. }
  9589. if (isa<TemplateTemplateParmDecl>(FirstParam) &&
  9590. isa<TemplateTemplateParmDecl>(SecondParam)) {
  9591. TemplateTemplateParmDecl *FirstTTPD =
  9592. cast<TemplateTemplateParmDecl>(FirstParam);
  9593. TemplateTemplateParmDecl *SecondTTPD =
  9594. cast<TemplateTemplateParmDecl>(SecondParam);
  9595. TemplateParameterList *FirstTPL =
  9596. FirstTTPD->getTemplateParameters();
  9597. TemplateParameterList *SecondTPL =
  9598. SecondTTPD->getTemplateParameters();
  9599. if (ComputeTemplateParameterListODRHash(FirstTPL) !=
  9600. ComputeTemplateParameterListODRHash(SecondTPL)) {
  9601. ODRDiagDeclError(FirstRecord, FirstModule,
  9602. FirstTemplate->getLocation(),
  9603. FirstTemplate->getSourceRange(),
  9604. FunctionTemplateParameterDifferentType)
  9605. << FirstTemplate << (i + 1);
  9606. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9607. SecondTemplate->getSourceRange(),
  9608. FunctionTemplateParameterDifferentType)
  9609. << SecondTemplate << (i + 1);
  9610. ParameterMismatch = true;
  9611. break;
  9612. }
  9613. bool HasFirstDefaultArgument =
  9614. FirstTTPD->hasDefaultArgument() &&
  9615. !FirstTTPD->defaultArgumentWasInherited();
  9616. bool HasSecondDefaultArgument =
  9617. SecondTTPD->hasDefaultArgument() &&
  9618. !SecondTTPD->defaultArgumentWasInherited();
  9619. if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
  9620. ODRDiagDeclError(FirstRecord, FirstModule,
  9621. FirstTemplate->getLocation(),
  9622. FirstTemplate->getSourceRange(),
  9623. FunctionTemplateParameterSingleDefaultArgument)
  9624. << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
  9625. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9626. SecondTemplate->getSourceRange(),
  9627. FunctionTemplateParameterSingleDefaultArgument)
  9628. << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
  9629. ParameterMismatch = true;
  9630. break;
  9631. }
  9632. if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
  9633. TemplateArgument FirstTA =
  9634. FirstTTPD->getDefaultArgument().getArgument();
  9635. TemplateArgument SecondTA =
  9636. SecondTTPD->getDefaultArgument().getArgument();
  9637. if (ComputeTemplateArgumentODRHash(FirstTA) !=
  9638. ComputeTemplateArgumentODRHash(SecondTA)) {
  9639. ODRDiagDeclError(
  9640. FirstRecord, FirstModule, FirstTemplate->getLocation(),
  9641. FirstTemplate->getSourceRange(),
  9642. FunctionTemplateParameterDifferentDefaultArgument)
  9643. << FirstTemplate << (i + 1) << FirstTA;
  9644. ODRDiagDeclNote(
  9645. SecondModule, SecondTemplate->getLocation(),
  9646. SecondTemplate->getSourceRange(),
  9647. FunctionTemplateParameterDifferentDefaultArgument)
  9648. << SecondTemplate << (i + 1) << SecondTA;
  9649. ParameterMismatch = true;
  9650. break;
  9651. }
  9652. }
  9653. if (FirstTTPD->isParameterPack() !=
  9654. SecondTTPD->isParameterPack()) {
  9655. ODRDiagDeclError(FirstRecord, FirstModule,
  9656. FirstTemplate->getLocation(),
  9657. FirstTemplate->getSourceRange(),
  9658. FunctionTemplatePackParameter)
  9659. << FirstTemplate << (i + 1) << FirstTTPD->isParameterPack();
  9660. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9661. SecondTemplate->getSourceRange(),
  9662. FunctionTemplatePackParameter)
  9663. << SecondTemplate << (i + 1) << SecondTTPD->isParameterPack();
  9664. ParameterMismatch = true;
  9665. break;
  9666. }
  9667. }
  9668. if (isa<NonTypeTemplateParmDecl>(FirstParam) &&
  9669. isa<NonTypeTemplateParmDecl>(SecondParam)) {
  9670. NonTypeTemplateParmDecl *FirstNTTPD =
  9671. cast<NonTypeTemplateParmDecl>(FirstParam);
  9672. NonTypeTemplateParmDecl *SecondNTTPD =
  9673. cast<NonTypeTemplateParmDecl>(SecondParam);
  9674. QualType FirstType = FirstNTTPD->getType();
  9675. QualType SecondType = SecondNTTPD->getType();
  9676. if (ComputeQualTypeODRHash(FirstType) !=
  9677. ComputeQualTypeODRHash(SecondType)) {
  9678. ODRDiagDeclError(FirstRecord, FirstModule,
  9679. FirstTemplate->getLocation(),
  9680. FirstTemplate->getSourceRange(),
  9681. FunctionTemplateParameterDifferentType)
  9682. << FirstTemplate << (i + 1);
  9683. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9684. SecondTemplate->getSourceRange(),
  9685. FunctionTemplateParameterDifferentType)
  9686. << SecondTemplate << (i + 1);
  9687. ParameterMismatch = true;
  9688. break;
  9689. }
  9690. bool HasFirstDefaultArgument =
  9691. FirstNTTPD->hasDefaultArgument() &&
  9692. !FirstNTTPD->defaultArgumentWasInherited();
  9693. bool HasSecondDefaultArgument =
  9694. SecondNTTPD->hasDefaultArgument() &&
  9695. !SecondNTTPD->defaultArgumentWasInherited();
  9696. if (HasFirstDefaultArgument != HasSecondDefaultArgument) {
  9697. ODRDiagDeclError(FirstRecord, FirstModule,
  9698. FirstTemplate->getLocation(),
  9699. FirstTemplate->getSourceRange(),
  9700. FunctionTemplateParameterSingleDefaultArgument)
  9701. << FirstTemplate << (i + 1) << HasFirstDefaultArgument;
  9702. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9703. SecondTemplate->getSourceRange(),
  9704. FunctionTemplateParameterSingleDefaultArgument)
  9705. << SecondTemplate << (i + 1) << HasSecondDefaultArgument;
  9706. ParameterMismatch = true;
  9707. break;
  9708. }
  9709. if (HasFirstDefaultArgument && HasSecondDefaultArgument) {
  9710. Expr *FirstDefaultArgument = FirstNTTPD->getDefaultArgument();
  9711. Expr *SecondDefaultArgument = SecondNTTPD->getDefaultArgument();
  9712. if (ComputeODRHash(FirstDefaultArgument) !=
  9713. ComputeODRHash(SecondDefaultArgument)) {
  9714. ODRDiagDeclError(
  9715. FirstRecord, FirstModule, FirstTemplate->getLocation(),
  9716. FirstTemplate->getSourceRange(),
  9717. FunctionTemplateParameterDifferentDefaultArgument)
  9718. << FirstTemplate << (i + 1) << FirstDefaultArgument;
  9719. ODRDiagDeclNote(
  9720. SecondModule, SecondTemplate->getLocation(),
  9721. SecondTemplate->getSourceRange(),
  9722. FunctionTemplateParameterDifferentDefaultArgument)
  9723. << SecondTemplate << (i + 1) << SecondDefaultArgument;
  9724. ParameterMismatch = true;
  9725. break;
  9726. }
  9727. }
  9728. if (FirstNTTPD->isParameterPack() !=
  9729. SecondNTTPD->isParameterPack()) {
  9730. ODRDiagDeclError(FirstRecord, FirstModule,
  9731. FirstTemplate->getLocation(),
  9732. FirstTemplate->getSourceRange(),
  9733. FunctionTemplatePackParameter)
  9734. << FirstTemplate << (i + 1) << FirstNTTPD->isParameterPack();
  9735. ODRDiagDeclNote(SecondModule, SecondTemplate->getLocation(),
  9736. SecondTemplate->getSourceRange(),
  9737. FunctionTemplatePackParameter)
  9738. << SecondTemplate << (i + 1)
  9739. << SecondNTTPD->isParameterPack();
  9740. ParameterMismatch = true;
  9741. break;
  9742. }
  9743. }
  9744. }
  9745. if (ParameterMismatch) {
  9746. Diagnosed = true;
  9747. break;
  9748. }
  9749. break;
  9750. }
  9751. }
  9752. if (Diagnosed)
  9753. continue;
  9754. Diag(FirstDecl->getLocation(),
  9755. diag::err_module_odr_violation_mismatch_decl_unknown)
  9756. << FirstRecord << FirstModule.empty() << FirstModule << FirstDiffType
  9757. << FirstDecl->getSourceRange();
  9758. Diag(SecondDecl->getLocation(),
  9759. diag::note_module_odr_violation_mismatch_decl_unknown)
  9760. << SecondModule << FirstDiffType << SecondDecl->getSourceRange();
  9761. Diagnosed = true;
  9762. }
  9763. if (!Diagnosed) {
  9764. // All definitions are updates to the same declaration. This happens if a
  9765. // module instantiates the declaration of a class template specialization
  9766. // and two or more other modules instantiate its definition.
  9767. //
  9768. // FIXME: Indicate which modules had instantiations of this definition.
  9769. // FIXME: How can this even happen?
  9770. Diag(Merge.first->getLocation(),
  9771. diag::err_module_odr_violation_different_instantiations)
  9772. << Merge.first;
  9773. }
  9774. }
  9775. // Issue ODR failures diagnostics for functions.
  9776. for (auto &Merge : FunctionOdrMergeFailures) {
  9777. enum ODRFunctionDifference {
  9778. ReturnType,
  9779. ParameterName,
  9780. ParameterType,
  9781. ParameterSingleDefaultArgument,
  9782. ParameterDifferentDefaultArgument,
  9783. FunctionBody,
  9784. };
  9785. FunctionDecl *FirstFunction = Merge.first;
  9786. std::string FirstModule = getOwningModuleNameForDiagnostic(FirstFunction);
  9787. bool Diagnosed = false;
  9788. for (auto &SecondFunction : Merge.second) {
  9789. if (FirstFunction == SecondFunction)
  9790. continue;
  9791. std::string SecondModule =
  9792. getOwningModuleNameForDiagnostic(SecondFunction);
  9793. auto ODRDiagError = [FirstFunction, &FirstModule,
  9794. this](SourceLocation Loc, SourceRange Range,
  9795. ODRFunctionDifference DiffType) {
  9796. return Diag(Loc, diag::err_module_odr_violation_function)
  9797. << FirstFunction << FirstModule.empty() << FirstModule << Range
  9798. << DiffType;
  9799. };
  9800. auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
  9801. SourceRange Range,
  9802. ODRFunctionDifference DiffType) {
  9803. return Diag(Loc, diag::note_module_odr_violation_function)
  9804. << SecondModule << Range << DiffType;
  9805. };
  9806. if (ComputeQualTypeODRHash(FirstFunction->getReturnType()) !=
  9807. ComputeQualTypeODRHash(SecondFunction->getReturnType())) {
  9808. ODRDiagError(FirstFunction->getReturnTypeSourceRange().getBegin(),
  9809. FirstFunction->getReturnTypeSourceRange(), ReturnType)
  9810. << FirstFunction->getReturnType();
  9811. ODRDiagNote(SecondFunction->getReturnTypeSourceRange().getBegin(),
  9812. SecondFunction->getReturnTypeSourceRange(), ReturnType)
  9813. << SecondFunction->getReturnType();
  9814. Diagnosed = true;
  9815. break;
  9816. }
  9817. assert(FirstFunction->param_size() == SecondFunction->param_size() &&
  9818. "Merged functions with different number of parameters");
  9819. auto ParamSize = FirstFunction->param_size();
  9820. bool ParameterMismatch = false;
  9821. for (unsigned I = 0; I < ParamSize; ++I) {
  9822. auto *FirstParam = FirstFunction->getParamDecl(I);
  9823. auto *SecondParam = SecondFunction->getParamDecl(I);
  9824. assert(getContext().hasSameType(FirstParam->getType(),
  9825. SecondParam->getType()) &&
  9826. "Merged function has different parameter types.");
  9827. if (FirstParam->getDeclName() != SecondParam->getDeclName()) {
  9828. ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
  9829. ParameterName)
  9830. << I + 1 << FirstParam->getDeclName();
  9831. ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
  9832. ParameterName)
  9833. << I + 1 << SecondParam->getDeclName();
  9834. ParameterMismatch = true;
  9835. break;
  9836. };
  9837. QualType FirstParamType = FirstParam->getType();
  9838. QualType SecondParamType = SecondParam->getType();
  9839. if (FirstParamType != SecondParamType &&
  9840. ComputeQualTypeODRHash(FirstParamType) !=
  9841. ComputeQualTypeODRHash(SecondParamType)) {
  9842. if (const DecayedType *ParamDecayedType =
  9843. FirstParamType->getAs<DecayedType>()) {
  9844. ODRDiagError(FirstParam->getLocation(),
  9845. FirstParam->getSourceRange(), ParameterType)
  9846. << (I + 1) << FirstParamType << true
  9847. << ParamDecayedType->getOriginalType();
  9848. } else {
  9849. ODRDiagError(FirstParam->getLocation(),
  9850. FirstParam->getSourceRange(), ParameterType)
  9851. << (I + 1) << FirstParamType << false;
  9852. }
  9853. if (const DecayedType *ParamDecayedType =
  9854. SecondParamType->getAs<DecayedType>()) {
  9855. ODRDiagNote(SecondParam->getLocation(),
  9856. SecondParam->getSourceRange(), ParameterType)
  9857. << (I + 1) << SecondParamType << true
  9858. << ParamDecayedType->getOriginalType();
  9859. } else {
  9860. ODRDiagNote(SecondParam->getLocation(),
  9861. SecondParam->getSourceRange(), ParameterType)
  9862. << (I + 1) << SecondParamType << false;
  9863. }
  9864. ParameterMismatch = true;
  9865. break;
  9866. }
  9867. const Expr *FirstInit = FirstParam->getInit();
  9868. const Expr *SecondInit = SecondParam->getInit();
  9869. if ((FirstInit == nullptr) != (SecondInit == nullptr)) {
  9870. ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
  9871. ParameterSingleDefaultArgument)
  9872. << (I + 1) << (FirstInit == nullptr)
  9873. << (FirstInit ? FirstInit->getSourceRange() : SourceRange());
  9874. ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
  9875. ParameterSingleDefaultArgument)
  9876. << (I + 1) << (SecondInit == nullptr)
  9877. << (SecondInit ? SecondInit->getSourceRange() : SourceRange());
  9878. ParameterMismatch = true;
  9879. break;
  9880. }
  9881. if (FirstInit && SecondInit &&
  9882. ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
  9883. ODRDiagError(FirstParam->getLocation(), FirstParam->getSourceRange(),
  9884. ParameterDifferentDefaultArgument)
  9885. << (I + 1) << FirstInit->getSourceRange();
  9886. ODRDiagNote(SecondParam->getLocation(), SecondParam->getSourceRange(),
  9887. ParameterDifferentDefaultArgument)
  9888. << (I + 1) << SecondInit->getSourceRange();
  9889. ParameterMismatch = true;
  9890. break;
  9891. }
  9892. assert(ComputeSubDeclODRHash(FirstParam) ==
  9893. ComputeSubDeclODRHash(SecondParam) &&
  9894. "Undiagnosed parameter difference.");
  9895. }
  9896. if (ParameterMismatch) {
  9897. Diagnosed = true;
  9898. break;
  9899. }
  9900. // If no error has been generated before now, assume the problem is in
  9901. // the body and generate a message.
  9902. ODRDiagError(FirstFunction->getLocation(),
  9903. FirstFunction->getSourceRange(), FunctionBody);
  9904. ODRDiagNote(SecondFunction->getLocation(),
  9905. SecondFunction->getSourceRange(), FunctionBody);
  9906. Diagnosed = true;
  9907. break;
  9908. }
  9909. (void)Diagnosed;
  9910. assert(Diagnosed && "Unable to emit ODR diagnostic.");
  9911. }
  9912. // Issue ODR failures diagnostics for enums.
  9913. for (auto &Merge : EnumOdrMergeFailures) {
  9914. enum ODREnumDifference {
  9915. SingleScopedEnum,
  9916. EnumTagKeywordMismatch,
  9917. SingleSpecifiedType,
  9918. DifferentSpecifiedTypes,
  9919. DifferentNumberEnumConstants,
  9920. EnumConstantName,
  9921. EnumConstantSingleInitilizer,
  9922. EnumConstantDifferentInitilizer,
  9923. };
  9924. // If we've already pointed out a specific problem with this enum, don't
  9925. // bother issuing a general "something's different" diagnostic.
  9926. if (!DiagnosedOdrMergeFailures.insert(Merge.first).second)
  9927. continue;
  9928. EnumDecl *FirstEnum = Merge.first;
  9929. std::string FirstModule = getOwningModuleNameForDiagnostic(FirstEnum);
  9930. using DeclHashes =
  9931. llvm::SmallVector<std::pair<EnumConstantDecl *, unsigned>, 4>;
  9932. auto PopulateHashes = [&ComputeSubDeclODRHash, FirstEnum](
  9933. DeclHashes &Hashes, EnumDecl *Enum) {
  9934. for (auto *D : Enum->decls()) {
  9935. // Due to decl merging, the first EnumDecl is the parent of
  9936. // Decls in both records.
  9937. if (!ODRHash::isDeclToBeProcessed(D, FirstEnum))
  9938. continue;
  9939. assert(isa<EnumConstantDecl>(D) && "Unexpected Decl kind");
  9940. Hashes.emplace_back(cast<EnumConstantDecl>(D),
  9941. ComputeSubDeclODRHash(D));
  9942. }
  9943. };
  9944. DeclHashes FirstHashes;
  9945. PopulateHashes(FirstHashes, FirstEnum);
  9946. bool Diagnosed = false;
  9947. for (auto &SecondEnum : Merge.second) {
  9948. if (FirstEnum == SecondEnum)
  9949. continue;
  9950. std::string SecondModule =
  9951. getOwningModuleNameForDiagnostic(SecondEnum);
  9952. auto ODRDiagError = [FirstEnum, &FirstModule,
  9953. this](SourceLocation Loc, SourceRange Range,
  9954. ODREnumDifference DiffType) {
  9955. return Diag(Loc, diag::err_module_odr_violation_enum)
  9956. << FirstEnum << FirstModule.empty() << FirstModule << Range
  9957. << DiffType;
  9958. };
  9959. auto ODRDiagNote = [&SecondModule, this](SourceLocation Loc,
  9960. SourceRange Range,
  9961. ODREnumDifference DiffType) {
  9962. return Diag(Loc, diag::note_module_odr_violation_enum)
  9963. << SecondModule << Range << DiffType;
  9964. };
  9965. if (FirstEnum->isScoped() != SecondEnum->isScoped()) {
  9966. ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
  9967. SingleScopedEnum)
  9968. << FirstEnum->isScoped();
  9969. ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
  9970. SingleScopedEnum)
  9971. << SecondEnum->isScoped();
  9972. Diagnosed = true;
  9973. continue;
  9974. }
  9975. if (FirstEnum->isScoped() && SecondEnum->isScoped()) {
  9976. if (FirstEnum->isScopedUsingClassTag() !=
  9977. SecondEnum->isScopedUsingClassTag()) {
  9978. ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
  9979. EnumTagKeywordMismatch)
  9980. << FirstEnum->isScopedUsingClassTag();
  9981. ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
  9982. EnumTagKeywordMismatch)
  9983. << SecondEnum->isScopedUsingClassTag();
  9984. Diagnosed = true;
  9985. continue;
  9986. }
  9987. }
  9988. QualType FirstUnderlyingType =
  9989. FirstEnum->getIntegerTypeSourceInfo()
  9990. ? FirstEnum->getIntegerTypeSourceInfo()->getType()
  9991. : QualType();
  9992. QualType SecondUnderlyingType =
  9993. SecondEnum->getIntegerTypeSourceInfo()
  9994. ? SecondEnum->getIntegerTypeSourceInfo()->getType()
  9995. : QualType();
  9996. if (FirstUnderlyingType.isNull() != SecondUnderlyingType.isNull()) {
  9997. ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
  9998. SingleSpecifiedType)
  9999. << !FirstUnderlyingType.isNull();
  10000. ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
  10001. SingleSpecifiedType)
  10002. << !SecondUnderlyingType.isNull();
  10003. Diagnosed = true;
  10004. continue;
  10005. }
  10006. if (!FirstUnderlyingType.isNull() && !SecondUnderlyingType.isNull()) {
  10007. if (ComputeQualTypeODRHash(FirstUnderlyingType) !=
  10008. ComputeQualTypeODRHash(SecondUnderlyingType)) {
  10009. ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
  10010. DifferentSpecifiedTypes)
  10011. << FirstUnderlyingType;
  10012. ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
  10013. DifferentSpecifiedTypes)
  10014. << SecondUnderlyingType;
  10015. Diagnosed = true;
  10016. continue;
  10017. }
  10018. }
  10019. DeclHashes SecondHashes;
  10020. PopulateHashes(SecondHashes, SecondEnum);
  10021. if (FirstHashes.size() != SecondHashes.size()) {
  10022. ODRDiagError(FirstEnum->getLocation(), FirstEnum->getSourceRange(),
  10023. DifferentNumberEnumConstants)
  10024. << (int)FirstHashes.size();
  10025. ODRDiagNote(SecondEnum->getLocation(), SecondEnum->getSourceRange(),
  10026. DifferentNumberEnumConstants)
  10027. << (int)SecondHashes.size();
  10028. Diagnosed = true;
  10029. continue;
  10030. }
  10031. for (unsigned I = 0; I < FirstHashes.size(); ++I) {
  10032. if (FirstHashes[I].second == SecondHashes[I].second)
  10033. continue;
  10034. const EnumConstantDecl *FirstEnumConstant = FirstHashes[I].first;
  10035. const EnumConstantDecl *SecondEnumConstant = SecondHashes[I].first;
  10036. if (FirstEnumConstant->getDeclName() !=
  10037. SecondEnumConstant->getDeclName()) {
  10038. ODRDiagError(FirstEnumConstant->getLocation(),
  10039. FirstEnumConstant->getSourceRange(), EnumConstantName)
  10040. << I + 1 << FirstEnumConstant;
  10041. ODRDiagNote(SecondEnumConstant->getLocation(),
  10042. SecondEnumConstant->getSourceRange(), EnumConstantName)
  10043. << I + 1 << SecondEnumConstant;
  10044. Diagnosed = true;
  10045. break;
  10046. }
  10047. const Expr *FirstInit = FirstEnumConstant->getInitExpr();
  10048. const Expr *SecondInit = SecondEnumConstant->getInitExpr();
  10049. if (!FirstInit && !SecondInit)
  10050. continue;
  10051. if (!FirstInit || !SecondInit) {
  10052. ODRDiagError(FirstEnumConstant->getLocation(),
  10053. FirstEnumConstant->getSourceRange(),
  10054. EnumConstantSingleInitilizer)
  10055. << I + 1 << FirstEnumConstant << (FirstInit != nullptr);
  10056. ODRDiagNote(SecondEnumConstant->getLocation(),
  10057. SecondEnumConstant->getSourceRange(),
  10058. EnumConstantSingleInitilizer)
  10059. << I + 1 << SecondEnumConstant << (SecondInit != nullptr);
  10060. Diagnosed = true;
  10061. break;
  10062. }
  10063. if (ComputeODRHash(FirstInit) != ComputeODRHash(SecondInit)) {
  10064. ODRDiagError(FirstEnumConstant->getLocation(),
  10065. FirstEnumConstant->getSourceRange(),
  10066. EnumConstantDifferentInitilizer)
  10067. << I + 1 << FirstEnumConstant;
  10068. ODRDiagNote(SecondEnumConstant->getLocation(),
  10069. SecondEnumConstant->getSourceRange(),
  10070. EnumConstantDifferentInitilizer)
  10071. << I + 1 << SecondEnumConstant;
  10072. Diagnosed = true;
  10073. break;
  10074. }
  10075. }
  10076. }
  10077. (void)Diagnosed;
  10078. assert(Diagnosed && "Unable to emit ODR diagnostic.");
  10079. }
  10080. }
  10081. void ASTReader::StartedDeserializing() {
  10082. if (++NumCurrentElementsDeserializing == 1 && ReadTimer.get())
  10083. ReadTimer->startTimer();
  10084. }
  10085. void ASTReader::FinishedDeserializing() {
  10086. assert(NumCurrentElementsDeserializing &&
  10087. "FinishedDeserializing not paired with StartedDeserializing");
  10088. if (NumCurrentElementsDeserializing == 1) {
  10089. // We decrease NumCurrentElementsDeserializing only after pending actions
  10090. // are finished, to avoid recursively re-calling finishPendingActions().
  10091. finishPendingActions();
  10092. }
  10093. --NumCurrentElementsDeserializing;
  10094. if (NumCurrentElementsDeserializing == 0) {
  10095. // Propagate exception specification and deduced type updates along
  10096. // redeclaration chains.
  10097. //
  10098. // We do this now rather than in finishPendingActions because we want to
  10099. // be able to walk the complete redeclaration chains of the updated decls.
  10100. while (!PendingExceptionSpecUpdates.empty() ||
  10101. !PendingDeducedTypeUpdates.empty()) {
  10102. auto ESUpdates = std::move(PendingExceptionSpecUpdates);
  10103. PendingExceptionSpecUpdates.clear();
  10104. for (auto Update : ESUpdates) {
  10105. ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
  10106. auto *FPT = Update.second->getType()->castAs<FunctionProtoType>();
  10107. auto ESI = FPT->getExtProtoInfo().ExceptionSpec;
  10108. if (auto *Listener = getContext().getASTMutationListener())
  10109. Listener->ResolvedExceptionSpec(cast<FunctionDecl>(Update.second));
  10110. for (auto *Redecl : Update.second->redecls())
  10111. getContext().adjustExceptionSpec(cast<FunctionDecl>(Redecl), ESI);
  10112. }
  10113. auto DTUpdates = std::move(PendingDeducedTypeUpdates);
  10114. PendingDeducedTypeUpdates.clear();
  10115. for (auto Update : DTUpdates) {
  10116. ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
  10117. // FIXME: If the return type is already deduced, check that it matches.
  10118. getContext().adjustDeducedFunctionResultType(Update.first,
  10119. Update.second);
  10120. }
  10121. }
  10122. if (ReadTimer)
  10123. ReadTimer->stopTimer();
  10124. diagnoseOdrViolations();
  10125. // We are not in recursive loading, so it's safe to pass the "interesting"
  10126. // decls to the consumer.
  10127. if (Consumer)
  10128. PassInterestingDeclsToConsumer();
  10129. }
  10130. }
  10131. void ASTReader::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
  10132. if (IdentifierInfo *II = Name.getAsIdentifierInfo()) {
  10133. // Remove any fake results before adding any real ones.
  10134. auto It = PendingFakeLookupResults.find(II);
  10135. if (It != PendingFakeLookupResults.end()) {
  10136. for (auto *ND : It->second)
  10137. SemaObj->IdResolver.RemoveDecl(ND);
  10138. // FIXME: this works around module+PCH performance issue.
  10139. // Rather than erase the result from the map, which is O(n), just clear
  10140. // the vector of NamedDecls.
  10141. It->second.clear();
  10142. }
  10143. }
  10144. if (SemaObj->IdResolver.tryAddTopLevelDecl(D, Name) && SemaObj->TUScope) {
  10145. SemaObj->TUScope->AddDecl(D);
  10146. } else if (SemaObj->TUScope) {
  10147. // Adding the decl to IdResolver may have failed because it was already in
  10148. // (even though it was not added in scope). If it is already in, make sure
  10149. // it gets in the scope as well.
  10150. if (std::find(SemaObj->IdResolver.begin(Name),
  10151. SemaObj->IdResolver.end(), D) != SemaObj->IdResolver.end())
  10152. SemaObj->TUScope->AddDecl(D);
  10153. }
  10154. }
  10155. ASTReader::ASTReader(Preprocessor &PP, InMemoryModuleCache &ModuleCache,
  10156. ASTContext *Context,
  10157. const PCHContainerReader &PCHContainerRdr,
  10158. ArrayRef<std::shared_ptr<ModuleFileExtension>> Extensions,
  10159. StringRef isysroot,
  10160. DisableValidationForModuleKind DisableValidationKind,
  10161. bool AllowASTWithCompilerErrors,
  10162. bool AllowConfigurationMismatch, bool ValidateSystemInputs,
  10163. bool ValidateASTInputFilesContent, bool UseGlobalIndex,
  10164. std::unique_ptr<llvm::Timer> ReadTimer)
  10165. : Listener(bool(DisableValidationKind &DisableValidationForModuleKind::PCH)
  10166. ? cast<ASTReaderListener>(new SimpleASTReaderListener(PP))
  10167. : cast<ASTReaderListener>(new PCHValidator(PP, *this))),
  10168. SourceMgr(PP.getSourceManager()), FileMgr(PP.getFileManager()),
  10169. PCHContainerRdr(PCHContainerRdr), Diags(PP.getDiagnostics()), PP(PP),
  10170. ContextObj(Context), ModuleMgr(PP.getFileManager(), ModuleCache,
  10171. PCHContainerRdr, PP.getHeaderSearchInfo()),
  10172. DummyIdResolver(PP), ReadTimer(std::move(ReadTimer)), isysroot(isysroot),
  10173. DisableValidationKind(DisableValidationKind),
  10174. AllowASTWithCompilerErrors(AllowASTWithCompilerErrors),
  10175. AllowConfigurationMismatch(AllowConfigurationMismatch),
  10176. ValidateSystemInputs(ValidateSystemInputs),
  10177. ValidateASTInputFilesContent(ValidateASTInputFilesContent),
  10178. UseGlobalIndex(UseGlobalIndex), CurrSwitchCaseStmts(&SwitchCaseStmts) {
  10179. SourceMgr.setExternalSLocEntrySource(this);
  10180. for (const auto &Ext : Extensions) {
  10181. auto BlockName = Ext->getExtensionMetadata().BlockName;
  10182. auto Known = ModuleFileExtensions.find(BlockName);
  10183. if (Known != ModuleFileExtensions.end()) {
  10184. Diags.Report(diag::warn_duplicate_module_file_extension)
  10185. << BlockName;
  10186. continue;
  10187. }
  10188. ModuleFileExtensions.insert({BlockName, Ext});
  10189. }
  10190. }
  10191. ASTReader::~ASTReader() {
  10192. if (OwnsDeserializationListener)
  10193. delete DeserializationListener;
  10194. }
  10195. IdentifierResolver &ASTReader::getIdResolver() {
  10196. return SemaObj ? SemaObj->IdResolver : DummyIdResolver;
  10197. }
  10198. Expected<unsigned> ASTRecordReader::readRecord(llvm::BitstreamCursor &Cursor,
  10199. unsigned AbbrevID) {
  10200. Idx = 0;
  10201. Record.clear();
  10202. return Cursor.readRecord(AbbrevID, Record);
  10203. }
  10204. //===----------------------------------------------------------------------===//
  10205. //// OMPClauseReader implementation
  10206. ////===----------------------------------------------------------------------===//
  10207. // This has to be in namespace clang because it's friended by all
  10208. // of the OMP clauses.
  10209. namespace clang {
  10210. class OMPClauseReader : public OMPClauseVisitor<OMPClauseReader> {
  10211. ASTRecordReader &Record;
  10212. ASTContext &Context;
  10213. public:
  10214. OMPClauseReader(ASTRecordReader &Record)
  10215. : Record(Record), Context(Record.getContext()) {}
  10216. #define GEN_CLANG_CLAUSE_CLASS
  10217. #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *C);
  10218. #include "llvm/Frontend/OpenMP/OMP.inc"
  10219. OMPClause *readClause();
  10220. void VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C);
  10221. void VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C);
  10222. };
  10223. } // end namespace clang
  10224. OMPClause *ASTRecordReader::readOMPClause() {
  10225. return OMPClauseReader(*this).readClause();
  10226. }
  10227. OMPClause *OMPClauseReader::readClause() {
  10228. OMPClause *C = nullptr;
  10229. switch (llvm::omp::Clause(Record.readInt())) {
  10230. case llvm::omp::OMPC_if:
  10231. C = new (Context) OMPIfClause();
  10232. break;
  10233. case llvm::omp::OMPC_final:
  10234. C = new (Context) OMPFinalClause();
  10235. break;
  10236. case llvm::omp::OMPC_num_threads:
  10237. C = new (Context) OMPNumThreadsClause();
  10238. break;
  10239. case llvm::omp::OMPC_safelen:
  10240. C = new (Context) OMPSafelenClause();
  10241. break;
  10242. case llvm::omp::OMPC_simdlen:
  10243. C = new (Context) OMPSimdlenClause();
  10244. break;
  10245. case llvm::omp::OMPC_sizes: {
  10246. unsigned NumSizes = Record.readInt();
  10247. C = OMPSizesClause::CreateEmpty(Context, NumSizes);
  10248. break;
  10249. }
  10250. case llvm::omp::OMPC_full:
  10251. C = OMPFullClause::CreateEmpty(Context);
  10252. break;
  10253. case llvm::omp::OMPC_partial:
  10254. C = OMPPartialClause::CreateEmpty(Context);
  10255. break;
  10256. case llvm::omp::OMPC_allocator:
  10257. C = new (Context) OMPAllocatorClause();
  10258. break;
  10259. case llvm::omp::OMPC_collapse:
  10260. C = new (Context) OMPCollapseClause();
  10261. break;
  10262. case llvm::omp::OMPC_default:
  10263. C = new (Context) OMPDefaultClause();
  10264. break;
  10265. case llvm::omp::OMPC_proc_bind:
  10266. C = new (Context) OMPProcBindClause();
  10267. break;
  10268. case llvm::omp::OMPC_schedule:
  10269. C = new (Context) OMPScheduleClause();
  10270. break;
  10271. case llvm::omp::OMPC_ordered:
  10272. C = OMPOrderedClause::CreateEmpty(Context, Record.readInt());
  10273. break;
  10274. case llvm::omp::OMPC_nowait:
  10275. C = new (Context) OMPNowaitClause();
  10276. break;
  10277. case llvm::omp::OMPC_untied:
  10278. C = new (Context) OMPUntiedClause();
  10279. break;
  10280. case llvm::omp::OMPC_mergeable:
  10281. C = new (Context) OMPMergeableClause();
  10282. break;
  10283. case llvm::omp::OMPC_read:
  10284. C = new (Context) OMPReadClause();
  10285. break;
  10286. case llvm::omp::OMPC_write:
  10287. C = new (Context) OMPWriteClause();
  10288. break;
  10289. case llvm::omp::OMPC_update:
  10290. C = OMPUpdateClause::CreateEmpty(Context, Record.readInt());
  10291. break;
  10292. case llvm::omp::OMPC_capture:
  10293. C = new (Context) OMPCaptureClause();
  10294. break;
  10295. case llvm::omp::OMPC_compare:
  10296. C = new (Context) OMPCompareClause();
  10297. break;
  10298. case llvm::omp::OMPC_seq_cst:
  10299. C = new (Context) OMPSeqCstClause();
  10300. break;
  10301. case llvm::omp::OMPC_acq_rel:
  10302. C = new (Context) OMPAcqRelClause();
  10303. break;
  10304. case llvm::omp::OMPC_acquire:
  10305. C = new (Context) OMPAcquireClause();
  10306. break;
  10307. case llvm::omp::OMPC_release:
  10308. C = new (Context) OMPReleaseClause();
  10309. break;
  10310. case llvm::omp::OMPC_relaxed:
  10311. C = new (Context) OMPRelaxedClause();
  10312. break;
  10313. case llvm::omp::OMPC_threads:
  10314. C = new (Context) OMPThreadsClause();
  10315. break;
  10316. case llvm::omp::OMPC_simd:
  10317. C = new (Context) OMPSIMDClause();
  10318. break;
  10319. case llvm::omp::OMPC_nogroup:
  10320. C = new (Context) OMPNogroupClause();
  10321. break;
  10322. case llvm::omp::OMPC_unified_address:
  10323. C = new (Context) OMPUnifiedAddressClause();
  10324. break;
  10325. case llvm::omp::OMPC_unified_shared_memory:
  10326. C = new (Context) OMPUnifiedSharedMemoryClause();
  10327. break;
  10328. case llvm::omp::OMPC_reverse_offload:
  10329. C = new (Context) OMPReverseOffloadClause();
  10330. break;
  10331. case llvm::omp::OMPC_dynamic_allocators:
  10332. C = new (Context) OMPDynamicAllocatorsClause();
  10333. break;
  10334. case llvm::omp::OMPC_atomic_default_mem_order:
  10335. C = new (Context) OMPAtomicDefaultMemOrderClause();
  10336. break;
  10337. case llvm::omp::OMPC_private:
  10338. C = OMPPrivateClause::CreateEmpty(Context, Record.readInt());
  10339. break;
  10340. case llvm::omp::OMPC_firstprivate:
  10341. C = OMPFirstprivateClause::CreateEmpty(Context, Record.readInt());
  10342. break;
  10343. case llvm::omp::OMPC_lastprivate:
  10344. C = OMPLastprivateClause::CreateEmpty(Context, Record.readInt());
  10345. break;
  10346. case llvm::omp::OMPC_shared:
  10347. C = OMPSharedClause::CreateEmpty(Context, Record.readInt());
  10348. break;
  10349. case llvm::omp::OMPC_reduction: {
  10350. unsigned N = Record.readInt();
  10351. auto Modifier = Record.readEnum<OpenMPReductionClauseModifier>();
  10352. C = OMPReductionClause::CreateEmpty(Context, N, Modifier);
  10353. break;
  10354. }
  10355. case llvm::omp::OMPC_task_reduction:
  10356. C = OMPTaskReductionClause::CreateEmpty(Context, Record.readInt());
  10357. break;
  10358. case llvm::omp::OMPC_in_reduction:
  10359. C = OMPInReductionClause::CreateEmpty(Context, Record.readInt());
  10360. break;
  10361. case llvm::omp::OMPC_linear:
  10362. C = OMPLinearClause::CreateEmpty(Context, Record.readInt());
  10363. break;
  10364. case llvm::omp::OMPC_aligned:
  10365. C = OMPAlignedClause::CreateEmpty(Context, Record.readInt());
  10366. break;
  10367. case llvm::omp::OMPC_copyin:
  10368. C = OMPCopyinClause::CreateEmpty(Context, Record.readInt());
  10369. break;
  10370. case llvm::omp::OMPC_copyprivate:
  10371. C = OMPCopyprivateClause::CreateEmpty(Context, Record.readInt());
  10372. break;
  10373. case llvm::omp::OMPC_flush:
  10374. C = OMPFlushClause::CreateEmpty(Context, Record.readInt());
  10375. break;
  10376. case llvm::omp::OMPC_depobj:
  10377. C = OMPDepobjClause::CreateEmpty(Context);
  10378. break;
  10379. case llvm::omp::OMPC_depend: {
  10380. unsigned NumVars = Record.readInt();
  10381. unsigned NumLoops = Record.readInt();
  10382. C = OMPDependClause::CreateEmpty(Context, NumVars, NumLoops);
  10383. break;
  10384. }
  10385. case llvm::omp::OMPC_device:
  10386. C = new (Context) OMPDeviceClause();
  10387. break;
  10388. case llvm::omp::OMPC_map: {
  10389. OMPMappableExprListSizeTy Sizes;
  10390. Sizes.NumVars = Record.readInt();
  10391. Sizes.NumUniqueDeclarations = Record.readInt();
  10392. Sizes.NumComponentLists = Record.readInt();
  10393. Sizes.NumComponents = Record.readInt();
  10394. C = OMPMapClause::CreateEmpty(Context, Sizes);
  10395. break;
  10396. }
  10397. case llvm::omp::OMPC_num_teams:
  10398. C = new (Context) OMPNumTeamsClause();
  10399. break;
  10400. case llvm::omp::OMPC_thread_limit:
  10401. C = new (Context) OMPThreadLimitClause();
  10402. break;
  10403. case llvm::omp::OMPC_priority:
  10404. C = new (Context) OMPPriorityClause();
  10405. break;
  10406. case llvm::omp::OMPC_grainsize:
  10407. C = new (Context) OMPGrainsizeClause();
  10408. break;
  10409. case llvm::omp::OMPC_num_tasks:
  10410. C = new (Context) OMPNumTasksClause();
  10411. break;
  10412. case llvm::omp::OMPC_hint:
  10413. C = new (Context) OMPHintClause();
  10414. break;
  10415. case llvm::omp::OMPC_dist_schedule:
  10416. C = new (Context) OMPDistScheduleClause();
  10417. break;
  10418. case llvm::omp::OMPC_defaultmap:
  10419. C = new (Context) OMPDefaultmapClause();
  10420. break;
  10421. case llvm::omp::OMPC_to: {
  10422. OMPMappableExprListSizeTy Sizes;
  10423. Sizes.NumVars = Record.readInt();
  10424. Sizes.NumUniqueDeclarations = Record.readInt();
  10425. Sizes.NumComponentLists = Record.readInt();
  10426. Sizes.NumComponents = Record.readInt();
  10427. C = OMPToClause::CreateEmpty(Context, Sizes);
  10428. break;
  10429. }
  10430. case llvm::omp::OMPC_from: {
  10431. OMPMappableExprListSizeTy Sizes;
  10432. Sizes.NumVars = Record.readInt();
  10433. Sizes.NumUniqueDeclarations = Record.readInt();
  10434. Sizes.NumComponentLists = Record.readInt();
  10435. Sizes.NumComponents = Record.readInt();
  10436. C = OMPFromClause::CreateEmpty(Context, Sizes);
  10437. break;
  10438. }
  10439. case llvm::omp::OMPC_use_device_ptr: {
  10440. OMPMappableExprListSizeTy Sizes;
  10441. Sizes.NumVars = Record.readInt();
  10442. Sizes.NumUniqueDeclarations = Record.readInt();
  10443. Sizes.NumComponentLists = Record.readInt();
  10444. Sizes.NumComponents = Record.readInt();
  10445. C = OMPUseDevicePtrClause::CreateEmpty(Context, Sizes);
  10446. break;
  10447. }
  10448. case llvm::omp::OMPC_use_device_addr: {
  10449. OMPMappableExprListSizeTy Sizes;
  10450. Sizes.NumVars = Record.readInt();
  10451. Sizes.NumUniqueDeclarations = Record.readInt();
  10452. Sizes.NumComponentLists = Record.readInt();
  10453. Sizes.NumComponents = Record.readInt();
  10454. C = OMPUseDeviceAddrClause::CreateEmpty(Context, Sizes);
  10455. break;
  10456. }
  10457. case llvm::omp::OMPC_is_device_ptr: {
  10458. OMPMappableExprListSizeTy Sizes;
  10459. Sizes.NumVars = Record.readInt();
  10460. Sizes.NumUniqueDeclarations = Record.readInt();
  10461. Sizes.NumComponentLists = Record.readInt();
  10462. Sizes.NumComponents = Record.readInt();
  10463. C = OMPIsDevicePtrClause::CreateEmpty(Context, Sizes);
  10464. break;
  10465. }
  10466. case llvm::omp::OMPC_allocate:
  10467. C = OMPAllocateClause::CreateEmpty(Context, Record.readInt());
  10468. break;
  10469. case llvm::omp::OMPC_nontemporal:
  10470. C = OMPNontemporalClause::CreateEmpty(Context, Record.readInt());
  10471. break;
  10472. case llvm::omp::OMPC_inclusive:
  10473. C = OMPInclusiveClause::CreateEmpty(Context, Record.readInt());
  10474. break;
  10475. case llvm::omp::OMPC_exclusive:
  10476. C = OMPExclusiveClause::CreateEmpty(Context, Record.readInt());
  10477. break;
  10478. case llvm::omp::OMPC_order:
  10479. C = new (Context) OMPOrderClause();
  10480. break;
  10481. case llvm::omp::OMPC_init:
  10482. C = OMPInitClause::CreateEmpty(Context, Record.readInt());
  10483. break;
  10484. case llvm::omp::OMPC_use:
  10485. C = new (Context) OMPUseClause();
  10486. break;
  10487. case llvm::omp::OMPC_destroy:
  10488. C = new (Context) OMPDestroyClause();
  10489. break;
  10490. case llvm::omp::OMPC_novariants:
  10491. C = new (Context) OMPNovariantsClause();
  10492. break;
  10493. case llvm::omp::OMPC_nocontext:
  10494. C = new (Context) OMPNocontextClause();
  10495. break;
  10496. case llvm::omp::OMPC_detach:
  10497. C = new (Context) OMPDetachClause();
  10498. break;
  10499. case llvm::omp::OMPC_uses_allocators:
  10500. C = OMPUsesAllocatorsClause::CreateEmpty(Context, Record.readInt());
  10501. break;
  10502. case llvm::omp::OMPC_affinity:
  10503. C = OMPAffinityClause::CreateEmpty(Context, Record.readInt());
  10504. break;
  10505. case llvm::omp::OMPC_filter:
  10506. C = new (Context) OMPFilterClause();
  10507. break;
  10508. case llvm::omp::OMPC_bind:
  10509. C = OMPBindClause::CreateEmpty(Context);
  10510. break;
  10511. case llvm::omp::OMPC_align:
  10512. C = new (Context) OMPAlignClause();
  10513. break;
  10514. #define OMP_CLAUSE_NO_CLASS(Enum, Str) \
  10515. case llvm::omp::Enum: \
  10516. break;
  10517. #include "llvm/Frontend/OpenMP/OMPKinds.def"
  10518. default:
  10519. break;
  10520. }
  10521. assert(C && "Unknown OMPClause type");
  10522. Visit(C);
  10523. C->setLocStart(Record.readSourceLocation());
  10524. C->setLocEnd(Record.readSourceLocation());
  10525. return C;
  10526. }
  10527. void OMPClauseReader::VisitOMPClauseWithPreInit(OMPClauseWithPreInit *C) {
  10528. C->setPreInitStmt(Record.readSubStmt(),
  10529. static_cast<OpenMPDirectiveKind>(Record.readInt()));
  10530. }
  10531. void OMPClauseReader::VisitOMPClauseWithPostUpdate(OMPClauseWithPostUpdate *C) {
  10532. VisitOMPClauseWithPreInit(C);
  10533. C->setPostUpdateExpr(Record.readSubExpr());
  10534. }
  10535. void OMPClauseReader::VisitOMPIfClause(OMPIfClause *C) {
  10536. VisitOMPClauseWithPreInit(C);
  10537. C->setNameModifier(static_cast<OpenMPDirectiveKind>(Record.readInt()));
  10538. C->setNameModifierLoc(Record.readSourceLocation());
  10539. C->setColonLoc(Record.readSourceLocation());
  10540. C->setCondition(Record.readSubExpr());
  10541. C->setLParenLoc(Record.readSourceLocation());
  10542. }
  10543. void OMPClauseReader::VisitOMPFinalClause(OMPFinalClause *C) {
  10544. VisitOMPClauseWithPreInit(C);
  10545. C->setCondition(Record.readSubExpr());
  10546. C->setLParenLoc(Record.readSourceLocation());
  10547. }
  10548. void OMPClauseReader::VisitOMPNumThreadsClause(OMPNumThreadsClause *C) {
  10549. VisitOMPClauseWithPreInit(C);
  10550. C->setNumThreads(Record.readSubExpr());
  10551. C->setLParenLoc(Record.readSourceLocation());
  10552. }
  10553. void OMPClauseReader::VisitOMPSafelenClause(OMPSafelenClause *C) {
  10554. C->setSafelen(Record.readSubExpr());
  10555. C->setLParenLoc(Record.readSourceLocation());
  10556. }
  10557. void OMPClauseReader::VisitOMPSimdlenClause(OMPSimdlenClause *C) {
  10558. C->setSimdlen(Record.readSubExpr());
  10559. C->setLParenLoc(Record.readSourceLocation());
  10560. }
  10561. void OMPClauseReader::VisitOMPSizesClause(OMPSizesClause *C) {
  10562. for (Expr *&E : C->getSizesRefs())
  10563. E = Record.readSubExpr();
  10564. C->setLParenLoc(Record.readSourceLocation());
  10565. }
  10566. void OMPClauseReader::VisitOMPFullClause(OMPFullClause *C) {}
  10567. void OMPClauseReader::VisitOMPPartialClause(OMPPartialClause *C) {
  10568. C->setFactor(Record.readSubExpr());
  10569. C->setLParenLoc(Record.readSourceLocation());
  10570. }
  10571. void OMPClauseReader::VisitOMPAllocatorClause(OMPAllocatorClause *C) {
  10572. C->setAllocator(Record.readExpr());
  10573. C->setLParenLoc(Record.readSourceLocation());
  10574. }
  10575. void OMPClauseReader::VisitOMPCollapseClause(OMPCollapseClause *C) {
  10576. C->setNumForLoops(Record.readSubExpr());
  10577. C->setLParenLoc(Record.readSourceLocation());
  10578. }
  10579. void OMPClauseReader::VisitOMPDefaultClause(OMPDefaultClause *C) {
  10580. C->setDefaultKind(static_cast<llvm::omp::DefaultKind>(Record.readInt()));
  10581. C->setLParenLoc(Record.readSourceLocation());
  10582. C->setDefaultKindKwLoc(Record.readSourceLocation());
  10583. }
  10584. void OMPClauseReader::VisitOMPProcBindClause(OMPProcBindClause *C) {
  10585. C->setProcBindKind(static_cast<llvm::omp::ProcBindKind>(Record.readInt()));
  10586. C->setLParenLoc(Record.readSourceLocation());
  10587. C->setProcBindKindKwLoc(Record.readSourceLocation());
  10588. }
  10589. void OMPClauseReader::VisitOMPScheduleClause(OMPScheduleClause *C) {
  10590. VisitOMPClauseWithPreInit(C);
  10591. C->setScheduleKind(
  10592. static_cast<OpenMPScheduleClauseKind>(Record.readInt()));
  10593. C->setFirstScheduleModifier(
  10594. static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
  10595. C->setSecondScheduleModifier(
  10596. static_cast<OpenMPScheduleClauseModifier>(Record.readInt()));
  10597. C->setChunkSize(Record.readSubExpr());
  10598. C->setLParenLoc(Record.readSourceLocation());
  10599. C->setFirstScheduleModifierLoc(Record.readSourceLocation());
  10600. C->setSecondScheduleModifierLoc(Record.readSourceLocation());
  10601. C->setScheduleKindLoc(Record.readSourceLocation());
  10602. C->setCommaLoc(Record.readSourceLocation());
  10603. }
  10604. void OMPClauseReader::VisitOMPOrderedClause(OMPOrderedClause *C) {
  10605. C->setNumForLoops(Record.readSubExpr());
  10606. for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
  10607. C->setLoopNumIterations(I, Record.readSubExpr());
  10608. for (unsigned I = 0, E = C->NumberOfLoops; I < E; ++I)
  10609. C->setLoopCounter(I, Record.readSubExpr());
  10610. C->setLParenLoc(Record.readSourceLocation());
  10611. }
  10612. void OMPClauseReader::VisitOMPDetachClause(OMPDetachClause *C) {
  10613. C->setEventHandler(Record.readSubExpr());
  10614. C->setLParenLoc(Record.readSourceLocation());
  10615. }
  10616. void OMPClauseReader::VisitOMPNowaitClause(OMPNowaitClause *) {}
  10617. void OMPClauseReader::VisitOMPUntiedClause(OMPUntiedClause *) {}
  10618. void OMPClauseReader::VisitOMPMergeableClause(OMPMergeableClause *) {}
  10619. void OMPClauseReader::VisitOMPReadClause(OMPReadClause *) {}
  10620. void OMPClauseReader::VisitOMPWriteClause(OMPWriteClause *) {}
  10621. void OMPClauseReader::VisitOMPUpdateClause(OMPUpdateClause *C) {
  10622. if (C->isExtended()) {
  10623. C->setLParenLoc(Record.readSourceLocation());
  10624. C->setArgumentLoc(Record.readSourceLocation());
  10625. C->setDependencyKind(Record.readEnum<OpenMPDependClauseKind>());
  10626. }
  10627. }
  10628. void OMPClauseReader::VisitOMPCaptureClause(OMPCaptureClause *) {}
  10629. void OMPClauseReader::VisitOMPCompareClause(OMPCompareClause *) {}
  10630. void OMPClauseReader::VisitOMPSeqCstClause(OMPSeqCstClause *) {}
  10631. void OMPClauseReader::VisitOMPAcqRelClause(OMPAcqRelClause *) {}
  10632. void OMPClauseReader::VisitOMPAcquireClause(OMPAcquireClause *) {}
  10633. void OMPClauseReader::VisitOMPReleaseClause(OMPReleaseClause *) {}
  10634. void OMPClauseReader::VisitOMPRelaxedClause(OMPRelaxedClause *) {}
  10635. void OMPClauseReader::VisitOMPThreadsClause(OMPThreadsClause *) {}
  10636. void OMPClauseReader::VisitOMPSIMDClause(OMPSIMDClause *) {}
  10637. void OMPClauseReader::VisitOMPNogroupClause(OMPNogroupClause *) {}
  10638. void OMPClauseReader::VisitOMPInitClause(OMPInitClause *C) {
  10639. unsigned NumVars = C->varlist_size();
  10640. SmallVector<Expr *, 16> Vars;
  10641. Vars.reserve(NumVars);
  10642. for (unsigned I = 0; I != NumVars; ++I)
  10643. Vars.push_back(Record.readSubExpr());
  10644. C->setVarRefs(Vars);
  10645. C->setIsTarget(Record.readBool());
  10646. C->setIsTargetSync(Record.readBool());
  10647. C->setLParenLoc(Record.readSourceLocation());
  10648. C->setVarLoc(Record.readSourceLocation());
  10649. }
  10650. void OMPClauseReader::VisitOMPUseClause(OMPUseClause *C) {
  10651. C->setInteropVar(Record.readSubExpr());
  10652. C->setLParenLoc(Record.readSourceLocation());
  10653. C->setVarLoc(Record.readSourceLocation());
  10654. }
  10655. void OMPClauseReader::VisitOMPDestroyClause(OMPDestroyClause *C) {
  10656. C->setInteropVar(Record.readSubExpr());
  10657. C->setLParenLoc(Record.readSourceLocation());
  10658. C->setVarLoc(Record.readSourceLocation());
  10659. }
  10660. void OMPClauseReader::VisitOMPNovariantsClause(OMPNovariantsClause *C) {
  10661. VisitOMPClauseWithPreInit(C);
  10662. C->setCondition(Record.readSubExpr());
  10663. C->setLParenLoc(Record.readSourceLocation());
  10664. }
  10665. void OMPClauseReader::VisitOMPNocontextClause(OMPNocontextClause *C) {
  10666. VisitOMPClauseWithPreInit(C);
  10667. C->setCondition(Record.readSubExpr());
  10668. C->setLParenLoc(Record.readSourceLocation());
  10669. }
  10670. void OMPClauseReader::VisitOMPUnifiedAddressClause(OMPUnifiedAddressClause *) {}
  10671. void OMPClauseReader::VisitOMPUnifiedSharedMemoryClause(
  10672. OMPUnifiedSharedMemoryClause *) {}
  10673. void OMPClauseReader::VisitOMPReverseOffloadClause(OMPReverseOffloadClause *) {}
  10674. void
  10675. OMPClauseReader::VisitOMPDynamicAllocatorsClause(OMPDynamicAllocatorsClause *) {
  10676. }
  10677. void OMPClauseReader::VisitOMPAtomicDefaultMemOrderClause(
  10678. OMPAtomicDefaultMemOrderClause *C) {
  10679. C->setAtomicDefaultMemOrderKind(
  10680. static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Record.readInt()));
  10681. C->setLParenLoc(Record.readSourceLocation());
  10682. C->setAtomicDefaultMemOrderKindKwLoc(Record.readSourceLocation());
  10683. }
  10684. void OMPClauseReader::VisitOMPPrivateClause(OMPPrivateClause *C) {
  10685. C->setLParenLoc(Record.readSourceLocation());
  10686. unsigned NumVars = C->varlist_size();
  10687. SmallVector<Expr *, 16> Vars;
  10688. Vars.reserve(NumVars);
  10689. for (unsigned i = 0; i != NumVars; ++i)
  10690. Vars.push_back(Record.readSubExpr());
  10691. C->setVarRefs(Vars);
  10692. Vars.clear();
  10693. for (unsigned i = 0; i != NumVars; ++i)
  10694. Vars.push_back(Record.readSubExpr());
  10695. C->setPrivateCopies(Vars);
  10696. }
  10697. void OMPClauseReader::VisitOMPFirstprivateClause(OMPFirstprivateClause *C) {
  10698. VisitOMPClauseWithPreInit(C);
  10699. C->setLParenLoc(Record.readSourceLocation());
  10700. unsigned NumVars = C->varlist_size();
  10701. SmallVector<Expr *, 16> Vars;
  10702. Vars.reserve(NumVars);
  10703. for (unsigned i = 0; i != NumVars; ++i)
  10704. Vars.push_back(Record.readSubExpr());
  10705. C->setVarRefs(Vars);
  10706. Vars.clear();
  10707. for (unsigned i = 0; i != NumVars; ++i)
  10708. Vars.push_back(Record.readSubExpr());
  10709. C->setPrivateCopies(Vars);
  10710. Vars.clear();
  10711. for (unsigned i = 0; i != NumVars; ++i)
  10712. Vars.push_back(Record.readSubExpr());
  10713. C->setInits(Vars);
  10714. }
  10715. void OMPClauseReader::VisitOMPLastprivateClause(OMPLastprivateClause *C) {
  10716. VisitOMPClauseWithPostUpdate(C);
  10717. C->setLParenLoc(Record.readSourceLocation());
  10718. C->setKind(Record.readEnum<OpenMPLastprivateModifier>());
  10719. C->setKindLoc(Record.readSourceLocation());
  10720. C->setColonLoc(Record.readSourceLocation());
  10721. unsigned NumVars = C->varlist_size();
  10722. SmallVector<Expr *, 16> Vars;
  10723. Vars.reserve(NumVars);
  10724. for (unsigned i = 0; i != NumVars; ++i)
  10725. Vars.push_back(Record.readSubExpr());
  10726. C->setVarRefs(Vars);
  10727. Vars.clear();
  10728. for (unsigned i = 0; i != NumVars; ++i)
  10729. Vars.push_back(Record.readSubExpr());
  10730. C->setPrivateCopies(Vars);
  10731. Vars.clear();
  10732. for (unsigned i = 0; i != NumVars; ++i)
  10733. Vars.push_back(Record.readSubExpr());
  10734. C->setSourceExprs(Vars);
  10735. Vars.clear();
  10736. for (unsigned i = 0; i != NumVars; ++i)
  10737. Vars.push_back(Record.readSubExpr());
  10738. C->setDestinationExprs(Vars);
  10739. Vars.clear();
  10740. for (unsigned i = 0; i != NumVars; ++i)
  10741. Vars.push_back(Record.readSubExpr());
  10742. C->setAssignmentOps(Vars);
  10743. }
  10744. void OMPClauseReader::VisitOMPSharedClause(OMPSharedClause *C) {
  10745. C->setLParenLoc(Record.readSourceLocation());
  10746. unsigned NumVars = C->varlist_size();
  10747. SmallVector<Expr *, 16> Vars;
  10748. Vars.reserve(NumVars);
  10749. for (unsigned i = 0; i != NumVars; ++i)
  10750. Vars.push_back(Record.readSubExpr());
  10751. C->setVarRefs(Vars);
  10752. }
  10753. void OMPClauseReader::VisitOMPReductionClause(OMPReductionClause *C) {
  10754. VisitOMPClauseWithPostUpdate(C);
  10755. C->setLParenLoc(Record.readSourceLocation());
  10756. C->setModifierLoc(Record.readSourceLocation());
  10757. C->setColonLoc(Record.readSourceLocation());
  10758. NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
  10759. DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
  10760. C->setQualifierLoc(NNSL);
  10761. C->setNameInfo(DNI);
  10762. unsigned NumVars = C->varlist_size();
  10763. SmallVector<Expr *, 16> Vars;
  10764. Vars.reserve(NumVars);
  10765. for (unsigned i = 0; i != NumVars; ++i)
  10766. Vars.push_back(Record.readSubExpr());
  10767. C->setVarRefs(Vars);
  10768. Vars.clear();
  10769. for (unsigned i = 0; i != NumVars; ++i)
  10770. Vars.push_back(Record.readSubExpr());
  10771. C->setPrivates(Vars);
  10772. Vars.clear();
  10773. for (unsigned i = 0; i != NumVars; ++i)
  10774. Vars.push_back(Record.readSubExpr());
  10775. C->setLHSExprs(Vars);
  10776. Vars.clear();
  10777. for (unsigned i = 0; i != NumVars; ++i)
  10778. Vars.push_back(Record.readSubExpr());
  10779. C->setRHSExprs(Vars);
  10780. Vars.clear();
  10781. for (unsigned i = 0; i != NumVars; ++i)
  10782. Vars.push_back(Record.readSubExpr());
  10783. C->setReductionOps(Vars);
  10784. if (C->getModifier() == OMPC_REDUCTION_inscan) {
  10785. Vars.clear();
  10786. for (unsigned i = 0; i != NumVars; ++i)
  10787. Vars.push_back(Record.readSubExpr());
  10788. C->setInscanCopyOps(Vars);
  10789. Vars.clear();
  10790. for (unsigned i = 0; i != NumVars; ++i)
  10791. Vars.push_back(Record.readSubExpr());
  10792. C->setInscanCopyArrayTemps(Vars);
  10793. Vars.clear();
  10794. for (unsigned i = 0; i != NumVars; ++i)
  10795. Vars.push_back(Record.readSubExpr());
  10796. C->setInscanCopyArrayElems(Vars);
  10797. }
  10798. }
  10799. void OMPClauseReader::VisitOMPTaskReductionClause(OMPTaskReductionClause *C) {
  10800. VisitOMPClauseWithPostUpdate(C);
  10801. C->setLParenLoc(Record.readSourceLocation());
  10802. C->setColonLoc(Record.readSourceLocation());
  10803. NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
  10804. DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
  10805. C->setQualifierLoc(NNSL);
  10806. C->setNameInfo(DNI);
  10807. unsigned NumVars = C->varlist_size();
  10808. SmallVector<Expr *, 16> Vars;
  10809. Vars.reserve(NumVars);
  10810. for (unsigned I = 0; I != NumVars; ++I)
  10811. Vars.push_back(Record.readSubExpr());
  10812. C->setVarRefs(Vars);
  10813. Vars.clear();
  10814. for (unsigned I = 0; I != NumVars; ++I)
  10815. Vars.push_back(Record.readSubExpr());
  10816. C->setPrivates(Vars);
  10817. Vars.clear();
  10818. for (unsigned I = 0; I != NumVars; ++I)
  10819. Vars.push_back(Record.readSubExpr());
  10820. C->setLHSExprs(Vars);
  10821. Vars.clear();
  10822. for (unsigned I = 0; I != NumVars; ++I)
  10823. Vars.push_back(Record.readSubExpr());
  10824. C->setRHSExprs(Vars);
  10825. Vars.clear();
  10826. for (unsigned I = 0; I != NumVars; ++I)
  10827. Vars.push_back(Record.readSubExpr());
  10828. C->setReductionOps(Vars);
  10829. }
  10830. void OMPClauseReader::VisitOMPInReductionClause(OMPInReductionClause *C) {
  10831. VisitOMPClauseWithPostUpdate(C);
  10832. C->setLParenLoc(Record.readSourceLocation());
  10833. C->setColonLoc(Record.readSourceLocation());
  10834. NestedNameSpecifierLoc NNSL = Record.readNestedNameSpecifierLoc();
  10835. DeclarationNameInfo DNI = Record.readDeclarationNameInfo();
  10836. C->setQualifierLoc(NNSL);
  10837. C->setNameInfo(DNI);
  10838. unsigned NumVars = C->varlist_size();
  10839. SmallVector<Expr *, 16> Vars;
  10840. Vars.reserve(NumVars);
  10841. for (unsigned I = 0; I != NumVars; ++I)
  10842. Vars.push_back(Record.readSubExpr());
  10843. C->setVarRefs(Vars);
  10844. Vars.clear();
  10845. for (unsigned I = 0; I != NumVars; ++I)
  10846. Vars.push_back(Record.readSubExpr());
  10847. C->setPrivates(Vars);
  10848. Vars.clear();
  10849. for (unsigned I = 0; I != NumVars; ++I)
  10850. Vars.push_back(Record.readSubExpr());
  10851. C->setLHSExprs(Vars);
  10852. Vars.clear();
  10853. for (unsigned I = 0; I != NumVars; ++I)
  10854. Vars.push_back(Record.readSubExpr());
  10855. C->setRHSExprs(Vars);
  10856. Vars.clear();
  10857. for (unsigned I = 0; I != NumVars; ++I)
  10858. Vars.push_back(Record.readSubExpr());
  10859. C->setReductionOps(Vars);
  10860. Vars.clear();
  10861. for (unsigned I = 0; I != NumVars; ++I)
  10862. Vars.push_back(Record.readSubExpr());
  10863. C->setTaskgroupDescriptors(Vars);
  10864. }
  10865. void OMPClauseReader::VisitOMPLinearClause(OMPLinearClause *C) {
  10866. VisitOMPClauseWithPostUpdate(C);
  10867. C->setLParenLoc(Record.readSourceLocation());
  10868. C->setColonLoc(Record.readSourceLocation());
  10869. C->setModifier(static_cast<OpenMPLinearClauseKind>(Record.readInt()));
  10870. C->setModifierLoc(Record.readSourceLocation());
  10871. unsigned NumVars = C->varlist_size();
  10872. SmallVector<Expr *, 16> Vars;
  10873. Vars.reserve(NumVars);
  10874. for (unsigned i = 0; i != NumVars; ++i)
  10875. Vars.push_back(Record.readSubExpr());
  10876. C->setVarRefs(Vars);
  10877. Vars.clear();
  10878. for (unsigned i = 0; i != NumVars; ++i)
  10879. Vars.push_back(Record.readSubExpr());
  10880. C->setPrivates(Vars);
  10881. Vars.clear();
  10882. for (unsigned i = 0; i != NumVars; ++i)
  10883. Vars.push_back(Record.readSubExpr());
  10884. C->setInits(Vars);
  10885. Vars.clear();
  10886. for (unsigned i = 0; i != NumVars; ++i)
  10887. Vars.push_back(Record.readSubExpr());
  10888. C->setUpdates(Vars);
  10889. Vars.clear();
  10890. for (unsigned i = 0; i != NumVars; ++i)
  10891. Vars.push_back(Record.readSubExpr());
  10892. C->setFinals(Vars);
  10893. C->setStep(Record.readSubExpr());
  10894. C->setCalcStep(Record.readSubExpr());
  10895. Vars.clear();
  10896. for (unsigned I = 0; I != NumVars + 1; ++I)
  10897. Vars.push_back(Record.readSubExpr());
  10898. C->setUsedExprs(Vars);
  10899. }
  10900. void OMPClauseReader::VisitOMPAlignedClause(OMPAlignedClause *C) {
  10901. C->setLParenLoc(Record.readSourceLocation());
  10902. C->setColonLoc(Record.readSourceLocation());
  10903. unsigned NumVars = C->varlist_size();
  10904. SmallVector<Expr *, 16> Vars;
  10905. Vars.reserve(NumVars);
  10906. for (unsigned i = 0; i != NumVars; ++i)
  10907. Vars.push_back(Record.readSubExpr());
  10908. C->setVarRefs(Vars);
  10909. C->setAlignment(Record.readSubExpr());
  10910. }
  10911. void OMPClauseReader::VisitOMPCopyinClause(OMPCopyinClause *C) {
  10912. C->setLParenLoc(Record.readSourceLocation());
  10913. unsigned NumVars = C->varlist_size();
  10914. SmallVector<Expr *, 16> Exprs;
  10915. Exprs.reserve(NumVars);
  10916. for (unsigned i = 0; i != NumVars; ++i)
  10917. Exprs.push_back(Record.readSubExpr());
  10918. C->setVarRefs(Exprs);
  10919. Exprs.clear();
  10920. for (unsigned i = 0; i != NumVars; ++i)
  10921. Exprs.push_back(Record.readSubExpr());
  10922. C->setSourceExprs(Exprs);
  10923. Exprs.clear();
  10924. for (unsigned i = 0; i != NumVars; ++i)
  10925. Exprs.push_back(Record.readSubExpr());
  10926. C->setDestinationExprs(Exprs);
  10927. Exprs.clear();
  10928. for (unsigned i = 0; i != NumVars; ++i)
  10929. Exprs.push_back(Record.readSubExpr());
  10930. C->setAssignmentOps(Exprs);
  10931. }
  10932. void OMPClauseReader::VisitOMPCopyprivateClause(OMPCopyprivateClause *C) {
  10933. C->setLParenLoc(Record.readSourceLocation());
  10934. unsigned NumVars = C->varlist_size();
  10935. SmallVector<Expr *, 16> Exprs;
  10936. Exprs.reserve(NumVars);
  10937. for (unsigned i = 0; i != NumVars; ++i)
  10938. Exprs.push_back(Record.readSubExpr());
  10939. C->setVarRefs(Exprs);
  10940. Exprs.clear();
  10941. for (unsigned i = 0; i != NumVars; ++i)
  10942. Exprs.push_back(Record.readSubExpr());
  10943. C->setSourceExprs(Exprs);
  10944. Exprs.clear();
  10945. for (unsigned i = 0; i != NumVars; ++i)
  10946. Exprs.push_back(Record.readSubExpr());
  10947. C->setDestinationExprs(Exprs);
  10948. Exprs.clear();
  10949. for (unsigned i = 0; i != NumVars; ++i)
  10950. Exprs.push_back(Record.readSubExpr());
  10951. C->setAssignmentOps(Exprs);
  10952. }
  10953. void OMPClauseReader::VisitOMPFlushClause(OMPFlushClause *C) {
  10954. C->setLParenLoc(Record.readSourceLocation());
  10955. unsigned NumVars = C->varlist_size();
  10956. SmallVector<Expr *, 16> Vars;
  10957. Vars.reserve(NumVars);
  10958. for (unsigned i = 0; i != NumVars; ++i)
  10959. Vars.push_back(Record.readSubExpr());
  10960. C->setVarRefs(Vars);
  10961. }
  10962. void OMPClauseReader::VisitOMPDepobjClause(OMPDepobjClause *C) {
  10963. C->setDepobj(Record.readSubExpr());
  10964. C->setLParenLoc(Record.readSourceLocation());
  10965. }
  10966. void OMPClauseReader::VisitOMPDependClause(OMPDependClause *C) {
  10967. C->setLParenLoc(Record.readSourceLocation());
  10968. C->setModifier(Record.readSubExpr());
  10969. C->setDependencyKind(
  10970. static_cast<OpenMPDependClauseKind>(Record.readInt()));
  10971. C->setDependencyLoc(Record.readSourceLocation());
  10972. C->setColonLoc(Record.readSourceLocation());
  10973. unsigned NumVars = C->varlist_size();
  10974. SmallVector<Expr *, 16> Vars;
  10975. Vars.reserve(NumVars);
  10976. for (unsigned I = 0; I != NumVars; ++I)
  10977. Vars.push_back(Record.readSubExpr());
  10978. C->setVarRefs(Vars);
  10979. for (unsigned I = 0, E = C->getNumLoops(); I < E; ++I)
  10980. C->setLoopData(I, Record.readSubExpr());
  10981. }
  10982. void OMPClauseReader::VisitOMPDeviceClause(OMPDeviceClause *C) {
  10983. VisitOMPClauseWithPreInit(C);
  10984. C->setModifier(Record.readEnum<OpenMPDeviceClauseModifier>());
  10985. C->setDevice(Record.readSubExpr());
  10986. C->setModifierLoc(Record.readSourceLocation());
  10987. C->setLParenLoc(Record.readSourceLocation());
  10988. }
  10989. void OMPClauseReader::VisitOMPMapClause(OMPMapClause *C) {
  10990. C->setLParenLoc(Record.readSourceLocation());
  10991. for (unsigned I = 0; I < NumberOfOMPMapClauseModifiers; ++I) {
  10992. C->setMapTypeModifier(
  10993. I, static_cast<OpenMPMapModifierKind>(Record.readInt()));
  10994. C->setMapTypeModifierLoc(I, Record.readSourceLocation());
  10995. }
  10996. C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
  10997. C->setMapperIdInfo(Record.readDeclarationNameInfo());
  10998. C->setMapType(
  10999. static_cast<OpenMPMapClauseKind>(Record.readInt()));
  11000. C->setMapLoc(Record.readSourceLocation());
  11001. C->setColonLoc(Record.readSourceLocation());
  11002. auto NumVars = C->varlist_size();
  11003. auto UniqueDecls = C->getUniqueDeclarationsNum();
  11004. auto TotalLists = C->getTotalComponentListNum();
  11005. auto TotalComponents = C->getTotalComponentsNum();
  11006. SmallVector<Expr *, 16> Vars;
  11007. Vars.reserve(NumVars);
  11008. for (unsigned i = 0; i != NumVars; ++i)
  11009. Vars.push_back(Record.readExpr());
  11010. C->setVarRefs(Vars);
  11011. SmallVector<Expr *, 16> UDMappers;
  11012. UDMappers.reserve(NumVars);
  11013. for (unsigned I = 0; I < NumVars; ++I)
  11014. UDMappers.push_back(Record.readExpr());
  11015. C->setUDMapperRefs(UDMappers);
  11016. SmallVector<ValueDecl *, 16> Decls;
  11017. Decls.reserve(UniqueDecls);
  11018. for (unsigned i = 0; i < UniqueDecls; ++i)
  11019. Decls.push_back(Record.readDeclAs<ValueDecl>());
  11020. C->setUniqueDecls(Decls);
  11021. SmallVector<unsigned, 16> ListsPerDecl;
  11022. ListsPerDecl.reserve(UniqueDecls);
  11023. for (unsigned i = 0; i < UniqueDecls; ++i)
  11024. ListsPerDecl.push_back(Record.readInt());
  11025. C->setDeclNumLists(ListsPerDecl);
  11026. SmallVector<unsigned, 32> ListSizes;
  11027. ListSizes.reserve(TotalLists);
  11028. for (unsigned i = 0; i < TotalLists; ++i)
  11029. ListSizes.push_back(Record.readInt());
  11030. C->setComponentListSizes(ListSizes);
  11031. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  11032. Components.reserve(TotalComponents);
  11033. for (unsigned i = 0; i < TotalComponents; ++i) {
  11034. Expr *AssociatedExprPr = Record.readExpr();
  11035. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  11036. Components.emplace_back(AssociatedExprPr, AssociatedDecl,
  11037. /*IsNonContiguous=*/false);
  11038. }
  11039. C->setComponents(Components, ListSizes);
  11040. }
  11041. void OMPClauseReader::VisitOMPAllocateClause(OMPAllocateClause *C) {
  11042. C->setLParenLoc(Record.readSourceLocation());
  11043. C->setColonLoc(Record.readSourceLocation());
  11044. C->setAllocator(Record.readSubExpr());
  11045. unsigned NumVars = C->varlist_size();
  11046. SmallVector<Expr *, 16> Vars;
  11047. Vars.reserve(NumVars);
  11048. for (unsigned i = 0; i != NumVars; ++i)
  11049. Vars.push_back(Record.readSubExpr());
  11050. C->setVarRefs(Vars);
  11051. }
  11052. void OMPClauseReader::VisitOMPNumTeamsClause(OMPNumTeamsClause *C) {
  11053. VisitOMPClauseWithPreInit(C);
  11054. C->setNumTeams(Record.readSubExpr());
  11055. C->setLParenLoc(Record.readSourceLocation());
  11056. }
  11057. void OMPClauseReader::VisitOMPThreadLimitClause(OMPThreadLimitClause *C) {
  11058. VisitOMPClauseWithPreInit(C);
  11059. C->setThreadLimit(Record.readSubExpr());
  11060. C->setLParenLoc(Record.readSourceLocation());
  11061. }
  11062. void OMPClauseReader::VisitOMPPriorityClause(OMPPriorityClause *C) {
  11063. VisitOMPClauseWithPreInit(C);
  11064. C->setPriority(Record.readSubExpr());
  11065. C->setLParenLoc(Record.readSourceLocation());
  11066. }
  11067. void OMPClauseReader::VisitOMPGrainsizeClause(OMPGrainsizeClause *C) {
  11068. VisitOMPClauseWithPreInit(C);
  11069. C->setGrainsize(Record.readSubExpr());
  11070. C->setLParenLoc(Record.readSourceLocation());
  11071. }
  11072. void OMPClauseReader::VisitOMPNumTasksClause(OMPNumTasksClause *C) {
  11073. VisitOMPClauseWithPreInit(C);
  11074. C->setNumTasks(Record.readSubExpr());
  11075. C->setLParenLoc(Record.readSourceLocation());
  11076. }
  11077. void OMPClauseReader::VisitOMPHintClause(OMPHintClause *C) {
  11078. C->setHint(Record.readSubExpr());
  11079. C->setLParenLoc(Record.readSourceLocation());
  11080. }
  11081. void OMPClauseReader::VisitOMPDistScheduleClause(OMPDistScheduleClause *C) {
  11082. VisitOMPClauseWithPreInit(C);
  11083. C->setDistScheduleKind(
  11084. static_cast<OpenMPDistScheduleClauseKind>(Record.readInt()));
  11085. C->setChunkSize(Record.readSubExpr());
  11086. C->setLParenLoc(Record.readSourceLocation());
  11087. C->setDistScheduleKindLoc(Record.readSourceLocation());
  11088. C->setCommaLoc(Record.readSourceLocation());
  11089. }
  11090. void OMPClauseReader::VisitOMPDefaultmapClause(OMPDefaultmapClause *C) {
  11091. C->setDefaultmapKind(
  11092. static_cast<OpenMPDefaultmapClauseKind>(Record.readInt()));
  11093. C->setDefaultmapModifier(
  11094. static_cast<OpenMPDefaultmapClauseModifier>(Record.readInt()));
  11095. C->setLParenLoc(Record.readSourceLocation());
  11096. C->setDefaultmapModifierLoc(Record.readSourceLocation());
  11097. C->setDefaultmapKindLoc(Record.readSourceLocation());
  11098. }
  11099. void OMPClauseReader::VisitOMPToClause(OMPToClause *C) {
  11100. C->setLParenLoc(Record.readSourceLocation());
  11101. for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
  11102. C->setMotionModifier(
  11103. I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
  11104. C->setMotionModifierLoc(I, Record.readSourceLocation());
  11105. }
  11106. C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
  11107. C->setMapperIdInfo(Record.readDeclarationNameInfo());
  11108. C->setColonLoc(Record.readSourceLocation());
  11109. auto NumVars = C->varlist_size();
  11110. auto UniqueDecls = C->getUniqueDeclarationsNum();
  11111. auto TotalLists = C->getTotalComponentListNum();
  11112. auto TotalComponents = C->getTotalComponentsNum();
  11113. SmallVector<Expr *, 16> Vars;
  11114. Vars.reserve(NumVars);
  11115. for (unsigned i = 0; i != NumVars; ++i)
  11116. Vars.push_back(Record.readSubExpr());
  11117. C->setVarRefs(Vars);
  11118. SmallVector<Expr *, 16> UDMappers;
  11119. UDMappers.reserve(NumVars);
  11120. for (unsigned I = 0; I < NumVars; ++I)
  11121. UDMappers.push_back(Record.readSubExpr());
  11122. C->setUDMapperRefs(UDMappers);
  11123. SmallVector<ValueDecl *, 16> Decls;
  11124. Decls.reserve(UniqueDecls);
  11125. for (unsigned i = 0; i < UniqueDecls; ++i)
  11126. Decls.push_back(Record.readDeclAs<ValueDecl>());
  11127. C->setUniqueDecls(Decls);
  11128. SmallVector<unsigned, 16> ListsPerDecl;
  11129. ListsPerDecl.reserve(UniqueDecls);
  11130. for (unsigned i = 0; i < UniqueDecls; ++i)
  11131. ListsPerDecl.push_back(Record.readInt());
  11132. C->setDeclNumLists(ListsPerDecl);
  11133. SmallVector<unsigned, 32> ListSizes;
  11134. ListSizes.reserve(TotalLists);
  11135. for (unsigned i = 0; i < TotalLists; ++i)
  11136. ListSizes.push_back(Record.readInt());
  11137. C->setComponentListSizes(ListSizes);
  11138. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  11139. Components.reserve(TotalComponents);
  11140. for (unsigned i = 0; i < TotalComponents; ++i) {
  11141. Expr *AssociatedExprPr = Record.readSubExpr();
  11142. bool IsNonContiguous = Record.readBool();
  11143. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  11144. Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
  11145. }
  11146. C->setComponents(Components, ListSizes);
  11147. }
  11148. void OMPClauseReader::VisitOMPFromClause(OMPFromClause *C) {
  11149. C->setLParenLoc(Record.readSourceLocation());
  11150. for (unsigned I = 0; I < NumberOfOMPMotionModifiers; ++I) {
  11151. C->setMotionModifier(
  11152. I, static_cast<OpenMPMotionModifierKind>(Record.readInt()));
  11153. C->setMotionModifierLoc(I, Record.readSourceLocation());
  11154. }
  11155. C->setMapperQualifierLoc(Record.readNestedNameSpecifierLoc());
  11156. C->setMapperIdInfo(Record.readDeclarationNameInfo());
  11157. C->setColonLoc(Record.readSourceLocation());
  11158. auto NumVars = C->varlist_size();
  11159. auto UniqueDecls = C->getUniqueDeclarationsNum();
  11160. auto TotalLists = C->getTotalComponentListNum();
  11161. auto TotalComponents = C->getTotalComponentsNum();
  11162. SmallVector<Expr *, 16> Vars;
  11163. Vars.reserve(NumVars);
  11164. for (unsigned i = 0; i != NumVars; ++i)
  11165. Vars.push_back(Record.readSubExpr());
  11166. C->setVarRefs(Vars);
  11167. SmallVector<Expr *, 16> UDMappers;
  11168. UDMappers.reserve(NumVars);
  11169. for (unsigned I = 0; I < NumVars; ++I)
  11170. UDMappers.push_back(Record.readSubExpr());
  11171. C->setUDMapperRefs(UDMappers);
  11172. SmallVector<ValueDecl *, 16> Decls;
  11173. Decls.reserve(UniqueDecls);
  11174. for (unsigned i = 0; i < UniqueDecls; ++i)
  11175. Decls.push_back(Record.readDeclAs<ValueDecl>());
  11176. C->setUniqueDecls(Decls);
  11177. SmallVector<unsigned, 16> ListsPerDecl;
  11178. ListsPerDecl.reserve(UniqueDecls);
  11179. for (unsigned i = 0; i < UniqueDecls; ++i)
  11180. ListsPerDecl.push_back(Record.readInt());
  11181. C->setDeclNumLists(ListsPerDecl);
  11182. SmallVector<unsigned, 32> ListSizes;
  11183. ListSizes.reserve(TotalLists);
  11184. for (unsigned i = 0; i < TotalLists; ++i)
  11185. ListSizes.push_back(Record.readInt());
  11186. C->setComponentListSizes(ListSizes);
  11187. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  11188. Components.reserve(TotalComponents);
  11189. for (unsigned i = 0; i < TotalComponents; ++i) {
  11190. Expr *AssociatedExprPr = Record.readSubExpr();
  11191. bool IsNonContiguous = Record.readBool();
  11192. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  11193. Components.emplace_back(AssociatedExprPr, AssociatedDecl, IsNonContiguous);
  11194. }
  11195. C->setComponents(Components, ListSizes);
  11196. }
  11197. void OMPClauseReader::VisitOMPUseDevicePtrClause(OMPUseDevicePtrClause *C) {
  11198. C->setLParenLoc(Record.readSourceLocation());
  11199. auto NumVars = C->varlist_size();
  11200. auto UniqueDecls = C->getUniqueDeclarationsNum();
  11201. auto TotalLists = C->getTotalComponentListNum();
  11202. auto TotalComponents = C->getTotalComponentsNum();
  11203. SmallVector<Expr *, 16> Vars;
  11204. Vars.reserve(NumVars);
  11205. for (unsigned i = 0; i != NumVars; ++i)
  11206. Vars.push_back(Record.readSubExpr());
  11207. C->setVarRefs(Vars);
  11208. Vars.clear();
  11209. for (unsigned i = 0; i != NumVars; ++i)
  11210. Vars.push_back(Record.readSubExpr());
  11211. C->setPrivateCopies(Vars);
  11212. Vars.clear();
  11213. for (unsigned i = 0; i != NumVars; ++i)
  11214. Vars.push_back(Record.readSubExpr());
  11215. C->setInits(Vars);
  11216. SmallVector<ValueDecl *, 16> Decls;
  11217. Decls.reserve(UniqueDecls);
  11218. for (unsigned i = 0; i < UniqueDecls; ++i)
  11219. Decls.push_back(Record.readDeclAs<ValueDecl>());
  11220. C->setUniqueDecls(Decls);
  11221. SmallVector<unsigned, 16> ListsPerDecl;
  11222. ListsPerDecl.reserve(UniqueDecls);
  11223. for (unsigned i = 0; i < UniqueDecls; ++i)
  11224. ListsPerDecl.push_back(Record.readInt());
  11225. C->setDeclNumLists(ListsPerDecl);
  11226. SmallVector<unsigned, 32> ListSizes;
  11227. ListSizes.reserve(TotalLists);
  11228. for (unsigned i = 0; i < TotalLists; ++i)
  11229. ListSizes.push_back(Record.readInt());
  11230. C->setComponentListSizes(ListSizes);
  11231. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  11232. Components.reserve(TotalComponents);
  11233. for (unsigned i = 0; i < TotalComponents; ++i) {
  11234. auto *AssociatedExprPr = Record.readSubExpr();
  11235. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  11236. Components.emplace_back(AssociatedExprPr, AssociatedDecl,
  11237. /*IsNonContiguous=*/false);
  11238. }
  11239. C->setComponents(Components, ListSizes);
  11240. }
  11241. void OMPClauseReader::VisitOMPUseDeviceAddrClause(OMPUseDeviceAddrClause *C) {
  11242. C->setLParenLoc(Record.readSourceLocation());
  11243. auto NumVars = C->varlist_size();
  11244. auto UniqueDecls = C->getUniqueDeclarationsNum();
  11245. auto TotalLists = C->getTotalComponentListNum();
  11246. auto TotalComponents = C->getTotalComponentsNum();
  11247. SmallVector<Expr *, 16> Vars;
  11248. Vars.reserve(NumVars);
  11249. for (unsigned i = 0; i != NumVars; ++i)
  11250. Vars.push_back(Record.readSubExpr());
  11251. C->setVarRefs(Vars);
  11252. SmallVector<ValueDecl *, 16> Decls;
  11253. Decls.reserve(UniqueDecls);
  11254. for (unsigned i = 0; i < UniqueDecls; ++i)
  11255. Decls.push_back(Record.readDeclAs<ValueDecl>());
  11256. C->setUniqueDecls(Decls);
  11257. SmallVector<unsigned, 16> ListsPerDecl;
  11258. ListsPerDecl.reserve(UniqueDecls);
  11259. for (unsigned i = 0; i < UniqueDecls; ++i)
  11260. ListsPerDecl.push_back(Record.readInt());
  11261. C->setDeclNumLists(ListsPerDecl);
  11262. SmallVector<unsigned, 32> ListSizes;
  11263. ListSizes.reserve(TotalLists);
  11264. for (unsigned i = 0; i < TotalLists; ++i)
  11265. ListSizes.push_back(Record.readInt());
  11266. C->setComponentListSizes(ListSizes);
  11267. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  11268. Components.reserve(TotalComponents);
  11269. for (unsigned i = 0; i < TotalComponents; ++i) {
  11270. Expr *AssociatedExpr = Record.readSubExpr();
  11271. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  11272. Components.emplace_back(AssociatedExpr, AssociatedDecl,
  11273. /*IsNonContiguous*/ false);
  11274. }
  11275. C->setComponents(Components, ListSizes);
  11276. }
  11277. void OMPClauseReader::VisitOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
  11278. C->setLParenLoc(Record.readSourceLocation());
  11279. auto NumVars = C->varlist_size();
  11280. auto UniqueDecls = C->getUniqueDeclarationsNum();
  11281. auto TotalLists = C->getTotalComponentListNum();
  11282. auto TotalComponents = C->getTotalComponentsNum();
  11283. SmallVector<Expr *, 16> Vars;
  11284. Vars.reserve(NumVars);
  11285. for (unsigned i = 0; i != NumVars; ++i)
  11286. Vars.push_back(Record.readSubExpr());
  11287. C->setVarRefs(Vars);
  11288. Vars.clear();
  11289. SmallVector<ValueDecl *, 16> Decls;
  11290. Decls.reserve(UniqueDecls);
  11291. for (unsigned i = 0; i < UniqueDecls; ++i)
  11292. Decls.push_back(Record.readDeclAs<ValueDecl>());
  11293. C->setUniqueDecls(Decls);
  11294. SmallVector<unsigned, 16> ListsPerDecl;
  11295. ListsPerDecl.reserve(UniqueDecls);
  11296. for (unsigned i = 0; i < UniqueDecls; ++i)
  11297. ListsPerDecl.push_back(Record.readInt());
  11298. C->setDeclNumLists(ListsPerDecl);
  11299. SmallVector<unsigned, 32> ListSizes;
  11300. ListSizes.reserve(TotalLists);
  11301. for (unsigned i = 0; i < TotalLists; ++i)
  11302. ListSizes.push_back(Record.readInt());
  11303. C->setComponentListSizes(ListSizes);
  11304. SmallVector<OMPClauseMappableExprCommon::MappableComponent, 32> Components;
  11305. Components.reserve(TotalComponents);
  11306. for (unsigned i = 0; i < TotalComponents; ++i) {
  11307. Expr *AssociatedExpr = Record.readSubExpr();
  11308. auto *AssociatedDecl = Record.readDeclAs<ValueDecl>();
  11309. Components.emplace_back(AssociatedExpr, AssociatedDecl,
  11310. /*IsNonContiguous=*/false);
  11311. }
  11312. C->setComponents(Components, ListSizes);
  11313. }
  11314. void OMPClauseReader::VisitOMPNontemporalClause(OMPNontemporalClause *C) {
  11315. C->setLParenLoc(Record.readSourceLocation());
  11316. unsigned NumVars = C->varlist_size();
  11317. SmallVector<Expr *, 16> Vars;
  11318. Vars.reserve(NumVars);
  11319. for (unsigned i = 0; i != NumVars; ++i)
  11320. Vars.push_back(Record.readSubExpr());
  11321. C->setVarRefs(Vars);
  11322. Vars.clear();
  11323. Vars.reserve(NumVars);
  11324. for (unsigned i = 0; i != NumVars; ++i)
  11325. Vars.push_back(Record.readSubExpr());
  11326. C->setPrivateRefs(Vars);
  11327. }
  11328. void OMPClauseReader::VisitOMPInclusiveClause(OMPInclusiveClause *C) {
  11329. C->setLParenLoc(Record.readSourceLocation());
  11330. unsigned NumVars = C->varlist_size();
  11331. SmallVector<Expr *, 16> Vars;
  11332. Vars.reserve(NumVars);
  11333. for (unsigned i = 0; i != NumVars; ++i)
  11334. Vars.push_back(Record.readSubExpr());
  11335. C->setVarRefs(Vars);
  11336. }
  11337. void OMPClauseReader::VisitOMPExclusiveClause(OMPExclusiveClause *C) {
  11338. C->setLParenLoc(Record.readSourceLocation());
  11339. unsigned NumVars = C->varlist_size();
  11340. SmallVector<Expr *, 16> Vars;
  11341. Vars.reserve(NumVars);
  11342. for (unsigned i = 0; i != NumVars; ++i)
  11343. Vars.push_back(Record.readSubExpr());
  11344. C->setVarRefs(Vars);
  11345. }
  11346. void OMPClauseReader::VisitOMPUsesAllocatorsClause(OMPUsesAllocatorsClause *C) {
  11347. C->setLParenLoc(Record.readSourceLocation());
  11348. unsigned NumOfAllocators = C->getNumberOfAllocators();
  11349. SmallVector<OMPUsesAllocatorsClause::Data, 4> Data;
  11350. Data.reserve(NumOfAllocators);
  11351. for (unsigned I = 0; I != NumOfAllocators; ++I) {
  11352. OMPUsesAllocatorsClause::Data &D = Data.emplace_back();
  11353. D.Allocator = Record.readSubExpr();
  11354. D.AllocatorTraits = Record.readSubExpr();
  11355. D.LParenLoc = Record.readSourceLocation();
  11356. D.RParenLoc = Record.readSourceLocation();
  11357. }
  11358. C->setAllocatorsData(Data);
  11359. }
  11360. void OMPClauseReader::VisitOMPAffinityClause(OMPAffinityClause *C) {
  11361. C->setLParenLoc(Record.readSourceLocation());
  11362. C->setModifier(Record.readSubExpr());
  11363. C->setColonLoc(Record.readSourceLocation());
  11364. unsigned NumOfLocators = C->varlist_size();
  11365. SmallVector<Expr *, 4> Locators;
  11366. Locators.reserve(NumOfLocators);
  11367. for (unsigned I = 0; I != NumOfLocators; ++I)
  11368. Locators.push_back(Record.readSubExpr());
  11369. C->setVarRefs(Locators);
  11370. }
  11371. void OMPClauseReader::VisitOMPOrderClause(OMPOrderClause *C) {
  11372. C->setKind(Record.readEnum<OpenMPOrderClauseKind>());
  11373. C->setLParenLoc(Record.readSourceLocation());
  11374. C->setKindKwLoc(Record.readSourceLocation());
  11375. }
  11376. void OMPClauseReader::VisitOMPFilterClause(OMPFilterClause *C) {
  11377. VisitOMPClauseWithPreInit(C);
  11378. C->setThreadID(Record.readSubExpr());
  11379. C->setLParenLoc(Record.readSourceLocation());
  11380. }
  11381. void OMPClauseReader::VisitOMPBindClause(OMPBindClause *C) {
  11382. C->setBindKind(Record.readEnum<OpenMPBindClauseKind>());
  11383. C->setLParenLoc(Record.readSourceLocation());
  11384. C->setBindKindLoc(Record.readSourceLocation());
  11385. }
  11386. void OMPClauseReader::VisitOMPAlignClause(OMPAlignClause *C) {
  11387. C->setAlignment(Record.readExpr());
  11388. C->setLParenLoc(Record.readSourceLocation());
  11389. }
  11390. OMPTraitInfo *ASTRecordReader::readOMPTraitInfo() {
  11391. OMPTraitInfo &TI = getContext().getNewOMPTraitInfo();
  11392. TI.Sets.resize(readUInt32());
  11393. for (auto &Set : TI.Sets) {
  11394. Set.Kind = readEnum<llvm::omp::TraitSet>();
  11395. Set.Selectors.resize(readUInt32());
  11396. for (auto &Selector : Set.Selectors) {
  11397. Selector.Kind = readEnum<llvm::omp::TraitSelector>();
  11398. Selector.ScoreOrCondition = nullptr;
  11399. if (readBool())
  11400. Selector.ScoreOrCondition = readExprRef();
  11401. Selector.Properties.resize(readUInt32());
  11402. for (auto &Property : Selector.Properties)
  11403. Property.Kind = readEnum<llvm::omp::TraitProperty>();
  11404. }
  11405. }
  11406. return &TI;
  11407. }
  11408. void ASTRecordReader::readOMPChildren(OMPChildren *Data) {
  11409. if (!Data)
  11410. return;
  11411. if (Reader->ReadingKind == ASTReader::Read_Stmt) {
  11412. // Skip NumClauses, NumChildren and HasAssociatedStmt fields.
  11413. skipInts(3);
  11414. }
  11415. SmallVector<OMPClause *, 4> Clauses(Data->getNumClauses());
  11416. for (unsigned I = 0, E = Data->getNumClauses(); I < E; ++I)
  11417. Clauses[I] = readOMPClause();
  11418. Data->setClauses(Clauses);
  11419. if (Data->hasAssociatedStmt())
  11420. Data->setAssociatedStmt(readStmt());
  11421. for (unsigned I = 0, E = Data->getNumChildren(); I < E; ++I)
  11422. Data->getChildren()[I] = readStmt();
  11423. }