Reader.cpp 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343
  1. //===- Reader.cpp - Code to read bytecode files ---------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file was developed by the LLVM research group and is distributed under
  6. // the University of Illinois Open Source License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This library implements the functionality defined in llvm/Bytecode/Reader.h
  11. //
  12. // Note that this library should be as fast as possible, reentrant, and
  13. // threadsafe!!
  14. //
  15. // TODO: Allow passing in an option to ignore the symbol table
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "Reader.h"
  19. #include "llvm/Bytecode/BytecodeHandler.h"
  20. #include "llvm/BasicBlock.h"
  21. #include "llvm/CallingConv.h"
  22. #include "llvm/Constants.h"
  23. #include "llvm/Instructions.h"
  24. #include "llvm/SymbolTable.h"
  25. #include "llvm/Bytecode/Format.h"
  26. #include "llvm/Config/alloca.h"
  27. #include "llvm/Support/GetElementPtrTypeIterator.h"
  28. #include "llvm/Support/Compressor.h"
  29. #include "llvm/Support/MathExtras.h"
  30. #include "llvm/ADT/StringExtras.h"
  31. #include <sstream>
  32. #include <algorithm>
  33. using namespace llvm;
  34. namespace {
  35. /// @brief A class for maintaining the slot number definition
  36. /// as a placeholder for the actual definition for forward constants defs.
  37. class ConstantPlaceHolder : public ConstantExpr {
  38. ConstantPlaceHolder(); // DO NOT IMPLEMENT
  39. void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
  40. public:
  41. Use Op;
  42. ConstantPlaceHolder(const Type *Ty)
  43. : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
  44. Op(UndefValue::get(Type::IntTy), this) {
  45. }
  46. };
  47. }
  48. // Provide some details on error
  49. inline void BytecodeReader::error(std::string err) {
  50. err += " (Vers=" ;
  51. err += itostr(RevisionNum) ;
  52. err += ", Pos=" ;
  53. err += itostr(At-MemStart);
  54. err += ")";
  55. throw err;
  56. }
  57. //===----------------------------------------------------------------------===//
  58. // Bytecode Reading Methods
  59. //===----------------------------------------------------------------------===//
  60. /// Determine if the current block being read contains any more data.
  61. inline bool BytecodeReader::moreInBlock() {
  62. return At < BlockEnd;
  63. }
  64. /// Throw an error if we've read past the end of the current block
  65. inline void BytecodeReader::checkPastBlockEnd(const char * block_name) {
  66. if (At > BlockEnd)
  67. error(std::string("Attempt to read past the end of ") + block_name +
  68. " block.");
  69. }
  70. /// Align the buffer position to a 32 bit boundary
  71. inline void BytecodeReader::align32() {
  72. if (hasAlignment) {
  73. BufPtr Save = At;
  74. At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
  75. if (At > Save)
  76. if (Handler) Handler->handleAlignment(At - Save);
  77. if (At > BlockEnd)
  78. error("Ran out of data while aligning!");
  79. }
  80. }
  81. /// Read a whole unsigned integer
  82. inline unsigned BytecodeReader::read_uint() {
  83. if (At+4 > BlockEnd)
  84. error("Ran out of data reading uint!");
  85. At += 4;
  86. return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
  87. }
  88. /// Read a variable-bit-rate encoded unsigned integer
  89. inline unsigned BytecodeReader::read_vbr_uint() {
  90. unsigned Shift = 0;
  91. unsigned Result = 0;
  92. BufPtr Save = At;
  93. do {
  94. if (At == BlockEnd)
  95. error("Ran out of data reading vbr_uint!");
  96. Result |= (unsigned)((*At++) & 0x7F) << Shift;
  97. Shift += 7;
  98. } while (At[-1] & 0x80);
  99. if (Handler) Handler->handleVBR32(At-Save);
  100. return Result;
  101. }
  102. /// Read a variable-bit-rate encoded unsigned 64-bit integer.
  103. inline uint64_t BytecodeReader::read_vbr_uint64() {
  104. unsigned Shift = 0;
  105. uint64_t Result = 0;
  106. BufPtr Save = At;
  107. do {
  108. if (At == BlockEnd)
  109. error("Ran out of data reading vbr_uint64!");
  110. Result |= (uint64_t)((*At++) & 0x7F) << Shift;
  111. Shift += 7;
  112. } while (At[-1] & 0x80);
  113. if (Handler) Handler->handleVBR64(At-Save);
  114. return Result;
  115. }
  116. /// Read a variable-bit-rate encoded signed 64-bit integer.
  117. inline int64_t BytecodeReader::read_vbr_int64() {
  118. uint64_t R = read_vbr_uint64();
  119. if (R & 1) {
  120. if (R != 1)
  121. return -(int64_t)(R >> 1);
  122. else // There is no such thing as -0 with integers. "-0" really means
  123. // 0x8000000000000000.
  124. return 1LL << 63;
  125. } else
  126. return (int64_t)(R >> 1);
  127. }
  128. /// Read a pascal-style string (length followed by text)
  129. inline std::string BytecodeReader::read_str() {
  130. unsigned Size = read_vbr_uint();
  131. const unsigned char *OldAt = At;
  132. At += Size;
  133. if (At > BlockEnd) // Size invalid?
  134. error("Ran out of data reading a string!");
  135. return std::string((char*)OldAt, Size);
  136. }
  137. /// Read an arbitrary block of data
  138. inline void BytecodeReader::read_data(void *Ptr, void *End) {
  139. unsigned char *Start = (unsigned char *)Ptr;
  140. unsigned Amount = (unsigned char *)End - Start;
  141. if (At+Amount > BlockEnd)
  142. error("Ran out of data!");
  143. std::copy(At, At+Amount, Start);
  144. At += Amount;
  145. }
  146. /// Read a float value in little-endian order
  147. inline void BytecodeReader::read_float(float& FloatVal) {
  148. /// FIXME: This isn't optimal, it has size problems on some platforms
  149. /// where FP is not IEEE.
  150. FloatVal = BitsToFloat(At[0] | (At[1] << 8) | (At[2] << 16) | (At[3] << 24));
  151. At+=sizeof(uint32_t);
  152. }
  153. /// Read a double value in little-endian order
  154. inline void BytecodeReader::read_double(double& DoubleVal) {
  155. /// FIXME: This isn't optimal, it has size problems on some platforms
  156. /// where FP is not IEEE.
  157. DoubleVal = BitsToDouble((uint64_t(At[0]) << 0) | (uint64_t(At[1]) << 8) |
  158. (uint64_t(At[2]) << 16) | (uint64_t(At[3]) << 24) |
  159. (uint64_t(At[4]) << 32) | (uint64_t(At[5]) << 40) |
  160. (uint64_t(At[6]) << 48) | (uint64_t(At[7]) << 56));
  161. At+=sizeof(uint64_t);
  162. }
  163. /// Read a block header and obtain its type and size
  164. inline void BytecodeReader::read_block(unsigned &Type, unsigned &Size) {
  165. if ( hasLongBlockHeaders ) {
  166. Type = read_uint();
  167. Size = read_uint();
  168. switch (Type) {
  169. case BytecodeFormat::Reserved_DoNotUse :
  170. error("Reserved_DoNotUse used as Module Type?");
  171. Type = BytecodeFormat::ModuleBlockID; break;
  172. case BytecodeFormat::Module:
  173. Type = BytecodeFormat::ModuleBlockID; break;
  174. case BytecodeFormat::Function:
  175. Type = BytecodeFormat::FunctionBlockID; break;
  176. case BytecodeFormat::ConstantPool:
  177. Type = BytecodeFormat::ConstantPoolBlockID; break;
  178. case BytecodeFormat::SymbolTable:
  179. Type = BytecodeFormat::SymbolTableBlockID; break;
  180. case BytecodeFormat::ModuleGlobalInfo:
  181. Type = BytecodeFormat::ModuleGlobalInfoBlockID; break;
  182. case BytecodeFormat::GlobalTypePlane:
  183. Type = BytecodeFormat::GlobalTypePlaneBlockID; break;
  184. case BytecodeFormat::InstructionList:
  185. Type = BytecodeFormat::InstructionListBlockID; break;
  186. case BytecodeFormat::CompactionTable:
  187. Type = BytecodeFormat::CompactionTableBlockID; break;
  188. case BytecodeFormat::BasicBlock:
  189. /// This block type isn't used after version 1.1. However, we have to
  190. /// still allow the value in case this is an old bc format file.
  191. /// We just let its value creep thru.
  192. break;
  193. default:
  194. error("Invalid block id found: " + utostr(Type));
  195. break;
  196. }
  197. } else {
  198. Size = read_uint();
  199. Type = Size & 0x1F; // mask low order five bits
  200. Size >>= 5; // get rid of five low order bits, leaving high 27
  201. }
  202. BlockStart = At;
  203. if (At + Size > BlockEnd)
  204. error("Attempt to size a block past end of memory");
  205. BlockEnd = At + Size;
  206. if (Handler) Handler->handleBlock(Type, BlockStart, Size);
  207. }
  208. /// In LLVM 1.2 and before, Types were derived from Value and so they were
  209. /// written as part of the type planes along with any other Value. In LLVM
  210. /// 1.3 this changed so that Type does not derive from Value. Consequently,
  211. /// the BytecodeReader's containers for Values can't contain Types because
  212. /// there's no inheritance relationship. This means that the "Type Type"
  213. /// plane is defunct along with the Type::TypeTyID TypeID. In LLVM 1.3
  214. /// whenever a bytecode construct must have both types and values together,
  215. /// the types are always read/written first and then the Values. Furthermore
  216. /// since Type::TypeTyID no longer exists, its value (12) now corresponds to
  217. /// Type::LabelTyID. In order to overcome this we must "sanitize" all the
  218. /// type TypeIDs we encounter. For LLVM 1.3 bytecode files, there's no change.
  219. /// For LLVM 1.2 and before, this function will decrement the type id by
  220. /// one to account for the missing Type::TypeTyID enumerator if the value is
  221. /// larger than 12 (Type::LabelTyID). If the value is exactly 12, then this
  222. /// function returns true, otherwise false. This helps detect situations
  223. /// where the pre 1.3 bytecode is indicating that what follows is a type.
  224. /// @returns true iff type id corresponds to pre 1.3 "type type"
  225. inline bool BytecodeReader::sanitizeTypeId(unsigned &TypeId) {
  226. if (hasTypeDerivedFromValue) { /// do nothing if 1.3 or later
  227. if (TypeId == Type::LabelTyID) {
  228. TypeId = Type::VoidTyID; // sanitize it
  229. return true; // indicate we got TypeTyID in pre 1.3 bytecode
  230. } else if (TypeId > Type::LabelTyID)
  231. --TypeId; // shift all planes down because type type plane is missing
  232. }
  233. return false;
  234. }
  235. /// Reads a vbr uint to read in a type id and does the necessary
  236. /// conversion on it by calling sanitizeTypeId.
  237. /// @returns true iff \p TypeId read corresponds to a pre 1.3 "type type"
  238. /// @see sanitizeTypeId
  239. inline bool BytecodeReader::read_typeid(unsigned &TypeId) {
  240. TypeId = read_vbr_uint();
  241. if ( !has32BitTypes )
  242. if ( TypeId == 0x00FFFFFF )
  243. TypeId = read_vbr_uint();
  244. return sanitizeTypeId(TypeId);
  245. }
  246. //===----------------------------------------------------------------------===//
  247. // IR Lookup Methods
  248. //===----------------------------------------------------------------------===//
  249. /// Determine if a type id has an implicit null value
  250. inline bool BytecodeReader::hasImplicitNull(unsigned TyID) {
  251. if (!hasExplicitPrimitiveZeros)
  252. return TyID != Type::LabelTyID && TyID != Type::VoidTyID;
  253. return TyID >= Type::FirstDerivedTyID;
  254. }
  255. /// Obtain a type given a typeid and account for things like compaction tables,
  256. /// function level vs module level, and the offsetting for the primitive types.
  257. const Type *BytecodeReader::getType(unsigned ID) {
  258. if (ID < Type::FirstDerivedTyID)
  259. if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
  260. return T; // Asked for a primitive type...
  261. // Otherwise, derived types need offset...
  262. ID -= Type::FirstDerivedTyID;
  263. if (!CompactionTypes.empty()) {
  264. if (ID >= CompactionTypes.size())
  265. error("Type ID out of range for compaction table!");
  266. return CompactionTypes[ID].first;
  267. }
  268. // Is it a module-level type?
  269. if (ID < ModuleTypes.size())
  270. return ModuleTypes[ID].get();
  271. // Nope, is it a function-level type?
  272. ID -= ModuleTypes.size();
  273. if (ID < FunctionTypes.size())
  274. return FunctionTypes[ID].get();
  275. error("Illegal type reference!");
  276. return Type::VoidTy;
  277. }
  278. /// Get a sanitized type id. This just makes sure that the \p ID
  279. /// is both sanitized and not the "type type" of pre-1.3 bytecode.
  280. /// @see sanitizeTypeId
  281. inline const Type* BytecodeReader::getSanitizedType(unsigned& ID) {
  282. if (sanitizeTypeId(ID))
  283. error("Invalid type id encountered");
  284. return getType(ID);
  285. }
  286. /// This method just saves some coding. It uses read_typeid to read
  287. /// in a sanitized type id, errors that its not the type type, and
  288. /// then calls getType to return the type value.
  289. inline const Type* BytecodeReader::readSanitizedType() {
  290. unsigned ID;
  291. if (read_typeid(ID))
  292. error("Invalid type id encountered");
  293. return getType(ID);
  294. }
  295. /// Get the slot number associated with a type accounting for primitive
  296. /// types, compaction tables, and function level vs module level.
  297. unsigned BytecodeReader::getTypeSlot(const Type *Ty) {
  298. if (Ty->isPrimitiveType())
  299. return Ty->getTypeID();
  300. // Scan the compaction table for the type if needed.
  301. if (!CompactionTypes.empty()) {
  302. for (unsigned i = 0, e = CompactionTypes.size(); i != e; ++i)
  303. if (CompactionTypes[i].first == Ty)
  304. return Type::FirstDerivedTyID + i;
  305. error("Couldn't find type specified in compaction table!");
  306. }
  307. // Check the function level types first...
  308. TypeListTy::iterator I = std::find(FunctionTypes.begin(),
  309. FunctionTypes.end(), Ty);
  310. if (I != FunctionTypes.end())
  311. return Type::FirstDerivedTyID + ModuleTypes.size() +
  312. (&*I - &FunctionTypes[0]);
  313. // If we don't have our cache yet, build it now.
  314. if (ModuleTypeIDCache.empty()) {
  315. unsigned N = 0;
  316. ModuleTypeIDCache.reserve(ModuleTypes.size());
  317. for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
  318. I != E; ++I, ++N)
  319. ModuleTypeIDCache.push_back(std::make_pair(*I, N));
  320. std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
  321. }
  322. // Binary search the cache for the entry.
  323. std::vector<std::pair<const Type*, unsigned> >::iterator IT =
  324. std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
  325. std::make_pair(Ty, 0U));
  326. if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
  327. error("Didn't find type in ModuleTypes.");
  328. return Type::FirstDerivedTyID + IT->second;
  329. }
  330. /// This is just like getType, but when a compaction table is in use, it is
  331. /// ignored. It also ignores function level types.
  332. /// @see getType
  333. const Type *BytecodeReader::getGlobalTableType(unsigned Slot) {
  334. if (Slot < Type::FirstDerivedTyID) {
  335. const Type *Ty = Type::getPrimitiveType((Type::TypeID)Slot);
  336. if (!Ty)
  337. error("Not a primitive type ID?");
  338. return Ty;
  339. }
  340. Slot -= Type::FirstDerivedTyID;
  341. if (Slot >= ModuleTypes.size())
  342. error("Illegal compaction table type reference!");
  343. return ModuleTypes[Slot];
  344. }
  345. /// This is just like getTypeSlot, but when a compaction table is in use, it
  346. /// is ignored. It also ignores function level types.
  347. unsigned BytecodeReader::getGlobalTableTypeSlot(const Type *Ty) {
  348. if (Ty->isPrimitiveType())
  349. return Ty->getTypeID();
  350. // If we don't have our cache yet, build it now.
  351. if (ModuleTypeIDCache.empty()) {
  352. unsigned N = 0;
  353. ModuleTypeIDCache.reserve(ModuleTypes.size());
  354. for (TypeListTy::iterator I = ModuleTypes.begin(), E = ModuleTypes.end();
  355. I != E; ++I, ++N)
  356. ModuleTypeIDCache.push_back(std::make_pair(*I, N));
  357. std::sort(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end());
  358. }
  359. // Binary search the cache for the entry.
  360. std::vector<std::pair<const Type*, unsigned> >::iterator IT =
  361. std::lower_bound(ModuleTypeIDCache.begin(), ModuleTypeIDCache.end(),
  362. std::make_pair(Ty, 0U));
  363. if (IT == ModuleTypeIDCache.end() || IT->first != Ty)
  364. error("Didn't find type in ModuleTypes.");
  365. return Type::FirstDerivedTyID + IT->second;
  366. }
  367. /// Retrieve a value of a given type and slot number, possibly creating
  368. /// it if it doesn't already exist.
  369. Value * BytecodeReader::getValue(unsigned type, unsigned oNum, bool Create) {
  370. assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
  371. unsigned Num = oNum;
  372. // If there is a compaction table active, it defines the low-level numbers.
  373. // If not, the module values define the low-level numbers.
  374. if (CompactionValues.size() > type && !CompactionValues[type].empty()) {
  375. if (Num < CompactionValues[type].size())
  376. return CompactionValues[type][Num];
  377. Num -= CompactionValues[type].size();
  378. } else {
  379. // By default, the global type id is the type id passed in
  380. unsigned GlobalTyID = type;
  381. // If the type plane was compactified, figure out the global type ID by
  382. // adding the derived type ids and the distance.
  383. if (!CompactionTypes.empty() && type >= Type::FirstDerivedTyID)
  384. GlobalTyID = CompactionTypes[type-Type::FirstDerivedTyID].second;
  385. if (hasImplicitNull(GlobalTyID)) {
  386. const Type *Ty = getType(type);
  387. if (!isa<OpaqueType>(Ty)) {
  388. if (Num == 0)
  389. return Constant::getNullValue(Ty);
  390. --Num;
  391. }
  392. }
  393. if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
  394. if (Num < ModuleValues[GlobalTyID]->size())
  395. return ModuleValues[GlobalTyID]->getOperand(Num);
  396. Num -= ModuleValues[GlobalTyID]->size();
  397. }
  398. }
  399. if (FunctionValues.size() > type &&
  400. FunctionValues[type] &&
  401. Num < FunctionValues[type]->size())
  402. return FunctionValues[type]->getOperand(Num);
  403. if (!Create) return 0; // Do not create a placeholder?
  404. // Did we already create a place holder?
  405. std::pair<unsigned,unsigned> KeyValue(type, oNum);
  406. ForwardReferenceMap::iterator I = ForwardReferences.lower_bound(KeyValue);
  407. if (I != ForwardReferences.end() && I->first == KeyValue)
  408. return I->second; // We have already created this placeholder
  409. // If the type exists (it should)
  410. if (const Type* Ty = getType(type)) {
  411. // Create the place holder
  412. Value *Val = new Argument(Ty);
  413. ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
  414. return Val;
  415. }
  416. throw "Can't create placeholder for value of type slot #" + utostr(type);
  417. }
  418. /// This is just like getValue, but when a compaction table is in use, it
  419. /// is ignored. Also, no forward references or other fancy features are
  420. /// supported.
  421. Value* BytecodeReader::getGlobalTableValue(unsigned TyID, unsigned SlotNo) {
  422. if (SlotNo == 0)
  423. return Constant::getNullValue(getType(TyID));
  424. if (!CompactionTypes.empty() && TyID >= Type::FirstDerivedTyID) {
  425. TyID -= Type::FirstDerivedTyID;
  426. if (TyID >= CompactionTypes.size())
  427. error("Type ID out of range for compaction table!");
  428. TyID = CompactionTypes[TyID].second;
  429. }
  430. --SlotNo;
  431. if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0 ||
  432. SlotNo >= ModuleValues[TyID]->size()) {
  433. if (TyID >= ModuleValues.size() || ModuleValues[TyID] == 0)
  434. error("Corrupt compaction table entry!"
  435. + utostr(TyID) + ", " + utostr(SlotNo) + ": "
  436. + utostr(ModuleValues.size()));
  437. else
  438. error("Corrupt compaction table entry!"
  439. + utostr(TyID) + ", " + utostr(SlotNo) + ": "
  440. + utostr(ModuleValues.size()) + ", "
  441. + utohexstr(reinterpret_cast<uint64_t>(((void*)ModuleValues[TyID])))
  442. + ", "
  443. + utostr(ModuleValues[TyID]->size()));
  444. }
  445. return ModuleValues[TyID]->getOperand(SlotNo);
  446. }
  447. /// Just like getValue, except that it returns a null pointer
  448. /// only on error. It always returns a constant (meaning that if the value is
  449. /// defined, but is not a constant, that is an error). If the specified
  450. /// constant hasn't been parsed yet, a placeholder is defined and used.
  451. /// Later, after the real value is parsed, the placeholder is eliminated.
  452. Constant* BytecodeReader::getConstantValue(unsigned TypeSlot, unsigned Slot) {
  453. if (Value *V = getValue(TypeSlot, Slot, false))
  454. if (Constant *C = dyn_cast<Constant>(V))
  455. return C; // If we already have the value parsed, just return it
  456. else
  457. error("Value for slot " + utostr(Slot) +
  458. " is expected to be a constant!");
  459. std::pair<unsigned, unsigned> Key(TypeSlot, Slot);
  460. ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
  461. if (I != ConstantFwdRefs.end() && I->first == Key) {
  462. return I->second;
  463. } else {
  464. // Create a placeholder for the constant reference and
  465. // keep track of the fact that we have a forward ref to recycle it
  466. Constant *C = new ConstantPlaceHolder(getType(TypeSlot));
  467. // Keep track of the fact that we have a forward ref to recycle it
  468. ConstantFwdRefs.insert(I, std::make_pair(Key, C));
  469. return C;
  470. }
  471. }
  472. //===----------------------------------------------------------------------===//
  473. // IR Construction Methods
  474. //===----------------------------------------------------------------------===//
  475. /// As values are created, they are inserted into the appropriate place
  476. /// with this method. The ValueTable argument must be one of ModuleValues
  477. /// or FunctionValues data members of this class.
  478. unsigned BytecodeReader::insertValue(Value *Val, unsigned type,
  479. ValueTable &ValueTab) {
  480. assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
  481. !hasImplicitNull(type) &&
  482. "Cannot read null values from bytecode!");
  483. if (ValueTab.size() <= type)
  484. ValueTab.resize(type+1);
  485. if (!ValueTab[type]) ValueTab[type] = new ValueList();
  486. ValueTab[type]->push_back(Val);
  487. bool HasOffset = hasImplicitNull(type) && !isa<OpaqueType>(Val->getType());
  488. return ValueTab[type]->size()-1 + HasOffset;
  489. }
  490. /// Insert the arguments of a function as new values in the reader.
  491. void BytecodeReader::insertArguments(Function* F) {
  492. const FunctionType *FT = F->getFunctionType();
  493. Function::arg_iterator AI = F->arg_begin();
  494. for (FunctionType::param_iterator It = FT->param_begin();
  495. It != FT->param_end(); ++It, ++AI)
  496. insertValue(AI, getTypeSlot(AI->getType()), FunctionValues);
  497. }
  498. //===----------------------------------------------------------------------===//
  499. // Bytecode Parsing Methods
  500. //===----------------------------------------------------------------------===//
  501. /// This method parses a single instruction. The instruction is
  502. /// inserted at the end of the \p BB provided. The arguments of
  503. /// the instruction are provided in the \p Oprnds vector.
  504. void BytecodeReader::ParseInstruction(std::vector<unsigned> &Oprnds,
  505. BasicBlock* BB) {
  506. BufPtr SaveAt = At;
  507. // Clear instruction data
  508. Oprnds.clear();
  509. unsigned iType = 0;
  510. unsigned Opcode = 0;
  511. unsigned Op = read_uint();
  512. // bits Instruction format: Common to all formats
  513. // --------------------------
  514. // 01-00: Opcode type, fixed to 1.
  515. // 07-02: Opcode
  516. Opcode = (Op >> 2) & 63;
  517. Oprnds.resize((Op >> 0) & 03);
  518. // Extract the operands
  519. switch (Oprnds.size()) {
  520. case 1:
  521. // bits Instruction format:
  522. // --------------------------
  523. // 19-08: Resulting type plane
  524. // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
  525. //
  526. iType = (Op >> 8) & 4095;
  527. Oprnds[0] = (Op >> 20) & 4095;
  528. if (Oprnds[0] == 4095) // Handle special encoding for 0 operands...
  529. Oprnds.resize(0);
  530. break;
  531. case 2:
  532. // bits Instruction format:
  533. // --------------------------
  534. // 15-08: Resulting type plane
  535. // 23-16: Operand #1
  536. // 31-24: Operand #2
  537. //
  538. iType = (Op >> 8) & 255;
  539. Oprnds[0] = (Op >> 16) & 255;
  540. Oprnds[1] = (Op >> 24) & 255;
  541. break;
  542. case 3:
  543. // bits Instruction format:
  544. // --------------------------
  545. // 13-08: Resulting type plane
  546. // 19-14: Operand #1
  547. // 25-20: Operand #2
  548. // 31-26: Operand #3
  549. //
  550. iType = (Op >> 8) & 63;
  551. Oprnds[0] = (Op >> 14) & 63;
  552. Oprnds[1] = (Op >> 20) & 63;
  553. Oprnds[2] = (Op >> 26) & 63;
  554. break;
  555. case 0:
  556. At -= 4; // Hrm, try this again...
  557. Opcode = read_vbr_uint();
  558. Opcode >>= 2;
  559. iType = read_vbr_uint();
  560. unsigned NumOprnds = read_vbr_uint();
  561. Oprnds.resize(NumOprnds);
  562. if (NumOprnds == 0)
  563. error("Zero-argument instruction found; this is invalid.");
  564. for (unsigned i = 0; i != NumOprnds; ++i)
  565. Oprnds[i] = read_vbr_uint();
  566. align32();
  567. break;
  568. }
  569. const Type *InstTy = getSanitizedType(iType);
  570. // We have enough info to inform the handler now.
  571. if (Handler) Handler->handleInstruction(Opcode, InstTy, Oprnds, At-SaveAt);
  572. // Declare the resulting instruction we'll build.
  573. Instruction *Result = 0;
  574. // If this is a bytecode format that did not include the unreachable
  575. // instruction, bump up all opcodes numbers to make space.
  576. if (hasNoUnreachableInst) {
  577. if (Opcode >= Instruction::Unreachable &&
  578. Opcode < 62) {
  579. ++Opcode;
  580. }
  581. }
  582. // Handle binary operators
  583. if (Opcode >= Instruction::BinaryOpsBegin &&
  584. Opcode < Instruction::BinaryOpsEnd && Oprnds.size() == 2)
  585. Result = BinaryOperator::create((Instruction::BinaryOps)Opcode,
  586. getValue(iType, Oprnds[0]),
  587. getValue(iType, Oprnds[1]));
  588. switch (Opcode) {
  589. default:
  590. if (Result == 0)
  591. error("Illegal instruction read!");
  592. break;
  593. case Instruction::VAArg:
  594. Result = new VAArgInst(getValue(iType, Oprnds[0]),
  595. getSanitizedType(Oprnds[1]));
  596. break;
  597. case 32: { //VANext_old
  598. const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
  599. Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
  600. (Type *)0);
  601. //b = vanext a, t ->
  602. //foo = alloca 1 of t
  603. //bar = vacopy a
  604. //store bar -> foo
  605. //tmp = vaarg foo, t
  606. //b = load foo
  607. AllocaInst* foo = new AllocaInst(ArgTy, 0, "vanext.fix");
  608. BB->getInstList().push_back(foo);
  609. CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
  610. BB->getInstList().push_back(bar);
  611. BB->getInstList().push_back(new StoreInst(bar, foo));
  612. Instruction* tmp = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
  613. BB->getInstList().push_back(tmp);
  614. Result = new LoadInst(foo);
  615. break;
  616. }
  617. case 33: { //VAArg_old
  618. const Type* ArgTy = getValue(iType, Oprnds[0])->getType();
  619. Function* NF = TheModule->getOrInsertFunction("llvm.va_copy", ArgTy, ArgTy,
  620. (Type *)0);
  621. //b = vaarg a, t ->
  622. //foo = alloca 1 of t
  623. //bar = vacopy a
  624. //store bar -> foo
  625. //b = vaarg foo, t
  626. AllocaInst* foo = new AllocaInst(ArgTy, 0, "vaarg.fix");
  627. BB->getInstList().push_back(foo);
  628. CallInst* bar = new CallInst(NF, getValue(iType, Oprnds[0]));
  629. BB->getInstList().push_back(bar);
  630. BB->getInstList().push_back(new StoreInst(bar, foo));
  631. Result = new VAArgInst(foo, getSanitizedType(Oprnds[1]));
  632. break;
  633. }
  634. case Instruction::Cast:
  635. Result = new CastInst(getValue(iType, Oprnds[0]),
  636. getSanitizedType(Oprnds[1]));
  637. break;
  638. case Instruction::Select:
  639. Result = new SelectInst(getValue(Type::BoolTyID, Oprnds[0]),
  640. getValue(iType, Oprnds[1]),
  641. getValue(iType, Oprnds[2]));
  642. break;
  643. case Instruction::PHI: {
  644. if (Oprnds.size() == 0 || (Oprnds.size() & 1))
  645. error("Invalid phi node encountered!");
  646. PHINode *PN = new PHINode(InstTy);
  647. PN->reserveOperandSpace(Oprnds.size());
  648. for (unsigned i = 0, e = Oprnds.size(); i != e; i += 2)
  649. PN->addIncoming(getValue(iType, Oprnds[i]), getBasicBlock(Oprnds[i+1]));
  650. Result = PN;
  651. break;
  652. }
  653. case Instruction::Shl:
  654. case Instruction::Shr:
  655. Result = new ShiftInst((Instruction::OtherOps)Opcode,
  656. getValue(iType, Oprnds[0]),
  657. getValue(Type::UByteTyID, Oprnds[1]));
  658. break;
  659. case Instruction::Ret:
  660. if (Oprnds.size() == 0)
  661. Result = new ReturnInst();
  662. else if (Oprnds.size() == 1)
  663. Result = new ReturnInst(getValue(iType, Oprnds[0]));
  664. else
  665. error("Unrecognized instruction!");
  666. break;
  667. case Instruction::Br:
  668. if (Oprnds.size() == 1)
  669. Result = new BranchInst(getBasicBlock(Oprnds[0]));
  670. else if (Oprnds.size() == 3)
  671. Result = new BranchInst(getBasicBlock(Oprnds[0]),
  672. getBasicBlock(Oprnds[1]), getValue(Type::BoolTyID , Oprnds[2]));
  673. else
  674. error("Invalid number of operands for a 'br' instruction!");
  675. break;
  676. case Instruction::Switch: {
  677. if (Oprnds.size() & 1)
  678. error("Switch statement with odd number of arguments!");
  679. SwitchInst *I = new SwitchInst(getValue(iType, Oprnds[0]),
  680. getBasicBlock(Oprnds[1]),
  681. Oprnds.size()/2-1);
  682. for (unsigned i = 2, e = Oprnds.size(); i != e; i += 2)
  683. I->addCase(cast<ConstantInt>(getValue(iType, Oprnds[i])),
  684. getBasicBlock(Oprnds[i+1]));
  685. Result = I;
  686. break;
  687. }
  688. case 58: // Call with extra operand for calling conv
  689. case 59: // tail call, Fast CC
  690. case 60: // normal call, Fast CC
  691. case 61: // tail call, C Calling Conv
  692. case Instruction::Call: { // Normal Call, C Calling Convention
  693. if (Oprnds.size() == 0)
  694. error("Invalid call instruction encountered!");
  695. Value *F = getValue(iType, Oprnds[0]);
  696. unsigned CallingConv = CallingConv::C;
  697. bool isTailCall = false;
  698. if (Opcode == 61 || Opcode == 59)
  699. isTailCall = true;
  700. // Check to make sure we have a pointer to function type
  701. const PointerType *PTy = dyn_cast<PointerType>(F->getType());
  702. if (PTy == 0) error("Call to non function pointer value!");
  703. const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
  704. if (FTy == 0) error("Call to non function pointer value!");
  705. std::vector<Value *> Params;
  706. if (!FTy->isVarArg()) {
  707. FunctionType::param_iterator It = FTy->param_begin();
  708. if (Opcode == 58) {
  709. isTailCall = Oprnds.back() & 1;
  710. CallingConv = Oprnds.back() >> 1;
  711. Oprnds.pop_back();
  712. } else if (Opcode == 59 || Opcode == 60)
  713. CallingConv = CallingConv::Fast;
  714. for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
  715. if (It == FTy->param_end())
  716. error("Invalid call instruction!");
  717. Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
  718. }
  719. if (It != FTy->param_end())
  720. error("Invalid call instruction!");
  721. } else {
  722. Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
  723. unsigned FirstVariableOperand;
  724. if (Oprnds.size() < FTy->getNumParams())
  725. error("Call instruction missing operands!");
  726. // Read all of the fixed arguments
  727. for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i)
  728. Params.push_back(getValue(getTypeSlot(FTy->getParamType(i)),Oprnds[i]));
  729. FirstVariableOperand = FTy->getNumParams();
  730. if ((Oprnds.size()-FirstVariableOperand) & 1)
  731. error("Invalid call instruction!"); // Must be pairs of type/value
  732. for (unsigned i = FirstVariableOperand, e = Oprnds.size();
  733. i != e; i += 2)
  734. Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
  735. }
  736. Result = new CallInst(F, Params);
  737. if (isTailCall) cast<CallInst>(Result)->setTailCall();
  738. if (CallingConv) cast<CallInst>(Result)->setCallingConv(CallingConv);
  739. break;
  740. }
  741. case 56: // Invoke with encoded CC
  742. case 57: // Invoke Fast CC
  743. case Instruction::Invoke: { // Invoke C CC
  744. if (Oprnds.size() < 3)
  745. error("Invalid invoke instruction!");
  746. Value *F = getValue(iType, Oprnds[0]);
  747. // Check to make sure we have a pointer to function type
  748. const PointerType *PTy = dyn_cast<PointerType>(F->getType());
  749. if (PTy == 0)
  750. error("Invoke to non function pointer value!");
  751. const FunctionType *FTy = dyn_cast<FunctionType>(PTy->getElementType());
  752. if (FTy == 0)
  753. error("Invoke to non function pointer value!");
  754. std::vector<Value *> Params;
  755. BasicBlock *Normal, *Except;
  756. unsigned CallingConv = CallingConv::C;
  757. if (Opcode == 57)
  758. CallingConv = CallingConv::Fast;
  759. else if (Opcode == 56) {
  760. CallingConv = Oprnds.back();
  761. Oprnds.pop_back();
  762. }
  763. if (!FTy->isVarArg()) {
  764. Normal = getBasicBlock(Oprnds[1]);
  765. Except = getBasicBlock(Oprnds[2]);
  766. FunctionType::param_iterator It = FTy->param_begin();
  767. for (unsigned i = 3, e = Oprnds.size(); i != e; ++i) {
  768. if (It == FTy->param_end())
  769. error("Invalid invoke instruction!");
  770. Params.push_back(getValue(getTypeSlot(*It++), Oprnds[i]));
  771. }
  772. if (It != FTy->param_end())
  773. error("Invalid invoke instruction!");
  774. } else {
  775. Oprnds.erase(Oprnds.begin(), Oprnds.begin()+1);
  776. Normal = getBasicBlock(Oprnds[0]);
  777. Except = getBasicBlock(Oprnds[1]);
  778. unsigned FirstVariableArgument = FTy->getNumParams()+2;
  779. for (unsigned i = 2; i != FirstVariableArgument; ++i)
  780. Params.push_back(getValue(getTypeSlot(FTy->getParamType(i-2)),
  781. Oprnds[i]));
  782. if (Oprnds.size()-FirstVariableArgument & 1) // Must be type/value pairs
  783. error("Invalid invoke instruction!");
  784. for (unsigned i = FirstVariableArgument; i < Oprnds.size(); i += 2)
  785. Params.push_back(getValue(Oprnds[i], Oprnds[i+1]));
  786. }
  787. Result = new InvokeInst(F, Normal, Except, Params);
  788. if (CallingConv) cast<InvokeInst>(Result)->setCallingConv(CallingConv);
  789. break;
  790. }
  791. case Instruction::Malloc:
  792. if (Oprnds.size() > 2)
  793. error("Invalid malloc instruction!");
  794. if (!isa<PointerType>(InstTy))
  795. error("Invalid malloc instruction!");
  796. Result = new MallocInst(cast<PointerType>(InstTy)->getElementType(),
  797. Oprnds.size() ? getValue(Type::UIntTyID,
  798. Oprnds[0]) : 0);
  799. break;
  800. case Instruction::Alloca:
  801. if (Oprnds.size() > 2)
  802. error("Invalid alloca instruction!");
  803. if (!isa<PointerType>(InstTy))
  804. error("Invalid alloca instruction!");
  805. Result = new AllocaInst(cast<PointerType>(InstTy)->getElementType(),
  806. Oprnds.size() ? getValue(Type::UIntTyID,
  807. Oprnds[0]) :0);
  808. break;
  809. case Instruction::Free:
  810. if (!isa<PointerType>(InstTy))
  811. error("Invalid free instruction!");
  812. Result = new FreeInst(getValue(iType, Oprnds[0]));
  813. break;
  814. case Instruction::GetElementPtr: {
  815. if (Oprnds.size() == 0 || !isa<PointerType>(InstTy))
  816. error("Invalid getelementptr instruction!");
  817. std::vector<Value*> Idx;
  818. const Type *NextTy = InstTy;
  819. for (unsigned i = 1, e = Oprnds.size(); i != e; ++i) {
  820. const CompositeType *TopTy = dyn_cast_or_null<CompositeType>(NextTy);
  821. if (!TopTy)
  822. error("Invalid getelementptr instruction!");
  823. unsigned ValIdx = Oprnds[i];
  824. unsigned IdxTy = 0;
  825. if (!hasRestrictedGEPTypes) {
  826. // Struct indices are always uints, sequential type indices can be any
  827. // of the 32 or 64-bit integer types. The actual choice of type is
  828. // encoded in the low two bits of the slot number.
  829. if (isa<StructType>(TopTy))
  830. IdxTy = Type::UIntTyID;
  831. else {
  832. switch (ValIdx & 3) {
  833. default:
  834. case 0: IdxTy = Type::UIntTyID; break;
  835. case 1: IdxTy = Type::IntTyID; break;
  836. case 2: IdxTy = Type::ULongTyID; break;
  837. case 3: IdxTy = Type::LongTyID; break;
  838. }
  839. ValIdx >>= 2;
  840. }
  841. } else {
  842. IdxTy = isa<StructType>(TopTy) ? Type::UByteTyID : Type::LongTyID;
  843. }
  844. Idx.push_back(getValue(IdxTy, ValIdx));
  845. // Convert ubyte struct indices into uint struct indices.
  846. if (isa<StructType>(TopTy) && hasRestrictedGEPTypes)
  847. if (ConstantUInt *C = dyn_cast<ConstantUInt>(Idx.back()))
  848. Idx[Idx.size()-1] = ConstantExpr::getCast(C, Type::UIntTy);
  849. NextTy = GetElementPtrInst::getIndexedType(InstTy, Idx, true);
  850. }
  851. Result = new GetElementPtrInst(getValue(iType, Oprnds[0]), Idx);
  852. break;
  853. }
  854. case 62: // volatile load
  855. case Instruction::Load:
  856. if (Oprnds.size() != 1 || !isa<PointerType>(InstTy))
  857. error("Invalid load instruction!");
  858. Result = new LoadInst(getValue(iType, Oprnds[0]), "", Opcode == 62);
  859. break;
  860. case 63: // volatile store
  861. case Instruction::Store: {
  862. if (!isa<PointerType>(InstTy) || Oprnds.size() != 2)
  863. error("Invalid store instruction!");
  864. Value *Ptr = getValue(iType, Oprnds[1]);
  865. const Type *ValTy = cast<PointerType>(Ptr->getType())->getElementType();
  866. Result = new StoreInst(getValue(getTypeSlot(ValTy), Oprnds[0]), Ptr,
  867. Opcode == 63);
  868. break;
  869. }
  870. case Instruction::Unwind:
  871. if (Oprnds.size() != 0) error("Invalid unwind instruction!");
  872. Result = new UnwindInst();
  873. break;
  874. case Instruction::Unreachable:
  875. if (Oprnds.size() != 0) error("Invalid unreachable instruction!");
  876. Result = new UnreachableInst();
  877. break;
  878. } // end switch(Opcode)
  879. unsigned TypeSlot;
  880. if (Result->getType() == InstTy)
  881. TypeSlot = iType;
  882. else
  883. TypeSlot = getTypeSlot(Result->getType());
  884. insertValue(Result, TypeSlot, FunctionValues);
  885. BB->getInstList().push_back(Result);
  886. }
  887. /// Get a particular numbered basic block, which might be a forward reference.
  888. /// This works together with ParseBasicBlock to handle these forward references
  889. /// in a clean manner. This function is used when constructing phi, br, switch,
  890. /// and other instructions that reference basic blocks. Blocks are numbered
  891. /// sequentially as they appear in the function.
  892. BasicBlock *BytecodeReader::getBasicBlock(unsigned ID) {
  893. // Make sure there is room in the table...
  894. if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
  895. // First check to see if this is a backwards reference, i.e., ParseBasicBlock
  896. // has already created this block, or if the forward reference has already
  897. // been created.
  898. if (ParsedBasicBlocks[ID])
  899. return ParsedBasicBlocks[ID];
  900. // Otherwise, the basic block has not yet been created. Do so and add it to
  901. // the ParsedBasicBlocks list.
  902. return ParsedBasicBlocks[ID] = new BasicBlock();
  903. }
  904. /// In LLVM 1.0 bytecode files, we used to output one basicblock at a time.
  905. /// This method reads in one of the basicblock packets. This method is not used
  906. /// for bytecode files after LLVM 1.0
  907. /// @returns The basic block constructed.
  908. BasicBlock *BytecodeReader::ParseBasicBlock(unsigned BlockNo) {
  909. if (Handler) Handler->handleBasicBlockBegin(BlockNo);
  910. BasicBlock *BB = 0;
  911. if (ParsedBasicBlocks.size() == BlockNo)
  912. ParsedBasicBlocks.push_back(BB = new BasicBlock());
  913. else if (ParsedBasicBlocks[BlockNo] == 0)
  914. BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
  915. else
  916. BB = ParsedBasicBlocks[BlockNo];
  917. std::vector<unsigned> Operands;
  918. while (moreInBlock())
  919. ParseInstruction(Operands, BB);
  920. if (Handler) Handler->handleBasicBlockEnd(BlockNo);
  921. return BB;
  922. }
  923. /// Parse all of the BasicBlock's & Instruction's in the body of a function.
  924. /// In post 1.0 bytecode files, we no longer emit basic block individually,
  925. /// in order to avoid per-basic-block overhead.
  926. /// @returns Rhe number of basic blocks encountered.
  927. unsigned BytecodeReader::ParseInstructionList(Function* F) {
  928. unsigned BlockNo = 0;
  929. std::vector<unsigned> Args;
  930. while (moreInBlock()) {
  931. if (Handler) Handler->handleBasicBlockBegin(BlockNo);
  932. BasicBlock *BB;
  933. if (ParsedBasicBlocks.size() == BlockNo)
  934. ParsedBasicBlocks.push_back(BB = new BasicBlock());
  935. else if (ParsedBasicBlocks[BlockNo] == 0)
  936. BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
  937. else
  938. BB = ParsedBasicBlocks[BlockNo];
  939. ++BlockNo;
  940. F->getBasicBlockList().push_back(BB);
  941. // Read instructions into this basic block until we get to a terminator
  942. while (moreInBlock() && !BB->getTerminator())
  943. ParseInstruction(Args, BB);
  944. if (!BB->getTerminator())
  945. error("Non-terminated basic block found!");
  946. if (Handler) Handler->handleBasicBlockEnd(BlockNo-1);
  947. }
  948. return BlockNo;
  949. }
  950. /// Parse a symbol table. This works for both module level and function
  951. /// level symbol tables. For function level symbol tables, the CurrentFunction
  952. /// parameter must be non-zero and the ST parameter must correspond to
  953. /// CurrentFunction's symbol table. For Module level symbol tables, the
  954. /// CurrentFunction argument must be zero.
  955. void BytecodeReader::ParseSymbolTable(Function *CurrentFunction,
  956. SymbolTable *ST) {
  957. if (Handler) Handler->handleSymbolTableBegin(CurrentFunction,ST);
  958. // Allow efficient basic block lookup by number.
  959. std::vector<BasicBlock*> BBMap;
  960. if (CurrentFunction)
  961. for (Function::iterator I = CurrentFunction->begin(),
  962. E = CurrentFunction->end(); I != E; ++I)
  963. BBMap.push_back(I);
  964. /// In LLVM 1.3 we write types separately from values so
  965. /// The types are always first in the symbol table. This is
  966. /// because Type no longer derives from Value.
  967. if (!hasTypeDerivedFromValue) {
  968. // Symtab block header: [num entries]
  969. unsigned NumEntries = read_vbr_uint();
  970. for (unsigned i = 0; i < NumEntries; ++i) {
  971. // Symtab entry: [def slot #][name]
  972. unsigned slot = read_vbr_uint();
  973. std::string Name = read_str();
  974. const Type* T = getType(slot);
  975. ST->insert(Name, T);
  976. }
  977. }
  978. while (moreInBlock()) {
  979. // Symtab block header: [num entries][type id number]
  980. unsigned NumEntries = read_vbr_uint();
  981. unsigned Typ = 0;
  982. bool isTypeType = read_typeid(Typ);
  983. const Type *Ty = getType(Typ);
  984. for (unsigned i = 0; i != NumEntries; ++i) {
  985. // Symtab entry: [def slot #][name]
  986. unsigned slot = read_vbr_uint();
  987. std::string Name = read_str();
  988. // if we're reading a pre 1.3 bytecode file and the type plane
  989. // is the "type type", handle it here
  990. if (isTypeType) {
  991. const Type* T = getType(slot);
  992. if (T == 0)
  993. error("Failed type look-up for name '" + Name + "'");
  994. ST->insert(Name, T);
  995. continue; // code below must be short circuited
  996. } else {
  997. Value *V = 0;
  998. if (Typ == Type::LabelTyID) {
  999. if (slot < BBMap.size())
  1000. V = BBMap[slot];
  1001. } else {
  1002. V = getValue(Typ, slot, false); // Find mapping...
  1003. }
  1004. if (V == 0)
  1005. error("Failed value look-up for name '" + Name + "'");
  1006. V->setName(Name);
  1007. }
  1008. }
  1009. }
  1010. checkPastBlockEnd("Symbol Table");
  1011. if (Handler) Handler->handleSymbolTableEnd();
  1012. }
  1013. /// Read in the types portion of a compaction table.
  1014. void BytecodeReader::ParseCompactionTypes(unsigned NumEntries) {
  1015. for (unsigned i = 0; i != NumEntries; ++i) {
  1016. unsigned TypeSlot = 0;
  1017. if (read_typeid(TypeSlot))
  1018. error("Invalid type in compaction table: type type");
  1019. const Type *Typ = getGlobalTableType(TypeSlot);
  1020. CompactionTypes.push_back(std::make_pair(Typ, TypeSlot));
  1021. if (Handler) Handler->handleCompactionTableType(i, TypeSlot, Typ);
  1022. }
  1023. }
  1024. /// Parse a compaction table.
  1025. void BytecodeReader::ParseCompactionTable() {
  1026. // Notify handler that we're beginning a compaction table.
  1027. if (Handler) Handler->handleCompactionTableBegin();
  1028. // In LLVM 1.3 Type no longer derives from Value. So,
  1029. // we always write them first in the compaction table
  1030. // because they can't occupy a "type plane" where the
  1031. // Values reside.
  1032. if (! hasTypeDerivedFromValue) {
  1033. unsigned NumEntries = read_vbr_uint();
  1034. ParseCompactionTypes(NumEntries);
  1035. }
  1036. // Compaction tables live in separate blocks so we have to loop
  1037. // until we've read the whole thing.
  1038. while (moreInBlock()) {
  1039. // Read the number of Value* entries in the compaction table
  1040. unsigned NumEntries = read_vbr_uint();
  1041. unsigned Ty = 0;
  1042. unsigned isTypeType = false;
  1043. // Decode the type from value read in. Most compaction table
  1044. // planes will have one or two entries in them. If that's the
  1045. // case then the length is encoded in the bottom two bits and
  1046. // the higher bits encode the type. This saves another VBR value.
  1047. if ((NumEntries & 3) == 3) {
  1048. // In this case, both low-order bits are set (value 3). This
  1049. // is a signal that the typeid follows.
  1050. NumEntries >>= 2;
  1051. isTypeType = read_typeid(Ty);
  1052. } else {
  1053. // In this case, the low-order bits specify the number of entries
  1054. // and the high order bits specify the type.
  1055. Ty = NumEntries >> 2;
  1056. isTypeType = sanitizeTypeId(Ty);
  1057. NumEntries &= 3;
  1058. }
  1059. // if we're reading a pre 1.3 bytecode file and the type plane
  1060. // is the "type type", handle it here
  1061. if (isTypeType) {
  1062. ParseCompactionTypes(NumEntries);
  1063. } else {
  1064. // Make sure we have enough room for the plane.
  1065. if (Ty >= CompactionValues.size())
  1066. CompactionValues.resize(Ty+1);
  1067. // Make sure the plane is empty or we have some kind of error.
  1068. if (!CompactionValues[Ty].empty())
  1069. error("Compaction table plane contains multiple entries!");
  1070. // Notify handler about the plane.
  1071. if (Handler) Handler->handleCompactionTablePlane(Ty, NumEntries);
  1072. // Push the implicit zero.
  1073. CompactionValues[Ty].push_back(Constant::getNullValue(getType(Ty)));
  1074. // Read in each of the entries, put them in the compaction table
  1075. // and notify the handler that we have a new compaction table value.
  1076. for (unsigned i = 0; i != NumEntries; ++i) {
  1077. unsigned ValSlot = read_vbr_uint();
  1078. Value *V = getGlobalTableValue(Ty, ValSlot);
  1079. CompactionValues[Ty].push_back(V);
  1080. if (Handler) Handler->handleCompactionTableValue(i, Ty, ValSlot);
  1081. }
  1082. }
  1083. }
  1084. // Notify handler that the compaction table is done.
  1085. if (Handler) Handler->handleCompactionTableEnd();
  1086. }
  1087. // Parse a single type. The typeid is read in first. If its a primitive type
  1088. // then nothing else needs to be read, we know how to instantiate it. If its
  1089. // a derived type, then additional data is read to fill out the type
  1090. // definition.
  1091. const Type *BytecodeReader::ParseType() {
  1092. unsigned PrimType = 0;
  1093. if (read_typeid(PrimType))
  1094. error("Invalid type (type type) in type constants!");
  1095. const Type *Result = 0;
  1096. if ((Result = Type::getPrimitiveType((Type::TypeID)PrimType)))
  1097. return Result;
  1098. switch (PrimType) {
  1099. case Type::FunctionTyID: {
  1100. const Type *RetType = readSanitizedType();
  1101. unsigned NumParams = read_vbr_uint();
  1102. std::vector<const Type*> Params;
  1103. while (NumParams--)
  1104. Params.push_back(readSanitizedType());
  1105. bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
  1106. if (isVarArg) Params.pop_back();
  1107. Result = FunctionType::get(RetType, Params, isVarArg);
  1108. break;
  1109. }
  1110. case Type::ArrayTyID: {
  1111. const Type *ElementType = readSanitizedType();
  1112. unsigned NumElements = read_vbr_uint();
  1113. Result = ArrayType::get(ElementType, NumElements);
  1114. break;
  1115. }
  1116. case Type::PackedTyID: {
  1117. const Type *ElementType = readSanitizedType();
  1118. unsigned NumElements = read_vbr_uint();
  1119. Result = PackedType::get(ElementType, NumElements);
  1120. break;
  1121. }
  1122. case Type::StructTyID: {
  1123. std::vector<const Type*> Elements;
  1124. unsigned Typ = 0;
  1125. if (read_typeid(Typ))
  1126. error("Invalid element type (type type) for structure!");
  1127. while (Typ) { // List is terminated by void/0 typeid
  1128. Elements.push_back(getType(Typ));
  1129. if (read_typeid(Typ))
  1130. error("Invalid element type (type type) for structure!");
  1131. }
  1132. Result = StructType::get(Elements);
  1133. break;
  1134. }
  1135. case Type::PointerTyID: {
  1136. Result = PointerType::get(readSanitizedType());
  1137. break;
  1138. }
  1139. case Type::OpaqueTyID: {
  1140. Result = OpaqueType::get();
  1141. break;
  1142. }
  1143. default:
  1144. error("Don't know how to deserialize primitive type " + utostr(PrimType));
  1145. break;
  1146. }
  1147. if (Handler) Handler->handleType(Result);
  1148. return Result;
  1149. }
  1150. // ParseTypes - We have to use this weird code to handle recursive
  1151. // types. We know that recursive types will only reference the current slab of
  1152. // values in the type plane, but they can forward reference types before they
  1153. // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
  1154. // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
  1155. // this ugly problem, we pessimistically insert an opaque type for each type we
  1156. // are about to read. This means that forward references will resolve to
  1157. // something and when we reread the type later, we can replace the opaque type
  1158. // with a new resolved concrete type.
  1159. //
  1160. void BytecodeReader::ParseTypes(TypeListTy &Tab, unsigned NumEntries){
  1161. assert(Tab.size() == 0 && "should not have read type constants in before!");
  1162. // Insert a bunch of opaque types to be resolved later...
  1163. Tab.reserve(NumEntries);
  1164. for (unsigned i = 0; i != NumEntries; ++i)
  1165. Tab.push_back(OpaqueType::get());
  1166. if (Handler)
  1167. Handler->handleTypeList(NumEntries);
  1168. // If we are about to resolve types, make sure the type cache is clear.
  1169. if (NumEntries)
  1170. ModuleTypeIDCache.clear();
  1171. // Loop through reading all of the types. Forward types will make use of the
  1172. // opaque types just inserted.
  1173. //
  1174. for (unsigned i = 0; i != NumEntries; ++i) {
  1175. const Type* NewTy = ParseType();
  1176. const Type* OldTy = Tab[i].get();
  1177. if (NewTy == 0)
  1178. error("Couldn't parse type!");
  1179. // Don't directly push the new type on the Tab. Instead we want to replace
  1180. // the opaque type we previously inserted with the new concrete value. This
  1181. // approach helps with forward references to types. The refinement from the
  1182. // abstract (opaque) type to the new type causes all uses of the abstract
  1183. // type to use the concrete type (NewTy). This will also cause the opaque
  1184. // type to be deleted.
  1185. cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
  1186. // This should have replaced the old opaque type with the new type in the
  1187. // value table... or with a preexisting type that was already in the system.
  1188. // Let's just make sure it did.
  1189. assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
  1190. }
  1191. }
  1192. /// Parse a single constant value
  1193. Constant *BytecodeReader::ParseConstantValue(unsigned TypeID) {
  1194. // We must check for a ConstantExpr before switching by type because
  1195. // a ConstantExpr can be of any type, and has no explicit value.
  1196. //
  1197. // 0 if not expr; numArgs if is expr
  1198. unsigned isExprNumArgs = read_vbr_uint();
  1199. if (isExprNumArgs) {
  1200. // 'undef' is encoded with 'exprnumargs' == 1.
  1201. if (!hasNoUndefValue)
  1202. if (--isExprNumArgs == 0)
  1203. return UndefValue::get(getType(TypeID));
  1204. // FIXME: Encoding of constant exprs could be much more compact!
  1205. std::vector<Constant*> ArgVec;
  1206. ArgVec.reserve(isExprNumArgs);
  1207. unsigned Opcode = read_vbr_uint();
  1208. // Bytecode files before LLVM 1.4 need have a missing terminator inst.
  1209. if (hasNoUnreachableInst) Opcode++;
  1210. // Read the slot number and types of each of the arguments
  1211. for (unsigned i = 0; i != isExprNumArgs; ++i) {
  1212. unsigned ArgValSlot = read_vbr_uint();
  1213. unsigned ArgTypeSlot = 0;
  1214. if (read_typeid(ArgTypeSlot))
  1215. error("Invalid argument type (type type) for constant value");
  1216. // Get the arg value from its slot if it exists, otherwise a placeholder
  1217. ArgVec.push_back(getConstantValue(ArgTypeSlot, ArgValSlot));
  1218. }
  1219. // Construct a ConstantExpr of the appropriate kind
  1220. if (isExprNumArgs == 1) { // All one-operand expressions
  1221. if (Opcode != Instruction::Cast)
  1222. error("Only cast instruction has one argument for ConstantExpr");
  1223. Constant* Result = ConstantExpr::getCast(ArgVec[0], getType(TypeID));
  1224. if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
  1225. return Result;
  1226. } else if (Opcode == Instruction::GetElementPtr) { // GetElementPtr
  1227. std::vector<Constant*> IdxList(ArgVec.begin()+1, ArgVec.end());
  1228. if (hasRestrictedGEPTypes) {
  1229. const Type *BaseTy = ArgVec[0]->getType();
  1230. generic_gep_type_iterator<std::vector<Constant*>::iterator>
  1231. GTI = gep_type_begin(BaseTy, IdxList.begin(), IdxList.end()),
  1232. E = gep_type_end(BaseTy, IdxList.begin(), IdxList.end());
  1233. for (unsigned i = 0; GTI != E; ++GTI, ++i)
  1234. if (isa<StructType>(*GTI)) {
  1235. if (IdxList[i]->getType() != Type::UByteTy)
  1236. error("Invalid index for getelementptr!");
  1237. IdxList[i] = ConstantExpr::getCast(IdxList[i], Type::UIntTy);
  1238. }
  1239. }
  1240. Constant* Result = ConstantExpr::getGetElementPtr(ArgVec[0], IdxList);
  1241. if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
  1242. return Result;
  1243. } else if (Opcode == Instruction::Select) {
  1244. if (ArgVec.size() != 3)
  1245. error("Select instruction must have three arguments.");
  1246. Constant* Result = ConstantExpr::getSelect(ArgVec[0], ArgVec[1],
  1247. ArgVec[2]);
  1248. if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
  1249. return Result;
  1250. } else { // All other 2-operand expressions
  1251. Constant* Result = ConstantExpr::get(Opcode, ArgVec[0], ArgVec[1]);
  1252. if (Handler) Handler->handleConstantExpression(Opcode, ArgVec, Result);
  1253. return Result;
  1254. }
  1255. }
  1256. // Ok, not an ConstantExpr. We now know how to read the given type...
  1257. const Type *Ty = getType(TypeID);
  1258. switch (Ty->getTypeID()) {
  1259. case Type::BoolTyID: {
  1260. unsigned Val = read_vbr_uint();
  1261. if (Val != 0 && Val != 1)
  1262. error("Invalid boolean value read.");
  1263. Constant* Result = ConstantBool::get(Val == 1);
  1264. if (Handler) Handler->handleConstantValue(Result);
  1265. return Result;
  1266. }
  1267. case Type::UByteTyID: // Unsigned integer types...
  1268. case Type::UShortTyID:
  1269. case Type::UIntTyID: {
  1270. unsigned Val = read_vbr_uint();
  1271. if (!ConstantUInt::isValueValidForType(Ty, Val))
  1272. error("Invalid unsigned byte/short/int read.");
  1273. Constant* Result = ConstantUInt::get(Ty, Val);
  1274. if (Handler) Handler->handleConstantValue(Result);
  1275. return Result;
  1276. }
  1277. case Type::ULongTyID: {
  1278. Constant* Result = ConstantUInt::get(Ty, read_vbr_uint64());
  1279. if (Handler) Handler->handleConstantValue(Result);
  1280. return Result;
  1281. }
  1282. case Type::SByteTyID: // Signed integer types...
  1283. case Type::ShortTyID:
  1284. case Type::IntTyID: {
  1285. case Type::LongTyID:
  1286. int64_t Val = read_vbr_int64();
  1287. if (!ConstantSInt::isValueValidForType(Ty, Val))
  1288. error("Invalid signed byte/short/int/long read.");
  1289. Constant* Result = ConstantSInt::get(Ty, Val);
  1290. if (Handler) Handler->handleConstantValue(Result);
  1291. return Result;
  1292. }
  1293. case Type::FloatTyID: {
  1294. float Val;
  1295. read_float(Val);
  1296. Constant* Result = ConstantFP::get(Ty, Val);
  1297. if (Handler) Handler->handleConstantValue(Result);
  1298. return Result;
  1299. }
  1300. case Type::DoubleTyID: {
  1301. double Val;
  1302. read_double(Val);
  1303. Constant* Result = ConstantFP::get(Ty, Val);
  1304. if (Handler) Handler->handleConstantValue(Result);
  1305. return Result;
  1306. }
  1307. case Type::ArrayTyID: {
  1308. const ArrayType *AT = cast<ArrayType>(Ty);
  1309. unsigned NumElements = AT->getNumElements();
  1310. unsigned TypeSlot = getTypeSlot(AT->getElementType());
  1311. std::vector<Constant*> Elements;
  1312. Elements.reserve(NumElements);
  1313. while (NumElements--) // Read all of the elements of the constant.
  1314. Elements.push_back(getConstantValue(TypeSlot,
  1315. read_vbr_uint()));
  1316. Constant* Result = ConstantArray::get(AT, Elements);
  1317. if (Handler) Handler->handleConstantArray(AT, Elements, TypeSlot, Result);
  1318. return Result;
  1319. }
  1320. case Type::StructTyID: {
  1321. const StructType *ST = cast<StructType>(Ty);
  1322. std::vector<Constant *> Elements;
  1323. Elements.reserve(ST->getNumElements());
  1324. for (unsigned i = 0; i != ST->getNumElements(); ++i)
  1325. Elements.push_back(getConstantValue(ST->getElementType(i),
  1326. read_vbr_uint()));
  1327. Constant* Result = ConstantStruct::get(ST, Elements);
  1328. if (Handler) Handler->handleConstantStruct(ST, Elements, Result);
  1329. return Result;
  1330. }
  1331. case Type::PackedTyID: {
  1332. const PackedType *PT = cast<PackedType>(Ty);
  1333. unsigned NumElements = PT->getNumElements();
  1334. unsigned TypeSlot = getTypeSlot(PT->getElementType());
  1335. std::vector<Constant*> Elements;
  1336. Elements.reserve(NumElements);
  1337. while (NumElements--) // Read all of the elements of the constant.
  1338. Elements.push_back(getConstantValue(TypeSlot,
  1339. read_vbr_uint()));
  1340. Constant* Result = ConstantPacked::get(PT, Elements);
  1341. if (Handler) Handler->handleConstantPacked(PT, Elements, TypeSlot, Result);
  1342. return Result;
  1343. }
  1344. case Type::PointerTyID: { // ConstantPointerRef value (backwards compat).
  1345. const PointerType *PT = cast<PointerType>(Ty);
  1346. unsigned Slot = read_vbr_uint();
  1347. // Check to see if we have already read this global variable...
  1348. Value *Val = getValue(TypeID, Slot, false);
  1349. if (Val) {
  1350. GlobalValue *GV = dyn_cast<GlobalValue>(Val);
  1351. if (!GV) error("GlobalValue not in ValueTable!");
  1352. if (Handler) Handler->handleConstantPointer(PT, Slot, GV);
  1353. return GV;
  1354. } else {
  1355. error("Forward references are not allowed here.");
  1356. }
  1357. }
  1358. default:
  1359. error("Don't know how to deserialize constant value of type '" +
  1360. Ty->getDescription());
  1361. break;
  1362. }
  1363. return 0;
  1364. }
  1365. /// Resolve references for constants. This function resolves the forward
  1366. /// referenced constants in the ConstantFwdRefs map. It uses the
  1367. /// replaceAllUsesWith method of Value class to substitute the placeholder
  1368. /// instance with the actual instance.
  1369. void BytecodeReader::ResolveReferencesToConstant(Constant *NewV, unsigned Typ,
  1370. unsigned Slot) {
  1371. ConstantRefsType::iterator I =
  1372. ConstantFwdRefs.find(std::make_pair(Typ, Slot));
  1373. if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
  1374. Value *PH = I->second; // Get the placeholder...
  1375. PH->replaceAllUsesWith(NewV);
  1376. delete PH; // Delete the old placeholder
  1377. ConstantFwdRefs.erase(I); // Remove the map entry for it
  1378. }
  1379. /// Parse the constant strings section.
  1380. void BytecodeReader::ParseStringConstants(unsigned NumEntries, ValueTable &Tab){
  1381. for (; NumEntries; --NumEntries) {
  1382. unsigned Typ = 0;
  1383. if (read_typeid(Typ))
  1384. error("Invalid type (type type) for string constant");
  1385. const Type *Ty = getType(Typ);
  1386. if (!isa<ArrayType>(Ty))
  1387. error("String constant data invalid!");
  1388. const ArrayType *ATy = cast<ArrayType>(Ty);
  1389. if (ATy->getElementType() != Type::SByteTy &&
  1390. ATy->getElementType() != Type::UByteTy)
  1391. error("String constant data invalid!");
  1392. // Read character data. The type tells us how long the string is.
  1393. char *Data = reinterpret_cast<char *>(alloca(ATy->getNumElements()));
  1394. read_data(Data, Data+ATy->getNumElements());
  1395. std::vector<Constant*> Elements(ATy->getNumElements());
  1396. if (ATy->getElementType() == Type::SByteTy)
  1397. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
  1398. Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
  1399. else
  1400. for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
  1401. Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
  1402. // Create the constant, inserting it as needed.
  1403. Constant *C = ConstantArray::get(ATy, Elements);
  1404. unsigned Slot = insertValue(C, Typ, Tab);
  1405. ResolveReferencesToConstant(C, Typ, Slot);
  1406. if (Handler) Handler->handleConstantString(cast<ConstantArray>(C));
  1407. }
  1408. }
  1409. /// Parse the constant pool.
  1410. void BytecodeReader::ParseConstantPool(ValueTable &Tab,
  1411. TypeListTy &TypeTab,
  1412. bool isFunction) {
  1413. if (Handler) Handler->handleGlobalConstantsBegin();
  1414. /// In LLVM 1.3 Type does not derive from Value so the types
  1415. /// do not occupy a plane. Consequently, we read the types
  1416. /// first in the constant pool.
  1417. if (isFunction && !hasTypeDerivedFromValue) {
  1418. unsigned NumEntries = read_vbr_uint();
  1419. ParseTypes(TypeTab, NumEntries);
  1420. }
  1421. while (moreInBlock()) {
  1422. unsigned NumEntries = read_vbr_uint();
  1423. unsigned Typ = 0;
  1424. bool isTypeType = read_typeid(Typ);
  1425. /// In LLVM 1.2 and before, Types were written to the
  1426. /// bytecode file in the "Type Type" plane (#12).
  1427. /// In 1.3 plane 12 is now the label plane. Handle this here.
  1428. if (isTypeType) {
  1429. ParseTypes(TypeTab, NumEntries);
  1430. } else if (Typ == Type::VoidTyID) {
  1431. /// Use of Type::VoidTyID is a misnomer. It actually means
  1432. /// that the following plane is constant strings
  1433. assert(&Tab == &ModuleValues && "Cannot read strings in functions!");
  1434. ParseStringConstants(NumEntries, Tab);
  1435. } else {
  1436. for (unsigned i = 0; i < NumEntries; ++i) {
  1437. Constant *C = ParseConstantValue(Typ);
  1438. assert(C && "ParseConstantValue returned NULL!");
  1439. unsigned Slot = insertValue(C, Typ, Tab);
  1440. // If we are reading a function constant table, make sure that we adjust
  1441. // the slot number to be the real global constant number.
  1442. //
  1443. if (&Tab != &ModuleValues && Typ < ModuleValues.size() &&
  1444. ModuleValues[Typ])
  1445. Slot += ModuleValues[Typ]->size();
  1446. ResolveReferencesToConstant(C, Typ, Slot);
  1447. }
  1448. }
  1449. }
  1450. // After we have finished parsing the constant pool, we had better not have
  1451. // any dangling references left.
  1452. if (!ConstantFwdRefs.empty()) {
  1453. ConstantRefsType::const_iterator I = ConstantFwdRefs.begin();
  1454. Constant* missingConst = I->second;
  1455. error(utostr(ConstantFwdRefs.size()) +
  1456. " unresolved constant reference exist. First one is '" +
  1457. missingConst->getName() + "' of type '" +
  1458. missingConst->getType()->getDescription() + "'.");
  1459. }
  1460. checkPastBlockEnd("Constant Pool");
  1461. if (Handler) Handler->handleGlobalConstantsEnd();
  1462. }
  1463. /// Parse the contents of a function. Note that this function can be
  1464. /// called lazily by materializeFunction
  1465. /// @see materializeFunction
  1466. void BytecodeReader::ParseFunctionBody(Function* F) {
  1467. unsigned FuncSize = BlockEnd - At;
  1468. GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
  1469. unsigned LinkageType = read_vbr_uint();
  1470. switch (LinkageType) {
  1471. case 0: Linkage = GlobalValue::ExternalLinkage; break;
  1472. case 1: Linkage = GlobalValue::WeakLinkage; break;
  1473. case 2: Linkage = GlobalValue::AppendingLinkage; break;
  1474. case 3: Linkage = GlobalValue::InternalLinkage; break;
  1475. case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
  1476. default:
  1477. error("Invalid linkage type for Function.");
  1478. Linkage = GlobalValue::InternalLinkage;
  1479. break;
  1480. }
  1481. F->setLinkage(Linkage);
  1482. if (Handler) Handler->handleFunctionBegin(F,FuncSize);
  1483. // Keep track of how many basic blocks we have read in...
  1484. unsigned BlockNum = 0;
  1485. bool InsertedArguments = false;
  1486. BufPtr MyEnd = BlockEnd;
  1487. while (At < MyEnd) {
  1488. unsigned Type, Size;
  1489. BufPtr OldAt = At;
  1490. read_block(Type, Size);
  1491. switch (Type) {
  1492. case BytecodeFormat::ConstantPoolBlockID:
  1493. if (!InsertedArguments) {
  1494. // Insert arguments into the value table before we parse the first basic
  1495. // block in the function, but after we potentially read in the
  1496. // compaction table.
  1497. insertArguments(F);
  1498. InsertedArguments = true;
  1499. }
  1500. ParseConstantPool(FunctionValues, FunctionTypes, true);
  1501. break;
  1502. case BytecodeFormat::CompactionTableBlockID:
  1503. ParseCompactionTable();
  1504. break;
  1505. case BytecodeFormat::BasicBlock: {
  1506. if (!InsertedArguments) {
  1507. // Insert arguments into the value table before we parse the first basic
  1508. // block in the function, but after we potentially read in the
  1509. // compaction table.
  1510. insertArguments(F);
  1511. InsertedArguments = true;
  1512. }
  1513. BasicBlock *BB = ParseBasicBlock(BlockNum++);
  1514. F->getBasicBlockList().push_back(BB);
  1515. break;
  1516. }
  1517. case BytecodeFormat::InstructionListBlockID: {
  1518. // Insert arguments into the value table before we parse the instruction
  1519. // list for the function, but after we potentially read in the compaction
  1520. // table.
  1521. if (!InsertedArguments) {
  1522. insertArguments(F);
  1523. InsertedArguments = true;
  1524. }
  1525. if (BlockNum)
  1526. error("Already parsed basic blocks!");
  1527. BlockNum = ParseInstructionList(F);
  1528. break;
  1529. }
  1530. case BytecodeFormat::SymbolTableBlockID:
  1531. ParseSymbolTable(F, &F->getSymbolTable());
  1532. break;
  1533. default:
  1534. At += Size;
  1535. if (OldAt > At)
  1536. error("Wrapped around reading bytecode.");
  1537. break;
  1538. }
  1539. BlockEnd = MyEnd;
  1540. // Malformed bc file if read past end of block.
  1541. align32();
  1542. }
  1543. // Make sure there were no references to non-existant basic blocks.
  1544. if (BlockNum != ParsedBasicBlocks.size())
  1545. error("Illegal basic block operand reference");
  1546. ParsedBasicBlocks.clear();
  1547. // Resolve forward references. Replace any uses of a forward reference value
  1548. // with the real value.
  1549. while (!ForwardReferences.empty()) {
  1550. std::map<std::pair<unsigned,unsigned>, Value*>::iterator
  1551. I = ForwardReferences.begin();
  1552. Value *V = getValue(I->first.first, I->first.second, false);
  1553. Value *PlaceHolder = I->second;
  1554. PlaceHolder->replaceAllUsesWith(V);
  1555. ForwardReferences.erase(I);
  1556. delete PlaceHolder;
  1557. }
  1558. // Clear out function-level types...
  1559. FunctionTypes.clear();
  1560. CompactionTypes.clear();
  1561. CompactionValues.clear();
  1562. freeTable(FunctionValues);
  1563. if (Handler) Handler->handleFunctionEnd(F);
  1564. }
  1565. /// This function parses LLVM functions lazily. It obtains the type of the
  1566. /// function and records where the body of the function is in the bytecode
  1567. /// buffer. The caller can then use the ParseNextFunction and
  1568. /// ParseAllFunctionBodies to get handler events for the functions.
  1569. void BytecodeReader::ParseFunctionLazily() {
  1570. if (FunctionSignatureList.empty())
  1571. error("FunctionSignatureList empty!");
  1572. Function *Func = FunctionSignatureList.back();
  1573. FunctionSignatureList.pop_back();
  1574. // Save the information for future reading of the function
  1575. LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
  1576. // This function has a body but it's not loaded so it appears `External'.
  1577. // Mark it as a `Ghost' instead to notify the users that it has a body.
  1578. Func->setLinkage(GlobalValue::GhostLinkage);
  1579. // Pretend we've `parsed' this function
  1580. At = BlockEnd;
  1581. }
  1582. /// The ParserFunction method lazily parses one function. Use this method to
  1583. /// casue the parser to parse a specific function in the module. Note that
  1584. /// this will remove the function from what is to be included by
  1585. /// ParseAllFunctionBodies.
  1586. /// @see ParseAllFunctionBodies
  1587. /// @see ParseBytecode
  1588. void BytecodeReader::ParseFunction(Function* Func) {
  1589. // Find {start, end} pointers and slot in the map. If not there, we're done.
  1590. LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
  1591. // Make sure we found it
  1592. if (Fi == LazyFunctionLoadMap.end()) {
  1593. error("Unrecognized function of type " + Func->getType()->getDescription());
  1594. return;
  1595. }
  1596. BlockStart = At = Fi->second.Buf;
  1597. BlockEnd = Fi->second.EndBuf;
  1598. assert(Fi->first == Func && "Found wrong function?");
  1599. LazyFunctionLoadMap.erase(Fi);
  1600. this->ParseFunctionBody(Func);
  1601. }
  1602. /// The ParseAllFunctionBodies method parses through all the previously
  1603. /// unparsed functions in the bytecode file. If you want to completely parse
  1604. /// a bytecode file, this method should be called after Parsebytecode because
  1605. /// Parsebytecode only records the locations in the bytecode file of where
  1606. /// the function definitions are located. This function uses that information
  1607. /// to materialize the functions.
  1608. /// @see ParseBytecode
  1609. void BytecodeReader::ParseAllFunctionBodies() {
  1610. LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
  1611. LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
  1612. while (Fi != Fe) {
  1613. Function* Func = Fi->first;
  1614. BlockStart = At = Fi->second.Buf;
  1615. BlockEnd = Fi->second.EndBuf;
  1616. ParseFunctionBody(Func);
  1617. ++Fi;
  1618. }
  1619. LazyFunctionLoadMap.clear();
  1620. }
  1621. /// Parse the global type list
  1622. void BytecodeReader::ParseGlobalTypes() {
  1623. // Read the number of types
  1624. unsigned NumEntries = read_vbr_uint();
  1625. // Ignore the type plane identifier for types if the bc file is pre 1.3
  1626. if (hasTypeDerivedFromValue)
  1627. read_vbr_uint();
  1628. ParseTypes(ModuleTypes, NumEntries);
  1629. }
  1630. /// Parse the Global info (types, global vars, constants)
  1631. void BytecodeReader::ParseModuleGlobalInfo() {
  1632. if (Handler) Handler->handleModuleGlobalsBegin();
  1633. // Read global variables...
  1634. unsigned VarType = read_vbr_uint();
  1635. while (VarType != Type::VoidTyID) { // List is terminated by Void
  1636. // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
  1637. // Linkage, bit4+ = slot#
  1638. unsigned SlotNo = VarType >> 5;
  1639. if (sanitizeTypeId(SlotNo))
  1640. error("Invalid type (type type) for global var!");
  1641. unsigned LinkageID = (VarType >> 2) & 7;
  1642. bool isConstant = VarType & 1;
  1643. bool hasInitializer = VarType & 2;
  1644. GlobalValue::LinkageTypes Linkage;
  1645. switch (LinkageID) {
  1646. case 0: Linkage = GlobalValue::ExternalLinkage; break;
  1647. case 1: Linkage = GlobalValue::WeakLinkage; break;
  1648. case 2: Linkage = GlobalValue::AppendingLinkage; break;
  1649. case 3: Linkage = GlobalValue::InternalLinkage; break;
  1650. case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
  1651. default:
  1652. error("Unknown linkage type: " + utostr(LinkageID));
  1653. Linkage = GlobalValue::InternalLinkage;
  1654. break;
  1655. }
  1656. const Type *Ty = getType(SlotNo);
  1657. if (!Ty) {
  1658. error("Global has no type! SlotNo=" + utostr(SlotNo));
  1659. }
  1660. if (!isa<PointerType>(Ty)) {
  1661. error("Global not a pointer type! Ty= " + Ty->getDescription());
  1662. }
  1663. const Type *ElTy = cast<PointerType>(Ty)->getElementType();
  1664. // Create the global variable...
  1665. GlobalVariable *GV = new GlobalVariable(ElTy, isConstant, Linkage,
  1666. 0, "", TheModule);
  1667. insertValue(GV, SlotNo, ModuleValues);
  1668. unsigned initSlot = 0;
  1669. if (hasInitializer) {
  1670. initSlot = read_vbr_uint();
  1671. GlobalInits.push_back(std::make_pair(GV, initSlot));
  1672. }
  1673. // Notify handler about the global value.
  1674. if (Handler)
  1675. Handler->handleGlobalVariable(ElTy, isConstant, Linkage, SlotNo,initSlot);
  1676. // Get next item
  1677. VarType = read_vbr_uint();
  1678. }
  1679. // Read the function objects for all of the functions that are coming
  1680. unsigned FnSignature = read_vbr_uint();
  1681. if (hasNoFlagsForFunctions)
  1682. FnSignature = (FnSignature << 5) + 1;
  1683. // List is terminated by VoidTy.
  1684. while ((FnSignature >> 5) != Type::VoidTyID) {
  1685. const Type *Ty = getType(FnSignature >> 5);
  1686. if (!isa<PointerType>(Ty) ||
  1687. !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
  1688. error("Function not a pointer to function type! Ty = " +
  1689. Ty->getDescription());
  1690. }
  1691. // We create functions by passing the underlying FunctionType to create...
  1692. const FunctionType* FTy =
  1693. cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
  1694. // Insert the place holder.
  1695. Function* Func = new Function(FTy, GlobalValue::ExternalLinkage,
  1696. "", TheModule);
  1697. insertValue(Func, FnSignature >> 5, ModuleValues);
  1698. // Flags are not used yet.
  1699. unsigned Flags = FnSignature & 31;
  1700. // Save this for later so we know type of lazily instantiated functions.
  1701. // Note that known-external functions do not have FunctionInfo blocks, so we
  1702. // do not add them to the FunctionSignatureList.
  1703. if ((Flags & (1 << 4)) == 0)
  1704. FunctionSignatureList.push_back(Func);
  1705. // Look at the low bits. If there is a calling conv here, apply it,
  1706. // read it as a vbr.
  1707. Flags &= 15;
  1708. if (Flags)
  1709. Func->setCallingConv(Flags-1);
  1710. else
  1711. Func->setCallingConv(read_vbr_uint());
  1712. if (Handler) Handler->handleFunctionDeclaration(Func);
  1713. // Get the next function signature.
  1714. FnSignature = read_vbr_uint();
  1715. if (hasNoFlagsForFunctions)
  1716. FnSignature = (FnSignature << 5) + 1;
  1717. }
  1718. // Now that the function signature list is set up, reverse it so that we can
  1719. // remove elements efficiently from the back of the vector.
  1720. std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
  1721. // If this bytecode format has dependent library information in it ..
  1722. if (!hasNoDependentLibraries) {
  1723. // Read in the number of dependent library items that follow
  1724. unsigned num_dep_libs = read_vbr_uint();
  1725. std::string dep_lib;
  1726. while( num_dep_libs-- ) {
  1727. dep_lib = read_str();
  1728. TheModule->addLibrary(dep_lib);
  1729. if (Handler)
  1730. Handler->handleDependentLibrary(dep_lib);
  1731. }
  1732. // Read target triple and place into the module
  1733. std::string triple = read_str();
  1734. TheModule->setTargetTriple(triple);
  1735. if (Handler)
  1736. Handler->handleTargetTriple(triple);
  1737. }
  1738. if (hasInconsistentModuleGlobalInfo)
  1739. align32();
  1740. // This is for future proofing... in the future extra fields may be added that
  1741. // we don't understand, so we transparently ignore them.
  1742. //
  1743. At = BlockEnd;
  1744. if (Handler) Handler->handleModuleGlobalsEnd();
  1745. }
  1746. /// Parse the version information and decode it by setting flags on the
  1747. /// Reader that enable backward compatibility of the reader.
  1748. void BytecodeReader::ParseVersionInfo() {
  1749. unsigned Version = read_vbr_uint();
  1750. // Unpack version number: low four bits are for flags, top bits = version
  1751. Module::Endianness Endianness;
  1752. Module::PointerSize PointerSize;
  1753. Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
  1754. PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
  1755. bool hasNoEndianness = Version & 4;
  1756. bool hasNoPointerSize = Version & 8;
  1757. RevisionNum = Version >> 4;
  1758. // Default values for the current bytecode version
  1759. hasInconsistentModuleGlobalInfo = false;
  1760. hasExplicitPrimitiveZeros = false;
  1761. hasRestrictedGEPTypes = false;
  1762. hasTypeDerivedFromValue = false;
  1763. hasLongBlockHeaders = false;
  1764. has32BitTypes = false;
  1765. hasNoDependentLibraries = false;
  1766. hasAlignment = false;
  1767. hasNoUndefValue = false;
  1768. hasNoFlagsForFunctions = false;
  1769. hasNoUnreachableInst = false;
  1770. switch (RevisionNum) {
  1771. case 0: // LLVM 1.0, 1.1 (Released)
  1772. // Base LLVM 1.0 bytecode format.
  1773. hasInconsistentModuleGlobalInfo = true;
  1774. hasExplicitPrimitiveZeros = true;
  1775. // FALL THROUGH
  1776. case 1: // LLVM 1.2 (Released)
  1777. // LLVM 1.2 added explicit support for emitting strings efficiently.
  1778. // Also, it fixed the problem where the size of the ModuleGlobalInfo block
  1779. // included the size for the alignment at the end, where the rest of the
  1780. // blocks did not.
  1781. // LLVM 1.2 and before required that GEP indices be ubyte constants for
  1782. // structures and longs for sequential types.
  1783. hasRestrictedGEPTypes = true;
  1784. // LLVM 1.2 and before had the Type class derive from Value class. This
  1785. // changed in release 1.3 and consequently LLVM 1.3 bytecode files are
  1786. // written differently because Types can no longer be part of the
  1787. // type planes for Values.
  1788. hasTypeDerivedFromValue = true;
  1789. // FALL THROUGH
  1790. case 2: // 1.2.5 (Not Released)
  1791. // LLVM 1.2 and earlier had two-word block headers. This is a bit wasteful,
  1792. // especially for small files where the 8 bytes per block is a large
  1793. // fraction of the total block size. In LLVM 1.3, the block type and length
  1794. // are compressed into a single 32-bit unsigned integer. 27 bits for length,
  1795. // 5 bits for block type.
  1796. hasLongBlockHeaders = true;
  1797. // LLVM 1.2 and earlier wrote type slot numbers as vbr_uint32. In LLVM 1.3
  1798. // this has been reduced to vbr_uint24. It shouldn't make much difference
  1799. // since we haven't run into a module with > 24 million types, but for
  1800. // safety the 24-bit restriction has been enforced in 1.3 to free some bits
  1801. // in various places and to ensure consistency.
  1802. has32BitTypes = true;
  1803. // LLVM 1.2 and earlier did not provide a target triple nor a list of
  1804. // libraries on which the bytecode is dependent. LLVM 1.3 provides these
  1805. // features, for use in future versions of LLVM.
  1806. hasNoDependentLibraries = true;
  1807. // FALL THROUGH
  1808. case 3: // LLVM 1.3 (Released)
  1809. // LLVM 1.3 and earlier caused alignment bytes to be written on some block
  1810. // boundaries and at the end of some strings. In extreme cases (e.g. lots
  1811. // of GEP references to a constant array), this can increase the file size
  1812. // by 30% or more. In version 1.4 alignment is done away with completely.
  1813. hasAlignment = true;
  1814. // FALL THROUGH
  1815. case 4: // 1.3.1 (Not Released)
  1816. // In version 4, we did not support the 'undef' constant.
  1817. hasNoUndefValue = true;
  1818. // In version 4 and above, we did not include space for flags for functions
  1819. // in the module info block.
  1820. hasNoFlagsForFunctions = true;
  1821. // In version 4 and above, we did not include the 'unreachable' instruction
  1822. // in the opcode numbering in the bytecode file.
  1823. hasNoUnreachableInst = true;
  1824. break;
  1825. // FALL THROUGH
  1826. case 5: // 1.4 (Released)
  1827. break;
  1828. default:
  1829. error("Unknown bytecode version number: " + itostr(RevisionNum));
  1830. }
  1831. if (hasNoEndianness) Endianness = Module::AnyEndianness;
  1832. if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
  1833. TheModule->setEndianness(Endianness);
  1834. TheModule->setPointerSize(PointerSize);
  1835. if (Handler) Handler->handleVersionInfo(RevisionNum, Endianness, PointerSize);
  1836. }
  1837. /// Parse a whole module.
  1838. void BytecodeReader::ParseModule() {
  1839. unsigned Type, Size;
  1840. FunctionSignatureList.clear(); // Just in case...
  1841. // Read into instance variables...
  1842. ParseVersionInfo();
  1843. align32();
  1844. bool SeenModuleGlobalInfo = false;
  1845. bool SeenGlobalTypePlane = false;
  1846. BufPtr MyEnd = BlockEnd;
  1847. while (At < MyEnd) {
  1848. BufPtr OldAt = At;
  1849. read_block(Type, Size);
  1850. switch (Type) {
  1851. case BytecodeFormat::GlobalTypePlaneBlockID:
  1852. if (SeenGlobalTypePlane)
  1853. error("Two GlobalTypePlane Blocks Encountered!");
  1854. if (Size > 0)
  1855. ParseGlobalTypes();
  1856. SeenGlobalTypePlane = true;
  1857. break;
  1858. case BytecodeFormat::ModuleGlobalInfoBlockID:
  1859. if (SeenModuleGlobalInfo)
  1860. error("Two ModuleGlobalInfo Blocks Encountered!");
  1861. ParseModuleGlobalInfo();
  1862. SeenModuleGlobalInfo = true;
  1863. break;
  1864. case BytecodeFormat::ConstantPoolBlockID:
  1865. ParseConstantPool(ModuleValues, ModuleTypes,false);
  1866. break;
  1867. case BytecodeFormat::FunctionBlockID:
  1868. ParseFunctionLazily();
  1869. break;
  1870. case BytecodeFormat::SymbolTableBlockID:
  1871. ParseSymbolTable(0, &TheModule->getSymbolTable());
  1872. break;
  1873. default:
  1874. At += Size;
  1875. if (OldAt > At) {
  1876. error("Unexpected Block of Type #" + utostr(Type) + " encountered!");
  1877. }
  1878. break;
  1879. }
  1880. BlockEnd = MyEnd;
  1881. align32();
  1882. }
  1883. // After the module constant pool has been read, we can safely initialize
  1884. // global variables...
  1885. while (!GlobalInits.empty()) {
  1886. GlobalVariable *GV = GlobalInits.back().first;
  1887. unsigned Slot = GlobalInits.back().second;
  1888. GlobalInits.pop_back();
  1889. // Look up the initializer value...
  1890. // FIXME: Preserve this type ID!
  1891. const llvm::PointerType* GVType = GV->getType();
  1892. unsigned TypeSlot = getTypeSlot(GVType->getElementType());
  1893. if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
  1894. if (GV->hasInitializer())
  1895. error("Global *already* has an initializer?!");
  1896. if (Handler) Handler->handleGlobalInitializer(GV,CV);
  1897. GV->setInitializer(CV);
  1898. } else
  1899. error("Cannot find initializer value.");
  1900. }
  1901. if (!ConstantFwdRefs.empty())
  1902. error("Use of undefined constants in a module");
  1903. /// Make sure we pulled them all out. If we didn't then there's a declaration
  1904. /// but a missing body. That's not allowed.
  1905. if (!FunctionSignatureList.empty())
  1906. error("Function declared, but bytecode stream ended before definition");
  1907. }
  1908. /// This function completely parses a bytecode buffer given by the \p Buf
  1909. /// and \p Length parameters.
  1910. void BytecodeReader::ParseBytecode(BufPtr Buf, unsigned Length,
  1911. const std::string &ModuleID) {
  1912. try {
  1913. RevisionNum = 0;
  1914. At = MemStart = BlockStart = Buf;
  1915. MemEnd = BlockEnd = Buf + Length;
  1916. // Create the module
  1917. TheModule = new Module(ModuleID);
  1918. if (Handler) Handler->handleStart(TheModule, Length);
  1919. // Read the four bytes of the signature.
  1920. unsigned Sig = read_uint();
  1921. // If this is a compressed file
  1922. if (Sig == ('l' | ('l' << 8) | ('v' << 16) | ('c' << 24))) {
  1923. // Invoke the decompression of the bytecode. Note that we have to skip the
  1924. // file's magic number which is not part of the compressed block. Hence,
  1925. // the Buf+4 and Length-4. The result goes into decompressedBlock, a data
  1926. // member for retention until BytecodeReader is destructed.
  1927. unsigned decompressedLength = Compressor::decompressToNewBuffer(
  1928. (char*)Buf+4,Length-4,decompressedBlock);
  1929. // We must adjust the buffer pointers used by the bytecode reader to point
  1930. // into the new decompressed block. After decompression, the
  1931. // decompressedBlock will point to a contiguous memory area that has
  1932. // the decompressed data.
  1933. At = MemStart = BlockStart = Buf = (BufPtr) decompressedBlock;
  1934. MemEnd = BlockEnd = Buf + decompressedLength;
  1935. // else if this isn't a regular (uncompressed) bytecode file, then its
  1936. // and error, generate that now.
  1937. } else if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
  1938. error("Invalid bytecode signature: " + utohexstr(Sig));
  1939. }
  1940. // Tell the handler we're starting a module
  1941. if (Handler) Handler->handleModuleBegin(ModuleID);
  1942. // Get the module block and size and verify. This is handled specially
  1943. // because the module block/size is always written in long format. Other
  1944. // blocks are written in short format so the read_block method is used.
  1945. unsigned Type, Size;
  1946. Type = read_uint();
  1947. Size = read_uint();
  1948. if (Type != BytecodeFormat::ModuleBlockID) {
  1949. error("Expected Module Block! Type:" + utostr(Type) + ", Size:"
  1950. + utostr(Size));
  1951. }
  1952. // It looks like the darwin ranlib program is broken, and adds trailing
  1953. // garbage to the end of some bytecode files. This hack allows the bc
  1954. // reader to ignore trailing garbage on bytecode files.
  1955. if (At + Size < MemEnd)
  1956. MemEnd = BlockEnd = At+Size;
  1957. if (At + Size != MemEnd)
  1958. error("Invalid Top Level Block Length! Type:" + utostr(Type)
  1959. + ", Size:" + utostr(Size));
  1960. // Parse the module contents
  1961. this->ParseModule();
  1962. // Check for missing functions
  1963. if (hasFunctions())
  1964. error("Function expected, but bytecode stream ended!");
  1965. // Tell the handler we're done with the module
  1966. if (Handler)
  1967. Handler->handleModuleEnd(ModuleID);
  1968. // Tell the handler we're finished the parse
  1969. if (Handler) Handler->handleFinish();
  1970. } catch (std::string& errstr) {
  1971. if (Handler) Handler->handleError(errstr);
  1972. freeState();
  1973. delete TheModule;
  1974. TheModule = 0;
  1975. if (decompressedBlock != 0 ) {
  1976. ::free(decompressedBlock);
  1977. decompressedBlock = 0;
  1978. }
  1979. throw;
  1980. } catch (...) {
  1981. std::string msg("Unknown Exception Occurred");
  1982. if (Handler) Handler->handleError(msg);
  1983. freeState();
  1984. delete TheModule;
  1985. TheModule = 0;
  1986. if (decompressedBlock != 0) {
  1987. ::free(decompressedBlock);
  1988. decompressedBlock = 0;
  1989. }
  1990. throw msg;
  1991. }
  1992. }
  1993. //===----------------------------------------------------------------------===//
  1994. //=== Default Implementations of Handler Methods
  1995. //===----------------------------------------------------------------------===//
  1996. BytecodeHandler::~BytecodeHandler() {}