BitcodeReader.cpp 240 KB

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