BitcodeReader.cpp 106 KB

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