BitcodeReader.cpp 120 KB

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