BitcodeReader.cpp 221 KB

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