BitcodeReader.cpp 169 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833
  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/ReaderWriter.h"
  10. #include "llvm/ADT/STLExtras.h"
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/SmallVector.h"
  13. #include "llvm/ADT/Triple.h"
  14. #include "llvm/Bitcode/BitstreamReader.h"
  15. #include "llvm/Bitcode/LLVMBitCodes.h"
  16. #include "llvm/IR/AutoUpgrade.h"
  17. #include "llvm/IR/Constants.h"
  18. #include "llvm/IR/DebugInfo.h"
  19. #include "llvm/IR/DebugInfoMetadata.h"
  20. #include "llvm/IR/DerivedTypes.h"
  21. #include "llvm/IR/DiagnosticPrinter.h"
  22. #include "llvm/IR/GVMaterializer.h"
  23. #include "llvm/IR/InlineAsm.h"
  24. #include "llvm/IR/IntrinsicInst.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IR/OperandTraits.h"
  28. #include "llvm/IR/Operator.h"
  29. #include "llvm/IR/ValueHandle.h"
  30. #include "llvm/Support/DataStream.h"
  31. #include "llvm/Support/ManagedStatic.h"
  32. #include "llvm/Support/MathExtras.h"
  33. #include "llvm/Support/MemoryBuffer.h"
  34. #include "llvm/Support/raw_ostream.h"
  35. #include <deque>
  36. using namespace llvm;
  37. namespace {
  38. enum {
  39. SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
  40. };
  41. class BitcodeReaderValueList {
  42. std::vector<WeakVH> ValuePtrs;
  43. /// As we resolve forward-referenced constants, we add information about them
  44. /// to this vector. This allows us to resolve them in bulk instead of
  45. /// resolving each reference at a time. See the code in
  46. /// ResolveConstantForwardRefs for more information about this.
  47. ///
  48. /// The key of this vector is the placeholder constant, the value is the slot
  49. /// number that holds the resolved value.
  50. typedef std::vector<std::pair<Constant*, unsigned> > ResolveConstantsTy;
  51. ResolveConstantsTy ResolveConstants;
  52. LLVMContext &Context;
  53. public:
  54. BitcodeReaderValueList(LLVMContext &C) : Context(C) {}
  55. ~BitcodeReaderValueList() {
  56. assert(ResolveConstants.empty() && "Constants not resolved?");
  57. }
  58. // vector compatibility methods
  59. unsigned size() const { return ValuePtrs.size(); }
  60. void resize(unsigned N) { ValuePtrs.resize(N); }
  61. void push_back(Value *V) { ValuePtrs.emplace_back(V); }
  62. void clear() {
  63. assert(ResolveConstants.empty() && "Constants not resolved?");
  64. ValuePtrs.clear();
  65. }
  66. Value *operator[](unsigned i) const {
  67. assert(i < ValuePtrs.size());
  68. return ValuePtrs[i];
  69. }
  70. Value *back() const { return ValuePtrs.back(); }
  71. void pop_back() { ValuePtrs.pop_back(); }
  72. bool empty() const { return ValuePtrs.empty(); }
  73. void shrinkTo(unsigned N) {
  74. assert(N <= size() && "Invalid shrinkTo request!");
  75. ValuePtrs.resize(N);
  76. }
  77. Constant *getConstantFwdRef(unsigned Idx, Type *Ty);
  78. Value *getValueFwdRef(unsigned Idx, Type *Ty);
  79. void assignValue(Value *V, unsigned Idx);
  80. /// Once all constants are read, this method bulk resolves any forward
  81. /// references.
  82. void resolveConstantForwardRefs();
  83. };
  84. class BitcodeReaderMDValueList {
  85. unsigned NumFwdRefs;
  86. bool AnyFwdRefs;
  87. unsigned MinFwdRef;
  88. unsigned MaxFwdRef;
  89. std::vector<TrackingMDRef> MDValuePtrs;
  90. LLVMContext &Context;
  91. public:
  92. BitcodeReaderMDValueList(LLVMContext &C)
  93. : NumFwdRefs(0), AnyFwdRefs(false), Context(C) {}
  94. // vector compatibility methods
  95. unsigned size() const { return MDValuePtrs.size(); }
  96. void resize(unsigned N) { MDValuePtrs.resize(N); }
  97. void push_back(Metadata *MD) { MDValuePtrs.emplace_back(MD); }
  98. void clear() { MDValuePtrs.clear(); }
  99. Metadata *back() const { return MDValuePtrs.back(); }
  100. void pop_back() { MDValuePtrs.pop_back(); }
  101. bool empty() const { return MDValuePtrs.empty(); }
  102. Metadata *operator[](unsigned i) const {
  103. assert(i < MDValuePtrs.size());
  104. return MDValuePtrs[i];
  105. }
  106. void shrinkTo(unsigned N) {
  107. assert(N <= size() && "Invalid shrinkTo request!");
  108. MDValuePtrs.resize(N);
  109. }
  110. Metadata *getValueFwdRef(unsigned Idx);
  111. void assignValue(Metadata *MD, unsigned Idx);
  112. void tryToResolveCycles();
  113. };
  114. class BitcodeReader : public GVMaterializer {
  115. LLVMContext &Context;
  116. DiagnosticHandlerFunction DiagnosticHandler;
  117. Module *TheModule = nullptr;
  118. std::unique_ptr<MemoryBuffer> Buffer;
  119. std::unique_ptr<BitstreamReader> StreamFile;
  120. BitstreamCursor Stream;
  121. uint64_t NextUnreadBit = 0;
  122. bool SeenValueSymbolTable = false;
  123. std::vector<Type*> TypeList;
  124. BitcodeReaderValueList ValueList;
  125. BitcodeReaderMDValueList MDValueList;
  126. std::vector<Comdat *> ComdatList;
  127. SmallVector<Instruction *, 64> InstructionList;
  128. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInits;
  129. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInits;
  130. std::vector<std::pair<Function*, unsigned> > FunctionPrefixes;
  131. std::vector<std::pair<Function*, unsigned> > FunctionPrologues;
  132. std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFns;
  133. SmallVector<Instruction*, 64> InstsWithTBAATag;
  134. /// The set of attributes by index. Index zero in the file is for null, and
  135. /// is thus not represented here. As such all indices are off by one.
  136. std::vector<AttributeSet> MAttributes;
  137. /// \brief The set of attribute groups.
  138. std::map<unsigned, AttributeSet> MAttributeGroups;
  139. /// While parsing a function body, this is a list of the basic blocks for the
  140. /// function.
  141. std::vector<BasicBlock*> FunctionBBs;
  142. // When reading the module header, this list is populated with functions that
  143. // have bodies later in the file.
  144. std::vector<Function*> FunctionsWithBodies;
  145. // When intrinsic functions are encountered which require upgrading they are
  146. // stored here with their replacement function.
  147. typedef DenseMap<Function*, Function*> UpgradedIntrinsicMap;
  148. UpgradedIntrinsicMap UpgradedIntrinsics;
  149. // Map the bitcode's custom MDKind ID to the Module's MDKind ID.
  150. DenseMap<unsigned, unsigned> MDKindMap;
  151. // Several operations happen after the module header has been read, but
  152. // before function bodies are processed. This keeps track of whether
  153. // we've done this yet.
  154. bool SeenFirstFunctionBody = false;
  155. /// When function bodies are initially scanned, this map contains info about
  156. /// where to find deferred function body in the stream.
  157. DenseMap<Function*, uint64_t> DeferredFunctionInfo;
  158. /// When Metadata block is initially scanned when parsing the module, we may
  159. /// choose to defer parsing of the metadata. This vector contains info about
  160. /// which Metadata blocks are deferred.
  161. std::vector<uint64_t> DeferredMetadataInfo;
  162. /// These are basic blocks forward-referenced by block addresses. They are
  163. /// inserted lazily into functions when they're loaded. The basic block ID is
  164. /// its index into the vector.
  165. DenseMap<Function *, std::vector<BasicBlock *>> BasicBlockFwdRefs;
  166. std::deque<Function *> BasicBlockFwdRefQueue;
  167. /// Indicates that we are using a new encoding for instruction operands where
  168. /// most operands in the current FUNCTION_BLOCK are encoded relative to the
  169. /// instruction number, for a more compact encoding. Some instruction
  170. /// operands are not relative to the instruction ID: basic block numbers, and
  171. /// types. Once the old style function blocks have been phased out, we would
  172. /// not need this flag.
  173. bool UseRelativeIDs = false;
  174. /// True if all functions will be materialized, negating the need to process
  175. /// (e.g.) blockaddress forward references.
  176. bool WillMaterializeAllForwardRefs = false;
  177. /// Functions that have block addresses taken. This is usually empty.
  178. SmallPtrSet<const Function *, 4> BlockAddressesTaken;
  179. /// True if any Metadata block has been materialized.
  180. bool IsMetadataMaterialized = false;
  181. bool StripDebugInfo = false;
  182. public:
  183. std::error_code error(BitcodeError E, const Twine &Message);
  184. std::error_code error(BitcodeError E);
  185. std::error_code error(const Twine &Message);
  186. BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
  187. DiagnosticHandlerFunction DiagnosticHandler);
  188. BitcodeReader(LLVMContext &Context,
  189. DiagnosticHandlerFunction DiagnosticHandler);
  190. ~BitcodeReader() override { freeState(); }
  191. std::error_code materializeForwardReferencedFunctions();
  192. void freeState();
  193. void releaseBuffer();
  194. BitstreamUseTracker Tracker; // HLSL Change
  195. bool isDematerializable(const GlobalValue *GV) const override;
  196. std::error_code materialize(GlobalValue *GV) override;
  197. std::error_code materializeModule(Module *M) override;
  198. std::vector<StructType *> getIdentifiedStructTypes() const override;
  199. void dematerialize(GlobalValue *GV) override;
  200. /// \brief Main interface to parsing a bitcode buffer.
  201. /// \returns true if an error occurred.
  202. std::error_code parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
  203. Module *M,
  204. bool ShouldLazyLoadMetadata = false);
  205. /// \brief Cheap mechanism to just extract module triple
  206. /// \returns true if an error occurred.
  207. ErrorOr<std::string> parseTriple();
  208. static uint64_t decodeSignRotatedValue(uint64_t V);
  209. /// Materialize any deferred Metadata block.
  210. std::error_code materializeMetadata() override;
  211. void setStripDebugInfo() override;
  212. private:
  213. std::vector<StructType *> IdentifiedStructTypes;
  214. StructType *createIdentifiedStructType(LLVMContext &Context, StringRef Name);
  215. StructType *createIdentifiedStructType(LLVMContext &Context);
  216. Type *getTypeByID(unsigned ID);
  217. Value *getFnValueByID(unsigned ID, Type *Ty) {
  218. if (Ty && Ty->isMetadataTy())
  219. return MetadataAsValue::get(Ty->getContext(), getFnMetadataByID(ID));
  220. return ValueList.getValueFwdRef(ID, Ty);
  221. }
  222. Metadata *getFnMetadataByID(unsigned ID) {
  223. return MDValueList.getValueFwdRef(ID);
  224. }
  225. BasicBlock *getBasicBlock(unsigned ID) const {
  226. if (ID >= FunctionBBs.size()) return nullptr; // Invalid ID
  227. return FunctionBBs[ID];
  228. }
  229. AttributeSet getAttributes(unsigned i) const {
  230. if (i-1 < MAttributes.size())
  231. return MAttributes[i-1];
  232. return AttributeSet();
  233. }
  234. /// Read a value/type pair out of the specified record from slot 'Slot'.
  235. /// Increment Slot past the number of slots used in the record. Return true on
  236. /// failure.
  237. bool getValueTypePair(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  238. unsigned InstNum, Value *&ResVal) {
  239. if (Slot == Record.size()) return true;
  240. unsigned ValNo = (unsigned)Record[Slot++];
  241. // Adjust the ValNo, if it was encoded relative to the InstNum.
  242. if (UseRelativeIDs)
  243. ValNo = InstNum - ValNo;
  244. if (ValNo < InstNum) {
  245. // If this is not a forward reference, just return the value we already
  246. // have.
  247. ResVal = getFnValueByID(ValNo, nullptr);
  248. return ResVal == nullptr;
  249. }
  250. if (Slot == Record.size())
  251. return true;
  252. unsigned TypeNo = (unsigned)Record[Slot++];
  253. ResVal = getFnValueByID(ValNo, getTypeByID(TypeNo));
  254. return ResVal == nullptr;
  255. }
  256. /// Read a value out of the specified record from slot 'Slot'. Increment Slot
  257. /// past the number of slots used by the value in the record. Return true if
  258. /// there is an error.
  259. bool popValue(SmallVectorImpl<uint64_t> &Record, unsigned &Slot,
  260. unsigned InstNum, Type *Ty, Value *&ResVal) {
  261. if (getValue(Record, Slot, InstNum, Ty, ResVal))
  262. return true;
  263. // All values currently take a single record slot.
  264. ++Slot;
  265. return false;
  266. }
  267. /// Like popValue, but does not increment the Slot number.
  268. bool getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  269. unsigned InstNum, Type *Ty, Value *&ResVal) {
  270. ResVal = getValue(Record, Slot, InstNum, Ty);
  271. return ResVal == nullptr;
  272. }
  273. /// Version of getValue that returns ResVal directly, or 0 if there is an
  274. /// error.
  275. Value *getValue(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  276. unsigned InstNum, Type *Ty) {
  277. if (Slot == Record.size()) return nullptr;
  278. unsigned ValNo = (unsigned)Record[Slot];
  279. // Adjust the ValNo, if it was encoded relative to the InstNum.
  280. if (UseRelativeIDs)
  281. ValNo = InstNum - ValNo;
  282. return getFnValueByID(ValNo, Ty);
  283. }
  284. /// Like getValue, but decodes signed VBRs.
  285. Value *getValueSigned(SmallVectorImpl<uint64_t> &Record, unsigned Slot,
  286. unsigned InstNum, Type *Ty) {
  287. if (Slot == Record.size()) return nullptr;
  288. unsigned ValNo = (unsigned)decodeSignRotatedValue(Record[Slot]);
  289. // Adjust the ValNo, if it was encoded relative to the InstNum.
  290. if (UseRelativeIDs)
  291. ValNo = InstNum - ValNo;
  292. return getFnValueByID(ValNo, Ty);
  293. }
  294. /// Converts alignment exponent (i.e. power of two (or zero)) to the
  295. /// corresponding alignment to use. If alignment is too large, returns
  296. /// a corresponding error code.
  297. std::error_code parseAlignmentValue(uint64_t Exponent, unsigned &Alignment);
  298. std::error_code parseAttrKind(uint64_t Code, Attribute::AttrKind *Kind);
  299. std::error_code parseModule(bool Resume, bool ShouldLazyLoadMetadata = false);
  300. std::error_code parseAttributeBlock();
  301. std::error_code parseAttributeGroupBlock();
  302. std::error_code parseTypeTable();
  303. std::error_code parseTypeTableBody();
  304. std::error_code parseValueSymbolTable();
  305. std::error_code parseConstants();
  306. std::error_code rememberAndSkipFunctionBody();
  307. /// Save the positions of the Metadata blocks and skip parsing the blocks.
  308. std::error_code rememberAndSkipMetadata();
  309. std::error_code parseFunctionBody(Function *F);
  310. std::error_code globalCleanup();
  311. std::error_code resolveGlobalAndAliasInits();
  312. std::error_code parseMetadata();
  313. std::error_code parseMetadataAttachment(Function &F);
  314. ErrorOr<std::string> parseModuleTriple();
  315. std::error_code parseUseLists();
  316. std::error_code initStream(std::unique_ptr<DataStreamer> Streamer);
  317. std::error_code initStreamFromBuffer();
  318. std::error_code initLazyStream(std::unique_ptr<DataStreamer> Streamer);
  319. std::error_code findFunctionInStream(
  320. Function *F,
  321. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator);
  322. };
  323. } // namespace
  324. BitcodeDiagnosticInfo::BitcodeDiagnosticInfo(std::error_code EC,
  325. DiagnosticSeverity Severity,
  326. const Twine &Msg)
  327. : DiagnosticInfo(DK_Bitcode, Severity), Msg(Msg), EC(EC) {}
  328. void BitcodeDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
  329. static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
  330. std::error_code EC, const Twine &Message) {
  331. BitcodeDiagnosticInfo DI(EC, DS_Error, Message);
  332. DiagnosticHandler(DI);
  333. return EC;
  334. }
  335. static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
  336. std::error_code EC) {
  337. return error(DiagnosticHandler, EC, EC.message());
  338. }
  339. static std::error_code error(DiagnosticHandlerFunction DiagnosticHandler,
  340. const Twine &Message) {
  341. return error(DiagnosticHandler,
  342. make_error_code(BitcodeError::CorruptedBitcode), Message);
  343. }
  344. std::error_code BitcodeReader::error(BitcodeError E, const Twine &Message) {
  345. return ::error(DiagnosticHandler, make_error_code(E), Message);
  346. }
  347. std::error_code BitcodeReader::error(const Twine &Message) {
  348. return ::error(DiagnosticHandler,
  349. make_error_code(BitcodeError::CorruptedBitcode), Message);
  350. }
  351. std::error_code BitcodeReader::error(BitcodeError E) {
  352. return ::error(DiagnosticHandler, make_error_code(E));
  353. }
  354. static DiagnosticHandlerFunction getDiagHandler(DiagnosticHandlerFunction F,
  355. LLVMContext &C) {
  356. if (F)
  357. return F;
  358. return [&C](const DiagnosticInfo &DI) { C.diagnose(DI); };
  359. }
  360. // HLSL Change Starts
  361. static void ReportWarning(DiagnosticHandlerFunction F, const char *Msg) {
  362. BitcodeDiagnosticInfo BDI(std::error_code(), DiagnosticSeverity::DS_Warning,
  363. Msg);
  364. F(BDI);
  365. }
  366. // HLSL Change Ends
  367. BitcodeReader::BitcodeReader(MemoryBuffer *Buffer, LLVMContext &Context,
  368. DiagnosticHandlerFunction DiagnosticHandler)
  369. : Context(Context),
  370. DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
  371. Buffer(Buffer), ValueList(Context), MDValueList(Context) {}
  372. BitcodeReader::BitcodeReader(LLVMContext &Context,
  373. DiagnosticHandlerFunction DiagnosticHandler)
  374. : Context(Context),
  375. DiagnosticHandler(getDiagHandler(DiagnosticHandler, Context)),
  376. Buffer(nullptr), ValueList(Context), MDValueList(Context) {}
  377. std::error_code BitcodeReader::materializeForwardReferencedFunctions() {
  378. if (WillMaterializeAllForwardRefs)
  379. return std::error_code();
  380. // Prevent recursion.
  381. WillMaterializeAllForwardRefs = true;
  382. while (!BasicBlockFwdRefQueue.empty()) {
  383. Function *F = BasicBlockFwdRefQueue.front();
  384. BasicBlockFwdRefQueue.pop_front();
  385. assert(F && "Expected valid function");
  386. if (!BasicBlockFwdRefs.count(F))
  387. // Already materialized.
  388. continue;
  389. // Check for a function that isn't materializable to prevent an infinite
  390. // loop. When parsing a blockaddress stored in a global variable, there
  391. // isn't a trivial way to check if a function will have a body without a
  392. // linear search through FunctionsWithBodies, so just check it here.
  393. if (!F->isMaterializable())
  394. return error("Never resolved function from blockaddress");
  395. // Try to materialize F.
  396. if (std::error_code EC = materialize(F))
  397. return EC;
  398. }
  399. assert(BasicBlockFwdRefs.empty() && "Function missing from queue");
  400. // Reset state.
  401. WillMaterializeAllForwardRefs = false;
  402. return std::error_code();
  403. }
  404. void BitcodeReader::freeState() {
  405. Buffer = nullptr;
  406. std::vector<Type*>().swap(TypeList);
  407. ValueList.clear();
  408. MDValueList.clear();
  409. std::vector<Comdat *>().swap(ComdatList);
  410. std::vector<AttributeSet>().swap(MAttributes);
  411. std::vector<BasicBlock*>().swap(FunctionBBs);
  412. std::vector<Function*>().swap(FunctionsWithBodies);
  413. DeferredFunctionInfo.clear();
  414. DeferredMetadataInfo.clear();
  415. MDKindMap.clear();
  416. assert(BasicBlockFwdRefs.empty() && "Unresolved blockaddress fwd references");
  417. BasicBlockFwdRefQueue.clear();
  418. }
  419. //===----------------------------------------------------------------------===//
  420. // Helper functions to implement forward reference resolution, etc.
  421. //===----------------------------------------------------------------------===//
  422. /// Convert a string from a record into an std::string, return true on failure.
  423. template <typename StrTy>
  424. static bool convertToString(ArrayRef<uint64_t> Record, unsigned Idx,
  425. StrTy &Result) {
  426. if (Idx > Record.size())
  427. return true;
  428. for (unsigned i = Idx, e = Record.size(); i != e; ++i)
  429. Result += (char)Record[i];
  430. return false;
  431. }
  432. static bool hasImplicitComdat(size_t Val) {
  433. switch (Val) {
  434. default:
  435. return false;
  436. case 1: // Old WeakAnyLinkage
  437. case 4: // Old LinkOnceAnyLinkage
  438. case 10: // Old WeakODRLinkage
  439. case 11: // Old LinkOnceODRLinkage
  440. return true;
  441. }
  442. }
  443. static GlobalValue::LinkageTypes getDecodedLinkage(unsigned Val) {
  444. switch (Val) {
  445. default: // Map unknown/new linkages to external
  446. case 0:
  447. return GlobalValue::ExternalLinkage;
  448. case 2:
  449. return GlobalValue::AppendingLinkage;
  450. case 3:
  451. return GlobalValue::InternalLinkage;
  452. case 5:
  453. return GlobalValue::ExternalLinkage; // Obsolete DLLImportLinkage
  454. case 6:
  455. return GlobalValue::ExternalLinkage; // Obsolete DLLExportLinkage
  456. case 7:
  457. return GlobalValue::ExternalWeakLinkage;
  458. case 8:
  459. return GlobalValue::CommonLinkage;
  460. case 9:
  461. return GlobalValue::PrivateLinkage;
  462. case 12:
  463. return GlobalValue::AvailableExternallyLinkage;
  464. case 13:
  465. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateLinkage
  466. case 14:
  467. return GlobalValue::PrivateLinkage; // Obsolete LinkerPrivateWeakLinkage
  468. case 15:
  469. return GlobalValue::ExternalLinkage; // Obsolete LinkOnceODRAutoHideLinkage
  470. case 1: // Old value with implicit comdat.
  471. case 16:
  472. return GlobalValue::WeakAnyLinkage;
  473. case 10: // Old value with implicit comdat.
  474. case 17:
  475. return GlobalValue::WeakODRLinkage;
  476. case 4: // Old value with implicit comdat.
  477. case 18:
  478. return GlobalValue::LinkOnceAnyLinkage;
  479. case 11: // Old value with implicit comdat.
  480. case 19:
  481. return GlobalValue::LinkOnceODRLinkage;
  482. }
  483. }
  484. static GlobalValue::VisibilityTypes getDecodedVisibility(unsigned Val) {
  485. switch (Val) {
  486. default: // Map unknown visibilities to default.
  487. case 0: return GlobalValue::DefaultVisibility;
  488. case 1: return GlobalValue::HiddenVisibility;
  489. case 2: return GlobalValue::ProtectedVisibility;
  490. }
  491. }
  492. static GlobalValue::DLLStorageClassTypes
  493. getDecodedDLLStorageClass(unsigned Val) {
  494. switch (Val) {
  495. default: // Map unknown values to default.
  496. case 0: return GlobalValue::DefaultStorageClass;
  497. case 1: return GlobalValue::DLLImportStorageClass;
  498. case 2: return GlobalValue::DLLExportStorageClass;
  499. }
  500. }
  501. static GlobalVariable::ThreadLocalMode getDecodedThreadLocalMode(unsigned Val) {
  502. switch (Val) {
  503. case 0: return GlobalVariable::NotThreadLocal;
  504. default: // Map unknown non-zero value to general dynamic.
  505. case 1: return GlobalVariable::GeneralDynamicTLSModel;
  506. case 2: return GlobalVariable::LocalDynamicTLSModel;
  507. case 3: return GlobalVariable::InitialExecTLSModel;
  508. case 4: return GlobalVariable::LocalExecTLSModel;
  509. }
  510. }
  511. static int getDecodedCastOpcode(unsigned Val) {
  512. switch (Val) {
  513. default: return -1;
  514. case bitc::CAST_TRUNC : return Instruction::Trunc;
  515. case bitc::CAST_ZEXT : return Instruction::ZExt;
  516. case bitc::CAST_SEXT : return Instruction::SExt;
  517. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  518. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  519. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  520. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  521. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  522. case bitc::CAST_FPEXT : return Instruction::FPExt;
  523. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  524. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  525. case bitc::CAST_BITCAST : return Instruction::BitCast;
  526. case bitc::CAST_ADDRSPACECAST: return Instruction::AddrSpaceCast;
  527. }
  528. }
  529. static int getDecodedBinaryOpcode(unsigned Val, Type *Ty) {
  530. bool IsFP = Ty->isFPOrFPVectorTy();
  531. // BinOps are only valid for int/fp or vector of int/fp types
  532. if (!IsFP && !Ty->isIntOrIntVectorTy())
  533. return -1;
  534. switch (Val) {
  535. default:
  536. return -1;
  537. case bitc::BINOP_ADD:
  538. return IsFP ? Instruction::FAdd : Instruction::Add;
  539. case bitc::BINOP_SUB:
  540. return IsFP ? Instruction::FSub : Instruction::Sub;
  541. case bitc::BINOP_MUL:
  542. return IsFP ? Instruction::FMul : Instruction::Mul;
  543. case bitc::BINOP_UDIV:
  544. return IsFP ? -1 : Instruction::UDiv;
  545. case bitc::BINOP_SDIV:
  546. return IsFP ? Instruction::FDiv : Instruction::SDiv;
  547. case bitc::BINOP_UREM:
  548. return IsFP ? -1 : Instruction::URem;
  549. case bitc::BINOP_SREM:
  550. return IsFP ? Instruction::FRem : Instruction::SRem;
  551. case bitc::BINOP_SHL:
  552. return IsFP ? -1 : Instruction::Shl;
  553. case bitc::BINOP_LSHR:
  554. return IsFP ? -1 : Instruction::LShr;
  555. case bitc::BINOP_ASHR:
  556. return IsFP ? -1 : Instruction::AShr;
  557. case bitc::BINOP_AND:
  558. return IsFP ? -1 : Instruction::And;
  559. case bitc::BINOP_OR:
  560. return IsFP ? -1 : Instruction::Or;
  561. case bitc::BINOP_XOR:
  562. return IsFP ? -1 : Instruction::Xor;
  563. }
  564. }
  565. static AtomicRMWInst::BinOp getDecodedRMWOperation(unsigned Val) {
  566. switch (Val) {
  567. default: return AtomicRMWInst::BAD_BINOP;
  568. case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
  569. case bitc::RMW_ADD: return AtomicRMWInst::Add;
  570. case bitc::RMW_SUB: return AtomicRMWInst::Sub;
  571. case bitc::RMW_AND: return AtomicRMWInst::And;
  572. case bitc::RMW_NAND: return AtomicRMWInst::Nand;
  573. case bitc::RMW_OR: return AtomicRMWInst::Or;
  574. case bitc::RMW_XOR: return AtomicRMWInst::Xor;
  575. case bitc::RMW_MAX: return AtomicRMWInst::Max;
  576. case bitc::RMW_MIN: return AtomicRMWInst::Min;
  577. case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
  578. case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
  579. }
  580. }
  581. static AtomicOrdering getDecodedOrdering(unsigned Val) {
  582. switch (Val) {
  583. case bitc::ORDERING_NOTATOMIC: return NotAtomic;
  584. case bitc::ORDERING_UNORDERED: return Unordered;
  585. case bitc::ORDERING_MONOTONIC: return Monotonic;
  586. case bitc::ORDERING_ACQUIRE: return Acquire;
  587. case bitc::ORDERING_RELEASE: return Release;
  588. case bitc::ORDERING_ACQREL: return AcquireRelease;
  589. default: // Map unknown orderings to sequentially-consistent.
  590. case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
  591. }
  592. }
  593. static SynchronizationScope getDecodedSynchScope(unsigned Val) {
  594. switch (Val) {
  595. case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
  596. default: // Map unknown scopes to cross-thread.
  597. case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
  598. }
  599. }
  600. static Comdat::SelectionKind getDecodedComdatSelectionKind(unsigned Val) {
  601. switch (Val) {
  602. default: // Map unknown selection kinds to any.
  603. case bitc::COMDAT_SELECTION_KIND_ANY:
  604. return Comdat::Any;
  605. case bitc::COMDAT_SELECTION_KIND_EXACT_MATCH:
  606. return Comdat::ExactMatch;
  607. case bitc::COMDAT_SELECTION_KIND_LARGEST:
  608. return Comdat::Largest;
  609. case bitc::COMDAT_SELECTION_KIND_NO_DUPLICATES:
  610. return Comdat::NoDuplicates;
  611. case bitc::COMDAT_SELECTION_KIND_SAME_SIZE:
  612. return Comdat::SameSize;
  613. }
  614. }
  615. static FastMathFlags getDecodedFastMathFlags(unsigned Val) {
  616. FastMathFlags FMF;
  617. if (0 != (Val & FastMathFlags::UnsafeAlgebra))
  618. FMF.setUnsafeAlgebra();
  619. if (0 != (Val & FastMathFlags::NoNaNs))
  620. FMF.setNoNaNs();
  621. if (0 != (Val & FastMathFlags::NoInfs))
  622. FMF.setNoInfs();
  623. if (0 != (Val & FastMathFlags::NoSignedZeros))
  624. FMF.setNoSignedZeros();
  625. if (0 != (Val & FastMathFlags::AllowReciprocal))
  626. FMF.setAllowReciprocal();
  627. return FMF;
  628. }
  629. static void upgradeDLLImportExportLinkage(llvm::GlobalValue *GV, unsigned Val) {
  630. switch (Val) {
  631. case 5: GV->setDLLStorageClass(GlobalValue::DLLImportStorageClass); break;
  632. case 6: GV->setDLLStorageClass(GlobalValue::DLLExportStorageClass); break;
  633. }
  634. }
  635. namespace llvm {
  636. namespace {
  637. /// \brief A class for maintaining the slot number definition
  638. /// as a placeholder for the actual definition for forward constants defs.
  639. class ConstantPlaceHolder : public ConstantExpr {
  640. void operator=(const ConstantPlaceHolder &) = delete;
  641. public:
  642. // allocate space for exactly one operand
  643. void *operator new(size_t s) { return User::operator new(s, 1); }
  644. explicit ConstantPlaceHolder(Type *Ty, LLVMContext &Context)
  645. : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
  646. Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
  647. }
  648. /// \brief Methods to support type inquiry through isa, cast, and dyn_cast.
  649. static bool classof(const Value *V) {
  650. return isa<ConstantExpr>(V) &&
  651. cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
  652. }
  653. /// Provide fast operand accessors
  654. DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
  655. };
  656. }
  657. // FIXME: can we inherit this from ConstantExpr?
  658. template <>
  659. struct OperandTraits<ConstantPlaceHolder> :
  660. public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
  661. };
  662. DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
  663. }
  664. void BitcodeReaderValueList::assignValue(Value *V, unsigned Idx) {
  665. if (Idx == size()) {
  666. push_back(V);
  667. return;
  668. }
  669. if (Idx >= size())
  670. resize(Idx+1);
  671. WeakVH &OldV = ValuePtrs[Idx];
  672. if (!OldV) {
  673. OldV = V;
  674. return;
  675. }
  676. // Handle constants and non-constants (e.g. instrs) differently for
  677. // efficiency.
  678. if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
  679. ResolveConstants.push_back(std::make_pair(PHC, Idx));
  680. OldV = V;
  681. } else {
  682. // If there was a forward reference to this value, replace it.
  683. Value *PrevVal = OldV;
  684. OldV->replaceAllUsesWith(V);
  685. delete PrevVal;
  686. }
  687. }
  688. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  689. Type *Ty) {
  690. if (Idx >= size())
  691. resize(Idx + 1);
  692. if (Value *V = ValuePtrs[Idx]) {
  693. if (Ty != V->getType())
  694. report_fatal_error("Type mismatch in constant table!");
  695. return cast<Constant>(V);
  696. }
  697. // Create and return a placeholder, which will later be RAUW'd.
  698. Constant *C = new ConstantPlaceHolder(Ty, Context);
  699. ValuePtrs[Idx] = C;
  700. return C;
  701. }
  702. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
  703. // Bail out for a clearly invalid value. This would make us call resize(0)
  704. if (Idx == UINT_MAX)
  705. return nullptr;
  706. if (Idx >= size())
  707. resize(Idx + 1);
  708. if (Value *V = ValuePtrs[Idx]) {
  709. // If the types don't match, it's invalid.
  710. if (Ty && Ty != V->getType())
  711. return nullptr;
  712. return V;
  713. }
  714. // No type specified, must be invalid reference.
  715. if (!Ty) return nullptr;
  716. // Create and return a placeholder, which will later be RAUW'd.
  717. Value *V = new Argument(Ty);
  718. ValuePtrs[Idx] = V;
  719. return V;
  720. }
  721. /// Once all constants are read, this method bulk resolves any forward
  722. /// references. The idea behind this is that we sometimes get constants (such
  723. /// as large arrays) which reference *many* forward ref constants. Replacing
  724. /// each of these causes a lot of thrashing when building/reuniquing the
  725. /// constant. Instead of doing this, we look at all the uses and rewrite all
  726. /// the place holders at once for any constant that uses a placeholder.
  727. void BitcodeReaderValueList::resolveConstantForwardRefs() {
  728. // Sort the values by-pointer so that they are efficient to look up with a
  729. // binary search.
  730. std::sort(ResolveConstants.begin(), ResolveConstants.end());
  731. SmallVector<Constant*, 64> NewOps;
  732. while (!ResolveConstants.empty()) {
  733. Value *RealVal = operator[](ResolveConstants.back().second);
  734. Constant *Placeholder = ResolveConstants.back().first;
  735. ResolveConstants.pop_back();
  736. // Loop over all users of the placeholder, updating them to reference the
  737. // new value. If they reference more than one placeholder, update them all
  738. // at once.
  739. while (!Placeholder->use_empty()) {
  740. auto UI = Placeholder->user_begin();
  741. User *U = *UI;
  742. // If the using object isn't uniqued, just update the operands. This
  743. // handles instructions and initializers for global variables.
  744. if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
  745. UI.getUse().set(RealVal);
  746. continue;
  747. }
  748. // Otherwise, we have a constant that uses the placeholder. Replace that
  749. // constant with a new constant that has *all* placeholder uses updated.
  750. Constant *UserC = cast<Constant>(U);
  751. for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
  752. I != E; ++I) {
  753. Value *NewOp;
  754. if (!isa<ConstantPlaceHolder>(*I)) {
  755. // Not a placeholder reference.
  756. NewOp = *I;
  757. } else if (*I == Placeholder) {
  758. // Common case is that it just references this one placeholder.
  759. NewOp = RealVal;
  760. } else {
  761. // Otherwise, look up the placeholder in ResolveConstants.
  762. ResolveConstantsTy::iterator It =
  763. std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
  764. std::pair<Constant*, unsigned>(cast<Constant>(*I),
  765. 0));
  766. assert(It != ResolveConstants.end() && It->first == *I);
  767. NewOp = operator[](It->second);
  768. }
  769. NewOps.push_back(cast<Constant>(NewOp));
  770. }
  771. // Make the new constant.
  772. Constant *NewC;
  773. if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
  774. NewC = ConstantArray::get(UserCA->getType(), NewOps);
  775. } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
  776. NewC = ConstantStruct::get(UserCS->getType(), NewOps);
  777. } else if (isa<ConstantVector>(UserC)) {
  778. NewC = ConstantVector::get(NewOps);
  779. } else {
  780. assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
  781. NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
  782. }
  783. UserC->replaceAllUsesWith(NewC);
  784. UserC->destroyConstant();
  785. NewOps.clear();
  786. }
  787. // Update all ValueHandles, they should be the only users at this point.
  788. Placeholder->replaceAllUsesWith(RealVal);
  789. delete Placeholder;
  790. }
  791. }
  792. void BitcodeReaderMDValueList::assignValue(Metadata *MD, unsigned Idx) {
  793. if (Idx == size()) {
  794. push_back(MD);
  795. return;
  796. }
  797. if (Idx >= size())
  798. resize(Idx+1);
  799. TrackingMDRef &OldMD = MDValuePtrs[Idx];
  800. if (!OldMD) {
  801. OldMD.reset(MD);
  802. return;
  803. }
  804. // If there was a forward reference to this value, replace it.
  805. TempMDTuple PrevMD(cast<MDTuple>(OldMD.get()));
  806. PrevMD->replaceAllUsesWith(MD);
  807. --NumFwdRefs;
  808. }
  809. Metadata *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
  810. if (Idx >= size())
  811. resize(Idx + 1);
  812. if (Metadata *MD = MDValuePtrs[Idx])
  813. return MD;
  814. // Track forward refs to be resolved later.
  815. if (AnyFwdRefs) {
  816. MinFwdRef = std::min(MinFwdRef, Idx);
  817. MaxFwdRef = std::max(MaxFwdRef, Idx);
  818. } else {
  819. AnyFwdRefs = true;
  820. MinFwdRef = MaxFwdRef = Idx;
  821. }
  822. ++NumFwdRefs;
  823. // Create and return a placeholder, which will later be RAUW'd.
  824. Metadata *MD = MDNode::getTemporary(Context, None).release();
  825. MDValuePtrs[Idx].reset(MD);
  826. return MD;
  827. }
  828. void BitcodeReaderMDValueList::tryToResolveCycles() {
  829. if (!AnyFwdRefs)
  830. // Nothing to do.
  831. return;
  832. if (NumFwdRefs)
  833. // Still forward references... can't resolve cycles.
  834. return;
  835. // Resolve any cycles.
  836. for (unsigned I = MinFwdRef, E = MaxFwdRef + 1; I != E; ++I) {
  837. auto &MD = MDValuePtrs[I];
  838. auto *N = dyn_cast_or_null<MDNode>(MD);
  839. if (!N)
  840. continue;
  841. assert(!N->isTemporary() && "Unexpected forward reference");
  842. N->resolveCycles();
  843. }
  844. // Make sure we return early again until there's another forward ref.
  845. AnyFwdRefs = false;
  846. }
  847. Type *BitcodeReader::getTypeByID(unsigned ID) {
  848. // The type table size is always specified correctly.
  849. if (ID >= TypeList.size())
  850. return nullptr;
  851. if (Type *Ty = TypeList[ID])
  852. return Ty;
  853. // If we have a forward reference, the only possible case is when it is to a
  854. // named struct. Just create a placeholder for now.
  855. return TypeList[ID] = createIdentifiedStructType(Context);
  856. }
  857. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context,
  858. StringRef Name) {
  859. auto *Ret = StructType::create(Context, Name);
  860. IdentifiedStructTypes.push_back(Ret);
  861. return Ret;
  862. }
  863. StructType *BitcodeReader::createIdentifiedStructType(LLVMContext &Context) {
  864. auto *Ret = StructType::create(Context);
  865. IdentifiedStructTypes.push_back(Ret);
  866. return Ret;
  867. }
  868. //===----------------------------------------------------------------------===//
  869. // Functions for parsing blocks from the bitcode file
  870. //===----------------------------------------------------------------------===//
  871. /// \brief This fills an AttrBuilder object with the LLVM attributes that have
  872. /// been decoded from the given integer. This function must stay in sync with
  873. /// 'encodeLLVMAttributesForBitcode'.
  874. static void decodeLLVMAttributesForBitcode(AttrBuilder &B,
  875. uint64_t EncodedAttrs) {
  876. // FIXME: Remove in 4.0.
  877. // The alignment is stored as a 16-bit raw value from bits 31--16. We shift
  878. // the bits above 31 down by 11 bits.
  879. unsigned Alignment = (EncodedAttrs & (0xffffULL << 16)) >> 16;
  880. assert((!Alignment || isPowerOf2_32(Alignment)) &&
  881. "Alignment must be a power of two.");
  882. if (Alignment)
  883. B.addAlignmentAttr(Alignment);
  884. B.addRawValue(((EncodedAttrs & (0xfffffULL << 32)) >> 11) |
  885. (EncodedAttrs & 0xffff));
  886. }
  887. std::error_code BitcodeReader::parseAttributeBlock() {
  888. if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
  889. return error("Invalid record");
  890. if (!MAttributes.empty())
  891. return error("Invalid multiple blocks");
  892. SmallVector<uint64_t, 64> Record;
  893. SmallVector<AttributeSet, 8> Attrs;
  894. // Read all the records.
  895. while (1) {
  896. // HLSL Change Starts - count skipped blocks
  897. unsigned skipCount = 0;
  898. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  899. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  900. // HLSL Change End
  901. switch (Entry.Kind) {
  902. case BitstreamEntry::SubBlock: // Handled for us already.
  903. case BitstreamEntry::Error:
  904. return error("Malformed block");
  905. case BitstreamEntry::EndBlock:
  906. return std::error_code();
  907. case BitstreamEntry::Record:
  908. // The interesting case.
  909. break;
  910. }
  911. // Read a record.
  912. Record.clear();
  913. switch (Stream.readRecord(Entry.ID, Record)) {
  914. default: // Default behavior: ignore.
  915. break;
  916. case bitc::PARAMATTR_CODE_ENTRY_OLD: { // ENTRY: [paramidx0, attr0, ...]
  917. // FIXME: Remove in 4.0.
  918. if (Record.size() & 1)
  919. return error("Invalid record");
  920. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  921. AttrBuilder B;
  922. decodeLLVMAttributesForBitcode(B, Record[i+1]);
  923. Attrs.push_back(AttributeSet::get(Context, Record[i], B));
  924. }
  925. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  926. Attrs.clear();
  927. break;
  928. }
  929. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [attrgrp0, attrgrp1, ...]
  930. for (unsigned i = 0, e = Record.size(); i != e; ++i)
  931. Attrs.push_back(MAttributeGroups[Record[i]]);
  932. MAttributes.push_back(AttributeSet::get(Context, Attrs));
  933. Attrs.clear();
  934. break;
  935. }
  936. }
  937. }
  938. }
  939. // Returns Attribute::None on unrecognized codes.
  940. static Attribute::AttrKind getAttrFromCode(uint64_t Code) {
  941. switch (Code) {
  942. default:
  943. return Attribute::None;
  944. case bitc::ATTR_KIND_ALIGNMENT:
  945. return Attribute::Alignment;
  946. case bitc::ATTR_KIND_ALWAYS_INLINE:
  947. return Attribute::AlwaysInline;
  948. case bitc::ATTR_KIND_ARGMEMONLY:
  949. return Attribute::ArgMemOnly;
  950. case bitc::ATTR_KIND_BUILTIN:
  951. return Attribute::Builtin;
  952. case bitc::ATTR_KIND_BY_VAL:
  953. return Attribute::ByVal;
  954. case bitc::ATTR_KIND_IN_ALLOCA:
  955. return Attribute::InAlloca;
  956. case bitc::ATTR_KIND_COLD:
  957. return Attribute::Cold;
  958. case bitc::ATTR_KIND_CONVERGENT:
  959. return Attribute::Convergent;
  960. case bitc::ATTR_KIND_INLINE_HINT:
  961. return Attribute::InlineHint;
  962. case bitc::ATTR_KIND_IN_REG:
  963. return Attribute::InReg;
  964. case bitc::ATTR_KIND_JUMP_TABLE:
  965. return Attribute::JumpTable;
  966. case bitc::ATTR_KIND_MIN_SIZE:
  967. return Attribute::MinSize;
  968. case bitc::ATTR_KIND_NAKED:
  969. return Attribute::Naked;
  970. case bitc::ATTR_KIND_NEST:
  971. return Attribute::Nest;
  972. case bitc::ATTR_KIND_NO_ALIAS:
  973. return Attribute::NoAlias;
  974. case bitc::ATTR_KIND_NO_BUILTIN:
  975. return Attribute::NoBuiltin;
  976. case bitc::ATTR_KIND_NO_CAPTURE:
  977. return Attribute::NoCapture;
  978. case bitc::ATTR_KIND_NO_DUPLICATE:
  979. return Attribute::NoDuplicate;
  980. case bitc::ATTR_KIND_NO_IMPLICIT_FLOAT:
  981. return Attribute::NoImplicitFloat;
  982. case bitc::ATTR_KIND_NO_INLINE:
  983. return Attribute::NoInline;
  984. case bitc::ATTR_KIND_NON_LAZY_BIND:
  985. return Attribute::NonLazyBind;
  986. case bitc::ATTR_KIND_NON_NULL:
  987. return Attribute::NonNull;
  988. case bitc::ATTR_KIND_DEREFERENCEABLE:
  989. return Attribute::Dereferenceable;
  990. case bitc::ATTR_KIND_DEREFERENCEABLE_OR_NULL:
  991. return Attribute::DereferenceableOrNull;
  992. case bitc::ATTR_KIND_NO_RED_ZONE:
  993. return Attribute::NoRedZone;
  994. case bitc::ATTR_KIND_NO_RETURN:
  995. return Attribute::NoReturn;
  996. case bitc::ATTR_KIND_NO_UNWIND:
  997. return Attribute::NoUnwind;
  998. case bitc::ATTR_KIND_OPTIMIZE_FOR_SIZE:
  999. return Attribute::OptimizeForSize;
  1000. case bitc::ATTR_KIND_OPTIMIZE_NONE:
  1001. return Attribute::OptimizeNone;
  1002. case bitc::ATTR_KIND_READ_NONE:
  1003. return Attribute::ReadNone;
  1004. case bitc::ATTR_KIND_READ_ONLY:
  1005. return Attribute::ReadOnly;
  1006. case bitc::ATTR_KIND_RETURNED:
  1007. return Attribute::Returned;
  1008. case bitc::ATTR_KIND_RETURNS_TWICE:
  1009. return Attribute::ReturnsTwice;
  1010. case bitc::ATTR_KIND_S_EXT:
  1011. return Attribute::SExt;
  1012. case bitc::ATTR_KIND_STACK_ALIGNMENT:
  1013. return Attribute::StackAlignment;
  1014. case bitc::ATTR_KIND_STACK_PROTECT:
  1015. return Attribute::StackProtect;
  1016. case bitc::ATTR_KIND_STACK_PROTECT_REQ:
  1017. return Attribute::StackProtectReq;
  1018. case bitc::ATTR_KIND_STACK_PROTECT_STRONG:
  1019. return Attribute::StackProtectStrong;
  1020. case bitc::ATTR_KIND_SAFESTACK:
  1021. return Attribute::SafeStack;
  1022. case bitc::ATTR_KIND_STRUCT_RET:
  1023. return Attribute::StructRet;
  1024. case bitc::ATTR_KIND_SANITIZE_ADDRESS:
  1025. return Attribute::SanitizeAddress;
  1026. case bitc::ATTR_KIND_SANITIZE_THREAD:
  1027. return Attribute::SanitizeThread;
  1028. case bitc::ATTR_KIND_SANITIZE_MEMORY:
  1029. return Attribute::SanitizeMemory;
  1030. case bitc::ATTR_KIND_UW_TABLE:
  1031. return Attribute::UWTable;
  1032. case bitc::ATTR_KIND_Z_EXT:
  1033. return Attribute::ZExt;
  1034. }
  1035. }
  1036. std::error_code BitcodeReader::parseAlignmentValue(uint64_t Exponent,
  1037. unsigned &Alignment) {
  1038. // Note: Alignment in bitcode files is incremented by 1, so that zero
  1039. // can be used for default alignment.
  1040. if (Exponent > Value::MaxAlignmentExponent + 1)
  1041. return error("Invalid alignment value");
  1042. Alignment = (1 << static_cast<unsigned>(Exponent)) >> 1;
  1043. return std::error_code();
  1044. }
  1045. std::error_code BitcodeReader::parseAttrKind(uint64_t Code,
  1046. Attribute::AttrKind *Kind) {
  1047. *Kind = getAttrFromCode(Code);
  1048. if (*Kind == Attribute::None)
  1049. return error(BitcodeError::CorruptedBitcode,
  1050. "Unknown attribute kind (" + Twine(Code) + ")");
  1051. return std::error_code();
  1052. }
  1053. std::error_code BitcodeReader::parseAttributeGroupBlock() {
  1054. if (Stream.EnterSubBlock(bitc::PARAMATTR_GROUP_BLOCK_ID))
  1055. return error("Invalid record");
  1056. if (!MAttributeGroups.empty())
  1057. return error("Invalid multiple blocks");
  1058. SmallVector<uint64_t, 64> Record;
  1059. // Read all the records.
  1060. while (1) {
  1061. // HLSL Change Starts - count skipped blocks
  1062. unsigned skipCount = 0;
  1063. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1064. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1065. // HLSL Change End
  1066. switch (Entry.Kind) {
  1067. case BitstreamEntry::SubBlock: // Handled for us already.
  1068. case BitstreamEntry::Error:
  1069. return error("Malformed block");
  1070. case BitstreamEntry::EndBlock:
  1071. return std::error_code();
  1072. case BitstreamEntry::Record:
  1073. // The interesting case.
  1074. break;
  1075. }
  1076. // Read a record.
  1077. Record.clear();
  1078. switch (Stream.readRecord(Entry.ID, Record)) {
  1079. default: // Default behavior: ignore.
  1080. break;
  1081. case bitc::PARAMATTR_GRP_CODE_ENTRY: { // ENTRY: [grpid, idx, a0, a1, ...]
  1082. if (Record.size() < 3)
  1083. return error("Invalid record");
  1084. uint64_t GrpID = Record[0];
  1085. uint64_t Idx = Record[1]; // Index of the object this attribute refers to.
  1086. AttrBuilder B;
  1087. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1088. if (Record[i] == 0) { // Enum attribute
  1089. Attribute::AttrKind Kind;
  1090. if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
  1091. return EC;
  1092. B.addAttribute(Kind);
  1093. } else if (Record[i] == 1) { // Integer attribute
  1094. Attribute::AttrKind Kind;
  1095. if (std::error_code EC = parseAttrKind(Record[++i], &Kind))
  1096. return EC;
  1097. if (Kind == Attribute::Alignment)
  1098. B.addAlignmentAttr(Record[++i]);
  1099. else if (Kind == Attribute::StackAlignment)
  1100. B.addStackAlignmentAttr(Record[++i]);
  1101. else if (Kind == Attribute::Dereferenceable)
  1102. B.addDereferenceableAttr(Record[++i]);
  1103. else if (Kind == Attribute::DereferenceableOrNull)
  1104. B.addDereferenceableOrNullAttr(Record[++i]);
  1105. } else { // String attribute
  1106. assert((Record[i] == 3 || Record[i] == 4) &&
  1107. "Invalid attribute group entry");
  1108. bool HasValue = (Record[i++] == 4);
  1109. SmallString<64> KindStr;
  1110. SmallString<64> ValStr;
  1111. while (Record[i] != 0 && i != e)
  1112. KindStr += Record[i++];
  1113. assert(Record[i] == 0 && "Kind string not null terminated");
  1114. if (HasValue) {
  1115. // Has a value associated with it.
  1116. ++i; // Skip the '0' that terminates the "kind" string.
  1117. while (Record[i] != 0 && i != e)
  1118. ValStr += Record[i++];
  1119. assert(Record[i] == 0 && "Value string not null terminated");
  1120. }
  1121. B.addAttribute(KindStr.str(), ValStr.str());
  1122. }
  1123. }
  1124. MAttributeGroups[GrpID] = AttributeSet::get(Context, Idx, B);
  1125. break;
  1126. }
  1127. }
  1128. }
  1129. }
  1130. std::error_code BitcodeReader::parseTypeTable() {
  1131. if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
  1132. return error("Invalid record");
  1133. return parseTypeTableBody();
  1134. }
  1135. std::error_code BitcodeReader::parseTypeTableBody() {
  1136. if (!TypeList.empty())
  1137. return error("Invalid multiple blocks");
  1138. SmallVector<uint64_t, 64> Record;
  1139. unsigned NumRecords = 0;
  1140. SmallString<64> TypeName;
  1141. // Read all the records for this type table.
  1142. while (1) {
  1143. // HLSL Change Starts - count skipped blocks
  1144. unsigned skipCount = 0;
  1145. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1146. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1147. // HLSL Change End
  1148. switch (Entry.Kind) {
  1149. case BitstreamEntry::SubBlock: // Handled for us already.
  1150. case BitstreamEntry::Error:
  1151. return error("Malformed block");
  1152. case BitstreamEntry::EndBlock:
  1153. if (NumRecords != TypeList.size())
  1154. return error("Malformed block");
  1155. return std::error_code();
  1156. case BitstreamEntry::Record:
  1157. // The interesting case.
  1158. break;
  1159. }
  1160. // Read a record.
  1161. Record.clear();
  1162. Type *ResultTy = nullptr;
  1163. switch (Stream.readRecord(Entry.ID, Record)) {
  1164. default:
  1165. return error("Invalid value");
  1166. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  1167. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  1168. // type list. This allows us to reserve space.
  1169. if (Record.size() < 1)
  1170. return error("Invalid record");
  1171. TypeList.resize(Record[0]);
  1172. continue;
  1173. case bitc::TYPE_CODE_VOID: // VOID
  1174. ResultTy = Type::getVoidTy(Context);
  1175. break;
  1176. case bitc::TYPE_CODE_HALF: // HALF
  1177. ResultTy = Type::getHalfTy(Context);
  1178. break;
  1179. case bitc::TYPE_CODE_FLOAT: // FLOAT
  1180. ResultTy = Type::getFloatTy(Context);
  1181. break;
  1182. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  1183. ResultTy = Type::getDoubleTy(Context);
  1184. break;
  1185. case bitc::TYPE_CODE_X86_FP80: // X86_FP80
  1186. ResultTy = Type::getX86_FP80Ty(Context);
  1187. break;
  1188. case bitc::TYPE_CODE_FP128: // FP128
  1189. ResultTy = Type::getFP128Ty(Context);
  1190. break;
  1191. case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
  1192. ResultTy = Type::getPPC_FP128Ty(Context);
  1193. break;
  1194. case bitc::TYPE_CODE_LABEL: // LABEL
  1195. ResultTy = Type::getLabelTy(Context);
  1196. break;
  1197. case bitc::TYPE_CODE_METADATA: // METADATA
  1198. ResultTy = Type::getMetadataTy(Context);
  1199. break;
  1200. case bitc::TYPE_CODE_X86_MMX: // X86_MMX
  1201. ResultTy = Type::getX86_MMXTy(Context);
  1202. break;
  1203. case bitc::TYPE_CODE_INTEGER: { // INTEGER: [width]
  1204. if (Record.size() < 1)
  1205. return error("Invalid record");
  1206. uint64_t NumBits = Record[0];
  1207. if (NumBits < IntegerType::MIN_INT_BITS ||
  1208. NumBits > IntegerType::MAX_INT_BITS)
  1209. return error("Bitwidth for integer type out of range");
  1210. ResultTy = IntegerType::get(Context, NumBits);
  1211. break;
  1212. }
  1213. case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
  1214. // [pointee type, address space]
  1215. if (Record.size() < 1)
  1216. return error("Invalid record");
  1217. unsigned AddressSpace = 0;
  1218. if (Record.size() == 2)
  1219. AddressSpace = Record[1];
  1220. ResultTy = getTypeByID(Record[0]);
  1221. if (!ResultTy ||
  1222. !PointerType::isValidElementType(ResultTy))
  1223. return error("Invalid type");
  1224. ResultTy = PointerType::get(ResultTy, AddressSpace);
  1225. break;
  1226. }
  1227. case bitc::TYPE_CODE_FUNCTION_OLD: {
  1228. // FIXME: attrid is dead, remove it in LLVM 4.0
  1229. // FUNCTION: [vararg, attrid, retty, paramty x N]
  1230. if (Record.size() < 3)
  1231. return error("Invalid record");
  1232. SmallVector<Type*, 8> ArgTys;
  1233. for (unsigned i = 3, e = Record.size(); i != e; ++i) {
  1234. if (Type *T = getTypeByID(Record[i]))
  1235. ArgTys.push_back(T);
  1236. else
  1237. break;
  1238. }
  1239. ResultTy = getTypeByID(Record[2]);
  1240. if (!ResultTy || ArgTys.size() < Record.size()-3)
  1241. return error("Invalid type");
  1242. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1243. break;
  1244. }
  1245. case bitc::TYPE_CODE_FUNCTION: {
  1246. // FUNCTION: [vararg, retty, paramty x N]
  1247. if (Record.size() < 2)
  1248. return error("Invalid record");
  1249. SmallVector<Type*, 8> ArgTys;
  1250. for (unsigned i = 2, e = Record.size(); i != e; ++i) {
  1251. if (Type *T = getTypeByID(Record[i])) {
  1252. if (!FunctionType::isValidArgumentType(T))
  1253. return error("Invalid function argument type");
  1254. ArgTys.push_back(T);
  1255. }
  1256. else
  1257. break;
  1258. }
  1259. ResultTy = getTypeByID(Record[1]);
  1260. if (!ResultTy || ArgTys.size() < Record.size()-2)
  1261. return error("Invalid type");
  1262. ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
  1263. break;
  1264. }
  1265. case bitc::TYPE_CODE_STRUCT_ANON: { // STRUCT: [ispacked, eltty x N]
  1266. if (Record.size() < 1)
  1267. return error("Invalid record");
  1268. SmallVector<Type*, 8> EltTys;
  1269. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1270. if (Type *T = getTypeByID(Record[i]))
  1271. EltTys.push_back(T);
  1272. else
  1273. break;
  1274. }
  1275. if (EltTys.size() != Record.size()-1)
  1276. return error("Invalid type");
  1277. ResultTy = StructType::get(Context, EltTys, Record[0]);
  1278. break;
  1279. }
  1280. case bitc::TYPE_CODE_STRUCT_NAME: // STRUCT_NAME: [strchr x N]
  1281. if (convertToString(Record, 0, TypeName))
  1282. return error("Invalid record");
  1283. continue;
  1284. case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
  1285. if (Record.size() < 1)
  1286. return error("Invalid record");
  1287. if (NumRecords >= TypeList.size())
  1288. return error("Invalid TYPE table");
  1289. // Check to see if this was forward referenced, if so fill in the temp.
  1290. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1291. if (Res) {
  1292. Res->setName(TypeName);
  1293. TypeList[NumRecords] = nullptr;
  1294. } else // Otherwise, create a new struct.
  1295. Res = createIdentifiedStructType(Context, TypeName);
  1296. TypeName.clear();
  1297. SmallVector<Type*, 8> EltTys;
  1298. for (unsigned i = 1, e = Record.size(); i != e; ++i) {
  1299. if (Type *T = getTypeByID(Record[i]))
  1300. EltTys.push_back(T);
  1301. else
  1302. break;
  1303. }
  1304. if (EltTys.size() != Record.size()-1)
  1305. return error("Invalid record");
  1306. Res->setBody(EltTys, Record[0]);
  1307. ResultTy = Res;
  1308. break;
  1309. }
  1310. case bitc::TYPE_CODE_OPAQUE: { // OPAQUE: []
  1311. if (Record.size() != 1)
  1312. return error("Invalid record");
  1313. if (NumRecords >= TypeList.size())
  1314. return error("Invalid TYPE table");
  1315. // Check to see if this was forward referenced, if so fill in the temp.
  1316. StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
  1317. if (Res) {
  1318. Res->setName(TypeName);
  1319. TypeList[NumRecords] = nullptr;
  1320. } else // Otherwise, create a new struct with no body.
  1321. Res = createIdentifiedStructType(Context, TypeName);
  1322. TypeName.clear();
  1323. ResultTy = Res;
  1324. break;
  1325. }
  1326. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  1327. if (Record.size() < 2)
  1328. return error("Invalid record");
  1329. ResultTy = getTypeByID(Record[1]);
  1330. if (!ResultTy || !ArrayType::isValidElementType(ResultTy))
  1331. return error("Invalid type");
  1332. ResultTy = ArrayType::get(ResultTy, Record[0]);
  1333. break;
  1334. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  1335. if (Record.size() < 2)
  1336. return error("Invalid record");
  1337. if (Record[0] == 0)
  1338. return error("Invalid vector length");
  1339. ResultTy = getTypeByID(Record[1]);
  1340. if (!ResultTy || !StructType::isValidElementType(ResultTy))
  1341. return error("Invalid type");
  1342. ResultTy = VectorType::get(ResultTy, Record[0]);
  1343. break;
  1344. }
  1345. if (NumRecords >= TypeList.size())
  1346. return error("Invalid TYPE table");
  1347. if (TypeList[NumRecords])
  1348. return error(
  1349. "Invalid TYPE table: Only named structs can be forward referenced");
  1350. assert(ResultTy && "Didn't read a type?");
  1351. TypeList[NumRecords++] = ResultTy;
  1352. }
  1353. }
  1354. std::error_code BitcodeReader::parseValueSymbolTable() {
  1355. if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
  1356. return error("Invalid record");
  1357. SmallVector<uint64_t, 64> Record;
  1358. Triple TT(TheModule->getTargetTriple());
  1359. // Read all the records for this value table.
  1360. SmallString<128> ValueName;
  1361. while (1) {
  1362. // HLSL Change Starts - count skipped blocks
  1363. unsigned skipCount = 0;
  1364. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1365. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1366. // HLSL Change End
  1367. switch (Entry.Kind) {
  1368. case BitstreamEntry::SubBlock: // Handled for us already.
  1369. case BitstreamEntry::Error:
  1370. return error("Malformed block");
  1371. case BitstreamEntry::EndBlock:
  1372. return std::error_code();
  1373. case BitstreamEntry::Record:
  1374. // The interesting case.
  1375. break;
  1376. }
  1377. // Read a record.
  1378. Record.clear();
  1379. switch (Stream.readRecord(Entry.ID, Record)) {
  1380. default: // Default behavior: unknown type.
  1381. break;
  1382. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namechar x N]
  1383. if (convertToString(Record, 1, ValueName))
  1384. return error("Invalid record");
  1385. unsigned ValueID = Record[0];
  1386. if (ValueID >= ValueList.size() || !ValueList[ValueID])
  1387. return error("Invalid record");
  1388. Value *V = ValueList[ValueID];
  1389. V->setName(StringRef(ValueName.data(), ValueName.size()));
  1390. if (auto *GO = dyn_cast<GlobalObject>(V)) {
  1391. if (GO->getComdat() == reinterpret_cast<Comdat *>(1)) {
  1392. if (TT.isOSBinFormatMachO())
  1393. GO->setComdat(nullptr);
  1394. else
  1395. GO->setComdat(TheModule->getOrInsertComdat(V->getName()));
  1396. }
  1397. }
  1398. ValueName.clear();
  1399. break;
  1400. }
  1401. case bitc::VST_CODE_BBENTRY: {
  1402. if (convertToString(Record, 1, ValueName))
  1403. return error("Invalid record");
  1404. BasicBlock *BB = getBasicBlock(Record[0]);
  1405. if (!BB)
  1406. return error("Invalid record");
  1407. BB->setName(StringRef(ValueName.data(), ValueName.size()));
  1408. ValueName.clear();
  1409. break;
  1410. }
  1411. }
  1412. }
  1413. }
  1414. static int64_t unrotateSign(uint64_t U) { return U & 1 ? ~(U >> 1) : U >> 1; }
  1415. std::error_code BitcodeReader::parseMetadata() {
  1416. IsMetadataMaterialized = true;
  1417. unsigned NextMDValueNo = MDValueList.size();
  1418. if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
  1419. return error("Invalid record");
  1420. SmallVector<uint64_t, 64> Record;
  1421. auto getMD =
  1422. [&](unsigned ID) -> Metadata *{ return MDValueList.getValueFwdRef(ID); };
  1423. auto getMDOrNull = [&](unsigned ID) -> Metadata *{
  1424. if (ID)
  1425. return getMD(ID - 1);
  1426. return nullptr;
  1427. };
  1428. auto getMDString = [&](unsigned ID) -> MDString *{
  1429. // This requires that the ID is not really a forward reference. In
  1430. // particular, the MDString must already have been resolved.
  1431. return cast_or_null<MDString>(getMDOrNull(ID));
  1432. };
  1433. #define GET_OR_DISTINCT(CLASS, DISTINCT, ARGS) \
  1434. (DISTINCT ? CLASS::getDistinct ARGS : CLASS::get ARGS)
  1435. // Read all the records.
  1436. while (1) {
  1437. // HLSL Change Starts - count skipped blocks
  1438. unsigned skipCount = 0;
  1439. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1440. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1441. // HLSL Change End
  1442. switch (Entry.Kind) {
  1443. case BitstreamEntry::SubBlock: // Handled for us already.
  1444. case BitstreamEntry::Error:
  1445. return error("Malformed block");
  1446. case BitstreamEntry::EndBlock:
  1447. MDValueList.tryToResolveCycles();
  1448. return std::error_code();
  1449. case BitstreamEntry::Record:
  1450. // The interesting case.
  1451. break;
  1452. }
  1453. // Read a record.
  1454. Record.clear();
  1455. unsigned Code = Stream.readRecord(Entry.ID, Record);
  1456. bool IsDistinct = false;
  1457. switch (Code) {
  1458. default: // Default behavior: ignore.
  1459. break;
  1460. case bitc::METADATA_NAME: {
  1461. // Read name of the named metadata.
  1462. SmallString<8> Name(Record.begin(), Record.end());
  1463. Record.clear();
  1464. Code = Stream.ReadCode();
  1465. unsigned NextBitCode = Stream.readRecord(Code, Record);
  1466. if (NextBitCode != bitc::METADATA_NAMED_NODE)
  1467. return error("METADATA_NAME not followed by METADATA_NAMED_NODE");
  1468. // Read named metadata elements.
  1469. unsigned Size = Record.size();
  1470. NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
  1471. for (unsigned i = 0; i != Size; ++i) {
  1472. MDNode *MD = dyn_cast_or_null<MDNode>(MDValueList.getValueFwdRef(Record[i]));
  1473. if (!MD)
  1474. return error("Invalid record");
  1475. NMD->addOperand(MD);
  1476. }
  1477. break;
  1478. }
  1479. case bitc::METADATA_OLD_FN_NODE: {
  1480. // FIXME: Remove in 4.0.
  1481. // This is a LocalAsMetadata record, the only type of function-local
  1482. // metadata.
  1483. if (Record.size() % 2 == 1)
  1484. return error("Invalid record");
  1485. // If this isn't a LocalAsMetadata record, we're dropping it. This used
  1486. // to be legal, but there's no upgrade path.
  1487. auto dropRecord = [&] {
  1488. MDValueList.assignValue(MDNode::get(Context, None), NextMDValueNo++);
  1489. };
  1490. if (Record.size() != 2) {
  1491. dropRecord();
  1492. break;
  1493. }
  1494. Type *Ty = getTypeByID(Record[0]);
  1495. if (Ty->isMetadataTy() || Ty->isVoidTy()) {
  1496. dropRecord();
  1497. break;
  1498. }
  1499. MDValueList.assignValue(
  1500. LocalAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  1501. NextMDValueNo++);
  1502. break;
  1503. }
  1504. case bitc::METADATA_OLD_NODE: {
  1505. // FIXME: Remove in 4.0.
  1506. if (Record.size() % 2 == 1)
  1507. return error("Invalid record");
  1508. unsigned Size = Record.size();
  1509. SmallVector<Metadata *, 8> Elts;
  1510. for (unsigned i = 0; i != Size; i += 2) {
  1511. Type *Ty = getTypeByID(Record[i]);
  1512. if (!Ty)
  1513. return error("Invalid record");
  1514. if (Ty->isMetadataTy())
  1515. Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
  1516. else if (!Ty->isVoidTy()) {
  1517. auto *MD =
  1518. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[i + 1], Ty));
  1519. assert(isa<ConstantAsMetadata>(MD) &&
  1520. "Expected non-function-local metadata");
  1521. Elts.push_back(MD);
  1522. } else
  1523. Elts.push_back(nullptr);
  1524. }
  1525. MDValueList.assignValue(MDNode::get(Context, Elts), NextMDValueNo++);
  1526. break;
  1527. }
  1528. case bitc::METADATA_VALUE: {
  1529. if (Record.size() != 2)
  1530. return error("Invalid record");
  1531. Type *Ty = getTypeByID(Record[0]);
  1532. if (Ty->isMetadataTy() || Ty->isVoidTy())
  1533. return error("Invalid record");
  1534. MDValueList.assignValue(
  1535. ValueAsMetadata::get(ValueList.getValueFwdRef(Record[1], Ty)),
  1536. NextMDValueNo++);
  1537. break;
  1538. }
  1539. case bitc::METADATA_DISTINCT_NODE:
  1540. IsDistinct = true;
  1541. // fallthrough...
  1542. case bitc::METADATA_NODE: {
  1543. SmallVector<Metadata *, 8> Elts;
  1544. Elts.reserve(Record.size());
  1545. for (unsigned ID : Record)
  1546. Elts.push_back(ID ? MDValueList.getValueFwdRef(ID - 1) : nullptr);
  1547. MDValueList.assignValue(IsDistinct ? MDNode::getDistinct(Context, Elts)
  1548. : MDNode::get(Context, Elts),
  1549. NextMDValueNo++);
  1550. break;
  1551. }
  1552. case bitc::METADATA_LOCATION: {
  1553. if (Record.size() != 5)
  1554. return error("Invalid record");
  1555. unsigned Line = Record[1];
  1556. unsigned Column = Record[2];
  1557. MDNode *Scope = cast<MDNode>(MDValueList.getValueFwdRef(Record[3]));
  1558. Metadata *InlinedAt =
  1559. Record[4] ? MDValueList.getValueFwdRef(Record[4] - 1) : nullptr;
  1560. MDValueList.assignValue(
  1561. GET_OR_DISTINCT(DILocation, Record[0],
  1562. (Context, Line, Column, Scope, InlinedAt)),
  1563. NextMDValueNo++);
  1564. break;
  1565. }
  1566. case bitc::METADATA_GENERIC_DEBUG: {
  1567. if (Record.size() < 4)
  1568. return error("Invalid record");
  1569. unsigned Tag = Record[1];
  1570. unsigned Version = Record[2];
  1571. if (Tag >= 1u << 16 || Version != 0)
  1572. return error("Invalid record");
  1573. auto *Header = getMDString(Record[3]);
  1574. SmallVector<Metadata *, 8> DwarfOps;
  1575. for (unsigned I = 4, E = Record.size(); I != E; ++I)
  1576. DwarfOps.push_back(Record[I] ? MDValueList.getValueFwdRef(Record[I] - 1)
  1577. : nullptr);
  1578. MDValueList.assignValue(GET_OR_DISTINCT(GenericDINode, Record[0],
  1579. (Context, Tag, Header, DwarfOps)),
  1580. NextMDValueNo++);
  1581. break;
  1582. }
  1583. case bitc::METADATA_SUBRANGE: {
  1584. if (Record.size() != 3)
  1585. return error("Invalid record");
  1586. MDValueList.assignValue(
  1587. GET_OR_DISTINCT(DISubrange, Record[0],
  1588. (Context, Record[1], unrotateSign(Record[2]))),
  1589. NextMDValueNo++);
  1590. break;
  1591. }
  1592. case bitc::METADATA_ENUMERATOR: {
  1593. if (Record.size() != 3)
  1594. return error("Invalid record");
  1595. MDValueList.assignValue(GET_OR_DISTINCT(DIEnumerator, Record[0],
  1596. (Context, unrotateSign(Record[1]),
  1597. getMDString(Record[2]))),
  1598. NextMDValueNo++);
  1599. break;
  1600. }
  1601. case bitc::METADATA_BASIC_TYPE: {
  1602. if (Record.size() != 6)
  1603. return error("Invalid record");
  1604. MDValueList.assignValue(
  1605. GET_OR_DISTINCT(DIBasicType, Record[0],
  1606. (Context, Record[1], getMDString(Record[2]),
  1607. Record[3], Record[4], Record[5])),
  1608. NextMDValueNo++);
  1609. break;
  1610. }
  1611. case bitc::METADATA_DERIVED_TYPE: {
  1612. if (Record.size() != 12)
  1613. return error("Invalid record");
  1614. MDValueList.assignValue(
  1615. GET_OR_DISTINCT(DIDerivedType, Record[0],
  1616. (Context, Record[1], getMDString(Record[2]),
  1617. getMDOrNull(Record[3]), Record[4],
  1618. getMDOrNull(Record[5]), getMDOrNull(Record[6]),
  1619. Record[7], Record[8], Record[9], Record[10],
  1620. getMDOrNull(Record[11]))),
  1621. NextMDValueNo++);
  1622. break;
  1623. }
  1624. case bitc::METADATA_COMPOSITE_TYPE: {
  1625. if (Record.size() != 16)
  1626. return error("Invalid record");
  1627. MDValueList.assignValue(
  1628. GET_OR_DISTINCT(DICompositeType, Record[0],
  1629. (Context, Record[1], getMDString(Record[2]),
  1630. getMDOrNull(Record[3]), Record[4],
  1631. getMDOrNull(Record[5]), getMDOrNull(Record[6]),
  1632. Record[7], Record[8], Record[9], Record[10],
  1633. getMDOrNull(Record[11]), Record[12],
  1634. getMDOrNull(Record[13]), getMDOrNull(Record[14]),
  1635. getMDString(Record[15]))),
  1636. NextMDValueNo++);
  1637. break;
  1638. }
  1639. case bitc::METADATA_SUBROUTINE_TYPE: {
  1640. if (Record.size() != 3)
  1641. return error("Invalid record");
  1642. MDValueList.assignValue(
  1643. GET_OR_DISTINCT(DISubroutineType, Record[0],
  1644. (Context, Record[1], getMDOrNull(Record[2]))),
  1645. NextMDValueNo++);
  1646. break;
  1647. }
  1648. case bitc::METADATA_MODULE: {
  1649. if (Record.size() != 6)
  1650. return error("Invalid record");
  1651. MDValueList.assignValue(
  1652. GET_OR_DISTINCT(DIModule, Record[0],
  1653. (Context, getMDOrNull(Record[1]),
  1654. getMDString(Record[2]), getMDString(Record[3]),
  1655. getMDString(Record[4]), getMDString(Record[5]))),
  1656. NextMDValueNo++);
  1657. break;
  1658. }
  1659. case bitc::METADATA_FILE: {
  1660. if (Record.size() != 3)
  1661. return error("Invalid record");
  1662. MDValueList.assignValue(
  1663. GET_OR_DISTINCT(DIFile, Record[0], (Context, getMDString(Record[1]),
  1664. getMDString(Record[2]))),
  1665. NextMDValueNo++);
  1666. break;
  1667. }
  1668. case bitc::METADATA_COMPILE_UNIT: {
  1669. if (Record.size() < 14 || Record.size() > 15)
  1670. return error("Invalid record");
  1671. MDValueList.assignValue(
  1672. GET_OR_DISTINCT(
  1673. DICompileUnit, Record[0],
  1674. (Context, Record[1], getMDOrNull(Record[2]),
  1675. getMDString(Record[3]), Record[4], getMDString(Record[5]),
  1676. Record[6], getMDString(Record[7]), Record[8],
  1677. getMDOrNull(Record[9]), getMDOrNull(Record[10]),
  1678. getMDOrNull(Record[11]), getMDOrNull(Record[12]),
  1679. getMDOrNull(Record[13]), Record.size() == 14 ? 0 : Record[14])),
  1680. NextMDValueNo++);
  1681. break;
  1682. }
  1683. case bitc::METADATA_SUBPROGRAM: {
  1684. if (Record.size() != 19)
  1685. return error("Invalid record");
  1686. MDValueList.assignValue(
  1687. GET_OR_DISTINCT(
  1688. DISubprogram, Record[0],
  1689. (Context, getMDOrNull(Record[1]), getMDString(Record[2]),
  1690. getMDString(Record[3]), getMDOrNull(Record[4]), Record[5],
  1691. getMDOrNull(Record[6]), Record[7], Record[8], Record[9],
  1692. getMDOrNull(Record[10]), Record[11], Record[12], Record[13],
  1693. Record[14], getMDOrNull(Record[15]), getMDOrNull(Record[16]),
  1694. getMDOrNull(Record[17]), getMDOrNull(Record[18]))),
  1695. NextMDValueNo++);
  1696. break;
  1697. }
  1698. case bitc::METADATA_LEXICAL_BLOCK: {
  1699. if (Record.size() != 5)
  1700. return error("Invalid record");
  1701. MDValueList.assignValue(
  1702. GET_OR_DISTINCT(DILexicalBlock, Record[0],
  1703. (Context, getMDOrNull(Record[1]),
  1704. getMDOrNull(Record[2]), Record[3], Record[4])),
  1705. NextMDValueNo++);
  1706. break;
  1707. }
  1708. case bitc::METADATA_LEXICAL_BLOCK_FILE: {
  1709. if (Record.size() != 4)
  1710. return error("Invalid record");
  1711. MDValueList.assignValue(
  1712. GET_OR_DISTINCT(DILexicalBlockFile, Record[0],
  1713. (Context, getMDOrNull(Record[1]),
  1714. getMDOrNull(Record[2]), Record[3])),
  1715. NextMDValueNo++);
  1716. break;
  1717. }
  1718. case bitc::METADATA_NAMESPACE: {
  1719. if (Record.size() != 5)
  1720. return error("Invalid record");
  1721. MDValueList.assignValue(
  1722. GET_OR_DISTINCT(DINamespace, Record[0],
  1723. (Context, getMDOrNull(Record[1]),
  1724. getMDOrNull(Record[2]), getMDString(Record[3]),
  1725. Record[4])),
  1726. NextMDValueNo++);
  1727. break;
  1728. }
  1729. case bitc::METADATA_TEMPLATE_TYPE: {
  1730. if (Record.size() != 3)
  1731. return error("Invalid record");
  1732. MDValueList.assignValue(GET_OR_DISTINCT(DITemplateTypeParameter,
  1733. Record[0],
  1734. (Context, getMDString(Record[1]),
  1735. getMDOrNull(Record[2]))),
  1736. NextMDValueNo++);
  1737. break;
  1738. }
  1739. case bitc::METADATA_TEMPLATE_VALUE: {
  1740. if (Record.size() != 5)
  1741. return error("Invalid record");
  1742. MDValueList.assignValue(
  1743. GET_OR_DISTINCT(DITemplateValueParameter, Record[0],
  1744. (Context, Record[1], getMDString(Record[2]),
  1745. getMDOrNull(Record[3]), getMDOrNull(Record[4]))),
  1746. NextMDValueNo++);
  1747. break;
  1748. }
  1749. case bitc::METADATA_GLOBAL_VAR: {
  1750. if (Record.size() != 11)
  1751. return error("Invalid record");
  1752. MDValueList.assignValue(
  1753. GET_OR_DISTINCT(DIGlobalVariable, Record[0],
  1754. (Context, getMDOrNull(Record[1]),
  1755. getMDString(Record[2]), getMDString(Record[3]),
  1756. getMDOrNull(Record[4]), Record[5],
  1757. getMDOrNull(Record[6]), Record[7], Record[8],
  1758. getMDOrNull(Record[9]), getMDOrNull(Record[10]))),
  1759. NextMDValueNo++);
  1760. break;
  1761. }
  1762. case bitc::METADATA_LOCAL_VAR: {
  1763. // 10th field is for the obseleted 'inlinedAt:' field.
  1764. if (Record.size() != 9 && Record.size() != 10)
  1765. return error("Invalid record");
  1766. MDValueList.assignValue(
  1767. GET_OR_DISTINCT(DILocalVariable, Record[0],
  1768. (Context, Record[1], getMDOrNull(Record[2]),
  1769. getMDString(Record[3]), getMDOrNull(Record[4]),
  1770. Record[5], getMDOrNull(Record[6]), Record[7],
  1771. Record[8])),
  1772. NextMDValueNo++);
  1773. break;
  1774. }
  1775. case bitc::METADATA_EXPRESSION: {
  1776. if (Record.size() < 1)
  1777. return error("Invalid record");
  1778. MDValueList.assignValue(
  1779. GET_OR_DISTINCT(DIExpression, Record[0],
  1780. (Context, makeArrayRef(Record).slice(1))),
  1781. NextMDValueNo++);
  1782. break;
  1783. }
  1784. case bitc::METADATA_OBJC_PROPERTY: {
  1785. if (Record.size() != 8)
  1786. return error("Invalid record");
  1787. MDValueList.assignValue(
  1788. GET_OR_DISTINCT(DIObjCProperty, Record[0],
  1789. (Context, getMDString(Record[1]),
  1790. getMDOrNull(Record[2]), Record[3],
  1791. getMDString(Record[4]), getMDString(Record[5]),
  1792. Record[6], getMDOrNull(Record[7]))),
  1793. NextMDValueNo++);
  1794. break;
  1795. }
  1796. case bitc::METADATA_IMPORTED_ENTITY: {
  1797. if (Record.size() != 6)
  1798. return error("Invalid record");
  1799. MDValueList.assignValue(
  1800. GET_OR_DISTINCT(DIImportedEntity, Record[0],
  1801. (Context, Record[1], getMDOrNull(Record[2]),
  1802. getMDOrNull(Record[3]), Record[4],
  1803. getMDString(Record[5]))),
  1804. NextMDValueNo++);
  1805. break;
  1806. }
  1807. case bitc::METADATA_STRING: {
  1808. std::string String(Record.begin(), Record.end());
  1809. llvm::UpgradeMDStringConstant(String);
  1810. Metadata *MD = MDString::get(Context, String);
  1811. MDValueList.assignValue(MD, NextMDValueNo++);
  1812. break;
  1813. }
  1814. case bitc::METADATA_KIND: {
  1815. if (Record.size() < 2)
  1816. return error("Invalid record");
  1817. unsigned Kind = Record[0];
  1818. SmallString<8> Name(Record.begin()+1, Record.end());
  1819. unsigned NewKind = TheModule->getMDKindID(Name.str());
  1820. if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
  1821. return error("Conflicting METADATA_KIND records");
  1822. break;
  1823. }
  1824. }
  1825. }
  1826. #undef GET_OR_DISTINCT
  1827. }
  1828. /// Decode a signed value stored with the sign bit in the LSB for dense VBR
  1829. /// encoding.
  1830. uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
  1831. if ((V & 1) == 0)
  1832. return V >> 1;
  1833. if (V != 1)
  1834. return -(V >> 1);
  1835. // There is no such thing as -0 with integers. "-0" really means MININT.
  1836. return 1ULL << 63;
  1837. }
  1838. /// Resolve all of the initializers for global values and aliases that we can.
  1839. std::error_code BitcodeReader::resolveGlobalAndAliasInits() {
  1840. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  1841. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  1842. std::vector<std::pair<Function*, unsigned> > FunctionPrefixWorklist;
  1843. std::vector<std::pair<Function*, unsigned> > FunctionPrologueWorklist;
  1844. std::vector<std::pair<Function*, unsigned> > FunctionPersonalityFnWorklist;
  1845. GlobalInitWorklist.swap(GlobalInits);
  1846. AliasInitWorklist.swap(AliasInits);
  1847. FunctionPrefixWorklist.swap(FunctionPrefixes);
  1848. FunctionPrologueWorklist.swap(FunctionPrologues);
  1849. FunctionPersonalityFnWorklist.swap(FunctionPersonalityFns);
  1850. while (!GlobalInitWorklist.empty()) {
  1851. unsigned ValID = GlobalInitWorklist.back().second;
  1852. if (ValID >= ValueList.size()) {
  1853. // Not ready to resolve this yet, it requires something later in the file.
  1854. GlobalInits.push_back(GlobalInitWorklist.back());
  1855. } else {
  1856. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1857. GlobalInitWorklist.back().first->setInitializer(C);
  1858. else
  1859. return error("Expected a constant");
  1860. }
  1861. GlobalInitWorklist.pop_back();
  1862. }
  1863. while (!AliasInitWorklist.empty()) {
  1864. unsigned ValID = AliasInitWorklist.back().second;
  1865. if (ValID >= ValueList.size()) {
  1866. AliasInits.push_back(AliasInitWorklist.back());
  1867. } else {
  1868. Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]);
  1869. if (!C)
  1870. return error("Expected a constant");
  1871. GlobalAlias *Alias = AliasInitWorklist.back().first;
  1872. if (C->getType() != Alias->getType())
  1873. return error("Alias and aliasee types don't match");
  1874. Alias->setAliasee(C);
  1875. }
  1876. AliasInitWorklist.pop_back();
  1877. }
  1878. while (!FunctionPrefixWorklist.empty()) {
  1879. unsigned ValID = FunctionPrefixWorklist.back().second;
  1880. if (ValID >= ValueList.size()) {
  1881. FunctionPrefixes.push_back(FunctionPrefixWorklist.back());
  1882. } else {
  1883. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1884. FunctionPrefixWorklist.back().first->setPrefixData(C);
  1885. else
  1886. return error("Expected a constant");
  1887. }
  1888. FunctionPrefixWorklist.pop_back();
  1889. }
  1890. while (!FunctionPrologueWorklist.empty()) {
  1891. unsigned ValID = FunctionPrologueWorklist.back().second;
  1892. if (ValID >= ValueList.size()) {
  1893. FunctionPrologues.push_back(FunctionPrologueWorklist.back());
  1894. } else {
  1895. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1896. FunctionPrologueWorklist.back().first->setPrologueData(C);
  1897. else
  1898. return error("Expected a constant");
  1899. }
  1900. FunctionPrologueWorklist.pop_back();
  1901. }
  1902. while (!FunctionPersonalityFnWorklist.empty()) {
  1903. unsigned ValID = FunctionPersonalityFnWorklist.back().second;
  1904. if (ValID >= ValueList.size()) {
  1905. FunctionPersonalityFns.push_back(FunctionPersonalityFnWorklist.back());
  1906. } else {
  1907. if (Constant *C = dyn_cast_or_null<Constant>(ValueList[ValID]))
  1908. FunctionPersonalityFnWorklist.back().first->setPersonalityFn(C);
  1909. else
  1910. return error("Expected a constant");
  1911. }
  1912. FunctionPersonalityFnWorklist.pop_back();
  1913. }
  1914. return std::error_code();
  1915. }
  1916. static APInt readWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
  1917. SmallVector<uint64_t, 8> Words(Vals.size());
  1918. std::transform(Vals.begin(), Vals.end(), Words.begin(),
  1919. BitcodeReader::decodeSignRotatedValue);
  1920. return APInt(TypeBits, Words);
  1921. }
  1922. std::error_code BitcodeReader::parseConstants() {
  1923. if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
  1924. return error("Invalid record");
  1925. SmallVector<uint64_t, 64> Record;
  1926. // Read all the records for this value table.
  1927. Type *CurTy = Type::getInt32Ty(Context);
  1928. unsigned NextCstNo = ValueList.size();
  1929. while (1) {
  1930. // HLSL Change Starts - count skipped blocks
  1931. unsigned skipCount = 0;
  1932. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  1933. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  1934. // HLSL Change End
  1935. switch (Entry.Kind) {
  1936. case BitstreamEntry::SubBlock: // Handled for us already.
  1937. case BitstreamEntry::Error:
  1938. return error("Malformed block");
  1939. case BitstreamEntry::EndBlock:
  1940. if (NextCstNo != ValueList.size())
  1941. return error("Invalid ronstant reference");
  1942. // Once all the constants have been read, go through and resolve forward
  1943. // references.
  1944. ValueList.resolveConstantForwardRefs();
  1945. return std::error_code();
  1946. case BitstreamEntry::Record:
  1947. // The interesting case.
  1948. break;
  1949. }
  1950. // Read a record.
  1951. Record.clear();
  1952. Value *V = nullptr;
  1953. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  1954. switch (BitCode) {
  1955. default: // Default behavior: unknown constant
  1956. case bitc::CST_CODE_UNDEF: // UNDEF
  1957. V = UndefValue::get(CurTy);
  1958. break;
  1959. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  1960. if (Record.empty())
  1961. return error("Invalid record");
  1962. if (Record[0] >= TypeList.size() || !TypeList[Record[0]])
  1963. return error("Invalid record");
  1964. CurTy = TypeList[Record[0]];
  1965. continue; // Skip the ValueList manipulation.
  1966. case bitc::CST_CODE_NULL: // NULL
  1967. V = Constant::getNullValue(CurTy);
  1968. break;
  1969. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  1970. if (!CurTy->isIntegerTy() || Record.empty())
  1971. return error("Invalid record");
  1972. V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
  1973. break;
  1974. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
  1975. if (!CurTy->isIntegerTy() || Record.empty())
  1976. return error("Invalid record");
  1977. APInt VInt =
  1978. readWideAPInt(Record, cast<IntegerType>(CurTy)->getBitWidth());
  1979. V = ConstantInt::get(Context, VInt);
  1980. break;
  1981. }
  1982. case bitc::CST_CODE_FLOAT: { // FLOAT: [fpval]
  1983. if (Record.empty())
  1984. return error("Invalid record");
  1985. if (CurTy->isHalfTy())
  1986. V = ConstantFP::get(Context, APFloat(APFloat::IEEEhalf,
  1987. APInt(16, (uint16_t)Record[0])));
  1988. else if (CurTy->isFloatTy())
  1989. V = ConstantFP::get(Context, APFloat(APFloat::IEEEsingle,
  1990. APInt(32, (uint32_t)Record[0])));
  1991. else if (CurTy->isDoubleTy())
  1992. V = ConstantFP::get(Context, APFloat(APFloat::IEEEdouble,
  1993. APInt(64, Record[0])));
  1994. else if (CurTy->isX86_FP80Ty()) {
  1995. // Bits are not stored the same way as a normal i80 APInt, compensate.
  1996. uint64_t Rearrange[2];
  1997. Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
  1998. Rearrange[1] = Record[0] >> 48;
  1999. V = ConstantFP::get(Context, APFloat(APFloat::x87DoubleExtended,
  2000. APInt(80, Rearrange)));
  2001. } else if (CurTy->isFP128Ty())
  2002. V = ConstantFP::get(Context, APFloat(APFloat::IEEEquad,
  2003. APInt(128, Record)));
  2004. else if (CurTy->isPPC_FP128Ty())
  2005. V = ConstantFP::get(Context, APFloat(APFloat::PPCDoubleDouble,
  2006. APInt(128, Record)));
  2007. else
  2008. V = UndefValue::get(CurTy);
  2009. break;
  2010. }
  2011. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
  2012. if (Record.empty())
  2013. return error("Invalid record");
  2014. unsigned Size = Record.size();
  2015. SmallVector<Constant*, 16> Elts;
  2016. if (StructType *STy = dyn_cast<StructType>(CurTy)) {
  2017. for (unsigned i = 0; i != Size; ++i)
  2018. Elts.push_back(ValueList.getConstantFwdRef(Record[i],
  2019. STy->getElementType(i)));
  2020. V = ConstantStruct::get(STy, Elts);
  2021. } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  2022. Type *EltTy = ATy->getElementType();
  2023. for (unsigned i = 0; i != Size; ++i)
  2024. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  2025. V = ConstantArray::get(ATy, Elts);
  2026. } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  2027. Type *EltTy = VTy->getElementType();
  2028. for (unsigned i = 0; i != Size; ++i)
  2029. Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
  2030. V = ConstantVector::get(Elts);
  2031. } else {
  2032. V = UndefValue::get(CurTy);
  2033. }
  2034. break;
  2035. }
  2036. case bitc::CST_CODE_STRING: // STRING: [values]
  2037. case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
  2038. if (Record.empty())
  2039. return error("Invalid record");
  2040. SmallString<16> Elts(Record.begin(), Record.end());
  2041. V = ConstantDataArray::getString(Context, Elts,
  2042. BitCode == bitc::CST_CODE_CSTRING);
  2043. break;
  2044. }
  2045. case bitc::CST_CODE_DATA: {// DATA: [n x value]
  2046. if (Record.empty())
  2047. return error("Invalid record");
  2048. Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
  2049. unsigned Size = Record.size();
  2050. if (EltTy->isIntegerTy(8)) {
  2051. SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
  2052. if (isa<VectorType>(CurTy))
  2053. V = ConstantDataVector::get(Context, Elts);
  2054. else
  2055. V = ConstantDataArray::get(Context, Elts);
  2056. } else if (EltTy->isIntegerTy(16)) {
  2057. SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
  2058. if (isa<VectorType>(CurTy))
  2059. V = ConstantDataVector::get(Context, Elts);
  2060. else
  2061. V = ConstantDataArray::get(Context, Elts);
  2062. } else if (EltTy->isIntegerTy(32)) {
  2063. SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
  2064. if (isa<VectorType>(CurTy))
  2065. V = ConstantDataVector::get(Context, Elts);
  2066. else
  2067. V = ConstantDataArray::get(Context, Elts);
  2068. } else if (EltTy->isIntegerTy(64)) {
  2069. SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
  2070. if (isa<VectorType>(CurTy))
  2071. V = ConstantDataVector::get(Context, Elts);
  2072. else
  2073. V = ConstantDataArray::get(Context, Elts);
  2074. } else if (EltTy->isFloatTy()) {
  2075. SmallVector<float, 16> Elts(Size);
  2076. std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
  2077. if (isa<VectorType>(CurTy))
  2078. V = ConstantDataVector::get(Context, Elts);
  2079. else
  2080. V = ConstantDataArray::get(Context, Elts);
  2081. } else if (EltTy->isDoubleTy()) {
  2082. SmallVector<double, 16> Elts(Size);
  2083. std::transform(Record.begin(), Record.end(), Elts.begin(),
  2084. BitsToDouble);
  2085. if (isa<VectorType>(CurTy))
  2086. V = ConstantDataVector::get(Context, Elts);
  2087. else
  2088. V = ConstantDataArray::get(Context, Elts);
  2089. } else {
  2090. return error("Invalid type for value");
  2091. }
  2092. break;
  2093. }
  2094. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  2095. if (Record.size() < 3)
  2096. return error("Invalid record");
  2097. int Opc = getDecodedBinaryOpcode(Record[0], CurTy);
  2098. if (Opc < 0) {
  2099. V = UndefValue::get(CurTy); // Unknown binop.
  2100. } else {
  2101. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  2102. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  2103. unsigned Flags = 0;
  2104. if (Record.size() >= 4) {
  2105. if (Opc == Instruction::Add ||
  2106. Opc == Instruction::Sub ||
  2107. Opc == Instruction::Mul ||
  2108. Opc == Instruction::Shl) {
  2109. if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  2110. Flags |= OverflowingBinaryOperator::NoSignedWrap;
  2111. if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  2112. Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
  2113. } else if (Opc == Instruction::SDiv ||
  2114. Opc == Instruction::UDiv ||
  2115. Opc == Instruction::LShr ||
  2116. Opc == Instruction::AShr) {
  2117. if (Record[3] & (1 << bitc::PEO_EXACT))
  2118. Flags |= SDivOperator::IsExact;
  2119. }
  2120. }
  2121. V = ConstantExpr::get(Opc, LHS, RHS, Flags);
  2122. }
  2123. break;
  2124. }
  2125. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  2126. if (Record.size() < 3)
  2127. return error("Invalid record");
  2128. int Opc = getDecodedCastOpcode(Record[0]);
  2129. if (Opc < 0) {
  2130. V = UndefValue::get(CurTy); // Unknown cast.
  2131. } else {
  2132. Type *OpTy = getTypeByID(Record[1]);
  2133. if (!OpTy)
  2134. return error("Invalid record");
  2135. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  2136. V = UpgradeBitCastExpr(Opc, Op, CurTy);
  2137. if (!V) V = ConstantExpr::getCast(Opc, Op, CurTy);
  2138. }
  2139. break;
  2140. }
  2141. case bitc::CST_CODE_CE_INBOUNDS_GEP:
  2142. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  2143. unsigned OpNum = 0;
  2144. Type *PointeeType = nullptr;
  2145. if (Record.size() % 2)
  2146. PointeeType = getTypeByID(Record[OpNum++]);
  2147. SmallVector<Constant*, 16> Elts;
  2148. while (OpNum != Record.size()) {
  2149. Type *ElTy = getTypeByID(Record[OpNum++]);
  2150. if (!ElTy)
  2151. return error("Invalid record");
  2152. Elts.push_back(ValueList.getConstantFwdRef(Record[OpNum++], ElTy));
  2153. }
  2154. if (PointeeType &&
  2155. PointeeType !=
  2156. cast<SequentialType>(Elts[0]->getType()->getScalarType())
  2157. ->getElementType())
  2158. return error("Explicit gep operator type does not match pointee type "
  2159. "of pointer operand");
  2160. ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
  2161. V = ConstantExpr::getGetElementPtr(PointeeType, Elts[0], Indices,
  2162. BitCode ==
  2163. bitc::CST_CODE_CE_INBOUNDS_GEP);
  2164. break;
  2165. }
  2166. case bitc::CST_CODE_CE_SELECT: { // CE_SELECT: [opval#, opval#, opval#]
  2167. if (Record.size() < 3)
  2168. return error("Invalid record");
  2169. Type *SelectorTy = Type::getInt1Ty(Context);
  2170. // If CurTy is a vector of length n, then Record[0] must be a <n x i1>
  2171. // vector. Otherwise, it must be a single bit.
  2172. if (VectorType *VTy = dyn_cast<VectorType>(CurTy))
  2173. SelectorTy = VectorType::get(Type::getInt1Ty(Context),
  2174. VTy->getNumElements());
  2175. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  2176. SelectorTy),
  2177. ValueList.getConstantFwdRef(Record[1],CurTy),
  2178. ValueList.getConstantFwdRef(Record[2],CurTy));
  2179. break;
  2180. }
  2181. case bitc::CST_CODE_CE_EXTRACTELT
  2182. : { // CE_EXTRACTELT: [opty, opval, opty, opval]
  2183. if (Record.size() < 3)
  2184. return error("Invalid record");
  2185. VectorType *OpTy =
  2186. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2187. if (!OpTy)
  2188. return error("Invalid record");
  2189. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2190. Constant *Op1 = nullptr;
  2191. if (Record.size() == 4) {
  2192. Type *IdxTy = getTypeByID(Record[2]);
  2193. if (!IdxTy)
  2194. return error("Invalid record");
  2195. Op1 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2196. } else // TODO: Remove with llvm 4.0
  2197. Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2198. if (!Op1)
  2199. return error("Invalid record");
  2200. V = ConstantExpr::getExtractElement(Op0, Op1);
  2201. break;
  2202. }
  2203. case bitc::CST_CODE_CE_INSERTELT
  2204. : { // CE_INSERTELT: [opval, opval, opty, opval]
  2205. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2206. if (Record.size() < 3 || !OpTy)
  2207. return error("Invalid record");
  2208. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2209. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  2210. OpTy->getElementType());
  2211. Constant *Op2 = nullptr;
  2212. if (Record.size() == 4) {
  2213. Type *IdxTy = getTypeByID(Record[2]);
  2214. if (!IdxTy)
  2215. return error("Invalid record");
  2216. Op2 = ValueList.getConstantFwdRef(Record[3], IdxTy);
  2217. } else // TODO: Remove with llvm 4.0
  2218. Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
  2219. if (!Op2)
  2220. return error("Invalid record");
  2221. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  2222. break;
  2223. }
  2224. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  2225. VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  2226. if (Record.size() < 3 || !OpTy)
  2227. return error("Invalid record");
  2228. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  2229. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2230. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2231. OpTy->getNumElements());
  2232. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  2233. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  2234. break;
  2235. }
  2236. case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
  2237. VectorType *RTy = dyn_cast<VectorType>(CurTy);
  2238. VectorType *OpTy =
  2239. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  2240. if (Record.size() < 4 || !RTy || !OpTy)
  2241. return error("Invalid record");
  2242. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2243. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  2244. Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
  2245. RTy->getNumElements());
  2246. Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
  2247. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  2248. break;
  2249. }
  2250. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  2251. if (Record.size() < 4)
  2252. return error("Invalid record");
  2253. Type *OpTy = getTypeByID(Record[0]);
  2254. if (!OpTy)
  2255. return error("Invalid record");
  2256. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  2257. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  2258. if (OpTy->isFPOrFPVectorTy())
  2259. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  2260. else
  2261. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  2262. break;
  2263. }
  2264. // This maintains backward compatibility, pre-asm dialect keywords.
  2265. // FIXME: Remove with the 4.0 release.
  2266. case bitc::CST_CODE_INLINEASM_OLD: {
  2267. if (Record.size() < 2)
  2268. return error("Invalid record");
  2269. std::string AsmStr, ConstrStr;
  2270. bool HasSideEffects = Record[0] & 1;
  2271. bool IsAlignStack = Record[0] >> 1;
  2272. unsigned AsmStrSize = Record[1];
  2273. if (2+AsmStrSize >= Record.size())
  2274. return error("Invalid record");
  2275. unsigned ConstStrSize = Record[2+AsmStrSize];
  2276. if (3+AsmStrSize+ConstStrSize > Record.size())
  2277. return error("Invalid record");
  2278. for (unsigned i = 0; i != AsmStrSize; ++i)
  2279. AsmStr += (char)Record[2+i];
  2280. for (unsigned i = 0; i != ConstStrSize; ++i)
  2281. ConstrStr += (char)Record[3+AsmStrSize+i];
  2282. PointerType *PTy = cast<PointerType>(CurTy);
  2283. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  2284. AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
  2285. break;
  2286. }
  2287. // This version adds support for the asm dialect keywords (e.g.,
  2288. // inteldialect).
  2289. case bitc::CST_CODE_INLINEASM: {
  2290. if (Record.size() < 2)
  2291. return error("Invalid record");
  2292. std::string AsmStr, ConstrStr;
  2293. bool HasSideEffects = Record[0] & 1;
  2294. bool IsAlignStack = (Record[0] >> 1) & 1;
  2295. unsigned AsmDialect = Record[0] >> 2;
  2296. unsigned AsmStrSize = Record[1];
  2297. if (2+AsmStrSize >= Record.size())
  2298. return error("Invalid record");
  2299. unsigned ConstStrSize = Record[2+AsmStrSize];
  2300. if (3+AsmStrSize+ConstStrSize > Record.size())
  2301. return error("Invalid record");
  2302. for (unsigned i = 0; i != AsmStrSize; ++i)
  2303. AsmStr += (char)Record[2+i];
  2304. for (unsigned i = 0; i != ConstStrSize; ++i)
  2305. ConstrStr += (char)Record[3+AsmStrSize+i];
  2306. PointerType *PTy = cast<PointerType>(CurTy);
  2307. V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
  2308. AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
  2309. InlineAsm::AsmDialect(AsmDialect));
  2310. break;
  2311. }
  2312. case bitc::CST_CODE_BLOCKADDRESS:{
  2313. if (Record.size() < 3)
  2314. return error("Invalid record");
  2315. Type *FnTy = getTypeByID(Record[0]);
  2316. if (!FnTy)
  2317. return error("Invalid record");
  2318. Function *Fn =
  2319. dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
  2320. if (!Fn)
  2321. return error("Invalid record");
  2322. // Don't let Fn get dematerialized.
  2323. BlockAddressesTaken.insert(Fn);
  2324. // If the function is already parsed we can insert the block address right
  2325. // away.
  2326. BasicBlock *BB;
  2327. unsigned BBID = Record[2];
  2328. if (!BBID)
  2329. // Invalid reference to entry block.
  2330. return error("Invalid ID");
  2331. if (!Fn->empty()) {
  2332. Function::iterator BBI = Fn->begin(), BBE = Fn->end();
  2333. for (size_t I = 0, E = BBID; I != E; ++I) {
  2334. if (BBI == BBE)
  2335. return error("Invalid ID");
  2336. ++BBI;
  2337. }
  2338. BB = BBI;
  2339. } else {
  2340. // Otherwise insert a placeholder and remember it so it can be inserted
  2341. // when the function is parsed.
  2342. auto &FwdBBs = BasicBlockFwdRefs[Fn];
  2343. if (FwdBBs.empty())
  2344. BasicBlockFwdRefQueue.push_back(Fn);
  2345. if (FwdBBs.size() < BBID + 1)
  2346. FwdBBs.resize(BBID + 1);
  2347. if (!FwdBBs[BBID])
  2348. FwdBBs[BBID] = BasicBlock::Create(Context);
  2349. BB = FwdBBs[BBID];
  2350. }
  2351. V = BlockAddress::get(Fn, BB);
  2352. break;
  2353. }
  2354. }
  2355. ValueList.assignValue(V, NextCstNo);
  2356. ++NextCstNo;
  2357. }
  2358. }
  2359. std::error_code BitcodeReader::parseUseLists() {
  2360. if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
  2361. return error("Invalid record");
  2362. // Read all the records.
  2363. SmallVector<uint64_t, 64> Record;
  2364. while (1) {
  2365. // HLSL Change Starts - count skipped blocks
  2366. unsigned skipCount = 0;
  2367. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  2368. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  2369. // HLSL Change End
  2370. switch (Entry.Kind) {
  2371. case BitstreamEntry::SubBlock: // Handled for us already.
  2372. case BitstreamEntry::Error:
  2373. return error("Malformed block");
  2374. case BitstreamEntry::EndBlock:
  2375. return std::error_code();
  2376. case BitstreamEntry::Record:
  2377. // The interesting case.
  2378. break;
  2379. }
  2380. // Read a use list record.
  2381. Record.clear();
  2382. bool IsBB = false;
  2383. switch (Stream.readRecord(Entry.ID, Record)) {
  2384. default: // Default behavior: unknown type.
  2385. break;
  2386. case bitc::USELIST_CODE_BB:
  2387. IsBB = true;
  2388. // fallthrough
  2389. case bitc::USELIST_CODE_DEFAULT: {
  2390. unsigned RecordLength = Record.size();
  2391. if (RecordLength < 3)
  2392. // Records should have at least an ID and two indexes.
  2393. return error("Invalid record");
  2394. unsigned ID = Record.back();
  2395. Record.pop_back();
  2396. Value *V;
  2397. if (IsBB) {
  2398. assert(ID < FunctionBBs.size() && "Basic block not found");
  2399. V = FunctionBBs[ID];
  2400. } else
  2401. V = ValueList[ID];
  2402. unsigned NumUses = 0;
  2403. SmallDenseMap<const Use *, unsigned, 16> Order;
  2404. for (const Use &U : V->uses()) {
  2405. if (++NumUses > Record.size())
  2406. break;
  2407. Order[&U] = Record[NumUses - 1];
  2408. }
  2409. if (Order.size() != Record.size() || NumUses > Record.size())
  2410. // Mismatches can happen if the functions are being materialized lazily
  2411. // (out-of-order), or a value has been upgraded.
  2412. break;
  2413. V->sortUseList([&](const Use &L, const Use &R) {
  2414. return Order.lookup(&L) < Order.lookup(&R);
  2415. });
  2416. break;
  2417. }
  2418. }
  2419. }
  2420. }
  2421. /// When we see the block for metadata, remember where it is and then skip it.
  2422. /// This lets us lazily deserialize the metadata.
  2423. std::error_code BitcodeReader::rememberAndSkipMetadata() {
  2424. // Save the current stream state.
  2425. uint64_t CurBit = Stream.GetCurrentBitNo();
  2426. DeferredMetadataInfo.push_back(CurBit);
  2427. // Skip over the block for now.
  2428. if (Stream.SkipBlock())
  2429. return error("Invalid record");
  2430. return std::error_code();
  2431. }
  2432. std::error_code BitcodeReader::materializeMetadata() {
  2433. for (uint64_t BitPos : DeferredMetadataInfo) {
  2434. // Move the bit stream to the saved position.
  2435. Stream.JumpToBit(BitPos);
  2436. if (std::error_code EC = parseMetadata())
  2437. return EC;
  2438. }
  2439. DeferredMetadataInfo.clear();
  2440. return std::error_code();
  2441. }
  2442. void BitcodeReader::setStripDebugInfo() { StripDebugInfo = true; }
  2443. /// When we see the block for a function body, remember where it is and then
  2444. /// skip it. This lets us lazily deserialize the functions.
  2445. std::error_code BitcodeReader::rememberAndSkipFunctionBody() {
  2446. // Get the function we are talking about.
  2447. if (FunctionsWithBodies.empty())
  2448. return error("Insufficient function protos");
  2449. Function *Fn = FunctionsWithBodies.back();
  2450. FunctionsWithBodies.pop_back();
  2451. // Save the current stream state.
  2452. uint64_t CurBit = Stream.GetCurrentBitNo();
  2453. DeferredFunctionInfo[Fn] = CurBit;
  2454. // Skip over the function block for now.
  2455. if (Stream.SkipBlock())
  2456. return error("Invalid record");
  2457. return std::error_code();
  2458. }
  2459. std::error_code BitcodeReader::globalCleanup() {
  2460. // Patch the initializers for globals and aliases up.
  2461. resolveGlobalAndAliasInits();
  2462. if (!GlobalInits.empty() || !AliasInits.empty())
  2463. return error("Malformed global initializer set");
  2464. // Look for intrinsic functions which need to be upgraded at some point
  2465. for (Function &F : *TheModule) {
  2466. Function *NewFn;
  2467. if (UpgradeIntrinsicFunction(&F, NewFn))
  2468. UpgradedIntrinsics[&F] = NewFn;
  2469. }
  2470. // Look for global variables which need to be renamed.
  2471. for (GlobalVariable &GV : TheModule->globals())
  2472. UpgradeGlobalVariable(&GV);
  2473. // Force deallocation of memory for these vectors to favor the client that
  2474. // want lazy deserialization.
  2475. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  2476. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  2477. return std::error_code();
  2478. }
  2479. std::error_code BitcodeReader::parseModule(bool Resume,
  2480. bool ShouldLazyLoadMetadata) {
  2481. if (Resume)
  2482. Stream.JumpToBit(NextUnreadBit);
  2483. else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  2484. return error("Invalid record");
  2485. SmallVector<uint64_t, 64> Record;
  2486. std::vector<std::string> SectionTable;
  2487. std::vector<std::string> GCTable;
  2488. // Read all the records for this module.
  2489. while (1) {
  2490. BitstreamEntry Entry = Stream.advance();
  2491. switch (Entry.Kind) {
  2492. case BitstreamEntry::Error:
  2493. return error("Malformed block");
  2494. case BitstreamEntry::EndBlock:
  2495. return globalCleanup();
  2496. case BitstreamEntry::SubBlock:
  2497. switch (Entry.ID) {
  2498. default: // Skip unknown content.
  2499. if (Stream.SkipBlock())
  2500. return error("Invalid record");
  2501. ReportWarning(DiagnosticHandler, "Unrecognized block found"); // HLSL Change - check for skipped blocks
  2502. break;
  2503. case bitc::BLOCKINFO_BLOCK_ID:
  2504. // HLSL Changes Start -- check for skipped blocks
  2505. unsigned count;
  2506. count = 0;
  2507. if (Stream.ReadBlockInfoBlock(&count))
  2508. return error("Malformed block");
  2509. if (count > 0)
  2510. ReportWarning(DiagnosticHandler, "Unrecognized block found");
  2511. // HLSL Changes End
  2512. break;
  2513. case bitc::PARAMATTR_BLOCK_ID:
  2514. if (std::error_code EC = parseAttributeBlock())
  2515. return EC;
  2516. break;
  2517. case bitc::PARAMATTR_GROUP_BLOCK_ID:
  2518. if (std::error_code EC = parseAttributeGroupBlock())
  2519. return EC;
  2520. break;
  2521. case bitc::TYPE_BLOCK_ID_NEW:
  2522. if (std::error_code EC = parseTypeTable())
  2523. return EC;
  2524. break;
  2525. case bitc::VALUE_SYMTAB_BLOCK_ID:
  2526. if (std::error_code EC = parseValueSymbolTable())
  2527. return EC;
  2528. SeenValueSymbolTable = true;
  2529. break;
  2530. case bitc::CONSTANTS_BLOCK_ID:
  2531. if (std::error_code EC = parseConstants())
  2532. return EC;
  2533. if (std::error_code EC = resolveGlobalAndAliasInits())
  2534. return EC;
  2535. break;
  2536. case bitc::METADATA_BLOCK_ID:
  2537. if (ShouldLazyLoadMetadata && !IsMetadataMaterialized) {
  2538. if (std::error_code EC = rememberAndSkipMetadata())
  2539. return EC;
  2540. break;
  2541. }
  2542. assert(DeferredMetadataInfo.empty() && "Unexpected deferred metadata");
  2543. if (std::error_code EC = parseMetadata())
  2544. return EC;
  2545. break;
  2546. case bitc::FUNCTION_BLOCK_ID:
  2547. // If this is the first function body we've seen, reverse the
  2548. // FunctionsWithBodies list.
  2549. if (!SeenFirstFunctionBody) {
  2550. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  2551. if (std::error_code EC = globalCleanup())
  2552. return EC;
  2553. SeenFirstFunctionBody = true;
  2554. }
  2555. if (std::error_code EC = rememberAndSkipFunctionBody())
  2556. return EC;
  2557. // Suspend parsing when we reach the function bodies. Subsequent
  2558. // materialization calls will resume it when necessary. If the bitcode
  2559. // file is old, the symbol table will be at the end instead and will not
  2560. // have been seen yet. In this case, just finish the parse now.
  2561. if (SeenValueSymbolTable) {
  2562. NextUnreadBit = Stream.GetCurrentBitNo();
  2563. return std::error_code();
  2564. }
  2565. break;
  2566. case bitc::USELIST_BLOCK_ID:
  2567. if (std::error_code EC = parseUseLists())
  2568. return EC;
  2569. break;
  2570. }
  2571. continue;
  2572. case BitstreamEntry::Record:
  2573. // The interesting case.
  2574. break;
  2575. }
  2576. // Read a record.
  2577. switch (Stream.readRecord(Entry.ID, Record)) {
  2578. default: break; // Default behavior, ignore unknown content.
  2579. case bitc::MODULE_CODE_VERSION: { // VERSION: [version#]
  2580. if (Record.size() < 1)
  2581. return error("Invalid record");
  2582. // Only version #0 and #1 are supported so far.
  2583. unsigned module_version = Record[0];
  2584. switch (module_version) {
  2585. default:
  2586. return error("Invalid value");
  2587. case 0:
  2588. UseRelativeIDs = false;
  2589. break;
  2590. case 1:
  2591. UseRelativeIDs = true;
  2592. break;
  2593. }
  2594. break;
  2595. }
  2596. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  2597. std::string S;
  2598. if (convertToString(Record, 0, S))
  2599. return error("Invalid record");
  2600. TheModule->setTargetTriple(S);
  2601. break;
  2602. }
  2603. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strchr x N]
  2604. std::string S;
  2605. if (convertToString(Record, 0, S))
  2606. return error("Invalid record");
  2607. TheModule->setDataLayout(S);
  2608. break;
  2609. }
  2610. case bitc::MODULE_CODE_ASM: { // ASM: [strchr x N]
  2611. std::string S;
  2612. if (convertToString(Record, 0, S))
  2613. return error("Invalid record");
  2614. TheModule->setModuleInlineAsm(S);
  2615. break;
  2616. }
  2617. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strchr x N]
  2618. // FIXME: Remove in 4.0.
  2619. std::string S;
  2620. if (convertToString(Record, 0, S))
  2621. return error("Invalid record");
  2622. // Ignore value.
  2623. break;
  2624. }
  2625. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strchr x N]
  2626. std::string S;
  2627. if (convertToString(Record, 0, S))
  2628. return error("Invalid record");
  2629. SectionTable.push_back(S);
  2630. break;
  2631. }
  2632. case bitc::MODULE_CODE_GCNAME: { // SECTIONNAME: [strchr x N]
  2633. std::string S;
  2634. if (convertToString(Record, 0, S))
  2635. return error("Invalid record");
  2636. GCTable.push_back(S);
  2637. break;
  2638. }
  2639. case bitc::MODULE_CODE_COMDAT: { // COMDAT: [selection_kind, name]
  2640. if (Record.size() < 2)
  2641. return error("Invalid record");
  2642. Comdat::SelectionKind SK = getDecodedComdatSelectionKind(Record[0]);
  2643. unsigned ComdatNameSize = Record[1];
  2644. std::string ComdatName;
  2645. ComdatName.reserve(ComdatNameSize);
  2646. for (unsigned i = 0; i != ComdatNameSize; ++i)
  2647. ComdatName += (char)Record[2 + i];
  2648. Comdat *C = TheModule->getOrInsertComdat(ComdatName);
  2649. C->setSelectionKind(SK);
  2650. ComdatList.push_back(C);
  2651. break;
  2652. }
  2653. // GLOBALVAR: [pointer type, isconst, initid,
  2654. // linkage, alignment, section, visibility, threadlocal,
  2655. // unnamed_addr, externally_initialized, dllstorageclass,
  2656. // comdat]
  2657. case bitc::MODULE_CODE_GLOBALVAR: {
  2658. if (Record.size() < 6)
  2659. return error("Invalid record");
  2660. Type *Ty = getTypeByID(Record[0]);
  2661. if (!Ty)
  2662. return error("Invalid record");
  2663. bool isConstant = Record[1] & 1;
  2664. bool explicitType = Record[1] & 2;
  2665. unsigned AddressSpace;
  2666. if (explicitType) {
  2667. AddressSpace = Record[1] >> 2;
  2668. } else {
  2669. if (!Ty->isPointerTy())
  2670. return error("Invalid type for value");
  2671. AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
  2672. Ty = cast<PointerType>(Ty)->getElementType();
  2673. }
  2674. uint64_t RawLinkage = Record[3];
  2675. GlobalValue::LinkageTypes Linkage = getDecodedLinkage(RawLinkage);
  2676. unsigned Alignment;
  2677. if (std::error_code EC = parseAlignmentValue(Record[4], Alignment))
  2678. return EC;
  2679. std::string Section;
  2680. if (Record[5]) {
  2681. if (Record[5]-1 >= SectionTable.size())
  2682. return error("Invalid ID");
  2683. Section = SectionTable[Record[5]-1];
  2684. }
  2685. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  2686. // Local linkage must have default visibility.
  2687. if (Record.size() > 6 && !GlobalValue::isLocalLinkage(Linkage))
  2688. // FIXME: Change to an error if non-default in 4.0.
  2689. Visibility = getDecodedVisibility(Record[6]);
  2690. GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
  2691. if (Record.size() > 7)
  2692. TLM = getDecodedThreadLocalMode(Record[7]);
  2693. bool UnnamedAddr = false;
  2694. if (Record.size() > 8)
  2695. UnnamedAddr = Record[8];
  2696. bool ExternallyInitialized = false;
  2697. if (Record.size() > 9)
  2698. ExternallyInitialized = Record[9];
  2699. GlobalVariable *NewGV =
  2700. new GlobalVariable(*TheModule, Ty, isConstant, Linkage, nullptr, "", nullptr,
  2701. TLM, AddressSpace, ExternallyInitialized);
  2702. NewGV->setAlignment(Alignment);
  2703. if (!Section.empty())
  2704. NewGV->setSection(Section);
  2705. NewGV->setVisibility(Visibility);
  2706. NewGV->setUnnamedAddr(UnnamedAddr);
  2707. if (Record.size() > 10)
  2708. NewGV->setDLLStorageClass(getDecodedDLLStorageClass(Record[10]));
  2709. else
  2710. upgradeDLLImportExportLinkage(NewGV, RawLinkage);
  2711. ValueList.push_back(NewGV);
  2712. // Remember which value to use for the global initializer.
  2713. if (unsigned InitID = Record[2])
  2714. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  2715. if (Record.size() > 11) {
  2716. if (unsigned ComdatID = Record[11]) {
  2717. if (ComdatID > ComdatList.size())
  2718. return error("Invalid global variable comdat ID");
  2719. NewGV->setComdat(ComdatList[ComdatID - 1]);
  2720. }
  2721. } else if (hasImplicitComdat(RawLinkage)) {
  2722. NewGV->setComdat(reinterpret_cast<Comdat *>(1));
  2723. }
  2724. break;
  2725. }
  2726. // FUNCTION: [type, callingconv, isproto, linkage, paramattr,
  2727. // alignment, section, visibility, gc, unnamed_addr,
  2728. // prologuedata, dllstorageclass, comdat, prefixdata]
  2729. case bitc::MODULE_CODE_FUNCTION: {
  2730. if (Record.size() < 8)
  2731. return error("Invalid record");
  2732. Type *Ty = getTypeByID(Record[0]);
  2733. if (!Ty)
  2734. return error("Invalid record");
  2735. if (auto *PTy = dyn_cast<PointerType>(Ty))
  2736. Ty = PTy->getElementType();
  2737. auto *FTy = dyn_cast<FunctionType>(Ty);
  2738. if (!FTy)
  2739. return error("Invalid type for value");
  2740. Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
  2741. "", TheModule);
  2742. Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
  2743. bool isProto = Record[2];
  2744. uint64_t RawLinkage = Record[3];
  2745. Func->setLinkage(getDecodedLinkage(RawLinkage));
  2746. Func->setAttributes(getAttributes(Record[4]));
  2747. unsigned Alignment;
  2748. if (std::error_code EC = parseAlignmentValue(Record[5], Alignment))
  2749. return EC;
  2750. Func->setAlignment(Alignment);
  2751. if (Record[6]) {
  2752. if (Record[6]-1 >= SectionTable.size())
  2753. return error("Invalid ID");
  2754. Func->setSection(SectionTable[Record[6]-1]);
  2755. }
  2756. // Local linkage must have default visibility.
  2757. if (!Func->hasLocalLinkage())
  2758. // FIXME: Change to an error if non-default in 4.0.
  2759. Func->setVisibility(getDecodedVisibility(Record[7]));
  2760. if (Record.size() > 8 && Record[8]) {
  2761. if (Record[8]-1 >= GCTable.size())
  2762. return error("Invalid ID");
  2763. Func->setGC(GCTable[Record[8]-1].c_str());
  2764. }
  2765. bool UnnamedAddr = false;
  2766. if (Record.size() > 9)
  2767. UnnamedAddr = Record[9];
  2768. Func->setUnnamedAddr(UnnamedAddr);
  2769. if (Record.size() > 10 && Record[10] != 0)
  2770. FunctionPrologues.push_back(std::make_pair(Func, Record[10]-1));
  2771. if (Record.size() > 11)
  2772. Func->setDLLStorageClass(getDecodedDLLStorageClass(Record[11]));
  2773. else
  2774. upgradeDLLImportExportLinkage(Func, RawLinkage);
  2775. if (Record.size() > 12) {
  2776. if (unsigned ComdatID = Record[12]) {
  2777. if (ComdatID > ComdatList.size())
  2778. return error("Invalid function comdat ID");
  2779. Func->setComdat(ComdatList[ComdatID - 1]);
  2780. }
  2781. } else if (hasImplicitComdat(RawLinkage)) {
  2782. Func->setComdat(reinterpret_cast<Comdat *>(1));
  2783. }
  2784. if (Record.size() > 13 && Record[13] != 0)
  2785. FunctionPrefixes.push_back(std::make_pair(Func, Record[13]-1));
  2786. if (Record.size() > 14 && Record[14] != 0)
  2787. FunctionPersonalityFns.push_back(std::make_pair(Func, Record[14] - 1));
  2788. ValueList.push_back(Func);
  2789. // If this is a function with a body, remember the prototype we are
  2790. // creating now, so that we can match up the body with them later.
  2791. if (!isProto) {
  2792. Func->setIsMaterializable(true);
  2793. FunctionsWithBodies.push_back(Func);
  2794. DeferredFunctionInfo[Func] = 0;
  2795. }
  2796. break;
  2797. }
  2798. // ALIAS: [alias type, aliasee val#, linkage]
  2799. // ALIAS: [alias type, aliasee val#, linkage, visibility, dllstorageclass]
  2800. case bitc::MODULE_CODE_ALIAS: {
  2801. if (Record.size() < 3)
  2802. return error("Invalid record");
  2803. Type *Ty = getTypeByID(Record[0]);
  2804. if (!Ty)
  2805. return error("Invalid record");
  2806. auto *PTy = dyn_cast<PointerType>(Ty);
  2807. if (!PTy)
  2808. return error("Invalid type for value");
  2809. auto *NewGA =
  2810. GlobalAlias::create(PTy, getDecodedLinkage(Record[2]), "", TheModule);
  2811. // Old bitcode files didn't have visibility field.
  2812. // Local linkage must have default visibility.
  2813. if (Record.size() > 3 && !NewGA->hasLocalLinkage())
  2814. // FIXME: Change to an error if non-default in 4.0.
  2815. NewGA->setVisibility(getDecodedVisibility(Record[3]));
  2816. if (Record.size() > 4)
  2817. NewGA->setDLLStorageClass(getDecodedDLLStorageClass(Record[4]));
  2818. else
  2819. upgradeDLLImportExportLinkage(NewGA, Record[2]);
  2820. if (Record.size() > 5)
  2821. NewGA->setThreadLocalMode(getDecodedThreadLocalMode(Record[5]));
  2822. if (Record.size() > 6)
  2823. NewGA->setUnnamedAddr(Record[6]);
  2824. ValueList.push_back(NewGA);
  2825. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  2826. break;
  2827. }
  2828. /// MODULE_CODE_PURGEVALS: [numvals]
  2829. case bitc::MODULE_CODE_PURGEVALS:
  2830. // Trim down the value list to the specified size.
  2831. if (Record.size() < 1 || Record[0] > ValueList.size())
  2832. return error("Invalid record");
  2833. ValueList.shrinkTo(Record[0]);
  2834. break;
  2835. }
  2836. Record.clear();
  2837. }
  2838. }
  2839. std::error_code
  2840. BitcodeReader::parseBitcodeInto(std::unique_ptr<DataStreamer> Streamer,
  2841. Module *M, bool ShouldLazyLoadMetadata) {
  2842. TheModule = M;
  2843. if (std::error_code EC = initStream(std::move(Streamer)))
  2844. return EC;
  2845. // Sniff for the signature.
  2846. if (Stream.Read(8) != 'B' ||
  2847. Stream.Read(8) != 'C' ||
  2848. Stream.Read(4) != 0x0 ||
  2849. Stream.Read(4) != 0xC ||
  2850. Stream.Read(4) != 0xE ||
  2851. Stream.Read(4) != 0xD)
  2852. return error("Invalid bitcode signature");
  2853. // We expect a number of well-defined blocks, though we don't necessarily
  2854. // need to understand them all.
  2855. while (1) {
  2856. if (Stream.AtEndOfStream()) {
  2857. return error("Malformed IR file");
  2858. }
  2859. BitstreamEntry Entry =
  2860. Stream.advance(BitstreamCursor::AF_DontAutoprocessAbbrevs);
  2861. if (Entry.Kind != BitstreamEntry::SubBlock)
  2862. return error("Malformed block");
  2863. // HLSL Change - process the complete stream.
  2864. if (Entry.ID == bitc::MODULE_BLOCK_ID) {
  2865. return parseModule(false, ShouldLazyLoadMetadata);
  2866. }
  2867. else {
  2868. ReportWarning(DiagnosticHandler, "Unrecognized block found");
  2869. if (Stream.SkipBlock())
  2870. return error("Invalid record");
  2871. }
  2872. // HLSL Change Ends - process the complete stream.
  2873. }
  2874. }
  2875. ErrorOr<std::string> BitcodeReader::parseModuleTriple() {
  2876. if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
  2877. return error("Invalid record");
  2878. SmallVector<uint64_t, 64> Record;
  2879. std::string Triple;
  2880. // Read all the records for this module.
  2881. while (1) {
  2882. // HLSL Change Starts - count skipped blocks
  2883. unsigned skipCount = 0;
  2884. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  2885. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  2886. // HLSL Change End
  2887. switch (Entry.Kind) {
  2888. case BitstreamEntry::SubBlock: // Handled for us already.
  2889. case BitstreamEntry::Error:
  2890. return error("Malformed block");
  2891. case BitstreamEntry::EndBlock:
  2892. return Triple;
  2893. case BitstreamEntry::Record:
  2894. // The interesting case.
  2895. break;
  2896. }
  2897. // Read a record.
  2898. switch (Stream.readRecord(Entry.ID, Record)) {
  2899. default: break; // Default behavior, ignore unknown content.
  2900. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strchr x N]
  2901. std::string S;
  2902. if (convertToString(Record, 0, S))
  2903. return error("Invalid record");
  2904. Triple = S;
  2905. break;
  2906. }
  2907. }
  2908. Record.clear();
  2909. }
  2910. llvm_unreachable("Exit infinite loop");
  2911. }
  2912. ErrorOr<std::string> BitcodeReader::parseTriple() {
  2913. if (std::error_code EC = initStream(nullptr))
  2914. return EC;
  2915. // Sniff for the signature.
  2916. if (Stream.Read(8) != 'B' ||
  2917. Stream.Read(8) != 'C' ||
  2918. Stream.Read(4) != 0x0 ||
  2919. Stream.Read(4) != 0xC ||
  2920. Stream.Read(4) != 0xE ||
  2921. Stream.Read(4) != 0xD)
  2922. return error("Invalid bitcode signature");
  2923. // We expect a number of well-defined blocks, though we don't necessarily
  2924. // need to understand them all.
  2925. while (1) {
  2926. BitstreamEntry Entry = Stream.advance();
  2927. switch (Entry.Kind) {
  2928. case BitstreamEntry::Error:
  2929. return error("Malformed block");
  2930. case BitstreamEntry::EndBlock:
  2931. return std::error_code();
  2932. case BitstreamEntry::SubBlock:
  2933. if (Entry.ID == bitc::MODULE_BLOCK_ID)
  2934. return parseModuleTriple();
  2935. // Ignore other sub-blocks.
  2936. if (Stream.SkipBlock())
  2937. return error("Malformed block");
  2938. ReportWarning(DiagnosticHandler, "Unrecognized block found");
  2939. continue;
  2940. case BitstreamEntry::Record:
  2941. Stream.skipRecord(Entry.ID);
  2942. continue;
  2943. }
  2944. }
  2945. }
  2946. /// Parse metadata attachments.
  2947. std::error_code BitcodeReader::parseMetadataAttachment(Function &F) {
  2948. if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
  2949. return error("Invalid record");
  2950. SmallVector<uint64_t, 64> Record;
  2951. while (1) {
  2952. // HLSL Change Starts - count skipped blocks
  2953. unsigned skipCount = 0;
  2954. BitstreamEntry Entry = Stream.advanceSkippingSubblocks(0, &skipCount);
  2955. if (skipCount) ReportWarning(DiagnosticHandler, "Unrecognized subblock");
  2956. // HLSL Change End
  2957. switch (Entry.Kind) {
  2958. case BitstreamEntry::SubBlock: // Handled for us already.
  2959. case BitstreamEntry::Error:
  2960. return error("Malformed block");
  2961. case BitstreamEntry::EndBlock:
  2962. return std::error_code();
  2963. case BitstreamEntry::Record:
  2964. // The interesting case.
  2965. break;
  2966. }
  2967. // Read a metadata attachment record.
  2968. Record.clear();
  2969. switch (Stream.readRecord(Entry.ID, Record)) {
  2970. default: // Default behavior: ignore.
  2971. break;
  2972. case bitc::METADATA_ATTACHMENT: {
  2973. unsigned RecordLength = Record.size();
  2974. if (Record.empty())
  2975. return error("Invalid record");
  2976. if (RecordLength % 2 == 0) {
  2977. // A function attachment.
  2978. for (unsigned I = 0; I != RecordLength; I += 2) {
  2979. auto K = MDKindMap.find(Record[I]);
  2980. if (K == MDKindMap.end())
  2981. return error("Invalid ID");
  2982. Metadata *MD = MDValueList.getValueFwdRef(Record[I + 1]);
  2983. F.setMetadata(K->second, cast<MDNode>(MD));
  2984. }
  2985. continue;
  2986. }
  2987. // An instruction attachment.
  2988. Instruction *Inst = InstructionList[Record[0]];
  2989. for (unsigned i = 1; i != RecordLength; i = i+2) {
  2990. unsigned Kind = Record[i];
  2991. DenseMap<unsigned, unsigned>::iterator I =
  2992. MDKindMap.find(Kind);
  2993. if (I == MDKindMap.end())
  2994. return error("Invalid ID");
  2995. Metadata *Node = MDValueList.getValueFwdRef(Record[i + 1]);
  2996. if (isa<LocalAsMetadata>(Node))
  2997. // Drop the attachment. This used to be legal, but there's no
  2998. // upgrade path.
  2999. break;
  3000. Inst->setMetadata(I->second, cast<MDNode>(Node));
  3001. if (I->second == LLVMContext::MD_tbaa)
  3002. InstsWithTBAATag.push_back(Inst);
  3003. }
  3004. break;
  3005. }
  3006. }
  3007. }
  3008. }
  3009. static std::error_code typeCheckLoadStoreInst(DiagnosticHandlerFunction DH,
  3010. Type *ValType, Type *PtrType) {
  3011. if (!isa<PointerType>(PtrType))
  3012. return error(DH, "Load/Store operand is not a pointer type");
  3013. Type *ElemType = cast<PointerType>(PtrType)->getElementType();
  3014. if (ValType && ValType != ElemType)
  3015. return error(DH, "Explicit load/store type does not match pointee type of "
  3016. "pointer operand");
  3017. if (!PointerType::isLoadableOrStorableType(ElemType))
  3018. return error(DH, "Cannot load/store from pointer");
  3019. return std::error_code();
  3020. }
  3021. /// Lazily parse the specified function body block.
  3022. std::error_code BitcodeReader::parseFunctionBody(Function *F) {
  3023. if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
  3024. return error("Invalid record");
  3025. InstructionList.clear();
  3026. unsigned ModuleValueListSize = ValueList.size();
  3027. unsigned ModuleMDValueListSize = MDValueList.size();
  3028. // Add all the function arguments to the value table.
  3029. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  3030. ValueList.push_back(I);
  3031. unsigned NextValueNo = ValueList.size();
  3032. BasicBlock *CurBB = nullptr;
  3033. unsigned CurBBNo = 0;
  3034. DebugLoc LastLoc;
  3035. auto getLastInstruction = [&]() -> Instruction * {
  3036. if (CurBB && !CurBB->empty())
  3037. return &CurBB->back();
  3038. else if (CurBBNo && FunctionBBs[CurBBNo - 1] &&
  3039. !FunctionBBs[CurBBNo - 1]->empty())
  3040. return &FunctionBBs[CurBBNo - 1]->back();
  3041. return nullptr;
  3042. };
  3043. // Read all the records.
  3044. SmallVector<uint64_t, 64> Record;
  3045. while (1) {
  3046. BitstreamEntry Entry = Stream.advance();
  3047. switch (Entry.Kind) {
  3048. case BitstreamEntry::Error:
  3049. return error("Malformed block");
  3050. case BitstreamEntry::EndBlock:
  3051. goto OutOfRecordLoop;
  3052. case BitstreamEntry::SubBlock:
  3053. switch (Entry.ID) {
  3054. default: // Skip unknown content.
  3055. if (Stream.SkipBlock())
  3056. return error("Invalid record");
  3057. ReportWarning(DiagnosticHandler, "Unrecognized block found");
  3058. break;
  3059. case bitc::CONSTANTS_BLOCK_ID:
  3060. if (std::error_code EC = parseConstants())
  3061. return EC;
  3062. NextValueNo = ValueList.size();
  3063. break;
  3064. case bitc::VALUE_SYMTAB_BLOCK_ID:
  3065. if (std::error_code EC = parseValueSymbolTable())
  3066. return EC;
  3067. break;
  3068. case bitc::METADATA_ATTACHMENT_ID:
  3069. if (std::error_code EC = parseMetadataAttachment(*F))
  3070. return EC;
  3071. break;
  3072. case bitc::METADATA_BLOCK_ID:
  3073. if (std::error_code EC = parseMetadata())
  3074. return EC;
  3075. break;
  3076. case bitc::USELIST_BLOCK_ID:
  3077. if (std::error_code EC = parseUseLists())
  3078. return EC;
  3079. break;
  3080. }
  3081. continue;
  3082. case BitstreamEntry::Record:
  3083. // The interesting case.
  3084. break;
  3085. }
  3086. // Read a record.
  3087. Record.clear();
  3088. Instruction *I = nullptr;
  3089. unsigned BitCode = Stream.readRecord(Entry.ID, Record);
  3090. switch (BitCode) {
  3091. default: // Default behavior: reject
  3092. return error("Invalid value");
  3093. case bitc::FUNC_CODE_DECLAREBLOCKS: { // DECLAREBLOCKS: [nblocks]
  3094. if (Record.size() < 1 || Record[0] == 0)
  3095. return error("Invalid record");
  3096. // Create all the basic blocks for the function.
  3097. FunctionBBs.resize(Record[0]);
  3098. // See if anything took the address of blocks in this function.
  3099. auto BBFRI = BasicBlockFwdRefs.find(F);
  3100. if (BBFRI == BasicBlockFwdRefs.end()) {
  3101. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  3102. FunctionBBs[i] = BasicBlock::Create(Context, "", F);
  3103. } else {
  3104. auto &BBRefs = BBFRI->second;
  3105. // Check for invalid basic block references.
  3106. if (BBRefs.size() > FunctionBBs.size())
  3107. return error("Invalid ID");
  3108. assert(!BBRefs.empty() && "Unexpected empty array");
  3109. assert(!BBRefs.front() && "Invalid reference to entry block");
  3110. for (unsigned I = 0, E = FunctionBBs.size(), RE = BBRefs.size(); I != E;
  3111. ++I)
  3112. if (I < RE && BBRefs[I]) {
  3113. BBRefs[I]->insertInto(F);
  3114. FunctionBBs[I] = BBRefs[I];
  3115. } else {
  3116. FunctionBBs[I] = BasicBlock::Create(Context, "", F);
  3117. }
  3118. // Erase from the table.
  3119. BasicBlockFwdRefs.erase(BBFRI);
  3120. }
  3121. CurBB = FunctionBBs[0];
  3122. continue;
  3123. }
  3124. case bitc::FUNC_CODE_DEBUG_LOC_AGAIN: // DEBUG_LOC_AGAIN
  3125. // This record indicates that the last instruction is at the same
  3126. // location as the previous instruction with a location.
  3127. I = getLastInstruction();
  3128. if (!I)
  3129. return error("Invalid record");
  3130. I->setDebugLoc(LastLoc);
  3131. I = nullptr;
  3132. continue;
  3133. case bitc::FUNC_CODE_DEBUG_LOC: { // DEBUG_LOC: [line, col, scope, ia]
  3134. I = getLastInstruction();
  3135. if (!I || Record.size() < 4)
  3136. return error("Invalid record");
  3137. unsigned Line = Record[0], Col = Record[1];
  3138. unsigned ScopeID = Record[2], IAID = Record[3];
  3139. MDNode *Scope = nullptr, *IA = nullptr;
  3140. if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
  3141. if (IAID) IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
  3142. LastLoc = DebugLoc::get(Line, Col, Scope, IA);
  3143. I->setDebugLoc(LastLoc);
  3144. I = nullptr;
  3145. continue;
  3146. }
  3147. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opval, ty, opval, opcode]
  3148. unsigned OpNum = 0;
  3149. Value *LHS, *RHS;
  3150. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  3151. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
  3152. OpNum+1 > Record.size())
  3153. return error("Invalid record");
  3154. int Opc = getDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
  3155. if (Opc == -1)
  3156. return error("Invalid record");
  3157. I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
  3158. InstructionList.push_back(I);
  3159. if (OpNum < Record.size()) {
  3160. if (Opc == Instruction::Add ||
  3161. Opc == Instruction::Sub ||
  3162. Opc == Instruction::Mul ||
  3163. Opc == Instruction::Shl) {
  3164. if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
  3165. cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
  3166. if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
  3167. cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
  3168. } else if (Opc == Instruction::SDiv ||
  3169. Opc == Instruction::UDiv ||
  3170. Opc == Instruction::LShr ||
  3171. Opc == Instruction::AShr) {
  3172. if (Record[OpNum] & (1 << bitc::PEO_EXACT))
  3173. cast<BinaryOperator>(I)->setIsExact(true);
  3174. } else if (isa<FPMathOperator>(I)) {
  3175. FastMathFlags FMF = getDecodedFastMathFlags(Record[OpNum]);
  3176. if (FMF.any())
  3177. I->setFastMathFlags(FMF);
  3178. }
  3179. }
  3180. break;
  3181. }
  3182. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opval, opty, destty, castopc]
  3183. unsigned OpNum = 0;
  3184. Value *Op;
  3185. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3186. OpNum+2 != Record.size())
  3187. return error("Invalid record");
  3188. Type *ResTy = getTypeByID(Record[OpNum]);
  3189. int Opc = getDecodedCastOpcode(Record[OpNum + 1]);
  3190. if (Opc == -1 || !ResTy)
  3191. return error("Invalid record");
  3192. Instruction *Temp = nullptr;
  3193. if ((I = UpgradeBitCastInst(Opc, Op, ResTy, Temp))) {
  3194. if (Temp) {
  3195. InstructionList.push_back(Temp);
  3196. CurBB->getInstList().push_back(Temp);
  3197. }
  3198. } else {
  3199. I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
  3200. }
  3201. InstructionList.push_back(I);
  3202. break;
  3203. }
  3204. case bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD:
  3205. case bitc::FUNC_CODE_INST_GEP_OLD:
  3206. case bitc::FUNC_CODE_INST_GEP: { // GEP: type, [n x operands]
  3207. unsigned OpNum = 0;
  3208. Type *Ty;
  3209. bool InBounds;
  3210. if (BitCode == bitc::FUNC_CODE_INST_GEP) {
  3211. InBounds = Record[OpNum++];
  3212. Ty = getTypeByID(Record[OpNum++]);
  3213. } else {
  3214. InBounds = BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP_OLD;
  3215. Ty = nullptr;
  3216. }
  3217. Value *BasePtr;
  3218. if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
  3219. return error("Invalid record");
  3220. if (!Ty)
  3221. Ty = cast<SequentialType>(BasePtr->getType()->getScalarType())
  3222. ->getElementType();
  3223. else if (Ty !=
  3224. cast<SequentialType>(BasePtr->getType()->getScalarType())
  3225. ->getElementType())
  3226. return error(
  3227. "Explicit gep type does not match pointee type of pointer operand");
  3228. SmallVector<Value*, 16> GEPIdx;
  3229. while (OpNum != Record.size()) {
  3230. Value *Op;
  3231. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3232. return error("Invalid record");
  3233. GEPIdx.push_back(Op);
  3234. }
  3235. I = GetElementPtrInst::Create(Ty, BasePtr, GEPIdx);
  3236. InstructionList.push_back(I);
  3237. if (InBounds)
  3238. cast<GetElementPtrInst>(I)->setIsInBounds(true);
  3239. break;
  3240. }
  3241. case bitc::FUNC_CODE_INST_EXTRACTVAL: {
  3242. // EXTRACTVAL: [opty, opval, n x indices]
  3243. unsigned OpNum = 0;
  3244. Value *Agg;
  3245. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  3246. return error("Invalid record");
  3247. unsigned RecSize = Record.size();
  3248. if (OpNum == RecSize)
  3249. return error("EXTRACTVAL: Invalid instruction with 0 indices");
  3250. SmallVector<unsigned, 4> EXTRACTVALIdx;
  3251. Type *CurTy = Agg->getType();
  3252. for (; OpNum != RecSize; ++OpNum) {
  3253. bool IsArray = CurTy->isArrayTy();
  3254. bool IsStruct = CurTy->isStructTy();
  3255. uint64_t Index = Record[OpNum];
  3256. if (!IsStruct && !IsArray)
  3257. return error("EXTRACTVAL: Invalid type");
  3258. if ((unsigned)Index != Index)
  3259. return error("Invalid value");
  3260. if (IsStruct && Index >= CurTy->subtypes().size())
  3261. return error("EXTRACTVAL: Invalid struct index");
  3262. if (IsArray && Index >= CurTy->getArrayNumElements())
  3263. return error("EXTRACTVAL: Invalid array index");
  3264. EXTRACTVALIdx.push_back((unsigned)Index);
  3265. if (IsStruct)
  3266. CurTy = CurTy->subtypes()[Index];
  3267. else
  3268. CurTy = CurTy->subtypes()[0];
  3269. }
  3270. I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
  3271. InstructionList.push_back(I);
  3272. break;
  3273. }
  3274. case bitc::FUNC_CODE_INST_INSERTVAL: {
  3275. // INSERTVAL: [opty, opval, opty, opval, n x indices]
  3276. unsigned OpNum = 0;
  3277. Value *Agg;
  3278. if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
  3279. return error("Invalid record");
  3280. Value *Val;
  3281. if (getValueTypePair(Record, OpNum, NextValueNo, Val))
  3282. return error("Invalid record");
  3283. unsigned RecSize = Record.size();
  3284. if (OpNum == RecSize)
  3285. return error("INSERTVAL: Invalid instruction with 0 indices");
  3286. SmallVector<unsigned, 4> INSERTVALIdx;
  3287. Type *CurTy = Agg->getType();
  3288. for (; OpNum != RecSize; ++OpNum) {
  3289. bool IsArray = CurTy->isArrayTy();
  3290. bool IsStruct = CurTy->isStructTy();
  3291. uint64_t Index = Record[OpNum];
  3292. if (!IsStruct && !IsArray)
  3293. return error("INSERTVAL: Invalid type");
  3294. if ((unsigned)Index != Index)
  3295. return error("Invalid value");
  3296. if (IsStruct && Index >= CurTy->subtypes().size())
  3297. return error("INSERTVAL: Invalid struct index");
  3298. if (IsArray && Index >= CurTy->getArrayNumElements())
  3299. return error("INSERTVAL: Invalid array index");
  3300. INSERTVALIdx.push_back((unsigned)Index);
  3301. if (IsStruct)
  3302. CurTy = CurTy->subtypes()[Index];
  3303. else
  3304. CurTy = CurTy->subtypes()[0];
  3305. }
  3306. if (CurTy != Val->getType())
  3307. return error("Inserted value type doesn't match aggregate type");
  3308. I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
  3309. InstructionList.push_back(I);
  3310. break;
  3311. }
  3312. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
  3313. // obsolete form of select
  3314. // handles select i1 ... in old bitcode
  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. popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
  3320. return error("Invalid record");
  3321. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  3322. InstructionList.push_back(I);
  3323. break;
  3324. }
  3325. case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
  3326. // new form of select
  3327. // handles select i1 or select [N x i1]
  3328. unsigned OpNum = 0;
  3329. Value *TrueVal, *FalseVal, *Cond;
  3330. if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
  3331. popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
  3332. getValueTypePair(Record, OpNum, NextValueNo, Cond))
  3333. return error("Invalid record");
  3334. // select condition can be either i1 or [N x i1]
  3335. if (VectorType* vector_type =
  3336. dyn_cast<VectorType>(Cond->getType())) {
  3337. // expect <n x i1>
  3338. if (vector_type->getElementType() != Type::getInt1Ty(Context))
  3339. return error("Invalid type for value");
  3340. } else {
  3341. // expect i1
  3342. if (Cond->getType() != Type::getInt1Ty(Context))
  3343. return error("Invalid type for value");
  3344. }
  3345. I = SelectInst::Create(Cond, TrueVal, FalseVal);
  3346. InstructionList.push_back(I);
  3347. break;
  3348. }
  3349. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  3350. unsigned OpNum = 0;
  3351. Value *Vec, *Idx;
  3352. if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
  3353. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  3354. return error("Invalid record");
  3355. if (!Vec->getType()->isVectorTy())
  3356. return error("Invalid type for value");
  3357. I = ExtractElementInst::Create(Vec, Idx);
  3358. InstructionList.push_back(I);
  3359. break;
  3360. }
  3361. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  3362. unsigned OpNum = 0;
  3363. Value *Vec, *Elt, *Idx;
  3364. if (getValueTypePair(Record, OpNum, NextValueNo, Vec))
  3365. return error("Invalid record");
  3366. if (!Vec->getType()->isVectorTy())
  3367. return error("Invalid type for value");
  3368. if (popValue(Record, OpNum, NextValueNo,
  3369. cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
  3370. getValueTypePair(Record, OpNum, NextValueNo, Idx))
  3371. return error("Invalid record");
  3372. I = InsertElementInst::Create(Vec, Elt, Idx);
  3373. InstructionList.push_back(I);
  3374. break;
  3375. }
  3376. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
  3377. unsigned OpNum = 0;
  3378. Value *Vec1, *Vec2, *Mask;
  3379. if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
  3380. popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
  3381. return error("Invalid record");
  3382. if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
  3383. return error("Invalid record");
  3384. if (!Vec1->getType()->isVectorTy() || !Vec2->getType()->isVectorTy())
  3385. return error("Invalid type for value");
  3386. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  3387. InstructionList.push_back(I);
  3388. break;
  3389. }
  3390. case bitc::FUNC_CODE_INST_CMP: // CMP: [opty, opval, opval, pred]
  3391. // Old form of ICmp/FCmp returning bool
  3392. // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
  3393. // both legal on vectors but had different behaviour.
  3394. case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
  3395. // FCmp/ICmp returning bool or vector of bool
  3396. unsigned OpNum = 0;
  3397. Value *LHS, *RHS;
  3398. if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
  3399. popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS))
  3400. return error("Invalid record");
  3401. unsigned PredVal = Record[OpNum];
  3402. bool IsFP = LHS->getType()->isFPOrFPVectorTy();
  3403. FastMathFlags FMF;
  3404. if (IsFP && Record.size() > OpNum+1)
  3405. FMF = getDecodedFastMathFlags(Record[++OpNum]);
  3406. if (OpNum+1 != Record.size())
  3407. return error("Invalid record");
  3408. if (LHS->getType()->isFPOrFPVectorTy())
  3409. I = new FCmpInst((FCmpInst::Predicate)PredVal, LHS, RHS);
  3410. else
  3411. I = new ICmpInst((ICmpInst::Predicate)PredVal, LHS, RHS);
  3412. if (FMF.any())
  3413. I->setFastMathFlags(FMF);
  3414. InstructionList.push_back(I);
  3415. break;
  3416. }
  3417. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  3418. {
  3419. unsigned Size = Record.size();
  3420. if (Size == 0) {
  3421. I = ReturnInst::Create(Context);
  3422. InstructionList.push_back(I);
  3423. break;
  3424. }
  3425. unsigned OpNum = 0;
  3426. Value *Op = nullptr;
  3427. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3428. return error("Invalid record");
  3429. if (OpNum != Record.size())
  3430. return error("Invalid record");
  3431. I = ReturnInst::Create(Context, Op);
  3432. InstructionList.push_back(I);
  3433. break;
  3434. }
  3435. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  3436. if (Record.size() != 1 && Record.size() != 3)
  3437. return error("Invalid record");
  3438. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  3439. if (!TrueDest)
  3440. return error("Invalid record");
  3441. if (Record.size() == 1) {
  3442. I = BranchInst::Create(TrueDest);
  3443. InstructionList.push_back(I);
  3444. }
  3445. else {
  3446. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  3447. Value *Cond = getValue(Record, 2, NextValueNo,
  3448. Type::getInt1Ty(Context));
  3449. if (!FalseDest || !Cond)
  3450. return error("Invalid record");
  3451. I = BranchInst::Create(TrueDest, FalseDest, Cond);
  3452. InstructionList.push_back(I);
  3453. }
  3454. break;
  3455. }
  3456. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
  3457. // Check magic
  3458. if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
  3459. // "New" SwitchInst format with case ranges. The changes to write this
  3460. // format were reverted but we still recognize bitcode that uses it.
  3461. // Hopefully someday we will have support for case ranges and can use
  3462. // this format again.
  3463. Type *OpTy = getTypeByID(Record[1]);
  3464. unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
  3465. Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
  3466. BasicBlock *Default = getBasicBlock(Record[3]);
  3467. if (!OpTy || !Cond || !Default)
  3468. return error("Invalid record");
  3469. unsigned NumCases = Record[4];
  3470. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  3471. InstructionList.push_back(SI);
  3472. unsigned CurIdx = 5;
  3473. for (unsigned i = 0; i != NumCases; ++i) {
  3474. SmallVector<ConstantInt*, 1> CaseVals;
  3475. unsigned NumItems = Record[CurIdx++];
  3476. for (unsigned ci = 0; ci != NumItems; ++ci) {
  3477. bool isSingleNumber = Record[CurIdx++];
  3478. APInt Low;
  3479. unsigned ActiveWords = 1;
  3480. if (ValueBitWidth > 64)
  3481. ActiveWords = Record[CurIdx++];
  3482. Low = readWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
  3483. ValueBitWidth);
  3484. CurIdx += ActiveWords;
  3485. if (!isSingleNumber) {
  3486. ActiveWords = 1;
  3487. if (ValueBitWidth > 64)
  3488. ActiveWords = Record[CurIdx++];
  3489. APInt High = readWideAPInt(
  3490. makeArrayRef(&Record[CurIdx], ActiveWords), ValueBitWidth);
  3491. CurIdx += ActiveWords;
  3492. // FIXME: It is not clear whether values in the range should be
  3493. // compared as signed or unsigned values. The partially
  3494. // implemented changes that used this format in the past used
  3495. // unsigned comparisons.
  3496. for ( ; Low.ule(High); ++Low)
  3497. CaseVals.push_back(ConstantInt::get(Context, Low));
  3498. } else
  3499. CaseVals.push_back(ConstantInt::get(Context, Low));
  3500. }
  3501. BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
  3502. for (SmallVector<ConstantInt*, 1>::iterator cvi = CaseVals.begin(),
  3503. cve = CaseVals.end(); cvi != cve; ++cvi)
  3504. SI->addCase(*cvi, DestBB);
  3505. }
  3506. I = SI;
  3507. break;
  3508. }
  3509. // Old SwitchInst format without case ranges.
  3510. if (Record.size() < 3 || (Record.size() & 1) == 0)
  3511. return error("Invalid record");
  3512. Type *OpTy = getTypeByID(Record[0]);
  3513. Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
  3514. BasicBlock *Default = getBasicBlock(Record[2]);
  3515. if (!OpTy || !Cond || !Default)
  3516. return error("Invalid record");
  3517. unsigned NumCases = (Record.size()-3)/2;
  3518. SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
  3519. InstructionList.push_back(SI);
  3520. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  3521. ConstantInt *CaseVal =
  3522. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  3523. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  3524. if (!CaseVal || !DestBB) {
  3525. delete SI;
  3526. return error("Invalid record");
  3527. }
  3528. SI->addCase(CaseVal, DestBB);
  3529. }
  3530. I = SI;
  3531. break;
  3532. }
  3533. case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
  3534. if (Record.size() < 2)
  3535. return error("Invalid record");
  3536. Type *OpTy = getTypeByID(Record[0]);
  3537. Value *Address = getValue(Record, 1, NextValueNo, OpTy);
  3538. if (!OpTy || !Address)
  3539. return error("Invalid record");
  3540. unsigned NumDests = Record.size()-2;
  3541. IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
  3542. InstructionList.push_back(IBI);
  3543. for (unsigned i = 0, e = NumDests; i != e; ++i) {
  3544. if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
  3545. IBI->addDestination(DestBB);
  3546. } else {
  3547. delete IBI;
  3548. return error("Invalid record");
  3549. }
  3550. }
  3551. I = IBI;
  3552. break;
  3553. }
  3554. case bitc::FUNC_CODE_INST_INVOKE: {
  3555. // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
  3556. if (Record.size() < 4)
  3557. return error("Invalid record");
  3558. unsigned OpNum = 0;
  3559. AttributeSet PAL = getAttributes(Record[OpNum++]);
  3560. unsigned CCInfo = Record[OpNum++];
  3561. BasicBlock *NormalBB = getBasicBlock(Record[OpNum++]);
  3562. BasicBlock *UnwindBB = getBasicBlock(Record[OpNum++]);
  3563. FunctionType *FTy = nullptr;
  3564. if (CCInfo >> 13 & 1 &&
  3565. !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
  3566. return error("Explicit invoke type is not a function type");
  3567. Value *Callee;
  3568. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  3569. return error("Invalid record");
  3570. PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
  3571. if (!CalleeTy)
  3572. return error("Callee is not a pointer");
  3573. if (!FTy) {
  3574. FTy = dyn_cast<FunctionType>(CalleeTy->getElementType());
  3575. if (!FTy)
  3576. return error("Callee is not of pointer to function type");
  3577. } else if (CalleeTy->getElementType() != FTy)
  3578. return error("Explicit invoke type does not match pointee type of "
  3579. "callee operand");
  3580. if (Record.size() < FTy->getNumParams() + OpNum)
  3581. return error("Insufficient operands to call");
  3582. SmallVector<Value*, 16> Ops;
  3583. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  3584. Ops.push_back(getValue(Record, OpNum, NextValueNo,
  3585. FTy->getParamType(i)));
  3586. if (!Ops.back())
  3587. return error("Invalid record");
  3588. }
  3589. if (!FTy->isVarArg()) {
  3590. if (Record.size() != OpNum)
  3591. return error("Invalid record");
  3592. } else {
  3593. // Read type/value pairs for varargs params.
  3594. while (OpNum != Record.size()) {
  3595. Value *Op;
  3596. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3597. return error("Invalid record");
  3598. Ops.push_back(Op);
  3599. }
  3600. }
  3601. I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
  3602. InstructionList.push_back(I);
  3603. cast<InvokeInst>(I)
  3604. ->setCallingConv(static_cast<CallingConv::ID>(~(1U << 13) & CCInfo));
  3605. cast<InvokeInst>(I)->setAttributes(PAL);
  3606. break;
  3607. }
  3608. case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
  3609. unsigned Idx = 0;
  3610. Value *Val = nullptr;
  3611. if (getValueTypePair(Record, Idx, NextValueNo, Val))
  3612. return error("Invalid record");
  3613. I = ResumeInst::Create(Val);
  3614. InstructionList.push_back(I);
  3615. break;
  3616. }
  3617. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  3618. I = new UnreachableInst(Context);
  3619. InstructionList.push_back(I);
  3620. break;
  3621. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
  3622. if (Record.size() < 1 || ((Record.size()-1)&1))
  3623. return error("Invalid record");
  3624. Type *Ty = getTypeByID(Record[0]);
  3625. if (!Ty)
  3626. return error("Invalid record");
  3627. PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
  3628. InstructionList.push_back(PN);
  3629. for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
  3630. Value *V;
  3631. // With the new function encoding, it is possible that operands have
  3632. // negative IDs (for forward references). Use a signed VBR
  3633. // representation to keep the encoding small.
  3634. if (UseRelativeIDs)
  3635. V = getValueSigned(Record, 1+i, NextValueNo, Ty);
  3636. else
  3637. V = getValue(Record, 1+i, NextValueNo, Ty);
  3638. BasicBlock *BB = getBasicBlock(Record[2+i]);
  3639. if (!V || !BB)
  3640. return error("Invalid record");
  3641. PN->addIncoming(V, BB);
  3642. }
  3643. I = PN;
  3644. break;
  3645. }
  3646. case bitc::FUNC_CODE_INST_LANDINGPAD:
  3647. case bitc::FUNC_CODE_INST_LANDINGPAD_OLD: {
  3648. // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
  3649. unsigned Idx = 0;
  3650. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD) {
  3651. if (Record.size() < 3)
  3652. return error("Invalid record");
  3653. } else {
  3654. assert(BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD);
  3655. if (Record.size() < 4)
  3656. return error("Invalid record");
  3657. }
  3658. Type *Ty = getTypeByID(Record[Idx++]);
  3659. if (!Ty)
  3660. return error("Invalid record");
  3661. if (BitCode == bitc::FUNC_CODE_INST_LANDINGPAD_OLD) {
  3662. Value *PersFn = nullptr;
  3663. if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
  3664. return error("Invalid record");
  3665. if (!F->hasPersonalityFn())
  3666. F->setPersonalityFn(cast<Constant>(PersFn));
  3667. else if (F->getPersonalityFn() != cast<Constant>(PersFn))
  3668. return error("Personality function mismatch");
  3669. }
  3670. bool IsCleanup = !!Record[Idx++];
  3671. unsigned NumClauses = Record[Idx++];
  3672. LandingPadInst *LP = LandingPadInst::Create(Ty, NumClauses);
  3673. LP->setCleanup(IsCleanup);
  3674. for (unsigned J = 0; J != NumClauses; ++J) {
  3675. LandingPadInst::ClauseType CT =
  3676. LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
  3677. Value *Val;
  3678. if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
  3679. delete LP;
  3680. return error("Invalid record");
  3681. }
  3682. assert((CT != LandingPadInst::Catch ||
  3683. !isa<ArrayType>(Val->getType())) &&
  3684. "Catch clause has a invalid type!");
  3685. assert((CT != LandingPadInst::Filter ||
  3686. isa<ArrayType>(Val->getType())) &&
  3687. "Filter clause has invalid type!");
  3688. LP->addClause(cast<Constant>(Val));
  3689. }
  3690. I = LP;
  3691. InstructionList.push_back(I);
  3692. break;
  3693. }
  3694. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
  3695. if (Record.size() != 4)
  3696. return error("Invalid record");
  3697. uint64_t AlignRecord = Record[3];
  3698. const uint64_t InAllocaMask = uint64_t(1) << 5;
  3699. const uint64_t ExplicitTypeMask = uint64_t(1) << 6;
  3700. const uint64_t FlagMask = InAllocaMask | ExplicitTypeMask;
  3701. bool InAlloca = AlignRecord & InAllocaMask;
  3702. Type *Ty = getTypeByID(Record[0]);
  3703. if ((AlignRecord & ExplicitTypeMask) == 0) {
  3704. auto *PTy = dyn_cast_or_null<PointerType>(Ty);
  3705. if (!PTy)
  3706. return error("Old-style alloca with a non-pointer type");
  3707. Ty = PTy->getElementType();
  3708. }
  3709. Type *OpTy = getTypeByID(Record[1]);
  3710. Value *Size = getFnValueByID(Record[2], OpTy);
  3711. unsigned Align;
  3712. if (std::error_code EC =
  3713. parseAlignmentValue(AlignRecord & ~FlagMask, Align)) {
  3714. return EC;
  3715. }
  3716. if (!Ty || !Size)
  3717. return error("Invalid record");
  3718. AllocaInst *AI = new AllocaInst(Ty, Size, Align);
  3719. AI->setUsedWithInAlloca(InAlloca);
  3720. I = AI;
  3721. InstructionList.push_back(I);
  3722. break;
  3723. }
  3724. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  3725. unsigned OpNum = 0;
  3726. Value *Op;
  3727. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3728. (OpNum + 2 != Record.size() && OpNum + 3 != Record.size()))
  3729. return error("Invalid record");
  3730. Type *Ty = nullptr;
  3731. if (OpNum + 3 == Record.size())
  3732. Ty = getTypeByID(Record[OpNum++]);
  3733. if (std::error_code EC =
  3734. typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
  3735. return EC;
  3736. if (!Ty)
  3737. Ty = cast<PointerType>(Op->getType())->getElementType();
  3738. unsigned Align;
  3739. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3740. return EC;
  3741. I = new LoadInst(Ty, Op, "", Record[OpNum + 1], Align);
  3742. InstructionList.push_back(I);
  3743. break;
  3744. }
  3745. case bitc::FUNC_CODE_INST_LOADATOMIC: {
  3746. // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
  3747. unsigned OpNum = 0;
  3748. Value *Op;
  3749. if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
  3750. (OpNum + 4 != Record.size() && OpNum + 5 != Record.size()))
  3751. return error("Invalid record");
  3752. Type *Ty = nullptr;
  3753. if (OpNum + 5 == Record.size())
  3754. Ty = getTypeByID(Record[OpNum++]);
  3755. if (std::error_code EC =
  3756. typeCheckLoadStoreInst(DiagnosticHandler, Ty, Op->getType()))
  3757. return EC;
  3758. if (!Ty)
  3759. Ty = cast<PointerType>(Op->getType())->getElementType();
  3760. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  3761. if (Ordering == NotAtomic || Ordering == Release ||
  3762. Ordering == AcquireRelease)
  3763. return error("Invalid record");
  3764. if (Ordering != NotAtomic && Record[OpNum] == 0)
  3765. return error("Invalid record");
  3766. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
  3767. unsigned Align;
  3768. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3769. return EC;
  3770. I = new LoadInst(Op, "", Record[OpNum+1], Align, Ordering, SynchScope);
  3771. InstructionList.push_back(I);
  3772. break;
  3773. }
  3774. case bitc::FUNC_CODE_INST_STORE:
  3775. case bitc::FUNC_CODE_INST_STORE_OLD: { // STORE2:[ptrty, ptr, val, align, vol]
  3776. unsigned OpNum = 0;
  3777. Value *Val, *Ptr;
  3778. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3779. (BitCode == bitc::FUNC_CODE_INST_STORE
  3780. ? getValueTypePair(Record, OpNum, NextValueNo, Val)
  3781. : popValue(Record, OpNum, NextValueNo,
  3782. cast<PointerType>(Ptr->getType())->getElementType(),
  3783. Val)) ||
  3784. OpNum + 2 != Record.size())
  3785. return error("Invalid record");
  3786. if (std::error_code EC = typeCheckLoadStoreInst(
  3787. DiagnosticHandler, Val->getType(), Ptr->getType()))
  3788. return EC;
  3789. unsigned Align;
  3790. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3791. return EC;
  3792. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align);
  3793. InstructionList.push_back(I);
  3794. break;
  3795. }
  3796. case bitc::FUNC_CODE_INST_STOREATOMIC:
  3797. case bitc::FUNC_CODE_INST_STOREATOMIC_OLD: {
  3798. // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
  3799. unsigned OpNum = 0;
  3800. Value *Val, *Ptr;
  3801. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3802. (BitCode == bitc::FUNC_CODE_INST_STOREATOMIC
  3803. ? getValueTypePair(Record, OpNum, NextValueNo, Val)
  3804. : popValue(Record, OpNum, NextValueNo,
  3805. cast<PointerType>(Ptr->getType())->getElementType(),
  3806. Val)) ||
  3807. OpNum + 4 != Record.size())
  3808. return error("Invalid record");
  3809. if (std::error_code EC = typeCheckLoadStoreInst(
  3810. DiagnosticHandler, Val->getType(), Ptr->getType()))
  3811. return EC;
  3812. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  3813. if (Ordering == NotAtomic || Ordering == Acquire ||
  3814. Ordering == AcquireRelease)
  3815. return error("Invalid record");
  3816. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
  3817. if (Ordering != NotAtomic && Record[OpNum] == 0)
  3818. return error("Invalid record");
  3819. unsigned Align;
  3820. if (std::error_code EC = parseAlignmentValue(Record[OpNum], Align))
  3821. return EC;
  3822. I = new StoreInst(Val, Ptr, Record[OpNum+1], Align, Ordering, SynchScope);
  3823. InstructionList.push_back(I);
  3824. break;
  3825. }
  3826. case bitc::FUNC_CODE_INST_CMPXCHG_OLD:
  3827. case bitc::FUNC_CODE_INST_CMPXCHG: {
  3828. // CMPXCHG:[ptrty, ptr, cmp, new, vol, successordering, synchscope,
  3829. // failureordering?, isweak?]
  3830. unsigned OpNum = 0;
  3831. Value *Ptr, *Cmp, *New;
  3832. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3833. (BitCode == bitc::FUNC_CODE_INST_CMPXCHG
  3834. ? getValueTypePair(Record, OpNum, NextValueNo, Cmp)
  3835. : popValue(Record, OpNum, NextValueNo,
  3836. cast<PointerType>(Ptr->getType())->getElementType(),
  3837. Cmp)) ||
  3838. popValue(Record, OpNum, NextValueNo, Cmp->getType(), New) ||
  3839. Record.size() < OpNum + 3 || Record.size() > OpNum + 5)
  3840. return error("Invalid record");
  3841. AtomicOrdering SuccessOrdering = getDecodedOrdering(Record[OpNum + 1]);
  3842. if (SuccessOrdering == NotAtomic || SuccessOrdering == Unordered)
  3843. return error("Invalid record");
  3844. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 2]);
  3845. if (std::error_code EC = typeCheckLoadStoreInst(
  3846. DiagnosticHandler, Cmp->getType(), Ptr->getType()))
  3847. return EC;
  3848. AtomicOrdering FailureOrdering;
  3849. if (Record.size() < 7)
  3850. FailureOrdering =
  3851. AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrdering);
  3852. else
  3853. FailureOrdering = getDecodedOrdering(Record[OpNum + 3]);
  3854. I = new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering, FailureOrdering,
  3855. SynchScope);
  3856. cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
  3857. if (Record.size() < 8) {
  3858. // Before weak cmpxchgs existed, the instruction simply returned the
  3859. // value loaded from memory, so bitcode files from that era will be
  3860. // expecting the first component of a modern cmpxchg.
  3861. CurBB->getInstList().push_back(I);
  3862. I = ExtractValueInst::Create(I, 0);
  3863. } else {
  3864. cast<AtomicCmpXchgInst>(I)->setWeak(Record[OpNum+4]);
  3865. }
  3866. InstructionList.push_back(I);
  3867. break;
  3868. }
  3869. case bitc::FUNC_CODE_INST_ATOMICRMW: {
  3870. // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
  3871. unsigned OpNum = 0;
  3872. Value *Ptr, *Val;
  3873. if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
  3874. popValue(Record, OpNum, NextValueNo,
  3875. cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
  3876. OpNum+4 != Record.size())
  3877. return error("Invalid record");
  3878. AtomicRMWInst::BinOp Operation = getDecodedRMWOperation(Record[OpNum]);
  3879. if (Operation < AtomicRMWInst::FIRST_BINOP ||
  3880. Operation > AtomicRMWInst::LAST_BINOP)
  3881. return error("Invalid record");
  3882. AtomicOrdering Ordering = getDecodedOrdering(Record[OpNum + 2]);
  3883. if (Ordering == NotAtomic || Ordering == Unordered)
  3884. return error("Invalid record");
  3885. SynchronizationScope SynchScope = getDecodedSynchScope(Record[OpNum + 3]);
  3886. I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
  3887. cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
  3888. InstructionList.push_back(I);
  3889. break;
  3890. }
  3891. case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
  3892. if (2 != Record.size())
  3893. return error("Invalid record");
  3894. AtomicOrdering Ordering = getDecodedOrdering(Record[0]);
  3895. if (Ordering == NotAtomic || Ordering == Unordered ||
  3896. Ordering == Monotonic)
  3897. return error("Invalid record");
  3898. SynchronizationScope SynchScope = getDecodedSynchScope(Record[1]);
  3899. I = new FenceInst(Context, Ordering, SynchScope);
  3900. InstructionList.push_back(I);
  3901. break;
  3902. }
  3903. case bitc::FUNC_CODE_INST_CALL: {
  3904. // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
  3905. if (Record.size() < 3)
  3906. return error("Invalid record");
  3907. unsigned OpNum = 0;
  3908. AttributeSet PAL = getAttributes(Record[OpNum++]);
  3909. unsigned CCInfo = Record[OpNum++];
  3910. FunctionType *FTy = nullptr;
  3911. if (CCInfo >> 15 & 1 &&
  3912. !(FTy = dyn_cast<FunctionType>(getTypeByID(Record[OpNum++]))))
  3913. return error("Explicit call type is not a function type");
  3914. Value *Callee;
  3915. if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
  3916. return error("Invalid record");
  3917. PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
  3918. if (!OpTy)
  3919. return error("Callee is not a pointer type");
  3920. if (!FTy) {
  3921. FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  3922. if (!FTy)
  3923. return error("Callee is not of pointer to function type");
  3924. } else if (OpTy->getElementType() != FTy)
  3925. return error("Explicit call type does not match pointee type of "
  3926. "callee operand");
  3927. if (Record.size() < FTy->getNumParams() + OpNum)
  3928. return error("Insufficient operands to call");
  3929. SmallVector<Value*, 16> Args;
  3930. // Read the fixed params.
  3931. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
  3932. if (FTy->getParamType(i)->isLabelTy())
  3933. Args.push_back(getBasicBlock(Record[OpNum]));
  3934. else
  3935. Args.push_back(getValue(Record, OpNum, NextValueNo,
  3936. FTy->getParamType(i)));
  3937. if (!Args.back())
  3938. return error("Invalid record");
  3939. }
  3940. // Read type/value pairs for varargs params.
  3941. if (!FTy->isVarArg()) {
  3942. if (OpNum != Record.size())
  3943. return error("Invalid record");
  3944. } else {
  3945. while (OpNum != Record.size()) {
  3946. Value *Op;
  3947. if (getValueTypePair(Record, OpNum, NextValueNo, Op))
  3948. return error("Invalid record");
  3949. Args.push_back(Op);
  3950. }
  3951. }
  3952. I = CallInst::Create(FTy, Callee, Args);
  3953. InstructionList.push_back(I);
  3954. cast<CallInst>(I)->setCallingConv(
  3955. static_cast<CallingConv::ID>((~(1U << 14) & CCInfo) >> 1));
  3956. CallInst::TailCallKind TCK = CallInst::TCK_None;
  3957. if (CCInfo & 1)
  3958. TCK = CallInst::TCK_Tail;
  3959. if (CCInfo & (1 << 14))
  3960. TCK = CallInst::TCK_MustTail;
  3961. cast<CallInst>(I)->setTailCallKind(TCK);
  3962. cast<CallInst>(I)->setAttributes(PAL);
  3963. break;
  3964. }
  3965. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  3966. if (Record.size() < 3)
  3967. return error("Invalid record");
  3968. Type *OpTy = getTypeByID(Record[0]);
  3969. Value *Op = getValue(Record, 1, NextValueNo, OpTy);
  3970. Type *ResTy = getTypeByID(Record[2]);
  3971. if (!OpTy || !Op || !ResTy)
  3972. return error("Invalid record");
  3973. I = new VAArgInst(Op, ResTy);
  3974. InstructionList.push_back(I);
  3975. break;
  3976. }
  3977. }
  3978. // Add instruction to end of current BB. If there is no current BB, reject
  3979. // this file.
  3980. if (!CurBB) {
  3981. delete I;
  3982. return error("Invalid instruction with no BB");
  3983. }
  3984. CurBB->getInstList().push_back(I);
  3985. // If this was a terminator instruction, move to the next block.
  3986. if (isa<TerminatorInst>(I)) {
  3987. ++CurBBNo;
  3988. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : nullptr;
  3989. }
  3990. // Non-void values get registered in the value table for future use.
  3991. if (I && !I->getType()->isVoidTy())
  3992. ValueList.assignValue(I, NextValueNo++);
  3993. }
  3994. OutOfRecordLoop:
  3995. // Check the function list for unresolved values.
  3996. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  3997. if (!A->getParent()) {
  3998. // We found at least one unresolved value. Nuke them all to avoid leaks.
  3999. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  4000. if ((A = dyn_cast_or_null<Argument>(ValueList[i])) && !A->getParent()) {
  4001. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  4002. delete A;
  4003. }
  4004. }
  4005. return error("Never resolved value found in function");
  4006. }
  4007. }
  4008. // FIXME: Check for unresolved forward-declared metadata references
  4009. // and clean up leaks.
  4010. // Trim the value list down to the size it was before we parsed this function.
  4011. ValueList.shrinkTo(ModuleValueListSize);
  4012. MDValueList.shrinkTo(ModuleMDValueListSize);
  4013. std::vector<BasicBlock*>().swap(FunctionBBs);
  4014. return std::error_code();
  4015. }
  4016. /// Find the function body in the bitcode stream
  4017. std::error_code BitcodeReader::findFunctionInStream(
  4018. Function *F,
  4019. DenseMap<Function *, uint64_t>::iterator DeferredFunctionInfoIterator) {
  4020. while (DeferredFunctionInfoIterator->second == 0) {
  4021. if (Stream.AtEndOfStream())
  4022. return error("Could not find function in stream");
  4023. // ParseModule will parse the next body in the stream and set its
  4024. // position in the DeferredFunctionInfo map.
  4025. if (std::error_code EC = parseModule(true))
  4026. return EC;
  4027. }
  4028. return std::error_code();
  4029. }
  4030. //===----------------------------------------------------------------------===//
  4031. // GVMaterializer implementation
  4032. //===----------------------------------------------------------------------===//
  4033. void BitcodeReader::releaseBuffer() { Buffer.release(); }
  4034. std::error_code BitcodeReader::materialize(GlobalValue *GV) {
  4035. if (std::error_code EC = materializeMetadata())
  4036. return EC;
  4037. Function *F = dyn_cast<Function>(GV);
  4038. // If it's not a function or is already material, ignore the request.
  4039. if (!F || !F->isMaterializable())
  4040. return std::error_code();
  4041. DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
  4042. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  4043. // If its position is recorded as 0, its body is somewhere in the stream
  4044. // but we haven't seen it yet.
  4045. if (DFII->second == 0)
  4046. if (std::error_code EC = findFunctionInStream(F, DFII))
  4047. return EC;
  4048. // Move the bit stream to the saved position of the deferred function body.
  4049. Stream.JumpToBit(DFII->second);
  4050. if (std::error_code EC = parseFunctionBody(F))
  4051. return EC;
  4052. F->setIsMaterializable(false);
  4053. if (StripDebugInfo)
  4054. stripDebugInfo(*F);
  4055. // Upgrade any old intrinsic calls in the function.
  4056. for (auto &I : UpgradedIntrinsics) {
  4057. for (auto UI = I.first->user_begin(), UE = I.first->user_end(); UI != UE;) {
  4058. User *U = *UI;
  4059. ++UI;
  4060. if (CallInst *CI = dyn_cast<CallInst>(U))
  4061. UpgradeIntrinsicCall(CI, I.second);
  4062. }
  4063. }
  4064. // Bring in any functions that this function forward-referenced via
  4065. // blockaddresses.
  4066. return materializeForwardReferencedFunctions();
  4067. }
  4068. bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
  4069. const Function *F = dyn_cast<Function>(GV);
  4070. if (!F || F->isDeclaration())
  4071. return false;
  4072. // Dematerializing F would leave dangling references that wouldn't be
  4073. // reconnected on re-materialization.
  4074. if (BlockAddressesTaken.count(F))
  4075. return false;
  4076. return DeferredFunctionInfo.count(const_cast<Function*>(F));
  4077. }
  4078. void BitcodeReader::dematerialize(GlobalValue *GV) {
  4079. Function *F = dyn_cast<Function>(GV);
  4080. // If this function isn't dematerializable, this is a noop.
  4081. if (!F || !isDematerializable(F))
  4082. return;
  4083. assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
  4084. // Just forget the function body, we can remat it later.
  4085. F->dropAllReferences();
  4086. F->setIsMaterializable(true);
  4087. }
  4088. std::error_code BitcodeReader::materializeModule(Module *M) {
  4089. assert(M == TheModule &&
  4090. "Can only Materialize the Module this BitcodeReader is attached to.");
  4091. if (std::error_code EC = materializeMetadata())
  4092. return EC;
  4093. // Promise to materialize all forward references.
  4094. WillMaterializeAllForwardRefs = true;
  4095. // Iterate over the module, deserializing any functions that are still on
  4096. // disk.
  4097. for (Module::iterator F = TheModule->begin(), E = TheModule->end();
  4098. F != E; ++F) {
  4099. if (std::error_code EC = materialize(F))
  4100. return EC;
  4101. }
  4102. // At this point, if there are any function bodies, the current bit is
  4103. // pointing to the END_BLOCK record after them. Now make sure the rest
  4104. // of the bits in the module have been read.
  4105. if (NextUnreadBit)
  4106. parseModule(true);
  4107. // Check that all block address forward references got resolved (as we
  4108. // promised above).
  4109. if (!BasicBlockFwdRefs.empty())
  4110. return error("Never resolved function from blockaddress");
  4111. // Upgrade any intrinsic calls that slipped through (should not happen!) and
  4112. // delete the old functions to clean up. We can't do this unless the entire
  4113. // module is materialized because there could always be another function body
  4114. // with calls to the old function.
  4115. for (auto &I : UpgradedIntrinsics) {
  4116. for (auto *U : I.first->users()) {
  4117. if (CallInst *CI = dyn_cast<CallInst>(U))
  4118. UpgradeIntrinsicCall(CI, I.second);
  4119. }
  4120. if (!I.first->use_empty())
  4121. I.first->replaceAllUsesWith(I.second);
  4122. I.first->eraseFromParent();
  4123. }
  4124. UpgradedIntrinsics.clear();
  4125. for (unsigned I = 0, E = InstsWithTBAATag.size(); I < E; I++)
  4126. UpgradeInstWithTBAATag(InstsWithTBAATag[I]);
  4127. UpgradeDebugInfo(*M);
  4128. // HLSL Change Starts
  4129. if (!Tracker.isDense((uint64_t)(Buffer->getBufferSize()) * 8)) {
  4130. ReportWarning(DiagnosticHandler, "Unused bits in buffer.");
  4131. }
  4132. // HLSL Change Ends
  4133. return std::error_code();
  4134. }
  4135. std::vector<StructType *> BitcodeReader::getIdentifiedStructTypes() const {
  4136. return IdentifiedStructTypes;
  4137. }
  4138. std::error_code
  4139. BitcodeReader::initStream(std::unique_ptr<DataStreamer> Streamer) {
  4140. if (Streamer)
  4141. return initLazyStream(std::move(Streamer));
  4142. return initStreamFromBuffer();
  4143. }
  4144. std::error_code BitcodeReader::initStreamFromBuffer() {
  4145. const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
  4146. const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
  4147. if (Buffer->getBufferSize() & 3)
  4148. return error("Invalid bitcode size"); // HLSL Change - bitcode size is the problem, not the signature per se
  4149. // If we have a wrapper header, parse it and ignore the non-bc file contents.
  4150. // The magic number is 0x0B17C0DE stored in little endian.
  4151. if (isBitcodeWrapper(BufPtr, BufEnd))
  4152. if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
  4153. return error("Invalid bitcode wrapper header");
  4154. StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
  4155. StreamFile->Tracker = &Tracker; // HLSL Change
  4156. Stream.init(&*StreamFile);
  4157. return std::error_code();
  4158. }
  4159. std::error_code
  4160. BitcodeReader::initLazyStream(std::unique_ptr<DataStreamer> Streamer) {
  4161. // Check and strip off the bitcode wrapper; BitstreamReader expects never to
  4162. // see it.
  4163. auto OwnedBytes =
  4164. llvm::make_unique<StreamingMemoryObject>(std::move(Streamer));
  4165. StreamingMemoryObject &Bytes = *OwnedBytes;
  4166. StreamFile = llvm::make_unique<BitstreamReader>(std::move(OwnedBytes));
  4167. Stream.init(&*StreamFile);
  4168. unsigned char buf[16];
  4169. if (Bytes.readBytes(buf, 16, 0) != 16)
  4170. return error("Invalid bitcode signature");
  4171. if (!isBitcode(buf, buf + 16))
  4172. return error("Invalid bitcode signature");
  4173. if (isBitcodeWrapper(buf, buf + 4)) {
  4174. const unsigned char *bitcodeStart = buf;
  4175. const unsigned char *bitcodeEnd = buf + 16;
  4176. SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
  4177. Bytes.dropLeadingBytes(bitcodeStart - buf);
  4178. Bytes.setKnownObjectSize(bitcodeEnd - bitcodeStart);
  4179. }
  4180. return std::error_code();
  4181. }
  4182. namespace {
  4183. class BitcodeErrorCategoryType : public std::error_category {
  4184. const char *name() const LLVM_NOEXCEPT override {
  4185. return "llvm.bitcode";
  4186. }
  4187. std::string message(int IE) const override {
  4188. BitcodeError E = static_cast<BitcodeError>(IE);
  4189. switch (E) {
  4190. case BitcodeError::InvalidBitcodeSignature:
  4191. return "Invalid bitcode signature";
  4192. case BitcodeError::CorruptedBitcode:
  4193. return "Corrupted bitcode";
  4194. }
  4195. llvm_unreachable("Unknown error type!");
  4196. }
  4197. };
  4198. }
  4199. static BitcodeErrorCategoryType g_ErrorCategory; // HLSL Change - not a ManagedStatic
  4200. const std::error_category &llvm::BitcodeErrorCategory() {
  4201. return g_ErrorCategory; // HLSL Change - simple global
  4202. }
  4203. //===----------------------------------------------------------------------===//
  4204. // External interface
  4205. //===----------------------------------------------------------------------===//
  4206. static ErrorOr<std::unique_ptr<Module>>
  4207. getBitcodeModuleImpl(std::unique_ptr<DataStreamer> Streamer, StringRef Name,
  4208. BitcodeReader *R, LLVMContext &Context,
  4209. bool MaterializeAll, bool ShouldLazyLoadMetadata) {
  4210. std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
  4211. M->setMaterializer(R);
  4212. auto cleanupOnError = [&](std::error_code EC) {
  4213. R->releaseBuffer(); // Never take ownership on error.
  4214. return EC;
  4215. };
  4216. // Delay parsing Metadata if ShouldLazyLoadMetadata is true.
  4217. if (std::error_code EC = R->parseBitcodeInto(std::move(Streamer), M.get(),
  4218. ShouldLazyLoadMetadata))
  4219. return cleanupOnError(EC);
  4220. if (MaterializeAll) {
  4221. // Read in the entire module, and destroy the BitcodeReader.
  4222. if (std::error_code EC = M->materializeAllPermanently())
  4223. return cleanupOnError(EC);
  4224. } else {
  4225. // Resolve forward references from blockaddresses.
  4226. if (std::error_code EC = R->materializeForwardReferencedFunctions())
  4227. return cleanupOnError(EC);
  4228. }
  4229. return std::move(M);
  4230. }
  4231. /// \brief Get a lazy one-at-time loading module from bitcode.
  4232. ///
  4233. /// This isn't always used in a lazy context. In particular, it's also used by
  4234. /// \a parseBitcodeFile(). If this is truly lazy, then we need to eagerly pull
  4235. /// in forward-referenced functions from block address references.
  4236. ///
  4237. /// \param[in] MaterializeAll Set to \c true if we should materialize
  4238. /// everything.
  4239. static ErrorOr<std::unique_ptr<Module>>
  4240. getLazyBitcodeModuleImpl(std::unique_ptr<MemoryBuffer> &&Buffer,
  4241. LLVMContext &Context, bool MaterializeAll,
  4242. DiagnosticHandlerFunction DiagnosticHandler,
  4243. bool ShouldLazyLoadMetadata = false) {
  4244. BitcodeReader *R =
  4245. new BitcodeReader(Buffer.get(), Context, DiagnosticHandler);
  4246. ErrorOr<std::unique_ptr<Module>> Ret =
  4247. getBitcodeModuleImpl(nullptr, Buffer->getBufferIdentifier(), R, Context,
  4248. MaterializeAll, ShouldLazyLoadMetadata);
  4249. if (!Ret)
  4250. return Ret;
  4251. Buffer.release(); // The BitcodeReader owns it now.
  4252. return Ret;
  4253. }
  4254. ErrorOr<std::unique_ptr<Module>> llvm::getLazyBitcodeModule(
  4255. std::unique_ptr<MemoryBuffer> &&Buffer, LLVMContext &Context,
  4256. DiagnosticHandlerFunction DiagnosticHandler, bool ShouldLazyLoadMetadata) {
  4257. return getLazyBitcodeModuleImpl(std::move(Buffer), Context, false,
  4258. DiagnosticHandler, ShouldLazyLoadMetadata);
  4259. }
  4260. ErrorOr<std::unique_ptr<Module>> llvm::getStreamedBitcodeModule(
  4261. StringRef Name, std::unique_ptr<DataStreamer> Streamer,
  4262. LLVMContext &Context, DiagnosticHandlerFunction DiagnosticHandler) {
  4263. std::unique_ptr<Module> M = make_unique<Module>(Name, Context);
  4264. BitcodeReader *R = new BitcodeReader(Context, DiagnosticHandler);
  4265. return getBitcodeModuleImpl(std::move(Streamer), Name, R, Context, false,
  4266. false);
  4267. }
  4268. // HLSL Change Starts
  4269. struct report_fatal_error_data {
  4270. report_fatal_error_data(DiagnosticHandlerFunction DH)
  4271. : DiagnosticHandler(DH) {}
  4272. DiagnosticHandlerFunction DiagnosticHandler;
  4273. };
  4274. void report_fatal_error_handler(void *user_datam, const std::string &reason,
  4275. bool gen_crash_diag) {
  4276. report_fatal_error_data *data = (report_fatal_error_data *)user_datam;
  4277. BitcodeDiagnosticInfo BDI(std::error_code(EINVAL, std::system_category()),
  4278. DiagnosticSeverity::DS_Error, reason);
  4279. data->DiagnosticHandler(BDI);
  4280. throw std::exception("Invalid bitcode");
  4281. }
  4282. // HLSL Change Ends
  4283. ErrorOr<std::unique_ptr<Module>>
  4284. llvm::parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context,
  4285. DiagnosticHandlerFunction DiagnosticHandler) {
  4286. // HLSL Change Starts - introduce a ScopedFatalErrorHandler to handle
  4287. // report_fatal_error from readers.
  4288. report_fatal_error_data data(DiagnosticHandler);
  4289. ScopedFatalErrorHandler SFE(report_fatal_error_handler, &data);
  4290. // HLSL Change Ends
  4291. std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
  4292. return getLazyBitcodeModuleImpl(std::move(Buf), Context, true,
  4293. DiagnosticHandler);
  4294. // TODO: Restore the use-lists to the in-memory state when the bitcode was
  4295. // written. We must defer until the Module has been fully materialized.
  4296. }
  4297. std::string
  4298. llvm::getBitcodeTargetTriple(MemoryBufferRef Buffer, LLVMContext &Context,
  4299. DiagnosticHandlerFunction DiagnosticHandler) {
  4300. std::unique_ptr<MemoryBuffer> Buf = MemoryBuffer::getMemBuffer(Buffer, false);
  4301. auto R = llvm::make_unique<BitcodeReader>(Buf.release(), Context,
  4302. DiagnosticHandler);
  4303. ErrorOr<std::string> Triple = R->parseTriple();
  4304. if (Triple.getError())
  4305. return "";
  4306. return Triple.get();
  4307. }