BitcodeReader.cpp 207 KB

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