BitcodeReader.cpp 230 KB

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