BitcodeReader.cpp 143 KB

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