BitcodeReader.cpp 239 KB

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