Merge Dumper.cpp and AnalyzerWrappers.cpp into this file. Also, adjust the
[oota-llvm.git] / lib / Bytecode / Reader / Parser.cpp
1 //===- Parser.cpp - Code to parse 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/Parser.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
19 #include "AnalyzerInternals.h"
20 #include "llvm/Module.h"
21 #include "llvm/Bytecode/Format.h"
22 #include "Support/StringExtras.h"
23 #include <iostream>
24 #include <sstream>
25
26 using namespace llvm;
27
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
31
32 #if TRACE_LEVEL    // ByteCodeReading_TRACEr
33 #define BCR_TRACE(n, X) \
34     if (n < TRACE_LEVEL) std::cerr << std::string(n*2, ' ') << X
35 #else
36 #define BCR_TRACE(n, X)
37 #endif
38
39 #define PARSE_ERROR(inserters) { \
40     std::ostringstream errormsg; \
41     errormsg << inserters; \
42     if ( ! handler->handleError( errormsg.str() ) ) \
43       throw std::string(errormsg.str()); \
44   }
45
46 inline bool AbstractBytecodeParser::moreInBlock() {
47   return At < BlockEnd;
48 }
49
50 inline void AbstractBytecodeParser::checkPastBlockEnd(const char * block_name) {
51   if ( At > BlockEnd )
52     PARSE_ERROR("Attempt to read past the end of " << block_name << " block.");
53 }
54
55 inline void AbstractBytecodeParser::align32() {
56   BufPtr Save = At;
57   At = (const unsigned char *)((unsigned long)(At+3) & (~3UL));
58   if ( reportAlignment && At > Save ) handler->handleAlignment( At - Save );
59   if (At > BlockEnd) 
60     throw std::string("Ran out of data while aligning!");
61 }
62
63 inline unsigned AbstractBytecodeParser::read_uint() {
64   if (At+4 > BlockEnd) 
65     throw std::string("Ran out of data reading uint!");
66   At += 4;
67   return At[-4] | (At[-3] << 8) | (At[-2] << 16) | (At[-1] << 24);
68 }
69
70 inline unsigned AbstractBytecodeParser::read_vbr_uint() {
71   unsigned Shift = 0;
72   unsigned Result = 0;
73   BufPtr Save = At;
74   
75   do {
76     if (At == BlockEnd) 
77       throw std::string("Ran out of data reading vbr_uint!");
78     Result |= (unsigned)((*At++) & 0x7F) << Shift;
79     Shift += 7;
80   } while (At[-1] & 0x80);
81   if (reportVBR)
82     handler->handleVBR32(At-Save);
83   return Result;
84 }
85
86 inline uint64_t AbstractBytecodeParser::read_vbr_uint64() {
87   unsigned Shift = 0;
88   uint64_t Result = 0;
89   BufPtr Save = At;
90   
91   do {
92     if (At == BlockEnd) 
93       throw std::string("Ran out of data reading vbr_uint64!");
94     Result |= (uint64_t)((*At++) & 0x7F) << Shift;
95     Shift += 7;
96   } while (At[-1] & 0x80);
97   if (reportVBR)
98     handler->handleVBR64(At-Save);
99   return Result;
100 }
101
102 inline int64_t AbstractBytecodeParser::read_vbr_int64() {
103   uint64_t R = read_vbr_uint64();
104   if (R & 1) {
105     if (R != 1)
106       return -(int64_t)(R >> 1);
107     else   // There is no such thing as -0 with integers.  "-0" really means
108            // 0x8000000000000000.
109       return 1LL << 63;
110   } else
111     return  (int64_t)(R >> 1);
112 }
113
114 inline std::string AbstractBytecodeParser::read_str() {
115   unsigned Size = read_vbr_uint();
116   const unsigned char *OldAt = At;
117   At += Size;
118   if (At > BlockEnd)             // Size invalid?
119     throw std::string("Ran out of data reading a string!");
120   return std::string((char*)OldAt, Size);
121 }
122
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);
129   At += Amount;
130 }
131
132 inline void AbstractBytecodeParser::readBlock(unsigned &Type, unsigned &Size) {
133   Type = read_uint();
134   Size = read_uint();
135   BlockStart = At;
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 );
141   }
142 }
143
144 const Type *AbstractBytecodeParser::getType(unsigned ID) {
145 //cerr << "Looking up Type ID: " << ID << "\n";
146
147 if (ID < Type::FirstDerivedTyID)
148   if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
149     return T;   // Asked for a primitive type...
150
151 // Otherwise, derived types need offset...
152 ID -= Type::FirstDerivedTyID;
153
154 if (!CompactionTypeTable.empty()) {
155   if (ID >= CompactionTypeTable.size())
156     PARSE_ERROR("Type ID out of range for compaction table!");
157   return CompactionTypeTable[ID];
158 }
159
160 // Is it a module-level type?
161   if (ID < ModuleTypes.size())
162     return ModuleTypes[ID].get();
163
164   // Nope, is it a function-level type?
165   ID -= ModuleTypes.size();
166   if (ID < FunctionTypes.size())
167     return FunctionTypes[ID].get();
168
169   PARSE_ERROR("Illegal type reference!");
170   return Type::VoidTy;
171 }
172
173 bool AbstractBytecodeParser::ParseInstruction(std::vector<unsigned> &Operands) {
174   BufPtr SaveAt = At;
175   Operands.clear();
176   unsigned iType = 0;
177   unsigned Opcode = 0;
178   unsigned Op = read_uint();
179
180   // bits   Instruction format:        Common to all formats
181   // --------------------------
182   // 01-00: Opcode type, fixed to 1.
183   // 07-02: Opcode
184   Opcode    = (Op >> 2) & 63;
185   Operands.resize((Op >> 0) & 03);
186
187   switch (Operands.size()) {
188   case 1:
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)
193     //
194     iType   = (Op >>  8) & 4095;
195     Operands[0] = (Op >> 20) & 4095;
196     if (Operands[0] == 4095)    // Handle special encoding for 0 operands...
197       Operands.resize(0);
198     break;
199   case 2:
200     // bits   Instruction format:
201     // --------------------------
202     // 15-08: Resulting type plane
203     // 23-16: Operand #1
204     // 31-24: Operand #2  
205     //
206     iType   = (Op >>  8) & 255;
207     Operands[0] = (Op >> 16) & 255;
208     Operands[1] = (Op >> 24) & 255;
209     break;
210   case 3:
211     // bits   Instruction format:
212     // --------------------------
213     // 13-08: Resulting type plane
214     // 19-14: Operand #1
215     // 25-20: Operand #2
216     // 31-26: Operand #3
217     //
218     iType   = (Op >>  8) & 63;
219     Operands[0] = (Op >> 14) & 63;
220     Operands[1] = (Op >> 20) & 63;
221     Operands[2] = (Op >> 26) & 63;
222     break;
223   case 0:
224     At -= 4;  // Hrm, try this again...
225     Opcode = read_vbr_uint();
226     Opcode >>= 2;
227     iType = read_vbr_uint();
228
229     unsigned NumOperands = read_vbr_uint();
230     Operands.resize(NumOperands);
231
232     if (NumOperands == 0)
233       PARSE_ERROR("Zero-argument instruction found; this is invalid.");
234
235     for (unsigned i = 0; i != NumOperands; ++i)
236       Operands[i] = read_vbr_uint();
237     align32();
238     break;
239   }
240
241   return handler->handleInstruction(Opcode, getType(iType), Operands, At-SaveAt);
242 }
243
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 );
248
249   std::vector<unsigned> Args;
250   bool is_terminating = false;
251   while ( moreInBlock() )
252     is_terminating = ParseInstruction(Args);
253
254   if ( ! is_terminating )
255     PARSE_ERROR("Non-terminated basic block found!");
256
257   handler->handleBasicBlockEnd( BlockNo );
258 }
259
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;
266
267   while ( moreInBlock() ) {
268     handler->handleBasicBlockBegin( BlockNo );
269
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 ) ;
274
275     if (!is_terminating)
276       PARSE_ERROR( "Non-terminated basic block found!");
277
278     handler->handleBasicBlockEnd( BlockNo );
279     ++BlockNo;
280   }
281   return BlockNo;
282 }
283
284 void AbstractBytecodeParser::ParseSymbolTable() {
285   handler->handleSymbolTableBegin();
286
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);
292
293     handler->handleSymbolTablePlane( Typ, NumEntries, Ty );
294
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();
299
300       if (Typ == Type::TypeTyID)
301         handler->handleSymbolTableType( i, slot, Name );
302       else
303         handler->handleSymbolTableValue( i, slot, Name );
304     }
305   }
306   checkPastBlockEnd("Symbol Table");
307
308   handler->handleSymbolTableEnd();
309 }
310
311 void AbstractBytecodeParser::ParseFunctionLazily() {
312   if (FunctionSignatureList.empty())
313     throw std::string("FunctionSignatureList empty!");
314
315   Function *Func = FunctionSignatureList.back();
316   FunctionSignatureList.pop_back();
317
318   // Save the information for future reading of the function
319   LazyFunctionLoadMap[Func] = LazyFunctionInfo(BlockStart, BlockEnd);
320
321   // Pretend we've `parsed' this function
322   At = BlockEnd;
323 }
324
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);
328
329   // Make sure we found it
330   if ( Fi == LazyFunctionLoadMap.end() ) {
331     PARSE_ERROR("Unrecognized function of type " << Func->getType()->getDescription());
332     return;
333   }
334
335   BlockStart = At = Fi->second.Buf;
336   BlockEnd = Fi->second.Buf;
337   assert(Fi->first == Func);
338
339   LazyFunctionLoadMap.erase(Fi);
340
341   this->ParseFunctionBody( Func );
342 }
343
344 void AbstractBytecodeParser::ParseAllFunctionBodies() {
345   LazyFunctionMap::iterator Fi = LazyFunctionLoadMap.begin();
346   LazyFunctionMap::iterator Fe = LazyFunctionLoadMap.end();
347
348   while ( Fi != Fe ) {
349     Function* Func = Fi->first;
350     BlockStart = At = Fi->second.Buf;
351     BlockEnd = Fi->second.EndBuf;
352     this->ParseFunctionBody(Func);
353     ++Fi;
354   }
355 }
356
357 void AbstractBytecodeParser::ParseFunctionBody(Function* Func ) {
358
359   unsigned FuncSize = BlockEnd - At;
360   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
361
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;
369   default:
370     PARSE_ERROR("Invalid linkage type for Function.");
371     Linkage = GlobalValue::InternalLinkage;
372     break;
373   }
374
375   Func->setLinkage( Linkage );
376   handler->handleFunctionBegin(Func,FuncSize);
377
378   // Keep track of how many basic blocks we have read in...
379   unsigned BlockNum = 0;
380   bool InsertedArguments = false;
381
382   BufPtr MyEnd = BlockEnd;
383   while ( At < MyEnd ) {
384     unsigned Type, Size;
385     BufPtr OldAt = At;
386     readBlock(Type, Size);
387
388     switch (Type) {
389     case BytecodeFormat::ConstantPool:
390       ParseConstantPool(FunctionTypes );
391       break;
392
393     case BytecodeFormat::CompactionTable:
394       ParseCompactionTable();
395       break;
396
397     case BytecodeFormat::BasicBlock:
398       ParseBasicBlock(BlockNum++);
399       break;
400
401     case BytecodeFormat::InstructionList:
402       if (BlockNum) 
403         PARSE_ERROR("InstructionList must come before basic blocks!");
404       BlockNum = ParseInstructionList();
405       break;
406
407     case BytecodeFormat::SymbolTable:
408       ParseSymbolTable();
409       break;
410
411     default:
412       At += Size;
413       if (OldAt > At)
414         PARSE_ERROR("Wrapped around reading bytecode");
415       break;
416     }
417     BlockEnd = MyEnd;
418
419     // Malformed bc file if read past end of block.
420     align32();
421   }
422
423   handler->handleFunctionEnd(Func);
424
425   // Clear out function-level types...
426   FunctionTypes.clear();
427   CompactionTypeTable.clear();
428 }
429
430 void AbstractBytecodeParser::ParseCompactionTable() {
431
432   handler->handleCompactionTableBegin();
433
434   while ( moreInBlock() ) {
435     unsigned NumEntries = read_vbr_uint();
436     unsigned Ty;
437
438     if ((NumEntries & 3) == 3) {
439       NumEntries >>= 2;
440       Ty = read_vbr_uint();
441     } else {
442       Ty = NumEntries >> 2;
443       NumEntries &= 3;
444     }
445
446     handler->handleCompactionTablePlane( Ty, NumEntries );
447
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 );
453       }
454     } else {
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 );
460       }
461     }
462   }
463   handler->handleCompactionTableEnd();
464 }
465
466 const Type *AbstractBytecodeParser::ParseTypeConstant() {
467   unsigned PrimType = read_vbr_uint();
468
469   const Type *Val = 0;
470   if ((Val = Type::getPrimitiveType((Type::TypeID)PrimType)))
471     return Val;
472   
473   switch (PrimType) {
474   case Type::FunctionTyID: {
475     const Type *RetType = getType(read_vbr_uint());
476
477     unsigned NumParams = read_vbr_uint();
478
479     std::vector<const Type*> Params;
480     while (NumParams--)
481       Params.push_back(getType(read_vbr_uint()));
482
483     bool isVarArg = Params.size() && Params.back() == Type::VoidTy;
484     if (isVarArg) Params.pop_back();
485
486     Type* result = FunctionType::get(RetType, Params, isVarArg);
487     handler->handleType( result );
488     return result;
489   }
490   case Type::ArrayTyID: {
491     unsigned ElTyp = read_vbr_uint();
492     const Type *ElementType = getType(ElTyp);
493
494     unsigned NumElements = read_vbr_uint();
495
496     BCR_TRACE(5, "Array Type Constant #" << ElTyp << " size=" 
497               << NumElements << "\n");
498     Type* result =  ArrayType::get(ElementType, NumElements);
499     handler->handleType( result );
500     return result;
501   }
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();
508     }
509
510     Type* result = StructType::get(Elements);
511     handler->handleType( result );
512     return result;
513   }
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 );
519     return result;
520   }
521
522   case Type::OpaqueTyID: {
523     Type* result = OpaqueType::get();
524     handler->handleType( result );
525     return result;
526   }
527
528   default:
529     PARSE_ERROR("Don't know how to deserialize primitive type" << PrimType << "\n");
530     return Val;
531   }
532 }
533
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.
543 //
544 void AbstractBytecodeParser::ParseTypeConstants( 
545   TypeListTy &Tab, unsigned NumEntries
546 ) {
547   assert(Tab.size() == 0 && "should not have read type constants in before!");
548
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());
553
554   // Loop through reading all of the types.  Forward types will make use of the
555   // opaque types just inserted.
556   //
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");
562
563     // Don't insertValue the new type... instead we want to replace the opaque
564     // type with the new concrete value...
565     //
566
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
569     // deleted...
570     //
571     cast<DerivedType>(const_cast<Type*>(OldTy))->refineAbstractTypeTo(NewTy);
572
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!");
576   }
577
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");
581   }
582 }
583
584
585 void AbstractBytecodeParser::ParseConstantValue(unsigned TypeID) {
586
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.
589   // 
590   // 0 if not expr; numArgs if is expr
591   unsigned isExprNumArgs = read_vbr_uint();
592   
593   if (isExprNumArgs) {
594     unsigned Opcode = read_vbr_uint();
595     const Type* Typ = getType(TypeID);
596     
597     // FIXME: Encoding of constant exprs could be much more compact!
598     std::vector<std::pair<const Type*,unsigned> > ArgVec;
599     ArgVec.reserve(isExprNumArgs);
600
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");
607       
608       // Get the arg value from its slot if it exists, otherwise a placeholder
609       ArgVec.push_back(std::make_pair(getType(ArgTypeSlot), ArgValSlot));
610     }
611
612     handler->handleConstantExpression( Opcode, Typ, ArgVec );
613     return;
614   }
615   
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.");
623
624     handler->handleConstantValue( ConstantBool::get(Val == 1));
625     break;
626   }
627
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) );
635     break;
636   }
637
638   case Type::ULongTyID: {
639     handler->handleConstantValue( ConstantUInt::get(Ty, read_vbr_uint64()) );
640     break;
641   }
642
643   case Type::SByteTyID:   // Signed integer types...
644   case Type::ShortTyID:
645   case Type::IntTyID: {
646   case Type::LongTyID:
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) );
651     break;
652   }
653
654   case Type::FloatTyID: {
655     float F;
656     read_data(&F, &F+1);
657     handler->handleConstantValue( ConstantFP::get(Ty, F) );
658     break;
659   }
660
661   case Type::DoubleTyID: {
662     double Val;
663     read_data(&Val, &Val+1);
664     handler->handleConstantValue( ConstantFP::get(Ty, Val) );
665     break;
666   }
667
668   case Type::TypeTyID:
669     PARSE_ERROR("Type constants shouldn't live in constant table!");
670     break;
671
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());
679
680     handler->handleConstantArray( AT, Elements );
681     break;
682   }
683
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 );
691     break;
692   }    
693
694   case Type::PointerTyID: {  // ConstantPointerRef value...
695     const PointerType *PT = cast<PointerType>(Ty);
696     unsigned Slot = read_vbr_uint();
697     handler->handleConstantPointer( PT, Slot );
698     break;
699   }
700
701   default:
702     PARSE_ERROR("Don't know how to deserialize constant value of type '"+
703                       Ty->getDescription());
704   }
705 }
706
707 void AbstractBytecodeParser::ParseGlobalTypes() {
708   ParseConstantPool(ModuleTypes);
709 }
710
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!");
717     
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!");
722     
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());
726
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]);
731     else
732       for (unsigned i = 0, e = ATy->getNumElements(); i != e; ++i)
733         Elements[i] = ConstantUInt::get(Type::UByteTy, (unsigned char)Data[i]);
734
735     // Create the constant, inserting it as needed.
736     ConstantArray *C = cast<ConstantArray>( ConstantArray::get(ATy, Elements) );
737     handler->handleConstantString( C );
738   }
739 }
740
741
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);
750     } else {
751       BCR_TRACE(3, "Type: '" << *getType(Typ) << "'  NumEntries: "
752                 << NumEntries << "\n");
753
754       for (unsigned i = 0; i < NumEntries; ++i) {
755         ParseConstantValue(Typ);
756       }
757     }
758   }
759   
760   checkPastBlockEnd("Constant Pool");
761 }
762
763 void AbstractBytecodeParser::ParseModuleGlobalInfo() {
764
765   handler->handleModuleGlobalsBegin();
766
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;
777
778     switch (LinkageID) {
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;
784     default: 
785       PARSE_ERROR("Unknown linkage type: " << LinkageID);
786       Linkage = GlobalValue::InternalLinkage;
787       break;
788     }
789
790     const Type *Ty = getType(SlotNo);
791     if ( !Ty ) {
792       PARSE_ERROR("Global has no type! SlotNo=" << SlotNo);
793     }
794
795     if ( !isa<PointerType>(Ty)) {
796       PARSE_ERROR("Global not a pointer type! Ty= " << Ty->getDescription());
797     }
798
799     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
800
801     // Create the global variable...
802     if (hasInitializer) {
803       unsigned initSlot = read_vbr_uint();
804       handler->handleInitializedGV( ElTy, isConstant, Linkage, initSlot );
805     } else 
806       handler->handleGlobalVariable( ElTy, isConstant, Linkage );
807
808     // Get next item
809     VarType = read_vbr_uint();
810   }
811
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?
821     }
822
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);
827
828     // Save this for later so we know type of lazily instantiated functions
829     FunctionSignatureList.push_back(Func);
830
831     handler->handleFunctionDeclaration(Func, FTy);
832
833     // Get Next function signature
834     FnSignature = read_vbr_uint();
835   }
836
837   if (hasInconsistentModuleGlobalInfo)
838     align32();
839
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());
843
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.
846   //
847   At = BlockEnd;
848
849   handler->handleModuleGlobalsEnd();
850 }
851
852 void AbstractBytecodeParser::ParseVersionInfo() {
853   unsigned Version = read_vbr_uint();
854
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;
860
861   bool hasNoEndianness = Version & 4;
862   bool hasNoPointerSize = Version & 8;
863   
864   RevisionNum = Version >> 4;
865
866   // Default values for the current bytecode version
867   hasInconsistentModuleGlobalInfo = false;
868   hasExplicitPrimitiveZeros = false;
869   hasRestrictedGEPTypes = false;
870
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;
876     // FALL THROUGH
877   case 1:               // LLVM 1.2 release version
878     // LLVM 1.2 added explicit support for emitting strings efficiently.
879
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
882     // blocks did not.
883
884     // LLVM 1.2 and before required that GEP indices be ubyte constants for
885     // structures and longs for sequential types.
886     hasRestrictedGEPTypes = true;
887
888     // FALL THROUGH
889   case 2:               // LLVM 1.3 release version
890     break;
891
892   default:
893     PARSE_ERROR("Unknown bytecode version number: " << RevisionNum);
894   }
895
896   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
897   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
898
899   handler->handleVersionInfo(RevisionNum, Endianness, PointerSize );
900 }
901
902 void AbstractBytecodeParser::ParseModule() {
903   unsigned Type, Size;
904
905   FunctionSignatureList.clear(); // Just in case...
906
907   // Read into instance variables...
908   ParseVersionInfo();
909   align32(); /// FIXME: Is this redundant? VI is first and 4 bytes!
910
911   bool SeenModuleGlobalInfo = false;
912   bool SeenGlobalTypePlane = false;
913   BufPtr MyEnd = BlockEnd;
914   while (At < MyEnd) {
915     BufPtr OldAt = At;
916     readBlock(Type, Size);
917
918     switch (Type) {
919
920     case BytecodeFormat::GlobalTypePlane:
921       if ( SeenGlobalTypePlane )
922         PARSE_ERROR("Two GlobalTypePlane Blocks Encountered!");
923
924       ParseGlobalTypes();
925       SeenGlobalTypePlane = true;
926       break;
927
928     case BytecodeFormat::ModuleGlobalInfo: 
929       if ( SeenModuleGlobalInfo )
930         PARSE_ERROR("Two ModuleGlobalInfo Blocks Encountered!");
931       ParseModuleGlobalInfo();
932       SeenModuleGlobalInfo = true;
933       break;
934
935     case BytecodeFormat::ConstantPool:
936       ParseConstantPool(ModuleTypes);
937       break;
938
939     case BytecodeFormat::Function:
940       ParseFunctionLazily();
941       break;
942
943     case BytecodeFormat::SymbolTable:
944       ParseSymbolTable();
945       break;
946
947     default:
948       At += Size;
949       if (OldAt > At) {
950         PARSE_ERROR("Unexpected Block of Type" << Type << "encountered!" );
951       }
952       break;
953     }
954     BlockEnd = MyEnd;
955     align32();
956   }
957
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())
961     throw std::string(
962       "Function declared, but bytecode stream ended before definition");
963 }
964
965 void AbstractBytecodeParser::ParseBytecode(
966        BufPtr b, unsigned Length,
967        const std::string &ModuleID) {
968
969   At = MemStart = BlockStart = b;
970   MemEnd = BlockEnd = b + Length;
971   handler->handleStart();
972
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);
977   }
978
979   handler->handleModuleBegin(ModuleID);
980
981   unsigned Type, Size;
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);
986   }
987   if ( At + Size != MemEnd ) {
988     PARSE_ERROR("Invalid Top Level Block Length! At: " 
989       << unsigned(intptr_t(At)) << ", Type:" << Type << ", Size:" << Size);
990   }
991   this->ParseModule();
992
993   handler->handleModuleEnd(ModuleID);
994
995   handler->handleFinish();
996 }
997
998 //===----------------------------------------------------------------------===//
999 //=== Default Implementations of Handler Methods
1000 //===----------------------------------------------------------------------===//
1001
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, 
1023   const Type* ) {}
1024 void BytecodeHandler::handleCompactionTableValue( unsigned i, unsigned ValSlot,
1025   const Type* ) {}
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, 
1036   unsigned Size ) {}
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); 
1042   }
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 ) {}
1061
1062 // vim: sw=2