BitcodeReader.cpp 210 KB

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