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: Return error messages to caller instead of printing them out directly.
16 // TODO: Allow passing in an option to ignore the symbol table
18 //===----------------------------------------------------------------------===//
20 #include "ReaderInternals.h"
21 #include "llvm/Bytecode/Reader.h"
22 #include "llvm/Bytecode/Format.h"
23 #include "llvm/Constants.h"
24 #include "llvm/iPHINode.h"
25 #include "llvm/iOther.h"
26 #include "llvm/Module.h"
27 #include "Support/StringExtras.h"
28 #include "Config/unistd.h"
29 #include "Config/sys/mman.h"
30 #include "Config/sys/stat.h"
31 #include "Config/sys/types.h"
35 static inline void ALIGN32(const unsigned char *&begin,
36 const unsigned char *end) {
37 if (align32(begin, end))
38 throw std::string("Alignment error in buffer: read past end of block.");
41 unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
42 if (Ty->isPrimitiveType())
43 return Ty->getPrimitiveID();
45 // Check the function level types first...
46 TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
47 FunctionTypeValues.end(), Ty);
48 if (I != FunctionTypeValues.end())
49 return FirstDerivedTyID + ModuleTypeValues.size() +
50 (&*I - &FunctionTypeValues[0]);
52 I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
53 if (I == ModuleTypeValues.end())
54 throw std::string("Didn't find type in ModuleTypeValues.");
55 return FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
58 const Type *BytecodeParser::getType(unsigned ID) {
59 if (ID < Type::NumPrimitiveIDs)
60 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
63 //cerr << "Looking up Type ID: " << ID << "\n";
65 if (ID < Type::NumPrimitiveIDs)
66 if (const Type *T = Type::getPrimitiveType((Type::PrimitiveID)ID))
67 return T; // Asked for a primitive type...
69 // Otherwise, derived types need offset...
70 ID -= FirstDerivedTyID;
72 // Is it a module-level type?
73 if (ID < ModuleTypeValues.size())
74 return ModuleTypeValues[ID].get();
76 // Nope, is it a function-level type?
77 ID -= ModuleTypeValues.size();
78 if (ID < FunctionTypeValues.size())
79 return FunctionTypeValues[ID].get();
81 throw std::string("Illegal type reference!");
84 unsigned BytecodeParser::insertValue(Value *Val, ValueTable &ValueTab) {
85 return insertValue(Val, getTypeSlot(Val->getType()), ValueTab);
88 unsigned BytecodeParser::insertValue(Value *Val, unsigned type,
89 ValueTable &ValueTab) {
90 assert((!isa<Constant>(Val) || Val->getType()->isPrimitiveType() ||
91 !cast<Constant>(Val)->isNullValue()) &&
92 "Cannot read null values from bytecode!");
93 assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
95 if (ValueTab.size() <= type) {
96 unsigned OldSize = ValueTab.size();
97 ValueTab.resize(type+1);
98 while (OldSize != type+1)
99 ValueTab[OldSize++] = new ValueList();
102 //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size()
103 // << "] = " << Val << "\n";
104 ValueTab[type]->push_back(Val);
106 bool HasOffset = !Val->getType()->isPrimitiveType();
107 return ValueTab[type]->size()-1 + HasOffset;
111 Value *BytecodeParser::getValue(const Type *Ty, unsigned oNum, bool Create) {
112 return getValue(getTypeSlot(Ty), oNum, Create);
115 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
116 assert(type != Type::TypeTyID && "getValue() cannot get types!");
117 assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
120 if (type >= FirstDerivedTyID) {
122 return Constant::getNullValue(getType(type));
126 if (type < ModuleValues.size()) {
127 if (Num < ModuleValues[type]->size())
128 return ModuleValues[type]->getOperand(Num);
129 Num -= ModuleValues[type]->size();
132 if (Values.size() > type && Values[type]->size() > Num)
133 return Values[type]->getOperand(Num);
135 if (!Create) return 0; // Do not create a placeholder?
137 std::pair<unsigned,unsigned> KeyValue(type, oNum);
138 std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
139 ForwardReferences.lower_bound(KeyValue);
140 if (I != ForwardReferences.end() && I->first == KeyValue)
141 return I->second; // We have already created this placeholder
143 Value *Val = new Argument(getType(type));
144 ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
148 /// getBasicBlock - Get a particular numbered basic block, which might be a
149 /// forward reference. This works together with ParseBasicBlock to handle these
150 /// forward references in a clean manner.
152 BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
153 // Make sure there is room in the table...
154 if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
156 // First check to see if this is a backwards reference, i.e., ParseBasicBlock
157 // has already created this block, or if the forward reference has already
159 if (ParsedBasicBlocks[ID])
160 return ParsedBasicBlocks[ID];
162 // Otherwise, the basic block has not yet been created. Do so and add it to
163 // the ParsedBasicBlocks list.
164 return ParsedBasicBlocks[ID] = new BasicBlock();
167 /// getConstantValue - Just like getValue, except that it returns a null pointer
168 /// only on error. It always returns a constant (meaning that if the value is
169 /// defined, but is not a constant, that is an error). If the specified
170 /// constant hasn't been parsed yet, a placeholder is defined and used. Later,
171 /// after the real value is parsed, the placeholder is eliminated.
173 Constant *BytecodeParser::getConstantValue(const Type *Ty, unsigned Slot) {
174 if (Value *V = getValue(Ty, Slot, false))
175 if (Constant *C = dyn_cast<Constant>(V))
176 return C; // If we already have the value parsed, just return it
178 throw std::string("Reference of a value is expected to be a constant!");
180 std::pair<const Type*, unsigned> Key(Ty, Slot);
181 GlobalRefsType::iterator I = GlobalRefs.lower_bound(Key);
183 if (I != GlobalRefs.end() && I->first == Key) {
184 BCR_TRACE(5, "Previous forward ref found!\n");
185 return cast<Constant>(I->second);
187 // Create a placeholder for the constant reference and
188 // keep track of the fact that we have a forward ref to recycle it
189 BCR_TRACE(5, "Creating new forward ref to a constant!\n");
190 Constant *C = new ConstPHolder(Ty, Slot);
192 // Keep track of the fact that we have a forward ref to recycle it
193 GlobalRefs.insert(I, std::make_pair(Key, C));
199 BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
200 const unsigned char *EndBuf,
203 if (ParsedBasicBlocks.size() == BlockNo)
204 ParsedBasicBlocks.push_back(BB = new BasicBlock());
205 else if (ParsedBasicBlocks[BlockNo] == 0)
206 BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
208 BB = ParsedBasicBlocks[BlockNo];
210 std::vector<unsigned> Args;
212 ParseInstruction(Buf, EndBuf, Args, BB);
217 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
218 const unsigned char *EndBuf,
220 Function *CurrentFunction) {
221 // Allow efficient basic block lookup by number.
222 std::vector<BasicBlock*> BBMap;
224 for (Function::iterator I = CurrentFunction->begin(),
225 E = CurrentFunction->end(); I != E; ++I)
228 while (Buf < EndBuf) {
229 // Symtab block header: [num entries][type id number]
230 unsigned NumEntries, Typ;
231 if (read_vbr(Buf, EndBuf, NumEntries) ||
232 read_vbr(Buf, EndBuf, Typ)) throw Error_readvbr;
233 const Type *Ty = getType(Typ);
234 BCR_TRACE(3, "Plane Type: '" << *Ty << "' with " << NumEntries <<
237 for (unsigned i = 0; i != NumEntries; ++i) {
238 // Symtab entry: [def slot #][name]
240 if (read_vbr(Buf, EndBuf, slot)) throw Error_readvbr;
242 if (read(Buf, EndBuf, Name, false)) // Not aligned...
243 throw std::string("Failed reading symbol name.");
246 if (Typ == Type::TypeTyID)
247 V = (Value*)getType(slot);
248 else if (Typ == Type::LabelTyID) {
249 if (slot < BBMap.size())
252 V = getValue(Typ, slot, false); // Find mapping...
254 if (V == 0) throw std::string("Failed value look-up.");
255 BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
256 if (!isa<Instruction>(V)) std::cerr << "\n");
258 V->setName(Name, ST);
262 if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
265 void BytecodeParser::ResolveReferencesToValue(Value *NewV, unsigned Slot) {
266 GlobalRefsType::iterator I = GlobalRefs.find(std::make_pair(NewV->getType(),
268 if (I == GlobalRefs.end()) return; // Never forward referenced?
270 BCR_TRACE(3, "Mutating forward refs!\n");
271 Value *VPH = I->second; // Get the placeholder...
272 VPH->replaceAllUsesWith(NewV);
274 // If this is a global variable being resolved, remove the placeholder from
276 if (GlobalValue* GVal = dyn_cast<GlobalValue>(NewV))
277 GVal->getParent()->getGlobalList().remove(cast<GlobalVariable>(VPH));
279 delete VPH; // Delete the old placeholder
280 GlobalRefs.erase(I); // Remove the map entry for it
283 void BytecodeParser::ParseFunction(const unsigned char *&Buf,
284 const unsigned char *EndBuf) {
285 if (FunctionSignatureList.empty())
286 throw std::string("FunctionSignatureList empty!");
288 Function *F = FunctionSignatureList.back().first;
289 unsigned FunctionSlot = FunctionSignatureList.back().second;
290 FunctionSignatureList.pop_back();
292 // Save the information for future reading of the function
293 LazyFunctionInfo *LFI = new LazyFunctionInfo();
294 LFI->Buf = Buf; LFI->EndBuf = EndBuf; LFI->FunctionSlot = FunctionSlot;
295 LazyFunctionLoadMap[F] = LFI;
296 // Pretend we've `parsed' this function
300 void BytecodeParser::materializeFunction(Function* F) {
301 // Find {start, end} pointers and slot in the map. If not there, we're done.
302 std::map<Function*, LazyFunctionInfo*>::iterator Fi =
303 LazyFunctionLoadMap.find(F);
304 if (Fi == LazyFunctionLoadMap.end()) return;
306 LazyFunctionInfo *LFI = Fi->second;
307 const unsigned char *Buf = LFI->Buf;
308 const unsigned char *EndBuf = LFI->EndBuf;
309 unsigned FunctionSlot = LFI->FunctionSlot;
310 LazyFunctionLoadMap.erase(Fi);
313 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
315 if (!hasInternalMarkerOnly) {
316 // We didn't support weak linkage explicitly.
317 unsigned LinkageType;
318 if (read_vbr(Buf, EndBuf, LinkageType))
319 throw std::string("ParseFunction: Error reading from buffer.");
320 if ((!hasExtendedLinkageSpecs && LinkageType > 3) ||
321 ( hasExtendedLinkageSpecs && LinkageType > 4))
322 throw std::string("Invalid linkage type for Function.");
323 switch (LinkageType) {
324 case 0: Linkage = GlobalValue::ExternalLinkage; break;
325 case 1: Linkage = GlobalValue::WeakLinkage; break;
326 case 2: Linkage = GlobalValue::AppendingLinkage; break;
327 case 3: Linkage = GlobalValue::InternalLinkage; break;
328 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
331 // We used to only support two linkage models: internal and external
333 if (read_vbr(Buf, EndBuf, isInternal))
334 throw std::string("ParseFunction: Error reading from buffer.");
335 if (isInternal) Linkage = GlobalValue::InternalLinkage;
338 F->setLinkage(Linkage);
340 const FunctionType::ParamTypes &Params =F->getFunctionType()->getParamTypes();
341 Function::aiterator AI = F->abegin();
342 for (FunctionType::ParamTypes::const_iterator It = Params.begin();
343 It != Params.end(); ++It, ++AI)
344 insertValue(AI, Values);
346 // Keep track of how many basic blocks we have read in...
347 unsigned BlockNum = 0;
349 while (Buf < EndBuf) {
351 const unsigned char *OldBuf = Buf;
352 readBlock(Buf, EndBuf, Type, Size);
355 case BytecodeFormat::ConstantPool: {
356 BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
357 ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
361 case BytecodeFormat::BasicBlock: {
362 BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
363 BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
364 F->getBasicBlockList().push_back(BB);
368 case BytecodeFormat::SymbolTable: {
369 BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
370 ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
375 BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
378 throw std::string("Wrapped around reading bytecode.");
381 BCR_TRACE(2, "} end block\n");
383 // Malformed bc file if read past end of block.
384 ALIGN32(Buf, EndBuf);
387 // Make sure there were no references to non-existant basic blocks.
388 if (BlockNum != ParsedBasicBlocks.size())
389 throw std::string("Illegal basic block operand reference");
390 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...
438 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
439 while (VarType != Type::VoidTyID) { // List is terminated by Void
441 GlobalValue::LinkageTypes Linkage;
443 if (!hasInternalMarkerOnly) {
445 if (hasExtendedLinkageSpecs) {
446 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
447 // bit2,3,4 = Linkage, bit4+ = slot#
448 SlotNo = VarType >> 5;
449 LinkageID = (VarType >> 2) & 7;
451 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
452 // bit2,3 = Linkage, bit4+ = slot#
453 SlotNo = VarType >> 4;
454 LinkageID = (VarType >> 2) & 3;
457 default: assert(0 && "Unknown linkage type!");
458 case 0: Linkage = GlobalValue::ExternalLinkage; break;
459 case 1: Linkage = GlobalValue::WeakLinkage; break;
460 case 2: Linkage = GlobalValue::AppendingLinkage; break;
461 case 3: Linkage = GlobalValue::InternalLinkage; break;
462 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
465 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer,
466 // bit2 = isInternal, bit3+ = slot#
467 SlotNo = VarType >> 3;
468 Linkage = (VarType & 4) ? GlobalValue::InternalLinkage :
469 GlobalValue::ExternalLinkage;
472 const Type *Ty = getType(SlotNo);
473 if (!isa<PointerType>(Ty))
474 throw std::string("Global not pointer type! Ty = " +
475 Ty->getDescription());
477 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
479 // Create the global variable...
480 GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
482 BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
483 ResolveReferencesToValue(GV, insertValue(GV, SlotNo, ModuleValues));
485 if (VarType & 2) { // Does it have an initializer?
487 if (read_vbr(Buf, End, InitSlot)) throw Error_readvbr;
488 GlobalInits.push_back(std::make_pair(GV, InitSlot));
490 if (read_vbr(Buf, End, VarType)) throw Error_readvbr;
493 // Read the function objects for all of the functions that are coming
494 unsigned FnSignature;
495 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
496 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
497 const Type *Ty = getType(FnSignature);
498 if (!isa<PointerType>(Ty) ||
499 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
500 throw std::string("Function not ptr to func type! Ty = " +
501 Ty->getDescription());
503 // We create functions by passing the underlying FunctionType to create...
504 Ty = cast<PointerType>(Ty)->getElementType();
506 // When the ModuleGlobalInfo section is read, we load the type of each
507 // function and the 'ModuleValues' slot that it lands in. We then load a
508 // placeholder into its slot to reserve it. When the function is loaded,
509 // this placeholder is replaced.
511 // Insert the placeholder...
512 Function *Func = new Function(cast<FunctionType>(Ty),
513 GlobalValue::InternalLinkage, "", TheModule);
514 unsigned DestSlot = insertValue(Func, FnSignature, ModuleValues);
515 ResolveReferencesToValue(Func, DestSlot);
517 // Keep track of this information in a list that is emptied as functions are
520 FunctionSignatureList.push_back(std::make_pair(Func, DestSlot));
522 if (read_vbr(Buf, End, FnSignature)) throw Error_readvbr;
523 BCR_TRACE(2, "Function of type: " << Ty << "\n");
528 // Now that the function signature list is set up, reverse it so that we can
529 // remove elements efficiently from the back of the vector.
530 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
532 // This is for future proofing... in the future extra fields may be added that
533 // we don't understand, so we transparently ignore them.
538 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
539 const unsigned char *EndBuf) {
541 if (read_vbr(Buf, EndBuf, Version)) throw Error_readvbr;
543 // Unpack version number: low four bits are for flags, top bits = version
544 Module::Endianness Endianness;
545 Module::PointerSize PointerSize;
546 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
547 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
549 bool hasNoEndianness = Version & 4;
550 bool hasNoPointerSize = Version & 8;
552 RevisionNum = Version >> 4;
554 // Default values for the current bytecode version
555 hasInternalMarkerOnly = false;
556 hasExtendedLinkageSpecs = true;
557 hasOldStyleVarargs = false;
558 hasVarArgCallPadding = false;
559 FirstDerivedTyID = 14;
561 switch (RevisionNum) {
562 case 1: // LLVM pre-1.0 release: will be deleted on the next rev
563 // Version #1 has four bit fields: isBigEndian, hasLongPointers,
564 // hasNoEndianness, and hasNoPointerSize.
565 hasInternalMarkerOnly = true;
566 hasExtendedLinkageSpecs = false;
567 hasOldStyleVarargs = true;
568 hasVarArgCallPadding = true;
570 case 2: // LLVM pre-1.0 release:
571 // Version #2 added information about all 4 linkage types instead of just
572 // having internal and external.
573 hasExtendedLinkageSpecs = false;
574 hasOldStyleVarargs = true;
575 hasVarArgCallPadding = true;
577 case 0: // LLVM 1.0 release version
578 // Compared to rev #2, we added support for weak linkage, a more dense
579 // encoding, and better varargs support.
581 // FIXME: densify the encoding!
584 throw std::string("Unknown bytecode version number!");
587 if (hasNoEndianness) Endianness = Module::AnyEndianness;
588 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
590 TheModule->setEndianness(Endianness);
591 TheModule->setPointerSize(PointerSize);
592 BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
593 BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
594 << PointerSize << "\n");
597 void BytecodeParser::ParseModule(const unsigned char *Buf,
598 const unsigned char *EndBuf) {
600 readBlock(Buf, EndBuf, Type, Size);
601 if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
602 throw std::string("Expected Module packet! B: "+
603 utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
604 " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
606 BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
607 FunctionSignatureList.clear(); // Just in case...
609 // Read into instance variables...
610 ParseVersionInfo(Buf, EndBuf);
611 ALIGN32(Buf, EndBuf);
613 while (Buf < EndBuf) {
614 const unsigned char *OldBuf = Buf;
615 readBlock(Buf, EndBuf, Type, Size);
617 case BytecodeFormat::GlobalTypePlane:
618 BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
619 ParseGlobalTypes(Buf, Buf+Size);
622 case BytecodeFormat::ModuleGlobalInfo:
623 BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
624 ParseModuleGlobalInfo(Buf, Buf+Size);
627 case BytecodeFormat::ConstantPool:
628 BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
629 ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
632 case BytecodeFormat::Function: {
633 BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
634 ParseFunction(Buf, Buf+Size);
638 case BytecodeFormat::SymbolTable:
639 BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
640 ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
645 if (OldBuf > Buf) throw std::string("Expected Module Block!");
648 BCR_TRACE(1, "} end block\n");
649 ALIGN32(Buf, EndBuf);
652 // After the module constant pool has been read, we can safely initialize
653 // global variables...
654 while (!GlobalInits.empty()) {
655 GlobalVariable *GV = GlobalInits.back().first;
656 unsigned Slot = GlobalInits.back().second;
657 GlobalInits.pop_back();
659 // Look up the initializer value...
660 if (Value *V = getValue(GV->getType()->getElementType(), Slot, false)) {
661 if (GV->hasInitializer())
662 throw std::string("Global *already* has an initializer?!");
663 GV->setInitializer(cast<Constant>(V));
665 throw std::string("Cannot find initializer value.");
668 if (!FunctionSignatureList.empty())
669 throw std::string("Function expected, but bytecode stream ended!");
671 BCR_TRACE(0, "} end block\n\n");
674 void BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
675 const std::string &ModuleID) {
677 unsigned char *EndBuf = (unsigned char*)(Buf + Length);
679 // Read and check signature...
681 if (read(Buf, EndBuf, Sig) ||
682 Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
683 throw std::string("Invalid bytecode signature!");
685 TheModule = new Module(ModuleID);
687 usesOldStyleVarargs = false;
688 ParseModule(Buf, EndBuf);
689 } catch (std::string &Error) {
690 freeState(); // Must destroy handles before deleting module!