BitcodeReader.cpp 238 KB

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