BitcodeReader.cpp 120 KB

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