1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This library implements the functionality defined in llvm/Bytecode/Reader.h
12 // Note that this library should be as fast as possible, reentrant, and
15 // TODO: Allow passing in an option to ignore the symbol table
17 //===----------------------------------------------------------------------===//
19 #include "ReaderInternals.h"
20 #include "llvm/Bytecode/Reader.h"
21 #include "llvm/Bytecode/Format.h"
22 #include "llvm/Module.h"
23 #include "Support/StringExtras.h"
26 unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
27 if (Ty->isPrimitiveType())
28 return Ty->getPrimitiveID();
30 // Check the function level types first...
31 TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
32 FunctionTypeValues.end(), Ty);
33 if (I != FunctionTypeValues.end())
34 return FirstDerivedTyID + ModuleTypeValues.size() +
35 (&*I - &FunctionTypeValues[0]);
37 I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
38 if (I == ModuleTypeValues.end())
39 throw std::string("Didn't find type in ModuleTypeValues.");
40 return FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
43 const Type *BytecodeParser::getType(unsigned ID) {
44 if (ID < Type::NumPrimitiveIDs)
45 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
48 //cerr << "Looking up Type ID: " << ID << "\n";
50 if (ID < Type::NumPrimitiveIDs)
51 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
52 return T; // Asked for a primitive type...
54 // Otherwise, derived types need offset...
55 ID -= FirstDerivedTyID;
57 // Is it a module-level type?
58 if (ID < ModuleTypeValues.size())
59 return ModuleTypeValues[ID].get();
61 // Nope, is it a function-level type?
62 ID -= ModuleTypeValues.size();
63 if (ID < FunctionTypeValues.size())
64 return FunctionTypeValues[ID].get();
66 throw std::string("Illegal type reference!");
69 static inline bool hasImplicitNull(unsigned TyID, bool EncodesPrimitiveZeros) {
70 if (!EncodesPrimitiveZeros)
71 return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&
72 TyID != Type::VoidTyID;
73 return TyID >= Type::FirstDerivedTyID;
76 unsigned BytecodeParser::insertValue(Value *Val, unsigned type,
77 ValueTable &ValueTab) {
78 assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
79 !hasImplicitNull(type, hasExplicitPrimitiveZeros) &&
80 "Cannot read null values from bytecode!");
81 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
83 if (ValueTab.size() <= type) {
84 unsigned OldSize = ValueTab.size();
85 ValueTab.resize(type+1);
88 if (!ValueTab[type]) ValueTab[type] = new ValueList();
90 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
91 // << "] = " << Val << "\n";
92 ValueTab[type]->push_back(Val);
94 bool HasOffset = !Val->getType()->isPrimitiveType();
95 return ValueTab[type]->size()-1 + HasOffset;
98 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
99 assert(type != Type::TypeTyID && "getValue() cannot get types!");
100 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
103 if (hasImplicitNull(type, hasExplicitPrimitiveZeros)) {
105 return Constant::getNullValue(getType(type));
109 if (type < ModuleValues.size() && ModuleValues[type]) {
110 if (Num < ModuleValues[type]->size())
111 return ModuleValues[type]->getOperand(Num);
112 Num -= ModuleValues[type]->size();
115 if (Values.size() > type && Values[type] && Num < Values[type]->size())
116 return Values[type]->getOperand(Num);
118 if (!Create) return 0; // Do not create a placeholder?
120 std::pair<unsigned,unsigned> KeyValue(type, oNum);
121 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
122 ForwardReferences.lower_bound(KeyValue);
123 if (I != ForwardReferences.end() && I->first == KeyValue)
124 return I->second; // We have already created this placeholder
126 Value *Val = new Argument(getType(type));
127 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
131 /// getBasicBlock - Get a particular numbered basic block, which might be a
132 /// forward reference. This works together with ParseBasicBlock to handle these
133 /// forward references in a clean manner.
135 BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
136 // Make sure there is room in the table...
137 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
139 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
140 // has already created this block, or if the forward reference has already
142 if (ParsedBasicBlocks[ID])
143 return ParsedBasicBlocks[ID];
145 // Otherwise, the basic block has not yet been created. Do so and add it to
146 // the ParsedBasicBlocks list.
147 return ParsedBasicBlocks[ID] = new BasicBlock();
150 /// getConstantValue - Just like getValue, except that it returns a null pointer
151 /// only on error. It always returns a constant (meaning that if the value is
152 /// defined, but is not a constant, that is an error). If the specified
153 /// constant hasn't been parsed yet, a placeholder is defined and used. Later,
154 /// after the real value is parsed, the placeholder is eliminated.
156 Constant *BytecodeParser::getConstantValue(unsigned TypeSlot, unsigned Slot) {
157 if (Value *V = getValue(TypeSlot, Slot, false))
158 if (Constant *C = dyn_cast<Constant>(V))
159 return C; // If we already have the value parsed, just return it
160 else if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
161 // ConstantPointerRef's are an abomination, but at least they don't have
162 // to infest bytecode files.
163 return ConstantPointerRef::get(GV);
165 throw std::string("Reference of a value is expected to be a constant!");
167 const Type *Ty = getType(TypeSlot);
168 std::pair<const Type*, unsigned> Key(Ty, Slot);
169 ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
171 if (I != ConstantFwdRefs.end() && I->first == Key) {
172 BCR_TRACE(5, "Previous forward ref found!\n");
175 // Create a placeholder for the constant reference and
176 // keep track of the fact that we have a forward ref to recycle it
177 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
178 Constant *C = new ConstPHolder(Ty, Slot);
180 // Keep track of the fact that we have a forward ref to recycle it
181 ConstantFwdRefs.insert(I, std::make_pair(Key, C));
186 /// ParseBasicBlock - In LLVM 1.0 bytecode files, we used to output one
187 /// basicblock at a time. This method reads in one of the basicblock packets.
188 BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
189 const unsigned char *EndBuf,
192 if (ParsedBasicBlocks.size() == BlockNo)
193 ParsedBasicBlocks.push_back(BB = new BasicBlock());
194 else if (ParsedBasicBlocks[BlockNo] == 0)
195 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
197 BB = ParsedBasicBlocks[BlockNo];
199 std::vector<unsigned> Args;
201 ParseInstruction(Buf, EndBuf, Args, BB);
207 /// ParseInstructionList - Parse all of the BasicBlock's & Instruction's in the
208 /// body of a function. In post 1.0 bytecode files, we no longer emit basic
209 /// block individually, in order to avoid per-basic-block overhead.
210 unsigned BytecodeParser::ParseInstructionList(Function *F,
211 const unsigned char *&Buf,
212 const unsigned char *EndBuf) {
213 unsigned BlockNo = 0;
214 std::vector<unsigned> Args;
216 while (Buf < EndBuf) {
218 if (ParsedBasicBlocks.size() == BlockNo)
219 ParsedBasicBlocks.push_back(BB = new BasicBlock());
220 else if (ParsedBasicBlocks[BlockNo] == 0)
221 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
223 BB = ParsedBasicBlocks[BlockNo];
225 F->getBasicBlockList().push_back(BB);
227 // Read instructions into this basic block until we get to a terminator
228 while (Buf < EndBuf && !BB->getTerminator())
229 ParseInstruction(Buf, EndBuf, Args, BB);
231 if (!BB->getTerminator())
232 throw std::string("Non-terminated basic block found!");
238 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
239 const unsigned char *EndBuf,
241 Function *CurrentFunction) {
242 // Allow efficient basic block lookup by number.
243 std::vector<BasicBlock*> BBMap;
245 for (Function::iterator I = CurrentFunction->begin(),
246 E = CurrentFunction->end(); I != E; ++I)
249 while (Buf < EndBuf) {
250 // Symtab block header: [num entries][type id number]
251 unsigned NumEntries = read_vbr_uint(Buf, EndBuf);
252 unsigned Typ = read_vbr_uint(Buf, EndBuf);
253 const Type *Ty = getType(Typ);
254 BCR_TRACE(3, "Plane Type: '" << *Ty << "' with " << NumEntries <<
257 for (unsigned i = 0; i != NumEntries; ++i) {
258 // Symtab entry: [def slot #][name]
259 unsigned slot = read_vbr_uint(Buf, EndBuf);
260 std::string Name = read_str(Buf, EndBuf);
263 if (Typ == Type::TypeTyID)
264 V = (Value*)getType(slot);
265 else if (Typ == Type::LabelTyID) {
266 if (slot < BBMap.size())
269 V = getValue(Typ, slot, false); // Find mapping...
271 if (V == 0) throw std::string("Failed value look-up.");
272 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
273 if (!isa<Instruction>(V)) std::cerr << "\n");
275 V->setName(Name, ST);
279 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
282 void BytecodeParser::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
283 ConstantRefsType::iterator I =
284 ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
285 if (I == ConstantFwdRefs.end()) return; // Never forward referenced?
287 BCR_TRACE(3, "Mutating forward refs!\n");
288 Value *PH = I->second; // Get the placeholder...
289 PH->replaceAllUsesWith(NewV);
290 delete PH; // Delete the old placeholder
291 ConstantFwdRefs.erase(I); // Remove the map entry for it
294 void BytecodeParser::ParseFunction(const unsigned char *&Buf,
295 const unsigned char *EndBuf) {
296 if (FunctionSignatureList.empty())
297 throw std::string("FunctionSignatureList empty!");
299 Function *F = FunctionSignatureList.back();
300 FunctionSignatureList.pop_back();
302 // Save the information for future reading of the function
303 LazyFunctionLoadMap[F] = LazyFunctionInfo(Buf, EndBuf);
304 // Pretend we've `parsed' this function
308 void BytecodeParser::materializeFunction(Function* F) {
309 // Find {start, end} pointers and slot in the map. If not there, we're done.
310 std::map<Function*, LazyFunctionInfo>::iterator Fi =
311 LazyFunctionLoadMap.find(F);
312 if (Fi == LazyFunctionLoadMap.end()) return;
314 const unsigned char *Buf = Fi->second.Buf;
315 const unsigned char *EndBuf = Fi->second.EndBuf;
316 LazyFunctionLoadMap.erase(Fi);
318 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
320 unsigned LinkageType = read_vbr_uint(Buf, EndBuf);
321 if ((!hasExtendedLinkageSpecs && LinkageType > 3) ||
322 ( hasExtendedLinkageSpecs && LinkageType > 4))
323 throw std::string("Invalid linkage type for Function.");
324 switch (LinkageType) {
325 case 0: Linkage = GlobalValue::ExternalLinkage; break;
326 case 1: Linkage = GlobalValue::WeakLinkage; break;
327 case 2: Linkage = GlobalValue::AppendingLinkage; break;
328 case 3: Linkage = GlobalValue::InternalLinkage; break;
329 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
332 F->setLinkage(Linkage);
334 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
335 Function::aiterator AI = F->abegin();
336 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
337 It != Params.end(); ++It, ++AI)
338 insertValue(AI, getTypeSlot(AI->getType()), Values);
340 // Keep track of how many basic blocks we have read in...
341 unsigned BlockNum = 0;
343 while (Buf < EndBuf) {
345 const unsigned char *OldBuf = Buf;
346 readBlock(Buf, EndBuf, Type, Size);
349 case BytecodeFormat::ConstantPool:
350 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
351 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
354 case BytecodeFormat::BasicBlock: {
355 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
356 BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
357 F->getBasicBlockList().push_back(BB);
361 case BytecodeFormat::InstructionList: {
362 BCR_TRACE(2, "BLOCK BytecodeFormat::InstructionList: {\n");
363 if (BlockNum) throw std::string("Already parsed basic blocks!");
364 BlockNum = ParseInstructionList(F, Buf, Buf+Size);
368 case BytecodeFormat::SymbolTable:
369 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
370 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
374 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
377 throw std::string("Wrapped around reading bytecode.");
380 BCR_TRACE(2, "} end block\n");
382 // Malformed bc file if read past end of block.
383 align32(Buf, EndBuf);
386 // Make sure there were no references to non-existant basic blocks.
387 if (BlockNum != ParsedBasicBlocks.size())
388 throw std::string("Illegal basic block operand reference");
389 ParsedBasicBlocks.clear();
392 // Resolve forward references. Replace any uses of a forward reference value
393 // with the real value.
395 // replaceAllUsesWith is very inefficient for instructions which have a LARGE
396 // number of operands. PHI nodes often have forward references, and can also
397 // often have a very large number of operands.
398 std::map<Value*, Value*> ForwardRefMapping;
399 for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator
400 I = ForwardReferences.begin(), E = ForwardReferences.end();
402 ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
405 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
406 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
407 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
408 if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
409 std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
410 if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
413 while (!ForwardReferences.empty()) {
414 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
415 ForwardReferences.begin();
416 Value *PlaceHolder = I->second;
417 ForwardReferences.erase(I);
419 // Now that all the uses are gone, delete the placeholder...
420 // If we couldn't find a def (error case), then leak a little
421 // memory, because otherwise we can't remove all uses!
425 // Clear out function-level types...
426 FunctionTypeValues.clear();
431 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
432 const unsigned char *End) {
433 if (!FunctionSignatureList.empty())
434 throw std::string("Two ModuleGlobalInfo packets found!");
436 // Read global variables...
437 unsigned VarType = read_vbr_uint(Buf, End);
438 while (VarType != Type::VoidTyID) { // List is terminated by Void
440 GlobalValue::LinkageTypes Linkage;
443 if (hasExtendedLinkageSpecs) {
444 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
445 // bit2,3,4 = Linkage, bit4+ = slot#
446 SlotNo = VarType >> 5;
447 LinkageID = (VarType >> 2) & 7;
449 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
450 // bit2,3 = Linkage, bit4+ = slot#
451 SlotNo = VarType >> 4;
452 LinkageID = (VarType >> 2) & 3;
455 default: assert(0 && "Unknown linkage type!");
456 case 0: Linkage = GlobalValue::ExternalLinkage; break;
457 case 1: Linkage = GlobalValue::WeakLinkage; break;
458 case 2: Linkage = GlobalValue::AppendingLinkage; break;
459 case 3: Linkage = GlobalValue::InternalLinkage; break;
460 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
463 const Type *Ty = getType(SlotNo);
464 if (!isa<PointerType>(Ty))
465 throw std::string("Global not pointer type! Ty = " +
466 Ty->getDescription());
468 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
470 // Create the global variable...
471 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
473 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
474 insertValue(GV, SlotNo, ModuleValues);
476 if (VarType & 2) // Does it have an initializer?
477 GlobalInits.push_back(std::make_pair(GV, read_vbr_uint(Buf, End)));
478 VarType = read_vbr_uint(Buf, End);
481 // Read the function objects for all of the functions that are coming
482 unsigned FnSignature = read_vbr_uint(Buf, End);
483 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
484 const Type *Ty = getType(FnSignature);
485 if (!isa<PointerType>(Ty) ||
486 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
487 throw std::string("Function not ptr to func type! Ty = " +
488 Ty->getDescription());
490 // We create functions by passing the underlying FunctionType to create...
491 Ty = cast<PointerType>(Ty)->getElementType();
493 // When the ModuleGlobalInfo section is read, we load the type of each
494 // function and the 'ModuleValues' slot that it lands in. We then load a
495 // placeholder into its slot to reserve it. When the function is loaded,
496 // this placeholder is replaced.
498 // Insert the placeholder...
499 Function *Func = new Function(cast<FunctionType>(Ty),
500 GlobalValue::InternalLinkage, "", TheModule);
501 insertValue(Func, FnSignature, ModuleValues);
503 // Keep track of this information in a list that is emptied as functions are
506 FunctionSignatureList.push_back(Func);
508 FnSignature = read_vbr_uint(Buf, End);
509 BCR_TRACE(2, "Function of type: " << Ty << "\n");
512 if (hasInconsistentModuleGlobalInfo)
515 // Now that the function signature list is set up, reverse it so that we can
516 // remove elements efficiently from the back of the vector.
517 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
519 // This is for future proofing... in the future extra fields may be added that
520 // we don't understand, so we transparently ignore them.
525 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
526 const unsigned char *EndBuf) {
527 unsigned Version = read_vbr_uint(Buf, EndBuf);
529 // Unpack version number: low four bits are for flags, top bits = version
530 Module::Endianness Endianness;
531 Module::PointerSize PointerSize;
532 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
533 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
535 bool hasNoEndianness = Version & 4;
536 bool hasNoPointerSize = Version & 8;
538 RevisionNum = Version >> 4;
540 // Default values for the current bytecode version
541 hasExtendedLinkageSpecs = true;
542 hasOldStyleVarargs = false;
543 hasVarArgCallPadding = false;
544 hasInconsistentModuleGlobalInfo = false;
545 hasExplicitPrimitiveZeros = false;
546 FirstDerivedTyID = 14;
548 switch (RevisionNum) {
549 case 2: // LLVM pre-1.0 release: will be deleted on the next rev
550 // Version #2 only supported 4 linkage types. It didn't support weak
552 hasExtendedLinkageSpecs = false;
553 hasOldStyleVarargs = true;
554 hasVarArgCallPadding = true;
556 case 0: // LLVM 1.0, 1.1 release version
557 // Compared to rev #2, we added support for weak linkage, a more dense
558 // encoding, and better varargs support.
560 // Base LLVM 1.0 bytecode format.
561 hasInconsistentModuleGlobalInfo = true;
562 hasExplicitPrimitiveZeros = true;
564 case 1: // LLVM 1.2 release version
565 // LLVM 1.2 added explicit support for emitting strings efficiently.
567 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
568 // included the size for the alignment at the end, where the rest of the
573 throw std::string("Unknown bytecode version number!");
576 if (hasNoEndianness) Endianness = Module::AnyEndianness;
577 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
579 TheModule->setEndianness(Endianness);
580 TheModule->setPointerSize(PointerSize);
581 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
582 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
583 << PointerSize << "\n");
586 void BytecodeParser::ParseModule(const unsigned char *Buf,
587 const unsigned char *EndBuf) {
589 readBlock(Buf, EndBuf, Type, Size);
590 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
591 throw std::string("Expected Module packet! B: "+
592 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
593 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
595 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
596 FunctionSignatureList.clear(); // Just in case...
598 // Read into instance variables...
599 ParseVersionInfo(Buf, EndBuf);
600 align32(Buf, EndBuf);
602 while (Buf < EndBuf) {
603 const unsigned char *OldBuf = Buf;
604 readBlock(Buf, EndBuf, Type, Size);
606 case BytecodeFormat::GlobalTypePlane:
607 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
608 ParseGlobalTypes(Buf, Buf+Size);
611 case BytecodeFormat::ModuleGlobalInfo:
612 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
613 ParseModuleGlobalInfo(Buf, Buf+Size);
616 case BytecodeFormat::ConstantPool:
617 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
618 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
621 case BytecodeFormat::Function: {
622 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
623 ParseFunction(Buf, Buf+Size);
627 case BytecodeFormat::SymbolTable:
628 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
629 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
633 if (OldBuf > Buf) throw std::string("Expected Module Block!");
636 BCR_TRACE(1, "} end block\n");
637 align32(Buf, EndBuf);
640 // After the module constant pool has been read, we can safely initialize
641 // global variables...
642 while (!GlobalInits.empty()) {
643 GlobalVariable *GV = GlobalInits.back().first;
644 unsigned Slot = GlobalInits.back().second;
645 GlobalInits.pop_back();
647 // Look up the initializer value...
648 // FIXME: Preserve this type ID!
649 unsigned TypeSlot = getTypeSlot(GV->getType()->getElementType());
650 if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
651 if (GV->hasInitializer())
652 throw std::string("Global *already* has an initializer?!");
653 GV->setInitializer(CV);
655 throw std::string("Cannot find initializer value.");
658 if (!FunctionSignatureList.empty())
659 throw std::string("Function expected, but bytecode stream ended!");
661 BCR_TRACE(0, "} end block\n\n");
664 void BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
665 const std::string &ModuleID) {
667 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
669 // Read and check signature...
670 unsigned Sig = read(Buf, EndBuf);
671 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
672 throw std::string("Invalid bytecode signature!");
674 TheModule = new Module(ModuleID);
676 usesOldStyleVarargs = false;
677 ParseModule(Buf, EndBuf);
678 } catch (std::string &Error) {
679 freeState(); // Must destroy handles before deleting module!