Reader.cpp 80 KB

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