BitcodeReader.cpp 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560
  1. //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by Chris Lattner and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This header defines the BitcodeReader class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Bitcode/ReaderWriter.h"
  14. #include "BitcodeReader.h"
  15. #include "llvm/Constants.h"
  16. #include "llvm/DerivedTypes.h"
  17. #include "llvm/Instructions.h"
  18. #include "llvm/Module.h"
  19. #include "llvm/ParameterAttributes.h"
  20. #include "llvm/ADT/SmallString.h"
  21. #include "llvm/Support/MathExtras.h"
  22. #include "llvm/Support/MemoryBuffer.h"
  23. using namespace llvm;
  24. BitcodeReader::~BitcodeReader() {
  25. delete Buffer;
  26. }
  27. //===----------------------------------------------------------------------===//
  28. // Helper functions to implement forward reference resolution, etc.
  29. //===----------------------------------------------------------------------===//
  30. /// ConvertToString - Convert a string from a record into an std::string, return
  31. /// true on failure.
  32. template<typename StrTy>
  33. static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
  34. StrTy &Result) {
  35. if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
  36. return true;
  37. for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
  38. Result += (char)Record[Idx+i+1];
  39. return false;
  40. }
  41. static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
  42. switch (Val) {
  43. default: // Map unknown/new linkages to external
  44. case 0: return GlobalValue::ExternalLinkage;
  45. case 1: return GlobalValue::WeakLinkage;
  46. case 2: return GlobalValue::AppendingLinkage;
  47. case 3: return GlobalValue::InternalLinkage;
  48. case 4: return GlobalValue::LinkOnceLinkage;
  49. case 5: return GlobalValue::DLLImportLinkage;
  50. case 6: return GlobalValue::DLLExportLinkage;
  51. case 7: return GlobalValue::ExternalWeakLinkage;
  52. }
  53. }
  54. static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
  55. switch (Val) {
  56. default: // Map unknown visibilities to default.
  57. case 0: return GlobalValue::DefaultVisibility;
  58. case 1: return GlobalValue::HiddenVisibility;
  59. case 2: return GlobalValue::ProtectedVisibility;
  60. }
  61. }
  62. static int GetDecodedCastOpcode(unsigned Val) {
  63. switch (Val) {
  64. default: return -1;
  65. case bitc::CAST_TRUNC : return Instruction::Trunc;
  66. case bitc::CAST_ZEXT : return Instruction::ZExt;
  67. case bitc::CAST_SEXT : return Instruction::SExt;
  68. case bitc::CAST_FPTOUI : return Instruction::FPToUI;
  69. case bitc::CAST_FPTOSI : return Instruction::FPToSI;
  70. case bitc::CAST_UITOFP : return Instruction::UIToFP;
  71. case bitc::CAST_SITOFP : return Instruction::SIToFP;
  72. case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
  73. case bitc::CAST_FPEXT : return Instruction::FPExt;
  74. case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
  75. case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
  76. case bitc::CAST_BITCAST : return Instruction::BitCast;
  77. }
  78. }
  79. static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
  80. switch (Val) {
  81. default: return -1;
  82. case bitc::BINOP_ADD: return Instruction::Add;
  83. case bitc::BINOP_SUB: return Instruction::Sub;
  84. case bitc::BINOP_MUL: return Instruction::Mul;
  85. case bitc::BINOP_UDIV: return Instruction::UDiv;
  86. case bitc::BINOP_SDIV:
  87. return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
  88. case bitc::BINOP_UREM: return Instruction::URem;
  89. case bitc::BINOP_SREM:
  90. return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
  91. case bitc::BINOP_SHL: return Instruction::Shl;
  92. case bitc::BINOP_LSHR: return Instruction::LShr;
  93. case bitc::BINOP_ASHR: return Instruction::AShr;
  94. case bitc::BINOP_AND: return Instruction::And;
  95. case bitc::BINOP_OR: return Instruction::Or;
  96. case bitc::BINOP_XOR: return Instruction::Xor;
  97. }
  98. }
  99. namespace {
  100. /// @brief A class for maintaining the slot number definition
  101. /// as a placeholder for the actual definition for forward constants defs.
  102. class ConstantPlaceHolder : public ConstantExpr {
  103. ConstantPlaceHolder(); // DO NOT IMPLEMENT
  104. void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
  105. public:
  106. Use Op;
  107. ConstantPlaceHolder(const Type *Ty)
  108. : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
  109. Op(UndefValue::get(Type::Int32Ty), this) {
  110. }
  111. };
  112. }
  113. Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
  114. const Type *Ty) {
  115. if (Idx >= size()) {
  116. // Insert a bunch of null values.
  117. Uses.resize(Idx+1);
  118. OperandList = &Uses[0];
  119. NumOperands = Idx+1;
  120. }
  121. if (Value *V = Uses[Idx]) {
  122. assert(Ty == V->getType() && "Type mismatch in constant table!");
  123. return cast<Constant>(V);
  124. }
  125. // Create and return a placeholder, which will later be RAUW'd.
  126. Constant *C = new ConstantPlaceHolder(Ty);
  127. Uses[Idx].init(C, this);
  128. return C;
  129. }
  130. Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
  131. if (Idx >= size()) {
  132. // Insert a bunch of null values.
  133. Uses.resize(Idx+1);
  134. OperandList = &Uses[0];
  135. NumOperands = Idx+1;
  136. }
  137. if (Value *V = Uses[Idx]) {
  138. assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
  139. return V;
  140. }
  141. // No type specified, must be invalid reference.
  142. if (Ty == 0) return 0;
  143. // Create and return a placeholder, which will later be RAUW'd.
  144. Value *V = new Argument(Ty);
  145. Uses[Idx].init(V, this);
  146. return V;
  147. }
  148. const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
  149. // If the TypeID is in range, return it.
  150. if (ID < TypeList.size())
  151. return TypeList[ID].get();
  152. if (!isTypeTable) return 0;
  153. // The type table allows forward references. Push as many Opaque types as
  154. // needed to get up to ID.
  155. while (TypeList.size() <= ID)
  156. TypeList.push_back(OpaqueType::get());
  157. return TypeList.back().get();
  158. }
  159. //===----------------------------------------------------------------------===//
  160. // Functions for parsing blocks from the bitcode file
  161. //===----------------------------------------------------------------------===//
  162. bool BitcodeReader::ParseParamAttrBlock() {
  163. if (Stream.EnterSubBlock())
  164. return Error("Malformed block record");
  165. if (!ParamAttrs.empty())
  166. return Error("Multiple PARAMATTR blocks found!");
  167. SmallVector<uint64_t, 64> Record;
  168. ParamAttrsVector Attrs;
  169. // Read all the records.
  170. while (1) {
  171. unsigned Code = Stream.ReadCode();
  172. if (Code == bitc::END_BLOCK) {
  173. if (Stream.ReadBlockEnd())
  174. return Error("Error at end of PARAMATTR block");
  175. return false;
  176. }
  177. if (Code == bitc::ENTER_SUBBLOCK) {
  178. // No known subblocks, always skip them.
  179. Stream.ReadSubBlockID();
  180. if (Stream.SkipBlock())
  181. return Error("Malformed block record");
  182. continue;
  183. }
  184. if (Code == bitc::DEFINE_ABBREV) {
  185. Stream.ReadAbbrevRecord();
  186. continue;
  187. }
  188. // Read a record.
  189. Record.clear();
  190. switch (Stream.ReadRecord(Code, Record)) {
  191. default: // Default behavior: ignore.
  192. break;
  193. case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
  194. if (Record.size() & 1)
  195. return Error("Invalid ENTRY record");
  196. ParamAttrsWithIndex PAWI;
  197. for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
  198. PAWI.index = Record[i];
  199. PAWI.attrs = Record[i+1];
  200. Attrs.push_back(PAWI);
  201. }
  202. ParamAttrs.push_back(ParamAttrsList::get(Attrs));
  203. Attrs.clear();
  204. break;
  205. }
  206. }
  207. }
  208. }
  209. bool BitcodeReader::ParseTypeTable() {
  210. if (Stream.EnterSubBlock())
  211. return Error("Malformed block record");
  212. if (!TypeList.empty())
  213. return Error("Multiple TYPE_BLOCKs found!");
  214. SmallVector<uint64_t, 64> Record;
  215. unsigned NumRecords = 0;
  216. // Read all the records for this type table.
  217. while (1) {
  218. unsigned Code = Stream.ReadCode();
  219. if (Code == bitc::END_BLOCK) {
  220. if (NumRecords != TypeList.size())
  221. return Error("Invalid type forward reference in TYPE_BLOCK");
  222. if (Stream.ReadBlockEnd())
  223. return Error("Error at end of type table block");
  224. return false;
  225. }
  226. if (Code == bitc::ENTER_SUBBLOCK) {
  227. // No known subblocks, always skip them.
  228. Stream.ReadSubBlockID();
  229. if (Stream.SkipBlock())
  230. return Error("Malformed block record");
  231. continue;
  232. }
  233. if (Code == bitc::DEFINE_ABBREV) {
  234. Stream.ReadAbbrevRecord();
  235. continue;
  236. }
  237. // Read a record.
  238. Record.clear();
  239. const Type *ResultTy = 0;
  240. switch (Stream.ReadRecord(Code, Record)) {
  241. default: // Default behavior: unknown type.
  242. ResultTy = 0;
  243. break;
  244. case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
  245. // TYPE_CODE_NUMENTRY contains a count of the number of types in the
  246. // type list. This allows us to reserve space.
  247. if (Record.size() < 1)
  248. return Error("Invalid TYPE_CODE_NUMENTRY record");
  249. TypeList.reserve(Record[0]);
  250. continue;
  251. case bitc::TYPE_CODE_VOID: // VOID
  252. ResultTy = Type::VoidTy;
  253. break;
  254. case bitc::TYPE_CODE_FLOAT: // FLOAT
  255. ResultTy = Type::FloatTy;
  256. break;
  257. case bitc::TYPE_CODE_DOUBLE: // DOUBLE
  258. ResultTy = Type::DoubleTy;
  259. break;
  260. case bitc::TYPE_CODE_LABEL: // LABEL
  261. ResultTy = Type::LabelTy;
  262. break;
  263. case bitc::TYPE_CODE_OPAQUE: // OPAQUE
  264. ResultTy = 0;
  265. break;
  266. case bitc::TYPE_CODE_INTEGER: // INTEGER: [width]
  267. if (Record.size() < 1)
  268. return Error("Invalid Integer type record");
  269. ResultTy = IntegerType::get(Record[0]);
  270. break;
  271. case bitc::TYPE_CODE_POINTER: // POINTER: [pointee type]
  272. if (Record.size() < 1)
  273. return Error("Invalid POINTER type record");
  274. ResultTy = PointerType::get(getTypeByID(Record[0], true));
  275. break;
  276. case bitc::TYPE_CODE_FUNCTION: {
  277. // FUNCTION: [vararg, retty, #pararms, paramty N]
  278. if (Record.size() < 3 || Record.size() < Record[2]+3)
  279. return Error("Invalid FUNCTION type record");
  280. std::vector<const Type*> ArgTys;
  281. for (unsigned i = 0, e = Record[2]; i != e; ++i)
  282. ArgTys.push_back(getTypeByID(Record[3+i], true));
  283. // FIXME: PARAM TYS.
  284. ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
  285. Record[0]);
  286. break;
  287. }
  288. case bitc::TYPE_CODE_STRUCT: { // STRUCT: [ispacked, #elts, eltty x N]
  289. if (Record.size() < 2 || Record.size() < Record[1]+2)
  290. return Error("Invalid STRUCT type record");
  291. std::vector<const Type*> EltTys;
  292. for (unsigned i = 0, e = Record[1]; i != e; ++i)
  293. EltTys.push_back(getTypeByID(Record[2+i], true));
  294. ResultTy = StructType::get(EltTys, Record[0]);
  295. break;
  296. }
  297. case bitc::TYPE_CODE_ARRAY: // ARRAY: [numelts, eltty]
  298. if (Record.size() < 2)
  299. return Error("Invalid ARRAY type record");
  300. ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
  301. break;
  302. case bitc::TYPE_CODE_VECTOR: // VECTOR: [numelts, eltty]
  303. if (Record.size() < 2)
  304. return Error("Invalid VECTOR type record");
  305. ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
  306. break;
  307. }
  308. if (NumRecords == TypeList.size()) {
  309. // If this is a new type slot, just append it.
  310. TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
  311. ++NumRecords;
  312. } else if (ResultTy == 0) {
  313. // Otherwise, this was forward referenced, so an opaque type was created,
  314. // but the result type is actually just an opaque. Leave the one we
  315. // created previously.
  316. ++NumRecords;
  317. } else {
  318. // Otherwise, this was forward referenced, so an opaque type was created.
  319. // Resolve the opaque type to the real type now.
  320. assert(NumRecords < TypeList.size() && "Typelist imbalance");
  321. const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
  322. // Don't directly push the new type on the Tab. Instead we want to replace
  323. // the opaque type we previously inserted with the new concrete value. The
  324. // refinement from the abstract (opaque) type to the new type causes all
  325. // uses of the abstract type to use the concrete type (NewTy). This will
  326. // also cause the opaque type to be deleted.
  327. const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
  328. // This should have replaced the old opaque type with the new type in the
  329. // value table... or with a preexisting type that was already in the
  330. // system. Let's just make sure it did.
  331. assert(TypeList[NumRecords-1].get() != OldTy &&
  332. "refineAbstractType didn't work!");
  333. }
  334. }
  335. }
  336. bool BitcodeReader::ParseTypeSymbolTable() {
  337. if (Stream.EnterSubBlock())
  338. return Error("Malformed block record");
  339. SmallVector<uint64_t, 64> Record;
  340. // Read all the records for this type table.
  341. std::string TypeName;
  342. while (1) {
  343. unsigned Code = Stream.ReadCode();
  344. if (Code == bitc::END_BLOCK) {
  345. if (Stream.ReadBlockEnd())
  346. return Error("Error at end of type symbol table block");
  347. return false;
  348. }
  349. if (Code == bitc::ENTER_SUBBLOCK) {
  350. // No known subblocks, always skip them.
  351. Stream.ReadSubBlockID();
  352. if (Stream.SkipBlock())
  353. return Error("Malformed block record");
  354. continue;
  355. }
  356. if (Code == bitc::DEFINE_ABBREV) {
  357. Stream.ReadAbbrevRecord();
  358. continue;
  359. }
  360. // Read a record.
  361. Record.clear();
  362. switch (Stream.ReadRecord(Code, Record)) {
  363. default: // Default behavior: unknown type.
  364. break;
  365. case bitc::TST_CODE_ENTRY: // TST_ENTRY: [typeid, namelen, namechar x N]
  366. if (ConvertToString(Record, 1, TypeName))
  367. return Error("Invalid TST_ENTRY record");
  368. unsigned TypeID = Record[0];
  369. if (TypeID >= TypeList.size())
  370. return Error("Invalid Type ID in TST_ENTRY record");
  371. TheModule->addTypeName(TypeName, TypeList[TypeID].get());
  372. TypeName.clear();
  373. break;
  374. }
  375. }
  376. }
  377. bool BitcodeReader::ParseValueSymbolTable() {
  378. if (Stream.EnterSubBlock())
  379. return Error("Malformed block record");
  380. SmallVector<uint64_t, 64> Record;
  381. // Read all the records for this value table.
  382. SmallString<128> ValueName;
  383. while (1) {
  384. unsigned Code = Stream.ReadCode();
  385. if (Code == bitc::END_BLOCK) {
  386. if (Stream.ReadBlockEnd())
  387. return Error("Error at end of value symbol table block");
  388. return false;
  389. }
  390. if (Code == bitc::ENTER_SUBBLOCK) {
  391. // No known subblocks, always skip them.
  392. Stream.ReadSubBlockID();
  393. if (Stream.SkipBlock())
  394. return Error("Malformed block record");
  395. continue;
  396. }
  397. if (Code == bitc::DEFINE_ABBREV) {
  398. Stream.ReadAbbrevRecord();
  399. continue;
  400. }
  401. // Read a record.
  402. Record.clear();
  403. switch (Stream.ReadRecord(Code, Record)) {
  404. default: // Default behavior: unknown type.
  405. break;
  406. case bitc::VST_CODE_ENTRY: { // VST_ENTRY: [valueid, namelen, namechar x N]
  407. if (ConvertToString(Record, 1, ValueName))
  408. return Error("Invalid TST_ENTRY record");
  409. unsigned ValueID = Record[0];
  410. if (ValueID >= ValueList.size())
  411. return Error("Invalid Value ID in VST_ENTRY record");
  412. Value *V = ValueList[ValueID];
  413. V->setName(&ValueName[0], ValueName.size());
  414. ValueName.clear();
  415. break;
  416. }
  417. case bitc::VST_CODE_BBENTRY: {
  418. if (ConvertToString(Record, 1, ValueName))
  419. return Error("Invalid VST_BBENTRY record");
  420. BasicBlock *BB = getBasicBlock(Record[0]);
  421. if (BB == 0)
  422. return Error("Invalid BB ID in VST_BBENTRY record");
  423. BB->setName(&ValueName[0], ValueName.size());
  424. ValueName.clear();
  425. break;
  426. }
  427. }
  428. }
  429. }
  430. /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
  431. /// the LSB for dense VBR encoding.
  432. static uint64_t DecodeSignRotatedValue(uint64_t V) {
  433. if ((V & 1) == 0)
  434. return V >> 1;
  435. if (V != 1)
  436. return -(V >> 1);
  437. // There is no such thing as -0 with integers. "-0" really means MININT.
  438. return 1ULL << 63;
  439. }
  440. /// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
  441. /// values and aliases that we can.
  442. bool BitcodeReader::ResolveGlobalAndAliasInits() {
  443. std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
  444. std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
  445. GlobalInitWorklist.swap(GlobalInits);
  446. AliasInitWorklist.swap(AliasInits);
  447. while (!GlobalInitWorklist.empty()) {
  448. unsigned ValID = GlobalInitWorklist.back().second;
  449. if (ValID >= ValueList.size()) {
  450. // Not ready to resolve this yet, it requires something later in the file.
  451. GlobalInits.push_back(GlobalInitWorklist.back());
  452. } else {
  453. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  454. GlobalInitWorklist.back().first->setInitializer(C);
  455. else
  456. return Error("Global variable initializer is not a constant!");
  457. }
  458. GlobalInitWorklist.pop_back();
  459. }
  460. while (!AliasInitWorklist.empty()) {
  461. unsigned ValID = AliasInitWorklist.back().second;
  462. if (ValID >= ValueList.size()) {
  463. AliasInits.push_back(AliasInitWorklist.back());
  464. } else {
  465. if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
  466. AliasInitWorklist.back().first->setAliasee(C);
  467. else
  468. return Error("Alias initializer is not a constant!");
  469. }
  470. AliasInitWorklist.pop_back();
  471. }
  472. return false;
  473. }
  474. bool BitcodeReader::ParseConstants() {
  475. if (Stream.EnterSubBlock())
  476. return Error("Malformed block record");
  477. SmallVector<uint64_t, 64> Record;
  478. // Read all the records for this value table.
  479. const Type *CurTy = Type::Int32Ty;
  480. unsigned NextCstNo = ValueList.size();
  481. while (1) {
  482. unsigned Code = Stream.ReadCode();
  483. if (Code == bitc::END_BLOCK) {
  484. if (NextCstNo != ValueList.size())
  485. return Error("Invalid constant reference!");
  486. if (Stream.ReadBlockEnd())
  487. return Error("Error at end of constants block");
  488. return false;
  489. }
  490. if (Code == bitc::ENTER_SUBBLOCK) {
  491. // No known subblocks, always skip them.
  492. Stream.ReadSubBlockID();
  493. if (Stream.SkipBlock())
  494. return Error("Malformed block record");
  495. continue;
  496. }
  497. if (Code == bitc::DEFINE_ABBREV) {
  498. Stream.ReadAbbrevRecord();
  499. continue;
  500. }
  501. // Read a record.
  502. Record.clear();
  503. Value *V = 0;
  504. switch (Stream.ReadRecord(Code, Record)) {
  505. default: // Default behavior: unknown constant
  506. case bitc::CST_CODE_UNDEF: // UNDEF
  507. V = UndefValue::get(CurTy);
  508. break;
  509. case bitc::CST_CODE_SETTYPE: // SETTYPE: [typeid]
  510. if (Record.empty())
  511. return Error("Malformed CST_SETTYPE record");
  512. if (Record[0] >= TypeList.size())
  513. return Error("Invalid Type ID in CST_SETTYPE record");
  514. CurTy = TypeList[Record[0]];
  515. continue; // Skip the ValueList manipulation.
  516. case bitc::CST_CODE_NULL: // NULL
  517. V = Constant::getNullValue(CurTy);
  518. break;
  519. case bitc::CST_CODE_INTEGER: // INTEGER: [intval]
  520. if (!isa<IntegerType>(CurTy) || Record.empty())
  521. return Error("Invalid CST_INTEGER record");
  522. V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
  523. break;
  524. case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
  525. if (!isa<IntegerType>(CurTy) || Record.empty() ||
  526. Record.size() < Record[0]+1)
  527. return Error("Invalid WIDE_INTEGER record");
  528. unsigned NumWords = Record[0];
  529. SmallVector<uint64_t, 8> Words;
  530. Words.resize(NumWords);
  531. for (unsigned i = 0; i != NumWords; ++i)
  532. Words[i] = DecodeSignRotatedValue(Record[i+1]);
  533. V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
  534. NumWords, &Words[0]));
  535. break;
  536. }
  537. case bitc::CST_CODE_FLOAT: // FLOAT: [fpval]
  538. if (Record.empty())
  539. return Error("Invalid FLOAT record");
  540. if (CurTy == Type::FloatTy)
  541. V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
  542. else if (CurTy == Type::DoubleTy)
  543. V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
  544. else
  545. V = UndefValue::get(CurTy);
  546. break;
  547. case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
  548. if (Record.empty() || Record.size() < Record[0]+1)
  549. return Error("Invalid CST_AGGREGATE record");
  550. unsigned Size = Record[0];
  551. std::vector<Constant*> Elts;
  552. if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
  553. for (unsigned i = 0; i != Size; ++i)
  554. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
  555. STy->getElementType(i)));
  556. V = ConstantStruct::get(STy, Elts);
  557. } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
  558. const Type *EltTy = ATy->getElementType();
  559. for (unsigned i = 0; i != Size; ++i)
  560. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
  561. V = ConstantArray::get(ATy, Elts);
  562. } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
  563. const Type *EltTy = VTy->getElementType();
  564. for (unsigned i = 0; i != Size; ++i)
  565. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
  566. V = ConstantVector::get(Elts);
  567. } else {
  568. V = UndefValue::get(CurTy);
  569. }
  570. break;
  571. }
  572. case bitc::CST_CODE_CE_BINOP: { // CE_BINOP: [opcode, opval, opval]
  573. if (Record.size() < 3) return Error("Invalid CE_BINOP record");
  574. int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
  575. if (Opc < 0) {
  576. V = UndefValue::get(CurTy); // Unknown binop.
  577. } else {
  578. Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
  579. Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
  580. V = ConstantExpr::get(Opc, LHS, RHS);
  581. }
  582. break;
  583. }
  584. case bitc::CST_CODE_CE_CAST: { // CE_CAST: [opcode, opty, opval]
  585. if (Record.size() < 3) return Error("Invalid CE_CAST record");
  586. int Opc = GetDecodedCastOpcode(Record[0]);
  587. if (Opc < 0) {
  588. V = UndefValue::get(CurTy); // Unknown cast.
  589. } else {
  590. const Type *OpTy = getTypeByID(Record[1]);
  591. Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
  592. V = ConstantExpr::getCast(Opc, Op, CurTy);
  593. }
  594. break;
  595. }
  596. case bitc::CST_CODE_CE_GEP: { // CE_GEP: [n x operands]
  597. if ((Record.size() & 1) == 0) return Error("Invalid CE_GEP record");
  598. SmallVector<Constant*, 16> Elts;
  599. for (unsigned i = 1, e = Record.size(); i != e; i += 2) {
  600. const Type *ElTy = getTypeByID(Record[i]);
  601. if (!ElTy) return Error("Invalid CE_GEP record");
  602. Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
  603. }
  604. V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
  605. break;
  606. }
  607. case bitc::CST_CODE_CE_SELECT: // CE_SELECT: [opval#, opval#, opval#]
  608. if (Record.size() < 3) return Error("Invalid CE_SELECT record");
  609. V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
  610. Type::Int1Ty),
  611. ValueList.getConstantFwdRef(Record[1],CurTy),
  612. ValueList.getConstantFwdRef(Record[2],CurTy));
  613. break;
  614. case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
  615. if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
  616. const VectorType *OpTy =
  617. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  618. if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
  619. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  620. Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
  621. OpTy->getElementType());
  622. V = ConstantExpr::getExtractElement(Op0, Op1);
  623. break;
  624. }
  625. case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
  626. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  627. if (Record.size() < 3 || OpTy == 0)
  628. return Error("Invalid CE_INSERTELT record");
  629. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  630. Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
  631. OpTy->getElementType());
  632. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
  633. V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
  634. break;
  635. }
  636. case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
  637. const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
  638. if (Record.size() < 3 || OpTy == 0)
  639. return Error("Invalid CE_INSERTELT record");
  640. Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
  641. Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
  642. const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
  643. Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
  644. V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
  645. break;
  646. }
  647. case bitc::CST_CODE_CE_CMP: { // CE_CMP: [opty, opval, opval, pred]
  648. if (Record.size() < 4) return Error("Invalid CE_CMP record");
  649. const Type *OpTy = getTypeByID(Record[0]);
  650. if (OpTy == 0) return Error("Invalid CE_CMP record");
  651. Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
  652. Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
  653. if (OpTy->isFloatingPoint())
  654. V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
  655. else
  656. V = ConstantExpr::getICmp(Record[3], Op0, Op1);
  657. break;
  658. }
  659. }
  660. ValueList.AssignValue(V, NextCstNo);
  661. ++NextCstNo;
  662. }
  663. }
  664. /// RememberAndSkipFunctionBody - When we see the block for a function body,
  665. /// remember where it is and then skip it. This lets us lazily deserialize the
  666. /// functions.
  667. bool BitcodeReader::RememberAndSkipFunctionBody() {
  668. // Get the function we are talking about.
  669. if (FunctionsWithBodies.empty())
  670. return Error("Insufficient function protos");
  671. Function *Fn = FunctionsWithBodies.back();
  672. FunctionsWithBodies.pop_back();
  673. // Save the current stream state.
  674. uint64_t CurBit = Stream.GetCurrentBitNo();
  675. DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
  676. // Set the functions linkage to GhostLinkage so we know it is lazily
  677. // deserialized.
  678. Fn->setLinkage(GlobalValue::GhostLinkage);
  679. // Skip over the function block for now.
  680. if (Stream.SkipBlock())
  681. return Error("Malformed block record");
  682. return false;
  683. }
  684. bool BitcodeReader::ParseModule(const std::string &ModuleID) {
  685. // Reject multiple MODULE_BLOCK's in a single bitstream.
  686. if (TheModule)
  687. return Error("Multiple MODULE_BLOCKs in same stream");
  688. if (Stream.EnterSubBlock())
  689. return Error("Malformed block record");
  690. // Otherwise, create the module.
  691. TheModule = new Module(ModuleID);
  692. SmallVector<uint64_t, 64> Record;
  693. std::vector<std::string> SectionTable;
  694. // Read all the records for this module.
  695. while (!Stream.AtEndOfStream()) {
  696. unsigned Code = Stream.ReadCode();
  697. if (Code == bitc::END_BLOCK) {
  698. if (Stream.ReadBlockEnd())
  699. return Error("Error at end of module block");
  700. // Patch the initializers for globals and aliases up.
  701. ResolveGlobalAndAliasInits();
  702. if (!GlobalInits.empty() || !AliasInits.empty())
  703. return Error("Malformed global initializer set");
  704. if (!FunctionsWithBodies.empty())
  705. return Error("Too few function bodies found");
  706. // Force deallocation of memory for these vectors to favor the client that
  707. // want lazy deserialization.
  708. std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
  709. std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
  710. std::vector<Function*>().swap(FunctionsWithBodies);
  711. return false;
  712. }
  713. if (Code == bitc::ENTER_SUBBLOCK) {
  714. switch (Stream.ReadSubBlockID()) {
  715. default: // Skip unknown content.
  716. if (Stream.SkipBlock())
  717. return Error("Malformed block record");
  718. break;
  719. case bitc::PARAMATTR_BLOCK_ID:
  720. if (ParseParamAttrBlock())
  721. return true;
  722. break;
  723. case bitc::TYPE_BLOCK_ID:
  724. if (ParseTypeTable())
  725. return true;
  726. break;
  727. case bitc::TYPE_SYMTAB_BLOCK_ID:
  728. if (ParseTypeSymbolTable())
  729. return true;
  730. break;
  731. case bitc::VALUE_SYMTAB_BLOCK_ID:
  732. if (ParseValueSymbolTable())
  733. return true;
  734. break;
  735. case bitc::CONSTANTS_BLOCK_ID:
  736. if (ParseConstants() || ResolveGlobalAndAliasInits())
  737. return true;
  738. break;
  739. case bitc::FUNCTION_BLOCK_ID:
  740. // If this is the first function body we've seen, reverse the
  741. // FunctionsWithBodies list.
  742. if (!HasReversedFunctionsWithBodies) {
  743. std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
  744. HasReversedFunctionsWithBodies = true;
  745. }
  746. if (RememberAndSkipFunctionBody())
  747. return true;
  748. break;
  749. }
  750. continue;
  751. }
  752. if (Code == bitc::DEFINE_ABBREV) {
  753. Stream.ReadAbbrevRecord();
  754. continue;
  755. }
  756. // Read a record.
  757. switch (Stream.ReadRecord(Code, Record)) {
  758. default: break; // Default behavior, ignore unknown content.
  759. case bitc::MODULE_CODE_VERSION: // VERSION: [version#]
  760. if (Record.size() < 1)
  761. return Error("Malformed MODULE_CODE_VERSION");
  762. // Only version #0 is supported so far.
  763. if (Record[0] != 0)
  764. return Error("Unknown bitstream version!");
  765. break;
  766. case bitc::MODULE_CODE_TRIPLE: { // TRIPLE: [strlen, strchr x N]
  767. std::string S;
  768. if (ConvertToString(Record, 0, S))
  769. return Error("Invalid MODULE_CODE_TRIPLE record");
  770. TheModule->setTargetTriple(S);
  771. break;
  772. }
  773. case bitc::MODULE_CODE_DATALAYOUT: { // DATALAYOUT: [strlen, strchr x N]
  774. std::string S;
  775. if (ConvertToString(Record, 0, S))
  776. return Error("Invalid MODULE_CODE_DATALAYOUT record");
  777. TheModule->setDataLayout(S);
  778. break;
  779. }
  780. case bitc::MODULE_CODE_ASM: { // ASM: [strlen, strchr x N]
  781. std::string S;
  782. if (ConvertToString(Record, 0, S))
  783. return Error("Invalid MODULE_CODE_ASM record");
  784. TheModule->setModuleInlineAsm(S);
  785. break;
  786. }
  787. case bitc::MODULE_CODE_DEPLIB: { // DEPLIB: [strlen, strchr x N]
  788. std::string S;
  789. if (ConvertToString(Record, 0, S))
  790. return Error("Invalid MODULE_CODE_DEPLIB record");
  791. TheModule->addLibrary(S);
  792. break;
  793. }
  794. case bitc::MODULE_CODE_SECTIONNAME: { // SECTIONNAME: [strlen, strchr x N]
  795. std::string S;
  796. if (ConvertToString(Record, 0, S))
  797. return Error("Invalid MODULE_CODE_SECTIONNAME record");
  798. SectionTable.push_back(S);
  799. break;
  800. }
  801. // GLOBALVAR: [type, isconst, initid,
  802. // linkage, alignment, section, visibility, threadlocal]
  803. case bitc::MODULE_CODE_GLOBALVAR: {
  804. if (Record.size() < 6)
  805. return Error("Invalid MODULE_CODE_GLOBALVAR record");
  806. const Type *Ty = getTypeByID(Record[0]);
  807. if (!isa<PointerType>(Ty))
  808. return Error("Global not a pointer type!");
  809. Ty = cast<PointerType>(Ty)->getElementType();
  810. bool isConstant = Record[1];
  811. GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
  812. unsigned Alignment = (1 << Record[4]) >> 1;
  813. std::string Section;
  814. if (Record[5]) {
  815. if (Record[5]-1 >= SectionTable.size())
  816. return Error("Invalid section ID");
  817. Section = SectionTable[Record[5]-1];
  818. }
  819. GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
  820. if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
  821. bool isThreadLocal = false;
  822. if (Record.size() >= 7) isThreadLocal = Record[7];
  823. GlobalVariable *NewGV =
  824. new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
  825. NewGV->setAlignment(Alignment);
  826. if (!Section.empty())
  827. NewGV->setSection(Section);
  828. NewGV->setVisibility(Visibility);
  829. NewGV->setThreadLocal(isThreadLocal);
  830. ValueList.push_back(NewGV);
  831. // Remember which value to use for the global initializer.
  832. if (unsigned InitID = Record[2])
  833. GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
  834. break;
  835. }
  836. // FUNCTION: [type, callingconv, isproto, linkage, alignment, section,
  837. // visibility]
  838. case bitc::MODULE_CODE_FUNCTION: {
  839. if (Record.size() < 7)
  840. return Error("Invalid MODULE_CODE_FUNCTION record");
  841. const Type *Ty = getTypeByID(Record[0]);
  842. if (!isa<PointerType>(Ty))
  843. return Error("Function not a pointer type!");
  844. const FunctionType *FTy =
  845. dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  846. if (!FTy)
  847. return Error("Function not a pointer to function type!");
  848. Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
  849. "", TheModule);
  850. Func->setCallingConv(Record[1]);
  851. bool isProto = Record[2];
  852. Func->setLinkage(GetDecodedLinkage(Record[3]));
  853. Func->setAlignment((1 << Record[4]) >> 1);
  854. if (Record[5]) {
  855. if (Record[5]-1 >= SectionTable.size())
  856. return Error("Invalid section ID");
  857. Func->setSection(SectionTable[Record[5]-1]);
  858. }
  859. Func->setVisibility(GetDecodedVisibility(Record[6]));
  860. ValueList.push_back(Func);
  861. // If this is a function with a body, remember the prototype we are
  862. // creating now, so that we can match up the body with them later.
  863. if (!isProto)
  864. FunctionsWithBodies.push_back(Func);
  865. break;
  866. }
  867. // ALIAS: [alias type, aliasee val#, linkage]
  868. case bitc::MODULE_CODE_ALIAS: {
  869. if (Record.size() < 3)
  870. return Error("Invalid MODULE_ALIAS record");
  871. const Type *Ty = getTypeByID(Record[0]);
  872. if (!isa<PointerType>(Ty))
  873. return Error("Function not a pointer type!");
  874. GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
  875. "", 0, TheModule);
  876. ValueList.push_back(NewGA);
  877. AliasInits.push_back(std::make_pair(NewGA, Record[1]));
  878. break;
  879. }
  880. /// MODULE_CODE_PURGEVALS: [numvals]
  881. case bitc::MODULE_CODE_PURGEVALS:
  882. // Trim down the value list to the specified size.
  883. if (Record.size() < 1 || Record[0] > ValueList.size())
  884. return Error("Invalid MODULE_PURGEVALS record");
  885. ValueList.shrinkTo(Record[0]);
  886. break;
  887. }
  888. Record.clear();
  889. }
  890. return Error("Premature end of bitstream");
  891. }
  892. bool BitcodeReader::ParseBitcode() {
  893. TheModule = 0;
  894. if (Buffer->getBufferSize() & 3)
  895. return Error("Bitcode stream should be a multiple of 4 bytes in length");
  896. unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
  897. Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
  898. // Sniff for the signature.
  899. if (Stream.Read(8) != 'B' ||
  900. Stream.Read(8) != 'C' ||
  901. Stream.Read(4) != 0x0 ||
  902. Stream.Read(4) != 0xC ||
  903. Stream.Read(4) != 0xE ||
  904. Stream.Read(4) != 0xD)
  905. return Error("Invalid bitcode signature");
  906. // We expect a number of well-defined blocks, though we don't necessarily
  907. // need to understand them all.
  908. while (!Stream.AtEndOfStream()) {
  909. unsigned Code = Stream.ReadCode();
  910. if (Code != bitc::ENTER_SUBBLOCK)
  911. return Error("Invalid record at top-level");
  912. unsigned BlockID = Stream.ReadSubBlockID();
  913. // We only know the MODULE subblock ID.
  914. if (BlockID == bitc::MODULE_BLOCK_ID) {
  915. if (ParseModule(Buffer->getBufferIdentifier()))
  916. return true;
  917. } else if (Stream.SkipBlock()) {
  918. return Error("Malformed block record");
  919. }
  920. }
  921. return false;
  922. }
  923. bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
  924. // If it already is material, ignore the request.
  925. if (!F->hasNotBeenReadFromBytecode()) return false;
  926. DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
  927. DeferredFunctionInfo.find(F);
  928. assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
  929. // Move the bit stream to the saved position of the deferred function body and
  930. // restore the real linkage type for the function.
  931. Stream.JumpToBit(DFII->second.first);
  932. F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
  933. DeferredFunctionInfo.erase(DFII);
  934. if (ParseFunctionBody(F)) {
  935. if (ErrInfo) *ErrInfo = ErrorString;
  936. return true;
  937. }
  938. return false;
  939. }
  940. Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
  941. DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
  942. DeferredFunctionInfo.begin();
  943. while (!DeferredFunctionInfo.empty()) {
  944. Function *F = (*I++).first;
  945. assert(F->hasNotBeenReadFromBytecode() &&
  946. "Deserialized function found in map!");
  947. if (materializeFunction(F, ErrInfo))
  948. return 0;
  949. }
  950. return TheModule;
  951. }
  952. /// ParseFunctionBody - Lazily parse the specified function body block.
  953. bool BitcodeReader::ParseFunctionBody(Function *F) {
  954. if (Stream.EnterSubBlock())
  955. return Error("Malformed block record");
  956. unsigned ModuleValueListSize = ValueList.size();
  957. // Add all the function arguments to the value table.
  958. for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
  959. ValueList.push_back(I);
  960. unsigned NextValueNo = ValueList.size();
  961. BasicBlock *CurBB = 0;
  962. unsigned CurBBNo = 0;
  963. // Read all the records.
  964. SmallVector<uint64_t, 64> Record;
  965. while (1) {
  966. unsigned Code = Stream.ReadCode();
  967. if (Code == bitc::END_BLOCK) {
  968. if (Stream.ReadBlockEnd())
  969. return Error("Error at end of function block");
  970. break;
  971. }
  972. if (Code == bitc::ENTER_SUBBLOCK) {
  973. switch (Stream.ReadSubBlockID()) {
  974. default: // Skip unknown content.
  975. if (Stream.SkipBlock())
  976. return Error("Malformed block record");
  977. break;
  978. case bitc::CONSTANTS_BLOCK_ID:
  979. if (ParseConstants()) return true;
  980. NextValueNo = ValueList.size();
  981. break;
  982. case bitc::VALUE_SYMTAB_BLOCK_ID:
  983. if (ParseValueSymbolTable()) return true;
  984. break;
  985. }
  986. continue;
  987. }
  988. if (Code == bitc::DEFINE_ABBREV) {
  989. Stream.ReadAbbrevRecord();
  990. continue;
  991. }
  992. // Read a record.
  993. Record.clear();
  994. Instruction *I = 0;
  995. switch (Stream.ReadRecord(Code, Record)) {
  996. default: // Default behavior: reject
  997. return Error("Unknown instruction");
  998. case bitc::FUNC_CODE_DECLAREBLOCKS: // DECLAREBLOCKS: [nblocks]
  999. if (Record.size() < 1 || Record[0] == 0)
  1000. return Error("Invalid DECLAREBLOCKS record");
  1001. // Create all the basic blocks for the function.
  1002. FunctionBBs.resize(Record[0]);
  1003. for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
  1004. FunctionBBs[i] = new BasicBlock("", F);
  1005. CurBB = FunctionBBs[0];
  1006. continue;
  1007. case bitc::FUNC_CODE_INST_BINOP: { // BINOP: [opcode, ty, opval, opval]
  1008. if (Record.size() < 4) return Error("Invalid BINOP record");
  1009. const Type *Ty = getTypeByID(Record[1]);
  1010. int Opc = GetDecodedBinaryOpcode(Record[0], Ty);
  1011. Value *LHS = getFnValueByID(Record[2], Ty);
  1012. Value *RHS = getFnValueByID(Record[3], Ty);
  1013. if (Opc == -1 || Ty == 0 || LHS == 0 || RHS == 0)
  1014. return Error("Invalid BINOP record");
  1015. I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
  1016. break;
  1017. }
  1018. case bitc::FUNC_CODE_INST_CAST: { // CAST: [opcode, ty, opty, opval]
  1019. if (Record.size() < 4) return Error("Invalid CAST record");
  1020. int Opc = GetDecodedCastOpcode(Record[0]);
  1021. const Type *ResTy = getTypeByID(Record[1]);
  1022. const Type *OpTy = getTypeByID(Record[2]);
  1023. Value *Op = getFnValueByID(Record[3], OpTy);
  1024. if (Opc == -1 || ResTy == 0 || OpTy == 0 || Op == 0)
  1025. return Error("Invalid CAST record");
  1026. I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
  1027. break;
  1028. }
  1029. case bitc::FUNC_CODE_INST_GEP: { // GEP: [n, n x operands]
  1030. if (Record.size() < 2 || (Record.size() & 1))
  1031. return Error("Invalid GEP record");
  1032. const Type *OpTy = getTypeByID(Record[0]);
  1033. Value *Op = getFnValueByID(Record[1], OpTy);
  1034. if (OpTy == 0 || Op == 0)
  1035. return Error("Invalid GEP record");
  1036. SmallVector<Value*, 16> GEPIdx;
  1037. for (unsigned i = 1, e = Record.size()/2; i != e; ++i) {
  1038. const Type *IdxTy = getTypeByID(Record[i*2]);
  1039. Value *Idx = getFnValueByID(Record[i*2+1], IdxTy);
  1040. if (IdxTy == 0 || Idx == 0)
  1041. return Error("Invalid GEP record");
  1042. GEPIdx.push_back(Idx);
  1043. }
  1044. I = new GetElementPtrInst(Op, &GEPIdx[0], GEPIdx.size());
  1045. break;
  1046. }
  1047. case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [ty, opval, opval, opval]
  1048. if (Record.size() < 4) return Error("Invalid SELECT record");
  1049. const Type *Ty = getTypeByID(Record[0]);
  1050. Value *Cond = getFnValueByID(Record[1], Type::Int1Ty);
  1051. Value *LHS = getFnValueByID(Record[2], Ty);
  1052. Value *RHS = getFnValueByID(Record[3], Ty);
  1053. if (Ty == 0 || Cond == 0 || LHS == 0 || RHS == 0)
  1054. return Error("Invalid SELECT record");
  1055. I = new SelectInst(Cond, LHS, RHS);
  1056. break;
  1057. }
  1058. case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
  1059. if (Record.size() < 3) return Error("Invalid EXTRACTELT record");
  1060. const Type *OpTy = getTypeByID(Record[0]);
  1061. Value *Vec = getFnValueByID(Record[1], OpTy);
  1062. Value *Idx = getFnValueByID(Record[2], Type::Int32Ty);
  1063. if (OpTy == 0 || Vec == 0 || Idx == 0)
  1064. return Error("Invalid EXTRACTELT record");
  1065. I = new ExtractElementInst(Vec, Idx);
  1066. break;
  1067. }
  1068. case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
  1069. if (Record.size() < 4) return Error("Invalid INSERTELT record");
  1070. const VectorType *OpTy =
  1071. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1072. if (OpTy == 0) return Error("Invalid INSERTELT record");
  1073. Value *Vec = getFnValueByID(Record[1], OpTy);
  1074. Value *Elt = getFnValueByID(Record[2], OpTy->getElementType());
  1075. Value *Idx = getFnValueByID(Record[3], Type::Int32Ty);
  1076. if (Vec == 0 || Elt == 0 || Idx == 0)
  1077. return Error("Invalid INSERTELT record");
  1078. I = new InsertElementInst(Vec, Elt, Idx);
  1079. break;
  1080. }
  1081. case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [ty,opval,opval,opval]
  1082. if (Record.size() < 4) return Error("Invalid SHUFFLEVEC record");
  1083. const VectorType *OpTy =
  1084. dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
  1085. if (OpTy == 0) return Error("Invalid SHUFFLEVEC record");
  1086. Value *Vec1 = getFnValueByID(Record[1], OpTy);
  1087. Value *Vec2 = getFnValueByID(Record[2], OpTy);
  1088. Value *Mask = getFnValueByID(Record[3],
  1089. VectorType::get(Type::Int32Ty,
  1090. OpTy->getNumElements()));
  1091. if (Vec1 == 0 || Vec2 == 0 || Mask == 0)
  1092. return Error("Invalid SHUFFLEVEC record");
  1093. I = new ShuffleVectorInst(Vec1, Vec2, Mask);
  1094. break;
  1095. }
  1096. case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
  1097. if (Record.size() < 4) return Error("Invalid CMP record");
  1098. const Type *OpTy = getTypeByID(Record[0]);
  1099. Value *LHS = getFnValueByID(Record[1], OpTy);
  1100. Value *RHS = getFnValueByID(Record[2], OpTy);
  1101. if (OpTy == 0 || LHS == 0 || RHS == 0)
  1102. return Error("Invalid CMP record");
  1103. if (OpTy->isFPOrFPVector())
  1104. I = new FCmpInst((FCmpInst::Predicate)Record[3], LHS, RHS);
  1105. else
  1106. I = new ICmpInst((ICmpInst::Predicate)Record[3], LHS, RHS);
  1107. break;
  1108. }
  1109. case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
  1110. if (Record.size() == 0) {
  1111. I = new ReturnInst();
  1112. break;
  1113. }
  1114. if (Record.size() == 2) {
  1115. const Type *OpTy = getTypeByID(Record[0]);
  1116. Value *Op = getFnValueByID(Record[1], OpTy);
  1117. if (!OpTy || !Op)
  1118. return Error("Invalid RET record");
  1119. I = new ReturnInst(Op);
  1120. break;
  1121. }
  1122. return Error("Invalid RET record");
  1123. case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
  1124. if (Record.size() != 1 && Record.size() != 3)
  1125. return Error("Invalid BR record");
  1126. BasicBlock *TrueDest = getBasicBlock(Record[0]);
  1127. if (TrueDest == 0)
  1128. return Error("Invalid BR record");
  1129. if (Record.size() == 1)
  1130. I = new BranchInst(TrueDest);
  1131. else {
  1132. BasicBlock *FalseDest = getBasicBlock(Record[1]);
  1133. Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
  1134. if (FalseDest == 0 || Cond == 0)
  1135. return Error("Invalid BR record");
  1136. I = new BranchInst(TrueDest, FalseDest, Cond);
  1137. }
  1138. break;
  1139. }
  1140. case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
  1141. if (Record.size() < 3 || (Record.size() & 1) == 0)
  1142. return Error("Invalid SWITCH record");
  1143. const Type *OpTy = getTypeByID(Record[0]);
  1144. Value *Cond = getFnValueByID(Record[1], OpTy);
  1145. BasicBlock *Default = getBasicBlock(Record[2]);
  1146. if (OpTy == 0 || Cond == 0 || Default == 0)
  1147. return Error("Invalid SWITCH record");
  1148. unsigned NumCases = (Record.size()-3)/2;
  1149. SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
  1150. for (unsigned i = 0, e = NumCases; i != e; ++i) {
  1151. ConstantInt *CaseVal =
  1152. dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
  1153. BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
  1154. if (CaseVal == 0 || DestBB == 0) {
  1155. delete SI;
  1156. return Error("Invalid SWITCH record!");
  1157. }
  1158. SI->addCase(CaseVal, DestBB);
  1159. }
  1160. I = SI;
  1161. break;
  1162. }
  1163. case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
  1164. if (Record.size() < 5)
  1165. return Error("Invalid INVOKE record");
  1166. unsigned CCInfo = Record[0];
  1167. const PointerType *CalleeTy =
  1168. dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
  1169. Value *Callee = getFnValueByID(Record[2], CalleeTy);
  1170. BasicBlock *NormalBB = getBasicBlock(Record[3]);
  1171. BasicBlock *UnwindBB = getBasicBlock(Record[4]);
  1172. if (CalleeTy == 0 || Callee == 0 || NormalBB == 0 || UnwindBB == 0)
  1173. return Error("Invalid INVOKE record");
  1174. const FunctionType *FTy =
  1175. dyn_cast<FunctionType>(CalleeTy->getElementType());
  1176. // Check that the right number of fixed parameters are here.
  1177. if (FTy == 0 || Record.size() < 5+FTy->getNumParams())
  1178. return Error("Invalid INVOKE record");
  1179. SmallVector<Value*, 16> Ops;
  1180. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
  1181. Ops.push_back(getFnValueByID(Record[5+i], FTy->getParamType(i)));
  1182. if (Ops.back() == 0)
  1183. return Error("Invalid INVOKE record");
  1184. }
  1185. unsigned FirstVarargParam = 5+FTy->getNumParams();
  1186. if (FTy->isVarArg()) {
  1187. // Read type/value pairs for varargs params.
  1188. if ((Record.size()-FirstVarargParam) & 1)
  1189. return Error("Invalid INVOKE record");
  1190. for (unsigned i = FirstVarargParam, e = Record.size(); i != e; i += 2) {
  1191. const Type *ArgTy = getTypeByID(Record[i]);
  1192. Ops.push_back(getFnValueByID(Record[i+1], ArgTy));
  1193. if (Ops.back() == 0 || ArgTy == 0)
  1194. return Error("Invalid INVOKE record");
  1195. }
  1196. } else {
  1197. if (Record.size() != FirstVarargParam)
  1198. return Error("Invalid INVOKE record");
  1199. }
  1200. I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
  1201. cast<InvokeInst>(I)->setCallingConv(CCInfo);
  1202. break;
  1203. }
  1204. case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
  1205. I = new UnwindInst();
  1206. break;
  1207. case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
  1208. I = new UnreachableInst();
  1209. break;
  1210. case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, #ops, val0,bb0, ...]
  1211. if (Record.size() < 2 || Record.size() < 2+Record[1] || (Record[1]&1))
  1212. return Error("Invalid PHI record");
  1213. const Type *Ty = getTypeByID(Record[0]);
  1214. if (!Ty) return Error("Invalid PHI record");
  1215. PHINode *PN = new PHINode(Ty);
  1216. PN->reserveOperandSpace(Record[1]);
  1217. for (unsigned i = 0, e = Record[1]; i != e; i += 2) {
  1218. Value *V = getFnValueByID(Record[2+i], Ty);
  1219. BasicBlock *BB = getBasicBlock(Record[3+i]);
  1220. if (!V || !BB) return Error("Invalid PHI record");
  1221. PN->addIncoming(V, BB);
  1222. }
  1223. I = PN;
  1224. break;
  1225. }
  1226. case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
  1227. if (Record.size() < 3)
  1228. return Error("Invalid MALLOC record");
  1229. const PointerType *Ty =
  1230. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1231. Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
  1232. unsigned Align = Record[2];
  1233. if (!Ty || !Size) return Error("Invalid MALLOC record");
  1234. I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  1235. break;
  1236. }
  1237. case bitc::FUNC_CODE_INST_FREE: { // FREE: [opty, op]
  1238. if (Record.size() < 2)
  1239. return Error("Invalid FREE record");
  1240. const Type *OpTy = getTypeByID(Record[0]);
  1241. Value *Op = getFnValueByID(Record[1], OpTy);
  1242. if (!OpTy || !Op)
  1243. return Error("Invalid FREE record");
  1244. I = new FreeInst(Op);
  1245. break;
  1246. }
  1247. case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
  1248. if (Record.size() < 3)
  1249. return Error("Invalid ALLOCA record");
  1250. const PointerType *Ty =
  1251. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1252. Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
  1253. unsigned Align = Record[2];
  1254. if (!Ty || !Size) return Error("Invalid ALLOCA record");
  1255. I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
  1256. break;
  1257. }
  1258. case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
  1259. if (Record.size() < 4)
  1260. return Error("Invalid LOAD record");
  1261. const Type *OpTy = getTypeByID(Record[0]);
  1262. Value *Op = getFnValueByID(Record[1], OpTy);
  1263. if (!OpTy || !Op)
  1264. return Error("Invalid LOAD record");
  1265. I = new LoadInst(Op, "", Record[3], (1 << Record[2]) >> 1);
  1266. break;
  1267. }
  1268. case bitc::FUNC_CODE_INST_STORE: { // STORE:[ptrty,val,ptr, align, vol]
  1269. if (Record.size() < 5)
  1270. return Error("Invalid LOAD record");
  1271. const PointerType *OpTy =
  1272. dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
  1273. Value *Op = getFnValueByID(Record[1], OpTy ? OpTy->getElementType() : 0);
  1274. Value *Ptr = getFnValueByID(Record[2], OpTy);
  1275. if (!OpTy || !Op || !Ptr)
  1276. return Error("Invalid STORE record");
  1277. I = new StoreInst(Op, Ptr, (1 << Record[3]) >> 1, Record[4]);
  1278. break;
  1279. }
  1280. case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
  1281. if (Record.size() < 3)
  1282. return Error("Invalid CALL record");
  1283. unsigned CCInfo = Record[0];
  1284. const PointerType *OpTy =
  1285. dyn_cast_or_null<PointerType>(getTypeByID(Record[1]));
  1286. const FunctionType *FTy = 0;
  1287. if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
  1288. Value *Callee = getFnValueByID(Record[2], OpTy);
  1289. if (!FTy || !Callee || Record.size() < FTy->getNumParams()+3)
  1290. return Error("Invalid CALL record");
  1291. SmallVector<Value*, 16> Args;
  1292. // Read the fixed params.
  1293. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i) {
  1294. Args.push_back(getFnValueByID(Record[i+3], FTy->getParamType(i)));
  1295. if (Args.back() == 0) return Error("Invalid CALL record");
  1296. }
  1297. // Read type/value pairs for varargs params.
  1298. unsigned NextArg = FTy->getNumParams()+3;
  1299. if (!FTy->isVarArg()) {
  1300. if (NextArg != Record.size())
  1301. return Error("Invalid CALL record");
  1302. } else {
  1303. if ((Record.size()-NextArg) & 1)
  1304. return Error("Invalid CALL record");
  1305. for (unsigned e = Record.size(); NextArg != e; NextArg += 2) {
  1306. Args.push_back(getFnValueByID(Record[NextArg+1],
  1307. getTypeByID(Record[NextArg])));
  1308. if (Args.back() == 0) return Error("Invalid CALL record");
  1309. }
  1310. }
  1311. I = new CallInst(Callee, &Args[0], Args.size());
  1312. cast<CallInst>(I)->setCallingConv(CCInfo>>1);
  1313. cast<CallInst>(I)->setTailCall(CCInfo & 1);
  1314. break;
  1315. }
  1316. case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
  1317. if (Record.size() < 3)
  1318. return Error("Invalid VAARG record");
  1319. const Type *OpTy = getTypeByID(Record[0]);
  1320. Value *Op = getFnValueByID(Record[1], OpTy);
  1321. const Type *ResTy = getTypeByID(Record[2]);
  1322. if (!OpTy || !Op || !ResTy)
  1323. return Error("Invalid VAARG record");
  1324. I = new VAArgInst(Op, ResTy);
  1325. break;
  1326. }
  1327. }
  1328. // Add instruction to end of current BB. If there is no current BB, reject
  1329. // this file.
  1330. if (CurBB == 0) {
  1331. delete I;
  1332. return Error("Invalid instruction with no BB");
  1333. }
  1334. CurBB->getInstList().push_back(I);
  1335. // If this was a terminator instruction, move to the next block.
  1336. if (isa<TerminatorInst>(I)) {
  1337. ++CurBBNo;
  1338. CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
  1339. }
  1340. // Non-void values get registered in the value table for future use.
  1341. if (I && I->getType() != Type::VoidTy)
  1342. ValueList.AssignValue(I, NextValueNo++);
  1343. }
  1344. // Check the function list for unresolved values.
  1345. if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
  1346. if (A->getParent() == 0) {
  1347. // We found at least one unresolved value. Nuke them all to avoid leaks.
  1348. for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
  1349. if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
  1350. A->replaceAllUsesWith(UndefValue::get(A->getType()));
  1351. delete A;
  1352. }
  1353. }
  1354. }
  1355. return Error("Never resolved value found in function!");
  1356. }
  1357. // Trim the value list down to the size it was before we parsed this function.
  1358. ValueList.shrinkTo(ModuleValueListSize);
  1359. std::vector<BasicBlock*>().swap(FunctionBBs);
  1360. return false;
  1361. }
  1362. //===----------------------------------------------------------------------===//
  1363. // External interface
  1364. //===----------------------------------------------------------------------===//
  1365. /// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
  1366. ///
  1367. ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
  1368. std::string *ErrMsg) {
  1369. BitcodeReader *R = new BitcodeReader(Buffer);
  1370. if (R->ParseBitcode()) {
  1371. if (ErrMsg)
  1372. *ErrMsg = R->getErrorString();
  1373. // Don't let the BitcodeReader dtor delete 'Buffer'.
  1374. R->releaseMemoryBuffer();
  1375. delete R;
  1376. return 0;
  1377. }
  1378. return R;
  1379. }
  1380. /// ParseBitcodeFile - Read the specified bitcode file, returning the module.
  1381. /// If an error occurs, return null and fill in *ErrMsg if non-null.
  1382. Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
  1383. BitcodeReader *R;
  1384. R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
  1385. if (!R) return 0;
  1386. // Read the whole module, get a pointer to it, tell ModuleProvider not to
  1387. // delete it when its dtor is run.
  1388. Module *M = R->releaseModule(ErrMsg);
  1389. // Don't let the BitcodeReader dtor delete 'Buffer'.
  1390. R->releaseMemoryBuffer();
  1391. delete R;
  1392. return M;
  1393. }