1 //===- Parser.cpp - Code to parse 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/Parser.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 "AnalyzerInternals.h"
20 #include "llvm/Module.h"
21 #include "llvm/Bytecode/Format.h"
22 #include "Support/StringExtras.h"
28 // Enable to trace to figure out what the heck is going on when parsing fails
29 //#define TRACE_LEVEL 10
30 //#define DEBUG_OUTPUT
32 #if TRACE_LEVEL // ByteCodeReading_TRACEr
33 #define BCR_TRACE(n, X) \
34 if (n < TRACE_LEVEL) std::cerr << std::string(n*2, ' ') << X
36 #define BCR_TRACE(n, X)
39 #define PARSE_ERROR(inserters) { \
40 std::ostringstream errormsg; \
41 errormsg << inserters; \
42 if ( ! handler->handleError( errormsg.str() ) ) \
43 throw std::string(errormsg.str()); \
46 inline bool AbstractBytecodeParser::moreInBlock() {
50 inline void AbstractBytecodeParser::checkPastBlockEnd(const char * block_name) {
52 PARSE_ERROR("Attempt to read past the end of " << block_name << " block.");
55 inline void AbstractBytecodeParser::align32() {
57 At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
58 if ( reportAlignment && At > Save ) handler->handleAlignment( At - Save );
60 throw std::string("Ran out of data while aligning!");
63 inline unsigned AbstractBytecodeParser::read_uint() {
65 throw std::string("Ran out of data reading uint!");
67 return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
70 inline unsigned AbstractBytecodeParser::read_vbr_uint() {
77 throw std::string("Ran out of data reading vbr_uint!");
78 Result |= (unsigned)((*At++) & 0x7F) << Shift;
80 } while (At[-1] & 0x80);
82 handler->handleVBR32(At-Save);
86 inline uint64_t AbstractBytecodeParser::read_vbr_uint64() {
93 throw std::string("Ran out of data reading vbr_uint64!");
94 Result |= (uint64_t)((*At++) & 0x7F) << Shift;
96 } while (At[-1] & 0x80);
98 handler->handleVBR64(At-Save);
102 inline int64_t AbstractBytecodeParser::read_vbr_int64() {
103 uint64_t R = read_vbr_uint64();
106 return -(int64_t)(R >> 1);
107 else // There is no such thing as -0 with integers. "-0" really means
108 // 0x8000000000000000.
111 return (int64_t)(R >> 1);
114 inline std::string AbstractBytecodeParser::read_str() {
115 unsigned Size = read_vbr_uint();
116 const unsigned char *OldAt = At;
118 if (At > BlockEnd) // Size invalid?
119 throw std::string("Ran out of data reading a string!");
120 return std::string((char*)OldAt, Size);
123 inline void AbstractBytecodeParser::read_data(void *Ptr, void *End) {
124 unsigned char *Start = (unsigned char *)Ptr;
125 unsigned Amount = (unsigned char *)End - Start;
126 if (At+Amount > BlockEnd)
127 throw std::string("Ran out of data!");
128 std::copy(At, At+Amount, Start);
132 inline void AbstractBytecodeParser::readBlock(unsigned &Type, unsigned &Size) {
136 if ( At + Size > BlockEnd )
137 throw std::string("Attempt to size a block past end of memory");
138 BlockEnd = At + Size;
139 if ( reportBlocks ) {
140 handler->handleBlock( Type, BlockStart, Size );
144 const Type *AbstractBytecodeParser::getType(unsigned ID) {
145 //cerr << "Looking up Type ID: " << ID << "\n";
147 if (ID < Type::FirstDerivedTyID)
148 if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
149 return T; // Asked for a primitive type...
151 // Otherwise, derived types need offset...
152 ID -= Type::FirstDerivedTyID;
154 if (!CompactionTypeTable.empty()) {
155 if (ID >= CompactionTypeTable.size())
156 PARSE_ERROR("Type ID out of range for compaction table!");
157 return CompactionTypeTable[ID];
160 // Is it a module-level type?
161 if (ID < ModuleTypes.size())
162 return ModuleTypes[ID].get();
164 // Nope, is it a function-level type?
165 ID -= ModuleTypes.size();
166 if (ID < FunctionTypes.size())
167 return FunctionTypes[ID].get();
169 PARSE_ERROR("Illegal type reference!");
173 bool AbstractBytecodeParser::ParseInstruction(std::vector<unsigned> &Operands) {
178 unsigned Op = read_uint();
180 // bits Instruction format: Common to all formats
181 // --------------------------
182 // 01-00: Opcode type, fixed to 1.
184 Opcode = (Op >> 2) & 63;
185 Operands.resize((Op >> 0) & 03);
187 switch (Operands.size()) {
189 // bits Instruction format:
190 // --------------------------
191 // 19-08: Resulting type plane
192 // 31-20: Operand #1 (if set to (2^12-1), then zero operands)
194 iType = (Op >> 8) & 4095;
195 Operands[0] = (Op >> 20) & 4095;
196 if (Operands[0] == 4095) // Handle special encoding for 0 operands...
200 // bits Instruction format:
201 // --------------------------
202 // 15-08: Resulting type plane
206 iType = (Op >> 8) & 255;
207 Operands[0] = (Op >> 16) & 255;
208 Operands[1] = (Op >> 24) & 255;
211 // bits Instruction format:
212 // --------------------------
213 // 13-08: Resulting type plane
218 iType = (Op >> 8) & 63;
219 Operands[0] = (Op >> 14) & 63;
220 Operands[1] = (Op >> 20) & 63;
221 Operands[2] = (Op >> 26) & 63;
224 At -= 4; // Hrm, try this again...
225 Opcode = read_vbr_uint();
227 iType = read_vbr_uint();
229 unsigned NumOperands = read_vbr_uint();
230 Operands.resize(NumOperands);
232 if (NumOperands == 0)
233 PARSE_ERROR("Zero-argument instruction found; this is invalid.");
235 for (unsigned i = 0; i != NumOperands; ++i)
236 Operands[i] = read_vbr_uint();
241 return handler->handleInstruction(Opcode, getType(iType), Operands, At-SaveAt);
244 /// ParseBasicBlock - In LLVM 1.0 bytecode files, we used to output one
245 /// basicblock at a time. This method reads in one of the basicblock packets.
246 void AbstractBytecodeParser::ParseBasicBlock( unsigned BlockNo) {
247 handler->handleBasicBlockBegin( BlockNo );
249 std::vector<unsigned> Args;
250 bool is_terminating = false;
251 while ( moreInBlock() )
252 is_terminating = ParseInstruction(Args);
254 if ( ! is_terminating )
255 PARSE_ERROR("Non-terminated basic block found!");
257 handler->handleBasicBlockEnd( BlockNo );
260 /// ParseInstructionList - Parse all of the BasicBlock's & Instruction's in the
261 /// body of a function. In post 1.0 bytecode files, we no longer emit basic
262 /// block individually, in order to avoid per-basic-block overhead.
263 unsigned AbstractBytecodeParser::ParseInstructionList() {
264 unsigned BlockNo = 0;
265 std::vector<unsigned> Args;
267 while ( moreInBlock() ) {
268 handler->handleBasicBlockBegin( BlockNo );
270 // Read instructions into this basic block until we get to a terminator
271 bool is_terminating = false;
272 while (moreInBlock() && !is_terminating )
273 is_terminating = ParseInstruction(Args ) ;
276 PARSE_ERROR( "Non-terminated basic block found!");
278 handler->handleBasicBlockEnd( BlockNo );
284 void AbstractBytecodeParser::ParseSymbolTable() {
285 handler->handleSymbolTableBegin();
287 while ( moreInBlock() ) {
288 // Symtab block header: [num entries][type id number]
289 unsigned NumEntries = read_vbr_uint();
290 unsigned Typ = read_vbr_uint();
291 const Type *Ty = getType(Typ);
293 handler->handleSymbolTablePlane( Typ, NumEntries, Ty );
295 for (unsigned i = 0; i != NumEntries; ++i) {
296 // Symtab entry: [def slot #][name]
297 unsigned slot = read_vbr_uint();
298 std::string Name = read_str();
300 if (Typ == Type::TypeTyID)
301 handler->handleSymbolTableType( i, slot, Name );
303 handler->handleSymbolTableValue( i, slot, Name );
306 checkPastBlockEnd("Symbol Table");
308 handler->handleSymbolTableEnd();
311 void AbstractBytecodeParser::ParseFunctionLazily() {
312 if (FunctionSignatureList.empty())
313 throw std::string("FunctionSignatureList empty!");
315 Function *Func = FunctionSignatureList.back();
316 FunctionSignatureList.pop_back();
318 // Save the information for future reading of the function
319 LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
321 // Pretend we've `parsed' this function
325 void AbstractBytecodeParser::ParseNextFunction(Function* Func) {
326 // Find {start, end} pointers and slot in the map. If not there, we're done.
327 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.find(Func);
329 // Make sure we found it
330 if ( Fi == LazyFunctionLoadMap.end() ) {
331 PARSE_ERROR("Unrecognized function of type " << Func->getType()->getDescription());
335 BlockStart = At = Fi->second.Buf;
336 BlockEnd = Fi->second.Buf;
337 assert(Fi->first == Func);
339 LazyFunctionLoadMap.erase(Fi);
341 this->ParseFunctionBody( Func );
344 void AbstractBytecodeParser::ParseAllFunctionBodies() {
345 LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
346 LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
349 Function* Func = Fi->first;
350 BlockStart = At = Fi->second.Buf;
351 BlockEnd = Fi->second.EndBuf;
352 this->ParseFunctionBody(Func);
357 void AbstractBytecodeParser::ParseFunctionBody(Function* Func ) {
359 unsigned FuncSize = BlockEnd - At;
360 GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
362 unsigned LinkageType = read_vbr_uint();
363 switch (LinkageType) {
364 case 0: Linkage = GlobalValue::ExternalLinkage; break;
365 case 1: Linkage = GlobalValue::WeakLinkage; break;
366 case 2: Linkage = GlobalValue::AppendingLinkage; break;
367 case 3: Linkage = GlobalValue::InternalLinkage; break;
368 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
370 PARSE_ERROR("Invalid linkage type for Function.");
371 Linkage = GlobalValue::InternalLinkage;
375 Func->setLinkage( Linkage );
376 handler->handleFunctionBegin(Func,FuncSize);
378 // Keep track of how many basic blocks we have read in...
379 unsigned BlockNum = 0;
380 bool InsertedArguments = false;
382 BufPtr MyEnd = BlockEnd;
383 while ( At < MyEnd ) {
386 readBlock(Type, Size);
389 case BytecodeFormat::ConstantPool:
390 ParseConstantPool(FunctionTypes );
393 case BytecodeFormat::CompactionTable:
394 ParseCompactionTable();
397 case BytecodeFormat::BasicBlock:
398 ParseBasicBlock(BlockNum++);
401 case BytecodeFormat::InstructionList:
403 PARSE_ERROR("InstructionList must come before basic blocks!");
404 BlockNum = ParseInstructionList();
407 case BytecodeFormat::SymbolTable:
414 PARSE_ERROR("Wrapped around reading bytecode");
419 // Malformed bc file if read past end of block.
423 handler->handleFunctionEnd(Func);
425 // Clear out function-level types...
426 FunctionTypes.clear();
427 CompactionTypeTable.clear();
430 void AbstractBytecodeParser::ParseCompactionTable() {
432 handler->handleCompactionTableBegin();
434 while ( moreInBlock() ) {
435 unsigned NumEntries = read_vbr_uint();
438 if ((NumEntries & 3) == 3) {
440 Ty = read_vbr_uint();
442 Ty = NumEntries >> 2;
446 handler->handleCompactionTablePlane( Ty, NumEntries );
448 if (Ty == Type::TypeTyID) {
449 for (unsigned i = 0; i != NumEntries; ++i) {
450 unsigned TypeSlot = read_vbr_uint();
451 const Type *Typ = getGlobalTableType(TypeSlot);
452 handler->handleCompactionTableType( i, TypeSlot, Typ );
455 const Type *Typ = getType(Ty);
456 // Push the implicit zero
457 for (unsigned i = 0; i != NumEntries; ++i) {
458 unsigned ValSlot = read_vbr_uint();
459 handler->handleCompactionTableValue( i, ValSlot, Typ );
463 handler->handleCompactionTableEnd();
466 const Type *AbstractBytecodeParser::ParseTypeConstant() {
467 unsigned PrimType = read_vbr_uint();
470 if ((Val = Type::getPrimitiveType((Type::TypeID)PrimType)))
474 case Type::FunctionTyID: {
475 const Type *RetType = getType(read_vbr_uint());
477 unsigned NumParams = read_vbr_uint();
479 std::vector<const Type*> Params;
481 Params.push_back(getType(read_vbr_uint()));
483 bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
484 if (isVarArg) Params.pop_back();
486 Type* result = FunctionType::get(RetType, Params, isVarArg);
487 handler->handleType( result );
490 case Type::ArrayTyID: {
491 unsigned ElTyp = read_vbr_uint();
492 const Type *ElementType = getType(ElTyp);
494 unsigned NumElements = read_vbr_uint();
496 BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size="
497 << NumElements << "\n");
498 Type* result = ArrayType::get(ElementType, NumElements);
499 handler->handleType( result );
502 case Type::StructTyID: {
503 std::vector<const Type*> Elements;
504 unsigned Typ = read_vbr_uint();
505 while (Typ) { // List is terminated by void/0 typeid
506 Elements.push_back(getType(Typ));
507 Typ = read_vbr_uint();
510 Type* result = StructType::get(Elements);
511 handler->handleType( result );
514 case Type::PointerTyID: {
515 unsigned ElTyp = read_vbr_uint();
516 BCR_TRACE(5, "Pointer Type Constant #" << ElTyp << "\n");
517 Type* result = PointerType::get(getType(ElTyp));
518 handler->handleType( result );
522 case Type::OpaqueTyID: {
523 Type* result = OpaqueType::get();
524 handler->handleType( result );
529 PARSE_ERROR("Don't know how to deserialize primitive type" << PrimType << "\n");
534 // ParseTypeConstants - We have to use this weird code to handle recursive
535 // types. We know that recursive types will only reference the current slab of
536 // values in the type plane, but they can forward reference types before they
537 // have been read. For example, Type #0 might be '{ Ty#1 }' and Type #1 might
538 // be 'Ty#0*'. When reading Type #0, type number one doesn't exist. To fix
539 // this ugly problem, we pessimistically insert an opaque type for each type we
540 // are about to read. This means that forward references will resolve to
541 // something and when we reread the type later, we can replace the opaque type
542 // with a new resolved concrete type.
544 void AbstractBytecodeParser::ParseTypeConstants(
545 TypeListTy &Tab, unsigned NumEntries
547 assert(Tab.size() == 0 && "should not have read type constants in before!");
549 // Insert a bunch of opaque types to be resolved later...
550 Tab.reserve(NumEntries);
551 for (unsigned i = 0; i != NumEntries; ++i)
552 Tab.push_back(OpaqueType::get());
554 // Loop through reading all of the types. Forward types will make use of the
555 // opaque types just inserted.
557 for (unsigned i = 0; i != NumEntries; ++i) {
558 const Type *NewTy = ParseTypeConstant(), *OldTy = Tab[i].get();
559 if (NewTy == 0) throw std::string("Couldn't parse type!");
560 BCR_TRACE(4, "#" << i << ": Read Type Constant: '" << NewTy <<
561 "' Replacing: " << OldTy << "\n");
563 // Don't insertValue the new type... instead we want to replace the opaque
564 // type with the new concrete value...
567 // Refine the abstract type to the new type. This causes all uses of the
568 // abstract type to use NewTy. This also will cause the opaque type to be
571 cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
573 // This should have replace the old opaque type with the new type in the
574 // value table... or with a preexisting type that was already in the system
575 assert(Tab[i] != OldTy && "refineAbstractType didn't work!");
578 BCR_TRACE(5, "Resulting types:\n");
579 for (unsigned i = 0; i < NumEntries; ++i) {
580 BCR_TRACE(5, (void*)Tab[i].get() << " - " << Tab[i].get() << "\n");
585 void AbstractBytecodeParser::ParseConstantValue(unsigned TypeID) {
587 // We must check for a ConstantExpr before switching by type because
588 // a ConstantExpr can be of any type, and has no explicit value.
590 // 0 if not expr; numArgs if is expr
591 unsigned isExprNumArgs = read_vbr_uint();
594 unsigned Opcode = read_vbr_uint();
595 const Type* Typ = getType(TypeID);
597 // FIXME: Encoding of constant exprs could be much more compact!
598 std::vector<std::pair<const Type*,unsigned> > ArgVec;
599 ArgVec.reserve(isExprNumArgs);
601 // Read the slot number and types of each of the arguments
602 for (unsigned i = 0; i != isExprNumArgs; ++i) {
603 unsigned ArgValSlot = read_vbr_uint();
604 unsigned ArgTypeSlot = read_vbr_uint();
605 BCR_TRACE(4, "CE Arg " << i << ": Type: '" << *getType(ArgTypeSlot)
606 << "' slot: " << ArgValSlot << "\n");
608 // Get the arg value from its slot if it exists, otherwise a placeholder
609 ArgVec.push_back(std::make_pair(getType(ArgTypeSlot), ArgValSlot));
612 handler->handleConstantExpression( Opcode, Typ, ArgVec );
616 // Ok, not an ConstantExpr. We now know how to read the given type...
617 const Type *Ty = getType(TypeID);
618 switch (Ty->getTypeID()) {
619 case Type::BoolTyID: {
620 unsigned Val = read_vbr_uint();
621 if (Val != 0 && Val != 1)
622 PARSE_ERROR("Invalid boolean value read.");
624 handler->handleConstantValue( ConstantBool::get(Val == 1));
628 case Type::UByteTyID: // Unsigned integer types...
629 case Type::UShortTyID:
630 case Type::UIntTyID: {
631 unsigned Val = read_vbr_uint();
632 if (!ConstantUInt::isValueValidForType(Ty, Val))
633 throw std::string("Invalid unsigned byte/short/int read.");
634 handler->handleConstantValue( ConstantUInt::get(Ty, Val) );
638 case Type::ULongTyID: {
639 handler->handleConstantValue( ConstantUInt::get(Ty, read_vbr_uint64()) );
643 case Type::SByteTyID: // Signed integer types...
644 case Type::ShortTyID:
645 case Type::IntTyID: {
647 int64_t Val = read_vbr_int64();
648 if (!ConstantSInt::isValueValidForType(Ty, Val))
649 throw std::string("Invalid signed byte/short/int/long read.");
650 handler->handleConstantValue( ConstantSInt::get(Ty, Val) );
654 case Type::FloatTyID: {
657 handler->handleConstantValue( ConstantFP::get(Ty, F) );
661 case Type::DoubleTyID: {
663 read_data(&Val, &Val+1);
664 handler->handleConstantValue( ConstantFP::get(Ty, Val) );
669 PARSE_ERROR("Type constants shouldn't live in constant table!");
672 case Type::ArrayTyID: {
673 const ArrayType *AT = cast<ArrayType>(Ty);
674 unsigned NumElements = AT->getNumElements();
675 std::vector<unsigned> Elements;
676 Elements.reserve(NumElements);
677 while (NumElements--) // Read all of the elements of the constant.
678 Elements.push_back(read_vbr_uint());
680 handler->handleConstantArray( AT, Elements );
684 case Type::StructTyID: {
685 const StructType *ST = cast<StructType>(Ty);
686 std::vector<unsigned> Elements;
687 Elements.reserve(ST->getNumElements());
688 for (unsigned i = 0; i != ST->getNumElements(); ++i)
689 Elements.push_back(read_vbr_uint());
690 handler->handleConstantStruct( ST, Elements );
694 case Type::PointerTyID: { // ConstantPointerRef value...
695 const PointerType *PT = cast<PointerType>(Ty);
696 unsigned Slot = read_vbr_uint();
697 handler->handleConstantPointer( PT, Slot );
702 PARSE_ERROR("Don't know how to deserialize constant value of type '"+
703 Ty->getDescription());
707 void AbstractBytecodeParser::ParseGlobalTypes() {
708 ParseConstantPool(ModuleTypes);
711 void AbstractBytecodeParser::ParseStringConstants(unsigned NumEntries ){
712 for (; NumEntries; --NumEntries) {
713 unsigned Typ = read_vbr_uint();
714 const Type *Ty = getType(Typ);
715 if (!isa<ArrayType>(Ty))
716 throw std::string("String constant data invalid!");
718 const ArrayType *ATy = cast<ArrayType>(Ty);
719 if (ATy->getElementType() != Type::SByteTy &&
720 ATy->getElementType() != Type::UByteTy)
721 throw std::string("String constant data invalid!");
723 // Read character data. The type tells us how long the string is.
724 char Data[ATy->getNumElements()];
725 read_data(Data, Data+ATy->getNumElements());
727 std::vector<Constant*> Elements(ATy->getNumElements());
728 if (ATy->getElementType() == Type::SByteTy)
729 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
730 Elements[i] = ConstantSInt::get(Type::SByteTy, (signed char)Data[i]);
732 for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
733 Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
735 // Create the constant, inserting it as needed.
736 ConstantArray *C = cast<ConstantArray>( ConstantArray::get(ATy, Elements) );
737 handler->handleConstantString( C );
742 void AbstractBytecodeParser::ParseConstantPool( TypeListTy &TypeTab) {
743 while ( moreInBlock() ) {
744 unsigned NumEntries = read_vbr_uint();
745 unsigned Typ = read_vbr_uint();
746 if (Typ == Type::TypeTyID) {
747 ParseTypeConstants(TypeTab, NumEntries);
748 } else if (Typ == Type::VoidTyID) {
749 ParseStringConstants(NumEntries);
751 BCR_TRACE(3, "Type: '" << *getType(Typ) << "' NumEntries: "
752 << NumEntries << "\n");
754 for (unsigned i = 0; i < NumEntries; ++i) {
755 ParseConstantValue(Typ);
760 checkPastBlockEnd("Constant Pool");
763 void AbstractBytecodeParser::ParseModuleGlobalInfo() {
765 handler->handleModuleGlobalsBegin();
767 // Read global variables...
768 unsigned VarType = read_vbr_uint();
769 while (VarType != Type::VoidTyID) { // List is terminated by Void
770 // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
771 // Linkage, bit4+ = slot#
772 unsigned SlotNo = VarType >> 5;
773 unsigned LinkageID = (VarType >> 2) & 7;
774 bool isConstant = VarType & 1;
775 bool hasInitializer = VarType & 2;
776 GlobalValue::LinkageTypes Linkage;
779 case 0: Linkage = GlobalValue::ExternalLinkage; break;
780 case 1: Linkage = GlobalValue::WeakLinkage; break;
781 case 2: Linkage = GlobalValue::AppendingLinkage; break;
782 case 3: Linkage = GlobalValue::InternalLinkage; break;
783 case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
785 PARSE_ERROR("Unknown linkage type: " << LinkageID);
786 Linkage = GlobalValue::InternalLinkage;
790 const Type *Ty = getType(SlotNo);
792 PARSE_ERROR("Global has no type! SlotNo=" << SlotNo);
795 if ( !isa<PointerType>(Ty)) {
796 PARSE_ERROR("Global not a pointer type! Ty= " << Ty->getDescription());
799 const Type *ElTy = cast<PointerType>(Ty)->getElementType();
801 // Create the global variable...
802 if (hasInitializer) {
803 unsigned initSlot = read_vbr_uint();
804 handler->handleInitializedGV( ElTy, isConstant, Linkage, initSlot );
806 handler->handleGlobalVariable( ElTy, isConstant, Linkage );
809 VarType = read_vbr_uint();
812 // Read the function objects for all of the functions that are coming
813 unsigned FnSignature = read_vbr_uint();
814 while (FnSignature != Type::VoidTyID) { // List is terminated by Void
815 const Type *Ty = getType(FnSignature);
816 if (!isa<PointerType>(Ty) ||
817 !isa<FunctionType>(cast<PointerType>(Ty)->getElementType())) {
818 PARSE_ERROR( "Function not a pointer to function type! Ty = " +
819 Ty->getDescription());
820 // FIXME: what should Ty be if handler continues?
823 // We create functions by passing the underlying FunctionType to create...
824 const FunctionType* FTy =
825 cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
826 Function* Func = new Function(FTy, GlobalValue::ExternalLinkage);
828 // Save this for later so we know type of lazily instantiated functions
829 FunctionSignatureList.push_back(Func);
831 handler->handleFunctionDeclaration(Func, FTy);
833 // Get Next function signature
834 FnSignature = read_vbr_uint();
837 if (hasInconsistentModuleGlobalInfo)
840 // Now that the function signature list is set up, reverse it so that we can
841 // remove elements efficiently from the back of the vector.
842 std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
844 // This is for future proofing... in the future extra fields may be added that
845 // we don't understand, so we transparently ignore them.
849 handler->handleModuleGlobalsEnd();
852 void AbstractBytecodeParser::ParseVersionInfo() {
853 unsigned Version = read_vbr_uint();
855 // Unpack version number: low four bits are for flags, top bits = version
856 Module::Endianness Endianness;
857 Module::PointerSize PointerSize;
858 Endianness = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
859 PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
861 bool hasNoEndianness = Version & 4;
862 bool hasNoPointerSize = Version & 8;
864 RevisionNum = Version >> 4;
866 // Default values for the current bytecode version
867 hasInconsistentModuleGlobalInfo = false;
868 hasExplicitPrimitiveZeros = false;
869 hasRestrictedGEPTypes = false;
871 switch (RevisionNum) {
872 case 0: // LLVM 1.0, 1.1 release version
873 // Base LLVM 1.0 bytecode format.
874 hasInconsistentModuleGlobalInfo = true;
875 hasExplicitPrimitiveZeros = true;
877 case 1: // LLVM 1.2 release version
878 // LLVM 1.2 added explicit support for emitting strings efficiently.
880 // Also, it fixed the problem where the size of the ModuleGlobalInfo block
881 // included the size for the alignment at the end, where the rest of the
884 // LLVM 1.2 and before required that GEP indices be ubyte constants for
885 // structures and longs for sequential types.
886 hasRestrictedGEPTypes = true;
889 case 2: // LLVM 1.3 release version
893 PARSE_ERROR("Unknown bytecode version number: " << RevisionNum);
896 if (hasNoEndianness) Endianness = Module::AnyEndianness;
897 if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
899 handler->handleVersionInfo(RevisionNum, Endianness, PointerSize );
902 void AbstractBytecodeParser::ParseModule() {
905 FunctionSignatureList.clear(); // Just in case...
907 // Read into instance variables...
909 align32(); /// FIXME: Is this redundant? VI is first and 4 bytes!
911 bool SeenModuleGlobalInfo = false;
912 bool SeenGlobalTypePlane = false;
913 BufPtr MyEnd = BlockEnd;
916 readBlock(Type, Size);
920 case BytecodeFormat::GlobalTypePlane:
921 if ( SeenGlobalTypePlane )
922 PARSE_ERROR("Two GlobalTypePlane Blocks Encountered!");
925 SeenGlobalTypePlane = true;
928 case BytecodeFormat::ModuleGlobalInfo:
929 if ( SeenModuleGlobalInfo )
930 PARSE_ERROR("Two ModuleGlobalInfo Blocks Encountered!");
931 ParseModuleGlobalInfo();
932 SeenModuleGlobalInfo = true;
935 case BytecodeFormat::ConstantPool:
936 ParseConstantPool(ModuleTypes);
939 case BytecodeFormat::Function:
940 ParseFunctionLazily();
943 case BytecodeFormat::SymbolTable:
950 PARSE_ERROR("Unexpected Block of Type" << Type << "encountered!" );
958 /// Make sure we pulled them all out. If we didn't then there's a declaration
959 /// but a missing body. That's not allowed.
960 if (!FunctionSignatureList.empty())
962 "Function declared, but bytecode stream ended before definition");
965 void AbstractBytecodeParser::ParseBytecode(
966 BufPtr b, unsigned Length,
967 const std::string &ModuleID) {
969 At = MemStart = BlockStart = b;
970 MemEnd = BlockEnd = b + Length;
971 handler->handleStart();
973 // Read and check signature...
974 unsigned Sig = read_uint();
975 if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24))) {
976 PARSE_ERROR("Invalid bytecode signature: " << Sig);
979 handler->handleModuleBegin(ModuleID);
982 readBlock(Type, Size);
983 if ( Type != BytecodeFormat::Module ) {
984 PARSE_ERROR("Expected Module Block! At: " << unsigned(intptr_t(At))
985 << ", Type:" << Type << ", Size:" << Size);
987 if ( At + Size != MemEnd ) {
988 PARSE_ERROR("Invalid Top Level Block Length! At: "
989 << unsigned(intptr_t(At)) << ", Type:" << Type << ", Size:" << Size);
993 handler->handleModuleEnd(ModuleID);
995 handler->handleFinish();
998 //===----------------------------------------------------------------------===//
999 //=== Default Implementations of Handler Methods
1000 //===----------------------------------------------------------------------===//
1002 bool BytecodeHandler::handleError(const std::string& str ) { return false; }
1003 void BytecodeHandler::handleStart() { }
1004 void BytecodeHandler::handleFinish() { }
1005 void BytecodeHandler::handleModuleBegin(const std::string& id) { }
1006 void BytecodeHandler::handleModuleEnd(const std::string& id) { }
1007 void BytecodeHandler::handleVersionInfo( unsigned char RevisionNum,
1008 Module::Endianness Endianness, Module::PointerSize PointerSize) { }
1009 void BytecodeHandler::handleModuleGlobalsBegin() { }
1010 void BytecodeHandler::handleGlobalVariable(
1011 const Type* ElemType, bool isConstant, GlobalValue::LinkageTypes ) { }
1012 void BytecodeHandler::handleInitializedGV(
1013 const Type* ElemType, bool isConstant, GlobalValue::LinkageTypes,
1014 unsigned initSlot) {}
1015 void BytecodeHandler::handleType( const Type* Ty ) {}
1016 void BytecodeHandler::handleFunctionDeclaration(
1017 Function* Func, const FunctionType* FuncType) {}
1018 void BytecodeHandler::handleModuleGlobalsEnd() { }
1019 void BytecodeHandler::handleCompactionTableBegin() { }
1020 void BytecodeHandler::handleCompactionTablePlane( unsigned Ty,
1021 unsigned NumEntries) {}
1022 void BytecodeHandler::handleCompactionTableType( unsigned i, unsigned TypSlot,
1024 void BytecodeHandler::handleCompactionTableValue( unsigned i, unsigned ValSlot,
1026 void BytecodeHandler::handleCompactionTableEnd() { }
1027 void BytecodeHandler::handleSymbolTableBegin() { }
1028 void BytecodeHandler::handleSymbolTablePlane( unsigned Ty, unsigned NumEntries,
1029 const Type* Typ) { }
1030 void BytecodeHandler::handleSymbolTableType( unsigned i, unsigned slot,
1031 const std::string& name ) { }
1032 void BytecodeHandler::handleSymbolTableValue( unsigned i, unsigned slot,
1033 const std::string& name ) { }
1034 void BytecodeHandler::handleSymbolTableEnd() { }
1035 void BytecodeHandler::handleFunctionBegin( Function* Func,
1037 void BytecodeHandler::handleFunctionEnd( Function* Func) { }
1038 void BytecodeHandler::handleBasicBlockBegin( unsigned blocknum) { }
1039 bool BytecodeHandler::handleInstruction( unsigned Opcode, const Type* iType,
1040 std::vector<unsigned>& Operands, unsigned Size) {
1041 return Instruction::isTerminator(Opcode);
1043 void BytecodeHandler::handleBasicBlockEnd(unsigned blocknum) { }
1044 void BytecodeHandler::handleGlobalConstantsBegin() { }
1045 void BytecodeHandler::handleConstantExpression( unsigned Opcode,
1046 const Type* Typ, std::vector<std::pair<const Type*,unsigned> > ArgVec ) { }
1047 void BytecodeHandler::handleConstantValue( Constant * c ) { }
1048 void BytecodeHandler::handleConstantArray( const ArrayType* AT,
1049 std::vector<unsigned>& Elements ) { }
1050 void BytecodeHandler::handleConstantStruct( const StructType* ST,
1051 std::vector<unsigned>& ElementSlots) { }
1052 void BytecodeHandler::handleConstantPointer(
1053 const PointerType* PT, unsigned Slot) { }
1054 void BytecodeHandler::handleConstantString( const ConstantArray* CA ) {}
1055 void BytecodeHandler::handleGlobalConstantsEnd() {}
1056 void BytecodeHandler::handleAlignment(unsigned numBytes) {}
1057 void BytecodeHandler::handleBlock(
1058 unsigned BType, const unsigned char* StartPtr, unsigned Size) {}
1059 void BytecodeHandler::handleVBR32(unsigned Size ) {}
1060 void BytecodeHandler::handleVBR64(unsigned Size ) {}