BitcodeReader.cpp 130 KB

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