BitcodeReader.cpp 224 KB

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