BitcodeReader.cpp 240 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755
  1. //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "llvm/ADT/APFloat.h"
  10. #include "llvm/ADT/APInt.h"
  11. #include "llvm/ADT/ArrayRef.h"
  12. #include "llvm/ADT/DenseMap.h"
  13. #include "llvm/ADT/None.h"
  14. #include "llvm/ADT/STLExtras.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/ADT/Triple.h"
  19. #include "llvm/ADT/Twine.h"
  20. #include "llvm/Bitcode/BitstreamReader.h"
  21. #include "llvm/Bitcode/LLVMBitCodes.h"
  22. #include "llvm/Bitcode/ReaderWriter.h"
  23. #include "llvm/IR/Argument.h"
  24. #include "llvm/IR/Attributes.h"
  25. #include "llvm/IR/AutoUpgrade.h"
  26. #include "llvm/IR/BasicBlock.h"
  27. #include "llvm/IR/CallingConv.h"
  28. #include "llvm/IR/CallSite.h"
  29. #include "llvm/IR/Comdat.h"
  30. #include "llvm/IR/Constant.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DebugInfo.h"
  33. #include "llvm/IR/DebugInfoMetadata.h"
  34. #include "llvm/IR/DebugLoc.h"
  35. #include "llvm/IR/DerivedTypes.h"
  36. #include "llvm/IR/DiagnosticInfo.h"
  37. #include "llvm/IR/DiagnosticPrinter.h"
  38. #include "llvm/IR/Function.h"
  39. #include "llvm/IR/GlobalAlias.h"
  40. #include "llvm/IR/GlobalIFunc.h"
  41. #include "llvm/IR/GlobalIndirectSymbol.h"
  42. #include "llvm/IR/GlobalObject.h"
  43. #include "llvm/IR/GlobalValue.h"
  44. #include "llvm/IR/GlobalVariable.h"
  45. #include "llvm/IR/GVMaterializer.h"
  46. #include "llvm/IR/InlineAsm.h"
  47. #include "llvm/IR/InstrTypes.h"
  48. #include "llvm/IR/Instruction.h"
  49. #include "llvm/IR/Instructions.h"
  50. #include "llvm/IR/Intrinsics.h"
  51. #include "llvm/IR/LLVMContext.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/IR/ModuleSummaryIndex.h"
  54. #include "llvm/IR/OperandTraits.h"
  55. #include "llvm/IR/Operator.h"
  56. #include "llvm/IR/TrackingMDRef.h"
  57. #include "llvm/IR/Type.h"
  58. #include "llvm/IR/ValueHandle.h"
  59. #include "llvm/Support/AtomicOrdering.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/Compiler.h"
  63. #include "llvm/Support/Debug.h"
  64. #include "llvm/Support/ErrorHandling.h"
  65. #include "llvm/Support/ErrorOr.h"
  66. #include "llvm/Support/ManagedStatic.h"
  67. #include "llvm/Support/MemoryBuffer.h"
  68. #include "llvm/Support/raw_ostream.h"
  69. #include <algorithm>
  70. #include <cassert>
  71. #include <cstddef>
  72. #include <cstdint>
  73. #include <deque>
  74. #include <limits>
  75. #include <map>
  76. #include <memory>
  77. #include <string>
  78. #include <system_error>
  79. #include <tuple>
  80. #include <utility>
  81. #include <vector>
  82. using namespace llvm;
  83. static cl::opt<bool> PrintSummaryGUIDs(
  84. "print-summary-global-ids", cl::init(false), cl::Hidden,
  85. cl::desc(
  86. "Print the global id for each value when reading the module summary"));
  87. namespace {
  88. enum {
  89. SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
  90. };
  91. class BitcodeReaderValueList {
  92. std::vector<WeakVH> ValuePtrs;
  93. /// As we resolve forward-referenced constants, we add information about them
  94. /// to this vector. This allows us to resolve them in bulk instead of
  95. /// resolving each reference at a time. See the code in
  96. /// ResolveConstantForwardRefs for more information about this.
  97. ///
  98. /// The key of this vector is the placeholder constant, the value is the slot
  99. /// number that holds the resolved value.
  100. typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
  101. ResolveConstantsTy ResolveConstants;
  102. LLVMContext &Context;
  103. public:
  104. BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
  105. ~BitcodeReaderValueList() {
  106. assert(ResolveConstants.empty() && "Constants not resolved?");
  107. }
  108. // vector compatibility methods
  109. unsigned size() const { return ValuePtrs.size(); }
  110. void resize(unsigned N) { ValuePtrs.resize(N); }
  111. void push_back(Value *V) { ValuePtrs.emplace_back(V); }
  112. void clear() {
  113. assert(ResolveConstants.empty() && "Constants not resolved?");
  114. ValuePtrs.clear();
  115. }
  116. Value *operator[](unsigned i) const {
  117. assert(i < ValuePtrs.size());
  118. return ValuePtrs[i];
  119. }
  120. Value *back() const { return ValuePtrs.back(); }
  121. void pop_back() { ValuePtrs.pop_back(); }
  122. bool empty() const { return ValuePtrs.empty(); }
  123. void shrinkTo(unsigned N) {
  124. assert(N <= size() && "Invalid shrinkTo request!");
  125. ValuePtrs.resize(N);
  126. }
  127. Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
  128. Value *getValueFwdRef(unsigned Idx, Type *Ty);
  129. void assignValue(Value *V, unsigned Idx);
  130. /// Once all constants are read, this method bulk resolves any forward
  131. /// references.
  132. void resolveConstantForwardRefs();
  133. };
  134. class BitcodeReaderMetadataList {
  135. unsigned NumFwdRefs;
  136. bool AnyFwdRefs;
  137. unsigned MinFwdRef;
  138. unsigned MaxFwdRef;
  139. /// Array of metadata references.
  140. ///
  141. /// Don't use std::vector here. Some versions of libc++ copy (instead of
  142. /// move) on resize, and TrackingMDRef is very expensive to copy.
  143. SmallVector<TrackingMDRef, 1> MetadataPtrs;
  144. /// Structures for resolving old type refs.
  145. struct {
  146. SmallDenseMap<MDString *, TempMDTuple, 1> Unknown;
  147. SmallDenseMap<MDString *, DICompositeType *, 1> Final;
  148. SmallDenseMap<MDString *, DICompositeType *, 1> FwdDecls;
  149. SmallVector<std::pair<TrackingMDRef, TempMDTuple>, 1> Arrays;
  150. } OldTypeRefs;
  151. LLVMContext &Context;
  152. public:
  153. BitcodeReaderMetadataList(LLVMContext &C)
  154. : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
  155. // vector compatibility methods
  156. unsigned size() const { return MetadataPtrs.size(); }
  157. void resize(unsigned N) { MetadataPtrs.resize(N); }
  158. void push_back(Metadata *MD) { MetadataPtrs.emplace_back(MD); }
  159. void clear() { MetadataPtrs.clear(); }
  160. Metadata *back() const { return MetadataPtrs.back(); }
  161. void pop_back() { MetadataPtrs.pop_back(); }
  162. bool empty() const { return MetadataPtrs.empty(); }
  163. Metadata *operator[](unsigned i) const {
  164. assert(i < MetadataPtrs.size());
  165. return MetadataPtrs[i];
  166. }
  167. Metadata *lookup(unsigned I) const {
  168. if (I < MetadataPtrs.size())
  169. return MetadataPtrs[I];
  170. return nullptr;
  171. }
  172. void shrinkTo(unsigned N) {
  173. assert(N <= size() && "Invalid shrinkTo request!");
  174. assert(!AnyFwdRefs && "Unexpected forward refs");
  175. MetadataPtrs.resize(N);
  176. }
  177. /// Return the given metadata, creating a replaceable forward reference if
  178. /// necessary.
  179. Metadata *getMetadataFwdRef(unsigned Idx);
  180. /// Return the the given metadata only if it is fully resolved.
  181. ///
  182. /// Gives the same result as \a lookup(), unless \a MDNode::isResolved()
  183. /// would give \c false.
  184. Metadata *getMetadataIfResolved(unsigned Idx);
  185. MDNode *getMDNodeFwdRefOrNull(unsigned Idx);
  186. void assignValue(Metadata *MD, unsigned Idx);
  187. void tryToResolveCycles();
  188. bool hasFwdRefs() const { return AnyFwdRefs; }
  189. /// Upgrade a type that had an MDString reference.
  190. void addTypeRef(MDString &UUID, DICompositeType &CT);
  191. /// Upgrade a type that had an MDString reference.
  192. Metadata *upgradeTypeRef(Metadata *MaybeUUID);
  193. /// Upgrade a type ref array that may have MDString references.
  194. Metadata *upgradeTypeRefArray(Metadata *MaybeTuple);
  195. private:
  196. Metadata *resolveTypeRefArray(Metadata *MaybeTuple);
  197. };
  198. class BitcodeReaderBase {
  199. protected:
  200. BitcodeReaderBase(MemoryBufferRef Buffer) : Buffer(Buffer) {}
  201. MemoryBufferRef Buffer;
  202. BitstreamBlockInfo BlockInfo;
  203. BitstreamCursor Stream;
  204. std::error_code initStream();
  205. bool readBlockInfo();
  206. virtual std::error_code error(const Twine &Message) = 0;
  207. virtual ~BitcodeReaderBase() = default;
  208. };
  209. std::error_code BitcodeReaderBase::initStream() {
  210. const unsigned char *BufPtr = (const unsigned char*)Buffer.getBufferStart();
  211. const unsigned char *BufEnd = BufPtr+Buffer.getBufferSize();
  212. if (Buffer.getBufferSize() & 3)
  213. return error("Invalid bitcode signature");
  214. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  215. // The magic number is 0x0B17C0DE stored in little endian.
  216. if (isBitcodeWrapper(BufPtr, BufEnd))
  217. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
  218. return error("Invalid bitcode wrapper header");
  219. Stream = BitstreamCursor(ArrayRef<uint8_t>(BufPtr, BufEnd));
  220. Stream.setBlockInfo(&BlockInfo);
  221. return std::error_code();
  222. }
  223. class BitcodeReader : public BitcodeReaderBase, public GVMaterializer {
  224. LLVMContext &Context;
  225. Module *TheModule = nullptr;
  226. // Next offset to start scanning for lazy parsing of function bodies.
  227. uint64_t NextUnreadBit = 0;
  228. // Last function offset found in the VST.
  229. uint64_t LastFunctionBlockBit = 0;
  230. bool SeenValueSymbolTable = false;
  231. uint64_t VSTOffset = 0;
  232. // Contains an arbitrary and optional string identifying the bitcode producer
  233. std::string ProducerIdentification;
  234. std::vector<Type*> TypeList;
  235. BitcodeReaderValueList ValueList;
  236. BitcodeReaderMetadataList MetadataList;
  237. std::vector<Comdat *> ComdatList;
  238. SmallVector<Instruction *, 64> InstructionList;
  239. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
  240. std::vector<std::pair<GlobalIndirectSymbol*, unsigned> > IndirectSymbolInits;
  241. std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
  242. std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
  243. std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
  244. bool HasSeenOldLoopTags = false;
  245. /// The set of attributes by index. Index zero in the file is for null, and
  246. /// is thus not represented here. As such all indices are off by one.
  247. std::vector<AttributeSet> MAttributes;
  248. /// The set of attribute groups.
  249. std::map<unsigned, AttributeSet> MAttributeGroups;
  250. /// While parsing a function body, this is a list of the basic blocks for the
  251. /// function.
  252. std::vector<BasicBlock*> FunctionBBs;
  253. // When reading the module header, this list is populated with functions that
  254. // have bodies later in the file.
  255. std::vector<Function*> FunctionsWithBodies;
  256. // When intrinsic functions are encountered which require upgrading they are
  257. // stored here with their replacement function.
  258. typedef DenseMap<Function*, Function*> UpdatedIntrinsicMap;
  259. UpdatedIntrinsicMap UpgradedIntrinsics;
  260. // Intrinsics which were remangled because of types rename
  261. UpdatedIntrinsicMap RemangledIntrinsics;
  262. // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
  263. DenseMap<unsigned, unsigned> MDKindMap;
  264. // Several operations happen after the module header has been read, but
  265. // before function bodies are processed. This keeps track of whether
  266. // we've done this yet.
  267. bool SeenFirstFunctionBody = false;
  268. /// When function bodies are initially scanned, this map contains info about
  269. /// where to find deferred function body in the stream.
  270. DenseMap<Function*, uint64_t> DeferredFunctionInfo;
  271. /// When Metadata block is initially scanned when parsing the module, we may
  272. /// choose to defer parsing of the metadata. This vector contains info about
  273. /// which Metadata blocks are deferred.
  274. std::vector<uint64_t> DeferredMetadataInfo;
  275. /// These are basic blocks forward-referenced by block addresses. They are
  276. /// inserted lazily into functions when they're loaded. The basic block ID is
  277. /// its index into the vector.
  278. DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
  279. std::deque<Function *> BasicBlockFwdRefQueue;
  280. /// Indicates that we are using a new encoding for instruction operands where
  281. /// most operands in the current FUNCTION_BLOCK are encoded relative to the
  282. /// instruction number, for a more compact encoding. Some instruction
  283. /// operands are not relative to the instruction ID: basic block numbers, and
  284. /// types. Once the old style function blocks have been phased out, we would
  285. /// not need this flag.
  286. bool UseRelativeIDs = false;
  287. /// True if all functions will be materialized, negating the need to process
  288. /// (e.g.) blockaddress forward references.
  289. bool WillMaterializeAllForwardRefs = false;
  290. /// True if any Metadata block has been materialized.
  291. bool IsMetadataMaterialized = false;
  292. bool StripDebugInfo = false;
  293. /// Functions that need to be matched with subprograms when upgrading old
  294. /// metadata.
  295. SmallDenseMap<Function *, DISubprogram *, 16> FunctionsWithSPs;
  296. std::vector<std::string> BundleTags;
  297. public:
  298. std::error_code error(BitcodeError E, const Twine &Message);
  299. std::error_code error(const Twine &Message) override;
  300. BitcodeReader(MemoryBufferRef Buffer, LLVMContext &Context);
  301. std::error_code materializeForwardReferencedFunctions();
  302. std::error_code materialize(GlobalValue *GV) override;
  303. std::error_code materializeModule() override;
  304. std::vector<StructType *> getIdentifiedStructTypes() const override;
  305. /// \brief Main interface to parsing a bitcode buffer.
  306. /// \returns true if an error occurred.
  307. std::error_code parseBitcodeInto(Module *M,
  308. bool ShouldLazyLoadMetadata = false);
  309. /// \brief Cheap mechanism to just extract module triple
  310. /// \returns true if an error occurred.
  311. ErrorOr<std::string> parseTriple();
  312. /// Cheap mechanism to just extract the identification block out of bitcode.
  313. ErrorOr<std::string> parseIdentificationBlock();
  314. /// Peak at the module content and return true if any ObjC category or class
  315. /// is found.
  316. ErrorOr<bool> hasObjCCategory();
  317. static uint64_t decodeSignRotatedValue(uint64_t V);
  318. /// Materialize any deferred Metadata block.
  319. std::error_code materializeMetadata() override;
  320. void setStripDebugInfo() override;
  321. private:
  322. /// Parse the "IDENTIFICATION_BLOCK_ID" block, populate the
  323. // ProducerIdentification data member, and do some basic enforcement on the
  324. // "epoch" encoded in the bitcode.
  325. std::error_code parseBitcodeVersion();
  326. std::vector<StructType *> IdentifiedStructTypes;
  327. StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
  328. StructType *createIdentifiedStructType(LLVMContext &Context);
  329. Type *getTypeByID(unsigned ID);
  330. Value *getFnValueByID(unsigned ID, Type *Ty) {
  331. if (Ty && Ty->isMetadataTy())
  332. return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
  333. return ValueList.getValueFwdRef(ID, Ty);
  334. }
  335. Metadata *getFnMetadataByID(unsigned ID) {
  336. return MetadataList.getMetadataFwdRef(ID);
  337. }
  338. BasicBlock *getBasicBlock(unsigned ID) const {
  339. if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
  340. return FunctionBBs[ID];
  341. }
  342. AttributeSet getAttributes(unsigned i) const {
  343. if (i-1 < MAttributes.size())
  344. return MAttributes[i-1];
  345. return AttributeSet();
  346. }
  347. /// Read a value/type pair out of the specified record from slot 'Slot'.
  348. /// Increment Slot past the number of slots used in the record. Return true on
  349. /// failure.
  350. bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  351. unsigned InstNum, Value *&ResVal) {
  352. if (Slot == Record.size()) return true;
  353. unsigned ValNo = (unsigned)Record[Slot++];
  354. // Adjust the ValNo, if it was encoded relative to the InstNum.
  355. if (UseRelativeIDs)
  356. ValNo = InstNum - ValNo;
  357. if (ValNo < InstNum) {
  358. // If this is not a forward reference, just return the value we already
  359. // have.
  360. ResVal = getFnValueByID(ValNo, nullptr);
  361. return ResVal == nullptr;
  362. }
  363. if (Slot == Record.size())
  364. return true;
  365. unsigned TypeNo = (unsigned)Record[Slot++];
  366. ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
  367. return ResVal == nullptr;
  368. }
  369. /// Read a value out of the specified record from slot 'Slot'. Increment Slot
  370. /// past the number of slots used by the value in the record. Return true if
  371. /// there is an error.
  372. bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  373. unsigned InstNum, Type *Ty, Value *&ResVal) {
  374. if (getValue(Record, Slot, InstNum, Ty, ResVal))
  375. return true;
  376. // All values currently take a single record slot.
  377. ++Slot;
  378. return false;
  379. }
  380. /// Like popValue, but does not increment the Slot number.
  381. bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  382. unsigned InstNum, Type *Ty, Value *&ResVal) {
  383. ResVal = getValue(Record, Slot, InstNum, Ty);
  384. return ResVal == nullptr;
  385. }
  386. /// Version of getValue that returns ResVal directly, or 0 if there is an
  387. /// error.
  388. Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  389. unsigned InstNum, Type *Ty) {
  390. if (Slot == Record.size()) return nullptr;
  391. unsigned ValNo = (unsigned)Record[Slot];
  392. // Adjust the ValNo, if it was encoded relative to the InstNum.
  393. if (UseRelativeIDs)
  394. ValNo = InstNum - ValNo;
  395. return getFnValueByID(ValNo, Ty);
  396. }
  397. /// Like getValue, but decodes signed VBRs.
  398. Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  399. unsigned InstNum, Type *Ty) {
  400. if (Slot == Record.size()) return nullptr;
  401. unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
  402. // Adjust the ValNo, if it was encoded relative to the InstNum.
  403. if (UseRelativeIDs)
  404. ValNo = InstNum - ValNo;
  405. return getFnValueByID(ValNo, Ty);
  406. }
  407. /// Converts alignment exponent (i.e. power of two (or zero)) to the
  408. /// corresponding alignment to use. If alignment is too large, returns
  409. /// a corresponding error code.
  410. std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
  411. std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
  412. std::error_code parseModule(uint64_t ResumeBit,
  413. bool ShouldLazyLoadMetadata = false);
  414. std::error_code parseAttributeBlock();
  415. std::error_code parseAttributeGroupBlock();
  416. std::error_code parseTypeTable();
  417. std::error_code parseTypeTableBody();
  418. std::error_code parseOperandBundleTags();
  419. ErrorOr<Value *> recordValue(SmallVectorImpl<uint64_t> &Record,
  420. unsigned NameIndex, Triple &TT);
  421. std::error_code parseValueSymbolTable(uint64_t Offset = 0);
  422. std::error_code parseConstants();
  423. std::error_code rememberAndSkipFunctionBodies();
  424. std::error_code rememberAndSkipFunctionBody();
  425. /// Save the positions of the Metadata blocks and skip parsing the blocks.
  426. std::error_code rememberAndSkipMetadata();
  427. std::error_code parseFunctionBody(Function *F);
  428. std::error_code globalCleanup();
  429. std::error_code resolveGlobalAndIndirectSymbolInits();
  430. std::error_code parseMetadata(bool ModuleLevel = false);
  431. std::error_code parseMetadataStrings(ArrayRef<uint64_t> Record,
  432. StringRef Blob,
  433. unsigned &NextMetadataNo);
  434. std::error_code parseMetadataKinds();
  435. std::error_code parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record);
  436. std::error_code
  437. parseGlobalObjectAttachment(GlobalObject &GO,
  438. ArrayRef<uint64_t> Record);
  439. std::error_code parseMetadataAttachment(Function &F);
  440. ErrorOr<std::string> parseModuleTriple();
  441. ErrorOr<bool> hasObjCCategoryInModule();
  442. std::error_code parseUseLists();
  443. std::error_code findFunctionInStream(
  444. Function *F,
  445. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
  446. };
  447. /// Class to manage reading and parsing function summary index bitcode
  448. /// files/sections.
  449. class ModuleSummaryIndexBitcodeReader : public BitcodeReaderBase {
  450. DiagnosticHandlerFunction DiagnosticHandler;
  451. /// Eventually points to the module index built during parsing.
  452. ModuleSummaryIndex *TheIndex = nullptr;
  453. /// Used to indicate whether caller only wants to check for the presence
  454. /// of the global value summary bitcode section. All blocks are skipped,
  455. /// but the SeenGlobalValSummary boolean is set.
  456. bool CheckGlobalValSummaryPresenceOnly = false;
  457. /// Indicates whether we have encountered a global value summary section
  458. /// yet during parsing, used when checking if file contains global value
  459. /// summary section.
  460. bool SeenGlobalValSummary = false;
  461. /// Indicates whether we have already parsed the VST, used for error checking.
  462. bool SeenValueSymbolTable = false;
  463. /// Set to the offset of the VST recorded in the MODULE_CODE_VSTOFFSET record.
  464. /// Used to enable on-demand parsing of the VST.
  465. uint64_t VSTOffset = 0;
  466. // Map to save ValueId to GUID association that was recorded in the
  467. // ValueSymbolTable. It is used after the VST is parsed to convert
  468. // call graph edges read from the function summary from referencing
  469. // callees by their ValueId to using the GUID instead, which is how
  470. // they are recorded in the summary index being built.
  471. // We save a second GUID which is the same as the first one, but ignoring the
  472. // linkage, i.e. for value other than local linkage they are identical.
  473. DenseMap<unsigned, std::pair<GlobalValue::GUID, GlobalValue::GUID>>
  474. ValueIdToCallGraphGUIDMap;
  475. /// Map populated during module path string table parsing, from the
  476. /// module ID to a string reference owned by the index's module
  477. /// path string table, used to correlate with combined index
  478. /// summary records.
  479. DenseMap<uint64_t, StringRef> ModuleIdMap;
  480. /// Original source file name recorded in a bitcode record.
  481. std::string SourceFileName;
  482. public:
  483. std::error_code error(const Twine &Message);
  484. ModuleSummaryIndexBitcodeReader(
  485. MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
  486. bool CheckGlobalValSummaryPresenceOnly = false);
  487. /// Check if the parser has encountered a summary section.
  488. bool foundGlobalValSummary() { return SeenGlobalValSummary; }
  489. /// \brief Main interface to parsing a bitcode buffer.
  490. /// \returns true if an error occurred.
  491. std::error_code parseSummaryIndexInto(ModuleSummaryIndex *I);
  492. private:
  493. std::error_code parseModule();
  494. std::error_code parseValueSymbolTable(
  495. uint64_t Offset,
  496. DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap);
  497. std::error_code parseEntireSummary();
  498. std::error_code parseModuleStringTable();
  499. std::pair<GlobalValue::GUID, GlobalValue::GUID>
  500. getGUIDFromValueId(unsigned ValueId);
  501. std::pair<GlobalValue::GUID, CalleeInfo::HotnessType>
  502. readCallGraphEdge(const SmallVector<uint64_t, 64> &Record, unsigned int &I,
  503. bool IsOldProfileFormat, bool HasProfile);
  504. };
  505. } // end anonymous namespace
  506. BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
  507. DiagnosticSeverity Severity,
  508. const Twine &Msg)
  509. : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
  510. void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
  511. static std::error_code error(const DiagnosticHandlerFunction &DiagnosticHandler,
  512. std::error_code EC, const Twine &Message) {
  513. BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
  514. DiagnosticHandler(DI);
  515. return EC;
  516. }
  517. static std::error_code error(LLVMContext &Context, std::error_code EC,
  518. const Twine &Message) {
  519. return error([&](const DiagnosticInfo &DI) { Context.diagnose(DI); }, EC,
  520. Message);
  521. }
  522. static std::error_code error(LLVMContext &Context, const Twine &Message) {
  523. return error(Context, make_error_code(BitcodeError::CorruptedBitcode),
  524. Message);
  525. }
  526. std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
  527. if (!ProducerIdentification.empty()) {
  528. return ::error(Context, make_error_code(E),
  529. Message + " (Producer: '" + ProducerIdentification +
  530. "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
  531. }
  532. return ::error(Context, make_error_code(E), Message);
  533. }
  534. std::error_code BitcodeReader::error(const Twine &Message) {
  535. if (!ProducerIdentification.empty()) {
  536. return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
  537. Message + " (Producer: '" + ProducerIdentification +
  538. "' Reader: 'LLVM " + LLVM_VERSION_STRING "')");
  539. }
  540. return ::error(Context, make_error_code(BitcodeError::CorruptedBitcode),
  541. Message);
  542. }
  543. BitcodeReader::BitcodeReader(MemoryBufferRef Buffer, LLVMContext &Context)
  544. : BitcodeReaderBase(Buffer), Context(Context), ValueList(Context),
  545. MetadataList(Context) {}
  546. std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
  547. if (WillMaterializeAllForwardRefs)
  548. return std::error_code();
  549. // Prevent recursion.
  550. WillMaterializeAllForwardRefs = true;
  551. while (!BasicBlockFwdRefQueue.empty()) {
  552. Function *F = BasicBlockFwdRefQueue.front();
  553. BasicBlockFwdRefQueue.pop_front();
  554. assert(F && "Expected valid function");
  555. if (!BasicBlockFwdRefs.count(F))
  556. // Already materialized.
  557. continue;
  558. // Check for a function that isn't materializable to prevent an infinite
  559. // loop. When parsing a blockaddress stored in a global variable, there
  560. // isn't a trivial way to check if a function will have a body without a
  561. // linear search through FunctionsWithBodies, so just check it here.
  562. if (!F->isMaterializable())
  563. return error("Never resolved function from blockaddress");
  564. // Try to materialize F.
  565. if (std::error_code EC = materialize(F))
  566. return EC;
  567. }
  568. assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
  569. // Reset state.
  570. WillMaterializeAllForwardRefs = false;
  571. return std::error_code();
  572. }
  573. //===----------------------------------------------------------------------===//
  574. // Helper functions to implement forward reference resolution, etc.
  575. //===----------------------------------------------------------------------===//
  576. /// Convert a string from a record into an std::string, return true on failure.
  577. template <typename StrTy>
  578. static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
  579. StrTy &Result) {
  580. if (Idx > Record.size())
  581. return true;
  582. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  583. Result += (char)Record[i];
  584. return false;
  585. }
  586. static bool hasImplicitComdat(size_t Val) {
  587. switch (Val) {
  588. default:
  589. return false;
  590. case 1: // Old WeakAnyLinkage
  591. case 4: // Old LinkOnceAnyLinkage
  592. case 10: // Old WeakODRLinkage
  593. case 11: // Old LinkOnceODRLinkage
  594. return true;
  595. }
  596. }
  597. static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
  598. switch (Val) {
  599. default: // Map unknown/new linkages to external
  600. case 0:
  601. return GlobalValue::ExternalLinkage;
  602. case 2:
  603. return GlobalValue::AppendingLinkage;
  604. case 3:
  605. return GlobalValue::InternalLinkage;
  606. case 5:
  607. return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
  608. case 6:
  609. return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
  610. case 7:
  611. return GlobalValue::ExternalWeakLinkage;
  612. case 8:
  613. return GlobalValue::CommonLinkage;
  614. case 9:
  615. return GlobalValue::PrivateLinkage;
  616. case 12:
  617. return GlobalValue::AvailableExternallyLinkage;
  618. case 13:
  619. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
  620. case 14:
  621. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
  622. case 15:
  623. return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
  624. case 1: // Old value with implicit comdat.
  625. case 16:
  626. return GlobalValue::WeakAnyLinkage;
  627. case 10: // Old value with implicit comdat.
  628. case 17:
  629. return GlobalValue::WeakODRLinkage;
  630. case 4: // Old value with implicit comdat.
  631. case 18:
  632. return GlobalValue::LinkOnceAnyLinkage;
  633. case 11: // Old value with implicit comdat.
  634. case 19:
  635. return GlobalValue::LinkOnceODRLinkage;
  636. }
  637. }
  638. /// Decode the flags for GlobalValue in the summary.
  639. static GlobalValueSummary::GVFlags getDecodedGVSummaryFlags(uint64_t RawFlags,
  640. uint64_t Version) {
  641. // Summary were not emitted before LLVM 3.9, we don't need to upgrade Linkage
  642. // like getDecodedLinkage() above. Any future change to the linkage enum and
  643. // to getDecodedLinkage() will need to be taken into account here as above.
  644. auto Linkage = GlobalValue::LinkageTypes(RawFlags & 0xF); // 4 bits
  645. RawFlags = RawFlags >> 4;
  646. bool NoRename = RawFlags & 0x1;
  647. bool IsNotViableToInline = RawFlags & 0x2;
  648. return GlobalValueSummary::GVFlags(Linkage, NoRename, IsNotViableToInline);
  649. }
  650. static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
  651. switch (Val) {
  652. default: // Map unknown visibilities to default.
  653. case 0: return GlobalValue::DefaultVisibility;
  654. case 1: return GlobalValue::HiddenVisibility;
  655. case 2: return GlobalValue::ProtectedVisibility;
  656. }
  657. }
  658. static GlobalValue::DLLStorageClassTypes
  659. getDecodedDLLStorageClass(unsigned Val) {
  660. switch (Val) {
  661. default: // Map unknown values to default.
  662. case 0: return GlobalValue::DefaultStorageClass;
  663. case 1: return GlobalValue::DLLImportStorageClass;
  664. case 2: return GlobalValue::DLLExportStorageClass;
  665. }
  666. }
  667. static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
  668. switch (Val) {
  669. case 0: return GlobalVariable::NotThreadLocal;
  670. default: // Map unknown non-zero value to general dynamic.
  671. case 1: return GlobalVariable::GeneralDynamicTLSModel;
  672. case 2: return GlobalVariable::LocalDynamicTLSModel;
  673. case 3: return GlobalVariable::InitialExecTLSModel;
  674. case 4: return GlobalVariable::LocalExecTLSModel;
  675. }
  676. }
  677. static GlobalVariable::UnnamedAddr getDecodedUnnamedAddrType(unsigned Val) {
  678. switch (Val) {
  679. default: // Map unknown to UnnamedAddr::None.
  680. case 0: return GlobalVariable::UnnamedAddr::None;
  681. case 1: return GlobalVariable::UnnamedAddr::Global;
  682. case 2: return GlobalVariable::UnnamedAddr::Local;
  683. }
  684. }
  685. static int getDecodedCastOpcode(unsigned Val) {
  686. switch (Val) {
  687. default: return -1;
  688. case bitc::CAST_TRUNC : return Instruction::Trunc;
  689. case bitc::CAST_ZEXT : return Instruction::ZExt;
  690. case bitc::CAST_SEXT : return Instruction::SExt;
  691. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  692. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  693. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  694. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  695. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  696. case bitc::CAST_FPEXT : return Instruction::FPExt;
  697. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  698. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  699. case bitc::CAST_BITCAST : return Instruction::BitCast;
  700. case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
  701. }
  702. }
  703. static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
  704. bool IsFP = Ty->isFPOrFPVectorTy();
  705. // BinOps are only valid for int/fp or vector of int/fp types
  706. if (!IsFP && !Ty->isIntOrIntVectorTy())
  707. return -1;
  708. switch (Val) {
  709. default:
  710. return -1;
  711. case bitc::BINOP_ADD:
  712. return IsFP ? Instruction::FAdd : Instruction::Add;
  713. case bitc::BINOP_SUB:
  714. return IsFP ? Instruction::FSub : Instruction::Sub;
  715. case bitc::BINOP_MUL:
  716. return IsFP ? Instruction::FMul : Instruction::Mul;
  717. case bitc::BINOP_UDIV:
  718. return IsFP ? -1 : Instruction::UDiv;
  719. case bitc::BINOP_SDIV:
  720. return IsFP ? Instruction::FDiv : Instruction::SDiv;
  721. case bitc::BINOP_UREM:
  722. return IsFP ? -1 : Instruction::URem;
  723. case bitc::BINOP_SREM:
  724. return IsFP ? Instruction::FRem : Instruction::SRem;
  725. case bitc::BINOP_SHL:
  726. return IsFP ? -1 : Instruction::Shl;
  727. case bitc::BINOP_LSHR:
  728. return IsFP ? -1 : Instruction::LShr;
  729. case bitc::BINOP_ASHR:
  730. return IsFP ? -1 : Instruction::AShr;
  731. case bitc::BINOP_AND:
  732. return IsFP ? -1 : Instruction::And;
  733. case bitc::BINOP_OR:
  734. return IsFP ? -1 : Instruction::Or;
  735. case bitc::BINOP_XOR:
  736. return IsFP ? -1 : Instruction::Xor;
  737. }
  738. }
  739. static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
  740. switch (Val) {
  741. default: return AtomicRMWInst::BAD_BINOP;
  742. case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
  743. case bitc::RMW_ADD: return AtomicRMWInst::Add;
  744. case bitc::RMW_SUB: return AtomicRMWInst::Sub;
  745. case bitc::RMW_AND: return AtomicRMWInst::And;
  746. case bitc::RMW_NAND: return AtomicRMWInst::Nand;
  747. case bitc::RMW_OR: return AtomicRMWInst::Or;
  748. case bitc::RMW_XOR: return AtomicRMWInst::Xor;
  749. case bitc::RMW_MAX: return AtomicRMWInst::Max;
  750. case bitc::RMW_MIN: return AtomicRMWInst::Min;
  751. case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
  752. case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
  753. }
  754. }
  755. static AtomicOrdering getDecodedOrdering(unsigned Val) {
  756. switch (Val) {
  757. case bitc::ORDERING_NOTATOMIC: return AtomicOrdering::NotAtomic;
  758. case bitc::ORDERING_UNORDERED: return AtomicOrdering::Unordered;
  759. case bitc::ORDERING_MONOTONIC: return AtomicOrdering::Monotonic;
  760. case bitc::ORDERING_ACQUIRE: return AtomicOrdering::Acquire;
  761. case bitc::ORDERING_RELEASE: return AtomicOrdering::Release;
  762. case bitc::ORDERING_ACQREL: return AtomicOrdering::AcquireRelease;
  763. default: // Map unknown orderings to sequentially-consistent.
  764. case bitc::ORDERING_SEQCST: return AtomicOrdering::SequentiallyConsistent;
  765. }
  766. }
  767. static SynchronizationScope getDecodedSynchScope(unsigned Val) {
  768. switch (Val) {
  769. case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
  770. default: // Map unknown scopes to cross-thread.
  771. case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
  772. }
  773. }
  774. static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
  775. switch (Val) {
  776. default: // Map unknown selection kinds to any.
  777. case bitc::COMDAT_SELECTION_KIND_ANY:
  778. return Comdat::Any;
  779. case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
  780. return Comdat::ExactMatch;
  781. case bitc::COMDAT_SELECTION_KIND_LARGEST:
  782. return Comdat::Largest;
  783. case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
  784. return Comdat::NoDuplicates;
  785. case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
  786. return Comdat::SameSize;
  787. }
  788. }
  789. static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
  790. FastMathFlags FMF;
  791. if (0 != (Val & FastMathFlags::UnsafeAlgebra))
  792. FMF.setUnsafeAlgebra();
  793. if (0 != (Val & FastMathFlags::NoNaNs))
  794. FMF.setNoNaNs();
  795. if (0 != (Val & FastMathFlags::NoInfs))
  796. FMF.setNoInfs();
  797. if (0 != (Val & FastMathFlags::NoSignedZeros))
  798. FMF.setNoSignedZeros();
  799. if (0 != (Val & FastMathFlags::AllowReciprocal))
  800. FMF.setAllowReciprocal();
  801. return FMF;
  802. }
  803. static void upgradeDLLImportExportLinkage(GlobalValue *GV, unsigned Val) {
  804. switch (Val) {
  805. case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
  806. case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
  807. }
  808. }
  809. namespace llvm {
  810. namespace {
  811. /// \brief A class for maintaining the slot number definition
  812. /// as a placeholder for the actual definition for forward constants defs.
  813. class ConstantPlaceHolder : public ConstantExpr {
  814. void operator=(const ConstantPlaceHolder &) = delete;
  815. public:
  816. // allocate space for exactly one operand
  817. void *operator new(size_t s) { return User::operator new(s, 1); }
  818. explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
  819. : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
  820. Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
  821. }
  822. /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
  823. static bool classof(const Value *V) {
  824. return isa<ConstantExpr>(V) &&
  825. cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
  826. }
  827. /// Provide fast operand accessors
  828. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  829. };
  830. } // end anonymous namespace
  831. // FIXME: can we inherit this from ConstantExpr?
  832. template <>
  833. struct OperandTraits<ConstantPlaceHolder> :
  834. public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
  835. };
  836. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
  837. } // end namespace llvm
  838. void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
  839. if (Idx == size()) {
  840. push_back(V);
  841. return;
  842. }
  843. if (Idx >= size())
  844. resize(Idx+1);
  845. WeakVH &OldV = ValuePtrs[Idx];
  846. if (!OldV) {
  847. OldV = V;
  848. return;
  849. }
  850. // Handle constants and non-constants (e.g. instrs) differently for
  851. // efficiency.
  852. if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
  853. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  854. OldV = V;
  855. } else {
  856. // If there was a forward reference to this value, replace it.
  857. Value *PrevVal = OldV;
  858. OldV->replaceAllUsesWith(V);
  859. delete PrevVal;
  860. }
  861. }
  862. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  863. Type *Ty) {
  864. if (Idx >= size())
  865. resize(Idx + 1);
  866. if (Value *V = ValuePtrs[Idx]) {
  867. if (Ty != V->getType())
  868. report_fatal_error("Type mismatch in constant table!");
  869. return cast<Constant>(V);
  870. }
  871. // Create and return a placeholder, which will later be RAUW'd.
  872. Constant *C = new ConstantPlaceHolder(Ty, Context);
  873. ValuePtrs[Idx] = C;
  874. return C;
  875. }
  876. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
  877. // Bail out for a clearly invalid value. This would make us call resize(0)
  878. if (Idx == std::numeric_limits<unsigned>::max())
  879. return nullptr;
  880. if (Idx >= size())
  881. resize(Idx + 1);
  882. if (Value *V = ValuePtrs[Idx]) {
  883. // If the types don't match, it's invalid.
  884. if (Ty && Ty != V->getType())
  885. return nullptr;
  886. return V;
  887. }
  888. // No type specified, must be invalid reference.
  889. if (!Ty) return nullptr;
  890. // Create and return a placeholder, which will later be RAUW'd.
  891. Value *V = new Argument(Ty);
  892. ValuePtrs[Idx] = V;
  893. return V;
  894. }
  895. /// Once all constants are read, this method bulk resolves any forward
  896. /// references. The idea behind this is that we sometimes get constants (such
  897. /// as large arrays) which reference *many* forward ref constants. Replacing
  898. /// each of these causes a lot of thrashing when building/reuniquing the
  899. /// constant. Instead of doing this, we look at all the uses and rewrite all
  900. /// the place holders at once for any constant that uses a placeholder.
  901. void BitcodeReaderValueList::resolveConstantForwardRefs() {
  902. // Sort the values by-pointer so that they are efficient to look up with a
  903. // binary search.
  904. std::sort(ResolveConstants.begin(), ResolveConstants.end());
  905. SmallVector<Constant*, 64> NewOps;
  906. while (!ResolveConstants.empty()) {
  907. Value *RealVal = operator[](ResolveConstants.back().second);
  908. Constant *Placeholder = ResolveConstants.back().first;
  909. ResolveConstants.pop_back();
  910. // Loop over all users of the placeholder, updating them to reference the
  911. // new value. If they reference more than one placeholder, update them all
  912. // at once.
  913. while (!Placeholder->use_empty()) {
  914. auto UI = Placeholder->user_begin();
  915. User *U = *UI;
  916. // If the using object isn't uniqued, just update the operands. This
  917. // handles instructions and initializers for global variables.
  918. if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
  919. UI.getUse().set(RealVal);
  920. continue;
  921. }
  922. // Otherwise, we have a constant that uses the placeholder. Replace that
  923. // constant with a new constant that has *all* placeholder uses updated.
  924. Constant *UserC = cast<Constant>(U);
  925. for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
  926. I != E; ++I) {
  927. Value *NewOp;
  928. if (!isa<ConstantPlaceHolder>(*I)) {
  929. // Not a placeholder reference.
  930. NewOp = *I;
  931. } else if (*I == Placeholder) {
  932. // Common case is that it just references this one placeholder.
  933. NewOp = RealVal;
  934. } else {
  935. // Otherwise, look up the placeholder in ResolveConstants.
  936. ResolveConstantsTy::iterator It =
  937. std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
  938. std::pair<Constant*, unsigned>(cast<Constant>(*I),
  939. 0));
  940. assert(It != ResolveConstants.end() && It->first == *I);
  941. NewOp = operator[](It->second);
  942. }
  943. NewOps.push_back(cast<Constant>(NewOp));
  944. }
  945. // Make the new constant.
  946. Constant *NewC;
  947. if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
  948. NewC = ConstantArray::get(UserCA->getType(), NewOps);
  949. } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
  950. NewC = ConstantStruct::get(UserCS->getType(), NewOps);
  951. } else if (isa<ConstantVector>(UserC)) {
  952. NewC = ConstantVector::get(NewOps);
  953. } else {
  954. assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
  955. NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
  956. }
  957. UserC->replaceAllUsesWith(NewC);
  958. UserC->destroyConstant();
  959. NewOps.clear();
  960. }
  961. // Update all ValueHandles, they should be the only users at this point.
  962. Placeholder->replaceAllUsesWith(RealVal);
  963. delete Placeholder;
  964. }
  965. }
  966. void BitcodeReaderMetadataList::assignValue(Metadata *MD, unsigned Idx) {
  967. if (Idx == size()) {
  968. push_back(MD);
  969. return;
  970. }
  971. if (Idx >= size())
  972. resize(Idx+1);
  973. TrackingMDRef &OldMD = MetadataPtrs[Idx];
  974. if (!OldMD) {
  975. OldMD.reset(MD);
  976. return;
  977. }
  978. // If there was a forward reference to this value, replace it.
  979. TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
  980. PrevMD->replaceAllUsesWith(MD);
  981. --NumFwdRefs;
  982. }
  983. Metadata *BitcodeReaderMetadataList::getMetadataFwdRef(unsigned Idx) {
  984. if (Idx >= size())
  985. resize(Idx + 1);
  986. if (Metadata *MD = MetadataPtrs[Idx])
  987. return MD;
  988. // Track forward refs to be resolved later.
  989. if (AnyFwdRefs) {
  990. MinFwdRef = std::min(MinFwdRef, Idx);
  991. MaxFwdRef = std::max(MaxFwdRef, Idx);
  992. } else {
  993. AnyFwdRefs = true;
  994. MinFwdRef = MaxFwdRef = Idx;
  995. }
  996. ++NumFwdRefs;
  997. // Create and return a placeholder, which will later be RAUW'd.
  998. Metadata *MD = MDNode::getTemporary(Context, None).release();
  999. MetadataPtrs[Idx].reset(MD);
  1000. return MD;
  1001. }
  1002. Metadata *BitcodeReaderMetadataList::getMetadataIfResolved(unsigned Idx) {
  1003. Metadata *MD = lookup(Idx);
  1004. if (auto *N = dyn_cast_or_null<MDNode>(MD))
  1005. if (!N->isResolved())
  1006. return nullptr;
  1007. return MD;
  1008. }
  1009. MDNode *BitcodeReaderMetadataList::getMDNodeFwdRefOrNull(unsigned Idx) {
  1010. return dyn_cast_or_null<MDNode>(getMetadataFwdRef(Idx));
  1011. }
  1012. void BitcodeReaderMetadataList::tryToResolveCycles() {
  1013. if (NumFwdRefs)
  1014. // Still forward references... can't resolve cycles.
  1015. return;
  1016. bool DidReplaceTypeRefs = false;
  1017. // Give up on finding a full definition for any forward decls that remain.
  1018. for (const auto &Ref : OldTypeRefs.FwdDecls)
  1019. OldTypeRefs.Final.insert(Ref);
  1020. OldTypeRefs.FwdDecls.clear();
  1021. // Upgrade from old type ref arrays. In strange cases, this could add to
  1022. // OldTypeRefs.Unknown.
  1023. for (const auto &Array : OldTypeRefs.Arrays) {
  1024. DidReplaceTypeRefs = true;
  1025. Array.second->replaceAllUsesWith(resolveTypeRefArray(Array.first.get()));
  1026. }
  1027. OldTypeRefs.Arrays.clear();
  1028. // Replace old string-based type refs with the resolved node, if possible.
  1029. // If we haven't seen the node, leave it to the verifier to complain about
  1030. // the invalid string reference.
  1031. for (const auto &Ref : OldTypeRefs.Unknown) {
  1032. DidReplaceTypeRefs = true;
  1033. if (DICompositeType *CT = OldTypeRefs.Final.lookup(Ref.first))
  1034. Ref.second->replaceAllUsesWith(CT);
  1035. else
  1036. Ref.second->replaceAllUsesWith(Ref.first);
  1037. }
  1038. OldTypeRefs.Unknown.clear();
  1039. // Make sure all the upgraded types are resolved.
  1040. if (DidReplaceTypeRefs) {
  1041. AnyFwdRefs = true;
  1042. MinFwdRef = 0;
  1043. MaxFwdRef = MetadataPtrs.size() - 1;
  1044. }
  1045. if (!AnyFwdRefs)
  1046. // Nothing to do.
  1047. return;
  1048. // Resolve any cycles.
  1049. for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
  1050. auto &MD = MetadataPtrs[I];
  1051. auto *N = dyn_cast_or_null<MDNode>(MD);
  1052. if (!N)
  1053. continue;
  1054. assert(!N->isTemporary() && "Unexpected forward reference");
  1055. N->resolveCycles();
  1056. }
  1057. // Make sure we return early again until there's another forward ref.
  1058. AnyFwdRefs = false;
  1059. }
  1060. void BitcodeReaderMetadataList::addTypeRef(MDString &UUID,
  1061. DICompositeType &CT) {
  1062. assert(CT.getRawIdentifier() == &UUID && "Mismatched UUID");
  1063. if (CT.isForwardDecl())
  1064. OldTypeRefs.FwdDecls.insert(std::make_pair(&UUID, &CT));
  1065. else
  1066. OldTypeRefs.Final.insert(std::make_pair(&UUID, &CT));
  1067. }
  1068. Metadata *BitcodeReaderMetadataList::upgradeTypeRef(Metadata *MaybeUUID) {
  1069. auto *UUID = dyn_cast_or_null<MDString>(MaybeUUID);
  1070. if (LLVM_LIKELY(!UUID))
  1071. return MaybeUUID;
  1072. if (auto *CT = OldTypeRefs.Final.lookup(UUID))
  1073. return CT;
  1074. auto &Ref = OldTypeRefs.Unknown[UUID];
  1075. if (!Ref)
  1076. Ref = MDNode::getTemporary(Context, None);
  1077. return Ref.get();
  1078. }
  1079. Metadata *BitcodeReaderMetadataList::upgradeTypeRefArray(Metadata *MaybeTuple) {
  1080. auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
  1081. if (!Tuple || Tuple->isDistinct())
  1082. return MaybeTuple;
  1083. // Look through the array immediately if possible.
  1084. if (!Tuple->isTemporary())
  1085. return resolveTypeRefArray(Tuple);
  1086. // Create and return a placeholder to use for now. Eventually
  1087. // resolveTypeRefArrays() will be resolve this forward reference.
  1088. OldTypeRefs.Arrays.emplace_back(
  1089. std::piecewise_construct, std::forward_as_tuple(Tuple),
  1090. std::forward_as_tuple(MDTuple::getTemporary(Context, None)));
  1091. return OldTypeRefs.Arrays.back().second.get();
  1092. }
  1093. Metadata *BitcodeReaderMetadataList::resolveTypeRefArray(Metadata *MaybeTuple) {
  1094. auto *Tuple = dyn_cast_or_null<MDTuple>(MaybeTuple);
  1095. if (!Tuple || Tuple->isDistinct())
  1096. return MaybeTuple;
  1097. // Look through the DITypeRefArray, upgrading each DITypeRef.
  1098. SmallVector<Metadata *, 32> Ops;
  1099. Ops.reserve(Tuple->getNumOperands());
  1100. for (Metadata *MD : Tuple->operands())
  1101. Ops.push_back(upgradeTypeRef(MD));
  1102. return MDTuple::get(Context, Ops);
  1103. }
  1104. Type *BitcodeReader::getTypeByID(unsigned ID) {
  1105. // The type table size is always specified correctly.
  1106. if (ID >= TypeList.size())
  1107. return nullptr;
  1108. if (Type *Ty = TypeList[ID])
  1109. return Ty;
  1110. // If we have a forward reference, the only possible case is when it is to a
  1111. // named struct. Just create a placeholder for now.
  1112. return TypeList[ID] = createIdentifiedStructType(Context);
  1113. }
  1114. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
  1115. StringRef Name) {
  1116. auto *Ret = StructType::create(Context, Name);
  1117. IdentifiedStructTypes.push_back(Ret);
  1118. return Ret;
  1119. }
  1120. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
  1121. auto *Ret = StructType::create(Context);
  1122. IdentifiedStructTypes.push_back(Ret);
  1123. return Ret;
  1124. }
  1125. //===----------------------------------------------------------------------===//
  1126. // Functions for parsing blocks from the bitcode file
  1127. //===----------------------------------------------------------------------===//
  1128. static uint64_t getRawAttributeMask(Attribute::AttrKind Val) {
  1129. switch (Val) {
  1130. case Attribute::EndAttrKinds:
  1131. llvm_unreachable("Synthetic enumerators which should never get here");
  1132. case Attribute::None: return 0;
  1133. case Attribute::ZExt: return 1 << 0;
  1134. case Attribute::SExt: return 1 << 1;
  1135. case Attribute::NoReturn: return 1 << 2;
  1136. case Attribute::InReg: return 1 << 3;
  1137. case Attribute::StructRet: return 1 << 4;
  1138. case Attribute::NoUnwind: return 1 << 5;
  1139. case Attribute::NoAlias: return 1 << 6;
  1140. case Attribute::ByVal: return 1 << 7;
  1141. case Attribute::Nest: return 1 << 8;
  1142. case Attribute::ReadNone: return 1 << 9;
  1143. case Attribute::ReadOnly: return 1 << 10;
  1144. case Attribute::NoInline: return 1 << 11;
  1145. case Attribute::AlwaysInline: return 1 << 12;
  1146. case Attribute::OptimizeForSize: return 1 << 13;
  1147. case Attribute::StackProtect: return 1 << 14;
  1148. case Attribute::StackProtectReq: return 1 << 15;
  1149. case Attribute::Alignment: return 31 << 16;
  1150. case Attribute::NoCapture: return 1 << 21;
  1151. case Attribute::NoRedZone: return 1 << 22;
  1152. case Attribute::NoImplicitFloat: return 1 << 23;
  1153. case Attribute::Naked: return 1 << 24;
  1154. case Attribute::InlineHint: return 1 << 25;
  1155. case Attribute::StackAlignment: return 7 << 26;
  1156. case Attribute::ReturnsTwice: return 1 << 29;
  1157. case Attribute::UWTable: return 1 << 30;
  1158. case Attribute::NonLazyBind: return 1U << 31;
  1159. case Attribute::SanitizeAddress: return 1ULL << 32;
  1160. case Attribute::MinSize: return 1ULL << 33;
  1161. case Attribute::NoDuplicate: return 1ULL << 34;
  1162. case Attribute::StackProtectStrong: return 1ULL << 35;
  1163. case Attribute::SanitizeThread: return 1ULL << 36;
  1164. case Attribute::SanitizeMemory: return 1ULL << 37;
  1165. case Attribute::NoBuiltin: return 1ULL << 38;
  1166. case Attribute::Returned: return 1ULL << 39;
  1167. case Attribute::Cold: return 1ULL << 40;
  1168. case Attribute::Builtin: return 1ULL << 41;
  1169. case Attribute::OptimizeNone: return 1ULL << 42;
  1170. case Attribute::InAlloca: return 1ULL << 43;
  1171. case Attribute::NonNull: return 1ULL << 44;
  1172. case Attribute::JumpTable: return 1ULL << 45;
  1173. case Attribute::Convergent: return 1ULL << 46;
  1174. case Attribute::SafeStack: return 1ULL << 47;
  1175. case Attribute::NoRecurse: return 1ULL << 48;
  1176. case Attribute::InaccessibleMemOnly: return 1ULL << 49;
  1177. case Attribute::InaccessibleMemOrArgMemOnly: return 1ULL << 50;
  1178. case Attribute::SwiftSelf: return 1ULL << 51;
  1179. case Attribute::SwiftError: return 1ULL << 52;
  1180. case Attribute::WriteOnly: return 1ULL << 53;
  1181. case Attribute::Dereferenceable:
  1182. llvm_unreachable("dereferenceable attribute not supported in raw format");
  1183. break;
  1184. case Attribute::DereferenceableOrNull:
  1185. llvm_unreachable("dereferenceable_or_null attribute not supported in raw "
  1186. "format");
  1187. break;
  1188. case Attribute::ArgMemOnly:
  1189. llvm_unreachable("argmemonly attribute not supported in raw format");
  1190. break;
  1191. case Attribute::AllocSize:
  1192. llvm_unreachable("allocsize not supported in raw format");
  1193. break;
  1194. }
  1195. llvm_unreachable("Unsupported attribute type");
  1196. }
  1197. static void addRawAttributeValue(AttrBuilder &B, uint64_t Val) {
  1198. if (!Val) return;
  1199. for (Attribute::AttrKind I = Attribute::None; I != Attribute::EndAttrKinds;
  1200. I = Attribute::AttrKind(I + 1)) {
  1201. if (I == Attribute::Dereferenceable ||
  1202. I == Attribute::DereferenceableOrNull ||
  1203. I == Attribute::ArgMemOnly ||
  1204. I == Attribute::AllocSize)
  1205. continue;
  1206. if (uint64_t A = (Val & getRawAttributeMask(I))) {
  1207. if (I == Attribute::Alignment)
  1208. B.addAlignmentAttr(1ULL << ((A >> 16) - 1));
  1209. else if (I == Attribute::StackAlignment)
  1210. B.addStackAlignmentAttr(1ULL << ((A >> 26)-1));
  1211. else
  1212. B.addAttribute(I);
  1213. }
  1214. }
  1215. }
  1216. /// \brief This fills an AttrBuilder object with the LLVM attributes that have
  1217. /// been decoded from the given integer. This function must stay in sync with
  1218. /// 'encodeLLVMAttributesForBitcode'.
  1219. static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
  1220. uint64_t EncodedAttrs) {
  1221. // FIXME: Remove in 4.0.
  1222. // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
  1223. // the bits above 31 down by 11 bits.
  1224. unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
  1225. assert((!Alignment || isPowerOf2_32(Alignment)) &&
  1226. "Alignment must be a power of two.");
  1227. if (Alignment)
  1228. B.addAlignmentAttr(Alignment);
  1229. addRawAttributeValue(B, ((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
  1230. (EncodedAttrs & 0xffff));
  1231. }
  1232. std::error_code BitcodeReader::parseAttributeBlock() {
  1233. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  1234. return error("Invalid record");
  1235. if (!MAttributes.empty())
  1236. return error("Invalid multiple blocks");
  1237. SmallVector<uint64_t, 64> Record;
  1238. SmallVector<AttributeSet, 8> Attrs;
  1239. // Read all the records.
  1240. while (true) {
  1241. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1242. switch (Entry.Kind) {
  1243. case BitstreamEntry::SubBlock: // Handled for us already.
  1244. case BitstreamEntry::Error:
  1245. return error("Malformed block");
  1246. case BitstreamEntry::EndBlock:
  1247. return std::error_code();
  1248. case BitstreamEntry::Record:
  1249. // The interesting case.
  1250. break;
  1251. }
  1252. // Read a record.
  1253. Record.clear();
  1254. switch (Stream.readRecord(Entry.ID, Record)) {
  1255. default: // Default behavior: ignore.
  1256. break;
  1257. case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
  1258. // FIXME: Remove in 4.0.
  1259. if (Record.size() & 1)
  1260. return error("Invalid record");
  1261. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  1262. AttrBuilder B;
  1263. decodeLLVMAttributesForBitcode(B, Record[i+1]);
  1264. Attrs.push_back(AttributeSet::get(Context, Record[i], B));
  1265. }
  1266. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  1267. Attrs.clear();
  1268. break;
  1269. }
  1270. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
  1271. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  1272. Attrs.push_back(MAttributeGroups[Record[i]]);
  1273. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  1274. Attrs.clear();
  1275. break;
  1276. }
  1277. }
  1278. }
  1279. }
  1280. // Returns Attribute::None on unrecognized codes.
  1281. static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
  1282. switch (Code) {
  1283. default:
  1284. return Attribute::None;
  1285. case bitc::ATTR_KIND_ALIGNMENT:
  1286. return Attribute::Alignment;
  1287. case bitc::ATTR_KIND_ALWAYS_INLINE:
  1288. return Attribute::AlwaysInline;
  1289. case bitc::ATTR_KIND_ARGMEMONLY:
  1290. return Attribute::ArgMemOnly;
  1291. case bitc::ATTR_KIND_BUILTIN:
  1292. return Attribute::Builtin;
  1293. case bitc::ATTR_KIND_BY_VAL:
  1294. return Attribute::ByVal;
  1295. case bitc::ATTR_KIND_IN_ALLOCA:
  1296. return Attribute::InAlloca;
  1297. case bitc::ATTR_KIND_COLD:
  1298. return Attribute::Cold;
  1299. case bitc::ATTR_KIND_CONVERGENT:
  1300. return Attribute::Convergent;
  1301. case bitc::ATTR_KIND_INACCESSIBLEMEM_ONLY:
  1302. return Attribute::InaccessibleMemOnly;
  1303. case bitc::ATTR_KIND_INACCESSIBLEMEM_OR_ARGMEMONLY:
  1304. return Attribute::InaccessibleMemOrArgMemOnly;
  1305. case bitc::ATTR_KIND_INLINE_HINT:
  1306. return Attribute::InlineHint;
  1307. case bitc::ATTR_KIND_IN_REG:
  1308. return Attribute::InReg;
  1309. case bitc::ATTR_KIND_JUMP_TABLE:
  1310. return Attribute::JumpTable;
  1311. case bitc::ATTR_KIND_MIN_SIZE:
  1312. return Attribute::MinSize;
  1313. case bitc::ATTR_KIND_NAKED:
  1314. return Attribute::Naked;
  1315. case bitc::ATTR_KIND_NEST:
  1316. return Attribute::Nest;
  1317. case bitc::ATTR_KIND_NO_ALIAS:
  1318. return Attribute::NoAlias;
  1319. case bitc::ATTR_KIND_NO_BUILTIN:
  1320. return Attribute::NoBuiltin;
  1321. case bitc::ATTR_KIND_NO_CAPTURE:
  1322. return Attribute::NoCapture;
  1323. case bitc::ATTR_KIND_NO_DUPLICATE:
  1324. return Attribute::NoDuplicate;
  1325. case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
  1326. return Attribute::NoImplicitFloat;
  1327. case bitc::ATTR_KIND_NO_INLINE:
  1328. return Attribute::NoInline;
  1329. case bitc::ATTR_KIND_NO_RECURSE:
  1330. return Attribute::NoRecurse;
  1331. case bitc::ATTR_KIND_NON_LAZY_BIND:
  1332. return Attribute::NonLazyBind;
  1333. case bitc::ATTR_KIND_NON_NULL:
  1334. return Attribute::NonNull;
  1335. case bitc::ATTR_KIND_DEREFERENCEABLE:
  1336. return Attribute::Dereferenceable;
  1337. case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
  1338. return Attribute::DereferenceableOrNull;
  1339. case bitc::ATTR_KIND_ALLOC_SIZE:
  1340. return Attribute::AllocSize;
  1341. case bitc::ATTR_KIND_NO_RED_ZONE:
  1342. return Attribute::NoRedZone;
  1343. case bitc::ATTR_KIND_NO_RETURN:
  1344. return Attribute::NoReturn;
  1345. case bitc::ATTR_KIND_NO_UNWIND:
  1346. return Attribute::NoUnwind;
  1347. case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
  1348. return Attribute::OptimizeForSize;
  1349. case bitc::ATTR_KIND_OPTIMIZE_NONE:
  1350. return Attribute::OptimizeNone;
  1351. case bitc::ATTR_KIND_READ_NONE:
  1352. return Attribute::ReadNone;
  1353. case bitc::ATTR_KIND_READ_ONLY:
  1354. return Attribute::ReadOnly;
  1355. case bitc::ATTR_KIND_RETURNED:
  1356. return Attribute::Returned;
  1357. case bitc::ATTR_KIND_RETURNS_TWICE:
  1358. return Attribute::ReturnsTwice;
  1359. case bitc::ATTR_KIND_S_EXT:
  1360. return Attribute::SExt;
  1361. case bitc::ATTR_KIND_STACK_ALIGNMENT:
  1362. return Attribute::StackAlignment;
  1363. case bitc::ATTR_KIND_STACK_PROTECT:
  1364. return Attribute::StackProtect;
  1365. case bitc::ATTR_KIND_STACK_PROTECT_REQ:
  1366. return Attribute::StackProtectReq;
  1367. case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
  1368. return Attribute::StackProtectStrong;
  1369. case bitc::ATTR_KIND_SAFESTACK:
  1370. return Attribute::SafeStack;
  1371. case bitc::ATTR_KIND_STRUCT_RET:
  1372. return Attribute::StructRet;
  1373. case bitc::ATTR_KIND_SANITIZE_ADDRESS:
  1374. return Attribute::SanitizeAddress;
  1375. case bitc::ATTR_KIND_SANITIZE_THREAD:
  1376. return Attribute::SanitizeThread;
  1377. case bitc::ATTR_KIND_SANITIZE_MEMORY:
  1378. return Attribute::SanitizeMemory;
  1379. case bitc::ATTR_KIND_SWIFT_ERROR:
  1380. return Attribute::SwiftError;
  1381. case bitc::ATTR_KIND_SWIFT_SELF:
  1382. return Attribute::SwiftSelf;
  1383. case bitc::ATTR_KIND_UW_TABLE:
  1384. return Attribute::UWTable;
  1385. case bitc::ATTR_KIND_WRITEONLY:
  1386. return Attribute::WriteOnly;
  1387. case bitc::ATTR_KIND_Z_EXT:
  1388. return Attribute::ZExt;
  1389. }
  1390. }
  1391. std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
  1392. unsigned &Alignment) {
  1393. // Note: Alignment in bitcode files is incremented by 1, so that zero
  1394. // can be used for default alignment.
  1395. if (Exponent > Value::MaxAlignmentExponent + 1)
  1396. return error("Invalid alignment value");
  1397. Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
  1398. return std::error_code();
  1399. }
  1400. std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
  1401. Attribute::AttrKind *Kind) {
  1402. *Kind = getAttrFromCode(Code);
  1403. if (*Kind == Attribute::None)
  1404. return error(BitcodeError::CorruptedBitcode,
  1405. "Unknown attribute kind (" + Twine(Code) + ")");
  1406. return std::error_code();
  1407. }
  1408. std::error_code BitcodeReader::parseAttributeGroupBlock() {
  1409. if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
  1410. return error("Invalid record");
  1411. if (!MAttributeGroups.empty())
  1412. return error("Invalid multiple blocks");
  1413. SmallVector<uint64_t, 64> Record;
  1414. // Read all the records.
  1415. while (true) {
  1416. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1417. switch (Entry.Kind) {
  1418. case BitstreamEntry::SubBlock: // Handled for us already.
  1419. case BitstreamEntry::Error:
  1420. return error("Malformed block");
  1421. case BitstreamEntry::EndBlock:
  1422. return std::error_code();
  1423. case BitstreamEntry::Record:
  1424. // The interesting case.
  1425. break;
  1426. }
  1427. // Read a record.
  1428. Record.clear();
  1429. switch (Stream.readRecord(Entry.ID, Record)) {
  1430. default: // Default behavior: ignore.
  1431. break;
  1432. case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
  1433. if (Record.size() < 3)
  1434. return error("Invalid record");
  1435. uint64_t GrpID = Record[0];
  1436. uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
  1437. AttrBuilder B;
  1438. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1439. if (Record[i] == 0) { // Enum attribute
  1440. Attribute::AttrKind Kind;
  1441. if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
  1442. return EC;
  1443. B.addAttribute(Kind);
  1444. } else if (Record[i] == 1) { // Integer attribute
  1445. Attribute::AttrKind Kind;
  1446. if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
  1447. return EC;
  1448. if (Kind == Attribute::Alignment)
  1449. B.addAlignmentAttr(Record[++i]);
  1450. else if (Kind == Attribute::StackAlignment)
  1451. B.addStackAlignmentAttr(Record[++i]);
  1452. else if (Kind == Attribute::Dereferenceable)
  1453. B.addDereferenceableAttr(Record[++i]);
  1454. else if (Kind == Attribute::DereferenceableOrNull)
  1455. B.addDereferenceableOrNullAttr(Record[++i]);
  1456. else if (Kind == Attribute::AllocSize)
  1457. B.addAllocSizeAttrFromRawRepr(Record[++i]);
  1458. } else { // String attribute
  1459. assert((Record[i] == 3 || Record[i] == 4) &&
  1460. "Invalid attribute group entry");
  1461. bool HasValue = (Record[i++] == 4);
  1462. SmallString<64> KindStr;
  1463. SmallString<64> ValStr;
  1464. while (Record[i] != 0 && i != e)
  1465. KindStr += Record[i++];
  1466. assert(Record[i] == 0 && "Kind string not null terminated");
  1467. if (HasValue) {
  1468. // Has a value associated with it.
  1469. ++i; // Skip the '0' that terminates the "kind" string.
  1470. while (Record[i] != 0 && i != e)
  1471. ValStr += Record[i++];
  1472. assert(Record[i] == 0 && "Value string not null terminated");
  1473. }
  1474. B.addAttribute(KindStr.str(), ValStr.str());
  1475. }
  1476. }
  1477. MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
  1478. break;
  1479. }
  1480. }
  1481. }
  1482. }
  1483. std::error_code BitcodeReader::parseTypeTable() {
  1484. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
  1485. return error("Invalid record");
  1486. return parseTypeTableBody();
  1487. }
  1488. std::error_code BitcodeReader::parseTypeTableBody() {
  1489. if (!TypeList.empty())
  1490. return error("Invalid multiple blocks");
  1491. SmallVector<uint64_t, 64> Record;
  1492. unsigned NumRecords = 0;
  1493. SmallString<64> TypeName;
  1494. // Read all the records for this type table.
  1495. while (true) {
  1496. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1497. switch (Entry.Kind) {
  1498. case BitstreamEntry::SubBlock: // Handled for us already.
  1499. case BitstreamEntry::Error:
  1500. return error("Malformed block");
  1501. case BitstreamEntry::EndBlock:
  1502. if (NumRecords != TypeList.size())
  1503. return error("Malformed block");
  1504. return std::error_code();
  1505. case BitstreamEntry::Record:
  1506. // The interesting case.
  1507. break;
  1508. }
  1509. // Read a record.
  1510. Record.clear();
  1511. Type *ResultTy = nullptr;
  1512. switch (Stream.readRecord(Entry.ID, Record)) {
  1513. default:
  1514. return error("Invalid value");
  1515. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  1516. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  1517. // type list. This allows us to reserve space.
  1518. if (Record.size() < 1)
  1519. return error("Invalid record");
  1520. TypeList.resize(Record[0]);
  1521. continue;
  1522. case bitc::TYPE_CODE_VOID: // VOID
  1523. ResultTy = Type::getVoidTy(Context);
  1524. break;
  1525. case bitc::TYPE_CODE_HALF: // HALF
  1526. ResultTy = Type::getHalfTy(Context);
  1527. break;
  1528. case bitc::TYPE_CODE_FLOAT: // FLOAT
  1529. ResultTy = Type::getFloatTy(Context);
  1530. break;
  1531. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  1532. ResultTy = Type::getDoubleTy(Context);
  1533. break;
  1534. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  1535. ResultTy = Type::getX86_FP80Ty(Context);
  1536. break;
  1537. case bitc::TYPE_CODE_FP128: // FP128
  1538. ResultTy = Type::getFP128Ty(Context);
  1539. break;
  1540. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  1541. ResultTy = Type::getPPC_FP128Ty(Context);
  1542. break;
  1543. case bitc::TYPE_CODE_LABEL: // LABEL
  1544. ResultTy = Type::getLabelTy(Context);
  1545. break;
  1546. case bitc::TYPE_CODE_METADATA: // METADATA
  1547. ResultTy = Type::getMetadataTy(Context);
  1548. break;
  1549. case bitc::TYPE_CODE_X86_MMX: // X86_MMX
  1550. ResultTy = Type::getX86_MMXTy(Context);
  1551. break;
  1552. case bitc::TYPE_CODE_TOKEN: // TOKEN
  1553. ResultTy = Type::getTokenTy(Context);
  1554. break;
  1555. case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
  1556. if (Record.size() < 1)
  1557. return error("Invalid record");
  1558. uint64_t NumBits = Record[0];
  1559. if (NumBits < IntegerType::MIN_INT_BITS ||
  1560. NumBits > IntegerType::MAX_INT_BITS)
  1561. return error("Bitwidth for integer type out of range");
  1562. ResultTy = IntegerType::get(Context, NumBits);
  1563. break;
  1564. }
  1565. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  1566. // [pointee type, address space]
  1567. if (Record.size() < 1)
  1568. return error("Invalid record");
  1569. unsigned AddressSpace = 0;
  1570. if (Record.size() == 2)
  1571. AddressSpace = Record[1];
  1572. ResultTy = getTypeByID(Record[0]);
  1573. if (!ResultTy ||
  1574. !PointerType::isValidElementType(ResultTy))
  1575. return error("Invalid type");
  1576. ResultTy = PointerType::get(ResultTy, AddressSpace);
  1577. break;
  1578. }
  1579. case bitc::TYPE_CODE_FUNCTION_OLD: {
  1580. // FIXME: attrid is dead, remove it in LLVM 4.0
  1581. // FUNCTION: [vararg, attrid, retty, paramty x N]
  1582. if (Record.size() < 3)
  1583. return error("Invalid record");
  1584. SmallVector<Type*, 8> ArgTys;
  1585. for (unsigned i = 3, e = Record.size(); i != e; ++i) {
  1586. if (Type *T = getTypeByID(Record[i]))
  1587. ArgTys.push_back(T);
  1588. else
  1589. break;
  1590. }
  1591. ResultTy = getTypeByID(Record[2]);
  1592. if (!ResultTy || ArgTys.size() < Record.size()-3)
  1593. return error("Invalid type");
  1594. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1595. break;
  1596. }
  1597. case bitc::TYPE_CODE_FUNCTION: {
  1598. // FUNCTION: [vararg, retty, paramty x N]
  1599. if (Record.size() < 2)
  1600. return error("Invalid record");
  1601. SmallVector<Type*, 8> ArgTys;
  1602. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1603. if (Type *T = getTypeByID(Record[i])) {
  1604. if (!FunctionType::isValidArgumentType(T))
  1605. return error("Invalid function argument type");
  1606. ArgTys.push_back(T);
  1607. }
  1608. else
  1609. break;
  1610. }
  1611. ResultTy = getTypeByID(Record[1]);
  1612. if (!ResultTy || ArgTys.size() < Record.size()-2)
  1613. return error("Invalid type");
  1614. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1615. break;
  1616. }
  1617. case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
  1618. if (Record.size() < 1)
  1619. return error("Invalid record");
  1620. SmallVector<Type*, 8> EltTys;
  1621. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1622. if (Type *T = getTypeByID(Record[i]))
  1623. EltTys.push_back(T);
  1624. else
  1625. break;
  1626. }
  1627. if (EltTys.size() != Record.size()-1)
  1628. return error("Invalid type");
  1629. ResultTy = StructType::get(Context, EltTys, Record[0]);
  1630. break;
  1631. }
  1632. case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
  1633. if (convertToString(Record, 0, TypeName))
  1634. return error("Invalid record");
  1635. continue;
  1636. case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
  1637. if (Record.size() < 1)
  1638. return error("Invalid record");
  1639. if (NumRecords >= TypeList.size())
  1640. return error("Invalid TYPE table");
  1641. // Check to see if this was forward referenced, if so fill in the temp.
  1642. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1643. if (Res) {
  1644. Res->setName(TypeName);
  1645. TypeList[NumRecords] = nullptr;
  1646. } else // Otherwise, create a new struct.
  1647. Res = createIdentifiedStructType(Context, TypeName);
  1648. TypeName.clear();
  1649. SmallVector<Type*, 8> EltTys;
  1650. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1651. if (Type *T = getTypeByID(Record[i]))
  1652. EltTys.push_back(T);
  1653. else
  1654. break;
  1655. }
  1656. if (EltTys.size() != Record.size()-1)
  1657. return error("Invalid record");
  1658. Res->setBody(EltTys, Record[0]);
  1659. ResultTy = Res;
  1660. break;
  1661. }
  1662. case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
  1663. if (Record.size() != 1)
  1664. return error("Invalid record");
  1665. if (NumRecords >= TypeList.size())
  1666. return error("Invalid TYPE table");
  1667. // Check to see if this was forward referenced, if so fill in the temp.
  1668. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1669. if (Res) {
  1670. Res->setName(TypeName);
  1671. TypeList[NumRecords] = nullptr;
  1672. } else // Otherwise, create a new struct with no body.
  1673. Res = createIdentifiedStructType(Context, TypeName);
  1674. TypeName.clear();
  1675. ResultTy = Res;
  1676. break;
  1677. }
  1678. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  1679. if (Record.size() < 2)
  1680. return error("Invalid record");
  1681. ResultTy = getTypeByID(Record[1]);
  1682. if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
  1683. return error("Invalid type");
  1684. ResultTy = ArrayType::get(ResultTy, Record[0]);
  1685. break;
  1686. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  1687. if (Record.size() < 2)
  1688. return error("Invalid record");
  1689. if (Record[0] == 0)
  1690. return error("Invalid vector length");
  1691. ResultTy = getTypeByID(Record[1]);
  1692. if (!ResultTy || !StructType::isValidElementType(ResultTy))
  1693. return error("Invalid type");
  1694. ResultTy = VectorType::get(ResultTy, Record[0]);
  1695. break;
  1696. }
  1697. if (NumRecords >= TypeList.size())
  1698. return error("Invalid TYPE table");
  1699. if (TypeList[NumRecords])
  1700. return error(
  1701. "Invalid TYPE table: Only named structs can be forward referenced");
  1702. assert(ResultTy && "Didn't read a type?");
  1703. TypeList[NumRecords++] = ResultTy;
  1704. }
  1705. }
  1706. std::error_code BitcodeReader::parseOperandBundleTags() {
  1707. if (Stream.EnterSubBlock(bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID))
  1708. return error("Invalid record");
  1709. if (!BundleTags.empty())
  1710. return error("Invalid multiple blocks");
  1711. SmallVector<uint64_t, 64> Record;
  1712. while (true) {
  1713. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1714. switch (Entry.Kind) {
  1715. case BitstreamEntry::SubBlock: // Handled for us already.
  1716. case BitstreamEntry::Error:
  1717. return error("Malformed block");
  1718. case BitstreamEntry::EndBlock:
  1719. return std::error_code();
  1720. case BitstreamEntry::Record:
  1721. // The interesting case.
  1722. break;
  1723. }
  1724. // Tags are implicitly mapped to integers by their order.
  1725. if (Stream.readRecord(Entry.ID, Record) != bitc::OPERAND_BUNDLE_TAG)
  1726. return error("Invalid record");
  1727. // OPERAND_BUNDLE_TAG: [strchr x N]
  1728. BundleTags.emplace_back();
  1729. if (convertToString(Record, 0, BundleTags.back()))
  1730. return error("Invalid record");
  1731. Record.clear();
  1732. }
  1733. }
  1734. /// Associate a value with its name from the given index in the provided record.
  1735. ErrorOr<Value *> BitcodeReader::recordValue(SmallVectorImpl<uint64_t> &Record,
  1736. unsigned NameIndex, Triple &TT) {
  1737. SmallString<128> ValueName;
  1738. if (convertToString(Record, NameIndex, ValueName))
  1739. return error("Invalid record");
  1740. unsigned ValueID = Record[0];
  1741. if (ValueID >= ValueList.size() || !ValueList[ValueID])
  1742. return error("Invalid record");
  1743. Value *V = ValueList[ValueID];
  1744. StringRef NameStr(ValueName.data(), ValueName.size());
  1745. if (NameStr.find_first_of(0) != StringRef::npos)
  1746. return error("Invalid value name");
  1747. V->setName(NameStr);
  1748. auto *GO = dyn_cast<GlobalObject>(V);
  1749. if (GO) {
  1750. if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
  1751. if (TT.isOSBinFormatMachO())
  1752. GO->setComdat(nullptr);
  1753. else
  1754. GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
  1755. }
  1756. }
  1757. return V;
  1758. }
  1759. /// Helper to note and return the current location, and jump to the given
  1760. /// offset.
  1761. static uint64_t jumpToValueSymbolTable(uint64_t Offset,
  1762. BitstreamCursor &Stream) {
  1763. // Save the current parsing location so we can jump back at the end
  1764. // of the VST read.
  1765. uint64_t CurrentBit = Stream.GetCurrentBitNo();
  1766. Stream.JumpToBit(Offset * 32);
  1767. #ifndef NDEBUG
  1768. // Do some checking if we are in debug mode.
  1769. BitstreamEntry Entry = Stream.advance();
  1770. assert(Entry.Kind == BitstreamEntry::SubBlock);
  1771. assert(Entry.ID == bitc::VALUE_SYMTAB_BLOCK_ID);
  1772. #else
  1773. // In NDEBUG mode ignore the output so we don't get an unused variable
  1774. // warning.
  1775. Stream.advance();
  1776. #endif
  1777. return CurrentBit;
  1778. }
  1779. /// Parse the value symbol table at either the current parsing location or
  1780. /// at the given bit offset if provided.
  1781. std::error_code BitcodeReader::parseValueSymbolTable(uint64_t Offset) {
  1782. uint64_t CurrentBit;
  1783. // Pass in the Offset to distinguish between calling for the module-level
  1784. // VST (where we want to jump to the VST offset) and the function-level
  1785. // VST (where we don't).
  1786. if (Offset > 0)
  1787. CurrentBit = jumpToValueSymbolTable(Offset, Stream);
  1788. // Compute the delta between the bitcode indices in the VST (the word offset
  1789. // to the word-aligned ENTER_SUBBLOCK for the function block, and that
  1790. // expected by the lazy reader. The reader's EnterSubBlock expects to have
  1791. // already read the ENTER_SUBBLOCK code (size getAbbrevIDWidth) and BlockID
  1792. // (size BlockIDWidth). Note that we access the stream's AbbrevID width here
  1793. // just before entering the VST subblock because: 1) the EnterSubBlock
  1794. // changes the AbbrevID width; 2) the VST block is nested within the same
  1795. // outer MODULE_BLOCK as the FUNCTION_BLOCKs and therefore have the same
  1796. // AbbrevID width before calling EnterSubBlock; and 3) when we want to
  1797. // jump to the FUNCTION_BLOCK using this offset later, we don't want
  1798. // to rely on the stream's AbbrevID width being that of the MODULE_BLOCK.
  1799. unsigned FuncBitcodeOffsetDelta =
  1800. Stream.getAbbrevIDWidth() + bitc::BlockIDWidth;
  1801. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  1802. return error("Invalid record");
  1803. SmallVector<uint64_t, 64> Record;
  1804. Triple TT(TheModule->getTargetTriple());
  1805. // Read all the records for this value table.
  1806. SmallString<128> ValueName;
  1807. while (true) {
  1808. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1809. switch (Entry.Kind) {
  1810. case BitstreamEntry::SubBlock: // Handled for us already.
  1811. case BitstreamEntry::Error:
  1812. return error("Malformed block");
  1813. case BitstreamEntry::EndBlock:
  1814. if (Offset > 0)
  1815. Stream.JumpToBit(CurrentBit);
  1816. return std::error_code();
  1817. case BitstreamEntry::Record:
  1818. // The interesting case.
  1819. break;
  1820. }
  1821. // Read a record.
  1822. Record.clear();
  1823. switch (Stream.readRecord(Entry.ID, Record)) {
  1824. default: // Default behavior: unknown type.
  1825. break;
  1826. case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
  1827. ErrorOr<Value *> ValOrErr = recordValue(Record, 1, TT);
  1828. if (std::error_code EC = ValOrErr.getError())
  1829. return EC;
  1830. ValOrErr.get();
  1831. break;
  1832. }
  1833. case bitc::VST_CODE_FNENTRY: {
  1834. // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
  1835. ErrorOr<Value *> ValOrErr = recordValue(Record, 2, TT);
  1836. if (std::error_code EC = ValOrErr.getError())
  1837. return EC;
  1838. Value *V = ValOrErr.get();
  1839. auto *GO = dyn_cast<GlobalObject>(V);
  1840. if (!GO) {
  1841. // If this is an alias, need to get the actual Function object
  1842. // it aliases, in order to set up the DeferredFunctionInfo entry below.
  1843. auto *GA = dyn_cast<GlobalAlias>(V);
  1844. if (GA)
  1845. GO = GA->getBaseObject();
  1846. assert(GO);
  1847. }
  1848. uint64_t FuncWordOffset = Record[1];
  1849. Function *F = dyn_cast<Function>(GO);
  1850. assert(F);
  1851. uint64_t FuncBitOffset = FuncWordOffset * 32;
  1852. DeferredFunctionInfo[F] = FuncBitOffset + FuncBitcodeOffsetDelta;
  1853. // Set the LastFunctionBlockBit to point to the last function block.
  1854. // Later when parsing is resumed after function materialization,
  1855. // we can simply skip that last function block.
  1856. if (FuncBitOffset > LastFunctionBlockBit)
  1857. LastFunctionBlockBit = FuncBitOffset;
  1858. break;
  1859. }
  1860. case bitc::VST_CODE_BBENTRY: {
  1861. if (convertToString(Record, 1, ValueName))
  1862. return error("Invalid record");
  1863. BasicBlock *BB = getBasicBlock(Record[0]);
  1864. if (!BB)
  1865. return error("Invalid record");
  1866. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  1867. ValueName.clear();
  1868. break;
  1869. }
  1870. }
  1871. }
  1872. }
  1873. /// Parse a single METADATA_KIND record, inserting result in MDKindMap.
  1874. std::error_code
  1875. BitcodeReader::parseMetadataKindRecord(SmallVectorImpl<uint64_t> &Record) {
  1876. if (Record.size() < 2)
  1877. return error("Invalid record");
  1878. unsigned Kind = Record[0];
  1879. SmallString<8> Name(Record.begin() + 1, Record.end());
  1880. unsigned NewKind = TheModule->getMDKindID(Name.str());
  1881. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  1882. return error("Conflicting METADATA_KIND records");
  1883. return std::error_code();
  1884. }
  1885. static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
  1886. std::error_code BitcodeReader::parseMetadataStrings(ArrayRef<uint64_t> Record,
  1887. StringRef Blob,
  1888. unsigned &NextMetadataNo) {
  1889. // All the MDStrings in the block are emitted together in a single
  1890. // record. The strings are concatenated and stored in a blob along with
  1891. // their sizes.
  1892. if (Record.size() != 2)
  1893. return error("Invalid record: metadata strings layout");
  1894. unsigned NumStrings = Record[0];
  1895. unsigned StringsOffset = Record[1];
  1896. if (!NumStrings)
  1897. return error("Invalid record: metadata strings with no strings");
  1898. if (StringsOffset > Blob.size())
  1899. return error("Invalid record: metadata strings corrupt offset");
  1900. StringRef Lengths = Blob.slice(0, StringsOffset);
  1901. SimpleBitstreamCursor R(Lengths);
  1902. StringRef Strings = Blob.drop_front(StringsOffset);
  1903. do {
  1904. if (R.AtEndOfStream())
  1905. return error("Invalid record: metadata strings bad length");
  1906. unsigned Size = R.ReadVBR(6);
  1907. if (Strings.size() < Size)
  1908. return error("Invalid record: metadata strings truncated chars");
  1909. MetadataList.assignValue(MDString::get(Context, Strings.slice(0, Size)),
  1910. NextMetadataNo++);
  1911. Strings = Strings.drop_front(Size);
  1912. } while (--NumStrings);
  1913. return std::error_code();
  1914. }
  1915. namespace {
  1916. class PlaceholderQueue {
  1917. // Placeholders would thrash around when moved, so store in a std::deque
  1918. // instead of some sort of vector.
  1919. std::deque<DistinctMDOperandPlaceholder> PHs;
  1920. public:
  1921. DistinctMDOperandPlaceholder &getPlaceholderOp(unsigned ID);
  1922. void flush(BitcodeReaderMetadataList &MetadataList);
  1923. };
  1924. } // end anonymous namespace
  1925. DistinctMDOperandPlaceholder &PlaceholderQueue::getPlaceholderOp(unsigned ID) {
  1926. PHs.emplace_back(ID);
  1927. return PHs.back();
  1928. }
  1929. void PlaceholderQueue::flush(BitcodeReaderMetadataList &MetadataList) {
  1930. while (!PHs.empty()) {
  1931. PHs.front().replaceUseWith(
  1932. MetadataList.getMetadataFwdRef(PHs.front().getID()));
  1933. PHs.pop_front();
  1934. }
  1935. }
  1936. /// Parse a METADATA_BLOCK. If ModuleLevel is true then we are parsing
  1937. /// module level metadata.
  1938. std::error_code BitcodeReader::parseMetadata(bool ModuleLevel) {
  1939. assert((ModuleLevel || DeferredMetadataInfo.empty()) &&
  1940. "Must read all module-level metadata before function-level");
  1941. IsMetadataMaterialized = true;
  1942. unsigned NextMetadataNo = MetadataList.size();
  1943. if (!ModuleLevel && MetadataList.hasFwdRefs())
  1944. return error("Invalid metadata: fwd refs into function blocks");
  1945. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  1946. return error("Invalid record");
  1947. std::vector<std::pair<DICompileUnit *, Metadata *>> CUSubprograms;
  1948. SmallVector<uint64_t, 64> Record;
  1949. PlaceholderQueue Placeholders;
  1950. bool IsDistinct;
  1951. auto getMD = [&](unsigned ID) -> Metadata * {
  1952. if (!IsDistinct)
  1953. return MetadataList.getMetadataFwdRef(ID);
  1954. if (auto *MD = MetadataList.getMetadataIfResolved(ID))
  1955. return MD;
  1956. return &Placeholders.getPlaceholderOp(ID);
  1957. };
  1958. auto getMDOrNull = [&](unsigned ID) -> Metadata * {
  1959. if (ID)
  1960. return getMD(ID - 1);
  1961. return nullptr;
  1962. };
  1963. auto getMDOrNullWithoutPlaceholders = [&](unsigned ID) -> Metadata * {
  1964. if (ID)
  1965. return MetadataList.getMetadataFwdRef(ID - 1);
  1966. return nullptr;
  1967. };
  1968. auto getMDString = [&](unsigned ID) -> MDString *{
  1969. // This requires that the ID is not really a forward reference. In
  1970. // particular, the MDString must already have been resolved.
  1971. return cast_or_null<MDString>(getMDOrNull(ID));
  1972. };
  1973. // Support for old type refs.
  1974. auto getDITypeRefOrNull = [&](unsigned ID) {
  1975. return MetadataList.upgradeTypeRef(getMDOrNull(ID));
  1976. };
  1977. #define GET_OR_DISTINCT(CLASS, ARGS) \
  1978. (IsDistinct ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  1979. // Read all the records.
  1980. while (true) {
  1981. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  1982. switch (Entry.Kind) {
  1983. case BitstreamEntry::SubBlock: // Handled for us already.
  1984. case BitstreamEntry::Error:
  1985. return error("Malformed block");
  1986. case BitstreamEntry::EndBlock:
  1987. // Upgrade old-style CU <-> SP pointers to point from SP to CU.
  1988. for (auto CU_SP : CUSubprograms)
  1989. if (auto *SPs = dyn_cast_or_null<MDTuple>(CU_SP.second))
  1990. for (auto &Op : SPs->operands())
  1991. if (auto *SP = dyn_cast_or_null<MDNode>(Op))
  1992. SP->replaceOperandWith(7, CU_SP.first);
  1993. MetadataList.tryToResolveCycles();
  1994. Placeholders.flush(MetadataList);
  1995. return std::error_code();
  1996. case BitstreamEntry::Record:
  1997. // The interesting case.
  1998. break;
  1999. }
  2000. // Read a record.
  2001. Record.clear();
  2002. StringRef Blob;
  2003. unsigned Code = Stream.readRecord(Entry.ID, Record, &Blob);
  2004. IsDistinct = false;
  2005. switch (Code) {
  2006. default: // Default behavior: ignore.
  2007. break;
  2008. case bitc::METADATA_NAME: {
  2009. // Read name of the named metadata.
  2010. SmallString<8> Name(Record.begin(), Record.end());
  2011. Record.clear();
  2012. Code = Stream.ReadCode();
  2013. unsigned NextBitCode = Stream.readRecord(Code, Record);
  2014. if (NextBitCode != bitc::METADATA_NAMED_NODE)
  2015. return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
  2016. // Read named metadata elements.
  2017. unsigned Size = Record.size();
  2018. NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
  2019. for (unsigned i = 0; i != Size; ++i) {
  2020. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[i]);
  2021. if (!MD)
  2022. return error("Invalid record");
  2023. NMD->addOperand(MD);
  2024. }
  2025. break;
  2026. }
  2027. case bitc::METADATA_OLD_FN_NODE: {
  2028. // FIXME: Remove in 4.0.
  2029. // This is a LocalAsMetadata record, the only type of function-local
  2030. // metadata.
  2031. if (Record.size() % 2 == 1)
  2032. return error("Invalid record");
  2033. // If this isn't a LocalAsMetadata record, we're dropping it. This used
  2034. // to be legal, but there's no upgrade path.
  2035. auto dropRecord = [&] {
  2036. MetadataList.assignValue(MDNode::get(Context, None), NextMetadataNo++);
  2037. };
  2038. if (Record.size() != 2) {
  2039. dropRecord();
  2040. break;
  2041. }
  2042. Type *Ty = getTypeByID(Record[0]);
  2043. if (Ty->isMetadataTy() || Ty->isVoidTy()) {
  2044. dropRecord();
  2045. break;
  2046. }
  2047. MetadataList.assignValue(
  2048. LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  2049. NextMetadataNo++);
  2050. break;
  2051. }
  2052. case bitc::METADATA_OLD_NODE: {
  2053. // FIXME: Remove in 4.0.
  2054. if (Record.size() % 2 == 1)
  2055. return error("Invalid record");
  2056. unsigned Size = Record.size();
  2057. SmallVector<Metadata *, 8> Elts;
  2058. for (unsigned i = 0; i != Size; i += 2) {
  2059. Type *Ty = getTypeByID(Record[i]);
  2060. if (!Ty)
  2061. return error("Invalid record");
  2062. if (Ty->isMetadataTy())
  2063. Elts.push_back(getMD(Record[i + 1]));
  2064. else if (!Ty->isVoidTy()) {
  2065. auto *MD =
  2066. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
  2067. assert(isa<ConstantAsMetadata>(MD) &&
  2068. "Expected non-function-local metadata");
  2069. Elts.push_back(MD);
  2070. } else
  2071. Elts.push_back(nullptr);
  2072. }
  2073. MetadataList.assignValue(MDNode::get(Context, Elts), NextMetadataNo++);
  2074. break;
  2075. }
  2076. case bitc::METADATA_VALUE: {
  2077. if (Record.size() != 2)
  2078. return error("Invalid record");
  2079. Type *Ty = getTypeByID(Record[0]);
  2080. if (Ty->isMetadataTy() || Ty->isVoidTy())
  2081. return error("Invalid record");
  2082. MetadataList.assignValue(
  2083. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  2084. NextMetadataNo++);
  2085. break;
  2086. }
  2087. case bitc::METADATA_DISTINCT_NODE:
  2088. IsDistinct = true;
  2089. LLVM_FALLTHROUGH;
  2090. case bitc::METADATA_NODE: {
  2091. SmallVector<Metadata *, 8> Elts;
  2092. Elts.reserve(Record.size());
  2093. for (unsigned ID : Record)
  2094. Elts.push_back(getMDOrNull(ID));
  2095. MetadataList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
  2096. : MDNode::get(Context, Elts),
  2097. NextMetadataNo++);
  2098. break;
  2099. }
  2100. case bitc::METADATA_LOCATION: {
  2101. if (Record.size() != 5)
  2102. return error("Invalid record");
  2103. IsDistinct = Record[0];
  2104. unsigned Line = Record[1];
  2105. unsigned Column = Record[2];
  2106. Metadata *Scope = getMD(Record[3]);
  2107. Metadata *InlinedAt = getMDOrNull(Record[4]);
  2108. MetadataList.assignValue(
  2109. GET_OR_DISTINCT(DILocation,
  2110. (Context, Line, Column, Scope, InlinedAt)),
  2111. NextMetadataNo++);
  2112. break;
  2113. }
  2114. case bitc::METADATA_GENERIC_DEBUG: {
  2115. if (Record.size() < 4)
  2116. return error("Invalid record");
  2117. IsDistinct = Record[0];
  2118. unsigned Tag = Record[1];
  2119. unsigned Version = Record[2];
  2120. if (Tag >= 1u << 16 || Version != 0)
  2121. return error("Invalid record");
  2122. auto *Header = getMDString(Record[3]);
  2123. SmallVector<Metadata *, 8> DwarfOps;
  2124. for (unsigned I = 4, E = Record.size(); I != E; ++I)
  2125. DwarfOps.push_back(getMDOrNull(Record[I]));
  2126. MetadataList.assignValue(
  2127. GET_OR_DISTINCT(GenericDINode, (Context, Tag, Header, DwarfOps)),
  2128. NextMetadataNo++);
  2129. break;
  2130. }
  2131. case bitc::METADATA_SUBRANGE: {
  2132. if (Record.size() != 3)
  2133. return error("Invalid record");
  2134. IsDistinct = Record[0];
  2135. MetadataList.assignValue(
  2136. GET_OR_DISTINCT(DISubrange,
  2137. (Context, Record[1], unrotateSign(Record[2]))),
  2138. NextMetadataNo++);
  2139. break;
  2140. }
  2141. case bitc::METADATA_ENUMERATOR: {
  2142. if (Record.size() != 3)
  2143. return error("Invalid record");
  2144. IsDistinct = Record[0];
  2145. MetadataList.assignValue(
  2146. GET_OR_DISTINCT(DIEnumerator, (Context, unrotateSign(Record[1]),
  2147. getMDString(Record[2]))),
  2148. NextMetadataNo++);
  2149. break;
  2150. }
  2151. case bitc::METADATA_BASIC_TYPE: {
  2152. if (Record.size() != 6)
  2153. return error("Invalid record");
  2154. IsDistinct = Record[0];
  2155. MetadataList.assignValue(
  2156. GET_OR_DISTINCT(DIBasicType,
  2157. (Context, Record[1], getMDString(Record[2]),
  2158. Record[3], Record[4], Record[5])),
  2159. NextMetadataNo++);
  2160. break;
  2161. }
  2162. case bitc::METADATA_DERIVED_TYPE: {
  2163. if (Record.size() != 12)
  2164. return error("Invalid record");
  2165. IsDistinct = Record[0];
  2166. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
  2167. MetadataList.assignValue(
  2168. GET_OR_DISTINCT(DIDerivedType,
  2169. (Context, Record[1], getMDString(Record[2]),
  2170. getMDOrNull(Record[3]), Record[4],
  2171. getDITypeRefOrNull(Record[5]),
  2172. getDITypeRefOrNull(Record[6]), Record[7], Record[8],
  2173. Record[9], Flags, getDITypeRefOrNull(Record[11]))),
  2174. NextMetadataNo++);
  2175. break;
  2176. }
  2177. case bitc::METADATA_COMPOSITE_TYPE: {
  2178. if (Record.size() != 16)
  2179. return error("Invalid record");
  2180. // If we have a UUID and this is not a forward declaration, lookup the
  2181. // mapping.
  2182. IsDistinct = Record[0] & 0x1;
  2183. bool IsNotUsedInTypeRef = Record[0] >= 2;
  2184. unsigned Tag = Record[1];
  2185. MDString *Name = getMDString(Record[2]);
  2186. Metadata *File = getMDOrNull(Record[3]);
  2187. unsigned Line = Record[4];
  2188. Metadata *Scope = getDITypeRefOrNull(Record[5]);
  2189. Metadata *BaseType = getDITypeRefOrNull(Record[6]);
  2190. uint64_t SizeInBits = Record[7];
  2191. if (Record[8] > (uint64_t)std::numeric_limits<uint32_t>::max())
  2192. return error("Alignment value is too large");
  2193. uint32_t AlignInBits = Record[8];
  2194. uint64_t OffsetInBits = Record[9];
  2195. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[10]);
  2196. Metadata *Elements = getMDOrNull(Record[11]);
  2197. unsigned RuntimeLang = Record[12];
  2198. Metadata *VTableHolder = getDITypeRefOrNull(Record[13]);
  2199. Metadata *TemplateParams = getMDOrNull(Record[14]);
  2200. auto *Identifier = getMDString(Record[15]);
  2201. DICompositeType *CT = nullptr;
  2202. if (Identifier)
  2203. CT = DICompositeType::buildODRType(
  2204. Context, *Identifier, Tag, Name, File, Line, Scope, BaseType,
  2205. SizeInBits, AlignInBits, OffsetInBits, Flags, Elements, RuntimeLang,
  2206. VTableHolder, TemplateParams);
  2207. // Create a node if we didn't get a lazy ODR type.
  2208. if (!CT)
  2209. CT = GET_OR_DISTINCT(DICompositeType,
  2210. (Context, Tag, Name, File, Line, Scope, BaseType,
  2211. SizeInBits, AlignInBits, OffsetInBits, Flags,
  2212. Elements, RuntimeLang, VTableHolder,
  2213. TemplateParams, Identifier));
  2214. if (!IsNotUsedInTypeRef && Identifier)
  2215. MetadataList.addTypeRef(*Identifier, *cast<DICompositeType>(CT));
  2216. MetadataList.assignValue(CT, NextMetadataNo++);
  2217. break;
  2218. }
  2219. case bitc::METADATA_SUBROUTINE_TYPE: {
  2220. if (Record.size() < 3 || Record.size() > 4)
  2221. return error("Invalid record");
  2222. bool IsOldTypeRefArray = Record[0] < 2;
  2223. unsigned CC = (Record.size() > 3) ? Record[3] : 0;
  2224. IsDistinct = Record[0] & 0x1;
  2225. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[1]);
  2226. Metadata *Types = getMDOrNull(Record[2]);
  2227. if (LLVM_UNLIKELY(IsOldTypeRefArray))
  2228. Types = MetadataList.upgradeTypeRefArray(Types);
  2229. MetadataList.assignValue(
  2230. GET_OR_DISTINCT(DISubroutineType, (Context, Flags, CC, Types)),
  2231. NextMetadataNo++);
  2232. break;
  2233. }
  2234. case bitc::METADATA_MODULE: {
  2235. if (Record.size() != 6)
  2236. return error("Invalid record");
  2237. IsDistinct = Record[0];
  2238. MetadataList.assignValue(
  2239. GET_OR_DISTINCT(DIModule,
  2240. (Context, getMDOrNull(Record[1]),
  2241. getMDString(Record[2]), getMDString(Record[3]),
  2242. getMDString(Record[4]), getMDString(Record[5]))),
  2243. NextMetadataNo++);
  2244. break;
  2245. }
  2246. case bitc::METADATA_FILE: {
  2247. if (Record.size() != 3)
  2248. return error("Invalid record");
  2249. IsDistinct = Record[0];
  2250. MetadataList.assignValue(
  2251. GET_OR_DISTINCT(DIFile, (Context, getMDString(Record[1]),
  2252. getMDString(Record[2]))),
  2253. NextMetadataNo++);
  2254. break;
  2255. }
  2256. case bitc::METADATA_COMPILE_UNIT: {
  2257. if (Record.size() < 14 || Record.size() > 17)
  2258. return error("Invalid record");
  2259. // Ignore Record[0], which indicates whether this compile unit is
  2260. // distinct. It's always distinct.
  2261. IsDistinct = true;
  2262. auto *CU = DICompileUnit::getDistinct(
  2263. Context, Record[1], getMDOrNull(Record[2]), getMDString(Record[3]),
  2264. Record[4], getMDString(Record[5]), Record[6], getMDString(Record[7]),
  2265. Record[8], getMDOrNull(Record[9]), getMDOrNull(Record[10]),
  2266. getMDOrNull(Record[12]), getMDOrNull(Record[13]),
  2267. Record.size() <= 15 ? nullptr : getMDOrNull(Record[15]),
  2268. Record.size() <= 14 ? 0 : Record[14],
  2269. Record.size() <= 16 ? true : Record[16]);
  2270. MetadataList.assignValue(CU, NextMetadataNo++);
  2271. // Move the Upgrade the list of subprograms.
  2272. if (Metadata *SPs = getMDOrNullWithoutPlaceholders(Record[11]))
  2273. CUSubprograms.push_back({CU, SPs});
  2274. break;
  2275. }
  2276. case bitc::METADATA_SUBPROGRAM: {
  2277. if (Record.size() < 18 || Record.size() > 20)
  2278. return error("Invalid record");
  2279. IsDistinct =
  2280. (Record[0] & 1) || Record[8]; // All definitions should be distinct.
  2281. // Version 1 has a Function as Record[15].
  2282. // Version 2 has removed Record[15].
  2283. // Version 3 has the Unit as Record[15].
  2284. // Version 4 added thisAdjustment.
  2285. bool HasUnit = Record[0] >= 2;
  2286. if (HasUnit && Record.size() < 19)
  2287. return error("Invalid record");
  2288. Metadata *CUorFn = getMDOrNull(Record[15]);
  2289. unsigned Offset = Record.size() >= 19 ? 1 : 0;
  2290. bool HasFn = Offset && !HasUnit;
  2291. bool HasThisAdj = Record.size() >= 20;
  2292. DISubprogram *SP = GET_OR_DISTINCT(
  2293. DISubprogram, (Context,
  2294. getDITypeRefOrNull(Record[1]), // scope
  2295. getMDString(Record[2]), // name
  2296. getMDString(Record[3]), // linkageName
  2297. getMDOrNull(Record[4]), // file
  2298. Record[5], // line
  2299. getMDOrNull(Record[6]), // type
  2300. Record[7], // isLocal
  2301. Record[8], // isDefinition
  2302. Record[9], // scopeLine
  2303. getDITypeRefOrNull(Record[10]), // containingType
  2304. Record[11], // virtuality
  2305. Record[12], // virtualIndex
  2306. HasThisAdj ? Record[19] : 0, // thisAdjustment
  2307. static_cast<DINode::DIFlags>(Record[13] // flags
  2308. ),
  2309. Record[14], // isOptimized
  2310. HasUnit ? CUorFn : nullptr, // unit
  2311. getMDOrNull(Record[15 + Offset]), // templateParams
  2312. getMDOrNull(Record[16 + Offset]), // declaration
  2313. getMDOrNull(Record[17 + Offset]) // variables
  2314. ));
  2315. MetadataList.assignValue(SP, NextMetadataNo++);
  2316. // Upgrade sp->function mapping to function->sp mapping.
  2317. if (HasFn) {
  2318. if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(CUorFn))
  2319. if (auto *F = dyn_cast<Function>(CMD->getValue())) {
  2320. if (F->isMaterializable())
  2321. // Defer until materialized; unmaterialized functions may not have
  2322. // metadata.
  2323. FunctionsWithSPs[F] = SP;
  2324. else if (!F->empty())
  2325. F->setSubprogram(SP);
  2326. }
  2327. }
  2328. break;
  2329. }
  2330. case bitc::METADATA_LEXICAL_BLOCK: {
  2331. if (Record.size() != 5)
  2332. return error("Invalid record");
  2333. IsDistinct = Record[0];
  2334. MetadataList.assignValue(
  2335. GET_OR_DISTINCT(DILexicalBlock,
  2336. (Context, getMDOrNull(Record[1]),
  2337. getMDOrNull(Record[2]), Record[3], Record[4])),
  2338. NextMetadataNo++);
  2339. break;
  2340. }
  2341. case bitc::METADATA_LEXICAL_BLOCK_FILE: {
  2342. if (Record.size() != 4)
  2343. return error("Invalid record");
  2344. IsDistinct = Record[0];
  2345. MetadataList.assignValue(
  2346. GET_OR_DISTINCT(DILexicalBlockFile,
  2347. (Context, getMDOrNull(Record[1]),
  2348. getMDOrNull(Record[2]), Record[3])),
  2349. NextMetadataNo++);
  2350. break;
  2351. }
  2352. case bitc::METADATA_NAMESPACE: {
  2353. if (Record.size() != 5)
  2354. return error("Invalid record");
  2355. IsDistinct = Record[0] & 1;
  2356. bool ExportSymbols = Record[0] & 2;
  2357. MetadataList.assignValue(
  2358. GET_OR_DISTINCT(DINamespace,
  2359. (Context, getMDOrNull(Record[1]),
  2360. getMDOrNull(Record[2]), getMDString(Record[3]),
  2361. Record[4], ExportSymbols)),
  2362. NextMetadataNo++);
  2363. break;
  2364. }
  2365. case bitc::METADATA_MACRO: {
  2366. if (Record.size() != 5)
  2367. return error("Invalid record");
  2368. IsDistinct = Record[0];
  2369. MetadataList.assignValue(
  2370. GET_OR_DISTINCT(DIMacro,
  2371. (Context, Record[1], Record[2],
  2372. getMDString(Record[3]), getMDString(Record[4]))),
  2373. NextMetadataNo++);
  2374. break;
  2375. }
  2376. case bitc::METADATA_MACRO_FILE: {
  2377. if (Record.size() != 5)
  2378. return error("Invalid record");
  2379. IsDistinct = Record[0];
  2380. MetadataList.assignValue(
  2381. GET_OR_DISTINCT(DIMacroFile,
  2382. (Context, Record[1], Record[2],
  2383. getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
  2384. NextMetadataNo++);
  2385. break;
  2386. }
  2387. case bitc::METADATA_TEMPLATE_TYPE: {
  2388. if (Record.size() != 3)
  2389. return error("Invalid record");
  2390. IsDistinct = Record[0];
  2391. MetadataList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
  2392. (Context, getMDString(Record[1]),
  2393. getDITypeRefOrNull(Record[2]))),
  2394. NextMetadataNo++);
  2395. break;
  2396. }
  2397. case bitc::METADATA_TEMPLATE_VALUE: {
  2398. if (Record.size() != 5)
  2399. return error("Invalid record");
  2400. IsDistinct = Record[0];
  2401. MetadataList.assignValue(
  2402. GET_OR_DISTINCT(DITemplateValueParameter,
  2403. (Context, Record[1], getMDString(Record[2]),
  2404. getDITypeRefOrNull(Record[3]),
  2405. getMDOrNull(Record[4]))),
  2406. NextMetadataNo++);
  2407. break;
  2408. }
  2409. case bitc::METADATA_GLOBAL_VAR: {
  2410. if (Record.size() < 11 || Record.size() > 12)
  2411. return error("Invalid record");
  2412. IsDistinct = Record[0];
  2413. // Upgrade old metadata, which stored a global variable reference or a
  2414. // ConstantInt here.
  2415. Metadata *Expr = getMDOrNull(Record[9]);
  2416. uint32_t AlignInBits = 0;
  2417. if (Record.size() > 11) {
  2418. if (Record[11] > (uint64_t)std::numeric_limits<uint32_t>::max())
  2419. return error("Alignment value is too large");
  2420. AlignInBits = Record[11];
  2421. }
  2422. GlobalVariable *Attach = nullptr;
  2423. if (auto *CMD = dyn_cast_or_null<ConstantAsMetadata>(Expr)) {
  2424. if (auto *GV = dyn_cast<GlobalVariable>(CMD->getValue())) {
  2425. Attach = GV;
  2426. Expr = nullptr;
  2427. } else if (auto *CI = dyn_cast<ConstantInt>(CMD->getValue())) {
  2428. Expr = DIExpression::get(Context,
  2429. {dwarf::DW_OP_constu, CI->getZExtValue(),
  2430. dwarf::DW_OP_stack_value});
  2431. } else {
  2432. Expr = nullptr;
  2433. }
  2434. }
  2435. DIGlobalVariable *DGV = GET_OR_DISTINCT(
  2436. DIGlobalVariable,
  2437. (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
  2438. getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
  2439. getDITypeRefOrNull(Record[6]), Record[7], Record[8], Expr,
  2440. getMDOrNull(Record[10]), AlignInBits));
  2441. MetadataList.assignValue(DGV, NextMetadataNo++);
  2442. if (Attach)
  2443. Attach->addDebugInfo(DGV);
  2444. break;
  2445. }
  2446. case bitc::METADATA_LOCAL_VAR: {
  2447. // 10th field is for the obseleted 'inlinedAt:' field.
  2448. if (Record.size() < 8 || Record.size() > 10)
  2449. return error("Invalid record");
  2450. IsDistinct = Record[0] & 1;
  2451. bool HasAlignment = Record[0] & 2;
  2452. // 2nd field used to be an artificial tag, either DW_TAG_auto_variable or
  2453. // DW_TAG_arg_variable, if we have alignment flag encoded it means, that
  2454. // this is newer version of record which doesn't have artifical tag.
  2455. bool HasTag = !HasAlignment && Record.size() > 8;
  2456. DINode::DIFlags Flags = static_cast<DINode::DIFlags>(Record[7 + HasTag]);
  2457. uint32_t AlignInBits = 0;
  2458. if (HasAlignment) {
  2459. if (Record[8 + HasTag] >
  2460. (uint64_t)std::numeric_limits<uint32_t>::max())
  2461. return error("Alignment value is too large");
  2462. AlignInBits = Record[8 + HasTag];
  2463. }
  2464. MetadataList.assignValue(
  2465. GET_OR_DISTINCT(DILocalVariable,
  2466. (Context, getMDOrNull(Record[1 + HasTag]),
  2467. getMDString(Record[2 + HasTag]),
  2468. getMDOrNull(Record[3 + HasTag]), Record[4 + HasTag],
  2469. getDITypeRefOrNull(Record[5 + HasTag]),
  2470. Record[6 + HasTag], Flags, AlignInBits)),
  2471. NextMetadataNo++);
  2472. break;
  2473. }
  2474. case bitc::METADATA_EXPRESSION: {
  2475. if (Record.size() < 1)
  2476. return error("Invalid record");
  2477. IsDistinct = Record[0];
  2478. MetadataList.assignValue(
  2479. GET_OR_DISTINCT(DIExpression,
  2480. (Context, makeArrayRef(Record).slice(1))),
  2481. NextMetadataNo++);
  2482. break;
  2483. }
  2484. case bitc::METADATA_OBJC_PROPERTY: {
  2485. if (Record.size() != 8)
  2486. return error("Invalid record");
  2487. IsDistinct = Record[0];
  2488. MetadataList.assignValue(
  2489. GET_OR_DISTINCT(DIObjCProperty,
  2490. (Context, getMDString(Record[1]),
  2491. getMDOrNull(Record[2]), Record[3],
  2492. getMDString(Record[4]), getMDString(Record[5]),
  2493. Record[6], getDITypeRefOrNull(Record[7]))),
  2494. NextMetadataNo++);
  2495. break;
  2496. }
  2497. case bitc::METADATA_IMPORTED_ENTITY: {
  2498. if (Record.size() != 6)
  2499. return error("Invalid record");
  2500. IsDistinct = Record[0];
  2501. MetadataList.assignValue(
  2502. GET_OR_DISTINCT(DIImportedEntity,
  2503. (Context, Record[1], getMDOrNull(Record[2]),
  2504. getDITypeRefOrNull(Record[3]), Record[4],
  2505. getMDString(Record[5]))),
  2506. NextMetadataNo++);
  2507. break;
  2508. }
  2509. case bitc::METADATA_STRING_OLD: {
  2510. std::string String(Record.begin(), Record.end());
  2511. // Test for upgrading !llvm.loop.
  2512. HasSeenOldLoopTags |= mayBeOldLoopAttachmentTag(String);
  2513. Metadata *MD = MDString::get(Context, String);
  2514. MetadataList.assignValue(MD, NextMetadataNo++);
  2515. break;
  2516. }
  2517. case bitc::METADATA_STRINGS:
  2518. if (std::error_code EC =
  2519. parseMetadataStrings(Record, Blob, NextMetadataNo))
  2520. return EC;
  2521. break;
  2522. case bitc::METADATA_GLOBAL_DECL_ATTACHMENT: {
  2523. if (Record.size() % 2 == 0)
  2524. return error("Invalid record");
  2525. unsigned ValueID = Record[0];
  2526. if (ValueID >= ValueList.size())
  2527. return error("Invalid record");
  2528. if (auto *GO = dyn_cast<GlobalObject>(ValueList[ValueID]))
  2529. parseGlobalObjectAttachment(*GO, ArrayRef<uint64_t>(Record).slice(1));
  2530. break;
  2531. }
  2532. case bitc::METADATA_KIND: {
  2533. // Support older bitcode files that had METADATA_KIND records in a
  2534. // block with METADATA_BLOCK_ID.
  2535. if (std::error_code EC = parseMetadataKindRecord(Record))
  2536. return EC;
  2537. break;
  2538. }
  2539. }
  2540. }
  2541. #undef GET_OR_DISTINCT
  2542. }
  2543. /// Parse the metadata kinds out of the METADATA_KIND_BLOCK.
  2544. std::error_code BitcodeReader::parseMetadataKinds() {
  2545. if (Stream.EnterSubBlock(bitc::METADATA_KIND_BLOCK_ID))
  2546. return error("Invalid record");
  2547. SmallVector<uint64_t, 64> Record;
  2548. // Read all the records.
  2549. while (true) {
  2550. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  2551. switch (Entry.Kind) {
  2552. case BitstreamEntry::SubBlock: // Handled for us already.
  2553. case BitstreamEntry::Error:
  2554. return error("Malformed block");
  2555. case BitstreamEntry::EndBlock:
  2556. return std::error_code();
  2557. case BitstreamEntry::Record:
  2558. // The interesting case.
  2559. break;
  2560. }
  2561. // Read a record.
  2562. Record.clear();
  2563. unsigned Code = Stream.readRecord(Entry.ID, Record);
  2564. switch (Code) {
  2565. default: // Default behavior: ignore.
  2566. break;
  2567. case bitc::METADATA_KIND: {
  2568. if (std::error_code EC = parseMetadataKindRecord(Record))
  2569. return EC;
  2570. break;
  2571. }
  2572. }
  2573. }
  2574. }
  2575. /// Decode a signed value stored with the sign bit in the LSB for dense VBR
  2576. /// encoding.
  2577. uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
  2578. if ((V & 1) == 0)
  2579. return V >> 1;
  2580. if (V != 1)
  2581. return -(V >> 1);
  2582. // There is no such thing as -0 with integers. "-0" really means MININT.
  2583. return 1ULL << 63;
  2584. }
  2585. /// Resolve all of the initializers for global values and aliases that we can.
  2586. std::error_code BitcodeReader::resolveGlobalAndIndirectSymbolInits() {
  2587. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  2588. std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >
  2589. IndirectSymbolInitWorklist;
  2590. std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
  2591. std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
  2592. std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
  2593. GlobalInitWorklist.swap(GlobalInits);
  2594. IndirectSymbolInitWorklist.swap(IndirectSymbolInits);
  2595. FunctionPrefixWorklist.swap(FunctionPrefixes);
  2596. FunctionPrologueWorklist.swap(FunctionPrologues);
  2597. FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
  2598. while (!GlobalInitWorklist.empty()) {
  2599. unsigned ValID = GlobalInitWorklist.back().second;
  2600. if (ValID >= ValueList.size()) {
  2601. // Not ready to resolve this yet, it requires something later in the file.
  2602. GlobalInits.push_back(GlobalInitWorklist.back());
  2603. } else {
  2604. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  2605. GlobalInitWorklist.back().first->setInitializer(C);
  2606. else
  2607. return error("Expected a constant");
  2608. }
  2609. GlobalInitWorklist.pop_back();
  2610. }
  2611. while (!IndirectSymbolInitWorklist.empty()) {
  2612. unsigned ValID = IndirectSymbolInitWorklist.back().second;
  2613. if (ValID >= ValueList.size()) {
  2614. IndirectSymbolInits.push_back(IndirectSymbolInitWorklist.back());
  2615. } else {
  2616. Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
  2617. if (!C)
  2618. return error("Expected a constant");
  2619. GlobalIndirectSymbol *GIS = IndirectSymbolInitWorklist.back().first;
  2620. if (isa<GlobalAlias>(GIS) && C->getType() != GIS->getType())
  2621. return error("Alias and aliasee types don't match");
  2622. GIS->setIndirectSymbol(C);
  2623. }
  2624. IndirectSymbolInitWorklist.pop_back();
  2625. }
  2626. while (!FunctionPrefixWorklist.empty()) {
  2627. unsigned ValID = FunctionPrefixWorklist.back().second;
  2628. if (ValID >= ValueList.size()) {
  2629. FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
  2630. } else {
  2631. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  2632. FunctionPrefixWorklist.back().first->setPrefixData(C);
  2633. else
  2634. return error("Expected a constant");
  2635. }
  2636. FunctionPrefixWorklist.pop_back();
  2637. }
  2638. while (!FunctionPrologueWorklist.empty()) {
  2639. unsigned ValID = FunctionPrologueWorklist.back().second;
  2640. if (ValID >= ValueList.size()) {
  2641. FunctionPrologues.push_back(FunctionPrologueWorklist.back());
  2642. } else {
  2643. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  2644. FunctionPrologueWorklist.back().first->setPrologueData(C);
  2645. else
  2646. return error("Expected a constant");
  2647. }
  2648. FunctionPrologueWorklist.pop_back();
  2649. }
  2650. while (!FunctionPersonalityFnWorklist.empty()) {
  2651. unsigned ValID = FunctionPersonalityFnWorklist.back().second;
  2652. if (ValID >= ValueList.size()) {
  2653. FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
  2654. } else {
  2655. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  2656. FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
  2657. else
  2658. return error("Expected a constant");
  2659. }
  2660. FunctionPersonalityFnWorklist.pop_back();
  2661. }
  2662. return std::error_code();
  2663. }
  2664. static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
  2665. SmallVector<uint64_t, 8> Words(Vals.size());
  2666. transform(Vals, Words.begin(),
  2667. BitcodeReader::decodeSignRotatedValue);
  2668. return APInt(TypeBits, Words);
  2669. }
  2670. std::error_code BitcodeReader::parseConstants() {
  2671. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  2672. return error("Invalid record");
  2673. SmallVector<uint64_t, 64> Record;
  2674. // Read all the records for this value table.
  2675. Type *CurTy = Type::getInt32Ty(Context);
  2676. unsigned NextCstNo = ValueList.size();
  2677. while (true) {
  2678. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  2679. switch (Entry.Kind) {
  2680. case BitstreamEntry::SubBlock: // Handled for us already.
  2681. case BitstreamEntry::Error:
  2682. return error("Malformed block");
  2683. case BitstreamEntry::EndBlock:
  2684. if (NextCstNo != ValueList.size())
  2685. return error("Invalid constant reference");
  2686. // Once all the constants have been read, go through and resolve forward
  2687. // references.
  2688. ValueList.resolveConstantForwardRefs();
  2689. return std::error_code();
  2690. case BitstreamEntry::Record:
  2691. // The interesting case.
  2692. break;
  2693. }
  2694. // Read a record.
  2695. Record.clear();
  2696. Type *VoidType = Type::getVoidTy(Context);
  2697. Value *V = nullptr;
  2698. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  2699. switch (BitCode) {
  2700. default: // Default behavior: unknown constant
  2701. case bitc::CST_CODE_UNDEF: // UNDEF
  2702. V = UndefValue::get(CurTy);
  2703. break;
  2704. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  2705. if (Record.empty())
  2706. return error("Invalid record");
  2707. if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
  2708. return error("Invalid record");
  2709. if (TypeList[Record[0]] == VoidType)
  2710. return error("Invalid constant type");
  2711. CurTy = TypeList[Record[0]];
  2712. continue; // Skip the ValueList manipulation.
  2713. case bitc::CST_CODE_NULL: // NULL
  2714. V = Constant::getNullValue(CurTy);
  2715. break;
  2716. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  2717. if (!CurTy->isIntegerTy() || Record.empty())
  2718. return error("Invalid record");
  2719. V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
  2720. break;
  2721. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  2722. if (!CurTy->isIntegerTy() || Record.empty())
  2723. return error("Invalid record");
  2724. APInt VInt =
  2725. readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
  2726. V = ConstantInt::get(Context, VInt);
  2727. break;
  2728. }
  2729. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  2730. if (Record.empty())
  2731. return error("Invalid record");
  2732. if (CurTy->isHalfTy())
  2733. V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
  2734. APInt(16, (uint16_t)Record[0])));
  2735. else if (CurTy->isFloatTy())
  2736. V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
  2737. APInt(32, (uint32_t)Record[0])));
  2738. else if (CurTy->isDoubleTy())
  2739. V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
  2740. APInt(64, Record[0])));
  2741. else if (CurTy->isX86_FP80Ty()) {
  2742. // Bits are not stored the same way as a normal i80 APInt, compensate.
  2743. uint64_t Rearrange[2];
  2744. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  2745. Rearrange[1] = Record[0] >> 48;
  2746. V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
  2747. APInt(80, Rearrange)));
  2748. } else if (CurTy->isFP128Ty())
  2749. V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
  2750. APInt(128, Record)));
  2751. else if (CurTy->isPPC_FP128Ty())
  2752. V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
  2753. APInt(128, Record)));
  2754. else
  2755. V = UndefValue::get(CurTy);
  2756. break;
  2757. }
  2758. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  2759. if (Record.empty())
  2760. return error("Invalid record");
  2761. unsigned Size = Record.size();
  2762. SmallVector<Constant*, 16> Elts;
  2763. if (StructType *STy = dyn_cast<StructType>(CurTy)) {
  2764. for (unsigned i = 0; i != Size; ++i)
  2765. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  2766. STy->getElementType(i)));
  2767. V = ConstantStruct::get(STy, Elts);
  2768. } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  2769. Type *EltTy = ATy->getElementType();
  2770. for (unsigned i = 0; i != Size; ++i)
  2771. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  2772. V = ConstantArray::get(ATy, Elts);
  2773. } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  2774. Type *EltTy = VTy->getElementType();
  2775. for (unsigned i = 0; i != Size; ++i)
  2776. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  2777. V = ConstantVector::get(Elts);
  2778. } else {
  2779. V = UndefValue::get(CurTy);
  2780. }
  2781. break;
  2782. }
  2783. case bitc::CST_CODE_STRING: // STRING: [values]
  2784. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  2785. if (Record.empty())
  2786. return error("Invalid record");
  2787. SmallString<16> Elts(Record.begin(), Record.end());
  2788. V = ConstantDataArray::getString(Context, Elts,
  2789. BitCode == bitc::CST_CODE_CSTRING);
  2790. break;
  2791. }
  2792. case bitc::CST_CODE_DATA: {// DATA: [n x value]
  2793. if (Record.empty())
  2794. return error("Invalid record");
  2795. Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
  2796. if (EltTy->isIntegerTy(8)) {
  2797. SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
  2798. if (isa<VectorType>(CurTy))
  2799. V = ConstantDataVector::get(Context, Elts);
  2800. else
  2801. V = ConstantDataArray::get(Context, Elts);
  2802. } else if (EltTy->isIntegerTy(16)) {
  2803. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  2804. if (isa<VectorType>(CurTy))
  2805. V = ConstantDataVector::get(Context, Elts);
  2806. else
  2807. V = ConstantDataArray::get(Context, Elts);
  2808. } else if (EltTy->isIntegerTy(32)) {
  2809. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  2810. if (isa<VectorType>(CurTy))
  2811. V = ConstantDataVector::get(Context, Elts);
  2812. else
  2813. V = ConstantDataArray::get(Context, Elts);
  2814. } else if (EltTy->isIntegerTy(64)) {
  2815. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  2816. if (isa<VectorType>(CurTy))
  2817. V = ConstantDataVector::get(Context, Elts);
  2818. else
  2819. V = ConstantDataArray::get(Context, Elts);
  2820. } else if (EltTy->isHalfTy()) {
  2821. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  2822. if (isa<VectorType>(CurTy))
  2823. V = ConstantDataVector::getFP(Context, Elts);
  2824. else
  2825. V = ConstantDataArray::getFP(Context, Elts);
  2826. } else if (EltTy->isFloatTy()) {
  2827. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  2828. if (isa<VectorType>(CurTy))
  2829. V = ConstantDataVector::getFP(Context, Elts);
  2830. else
  2831. V = ConstantDataArray::getFP(Context, Elts);
  2832. } else if (EltTy->isDoubleTy()) {
  2833. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  2834. if (isa<VectorType>(CurTy))
  2835. V = ConstantDataVector::getFP(Context, Elts);
  2836. else
  2837. V = ConstantDataArray::getFP(Context, Elts);
  2838. } else {
  2839. return error("Invalid type for value");
  2840. }
  2841. break;
  2842. }
  2843. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  2844. if (Record.size() < 3)
  2845. return error("Invalid record");
  2846. int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
  2847. if (Opc < 0) {
  2848. V = UndefValue::get(CurTy); // Unknown binop.
  2849. } else {
  2850. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  2851. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  2852. unsigned Flags = 0;
  2853. if (Record.size() >= 4) {
  2854. if (Opc == Instruction::Add ||
  2855. Opc == Instruction::Sub ||
  2856. Opc == Instruction::Mul ||
  2857. Opc == Instruction::Shl) {
  2858. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  2859. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  2860. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  2861. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  2862. } else if (Opc == Instruction::SDiv ||
  2863. Opc == Instruction::UDiv ||
  2864. Opc == Instruction::LShr ||
  2865. Opc == Instruction::AShr) {
  2866. if (Record[3] & (1 << bitc::PEO_EXACT))
  2867. Flags |= SDivOperator::IsExact;
  2868. }
  2869. }
  2870. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  2871. }
  2872. break;
  2873. }
  2874. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  2875. if (Record.size() < 3)
  2876. return error("Invalid record");
  2877. int Opc = getDecodedCastOpcode(Record[0]);
  2878. if (Opc < 0) {
  2879. V = UndefValue::get(CurTy); // Unknown cast.
  2880. } else {
  2881. Type *OpTy = getTypeByID(Record[1]);
  2882. if (!OpTy)
  2883. return error("Invalid record");
  2884. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  2885. V = UpgradeBitCastExpr(Opc, Op, CurTy);
  2886. if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
  2887. }
  2888. break;
  2889. }
  2890. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  2891. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  2892. unsigned OpNum = 0;
  2893. Type *PointeeType = nullptr;
  2894. if (Record.size() % 2)
  2895. PointeeType = getTypeByID(Record[OpNum++]);
  2896. SmallVector<Constant*, 16> Elts;
  2897. while (OpNum != Record.size()) {
  2898. Type *ElTy = getTypeByID(Record[OpNum++]);
  2899. if (!ElTy)
  2900. return error("Invalid record");
  2901. Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
  2902. }
  2903. if (PointeeType &&
  2904. PointeeType !=
  2905. cast<SequentialType>(Elts[0]->getType()->getScalarType())
  2906. ->getElementType())
  2907. return error("Explicit gep operator type does not match pointee type "
  2908. "of pointer operand");
  2909. if (Elts.size() < 1)
  2910. return error("Invalid gep with no operands");
  2911. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  2912. V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
  2913. BitCode ==
  2914. bitc::CST_CODE_CE_INBOUNDS_GEP);
  2915. break;
  2916. }
  2917. case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
  2918. if (Record.size() < 3)
  2919. return error("Invalid record");
  2920. Type *SelectorTy = Type::getInt1Ty(Context);
  2921. // The selector might be an i1 or an <n x i1>
  2922. // Get the type from the ValueList before getting a forward ref.
  2923. if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
  2924. if (Value *V = ValueList[Record[0]])
  2925. if (SelectorTy != V->getType())
  2926. SelectorTy = VectorType::get(SelectorTy, VTy->getNumElements());
  2927. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  2928. SelectorTy),
  2929. ValueList.getConstantFwdRef(Record[1],CurTy),
  2930. ValueList.getConstantFwdRef(Record[2],CurTy));
  2931. break;
  2932. }
  2933. case bitc::CST_CODE_CE_EXTRACTELT
  2934. : { // CE_EXTRACTELT: [opty, opval, opty, opval]
  2935. if (Record.size() < 3)
  2936. return error("Invalid record");
  2937. VectorType *OpTy =
  2938. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2939. if (!OpTy)
  2940. return error("Invalid record");
  2941. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2942. Constant *Op1 = nullptr;
  2943. if (Record.size() == 4) {
  2944. Type *IdxTy = getTypeByID(Record[2]);
  2945. if (!IdxTy)
  2946. return error("Invalid record");
  2947. Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2948. } else // TODO: Remove with llvm 4.0
  2949. Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2950. if (!Op1)
  2951. return error("Invalid record");
  2952. V = ConstantExpr::getExtractElement(Op0, Op1);
  2953. break;
  2954. }
  2955. case bitc::CST_CODE_CE_INSERTELT
  2956. : { // CE_INSERTELT: [opval, opval, opty, opval]
  2957. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2958. if (Record.size() < 3 || !OpTy)
  2959. return error("Invalid record");
  2960. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2961. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  2962. OpTy->getElementType());
  2963. Constant *Op2 = nullptr;
  2964. if (Record.size() == 4) {
  2965. Type *IdxTy = getTypeByID(Record[2]);
  2966. if (!IdxTy)
  2967. return error("Invalid record");
  2968. Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2969. } else // TODO: Remove with llvm 4.0
  2970. Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2971. if (!Op2)
  2972. return error("Invalid record");
  2973. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  2974. break;
  2975. }
  2976. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  2977. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2978. if (Record.size() < 3 || !OpTy)
  2979. return error("Invalid record");
  2980. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2981. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2982. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2983. OpTy->getNumElements());
  2984. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  2985. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  2986. break;
  2987. }
  2988. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  2989. VectorType *RTy = dyn_cast<VectorType>(CurTy);
  2990. VectorType *OpTy =
  2991. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2992. if (Record.size() < 4 || !RTy || !OpTy)
  2993. return error("Invalid record");
  2994. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2995. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  2996. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2997. RTy->getNumElements());
  2998. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  2999. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  3000. break;
  3001. }
  3002. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  3003. if (Record.size() < 4)
  3004. return error("Invalid record");
  3005. Type *OpTy = getTypeByID(Record[0]);
  3006. if (!OpTy)
  3007. return error("Invalid record");
  3008. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  3009. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  3010. if (OpTy->isFPOrFPVectorTy())
  3011. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  3012. else
  3013. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  3014. break;
  3015. }
  3016. // This maintains backward compatibility, pre-asm dialect keywords.
  3017. // FIXME: Remove with the 4.0 release.
  3018. case bitc::CST_CODE_INLINEASM_OLD: {
  3019. if (Record.size() < 2)
  3020. return error("Invalid record");
  3021. std::string AsmStr, ConstrStr;
  3022. bool HasSideEffects = Record[0] & 1;
  3023. bool IsAlignStack = Record[0] >> 1;
  3024. unsigned AsmStrSize = Record[1];
  3025. if (2+AsmStrSize >= Record.size())
  3026. return error("Invalid record");
  3027. unsigned ConstStrSize = Record[2+AsmStrSize];
  3028. if (3+AsmStrSize+ConstStrSize > Record.size())
  3029. return error("Invalid record");
  3030. for (unsigned i = 0; i != AsmStrSize; ++i)
  3031. AsmStr += (char)Record[2+i];
  3032. for (unsigned i = 0; i != ConstStrSize; ++i)
  3033. ConstrStr += (char)Record[3+AsmStrSize+i];
  3034. PointerType *PTy = cast<PointerType>(CurTy);
  3035. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  3036. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  3037. break;
  3038. }
  3039. // This version adds support for the asm dialect keywords (e.g.,
  3040. // inteldialect).
  3041. case bitc::CST_CODE_INLINEASM: {
  3042. if (Record.size() < 2)
  3043. return error("Invalid record");
  3044. std::string AsmStr, ConstrStr;
  3045. bool HasSideEffects = Record[0] & 1;
  3046. bool IsAlignStack = (Record[0] >> 1) & 1;
  3047. unsigned AsmDialect = Record[0] >> 2;
  3048. unsigned AsmStrSize = Record[1];
  3049. if (2+AsmStrSize >= Record.size())
  3050. return error("Invalid record");
  3051. unsigned ConstStrSize = Record[2+AsmStrSize];
  3052. if (3+AsmStrSize+ConstStrSize > Record.size())
  3053. return error("Invalid record");
  3054. for (unsigned i = 0; i != AsmStrSize; ++i)
  3055. AsmStr += (char)Record[2+i];
  3056. for (unsigned i = 0; i != ConstStrSize; ++i)
  3057. ConstrStr += (char)Record[3+AsmStrSize+i];
  3058. PointerType *PTy = cast<PointerType>(CurTy);
  3059. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  3060. AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
  3061. InlineAsm::AsmDialect(AsmDialect));
  3062. break;
  3063. }
  3064. case bitc::CST_CODE_BLOCKADDRESS:{
  3065. if (Record.size() < 3)
  3066. return error("Invalid record");
  3067. Type *FnTy = getTypeByID(Record[0]);
  3068. if (!FnTy)
  3069. return error("Invalid record");
  3070. Function *Fn =
  3071. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  3072. if (!Fn)
  3073. return error("Invalid record");
  3074. // If the function is already parsed we can insert the block address right
  3075. // away.
  3076. BasicBlock *BB;
  3077. unsigned BBID = Record[2];
  3078. if (!BBID)
  3079. // Invalid reference to entry block.
  3080. return error("Invalid ID");
  3081. if (!Fn->empty()) {
  3082. Function::iterator BBI = Fn->begin(), BBE = Fn->end();
  3083. for (size_t I = 0, E = BBID; I != E; ++I) {
  3084. if (BBI == BBE)
  3085. return error("Invalid ID");
  3086. ++BBI;
  3087. }
  3088. BB = &*BBI;
  3089. } else {
  3090. // Otherwise insert a placeholder and remember it so it can be inserted
  3091. // when the function is parsed.
  3092. auto &FwdBBs = BasicBlockFwdRefs[Fn];
  3093. if (FwdBBs.empty())
  3094. BasicBlockFwdRefQueue.push_back(Fn);
  3095. if (FwdBBs.size() < BBID + 1)
  3096. FwdBBs.resize(BBID + 1);
  3097. if (!FwdBBs[BBID])
  3098. FwdBBs[BBID] = BasicBlock::Create(Context);
  3099. BB = FwdBBs[BBID];
  3100. }
  3101. V = BlockAddress::get(Fn, BB);
  3102. break;
  3103. }
  3104. }
  3105. ValueList.assignValue(V, NextCstNo);
  3106. ++NextCstNo;
  3107. }
  3108. }
  3109. std::error_code BitcodeReader::parseUseLists() {
  3110. if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
  3111. return error("Invalid record");
  3112. // Read all the records.
  3113. SmallVector<uint64_t, 64> Record;
  3114. while (true) {
  3115. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3116. switch (Entry.Kind) {
  3117. case BitstreamEntry::SubBlock: // Handled for us already.
  3118. case BitstreamEntry::Error:
  3119. return error("Malformed block");
  3120. case BitstreamEntry::EndBlock:
  3121. return std::error_code();
  3122. case BitstreamEntry::Record:
  3123. // The interesting case.
  3124. break;
  3125. }
  3126. // Read a use list record.
  3127. Record.clear();
  3128. bool IsBB = false;
  3129. switch (Stream.readRecord(Entry.ID, Record)) {
  3130. default: // Default behavior: unknown type.
  3131. break;
  3132. case bitc::USELIST_CODE_BB:
  3133. IsBB = true;
  3134. LLVM_FALLTHROUGH;
  3135. case bitc::USELIST_CODE_DEFAULT: {
  3136. unsigned RecordLength = Record.size();
  3137. if (RecordLength < 3)
  3138. // Records should have at least an ID and two indexes.
  3139. return error("Invalid record");
  3140. unsigned ID = Record.back();
  3141. Record.pop_back();
  3142. Value *V;
  3143. if (IsBB) {
  3144. assert(ID < FunctionBBs.size() && "Basic block not found");
  3145. V = FunctionBBs[ID];
  3146. } else
  3147. V = ValueList[ID];
  3148. unsigned NumUses = 0;
  3149. SmallDenseMap<const Use *, unsigned, 16> Order;
  3150. for (const Use &U : V->materialized_uses()) {
  3151. if (++NumUses > Record.size())
  3152. break;
  3153. Order[&U] = Record[NumUses - 1];
  3154. }
  3155. if (Order.size() != Record.size() || NumUses > Record.size())
  3156. // Mismatches can happen if the functions are being materialized lazily
  3157. // (out-of-order), or a value has been upgraded.
  3158. break;
  3159. V->sortUseList([&](const Use &L, const Use &R) {
  3160. return Order.lookup(&L) < Order.lookup(&R);
  3161. });
  3162. break;
  3163. }
  3164. }
  3165. }
  3166. }
  3167. /// When we see the block for metadata, remember where it is and then skip it.
  3168. /// This lets us lazily deserialize the metadata.
  3169. std::error_code BitcodeReader::rememberAndSkipMetadata() {
  3170. // Save the current stream state.
  3171. uint64_t CurBit = Stream.GetCurrentBitNo();
  3172. DeferredMetadataInfo.push_back(CurBit);
  3173. // Skip over the block for now.
  3174. if (Stream.SkipBlock())
  3175. return error("Invalid record");
  3176. return std::error_code();
  3177. }
  3178. std::error_code BitcodeReader::materializeMetadata() {
  3179. for (uint64_t BitPos : DeferredMetadataInfo) {
  3180. // Move the bit stream to the saved position.
  3181. Stream.JumpToBit(BitPos);
  3182. if (std::error_code EC = parseMetadata(true))
  3183. return EC;
  3184. }
  3185. DeferredMetadataInfo.clear();
  3186. return std::error_code();
  3187. }
  3188. void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
  3189. /// When we see the block for a function body, remember where it is and then
  3190. /// skip it. This lets us lazily deserialize the functions.
  3191. std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
  3192. // Get the function we are talking about.
  3193. if (FunctionsWithBodies.empty())
  3194. return error("Insufficient function protos");
  3195. Function *Fn = FunctionsWithBodies.back();
  3196. FunctionsWithBodies.pop_back();
  3197. // Save the current stream state.
  3198. uint64_t CurBit = Stream.GetCurrentBitNo();
  3199. assert(
  3200. (DeferredFunctionInfo[Fn] == 0 || DeferredFunctionInfo[Fn] == CurBit) &&
  3201. "Mismatch between VST and scanned function offsets");
  3202. DeferredFunctionInfo[Fn] = CurBit;
  3203. // Skip over the function block for now.
  3204. if (Stream.SkipBlock())
  3205. return error("Invalid record");
  3206. return std::error_code();
  3207. }
  3208. std::error_code BitcodeReader::globalCleanup() {
  3209. // Patch the initializers for globals and aliases up.
  3210. resolveGlobalAndIndirectSymbolInits();
  3211. if (!GlobalInits.empty() || !IndirectSymbolInits.empty())
  3212. return error("Malformed global initializer set");
  3213. // Look for intrinsic functions which need to be upgraded at some point
  3214. for (Function &F : *TheModule) {
  3215. Function *NewFn;
  3216. if (UpgradeIntrinsicFunction(&F, NewFn))
  3217. UpgradedIntrinsics[&F] = NewFn;
  3218. else if (auto Remangled = Intrinsic::remangleIntrinsicFunction(&F))
  3219. // Some types could be renamed during loading if several modules are
  3220. // loaded in the same LLVMContext (LTO scenario). In this case we should
  3221. // remangle intrinsics names as well.
  3222. RemangledIntrinsics[&F] = Remangled.getValue();
  3223. }
  3224. // Look for global variables which need to be renamed.
  3225. for (GlobalVariable &GV : TheModule->globals())
  3226. UpgradeGlobalVariable(&GV);
  3227. // Force deallocation of memory for these vectors to favor the client that
  3228. // want lazy deserialization.
  3229. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  3230. std::vector<std::pair<GlobalIndirectSymbol*, unsigned> >().swap(
  3231. IndirectSymbolInits);
  3232. return std::error_code();
  3233. }
  3234. /// Support for lazy parsing of function bodies. This is required if we
  3235. /// either have an old bitcode file without a VST forward declaration record,
  3236. /// or if we have an anonymous function being materialized, since anonymous
  3237. /// functions do not have a name and are therefore not in the VST.
  3238. std::error_code BitcodeReader::rememberAndSkipFunctionBodies() {
  3239. Stream.JumpToBit(NextUnreadBit);
  3240. if (Stream.AtEndOfStream())
  3241. return error("Could not find function in stream");
  3242. if (!SeenFirstFunctionBody)
  3243. return error("Trying to materialize functions before seeing function blocks");
  3244. // An old bitcode file with the symbol table at the end would have
  3245. // finished the parse greedily.
  3246. assert(SeenValueSymbolTable);
  3247. SmallVector<uint64_t, 64> Record;
  3248. while (true) {
  3249. BitstreamEntry Entry = Stream.advance();
  3250. switch (Entry.Kind) {
  3251. default:
  3252. return error("Expect SubBlock");
  3253. case BitstreamEntry::SubBlock:
  3254. switch (Entry.ID) {
  3255. default:
  3256. return error("Expect function block");
  3257. case bitc::FUNCTION_BLOCK_ID:
  3258. if (std::error_code EC = rememberAndSkipFunctionBody())
  3259. return EC;
  3260. NextUnreadBit = Stream.GetCurrentBitNo();
  3261. return std::error_code();
  3262. }
  3263. }
  3264. }
  3265. }
  3266. std::error_code BitcodeReader::parseBitcodeVersion() {
  3267. if (Stream.EnterSubBlock(bitc::IDENTIFICATION_BLOCK_ID))
  3268. return error("Invalid record");
  3269. // Read all the records.
  3270. SmallVector<uint64_t, 64> Record;
  3271. while (true) {
  3272. BitstreamEntry Entry = Stream.advance();
  3273. switch (Entry.Kind) {
  3274. default:
  3275. case BitstreamEntry::Error:
  3276. return error("Malformed block");
  3277. case BitstreamEntry::EndBlock:
  3278. return std::error_code();
  3279. case BitstreamEntry::Record:
  3280. // The interesting case.
  3281. break;
  3282. }
  3283. // Read a record.
  3284. Record.clear();
  3285. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  3286. switch (BitCode) {
  3287. default: // Default behavior: reject
  3288. return error("Invalid value");
  3289. case bitc::IDENTIFICATION_CODE_STRING: { // IDENTIFICATION: [strchr x
  3290. // N]
  3291. convertToString(Record, 0, ProducerIdentification);
  3292. break;
  3293. }
  3294. case bitc::IDENTIFICATION_CODE_EPOCH: { // EPOCH: [epoch#]
  3295. unsigned epoch = (unsigned)Record[0];
  3296. if (epoch != bitc::BITCODE_CURRENT_EPOCH) {
  3297. return error(
  3298. Twine("Incompatible epoch: Bitcode '") + Twine(epoch) +
  3299. "' vs current: '" + Twine(bitc::BITCODE_CURRENT_EPOCH) + "'");
  3300. }
  3301. }
  3302. }
  3303. }
  3304. }
  3305. bool BitcodeReaderBase::readBlockInfo() {
  3306. Optional<BitstreamBlockInfo> NewBlockInfo = Stream.ReadBlockInfoBlock();
  3307. if (!NewBlockInfo)
  3308. return true;
  3309. BlockInfo = std::move(*NewBlockInfo);
  3310. return false;
  3311. }
  3312. std::error_code BitcodeReader::parseModule(uint64_t ResumeBit,
  3313. bool ShouldLazyLoadMetadata) {
  3314. if (ResumeBit)
  3315. Stream.JumpToBit(ResumeBit);
  3316. else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  3317. return error("Invalid record");
  3318. SmallVector<uint64_t, 64> Record;
  3319. std::vector<std::string> SectionTable;
  3320. std::vector<std::string> GCTable;
  3321. // Read all the records for this module.
  3322. while (true) {
  3323. BitstreamEntry Entry = Stream.advance();
  3324. switch (Entry.Kind) {
  3325. case BitstreamEntry::Error:
  3326. return error("Malformed block");
  3327. case BitstreamEntry::EndBlock:
  3328. return globalCleanup();
  3329. case BitstreamEntry::SubBlock:
  3330. switch (Entry.ID) {
  3331. default: // Skip unknown content.
  3332. if (Stream.SkipBlock())
  3333. return error("Invalid record");
  3334. break;
  3335. case bitc::BLOCKINFO_BLOCK_ID:
  3336. if (readBlockInfo())
  3337. return error("Malformed block");
  3338. break;
  3339. case bitc::PARAMATTR_BLOCK_ID:
  3340. if (std::error_code EC = parseAttributeBlock())
  3341. return EC;
  3342. break;
  3343. case bitc::PARAMATTR_GROUP_BLOCK_ID:
  3344. if (std::error_code EC = parseAttributeGroupBlock())
  3345. return EC;
  3346. break;
  3347. case bitc::TYPE_BLOCK_ID_NEW:
  3348. if (std::error_code EC = parseTypeTable())
  3349. return EC;
  3350. break;
  3351. case bitc::VALUE_SYMTAB_BLOCK_ID:
  3352. if (!SeenValueSymbolTable) {
  3353. // Either this is an old form VST without function index and an
  3354. // associated VST forward declaration record (which would have caused
  3355. // the VST to be jumped to and parsed before it was encountered
  3356. // normally in the stream), or there were no function blocks to
  3357. // trigger an earlier parsing of the VST.
  3358. assert(VSTOffset == 0 || FunctionsWithBodies.empty());
  3359. if (std::error_code EC = parseValueSymbolTable())
  3360. return EC;
  3361. SeenValueSymbolTable = true;
  3362. } else {
  3363. // We must have had a VST forward declaration record, which caused
  3364. // the parser to jump to and parse the VST earlier.
  3365. assert(VSTOffset > 0);
  3366. if (Stream.SkipBlock())
  3367. return error("Invalid record");
  3368. }
  3369. break;
  3370. case bitc::CONSTANTS_BLOCK_ID:
  3371. if (std::error_code EC = parseConstants())
  3372. return EC;
  3373. if (std::error_code EC = resolveGlobalAndIndirectSymbolInits())
  3374. return EC;
  3375. break;
  3376. case bitc::METADATA_BLOCK_ID:
  3377. if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
  3378. if (std::error_code EC = rememberAndSkipMetadata())
  3379. return EC;
  3380. break;
  3381. }
  3382. assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
  3383. if (std::error_code EC = parseMetadata(true))
  3384. return EC;
  3385. break;
  3386. case bitc::METADATA_KIND_BLOCK_ID:
  3387. if (std::error_code EC = parseMetadataKinds())
  3388. return EC;
  3389. break;
  3390. case bitc::FUNCTION_BLOCK_ID:
  3391. // If this is the first function body we've seen, reverse the
  3392. // FunctionsWithBodies list.
  3393. if (!SeenFirstFunctionBody) {
  3394. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  3395. if (std::error_code EC = globalCleanup())
  3396. return EC;
  3397. SeenFirstFunctionBody = true;
  3398. }
  3399. if (VSTOffset > 0) {
  3400. // If we have a VST forward declaration record, make sure we
  3401. // parse the VST now if we haven't already. It is needed to
  3402. // set up the DeferredFunctionInfo vector for lazy reading.
  3403. if (!SeenValueSymbolTable) {
  3404. if (std::error_code EC =
  3405. BitcodeReader::parseValueSymbolTable(VSTOffset))
  3406. return EC;
  3407. SeenValueSymbolTable = true;
  3408. // Fall through so that we record the NextUnreadBit below.
  3409. // This is necessary in case we have an anonymous function that
  3410. // is later materialized. Since it will not have a VST entry we
  3411. // need to fall back to the lazy parse to find its offset.
  3412. } else {
  3413. // If we have a VST forward declaration record, but have already
  3414. // parsed the VST (just above, when the first function body was
  3415. // encountered here), then we are resuming the parse after
  3416. // materializing functions. The ResumeBit points to the
  3417. // start of the last function block recorded in the
  3418. // DeferredFunctionInfo map. Skip it.
  3419. if (Stream.SkipBlock())
  3420. return error("Invalid record");
  3421. continue;
  3422. }
  3423. }
  3424. // Support older bitcode files that did not have the function
  3425. // index in the VST, nor a VST forward declaration record, as
  3426. // well as anonymous functions that do not have VST entries.
  3427. // Build the DeferredFunctionInfo vector on the fly.
  3428. if (std::error_code EC = rememberAndSkipFunctionBody())
  3429. return EC;
  3430. // Suspend parsing when we reach the function bodies. Subsequent
  3431. // materialization calls will resume it when necessary. If the bitcode
  3432. // file is old, the symbol table will be at the end instead and will not
  3433. // have been seen yet. In this case, just finish the parse now.
  3434. if (SeenValueSymbolTable) {
  3435. NextUnreadBit = Stream.GetCurrentBitNo();
  3436. // After the VST has been parsed, we need to make sure intrinsic name
  3437. // are auto-upgraded.
  3438. return globalCleanup();
  3439. }
  3440. break;
  3441. case bitc::USELIST_BLOCK_ID:
  3442. if (std::error_code EC = parseUseLists())
  3443. return EC;
  3444. break;
  3445. case bitc::OPERAND_BUNDLE_TAGS_BLOCK_ID:
  3446. if (std::error_code EC = parseOperandBundleTags())
  3447. return EC;
  3448. break;
  3449. }
  3450. continue;
  3451. case BitstreamEntry::Record:
  3452. // The interesting case.
  3453. break;
  3454. }
  3455. // Read a record.
  3456. auto BitCode = Stream.readRecord(Entry.ID, Record);
  3457. switch (BitCode) {
  3458. default: break; // Default behavior, ignore unknown content.
  3459. case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
  3460. if (Record.size() < 1)
  3461. return error("Invalid record");
  3462. // Only version #0 and #1 are supported so far.
  3463. unsigned module_version = Record[0];
  3464. switch (module_version) {
  3465. default:
  3466. return error("Invalid value");
  3467. case 0:
  3468. UseRelativeIDs = false;
  3469. break;
  3470. case 1:
  3471. UseRelativeIDs = true;
  3472. break;
  3473. }
  3474. break;
  3475. }
  3476. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  3477. std::string S;
  3478. if (convertToString(Record, 0, S))
  3479. return error("Invalid record");
  3480. TheModule->setTargetTriple(S);
  3481. break;
  3482. }
  3483. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  3484. std::string S;
  3485. if (convertToString(Record, 0, S))
  3486. return error("Invalid record");
  3487. TheModule->setDataLayout(S);
  3488. break;
  3489. }
  3490. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  3491. std::string S;
  3492. if (convertToString(Record, 0, S))
  3493. return error("Invalid record");
  3494. TheModule->setModuleInlineAsm(S);
  3495. break;
  3496. }
  3497. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  3498. // FIXME: Remove in 4.0.
  3499. std::string S;
  3500. if (convertToString(Record, 0, S))
  3501. return error("Invalid record");
  3502. // Ignore value.
  3503. break;
  3504. }
  3505. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  3506. std::string S;
  3507. if (convertToString(Record, 0, S))
  3508. return error("Invalid record");
  3509. SectionTable.push_back(S);
  3510. break;
  3511. }
  3512. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  3513. std::string S;
  3514. if (convertToString(Record, 0, S))
  3515. return error("Invalid record");
  3516. GCTable.push_back(S);
  3517. break;
  3518. }
  3519. case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
  3520. if (Record.size() < 2)
  3521. return error("Invalid record");
  3522. Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
  3523. unsigned ComdatNameSize = Record[1];
  3524. std::string ComdatName;
  3525. ComdatName.reserve(ComdatNameSize);
  3526. for (unsigned i = 0; i != ComdatNameSize; ++i)
  3527. ComdatName += (char)Record[2 + i];
  3528. Comdat *C = TheModule->getOrInsertComdat(ComdatName);
  3529. C->setSelectionKind(SK);
  3530. ComdatList.push_back(C);
  3531. break;
  3532. }
  3533. // GLOBALVAR: [pointer type, isconst, initid,
  3534. // linkage, alignment, section, visibility, threadlocal,
  3535. // unnamed_addr, externally_initialized, dllstorageclass,
  3536. // comdat]
  3537. case bitc::MODULE_CODE_GLOBALVAR: {
  3538. if (Record.size() < 6)
  3539. return error("Invalid record");
  3540. Type *Ty = getTypeByID(Record[0]);
  3541. if (!Ty)
  3542. return error("Invalid record");
  3543. bool isConstant = Record[1] & 1;
  3544. bool explicitType = Record[1] & 2;
  3545. unsigned AddressSpace;
  3546. if (explicitType) {
  3547. AddressSpace = Record[1] >> 2;
  3548. } else {
  3549. if (!Ty->isPointerTy())
  3550. return error("Invalid type for value");
  3551. AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  3552. Ty = cast<PointerType>(Ty)->getElementType();
  3553. }
  3554. uint64_t RawLinkage = Record[3];
  3555. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  3556. unsigned Alignment;
  3557. if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
  3558. return EC;
  3559. std::string Section;
  3560. if (Record[5]) {
  3561. if (Record[5]-1 >= SectionTable.size())
  3562. return error("Invalid ID");
  3563. Section = SectionTable[Record[5]-1];
  3564. }
  3565. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  3566. // Local linkage must have default visibility.
  3567. if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
  3568. // FIXME: Change to an error if non-default in 4.0.
  3569. Visibility = getDecodedVisibility(Record[6]);
  3570. GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
  3571. if (Record.size() > 7)
  3572. TLM = getDecodedThreadLocalMode(Record[7]);
  3573. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
  3574. if (Record.size() > 8)
  3575. UnnamedAddr = getDecodedUnnamedAddrType(Record[8]);
  3576. bool ExternallyInitialized = false;
  3577. if (Record.size() > 9)
  3578. ExternallyInitialized = Record[9];
  3579. GlobalVariable *NewGV =
  3580. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
  3581. TLM, AddressSpace, ExternallyInitialized);
  3582. NewGV->setAlignment(Alignment);
  3583. if (!Section.empty())
  3584. NewGV->setSection(Section);
  3585. NewGV->setVisibility(Visibility);
  3586. NewGV->setUnnamedAddr(UnnamedAddr);
  3587. if (Record.size() > 10)
  3588. NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
  3589. else
  3590. upgradeDLLImportExportLinkage(NewGV, RawLinkage);
  3591. ValueList.push_back(NewGV);
  3592. // Remember which value to use for the global initializer.
  3593. if (unsigned InitID = Record[2])
  3594. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  3595. if (Record.size() > 11) {
  3596. if (unsigned ComdatID = Record[11]) {
  3597. if (ComdatID > ComdatList.size())
  3598. return error("Invalid global variable comdat ID");
  3599. NewGV->setComdat(ComdatList[ComdatID - 1]);
  3600. }
  3601. } else if (hasImplicitComdat(RawLinkage)) {
  3602. NewGV->setComdat(reinterpret_cast<Comdat *>(1));
  3603. }
  3604. break;
  3605. }
  3606. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  3607. // alignment, section, visibility, gc, unnamed_addr,
  3608. // prologuedata, dllstorageclass, comdat, prefixdata]
  3609. case bitc::MODULE_CODE_FUNCTION: {
  3610. if (Record.size() < 8)
  3611. return error("Invalid record");
  3612. Type *Ty = getTypeByID(Record[0]);
  3613. if (!Ty)
  3614. return error("Invalid record");
  3615. if (auto *PTy = dyn_cast<PointerType>(Ty))
  3616. Ty = PTy->getElementType();
  3617. auto *FTy = dyn_cast<FunctionType>(Ty);
  3618. if (!FTy)
  3619. return error("Invalid type for value");
  3620. auto CC = static_cast<CallingConv::ID>(Record[1]);
  3621. if (CC & ~CallingConv::MaxID)
  3622. return error("Invalid calling convention ID");
  3623. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  3624. "", TheModule);
  3625. Func->setCallingConv(CC);
  3626. bool isProto = Record[2];
  3627. uint64_t RawLinkage = Record[3];
  3628. Func->setLinkage(getDecodedLinkage(RawLinkage));
  3629. Func->setAttributes(getAttributes(Record[4]));
  3630. unsigned Alignment;
  3631. if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
  3632. return EC;
  3633. Func->setAlignment(Alignment);
  3634. if (Record[6]) {
  3635. if (Record[6]-1 >= SectionTable.size())
  3636. return error("Invalid ID");
  3637. Func->setSection(SectionTable[Record[6]-1]);
  3638. }
  3639. // Local linkage must have default visibility.
  3640. if (!Func->hasLocalLinkage())
  3641. // FIXME: Change to an error if non-default in 4.0.
  3642. Func->setVisibility(getDecodedVisibility(Record[7]));
  3643. if (Record.size() > 8 && Record[8]) {
  3644. if (Record[8]-1 >= GCTable.size())
  3645. return error("Invalid ID");
  3646. Func->setGC(GCTable[Record[8] - 1]);
  3647. }
  3648. GlobalValue::UnnamedAddr UnnamedAddr = GlobalValue::UnnamedAddr::None;
  3649. if (Record.size() > 9)
  3650. UnnamedAddr = getDecodedUnnamedAddrType(Record[9]);
  3651. Func->setUnnamedAddr(UnnamedAddr);
  3652. if (Record.size() > 10 && Record[10] != 0)
  3653. FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
  3654. if (Record.size() > 11)
  3655. Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
  3656. else
  3657. upgradeDLLImportExportLinkage(Func, RawLinkage);
  3658. if (Record.size() > 12) {
  3659. if (unsigned ComdatID = Record[12]) {
  3660. if (ComdatID > ComdatList.size())
  3661. return error("Invalid function comdat ID");
  3662. Func->setComdat(ComdatList[ComdatID - 1]);
  3663. }
  3664. } else if (hasImplicitComdat(RawLinkage)) {
  3665. Func->setComdat(reinterpret_cast<Comdat *>(1));
  3666. }
  3667. if (Record.size() > 13 && Record[13] != 0)
  3668. FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
  3669. if (Record.size() > 14 && Record[14] != 0)
  3670. FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
  3671. ValueList.push_back(Func);
  3672. // If this is a function with a body, remember the prototype we are
  3673. // creating now, so that we can match up the body with them later.
  3674. if (!isProto) {
  3675. Func->setIsMaterializable(true);
  3676. FunctionsWithBodies.push_back(Func);
  3677. DeferredFunctionInfo[Func] = 0;
  3678. }
  3679. break;
  3680. }
  3681. // ALIAS: [alias type, addrspace, aliasee val#, linkage]
  3682. // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
  3683. // IFUNC: [alias type, addrspace, aliasee val#, linkage, visibility, dllstorageclass]
  3684. case bitc::MODULE_CODE_IFUNC:
  3685. case bitc::MODULE_CODE_ALIAS:
  3686. case bitc::MODULE_CODE_ALIAS_OLD: {
  3687. bool NewRecord = BitCode != bitc::MODULE_CODE_ALIAS_OLD;
  3688. if (Record.size() < (3 + (unsigned)NewRecord))
  3689. return error("Invalid record");
  3690. unsigned OpNum = 0;
  3691. Type *Ty = getTypeByID(Record[OpNum++]);
  3692. if (!Ty)
  3693. return error("Invalid record");
  3694. unsigned AddrSpace;
  3695. if (!NewRecord) {
  3696. auto *PTy = dyn_cast<PointerType>(Ty);
  3697. if (!PTy)
  3698. return error("Invalid type for value");
  3699. Ty = PTy->getElementType();
  3700. AddrSpace = PTy->getAddressSpace();
  3701. } else {
  3702. AddrSpace = Record[OpNum++];
  3703. }
  3704. auto Val = Record[OpNum++];
  3705. auto Linkage = Record[OpNum++];
  3706. GlobalIndirectSymbol *NewGA;
  3707. if (BitCode == bitc::MODULE_CODE_ALIAS ||
  3708. BitCode == bitc::MODULE_CODE_ALIAS_OLD)
  3709. NewGA = GlobalAlias::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
  3710. "", TheModule);
  3711. else
  3712. NewGA = GlobalIFunc::create(Ty, AddrSpace, getDecodedLinkage(Linkage),
  3713. "", nullptr, TheModule);
  3714. // Old bitcode files didn't have visibility field.
  3715. // Local linkage must have default visibility.
  3716. if (OpNum != Record.size()) {
  3717. auto VisInd = OpNum++;
  3718. if (!NewGA->hasLocalLinkage())
  3719. // FIXME: Change to an error if non-default in 4.0.
  3720. NewGA->setVisibility(getDecodedVisibility(Record[VisInd]));
  3721. }
  3722. if (OpNum != Record.size())
  3723. NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[OpNum++]));
  3724. else
  3725. upgradeDLLImportExportLinkage(NewGA, Linkage);
  3726. if (OpNum != Record.size())
  3727. NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[OpNum++]));
  3728. if (OpNum != Record.size())
  3729. NewGA->setUnnamedAddr(getDecodedUnnamedAddrType(Record[OpNum++]));
  3730. ValueList.push_back(NewGA);
  3731. IndirectSymbolInits.push_back(std::make_pair(NewGA, Val));
  3732. break;
  3733. }
  3734. /// MODULE_CODE_PURGEVALS: [numvals]
  3735. case bitc::MODULE_CODE_PURGEVALS:
  3736. // Trim down the value list to the specified size.
  3737. if (Record.size() < 1 || Record[0] > ValueList.size())
  3738. return error("Invalid record");
  3739. ValueList.shrinkTo(Record[0]);
  3740. break;
  3741. /// MODULE_CODE_VSTOFFSET: [offset]
  3742. case bitc::MODULE_CODE_VSTOFFSET:
  3743. if (Record.size() < 1)
  3744. return error("Invalid record");
  3745. VSTOffset = Record[0];
  3746. break;
  3747. /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  3748. case bitc::MODULE_CODE_SOURCE_FILENAME:
  3749. SmallString<128> ValueName;
  3750. if (convertToString(Record, 0, ValueName))
  3751. return error("Invalid record");
  3752. TheModule->setSourceFileName(ValueName);
  3753. break;
  3754. }
  3755. Record.clear();
  3756. }
  3757. }
  3758. /// Helper to read the header common to all bitcode files.
  3759. static bool hasValidBitcodeHeader(BitstreamCursor &Stream) {
  3760. // Sniff for the signature.
  3761. if (!Stream.canSkipToPos(4) ||
  3762. Stream.Read(8) != 'B' ||
  3763. Stream.Read(8) != 'C' ||
  3764. Stream.Read(4) != 0x0 ||
  3765. Stream.Read(4) != 0xC ||
  3766. Stream.Read(4) != 0xE ||
  3767. Stream.Read(4) != 0xD)
  3768. return false;
  3769. return true;
  3770. }
  3771. std::error_code BitcodeReader::parseBitcodeInto(Module *M,
  3772. bool ShouldLazyLoadMetadata) {
  3773. TheModule = M;
  3774. if (std::error_code EC = initStream())
  3775. return EC;
  3776. // Sniff for the signature.
  3777. if (!hasValidBitcodeHeader(Stream))
  3778. return error("Invalid bitcode signature");
  3779. // We expect a number of well-defined blocks, though we don't necessarily
  3780. // need to understand them all.
  3781. while (true) {
  3782. if (Stream.AtEndOfStream()) {
  3783. // We didn't really read a proper Module.
  3784. return error("Malformed IR file");
  3785. }
  3786. BitstreamEntry Entry =
  3787. Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
  3788. if (Entry.Kind != BitstreamEntry::SubBlock)
  3789. return error("Malformed block");
  3790. if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
  3791. parseBitcodeVersion();
  3792. continue;
  3793. }
  3794. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  3795. return parseModule(0, ShouldLazyLoadMetadata);
  3796. if (Stream.SkipBlock())
  3797. return error("Invalid record");
  3798. }
  3799. }
  3800. ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
  3801. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  3802. return error("Invalid record");
  3803. SmallVector<uint64_t, 64> Record;
  3804. std::string Triple;
  3805. // Read all the records for this module.
  3806. while (true) {
  3807. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3808. switch (Entry.Kind) {
  3809. case BitstreamEntry::SubBlock: // Handled for us already.
  3810. case BitstreamEntry::Error:
  3811. return error("Malformed block");
  3812. case BitstreamEntry::EndBlock:
  3813. return Triple;
  3814. case BitstreamEntry::Record:
  3815. // The interesting case.
  3816. break;
  3817. }
  3818. // Read a record.
  3819. switch (Stream.readRecord(Entry.ID, Record)) {
  3820. default: break; // Default behavior, ignore unknown content.
  3821. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  3822. std::string S;
  3823. if (convertToString(Record, 0, S))
  3824. return error("Invalid record");
  3825. Triple = S;
  3826. break;
  3827. }
  3828. }
  3829. Record.clear();
  3830. }
  3831. llvm_unreachable("Exit infinite loop");
  3832. }
  3833. ErrorOr<std::string> BitcodeReader::parseTriple() {
  3834. if (std::error_code EC = initStream())
  3835. return EC;
  3836. // Sniff for the signature.
  3837. if (!hasValidBitcodeHeader(Stream))
  3838. return error("Invalid bitcode signature");
  3839. // We expect a number of well-defined blocks, though we don't necessarily
  3840. // need to understand them all.
  3841. while (true) {
  3842. BitstreamEntry Entry = Stream.advance();
  3843. switch (Entry.Kind) {
  3844. case BitstreamEntry::Error:
  3845. return error("Malformed block");
  3846. case BitstreamEntry::EndBlock:
  3847. return std::error_code();
  3848. case BitstreamEntry::SubBlock:
  3849. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  3850. return parseModuleTriple();
  3851. // Ignore other sub-blocks.
  3852. if (Stream.SkipBlock())
  3853. return error("Malformed block");
  3854. continue;
  3855. case BitstreamEntry::Record:
  3856. Stream.skipRecord(Entry.ID);
  3857. continue;
  3858. }
  3859. }
  3860. }
  3861. ErrorOr<std::string> BitcodeReader::parseIdentificationBlock() {
  3862. if (std::error_code EC = initStream())
  3863. return EC;
  3864. // Sniff for the signature.
  3865. if (!hasValidBitcodeHeader(Stream))
  3866. return error("Invalid bitcode signature");
  3867. // We expect a number of well-defined blocks, though we don't necessarily
  3868. // need to understand them all.
  3869. while (true) {
  3870. BitstreamEntry Entry = Stream.advance();
  3871. switch (Entry.Kind) {
  3872. case BitstreamEntry::Error:
  3873. return error("Malformed block");
  3874. case BitstreamEntry::EndBlock:
  3875. return std::error_code();
  3876. case BitstreamEntry::SubBlock:
  3877. if (Entry.ID == bitc::IDENTIFICATION_BLOCK_ID) {
  3878. if (std::error_code EC = parseBitcodeVersion())
  3879. return EC;
  3880. return ProducerIdentification;
  3881. }
  3882. // Ignore other sub-blocks.
  3883. if (Stream.SkipBlock())
  3884. return error("Malformed block");
  3885. continue;
  3886. case BitstreamEntry::Record:
  3887. Stream.skipRecord(Entry.ID);
  3888. continue;
  3889. }
  3890. }
  3891. }
  3892. std::error_code BitcodeReader::parseGlobalObjectAttachment(
  3893. GlobalObject &GO, ArrayRef<uint64_t> Record) {
  3894. assert(Record.size() % 2 == 0);
  3895. for (unsigned I = 0, E = Record.size(); I != E; I += 2) {
  3896. auto K = MDKindMap.find(Record[I]);
  3897. if (K == MDKindMap.end())
  3898. return error("Invalid ID");
  3899. MDNode *MD = MetadataList.getMDNodeFwdRefOrNull(Record[I + 1]);
  3900. if (!MD)
  3901. return error("Invalid metadata attachment");
  3902. GO.addMetadata(K->second, *MD);
  3903. }
  3904. return std::error_code();
  3905. }
  3906. ErrorOr<bool> BitcodeReader::hasObjCCategory() {
  3907. if (std::error_code EC = initStream())
  3908. return EC;
  3909. // Sniff for the signature.
  3910. if (!hasValidBitcodeHeader(Stream))
  3911. return error("Invalid bitcode signature");
  3912. // We expect a number of well-defined blocks, though we don't necessarily
  3913. // need to understand them all.
  3914. while (true) {
  3915. BitstreamEntry Entry = Stream.advance();
  3916. switch (Entry.Kind) {
  3917. case BitstreamEntry::Error:
  3918. return error("Malformed block");
  3919. case BitstreamEntry::EndBlock:
  3920. return std::error_code();
  3921. case BitstreamEntry::SubBlock:
  3922. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  3923. return hasObjCCategoryInModule();
  3924. // Ignore other sub-blocks.
  3925. if (Stream.SkipBlock())
  3926. return error("Malformed block");
  3927. continue;
  3928. case BitstreamEntry::Record:
  3929. Stream.skipRecord(Entry.ID);
  3930. continue;
  3931. }
  3932. }
  3933. }
  3934. ErrorOr<bool> BitcodeReader::hasObjCCategoryInModule() {
  3935. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  3936. return error("Invalid record");
  3937. SmallVector<uint64_t, 64> Record;
  3938. // Read all the records for this module.
  3939. while (true) {
  3940. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3941. switch (Entry.Kind) {
  3942. case BitstreamEntry::SubBlock: // Handled for us already.
  3943. case BitstreamEntry::Error:
  3944. return error("Malformed block");
  3945. case BitstreamEntry::EndBlock:
  3946. return false;
  3947. case BitstreamEntry::Record:
  3948. // The interesting case.
  3949. break;
  3950. }
  3951. // Read a record.
  3952. switch (Stream.readRecord(Entry.ID, Record)) {
  3953. default:
  3954. break; // Default behavior, ignore unknown content.
  3955. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  3956. std::string S;
  3957. if (convertToString(Record, 0, S))
  3958. return error("Invalid record");
  3959. // Check for the i386 and other (x86_64, ARM) conventions
  3960. if (S.find("__DATA, __objc_catlist") != std::string::npos ||
  3961. S.find("__OBJC,__category") != std::string::npos)
  3962. return true;
  3963. break;
  3964. }
  3965. }
  3966. Record.clear();
  3967. }
  3968. llvm_unreachable("Exit infinite loop");
  3969. }
  3970. /// Parse metadata attachments.
  3971. std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
  3972. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  3973. return error("Invalid record");
  3974. SmallVector<uint64_t, 64> Record;
  3975. while (true) {
  3976. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  3977. switch (Entry.Kind) {
  3978. case BitstreamEntry::SubBlock: // Handled for us already.
  3979. case BitstreamEntry::Error:
  3980. return error("Malformed block");
  3981. case BitstreamEntry::EndBlock:
  3982. return std::error_code();
  3983. case BitstreamEntry::Record:
  3984. // The interesting case.
  3985. break;
  3986. }
  3987. // Read a metadata attachment record.
  3988. Record.clear();
  3989. switch (Stream.readRecord(Entry.ID, Record)) {
  3990. default: // Default behavior: ignore.
  3991. break;
  3992. case bitc::METADATA_ATTACHMENT: {
  3993. unsigned RecordLength = Record.size();
  3994. if (Record.empty())
  3995. return error("Invalid record");
  3996. if (RecordLength % 2 == 0) {
  3997. // A function attachment.
  3998. if (std::error_code EC = parseGlobalObjectAttachment(F, Record))
  3999. return EC;
  4000. continue;
  4001. }
  4002. // An instruction attachment.
  4003. Instruction *Inst = InstructionList[Record[0]];
  4004. for (unsigned i = 1; i != RecordLength; i = i+2) {
  4005. unsigned Kind = Record[i];
  4006. DenseMap<unsigned, unsigned>::iterator I =
  4007. MDKindMap.find(Kind);
  4008. if (I == MDKindMap.end())
  4009. return error("Invalid ID");
  4010. Metadata *Node = MetadataList.getMetadataFwdRef(Record[i + 1]);
  4011. if (isa<LocalAsMetadata>(Node))
  4012. // Drop the attachment. This used to be legal, but there's no
  4013. // upgrade path.
  4014. break;
  4015. MDNode *MD = dyn_cast_or_null<MDNode>(Node);
  4016. if (!MD)
  4017. return error("Invalid metadata attachment");
  4018. if (HasSeenOldLoopTags && I->second == LLVMContext::MD_loop)
  4019. MD = upgradeInstructionLoopAttachment(*MD);
  4020. if (I->second == LLVMContext::MD_tbaa) {
  4021. assert(!MD->isTemporary() && "should load MDs before attachments");
  4022. MD = UpgradeTBAANode(*MD);
  4023. }
  4024. Inst->setMetadata(I->second, MD);
  4025. }
  4026. break;
  4027. }
  4028. }
  4029. }
  4030. }
  4031. static std::error_code typeCheckLoadStoreInst(Type *ValType, Type *PtrType) {
  4032. LLVMContext &Context = PtrType->getContext();
  4033. if (!isa<PointerType>(PtrType))
  4034. return error(Context, "Load/Store operand is not a pointer type");
  4035. Type *ElemType = cast<PointerType>(PtrType)->getElementType();
  4036. if (ValType && ValType != ElemType)
  4037. return error(Context, "Explicit load/store type does not match pointee "
  4038. "type of pointer operand");
  4039. if (!PointerType::isLoadableOrStorableType(ElemType))
  4040. return error(Context, "Cannot load/store from pointer");
  4041. return std::error_code();
  4042. }
  4043. /// Lazily parse the specified function body block.
  4044. std::error_code BitcodeReader::parseFunctionBody(Function *F) {
  4045. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  4046. return error("Invalid record");
  4047. // Unexpected unresolved metadata when parsing function.
  4048. if (MetadataList.hasFwdRefs())
  4049. return error("Invalid function metadata: incoming forward references");
  4050. InstructionList.clear();
  4051. unsigned ModuleValueListSize = ValueList.size();
  4052. unsigned ModuleMetadataListSize = MetadataList.size();
  4053. // Add all the function arguments to the value table.
  4054. for (Argument &I : F->args())
  4055. ValueList.push_back(&I);
  4056. unsigned NextValueNo = ValueList.size();
  4057. BasicBlock *CurBB = nullptr;
  4058. unsigned CurBBNo = 0;
  4059. DebugLoc LastLoc;
  4060. auto getLastInstruction = [&]() -> Instruction * {
  4061. if (CurBB && !CurBB->empty())
  4062. return &CurBB->back();
  4063. else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
  4064. !FunctionBBs[CurBBNo - 1]->empty())
  4065. return &FunctionBBs[CurBBNo - 1]->back();
  4066. return nullptr;
  4067. };
  4068. std::vector<OperandBundleDef> OperandBundles;
  4069. // Read all the records.
  4070. SmallVector<uint64_t, 64> Record;
  4071. while (true) {
  4072. BitstreamEntry Entry = Stream.advance();
  4073. switch (Entry.Kind) {
  4074. case BitstreamEntry::Error:
  4075. return error("Malformed block");
  4076. case BitstreamEntry::EndBlock:
  4077. goto OutOfRecordLoop;
  4078. case BitstreamEntry::SubBlock:
  4079. switch (Entry.ID) {
  4080. default: // Skip unknown content.
  4081. if (Stream.SkipBlock())
  4082. return error("Invalid record");
  4083. break;
  4084. case bitc::CONSTANTS_BLOCK_ID:
  4085. if (std::error_code EC = parseConstants())
  4086. return EC;
  4087. NextValueNo = ValueList.size();
  4088. break;
  4089. case bitc::VALUE_SYMTAB_BLOCK_ID:
  4090. if (std::error_code EC = parseValueSymbolTable())
  4091. return EC;
  4092. break;
  4093. case bitc::METADATA_ATTACHMENT_ID:
  4094. if (std::error_code EC = parseMetadataAttachment(*F))
  4095. return EC;
  4096. break;
  4097. case bitc::METADATA_BLOCK_ID:
  4098. if (std::error_code EC = parseMetadata())
  4099. return EC;
  4100. break;
  4101. case bitc::USELIST_BLOCK_ID:
  4102. if (std::error_code EC = parseUseLists())
  4103. return EC;
  4104. break;
  4105. }
  4106. continue;
  4107. case BitstreamEntry::Record:
  4108. // The interesting case.
  4109. break;
  4110. }
  4111. // Read a record.
  4112. Record.clear();
  4113. Instruction *I = nullptr;
  4114. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  4115. switch (BitCode) {
  4116. default: // Default behavior: reject
  4117. return error("Invalid value");
  4118. case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
  4119. if (Record.size() < 1 || Record[0] == 0)
  4120. return error("Invalid record");
  4121. // Create all the basic blocks for the function.
  4122. FunctionBBs.resize(Record[0]);
  4123. // See if anything took the address of blocks in this function.
  4124. auto BBFRI = BasicBlockFwdRefs.find(F);
  4125. if (BBFRI == BasicBlockFwdRefs.end()) {
  4126. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  4127. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  4128. } else {
  4129. auto &BBRefs = BBFRI->second;
  4130. // Check for invalid basic block references.
  4131. if (BBRefs.size() > FunctionBBs.size())
  4132. return error("Invalid ID");
  4133. assert(!BBRefs.empty() && "Unexpected empty array");
  4134. assert(!BBRefs.front() && "Invalid reference to entry block");
  4135. for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
  4136. ++I)
  4137. if (I < RE && BBRefs[I]) {
  4138. BBRefs[I]->insertInto(F);
  4139. FunctionBBs[I] = BBRefs[I];
  4140. } else {
  4141. FunctionBBs[I] = BasicBlock::Create(Context, "", F);
  4142. }
  4143. // Erase from the table.
  4144. BasicBlockFwdRefs.erase(BBFRI);
  4145. }
  4146. CurBB = FunctionBBs[0];
  4147. continue;
  4148. }
  4149. case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
  4150. // This record indicates that the last instruction is at the same
  4151. // location as the previous instruction with a location.
  4152. I = getLastInstruction();
  4153. if (!I)
  4154. return error("Invalid record");
  4155. I->setDebugLoc(LastLoc);
  4156. I = nullptr;
  4157. continue;
  4158. case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
  4159. I = getLastInstruction();
  4160. if (!I || Record.size() < 4)
  4161. return error("Invalid record");
  4162. unsigned Line = Record[0], Col = Record[1];
  4163. unsigned ScopeID = Record[2], IAID = Record[3];
  4164. MDNode *Scope = nullptr, *IA = nullptr;
  4165. if (ScopeID) {
  4166. Scope = MetadataList.getMDNodeFwdRefOrNull(ScopeID - 1);
  4167. if (!Scope)
  4168. return error("Invalid record");
  4169. }
  4170. if (IAID) {
  4171. IA = MetadataList.getMDNodeFwdRefOrNull(IAID - 1);
  4172. if (!IA)
  4173. return error("Invalid record");
  4174. }
  4175. LastLoc = DebugLoc::get(Line, Col, Scope, IA);
  4176. I->setDebugLoc(LastLoc);
  4177. I = nullptr;
  4178. continue;
  4179. }
  4180. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  4181. unsigned OpNum = 0;
  4182. Value *LHS, *RHS;
  4183. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  4184. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  4185. OpNum+1 > Record.size())
  4186. return error("Invalid record");
  4187. int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  4188. if (Opc == -1)
  4189. return error("Invalid record");
  4190. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  4191. InstructionList.push_back(I);
  4192. if (OpNum < Record.size()) {
  4193. if (Opc == Instruction::Add ||
  4194. Opc == Instruction::Sub ||
  4195. Opc == Instruction::Mul ||
  4196. Opc == Instruction::Shl) {
  4197. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  4198. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  4199. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  4200. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  4201. } else if (Opc == Instruction::SDiv ||
  4202. Opc == Instruction::UDiv ||
  4203. Opc == Instruction::LShr ||
  4204. Opc == Instruction::AShr) {
  4205. if (Record[OpNum] & (1 << bitc::PEO_EXACT))
  4206. cast<BinaryOperator>(I)->setIsExact(true);
  4207. } else if (isa<FPMathOperator>(I)) {
  4208. FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
  4209. if (FMF.any())
  4210. I->setFastMathFlags(FMF);
  4211. }
  4212. }
  4213. break;
  4214. }
  4215. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  4216. unsigned OpNum = 0;
  4217. Value *Op;
  4218. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  4219. OpNum+2 != Record.size())
  4220. return error("Invalid record");
  4221. Type *ResTy = getTypeByID(Record[OpNum]);
  4222. int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
  4223. if (Opc == -1 || !ResTy)
  4224. return error("Invalid record");
  4225. Instruction *Temp = nullptr;
  4226. if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
  4227. if (Temp) {
  4228. InstructionList.push_back(Temp);
  4229. CurBB->getInstList().push_back(Temp);
  4230. }
  4231. } else {
  4232. auto CastOp = (Instruction::CastOps)Opc;
  4233. if (!CastInst::castIsValid(CastOp, Op, ResTy))
  4234. return error("Invalid cast");
  4235. I = CastInst::Create(CastOp, Op, ResTy);
  4236. }
  4237. InstructionList.push_back(I);
  4238. break;
  4239. }
  4240. case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
  4241. case bitc::FUNC_CODE_INST_GEP_OLD:
  4242. case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
  4243. unsigned OpNum = 0;
  4244. Type *Ty;
  4245. bool InBounds;
  4246. if (BitCode == bitc::FUNC_CODE_INST_GEP) {
  4247. InBounds = Record[OpNum++];
  4248. Ty = getTypeByID(Record[OpNum++]);
  4249. } else {
  4250. InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
  4251. Ty = nullptr;
  4252. }
  4253. Value *BasePtr;
  4254. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  4255. return error("Invalid record");
  4256. if (!Ty)
  4257. Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
  4258. ->getElementType();
  4259. else if (Ty !=
  4260. cast<SequentialType>(BasePtr->getType()->getScalarType())
  4261. ->getElementType())
  4262. return error(
  4263. "Explicit gep type does not match pointee type of pointer operand");
  4264. SmallVector<Value*, 16> GEPIdx;
  4265. while (OpNum != Record.size()) {
  4266. Value *Op;
  4267. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  4268. return error("Invalid record");
  4269. GEPIdx.push_back(Op);
  4270. }
  4271. I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
  4272. InstructionList.push_back(I);
  4273. if (InBounds)
  4274. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  4275. break;
  4276. }
  4277. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  4278. // EXTRACTVAL: [opty, opval, n x indices]
  4279. unsigned OpNum = 0;
  4280. Value *Agg;
  4281. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  4282. return error("Invalid record");
  4283. unsigned RecSize = Record.size();
  4284. if (OpNum == RecSize)
  4285. return error("EXTRACTVAL: Invalid instruction with 0 indices");
  4286. SmallVector<unsigned, 4> EXTRACTVALIdx;
  4287. Type *CurTy = Agg->getType();
  4288. for (; OpNum != RecSize; ++OpNum) {
  4289. bool IsArray = CurTy->isArrayTy();
  4290. bool IsStruct = CurTy->isStructTy();
  4291. uint64_t Index = Record[OpNum];
  4292. if (!IsStruct && !IsArray)
  4293. return error("EXTRACTVAL: Invalid type");
  4294. if ((unsigned)Index != Index)
  4295. return error("Invalid value");
  4296. if (IsStruct && Index >= CurTy->subtypes().size())
  4297. return error("EXTRACTVAL: Invalid struct index");
  4298. if (IsArray && Index >= CurTy->getArrayNumElements())
  4299. return error("EXTRACTVAL: Invalid array index");
  4300. EXTRACTVALIdx.push_back((unsigned)Index);
  4301. if (IsStruct)
  4302. CurTy = CurTy->subtypes()[Index];
  4303. else
  4304. CurTy = CurTy->subtypes()[0];
  4305. }
  4306. I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
  4307. InstructionList.push_back(I);
  4308. break;
  4309. }
  4310. case bitc::FUNC_CODE_INST_INSERTVAL: {
  4311. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  4312. unsigned OpNum = 0;
  4313. Value *Agg;
  4314. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  4315. return error("Invalid record");
  4316. Value *Val;
  4317. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  4318. return error("Invalid record");
  4319. unsigned RecSize = Record.size();
  4320. if (OpNum == RecSize)
  4321. return error("INSERTVAL: Invalid instruction with 0 indices");
  4322. SmallVector<unsigned, 4> INSERTVALIdx;
  4323. Type *CurTy = Agg->getType();
  4324. for (; OpNum != RecSize; ++OpNum) {
  4325. bool IsArray = CurTy->isArrayTy();
  4326. bool IsStruct = CurTy->isStructTy();
  4327. uint64_t Index = Record[OpNum];
  4328. if (!IsStruct && !IsArray)
  4329. return error("INSERTVAL: Invalid type");
  4330. if ((unsigned)Index != Index)
  4331. return error("Invalid value");
  4332. if (IsStruct && Index >= CurTy->subtypes().size())
  4333. return error("INSERTVAL: Invalid struct index");
  4334. if (IsArray && Index >= CurTy->getArrayNumElements())
  4335. return error("INSERTVAL: Invalid array index");
  4336. INSERTVALIdx.push_back((unsigned)Index);
  4337. if (IsStruct)
  4338. CurTy = CurTy->subtypes()[Index];
  4339. else
  4340. CurTy = CurTy->subtypes()[0];
  4341. }
  4342. if (CurTy != Val->getType())
  4343. return error("Inserted value type doesn't match aggregate type");
  4344. I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
  4345. InstructionList.push_back(I);
  4346. break;
  4347. }
  4348. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  4349. // obsolete form of select
  4350. // handles select i1 ... in old bitcode
  4351. unsigned OpNum = 0;
  4352. Value *TrueVal, *FalseVal, *Cond;
  4353. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  4354. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  4355. popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
  4356. return error("Invalid record");
  4357. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  4358. InstructionList.push_back(I);
  4359. break;
  4360. }
  4361. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  4362. // new form of select
  4363. // handles select i1 or select [N x i1]
  4364. unsigned OpNum = 0;
  4365. Value *TrueVal, *FalseVal, *Cond;
  4366. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  4367. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  4368. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  4369. return error("Invalid record");
  4370. // select condition can be either i1 or [N x i1]
  4371. if (VectorType* vector_type =
  4372. dyn_cast<VectorType>(Cond->getType())) {
  4373. // expect <n x i1>
  4374. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  4375. return error("Invalid type for value");
  4376. } else {
  4377. // expect i1
  4378. if (Cond->getType() != Type::getInt1Ty(Context))
  4379. return error("Invalid type for value");
  4380. }
  4381. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  4382. InstructionList.push_back(I);
  4383. break;
  4384. }
  4385. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  4386. unsigned OpNum = 0;
  4387. Value *Vec, *Idx;
  4388. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  4389. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  4390. return error("Invalid record");
  4391. if (!Vec->getType()->isVectorTy())
  4392. return error("Invalid type for value");
  4393. I = ExtractElementInst::Create(Vec, Idx);
  4394. InstructionList.push_back(I);
  4395. break;
  4396. }
  4397. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  4398. unsigned OpNum = 0;
  4399. Value *Vec, *Elt, *Idx;
  4400. if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
  4401. return error("Invalid record");
  4402. if (!Vec->getType()->isVectorTy())
  4403. return error("Invalid type for value");
  4404. if (popValue(Record, OpNum, NextValueNo,
  4405. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  4406. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  4407. return error("Invalid record");
  4408. I = InsertElementInst::Create(Vec, Elt, Idx);
  4409. InstructionList.push_back(I);
  4410. break;
  4411. }
  4412. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  4413. unsigned OpNum = 0;
  4414. Value *Vec1, *Vec2, *Mask;
  4415. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  4416. popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
  4417. return error("Invalid record");
  4418. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  4419. return error("Invalid record");
  4420. if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
  4421. return error("Invalid type for value");
  4422. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  4423. InstructionList.push_back(I);
  4424. break;
  4425. }
  4426. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  4427. // Old form of ICmp/FCmp returning bool
  4428. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  4429. // both legal on vectors but had different behaviour.
  4430. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  4431. // FCmp/ICmp returning bool or vector of bool
  4432. unsigned OpNum = 0;
  4433. Value *LHS, *RHS;
  4434. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  4435. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
  4436. return error("Invalid record");
  4437. unsigned PredVal = Record[OpNum];
  4438. bool IsFP = LHS->getType()->isFPOrFPVectorTy();
  4439. FastMathFlags FMF;
  4440. if (IsFP && Record.size() > OpNum+1)
  4441. FMF = getDecodedFastMathFlags(Record[++OpNum]);
  4442. if (OpNum+1 != Record.size())
  4443. return error("Invalid record");
  4444. if (LHS->getType()->isFPOrFPVectorTy())
  4445. I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
  4446. else
  4447. I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
  4448. if (FMF.any())
  4449. I->setFastMathFlags(FMF);
  4450. InstructionList.push_back(I);
  4451. break;
  4452. }
  4453. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  4454. {
  4455. unsigned Size = Record.size();
  4456. if (Size == 0) {
  4457. I = ReturnInst::Create(Context);
  4458. InstructionList.push_back(I);
  4459. break;
  4460. }
  4461. unsigned OpNum = 0;
  4462. Value *Op = nullptr;
  4463. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  4464. return error("Invalid record");
  4465. if (OpNum != Record.size())
  4466. return error("Invalid record");
  4467. I = ReturnInst::Create(Context, Op);
  4468. InstructionList.push_back(I);
  4469. break;
  4470. }
  4471. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  4472. if (Record.size() != 1 && Record.size() != 3)
  4473. return error("Invalid record");
  4474. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  4475. if (!TrueDest)
  4476. return error("Invalid record");
  4477. if (Record.size() == 1) {
  4478. I = BranchInst::Create(TrueDest);
  4479. InstructionList.push_back(I);
  4480. }
  4481. else {
  4482. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  4483. Value *Cond = getValue(Record, 2, NextValueNo,
  4484. Type::getInt1Ty(Context));
  4485. if (!FalseDest || !Cond)
  4486. return error("Invalid record");
  4487. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  4488. InstructionList.push_back(I);
  4489. }
  4490. break;
  4491. }
  4492. case bitc::FUNC_CODE_INST_CLEANUPRET: { // CLEANUPRET: [val] or [val,bb#]
  4493. if (Record.size() != 1 && Record.size() != 2)
  4494. return error("Invalid record");
  4495. unsigned Idx = 0;
  4496. Value *CleanupPad =
  4497. getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
  4498. if (!CleanupPad)
  4499. return error("Invalid record");
  4500. BasicBlock *UnwindDest = nullptr;
  4501. if (Record.size() == 2) {
  4502. UnwindDest = getBasicBlock(Record[Idx++]);
  4503. if (!UnwindDest)
  4504. return error("Invalid record");
  4505. }
  4506. I = CleanupReturnInst::Create(CleanupPad, UnwindDest);
  4507. InstructionList.push_back(I);
  4508. break;
  4509. }
  4510. case bitc::FUNC_CODE_INST_CATCHRET: { // CATCHRET: [val,bb#]
  4511. if (Record.size() != 2)
  4512. return error("Invalid record");
  4513. unsigned Idx = 0;
  4514. Value *CatchPad =
  4515. getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
  4516. if (!CatchPad)
  4517. return error("Invalid record");
  4518. BasicBlock *BB = getBasicBlock(Record[Idx++]);
  4519. if (!BB)
  4520. return error("Invalid record");
  4521. I = CatchReturnInst::Create(CatchPad, BB);
  4522. InstructionList.push_back(I);
  4523. break;
  4524. }
  4525. case bitc::FUNC_CODE_INST_CATCHSWITCH: { // CATCHSWITCH: [tok,num,(bb)*,bb?]
  4526. // We must have, at minimum, the outer scope and the number of arguments.
  4527. if (Record.size() < 2)
  4528. return error("Invalid record");
  4529. unsigned Idx = 0;
  4530. Value *ParentPad =
  4531. getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
  4532. unsigned NumHandlers = Record[Idx++];
  4533. SmallVector<BasicBlock *, 2> Handlers;
  4534. for (unsigned Op = 0; Op != NumHandlers; ++Op) {
  4535. BasicBlock *BB = getBasicBlock(Record[Idx++]);
  4536. if (!BB)
  4537. return error("Invalid record");
  4538. Handlers.push_back(BB);
  4539. }
  4540. BasicBlock *UnwindDest = nullptr;
  4541. if (Idx + 1 == Record.size()) {
  4542. UnwindDest = getBasicBlock(Record[Idx++]);
  4543. if (!UnwindDest)
  4544. return error("Invalid record");
  4545. }
  4546. if (Record.size() != Idx)
  4547. return error("Invalid record");
  4548. auto *CatchSwitch =
  4549. CatchSwitchInst::Create(ParentPad, UnwindDest, NumHandlers);
  4550. for (BasicBlock *Handler : Handlers)
  4551. CatchSwitch->addHandler(Handler);
  4552. I = CatchSwitch;
  4553. InstructionList.push_back(I);
  4554. break;
  4555. }
  4556. case bitc::FUNC_CODE_INST_CATCHPAD:
  4557. case bitc::FUNC_CODE_INST_CLEANUPPAD: { // [tok,num,(ty,val)*]
  4558. // We must have, at minimum, the outer scope and the number of arguments.
  4559. if (Record.size() < 2)
  4560. return error("Invalid record");
  4561. unsigned Idx = 0;
  4562. Value *ParentPad =
  4563. getValue(Record, Idx++, NextValueNo, Type::getTokenTy(Context));
  4564. unsigned NumArgOperands = Record[Idx++];
  4565. SmallVector<Value *, 2> Args;
  4566. for (unsigned Op = 0; Op != NumArgOperands; ++Op) {
  4567. Value *Val;
  4568. if (getValueTypePair(Record, Idx, NextValueNo, Val))
  4569. return error("Invalid record");
  4570. Args.push_back(Val);
  4571. }
  4572. if (Record.size() != Idx)
  4573. return error("Invalid record");
  4574. if (BitCode == bitc::FUNC_CODE_INST_CLEANUPPAD)
  4575. I = CleanupPadInst::Create(ParentPad, Args);
  4576. else
  4577. I = CatchPadInst::Create(ParentPad, Args);
  4578. InstructionList.push_back(I);
  4579. break;
  4580. }
  4581. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  4582. // Check magic
  4583. if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
  4584. // "New" SwitchInst format with case ranges. The changes to write this
  4585. // format were reverted but we still recognize bitcode that uses it.
  4586. // Hopefully someday we will have support for case ranges and can use
  4587. // this format again.
  4588. Type *OpTy = getTypeByID(Record[1]);
  4589. unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
  4590. Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
  4591. BasicBlock *Default = getBasicBlock(Record[3]);
  4592. if (!OpTy || !Cond || !Default)
  4593. return error("Invalid record");
  4594. unsigned NumCases = Record[4];
  4595. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  4596. InstructionList.push_back(SI);
  4597. unsigned CurIdx = 5;
  4598. for (unsigned i = 0; i != NumCases; ++i) {
  4599. SmallVector<ConstantInt*, 1> CaseVals;
  4600. unsigned NumItems = Record[CurIdx++];
  4601. for (unsigned ci = 0; ci != NumItems; ++ci) {
  4602. bool isSingleNumber = Record[CurIdx++];
  4603. APInt Low;
  4604. unsigned ActiveWords = 1;
  4605. if (ValueBitWidth > 64)
  4606. ActiveWords = Record[CurIdx++];
  4607. Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  4608. ValueBitWidth);
  4609. CurIdx += ActiveWords;
  4610. if (!isSingleNumber) {
  4611. ActiveWords = 1;
  4612. if (ValueBitWidth > 64)
  4613. ActiveWords = Record[CurIdx++];
  4614. APInt High = readWideAPInt(
  4615. makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
  4616. CurIdx += ActiveWords;
  4617. // FIXME: It is not clear whether values in the range should be
  4618. // compared as signed or unsigned values. The partially
  4619. // implemented changes that used this format in the past used
  4620. // unsigned comparisons.
  4621. for ( ; Low.ule(High); ++Low)
  4622. CaseVals.push_back(ConstantInt::get(Context, Low));
  4623. } else
  4624. CaseVals.push_back(ConstantInt::get(Context, Low));
  4625. }
  4626. BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
  4627. for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
  4628. cve = CaseVals.end(); cvi != cve; ++cvi)
  4629. SI->addCase(*cvi, DestBB);
  4630. }
  4631. I = SI;
  4632. break;
  4633. }
  4634. // Old SwitchInst format without case ranges.
  4635. if (Record.size() < 3 || (Record.size() & 1) == 0)
  4636. return error("Invalid record");
  4637. Type *OpTy = getTypeByID(Record[0]);
  4638. Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
  4639. BasicBlock *Default = getBasicBlock(Record[2]);
  4640. if (!OpTy || !Cond || !Default)
  4641. return error("Invalid record");
  4642. unsigned NumCases = (Record.size()-3)/2;
  4643. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  4644. InstructionList.push_back(SI);
  4645. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  4646. ConstantInt *CaseVal =
  4647. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  4648. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  4649. if (!CaseVal || !DestBB) {
  4650. delete SI;
  4651. return error("Invalid record");
  4652. }
  4653. SI->addCase(CaseVal, DestBB);
  4654. }
  4655. I = SI;
  4656. break;
  4657. }
  4658. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  4659. if (Record.size() < 2)
  4660. return error("Invalid record");
  4661. Type *OpTy = getTypeByID(Record[0]);
  4662. Value *Address = getValue(Record, 1, NextValueNo, OpTy);
  4663. if (!OpTy || !Address)
  4664. return error("Invalid record");
  4665. unsigned NumDests = Record.size()-2;
  4666. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  4667. InstructionList.push_back(IBI);
  4668. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  4669. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  4670. IBI->addDestination(DestBB);
  4671. } else {
  4672. delete IBI;
  4673. return error("Invalid record");
  4674. }
  4675. }
  4676. I = IBI;
  4677. break;
  4678. }
  4679. case bitc::FUNC_CODE_INST_INVOKE: {
  4680. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  4681. if (Record.size() < 4)
  4682. return error("Invalid record");
  4683. unsigned OpNum = 0;
  4684. AttributeSet PAL = getAttributes(Record[OpNum++]);
  4685. unsigned CCInfo = Record[OpNum++];
  4686. BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
  4687. BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
  4688. FunctionType *FTy = nullptr;
  4689. if (CCInfo >> 13 & 1 &&
  4690. !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
  4691. return error("Explicit invoke type is not a function type");
  4692. Value *Callee;
  4693. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  4694. return error("Invalid record");
  4695. PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  4696. if (!CalleeTy)
  4697. return error("Callee is not a pointer");
  4698. if (!FTy) {
  4699. FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
  4700. if (!FTy)
  4701. return error("Callee is not of pointer to function type");
  4702. } else if (CalleeTy->getElementType() != FTy)
  4703. return error("Explicit invoke type does not match pointee type of "
  4704. "callee operand");
  4705. if (Record.size() < FTy->getNumParams() + OpNum)
  4706. return error("Insufficient operands to call");
  4707. SmallVector<Value*, 16> Ops;
  4708. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  4709. Ops.push_back(getValue(Record, OpNum, NextValueNo,
  4710. FTy->getParamType(i)));
  4711. if (!Ops.back())
  4712. return error("Invalid record");
  4713. }
  4714. if (!FTy->isVarArg()) {
  4715. if (Record.size() != OpNum)
  4716. return error("Invalid record");
  4717. } else {
  4718. // Read type/value pairs for varargs params.
  4719. while (OpNum != Record.size()) {
  4720. Value *Op;
  4721. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  4722. return error("Invalid record");
  4723. Ops.push_back(Op);
  4724. }
  4725. }
  4726. I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops, OperandBundles);
  4727. OperandBundles.clear();
  4728. InstructionList.push_back(I);
  4729. cast<InvokeInst>(I)->setCallingConv(
  4730. static_cast<CallingConv::ID>(CallingConv::MaxID & CCInfo));
  4731. cast<InvokeInst>(I)->setAttributes(PAL);
  4732. break;
  4733. }
  4734. case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
  4735. unsigned Idx = 0;
  4736. Value *Val = nullptr;
  4737. if (getValueTypePair(Record, Idx, NextValueNo, Val))
  4738. return error("Invalid record");
  4739. I = ResumeInst::Create(Val);
  4740. InstructionList.push_back(I);
  4741. break;
  4742. }
  4743. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  4744. I = new UnreachableInst(Context);
  4745. InstructionList.push_back(I);
  4746. break;
  4747. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  4748. if (Record.size() < 1 || ((Record.size()-1)&1))
  4749. return error("Invalid record");
  4750. Type *Ty = getTypeByID(Record[0]);
  4751. if (!Ty)
  4752. return error("Invalid record");
  4753. PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
  4754. InstructionList.push_back(PN);
  4755. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  4756. Value *V;
  4757. // With the new function encoding, it is possible that operands have
  4758. // negative IDs (for forward references). Use a signed VBR
  4759. // representation to keep the encoding small.
  4760. if (UseRelativeIDs)
  4761. V = getValueSigned(Record, 1+i, NextValueNo, Ty);
  4762. else
  4763. V = getValue(Record, 1+i, NextValueNo, Ty);
  4764. BasicBlock *BB = getBasicBlock(Record[2+i]);
  4765. if (!V || !BB)
  4766. return error("Invalid record");
  4767. PN->addIncoming(V, BB);
  4768. }
  4769. I = PN;
  4770. break;
  4771. }
  4772. case bitc::FUNC_CODE_INST_LANDINGPAD:
  4773. case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
  4774. // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
  4775. unsigned Idx = 0;
  4776. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
  4777. if (Record.size() < 3)
  4778. return error("Invalid record");
  4779. } else {
  4780. assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
  4781. if (Record.size() < 4)
  4782. return error("Invalid record");
  4783. }
  4784. Type *Ty = getTypeByID(Record[Idx++]);
  4785. if (!Ty)
  4786. return error("Invalid record");
  4787. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
  4788. Value *PersFn = nullptr;
  4789. if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
  4790. return error("Invalid record");
  4791. if (!F->hasPersonalityFn())
  4792. F->setPersonalityFn(cast<Constant>(PersFn));
  4793. else if (F->getPersonalityFn() != cast<Constant>(PersFn))
  4794. return error("Personality function mismatch");
  4795. }
  4796. bool IsCleanup = !!Record[Idx++];
  4797. unsigned NumClauses = Record[Idx++];
  4798. LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
  4799. LP->setCleanup(IsCleanup);
  4800. for (unsigned J = 0; J != NumClauses; ++J) {
  4801. LandingPadInst::ClauseType CT =
  4802. LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
  4803. Value *Val;
  4804. if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
  4805. delete LP;
  4806. return error("Invalid record");
  4807. }
  4808. assert((CT != LandingPadInst::Catch ||
  4809. !isa<ArrayType>(Val->getType())) &&
  4810. "Catch clause has a invalid type!");
  4811. assert((CT != LandingPadInst::Filter ||
  4812. isa<ArrayType>(Val->getType())) &&
  4813. "Filter clause has invalid type!");
  4814. LP->addClause(cast<Constant>(Val));
  4815. }
  4816. I = LP;
  4817. InstructionList.push_back(I);
  4818. break;
  4819. }
  4820. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
  4821. if (Record.size() != 4)
  4822. return error("Invalid record");
  4823. uint64_t AlignRecord = Record[3];
  4824. const uint64_t InAllocaMask = uint64_t(1) << 5;
  4825. const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
  4826. const uint64_t SwiftErrorMask = uint64_t(1) << 7;
  4827. const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask |
  4828. SwiftErrorMask;
  4829. bool InAlloca = AlignRecord & InAllocaMask;
  4830. bool SwiftError = AlignRecord & SwiftErrorMask;
  4831. Type *Ty = getTypeByID(Record[0]);
  4832. if ((AlignRecord & ExplicitTypeMask) == 0) {
  4833. auto *PTy = dyn_cast_or_null<PointerType>(Ty);
  4834. if (!PTy)
  4835. return error("Old-style alloca with a non-pointer type");
  4836. Ty = PTy->getElementType();
  4837. }
  4838. Type *OpTy = getTypeByID(Record[1]);
  4839. Value *Size = getFnValueByID(Record[2], OpTy);
  4840. unsigned Align;
  4841. if (std::error_code EC =
  4842. parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
  4843. return EC;
  4844. }
  4845. if (!Ty || !Size)
  4846. return error("Invalid record");
  4847. AllocaInst *AI = new AllocaInst(Ty, Size, Align);
  4848. AI->setUsedWithInAlloca(InAlloca);
  4849. AI->setSwiftError(SwiftError);
  4850. I = AI;
  4851. InstructionList.push_back(I);
  4852. break;
  4853. }
  4854. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  4855. unsigned OpNum = 0;
  4856. Value *Op;
  4857. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  4858. (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
  4859. return error("Invalid record");
  4860. Type *Ty = nullptr;
  4861. if (OpNum + 3 == Record.size())
  4862. Ty = getTypeByID(Record[OpNum++]);
  4863. if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
  4864. return EC;
  4865. if (!Ty)
  4866. Ty = cast<PointerType>(Op->getType())->getElementType();
  4867. unsigned Align;
  4868. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  4869. return EC;
  4870. I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
  4871. InstructionList.push_back(I);
  4872. break;
  4873. }
  4874. case bitc::FUNC_CODE_INST_LOADATOMIC: {
  4875. // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
  4876. unsigned OpNum = 0;
  4877. Value *Op;
  4878. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  4879. (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
  4880. return error("Invalid record");
  4881. Type *Ty = nullptr;
  4882. if (OpNum + 5 == Record.size())
  4883. Ty = getTypeByID(Record[OpNum++]);
  4884. if (std::error_code EC = typeCheckLoadStoreInst(Ty, Op->getType()))
  4885. return EC;
  4886. if (!Ty)
  4887. Ty = cast<PointerType>(Op->getType())->getElementType();
  4888. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  4889. if (Ordering == AtomicOrdering::NotAtomic ||
  4890. Ordering == AtomicOrdering::Release ||
  4891. Ordering == AtomicOrdering::AcquireRelease)
  4892. return error("Invalid record");
  4893. if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
  4894. return error("Invalid record");
  4895. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
  4896. unsigned Align;
  4897. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  4898. return EC;
  4899. I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
  4900. InstructionList.push_back(I);
  4901. break;
  4902. }
  4903. case bitc::FUNC_CODE_INST_STORE:
  4904. case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
  4905. unsigned OpNum = 0;
  4906. Value *Val, *Ptr;
  4907. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  4908. (BitCode == bitc::FUNC_CODE_INST_STORE
  4909. ? getValueTypePair(Record, OpNum, NextValueNo, Val)
  4910. : popValue(Record, OpNum, NextValueNo,
  4911. cast<PointerType>(Ptr->getType())->getElementType(),
  4912. Val)) ||
  4913. OpNum + 2 != Record.size())
  4914. return error("Invalid record");
  4915. if (std::error_code EC =
  4916. typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
  4917. return EC;
  4918. unsigned Align;
  4919. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  4920. return EC;
  4921. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
  4922. InstructionList.push_back(I);
  4923. break;
  4924. }
  4925. case bitc::FUNC_CODE_INST_STOREATOMIC:
  4926. case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
  4927. // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
  4928. unsigned OpNum = 0;
  4929. Value *Val, *Ptr;
  4930. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  4931. !isa<PointerType>(Ptr->getType()) ||
  4932. (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
  4933. ? getValueTypePair(Record, OpNum, NextValueNo, Val)
  4934. : popValue(Record, OpNum, NextValueNo,
  4935. cast<PointerType>(Ptr->getType())->getElementType(),
  4936. Val)) ||
  4937. OpNum + 4 != Record.size())
  4938. return error("Invalid record");
  4939. if (std::error_code EC =
  4940. typeCheckLoadStoreInst(Val->getType(), Ptr->getType()))
  4941. return EC;
  4942. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  4943. if (Ordering == AtomicOrdering::NotAtomic ||
  4944. Ordering == AtomicOrdering::Acquire ||
  4945. Ordering == AtomicOrdering::AcquireRelease)
  4946. return error("Invalid record");
  4947. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
  4948. if (Ordering != AtomicOrdering::NotAtomic && Record[OpNum] == 0)
  4949. return error("Invalid record");
  4950. unsigned Align;
  4951. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  4952. return EC;
  4953. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
  4954. InstructionList.push_back(I);
  4955. break;
  4956. }
  4957. case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
  4958. case bitc::FUNC_CODE_INST_CMPXCHG: {
  4959. // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
  4960. // failureordering?, isweak?]
  4961. unsigned OpNum = 0;
  4962. Value *Ptr, *Cmp, *New;
  4963. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  4964. (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
  4965. ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
  4966. : popValue(Record, OpNum, NextValueNo,
  4967. cast<PointerType>(Ptr->getType())->getElementType(),
  4968. Cmp)) ||
  4969. popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
  4970. Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
  4971. return error("Invalid record");
  4972. AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
  4973. if (SuccessOrdering == AtomicOrdering::NotAtomic ||
  4974. SuccessOrdering == AtomicOrdering::Unordered)
  4975. return error("Invalid record");
  4976. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
  4977. if (std::error_code EC =
  4978. typeCheckLoadStoreInst(Cmp->getType(), Ptr->getType()))
  4979. return EC;
  4980. AtomicOrdering FailureOrdering;
  4981. if (Record.size() < 7)
  4982. FailureOrdering =
  4983. AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
  4984. else
  4985. FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
  4986. I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
  4987. SynchScope);
  4988. cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
  4989. if (Record.size() < 8) {
  4990. // Before weak cmpxchgs existed, the instruction simply returned the
  4991. // value loaded from memory, so bitcode files from that era will be
  4992. // expecting the first component of a modern cmpxchg.
  4993. CurBB->getInstList().push_back(I);
  4994. I = ExtractValueInst::Create(I, 0);
  4995. } else {
  4996. cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
  4997. }
  4998. InstructionList.push_back(I);
  4999. break;
  5000. }
  5001. case bitc::FUNC_CODE_INST_ATOMICRMW: {
  5002. // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
  5003. unsigned OpNum = 0;
  5004. Value *Ptr, *Val;
  5005. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  5006. !isa<PointerType>(Ptr->getType()) ||
  5007. popValue(Record, OpNum, NextValueNo,
  5008. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  5009. OpNum+4 != Record.size())
  5010. return error("Invalid record");
  5011. AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
  5012. if (Operation < AtomicRMWInst::FIRST_BINOP ||
  5013. Operation > AtomicRMWInst::LAST_BINOP)
  5014. return error("Invalid record");
  5015. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  5016. if (Ordering == AtomicOrdering::NotAtomic ||
  5017. Ordering == AtomicOrdering::Unordered)
  5018. return error("Invalid record");
  5019. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
  5020. I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
  5021. cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
  5022. InstructionList.push_back(I);
  5023. break;
  5024. }
  5025. case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
  5026. if (2 != Record.size())
  5027. return error("Invalid record");
  5028. AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
  5029. if (Ordering == AtomicOrdering::NotAtomic ||
  5030. Ordering == AtomicOrdering::Unordered ||
  5031. Ordering == AtomicOrdering::Monotonic)
  5032. return error("Invalid record");
  5033. SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
  5034. I = new FenceInst(Context, Ordering, SynchScope);
  5035. InstructionList.push_back(I);
  5036. break;
  5037. }
  5038. case bitc::FUNC_CODE_INST_CALL: {
  5039. // CALL: [paramattrs, cc, fmf, fnty, fnid, arg0, arg1...]
  5040. if (Record.size() < 3)
  5041. return error("Invalid record");
  5042. unsigned OpNum = 0;
  5043. AttributeSet PAL = getAttributes(Record[OpNum++]);
  5044. unsigned CCInfo = Record[OpNum++];
  5045. FastMathFlags FMF;
  5046. if ((CCInfo >> bitc::CALL_FMF) & 1) {
  5047. FMF = getDecodedFastMathFlags(Record[OpNum++]);
  5048. if (!FMF.any())
  5049. return error("Fast math flags indicator set for call with no FMF");
  5050. }
  5051. FunctionType *FTy = nullptr;
  5052. if (CCInfo >> bitc::CALL_EXPLICIT_TYPE & 1 &&
  5053. !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
  5054. return error("Explicit call type is not a function type");
  5055. Value *Callee;
  5056. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  5057. return error("Invalid record");
  5058. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  5059. if (!OpTy)
  5060. return error("Callee is not a pointer type");
  5061. if (!FTy) {
  5062. FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  5063. if (!FTy)
  5064. return error("Callee is not of pointer to function type");
  5065. } else if (OpTy->getElementType() != FTy)
  5066. return error("Explicit call type does not match pointee type of "
  5067. "callee operand");
  5068. if (Record.size() < FTy->getNumParams() + OpNum)
  5069. return error("Insufficient operands to call");
  5070. SmallVector<Value*, 16> Args;
  5071. // Read the fixed params.
  5072. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  5073. if (FTy->getParamType(i)->isLabelTy())
  5074. Args.push_back(getBasicBlock(Record[OpNum]));
  5075. else
  5076. Args.push_back(getValue(Record, OpNum, NextValueNo,
  5077. FTy->getParamType(i)));
  5078. if (!Args.back())
  5079. return error("Invalid record");
  5080. }
  5081. // Read type/value pairs for varargs params.
  5082. if (!FTy->isVarArg()) {
  5083. if (OpNum != Record.size())
  5084. return error("Invalid record");
  5085. } else {
  5086. while (OpNum != Record.size()) {
  5087. Value *Op;
  5088. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  5089. return error("Invalid record");
  5090. Args.push_back(Op);
  5091. }
  5092. }
  5093. I = CallInst::Create(FTy, Callee, Args, OperandBundles);
  5094. OperandBundles.clear();
  5095. InstructionList.push_back(I);
  5096. cast<CallInst>(I)->setCallingConv(
  5097. static_cast<CallingConv::ID>((0x7ff & CCInfo) >> bitc::CALL_CCONV));
  5098. CallInst::TailCallKind TCK = CallInst::TCK_None;
  5099. if (CCInfo & 1 << bitc::CALL_TAIL)
  5100. TCK = CallInst::TCK_Tail;
  5101. if (CCInfo & (1 << bitc::CALL_MUSTTAIL))
  5102. TCK = CallInst::TCK_MustTail;
  5103. if (CCInfo & (1 << bitc::CALL_NOTAIL))
  5104. TCK = CallInst::TCK_NoTail;
  5105. cast<CallInst>(I)->setTailCallKind(TCK);
  5106. cast<CallInst>(I)->setAttributes(PAL);
  5107. if (FMF.any()) {
  5108. if (!isa<FPMathOperator>(I))
  5109. return error("Fast-math-flags specified for call without "
  5110. "floating-point scalar or vector return type");
  5111. I->setFastMathFlags(FMF);
  5112. }
  5113. break;
  5114. }
  5115. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  5116. if (Record.size() < 3)
  5117. return error("Invalid record");
  5118. Type *OpTy = getTypeByID(Record[0]);
  5119. Value *Op = getValue(Record, 1, NextValueNo, OpTy);
  5120. Type *ResTy = getTypeByID(Record[2]);
  5121. if (!OpTy || !Op || !ResTy)
  5122. return error("Invalid record");
  5123. I = new VAArgInst(Op, ResTy);
  5124. InstructionList.push_back(I);
  5125. break;
  5126. }
  5127. case bitc::FUNC_CODE_OPERAND_BUNDLE: {
  5128. // A call or an invoke can be optionally prefixed with some variable
  5129. // number of operand bundle blocks. These blocks are read into
  5130. // OperandBundles and consumed at the next call or invoke instruction.
  5131. if (Record.size() < 1 || Record[0] >= BundleTags.size())
  5132. return error("Invalid record");
  5133. std::vector<Value *> Inputs;
  5134. unsigned OpNum = 1;
  5135. while (OpNum != Record.size()) {
  5136. Value *Op;
  5137. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  5138. return error("Invalid record");
  5139. Inputs.push_back(Op);
  5140. }
  5141. OperandBundles.emplace_back(BundleTags[Record[0]], std::move(Inputs));
  5142. continue;
  5143. }
  5144. }
  5145. // Add instruction to end of current BB. If there is no current BB, reject
  5146. // this file.
  5147. if (!CurBB) {
  5148. delete I;
  5149. return error("Invalid instruction with no BB");
  5150. }
  5151. if (!OperandBundles.empty()) {
  5152. delete I;
  5153. return error("Operand bundles found with no consumer");
  5154. }
  5155. CurBB->getInstList().push_back(I);
  5156. // If this was a terminator instruction, move to the next block.
  5157. if (isa<TerminatorInst>(I)) {
  5158. ++CurBBNo;
  5159. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
  5160. }
  5161. // Non-void values get registered in the value table for future use.
  5162. if (I && !I->getType()->isVoidTy())
  5163. ValueList.assignValue(I, NextValueNo++);
  5164. }
  5165. OutOfRecordLoop:
  5166. if (!OperandBundles.empty())
  5167. return error("Operand bundles found with no consumer");
  5168. // Check the function list for unresolved values.
  5169. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  5170. if (!A->getParent()) {
  5171. // We found at least one unresolved value. Nuke them all to avoid leaks.
  5172. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  5173. if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
  5174. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  5175. delete A;
  5176. }
  5177. }
  5178. return error("Never resolved value found in function");
  5179. }
  5180. }
  5181. // Unexpected unresolved metadata about to be dropped.
  5182. if (MetadataList.hasFwdRefs())
  5183. return error("Invalid function metadata: outgoing forward refs");
  5184. // Trim the value list down to the size it was before we parsed this function.
  5185. ValueList.shrinkTo(ModuleValueListSize);
  5186. MetadataList.shrinkTo(ModuleMetadataListSize);
  5187. std::vector<BasicBlock*>().swap(FunctionBBs);
  5188. return std::error_code();
  5189. }
  5190. /// Find the function body in the bitcode stream
  5191. std::error_code BitcodeReader::findFunctionInStream(
  5192. Function *F,
  5193. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
  5194. while (DeferredFunctionInfoIterator->second == 0) {
  5195. // This is the fallback handling for the old format bitcode that
  5196. // didn't contain the function index in the VST, or when we have
  5197. // an anonymous function which would not have a VST entry.
  5198. // Assert that we have one of those two cases.
  5199. assert(VSTOffset == 0 || !F->hasName());
  5200. // Parse the next body in the stream and set its position in the
  5201. // DeferredFunctionInfo map.
  5202. if (std::error_code EC = rememberAndSkipFunctionBodies())
  5203. return EC;
  5204. }
  5205. return std::error_code();
  5206. }
  5207. //===----------------------------------------------------------------------===//
  5208. // GVMaterializer implementation
  5209. //===----------------------------------------------------------------------===//
  5210. std::error_code BitcodeReader::materialize(GlobalValue *GV) {
  5211. Function *F = dyn_cast<Function>(GV);
  5212. // If it's not a function or is already material, ignore the request.
  5213. if (!F || !F->isMaterializable())
  5214. return std::error_code();
  5215. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  5216. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  5217. // If its position is recorded as 0, its body is somewhere in the stream
  5218. // but we haven't seen it yet.
  5219. if (DFII->second == 0)
  5220. if (std::error_code EC = findFunctionInStream(F, DFII))
  5221. return EC;
  5222. // Materialize metadata before parsing any function bodies.
  5223. if (std::error_code EC = materializeMetadata())
  5224. return EC;
  5225. // Move the bit stream to the saved position of the deferred function body.
  5226. Stream.JumpToBit(DFII->second);
  5227. if (std::error_code EC = parseFunctionBody(F))
  5228. return EC;
  5229. F->setIsMaterializable(false);
  5230. if (StripDebugInfo)
  5231. stripDebugInfo(*F);
  5232. // Upgrade any old intrinsic calls in the function.
  5233. for (auto &I : UpgradedIntrinsics) {
  5234. for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
  5235. UI != UE;) {
  5236. User *U = *UI;
  5237. ++UI;
  5238. if (CallInst *CI = dyn_cast<CallInst>(U))
  5239. UpgradeIntrinsicCall(CI, I.second);
  5240. }
  5241. }
  5242. // Update calls to the remangled intrinsics
  5243. for (auto &I : RemangledIntrinsics)
  5244. for (auto UI = I.first->materialized_user_begin(), UE = I.first->user_end();
  5245. UI != UE;)
  5246. // Don't expect any other users than call sites
  5247. CallSite(*UI++).setCalledFunction(I.second);
  5248. // Finish fn->subprogram upgrade for materialized functions.
  5249. if (DISubprogram *SP = FunctionsWithSPs.lookup(F))
  5250. F->setSubprogram(SP);
  5251. // Bring in any functions that this function forward-referenced via
  5252. // blockaddresses.
  5253. return materializeForwardReferencedFunctions();
  5254. }
  5255. std::error_code BitcodeReader::materializeModule() {
  5256. if (std::error_code EC = materializeMetadata())
  5257. return EC;
  5258. // Promise to materialize all forward references.
  5259. WillMaterializeAllForwardRefs = true;
  5260. // Iterate over the module, deserializing any functions that are still on
  5261. // disk.
  5262. for (Function &F : *TheModule) {
  5263. if (std::error_code EC = materialize(&F))
  5264. return EC;
  5265. }
  5266. // At this point, if there are any function bodies, parse the rest of
  5267. // the bits in the module past the last function block we have recorded
  5268. // through either lazy scanning or the VST.
  5269. if (LastFunctionBlockBit || NextUnreadBit)
  5270. parseModule(LastFunctionBlockBit > NextUnreadBit ? LastFunctionBlockBit
  5271. : NextUnreadBit);
  5272. // Check that all block address forward references got resolved (as we
  5273. // promised above).
  5274. if (!BasicBlockFwdRefs.empty())
  5275. return error("Never resolved function from blockaddress");
  5276. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  5277. // delete the old functions to clean up. We can't do this unless the entire
  5278. // module is materialized because there could always be another function body
  5279. // with calls to the old function.
  5280. for (auto &I : UpgradedIntrinsics) {
  5281. for (auto *U : I.first->users()) {
  5282. if (CallInst *CI = dyn_cast<CallInst>(U))
  5283. UpgradeIntrinsicCall(CI, I.second);
  5284. }
  5285. if (!I.first->use_empty())
  5286. I.first->replaceAllUsesWith(I.second);
  5287. I.first->eraseFromParent();
  5288. }
  5289. UpgradedIntrinsics.clear();
  5290. // Do the same for remangled intrinsics
  5291. for (auto &I : RemangledIntrinsics) {
  5292. I.first->replaceAllUsesWith(I.second);
  5293. I.first->eraseFromParent();
  5294. }
  5295. RemangledIntrinsics.clear();
  5296. UpgradeDebugInfo(*TheModule);
  5297. UpgradeModuleFlags(*TheModule);
  5298. return std::error_code();
  5299. }
  5300. std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
  5301. return IdentifiedStructTypes;
  5302. }
  5303. std::error_code ModuleSummaryIndexBitcodeReader::error(const Twine &Message) {
  5304. return ::error(DiagnosticHandler,
  5305. make_error_code(BitcodeError::CorruptedBitcode), Message);
  5306. }
  5307. ModuleSummaryIndexBitcodeReader::ModuleSummaryIndexBitcodeReader(
  5308. MemoryBufferRef Buffer, DiagnosticHandlerFunction DiagnosticHandler,
  5309. bool CheckGlobalValSummaryPresenceOnly)
  5310. : BitcodeReaderBase(Buffer),
  5311. DiagnosticHandler(std::move(DiagnosticHandler)),
  5312. CheckGlobalValSummaryPresenceOnly(CheckGlobalValSummaryPresenceOnly) {}
  5313. std::pair<GlobalValue::GUID, GlobalValue::GUID>
  5314. ModuleSummaryIndexBitcodeReader::getGUIDFromValueId(unsigned ValueId) {
  5315. auto VGI = ValueIdToCallGraphGUIDMap.find(ValueId);
  5316. assert(VGI != ValueIdToCallGraphGUIDMap.end());
  5317. return VGI->second;
  5318. }
  5319. // Specialized value symbol table parser used when reading module index
  5320. // blocks where we don't actually create global values. The parsed information
  5321. // is saved in the bitcode reader for use when later parsing summaries.
  5322. std::error_code ModuleSummaryIndexBitcodeReader::parseValueSymbolTable(
  5323. uint64_t Offset,
  5324. DenseMap<unsigned, GlobalValue::LinkageTypes> &ValueIdToLinkageMap) {
  5325. assert(Offset > 0 && "Expected non-zero VST offset");
  5326. uint64_t CurrentBit = jumpToValueSymbolTable(Offset, Stream);
  5327. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  5328. return error("Invalid record");
  5329. SmallVector<uint64_t, 64> Record;
  5330. // Read all the records for this value table.
  5331. SmallString<128> ValueName;
  5332. while (true) {
  5333. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  5334. switch (Entry.Kind) {
  5335. case BitstreamEntry::SubBlock: // Handled for us already.
  5336. case BitstreamEntry::Error:
  5337. return error("Malformed block");
  5338. case BitstreamEntry::EndBlock:
  5339. // Done parsing VST, jump back to wherever we came from.
  5340. Stream.JumpToBit(CurrentBit);
  5341. return std::error_code();
  5342. case BitstreamEntry::Record:
  5343. // The interesting case.
  5344. break;
  5345. }
  5346. // Read a record.
  5347. Record.clear();
  5348. switch (Stream.readRecord(Entry.ID, Record)) {
  5349. default: // Default behavior: ignore (e.g. VST_CODE_BBENTRY records).
  5350. break;
  5351. case bitc::VST_CODE_ENTRY: { // VST_CODE_ENTRY: [valueid, namechar x N]
  5352. if (convertToString(Record, 1, ValueName))
  5353. return error("Invalid record");
  5354. unsigned ValueID = Record[0];
  5355. assert(!SourceFileName.empty());
  5356. auto VLI = ValueIdToLinkageMap.find(ValueID);
  5357. assert(VLI != ValueIdToLinkageMap.end() &&
  5358. "No linkage found for VST entry?");
  5359. auto Linkage = VLI->second;
  5360. std::string GlobalId =
  5361. GlobalValue::getGlobalIdentifier(ValueName, Linkage, SourceFileName);
  5362. auto ValueGUID = GlobalValue::getGUID(GlobalId);
  5363. auto OriginalNameID = ValueGUID;
  5364. if (GlobalValue::isLocalLinkage(Linkage))
  5365. OriginalNameID = GlobalValue::getGUID(ValueName);
  5366. if (PrintSummaryGUIDs)
  5367. dbgs() << "GUID " << ValueGUID << "(" << OriginalNameID << ") is "
  5368. << ValueName << "\n";
  5369. ValueIdToCallGraphGUIDMap[ValueID] =
  5370. std::make_pair(ValueGUID, OriginalNameID);
  5371. ValueName.clear();
  5372. break;
  5373. }
  5374. case bitc::VST_CODE_FNENTRY: {
  5375. // VST_CODE_FNENTRY: [valueid, offset, namechar x N]
  5376. if (convertToString(Record, 2, ValueName))
  5377. return error("Invalid record");
  5378. unsigned ValueID = Record[0];
  5379. assert(!SourceFileName.empty());
  5380. auto VLI = ValueIdToLinkageMap.find(ValueID);
  5381. assert(VLI != ValueIdToLinkageMap.end() &&
  5382. "No linkage found for VST entry?");
  5383. auto Linkage = VLI->second;
  5384. std::string FunctionGlobalId = GlobalValue::getGlobalIdentifier(
  5385. ValueName, VLI->second, SourceFileName);
  5386. auto FunctionGUID = GlobalValue::getGUID(FunctionGlobalId);
  5387. auto OriginalNameID = FunctionGUID;
  5388. if (GlobalValue::isLocalLinkage(Linkage))
  5389. OriginalNameID = GlobalValue::getGUID(ValueName);
  5390. if (PrintSummaryGUIDs)
  5391. dbgs() << "GUID " << FunctionGUID << "(" << OriginalNameID << ") is "
  5392. << ValueName << "\n";
  5393. ValueIdToCallGraphGUIDMap[ValueID] =
  5394. std::make_pair(FunctionGUID, OriginalNameID);
  5395. ValueName.clear();
  5396. break;
  5397. }
  5398. case bitc::VST_CODE_COMBINED_ENTRY: {
  5399. // VST_CODE_COMBINED_ENTRY: [valueid, refguid]
  5400. unsigned ValueID = Record[0];
  5401. GlobalValue::GUID RefGUID = Record[1];
  5402. // The "original name", which is the second value of the pair will be
  5403. // overriden later by a FS_COMBINED_ORIGINAL_NAME in the combined index.
  5404. ValueIdToCallGraphGUIDMap[ValueID] = std::make_pair(RefGUID, RefGUID);
  5405. break;
  5406. }
  5407. }
  5408. }
  5409. }
  5410. // Parse just the blocks needed for building the index out of the module.
  5411. // At the end of this routine the module Index is populated with a map
  5412. // from global value id to GlobalValueSummary objects.
  5413. std::error_code ModuleSummaryIndexBitcodeReader::parseModule() {
  5414. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  5415. return error("Invalid record");
  5416. SmallVector<uint64_t, 64> Record;
  5417. DenseMap<unsigned, GlobalValue::LinkageTypes> ValueIdToLinkageMap;
  5418. unsigned ValueId = 0;
  5419. // Read the index for this module.
  5420. while (true) {
  5421. BitstreamEntry Entry = Stream.advance();
  5422. switch (Entry.Kind) {
  5423. case BitstreamEntry::Error:
  5424. return error("Malformed block");
  5425. case BitstreamEntry::EndBlock:
  5426. return std::error_code();
  5427. case BitstreamEntry::SubBlock:
  5428. if (CheckGlobalValSummaryPresenceOnly) {
  5429. if (Entry.ID == bitc::GLOBALVAL_SUMMARY_BLOCK_ID) {
  5430. SeenGlobalValSummary = true;
  5431. // No need to parse the rest since we found the summary.
  5432. return std::error_code();
  5433. }
  5434. if (Stream.SkipBlock())
  5435. return error("Invalid record");
  5436. continue;
  5437. }
  5438. switch (Entry.ID) {
  5439. default: // Skip unknown content.
  5440. if (Stream.SkipBlock())
  5441. return error("Invalid record");
  5442. break;
  5443. case bitc::BLOCKINFO_BLOCK_ID:
  5444. // Need to parse these to get abbrev ids (e.g. for VST)
  5445. if (readBlockInfo())
  5446. return error("Malformed block");
  5447. break;
  5448. case bitc::VALUE_SYMTAB_BLOCK_ID:
  5449. // Should have been parsed earlier via VSTOffset, unless there
  5450. // is no summary section.
  5451. assert(((SeenValueSymbolTable && VSTOffset > 0) ||
  5452. !SeenGlobalValSummary) &&
  5453. "Expected early VST parse via VSTOffset record");
  5454. if (Stream.SkipBlock())
  5455. return error("Invalid record");
  5456. break;
  5457. case bitc::GLOBALVAL_SUMMARY_BLOCK_ID:
  5458. assert(!SeenValueSymbolTable &&
  5459. "Already read VST when parsing summary block?");
  5460. // We might not have a VST if there were no values in the
  5461. // summary. An empty summary block generated when we are
  5462. // performing ThinLTO compiles so we don't later invoke
  5463. // the regular LTO process on them.
  5464. if (VSTOffset > 0) {
  5465. if (std::error_code EC =
  5466. parseValueSymbolTable(VSTOffset, ValueIdToLinkageMap))
  5467. return EC;
  5468. SeenValueSymbolTable = true;
  5469. }
  5470. SeenGlobalValSummary = true;
  5471. if (std::error_code EC = parseEntireSummary())
  5472. return EC;
  5473. break;
  5474. case bitc::MODULE_STRTAB_BLOCK_ID:
  5475. if (std::error_code EC = parseModuleStringTable())
  5476. return EC;
  5477. break;
  5478. }
  5479. continue;
  5480. case BitstreamEntry::Record: {
  5481. Record.clear();
  5482. auto BitCode = Stream.readRecord(Entry.ID, Record);
  5483. switch (BitCode) {
  5484. default:
  5485. break; // Default behavior, ignore unknown content.
  5486. /// MODULE_CODE_SOURCE_FILENAME: [namechar x N]
  5487. case bitc::MODULE_CODE_SOURCE_FILENAME: {
  5488. SmallString<128> ValueName;
  5489. if (convertToString(Record, 0, ValueName))
  5490. return error("Invalid record");
  5491. SourceFileName = ValueName.c_str();
  5492. break;
  5493. }
  5494. /// MODULE_CODE_HASH: [5*i32]
  5495. case bitc::MODULE_CODE_HASH: {
  5496. if (Record.size() != 5)
  5497. return error("Invalid hash length " + Twine(Record.size()).str());
  5498. if (!TheIndex)
  5499. break;
  5500. if (TheIndex->modulePaths().empty())
  5501. // We always seed the index with the module.
  5502. TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0);
  5503. if (TheIndex->modulePaths().size() != 1)
  5504. return error("Don't expect multiple modules defined?");
  5505. auto &Hash = TheIndex->modulePaths().begin()->second.second;
  5506. int Pos = 0;
  5507. for (auto &Val : Record) {
  5508. assert(!(Val >> 32) && "Unexpected high bits set");
  5509. Hash[Pos++] = Val;
  5510. }
  5511. break;
  5512. }
  5513. /// MODULE_CODE_VSTOFFSET: [offset]
  5514. case bitc::MODULE_CODE_VSTOFFSET:
  5515. if (Record.size() < 1)
  5516. return error("Invalid record");
  5517. VSTOffset = Record[0];
  5518. break;
  5519. // GLOBALVAR: [pointer type, isconst, initid,
  5520. // linkage, alignment, section, visibility, threadlocal,
  5521. // unnamed_addr, externally_initialized, dllstorageclass,
  5522. // comdat]
  5523. case bitc::MODULE_CODE_GLOBALVAR: {
  5524. if (Record.size() < 6)
  5525. return error("Invalid record");
  5526. uint64_t RawLinkage = Record[3];
  5527. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  5528. ValueIdToLinkageMap[ValueId++] = Linkage;
  5529. break;
  5530. }
  5531. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  5532. // alignment, section, visibility, gc, unnamed_addr,
  5533. // prologuedata, dllstorageclass, comdat, prefixdata]
  5534. case bitc::MODULE_CODE_FUNCTION: {
  5535. if (Record.size() < 8)
  5536. return error("Invalid record");
  5537. uint64_t RawLinkage = Record[3];
  5538. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  5539. ValueIdToLinkageMap[ValueId++] = Linkage;
  5540. break;
  5541. }
  5542. // ALIAS: [alias type, addrspace, aliasee val#, linkage, visibility,
  5543. // dllstorageclass]
  5544. case bitc::MODULE_CODE_ALIAS: {
  5545. if (Record.size() < 6)
  5546. return error("Invalid record");
  5547. uint64_t RawLinkage = Record[3];
  5548. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  5549. ValueIdToLinkageMap[ValueId++] = Linkage;
  5550. break;
  5551. }
  5552. }
  5553. }
  5554. continue;
  5555. }
  5556. }
  5557. }
  5558. // Eagerly parse the entire summary block. This populates the GlobalValueSummary
  5559. // objects in the index.
  5560. std::error_code ModuleSummaryIndexBitcodeReader::parseEntireSummary() {
  5561. if (Stream.EnterSubBlock(bitc::GLOBALVAL_SUMMARY_BLOCK_ID))
  5562. return error("Invalid record");
  5563. SmallVector<uint64_t, 64> Record;
  5564. // Parse version
  5565. {
  5566. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  5567. if (Entry.Kind != BitstreamEntry::Record)
  5568. return error("Invalid Summary Block: record for version expected");
  5569. if (Stream.readRecord(Entry.ID, Record) != bitc::FS_VERSION)
  5570. return error("Invalid Summary Block: version expected");
  5571. }
  5572. const uint64_t Version = Record[0];
  5573. const bool IsOldProfileFormat = Version == 1;
  5574. if (!IsOldProfileFormat && Version != 2)
  5575. return error("Invalid summary version " + Twine(Version) +
  5576. ", 1 or 2 expected");
  5577. Record.clear();
  5578. // Keep around the last seen summary to be used when we see an optional
  5579. // "OriginalName" attachement.
  5580. GlobalValueSummary *LastSeenSummary = nullptr;
  5581. bool Combined = false;
  5582. while (true) {
  5583. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  5584. switch (Entry.Kind) {
  5585. case BitstreamEntry::SubBlock: // Handled for us already.
  5586. case BitstreamEntry::Error:
  5587. return error("Malformed block");
  5588. case BitstreamEntry::EndBlock:
  5589. // For a per-module index, remove any entries that still have empty
  5590. // summaries. The VST parsing creates entries eagerly for all symbols,
  5591. // but not all have associated summaries (e.g. it doesn't know how to
  5592. // distinguish between VST_CODE_ENTRY for function declarations vs global
  5593. // variables with initializers that end up with a summary). Remove those
  5594. // entries now so that we don't need to rely on the combined index merger
  5595. // to clean them up (especially since that may not run for the first
  5596. // module's index if we merge into that).
  5597. if (!Combined)
  5598. TheIndex->removeEmptySummaryEntries();
  5599. return std::error_code();
  5600. case BitstreamEntry::Record:
  5601. // The interesting case.
  5602. break;
  5603. }
  5604. // Read a record. The record format depends on whether this
  5605. // is a per-module index or a combined index file. In the per-module
  5606. // case the records contain the associated value's ID for correlation
  5607. // with VST entries. In the combined index the correlation is done
  5608. // via the bitcode offset of the summary records (which were saved
  5609. // in the combined index VST entries). The records also contain
  5610. // information used for ThinLTO renaming and importing.
  5611. Record.clear();
  5612. auto BitCode = Stream.readRecord(Entry.ID, Record);
  5613. switch (BitCode) {
  5614. default: // Default behavior: ignore.
  5615. break;
  5616. // FS_PERMODULE: [valueid, flags, instcount, numrefs, numrefs x valueid,
  5617. // n x (valueid)]
  5618. // FS_PERMODULE_PROFILE: [valueid, flags, instcount, numrefs,
  5619. // numrefs x valueid,
  5620. // n x (valueid, hotness)]
  5621. case bitc::FS_PERMODULE:
  5622. case bitc::FS_PERMODULE_PROFILE: {
  5623. unsigned ValueID = Record[0];
  5624. uint64_t RawFlags = Record[1];
  5625. unsigned InstCount = Record[2];
  5626. unsigned NumRefs = Record[3];
  5627. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  5628. std::unique_ptr<FunctionSummary> FS =
  5629. llvm::make_unique<FunctionSummary>(Flags, InstCount);
  5630. // The module path string ref set in the summary must be owned by the
  5631. // index's module string table. Since we don't have a module path
  5632. // string table section in the per-module index, we create a single
  5633. // module path string table entry with an empty (0) ID to take
  5634. // ownership.
  5635. FS->setModulePath(
  5636. TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0)->first());
  5637. static int RefListStartIndex = 4;
  5638. int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
  5639. assert(Record.size() >= RefListStartIndex + NumRefs &&
  5640. "Record size inconsistent with number of references");
  5641. for (unsigned I = 4, E = CallGraphEdgeStartIndex; I != E; ++I) {
  5642. unsigned RefValueId = Record[I];
  5643. GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
  5644. FS->addRefEdge(RefGUID);
  5645. }
  5646. bool HasProfile = (BitCode == bitc::FS_PERMODULE_PROFILE);
  5647. for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
  5648. ++I) {
  5649. CalleeInfo::HotnessType Hotness;
  5650. GlobalValue::GUID CalleeGUID;
  5651. std::tie(CalleeGUID, Hotness) =
  5652. readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile);
  5653. FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness));
  5654. }
  5655. auto GUID = getGUIDFromValueId(ValueID);
  5656. FS->setOriginalName(GUID.second);
  5657. TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
  5658. break;
  5659. }
  5660. // FS_ALIAS: [valueid, flags, valueid]
  5661. // Aliases must be emitted (and parsed) after all FS_PERMODULE entries, as
  5662. // they expect all aliasee summaries to be available.
  5663. case bitc::FS_ALIAS: {
  5664. unsigned ValueID = Record[0];
  5665. uint64_t RawFlags = Record[1];
  5666. unsigned AliaseeID = Record[2];
  5667. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  5668. std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
  5669. // The module path string ref set in the summary must be owned by the
  5670. // index's module string table. Since we don't have a module path
  5671. // string table section in the per-module index, we create a single
  5672. // module path string table entry with an empty (0) ID to take
  5673. // ownership.
  5674. AS->setModulePath(
  5675. TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0)->first());
  5676. GlobalValue::GUID AliaseeGUID = getGUIDFromValueId(AliaseeID).first;
  5677. auto *AliaseeSummary = TheIndex->getGlobalValueSummary(AliaseeGUID);
  5678. if (!AliaseeSummary)
  5679. return error("Alias expects aliasee summary to be parsed");
  5680. AS->setAliasee(AliaseeSummary);
  5681. auto GUID = getGUIDFromValueId(ValueID);
  5682. AS->setOriginalName(GUID.second);
  5683. TheIndex->addGlobalValueSummary(GUID.first, std::move(AS));
  5684. break;
  5685. }
  5686. // FS_PERMODULE_GLOBALVAR_INIT_REFS: [valueid, flags, n x valueid]
  5687. case bitc::FS_PERMODULE_GLOBALVAR_INIT_REFS: {
  5688. unsigned ValueID = Record[0];
  5689. uint64_t RawFlags = Record[1];
  5690. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  5691. std::unique_ptr<GlobalVarSummary> FS =
  5692. llvm::make_unique<GlobalVarSummary>(Flags);
  5693. FS->setModulePath(
  5694. TheIndex->addModulePath(Buffer.getBufferIdentifier(), 0)->first());
  5695. for (unsigned I = 2, E = Record.size(); I != E; ++I) {
  5696. unsigned RefValueId = Record[I];
  5697. GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
  5698. FS->addRefEdge(RefGUID);
  5699. }
  5700. auto GUID = getGUIDFromValueId(ValueID);
  5701. FS->setOriginalName(GUID.second);
  5702. TheIndex->addGlobalValueSummary(GUID.first, std::move(FS));
  5703. break;
  5704. }
  5705. // FS_COMBINED: [valueid, modid, flags, instcount, numrefs,
  5706. // numrefs x valueid, n x (valueid)]
  5707. // FS_COMBINED_PROFILE: [valueid, modid, flags, instcount, numrefs,
  5708. // numrefs x valueid, n x (valueid, hotness)]
  5709. case bitc::FS_COMBINED:
  5710. case bitc::FS_COMBINED_PROFILE: {
  5711. unsigned ValueID = Record[0];
  5712. uint64_t ModuleId = Record[1];
  5713. uint64_t RawFlags = Record[2];
  5714. unsigned InstCount = Record[3];
  5715. unsigned NumRefs = Record[4];
  5716. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  5717. std::unique_ptr<FunctionSummary> FS =
  5718. llvm::make_unique<FunctionSummary>(Flags, InstCount);
  5719. LastSeenSummary = FS.get();
  5720. FS->setModulePath(ModuleIdMap[ModuleId]);
  5721. static int RefListStartIndex = 5;
  5722. int CallGraphEdgeStartIndex = RefListStartIndex + NumRefs;
  5723. assert(Record.size() >= RefListStartIndex + NumRefs &&
  5724. "Record size inconsistent with number of references");
  5725. for (unsigned I = RefListStartIndex, E = CallGraphEdgeStartIndex; I != E;
  5726. ++I) {
  5727. unsigned RefValueId = Record[I];
  5728. GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
  5729. FS->addRefEdge(RefGUID);
  5730. }
  5731. bool HasProfile = (BitCode == bitc::FS_COMBINED_PROFILE);
  5732. for (unsigned I = CallGraphEdgeStartIndex, E = Record.size(); I != E;
  5733. ++I) {
  5734. CalleeInfo::HotnessType Hotness;
  5735. GlobalValue::GUID CalleeGUID;
  5736. std::tie(CalleeGUID, Hotness) =
  5737. readCallGraphEdge(Record, I, IsOldProfileFormat, HasProfile);
  5738. FS->addCallGraphEdge(CalleeGUID, CalleeInfo(Hotness));
  5739. }
  5740. GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
  5741. TheIndex->addGlobalValueSummary(GUID, std::move(FS));
  5742. Combined = true;
  5743. break;
  5744. }
  5745. // FS_COMBINED_ALIAS: [valueid, modid, flags, valueid]
  5746. // Aliases must be emitted (and parsed) after all FS_COMBINED entries, as
  5747. // they expect all aliasee summaries to be available.
  5748. case bitc::FS_COMBINED_ALIAS: {
  5749. unsigned ValueID = Record[0];
  5750. uint64_t ModuleId = Record[1];
  5751. uint64_t RawFlags = Record[2];
  5752. unsigned AliaseeValueId = Record[3];
  5753. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  5754. std::unique_ptr<AliasSummary> AS = llvm::make_unique<AliasSummary>(Flags);
  5755. LastSeenSummary = AS.get();
  5756. AS->setModulePath(ModuleIdMap[ModuleId]);
  5757. auto AliaseeGUID = getGUIDFromValueId(AliaseeValueId).first;
  5758. auto AliaseeInModule =
  5759. TheIndex->findSummaryInModule(AliaseeGUID, AS->modulePath());
  5760. if (!AliaseeInModule)
  5761. return error("Alias expects aliasee summary to be parsed");
  5762. AS->setAliasee(AliaseeInModule);
  5763. GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
  5764. TheIndex->addGlobalValueSummary(GUID, std::move(AS));
  5765. Combined = true;
  5766. break;
  5767. }
  5768. // FS_COMBINED_GLOBALVAR_INIT_REFS: [valueid, modid, flags, n x valueid]
  5769. case bitc::FS_COMBINED_GLOBALVAR_INIT_REFS: {
  5770. unsigned ValueID = Record[0];
  5771. uint64_t ModuleId = Record[1];
  5772. uint64_t RawFlags = Record[2];
  5773. auto Flags = getDecodedGVSummaryFlags(RawFlags, Version);
  5774. std::unique_ptr<GlobalVarSummary> FS =
  5775. llvm::make_unique<GlobalVarSummary>(Flags);
  5776. LastSeenSummary = FS.get();
  5777. FS->setModulePath(ModuleIdMap[ModuleId]);
  5778. for (unsigned I = 3, E = Record.size(); I != E; ++I) {
  5779. unsigned RefValueId = Record[I];
  5780. GlobalValue::GUID RefGUID = getGUIDFromValueId(RefValueId).first;
  5781. FS->addRefEdge(RefGUID);
  5782. }
  5783. GlobalValue::GUID GUID = getGUIDFromValueId(ValueID).first;
  5784. TheIndex->addGlobalValueSummary(GUID, std::move(FS));
  5785. Combined = true;
  5786. break;
  5787. }
  5788. // FS_COMBINED_ORIGINAL_NAME: [original_name]
  5789. case bitc::FS_COMBINED_ORIGINAL_NAME: {
  5790. uint64_t OriginalName = Record[0];
  5791. if (!LastSeenSummary)
  5792. return error("Name attachment that does not follow a combined record");
  5793. LastSeenSummary->setOriginalName(OriginalName);
  5794. // Reset the LastSeenSummary
  5795. LastSeenSummary = nullptr;
  5796. }
  5797. }
  5798. }
  5799. llvm_unreachable("Exit infinite loop");
  5800. }
  5801. std::pair<GlobalValue::GUID, CalleeInfo::HotnessType>
  5802. ModuleSummaryIndexBitcodeReader::readCallGraphEdge(
  5803. const SmallVector<uint64_t, 64> &Record, unsigned int &I,
  5804. const bool IsOldProfileFormat, const bool HasProfile) {
  5805. auto Hotness = CalleeInfo::HotnessType::Unknown;
  5806. unsigned CalleeValueId = Record[I];
  5807. GlobalValue::GUID CalleeGUID = getGUIDFromValueId(CalleeValueId).first;
  5808. if (IsOldProfileFormat) {
  5809. I += 1; // Skip old callsitecount field
  5810. if (HasProfile)
  5811. I += 1; // Skip old profilecount field
  5812. } else if (HasProfile)
  5813. Hotness = static_cast<CalleeInfo::HotnessType>(Record[++I]);
  5814. return {CalleeGUID, Hotness};
  5815. }
  5816. // Parse the module string table block into the Index.
  5817. // This populates the ModulePathStringTable map in the index.
  5818. std::error_code ModuleSummaryIndexBitcodeReader::parseModuleStringTable() {
  5819. if (Stream.EnterSubBlock(bitc::MODULE_STRTAB_BLOCK_ID))
  5820. return error("Invalid record");
  5821. SmallVector<uint64_t, 64> Record;
  5822. SmallString<128> ModulePath;
  5823. ModulePathStringTableTy::iterator LastSeenModulePath;
  5824. while (true) {
  5825. BitstreamEntry Entry = Stream.advanceSkippingSubblocks();
  5826. switch (Entry.Kind) {
  5827. case BitstreamEntry::SubBlock: // Handled for us already.
  5828. case BitstreamEntry::Error:
  5829. return error("Malformed block");
  5830. case BitstreamEntry::EndBlock:
  5831. return std::error_code();
  5832. case BitstreamEntry::Record:
  5833. // The interesting case.
  5834. break;
  5835. }
  5836. Record.clear();
  5837. switch (Stream.readRecord(Entry.ID, Record)) {
  5838. default: // Default behavior: ignore.
  5839. break;
  5840. case bitc::MST_CODE_ENTRY: {
  5841. // MST_ENTRY: [modid, namechar x N]
  5842. uint64_t ModuleId = Record[0];
  5843. if (convertToString(Record, 1, ModulePath))
  5844. return error("Invalid record");
  5845. LastSeenModulePath = TheIndex->addModulePath(ModulePath, ModuleId);
  5846. ModuleIdMap[ModuleId] = LastSeenModulePath->first();
  5847. ModulePath.clear();
  5848. break;
  5849. }
  5850. /// MST_CODE_HASH: [5*i32]
  5851. case bitc::MST_CODE_HASH: {
  5852. if (Record.size() != 5)
  5853. return error("Invalid hash length " + Twine(Record.size()).str());
  5854. if (LastSeenModulePath == TheIndex->modulePaths().end())
  5855. return error("Invalid hash that does not follow a module path");
  5856. int Pos = 0;
  5857. for (auto &Val : Record) {
  5858. assert(!(Val >> 32) && "Unexpected high bits set");
  5859. LastSeenModulePath->second.second[Pos++] = Val;
  5860. }
  5861. // Reset LastSeenModulePath to avoid overriding the hash unexpectedly.
  5862. LastSeenModulePath = TheIndex->modulePaths().end();
  5863. break;
  5864. }
  5865. }
  5866. }
  5867. llvm_unreachable("Exit infinite loop");
  5868. }
  5869. // Parse the function info index from the bitcode streamer into the given index.
  5870. std::error_code
  5871. ModuleSummaryIndexBitcodeReader::parseSummaryIndexInto(ModuleSummaryIndex *I) {
  5872. TheIndex = I;
  5873. if (std::error_code EC = initStream())
  5874. return EC;
  5875. // Sniff for the signature.
  5876. if (!hasValidBitcodeHeader(Stream))
  5877. return error("Invalid bitcode signature");
  5878. // We expect a number of well-defined blocks, though we don't necessarily
  5879. // need to understand them all.
  5880. while (true) {
  5881. if (Stream.AtEndOfStream()) {
  5882. // We didn't really read a proper Module block.
  5883. return error("Malformed block");
  5884. }
  5885. BitstreamEntry Entry =
  5886. Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
  5887. if (Entry.Kind != BitstreamEntry::SubBlock)
  5888. return error("Malformed block");
  5889. // If we see a MODULE_BLOCK, parse it to find the blocks needed for
  5890. // building the function summary index.
  5891. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  5892. return parseModule();
  5893. if (Stream.SkipBlock())
  5894. return error("Invalid record");
  5895. }
  5896. }
  5897. namespace {
  5898. // FIXME: This class is only here to support the transition to llvm::Error. It
  5899. // will be removed once this transition is complete. Clients should prefer to
  5900. // deal with the Error value directly, rather than converting to error_code.
  5901. class BitcodeErrorCategoryType : public std::error_category {
  5902. const char *name() const noexcept override {
  5903. return "llvm.bitcode";
  5904. }
  5905. std::string message(int IE) const override {
  5906. BitcodeError E = static_cast<BitcodeError>(IE);
  5907. switch (E) {
  5908. case BitcodeError::InvalidBitcodeSignature:
  5909. return "Invalid bitcode signature";
  5910. case BitcodeError::CorruptedBitcode:
  5911. return "Corrupted bitcode";
  5912. }
  5913. llvm_unreachable("Unknown error type!");
  5914. }
  5915. };
  5916. } // end anonymous namespace
  5917. static ManagedStatic<BitcodeErrorCategoryType> ErrorCategory;
  5918. const std::error_category &llvm::BitcodeErrorCategory() {
  5919. return *ErrorCategory;
  5920. }
  5921. //===----------------------------------------------------------------------===//
  5922. // External interface
  5923. //===----------------------------------------------------------------------===//
  5924. /// \brief Get a lazy one-at-time loading module from bitcode.
  5925. ///
  5926. /// This isn't always used in a lazy context. In particular, it's also used by
  5927. /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
  5928. /// in forward-referenced functions from block address references.
  5929. ///
  5930. /// \param[in] MaterializeAll Set to \c true if we should materialize
  5931. /// everything.
  5932. static ErrorOr<std::unique_ptr<Module>>
  5933. getLazyBitcodeModuleImpl(MemoryBufferRef Buffer, LLVMContext &Context,
  5934. bool MaterializeAll,
  5935. bool ShouldLazyLoadMetadata = false) {
  5936. BitcodeReader *R = new BitcodeReader(Buffer, Context);
  5937. std::unique_ptr<Module> M =
  5938. llvm::make_unique<Module>(Buffer.getBufferIdentifier(), Context);
  5939. M->setMaterializer(R);
  5940. // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
  5941. if (std::error_code EC = R->parseBitcodeInto(M.get(), ShouldLazyLoadMetadata))
  5942. return EC;
  5943. if (MaterializeAll) {
  5944. // Read in the entire module, and destroy the BitcodeReader.
  5945. if (std::error_code EC = M->materializeAll())
  5946. return EC;
  5947. } else {
  5948. // Resolve forward references from blockaddresses.
  5949. if (std::error_code EC = R->materializeForwardReferencedFunctions())
  5950. return EC;
  5951. }
  5952. return std::move(M);
  5953. }
  5954. ErrorOr<std::unique_ptr<Module>>
  5955. llvm::getLazyBitcodeModule(MemoryBufferRef Buffer,
  5956. LLVMContext &Context, bool ShouldLazyLoadMetadata) {
  5957. return getLazyBitcodeModuleImpl(Buffer, Context, false,
  5958. ShouldLazyLoadMetadata);
  5959. }
  5960. ErrorOr<std::unique_ptr<Module>>
  5961. llvm::getOwningLazyBitcodeModule(std::unique_ptr<MemoryBuffer> &&Buffer,
  5962. LLVMContext &Context,
  5963. bool ShouldLazyLoadMetadata) {
  5964. auto MOrErr = getLazyBitcodeModule(*Buffer, Context, ShouldLazyLoadMetadata);
  5965. if (MOrErr)
  5966. (*MOrErr)->setOwnedMemoryBuffer(std::move(Buffer));
  5967. return MOrErr;
  5968. }
  5969. ErrorOr<std::unique_ptr<Module>> llvm::parseBitcodeFile(MemoryBufferRef Buffer,
  5970. LLVMContext &Context) {
  5971. return getLazyBitcodeModuleImpl(Buffer, Context, true);
  5972. // TODO: Restore the use-lists to the in-memory state when the bitcode was
  5973. // written. We must defer until the Module has been fully materialized.
  5974. }
  5975. std::string llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer,
  5976. LLVMContext &Context) {
  5977. BitcodeReader R(Buffer, Context);
  5978. ErrorOr<std::string> Triple = R.parseTriple();
  5979. if (Triple.getError())
  5980. return "";
  5981. return Triple.get();
  5982. }
  5983. bool llvm::isBitcodeContainingObjCCategory(MemoryBufferRef Buffer,
  5984. LLVMContext &Context) {
  5985. BitcodeReader R(Buffer, Context);
  5986. ErrorOr<bool> hasObjCCategory = R.hasObjCCategory();
  5987. if (hasObjCCategory.getError())
  5988. return false;
  5989. return hasObjCCategory.get();
  5990. }
  5991. std::string llvm::getBitcodeProducerString(MemoryBufferRef Buffer,
  5992. LLVMContext &Context) {
  5993. BitcodeReader R(Buffer, Context);
  5994. ErrorOr<std::string> ProducerString = R.parseIdentificationBlock();
  5995. if (ProducerString.getError())
  5996. return "";
  5997. return ProducerString.get();
  5998. }
  5999. // Parse the specified bitcode buffer, returning the function info index.
  6000. ErrorOr<std::unique_ptr<ModuleSummaryIndex>> llvm::getModuleSummaryIndex(
  6001. MemoryBufferRef Buffer,
  6002. const DiagnosticHandlerFunction &DiagnosticHandler) {
  6003. ModuleSummaryIndexBitcodeReader R(Buffer, DiagnosticHandler);
  6004. auto Index = llvm::make_unique<ModuleSummaryIndex>();
  6005. if (std::error_code EC = R.parseSummaryIndexInto(Index.get()))
  6006. return EC;
  6007. return std::move(Index);
  6008. }
  6009. // Check if the given bitcode buffer contains a global value summary block.
  6010. bool llvm::hasGlobalValueSummary(
  6011. MemoryBufferRef Buffer,
  6012. const DiagnosticHandlerFunction &DiagnosticHandler) {
  6013. ModuleSummaryIndexBitcodeReader R(Buffer, DiagnosticHandler, true);
  6014. if (R.parseSummaryIndexInto(nullptr))
  6015. return false;
  6016. return R.foundGlobalValSummary();
  6017. }