BitcodeReader.cpp 240 KB

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