Merge Dumper.cpp and AnalyzerWrappers.cpp into this file. Also, adjust the
[oota-llvm.git] / lib / Bytecode / Reader / Reader.cpp
1 //===- Reader.cpp - Code to read bytecode files ---------------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This library implements the functionality defined in llvm/Bytecode/Reader.h
11 //
12 // Note that this library should be as fast as possible, reentrant, and 
13 // threadsafe!!
14 //
15 // TODO: Allow passing in an option to ignore the symbol table
16 //
17 //===----------------------------------------------------------------------===//
18
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"
24 using namespace llvm;
25
26 unsigned BytecodeParser::getTypeSlot(const Type *Ty) {
27   if (Ty->isPrimitiveType())
28     return Ty->getTypeID();
29
30   // Scan the compaction table for the type if needed.
31   if (CompactionTable.size() > Type::TypeTyID) {
32     std::vector<Value*> &Plane = CompactionTable[Type::TypeTyID];
33     if (!Plane.empty()) {
34       std::vector<Value*>::iterator I = find(Plane.begin(), Plane.end(),
35                                              const_cast<Type*>(Ty));
36       if (I == Plane.end())
37         throw std::string("Couldn't find type specified in compaction table!");
38       return Type::FirstDerivedTyID + (&*I - &Plane[0]);
39     }
40   }
41
42   // Check the function level types first...
43   TypeValuesListTy::iterator I = find(FunctionTypeValues.begin(),
44                                       FunctionTypeValues.end(), Ty);
45   if (I != FunctionTypeValues.end())
46     return Type::FirstDerivedTyID + ModuleTypeValues.size() +
47              (&*I - &FunctionTypeValues[0]);
48
49   I = find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
50   if (I == ModuleTypeValues.end())
51     throw std::string("Didn't find type in ModuleTypeValues.");
52   return Type::FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
53 }
54
55 const Type *BytecodeParser::getType(unsigned ID) {
56   //cerr << "Looking up Type ID: " << ID << "\n";
57
58   if (ID < Type::FirstDerivedTyID)
59     if (const Type *T = Type::getPrimitiveType((Type::TypeID)ID))
60       return T;   // Asked for a primitive type...
61
62   // Otherwise, derived types need offset...
63   ID -= Type::FirstDerivedTyID;
64
65   if (CompactionTable.size() > Type::TypeTyID &&
66       !CompactionTable[Type::TypeTyID].empty()) {
67     if (ID >= CompactionTable[Type::TypeTyID].size())
68       throw std::string("Type ID out of range for compaction table!");
69     return cast<Type>(CompactionTable[Type::TypeTyID][ID]);
70   }
71
72   // Is it a module-level type?
73   if (ID < ModuleTypeValues.size())
74     return ModuleTypeValues[ID].get();
75
76   // Nope, is it a function-level type?
77   ID -= ModuleTypeValues.size();
78   if (ID < FunctionTypeValues.size())
79     return FunctionTypeValues[ID].get();
80
81   throw std::string("Illegal type reference!");
82 }
83
84 static inline bool hasImplicitNull(unsigned TyID, bool EncodesPrimitiveZeros) {
85   if (!EncodesPrimitiveZeros)
86     return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&
87            TyID != Type::VoidTyID;
88   return TyID >= Type::FirstDerivedTyID;
89 }
90
91 unsigned BytecodeParser::insertValue(Value *Val, unsigned type,
92                                      ValueTable &ValueTab) {
93   assert((!isa<Constant>(Val) || !cast<Constant>(Val)->isNullValue()) ||
94           !hasImplicitNull(type, hasExplicitPrimitiveZeros) &&
95          "Cannot read null values from bytecode!");
96   assert(type != Type::TypeTyID && "Types should never be insertValue'd!");
97
98   if (ValueTab.size() <= type)
99     ValueTab.resize(type+1);
100
101   if (!ValueTab[type]) ValueTab[type] = new ValueList();
102
103   //cerr << "insertValue Values[" << type << "][" << ValueTab[type].size() 
104   //   << "] = " << Val << "\n";
105   ValueTab[type]->push_back(Val);
106
107   bool HasOffset = hasImplicitNull(type, hasExplicitPrimitiveZeros);
108   return ValueTab[type]->size()-1 + HasOffset;
109 }
110
111 Value *BytecodeParser::getValue(unsigned type, unsigned oNum, bool Create) {
112   assert(type != Type::TypeTyID && "getValue() cannot get types!");
113   assert(type != Type::LabelTyID && "getValue() cannot get blocks!");
114   unsigned Num = oNum;
115
116   // If there is a compaction table active, it defines the low-level numbers.
117   // If not, the module values define the low-level numbers.
118   if (CompactionTable.size() > type && !CompactionTable[type].empty()) {
119     if (Num < CompactionTable[type].size())
120       return CompactionTable[type][Num];
121     Num -= CompactionTable[type].size();
122   } else {
123     // If the type plane was compactified, figure out the global type ID.
124     unsigned GlobalTyID = type;
125     if (CompactionTable.size() > Type::TypeTyID &&
126         !CompactionTable[Type::TypeTyID].empty() &&
127         type >= Type::FirstDerivedTyID) {
128       std::vector<Value*> &TypePlane = CompactionTable[Type::TypeTyID];
129       const Type *Ty = cast<Type>(TypePlane[type-Type::FirstDerivedTyID]);
130       TypeValuesListTy::iterator I =
131         find(ModuleTypeValues.begin(), ModuleTypeValues.end(), Ty);
132       assert(I != ModuleTypeValues.end());
133       GlobalTyID = Type::FirstDerivedTyID + (&*I - &ModuleTypeValues[0]);
134     }
135
136     if (hasImplicitNull(GlobalTyID, hasExplicitPrimitiveZeros)) {
137       if (Num == 0)
138         return Constant::getNullValue(getType(type));
139       --Num;
140     }
141
142     if (GlobalTyID < ModuleValues.size() && ModuleValues[GlobalTyID]) {
143       if (Num < ModuleValues[GlobalTyID]->size())
144         return ModuleValues[GlobalTyID]->getOperand(Num);
145       Num -= ModuleValues[GlobalTyID]->size();
146     }
147   }
148
149   if (Values.size() > type && Values[type] && Num < Values[type]->size())
150     return Values[type]->getOperand(Num);
151
152   if (!Create) return 0;  // Do not create a placeholder?
153
154   std::pair<unsigned,unsigned> KeyValue(type, oNum);
155   std::map<std::pair<unsigned,unsigned>, Value*>::iterator I = 
156     ForwardReferences.lower_bound(KeyValue);
157   if (I != ForwardReferences.end() && I->first == KeyValue)
158     return I->second;   // We have already created this placeholder
159
160   Value *Val = new Argument(getType(type));
161   ForwardReferences.insert(I, std::make_pair(KeyValue, Val));
162   return Val;
163 }
164
165 /// getBasicBlock - Get a particular numbered basic block, which might be a
166 /// forward reference.  This works together with ParseBasicBlock to handle these
167 /// forward references in a clean manner.
168 ///
169 BasicBlock *BytecodeParser::getBasicBlock(unsigned ID) {
170   // Make sure there is room in the table...
171   if (ParsedBasicBlocks.size() <= ID) ParsedBasicBlocks.resize(ID+1);
172
173   // First check to see if this is a backwards reference, i.e., ParseBasicBlock
174   // has already created this block, or if the forward reference has already
175   // been created.
176   if (ParsedBasicBlocks[ID])
177     return ParsedBasicBlocks[ID];
178
179   // Otherwise, the basic block has not yet been created.  Do so and add it to
180   // the ParsedBasicBlocks list.
181   return ParsedBasicBlocks[ID] = new BasicBlock();
182 }
183
184 /// getConstantValue - Just like getValue, except that it returns a null pointer
185 /// only on error.  It always returns a constant (meaning that if the value is
186 /// defined, but is not a constant, that is an error).  If the specified
187 /// constant hasn't been parsed yet, a placeholder is defined and used.  Later,
188 /// after the real value is parsed, the placeholder is eliminated.
189 ///
190 Constant *BytecodeParser::getConstantValue(unsigned TypeSlot, unsigned Slot) {
191   if (Value *V = getValue(TypeSlot, Slot, false))
192     if (Constant *C = dyn_cast<Constant>(V))
193       return C;   // If we already have the value parsed, just return it
194     else if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
195       // ConstantPointerRef's are an abomination, but at least they don't have
196       // to infest bytecode files.
197       return ConstantPointerRef::get(GV);
198     else
199       throw std::string("Reference of a value is expected to be a constant!");
200
201   const Type *Ty = getType(TypeSlot);
202   std::pair<const Type*, unsigned> Key(Ty, Slot);
203   ConstantRefsType::iterator I = ConstantFwdRefs.lower_bound(Key);
204
205   if (I != ConstantFwdRefs.end() && I->first == Key) {
206     BCR_TRACE(5, "Previous forward ref found!\n");
207     return I->second;
208   } else {
209     // Create a placeholder for the constant reference and
210     // keep track of the fact that we have a forward ref to recycle it
211     BCR_TRACE(5, "Creating new forward ref to a constant!\n");
212     Constant *C = new ConstPHolder(Ty, Slot);
213     
214     // Keep track of the fact that we have a forward ref to recycle it
215     ConstantFwdRefs.insert(I, std::make_pair(Key, C));
216     return C;
217   }
218 }
219
220 /// ParseBasicBlock - In LLVM 1.0 bytecode files, we used to output one
221 /// basicblock at a time.  This method reads in one of the basicblock packets.
222 BasicBlock *BytecodeParser::ParseBasicBlock(const unsigned char *&Buf,
223                                             const unsigned char *EndBuf,
224                                             unsigned BlockNo) {
225   BasicBlock *BB;
226   if (ParsedBasicBlocks.size() == BlockNo)
227     ParsedBasicBlocks.push_back(BB = new BasicBlock());
228   else if (ParsedBasicBlocks[BlockNo] == 0)
229     BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
230   else
231     BB = ParsedBasicBlocks[BlockNo];
232
233   std::vector<unsigned> Args;
234   while (Buf < EndBuf)
235     ParseInstruction(Buf, EndBuf, Args, BB);
236
237   return BB;
238 }
239
240
241 /// ParseInstructionList - Parse all of the BasicBlock's & Instruction's in the
242 /// body of a function.  In post 1.0 bytecode files, we no longer emit basic
243 /// block individually, in order to avoid per-basic-block overhead.
244 unsigned BytecodeParser::ParseInstructionList(Function *F,
245                                               const unsigned char *&Buf,
246                                               const unsigned char *EndBuf) {
247   unsigned BlockNo = 0;
248   std::vector<unsigned> Args;
249
250   while (Buf < EndBuf) {
251     BasicBlock *BB;
252     if (ParsedBasicBlocks.size() == BlockNo)
253       ParsedBasicBlocks.push_back(BB = new BasicBlock());
254     else if (ParsedBasicBlocks[BlockNo] == 0)
255       BB = ParsedBasicBlocks[BlockNo] = new BasicBlock();
256     else
257       BB = ParsedBasicBlocks[BlockNo];
258     ++BlockNo;
259     F->getBasicBlockList().push_back(BB);
260
261     // Read instructions into this basic block until we get to a terminator
262     while (Buf < EndBuf && !BB->getTerminator())
263       ParseInstruction(Buf, EndBuf, Args, BB);
264
265     if (!BB->getTerminator())
266       throw std::string("Non-terminated basic block found!");
267   }
268
269   return BlockNo;
270 }
271
272 void BytecodeParser::ParseSymbolTable(const unsigned char *&Buf,
273                                       const unsigned char *EndBuf,
274                                       SymbolTable *ST,
275                                       Function *CurrentFunction) {
276   // Allow efficient basic block lookup by number.
277   std::vector<BasicBlock*> BBMap;
278   if (CurrentFunction)
279     for (Function::iterator I = CurrentFunction->begin(),
280            E = CurrentFunction->end(); I != E; ++I)
281       BBMap.push_back(I);
282
283   while (Buf < EndBuf) {
284     // Symtab block header: [num entries][type id number]
285     unsigned NumEntries = read_vbr_uint(Buf, EndBuf);
286     unsigned Typ = read_vbr_uint(Buf, EndBuf);
287     const Type *Ty = getType(Typ);
288     BCR_TRACE(3, "Plane Type: '" << *Ty << "' with " << NumEntries <<
289                  " entries\n");
290
291     for (unsigned i = 0; i != NumEntries; ++i) {
292       // Symtab entry: [def slot #][name]
293       unsigned slot = read_vbr_uint(Buf, EndBuf);
294       std::string Name = read_str(Buf, EndBuf);
295
296       Value *V = 0;
297       if (Typ == Type::TypeTyID)
298         V = (Value*)getType(slot);
299       else if (Typ == Type::LabelTyID) {
300         if (slot < BBMap.size())
301           V = BBMap[slot];
302       } else {
303         V = getValue(Typ, slot, false); // Find mapping...
304       }
305       if (V == 0)
306         throw "Failed value look-up for name '" + Name + "'";
307       BCR_TRACE(4, "Map: '" << Name << "' to #" << slot << ":" << *V;
308                 if (!isa<Instruction>(V)) std::cerr << "\n");
309
310       V->setName(Name, ST);
311     }
312   }
313
314   if (Buf > EndBuf) throw std::string("Tried to read past end of buffer.");
315 }
316
317 void BytecodeParser::ResolveReferencesToConstant(Constant *NewV, unsigned Slot){
318   ConstantRefsType::iterator I =
319     ConstantFwdRefs.find(std::make_pair(NewV->getType(), Slot));
320   if (I == ConstantFwdRefs.end()) return;   // Never forward referenced?
321
322   BCR_TRACE(3, "Mutating forward refs!\n");
323   Value *PH = I->second;   // Get the placeholder...
324   PH->replaceAllUsesWith(NewV);
325   delete PH;                               // Delete the old placeholder
326   ConstantFwdRefs.erase(I);                // Remove the map entry for it
327 }
328
329 void BytecodeParser::ParseFunction(const unsigned char *&Buf,
330                                    const unsigned char *EndBuf) {
331   if (FunctionSignatureList.empty())
332     throw std::string("FunctionSignatureList empty!");
333
334   Function *F = FunctionSignatureList.back();
335   FunctionSignatureList.pop_back();
336
337   // Save the information for future reading of the function
338   LazyFunctionLoadMap[F] = LazyFunctionInfo(Buf, EndBuf);
339   // Pretend we've `parsed' this function
340   Buf = EndBuf;
341 }
342
343 void BytecodeParser::materializeFunction(Function* F) {
344   // Find {start, end} pointers and slot in the map. If not there, we're done.
345   std::map<Function*, LazyFunctionInfo>::iterator Fi =
346     LazyFunctionLoadMap.find(F);
347   if (Fi == LazyFunctionLoadMap.end()) return;
348
349   const unsigned char *Buf = Fi->second.Buf;
350   const unsigned char *EndBuf = Fi->second.EndBuf;
351   LazyFunctionLoadMap.erase(Fi);
352
353   GlobalValue::LinkageTypes Linkage = GlobalValue::ExternalLinkage;
354
355   unsigned LinkageType = read_vbr_uint(Buf, EndBuf);
356   if (LinkageType > 4)
357     throw std::string("Invalid linkage type for Function.");
358   switch (LinkageType) {
359   case 0: Linkage = GlobalValue::ExternalLinkage; break;
360   case 1: Linkage = GlobalValue::WeakLinkage; break;
361   case 2: Linkage = GlobalValue::AppendingLinkage; break;
362   case 3: Linkage = GlobalValue::InternalLinkage; break;
363   case 4: Linkage = GlobalValue::LinkOnceLinkage; break;
364   }
365
366   F->setLinkage(Linkage);
367
368   // Keep track of how many basic blocks we have read in...
369   unsigned BlockNum = 0;
370   bool InsertedArguments = false;
371
372   while (Buf < EndBuf) {
373     unsigned Type, Size;
374     const unsigned char *OldBuf = Buf;
375     readBlock(Buf, EndBuf, Type, Size);
376
377     switch (Type) {
378     case BytecodeFormat::ConstantPool:
379       if (!InsertedArguments) {
380         // Insert arguments into the value table before we parse the first basic
381         // block in the function, but after we potentially read in the
382         // compaction table.
383         const FunctionType *FT = F->getFunctionType();
384         Function::aiterator AI = F->abegin();
385         for (FunctionType::param_iterator It = FT->param_begin();
386              It != FT->param_end(); ++It, ++AI)
387           insertValue(AI, getTypeSlot(AI->getType()), Values);
388         InsertedArguments = true;
389       }
390
391       BCR_TRACE(2, "BLOCK BytecodeFormat::ConstantPool: {\n");
392       ParseConstantPool(Buf, Buf+Size, Values, FunctionTypeValues);
393       break;
394
395     case BytecodeFormat::CompactionTable:
396       BCR_TRACE(2, "BLOCK BytecodeFormat::CompactionTable: {\n");
397       ParseCompactionTable(Buf, Buf+Size);
398       break;
399
400     case BytecodeFormat::BasicBlock: {
401       if (!InsertedArguments) {
402         // Insert arguments into the value table before we parse the first basic
403         // block in the function, but after we potentially read in the
404         // compaction table.
405         const FunctionType *FT = F->getFunctionType();
406         Function::aiterator AI = F->abegin();
407         for (FunctionType::param_iterator It = FT->param_begin();
408              It != FT->param_end(); ++It, ++AI)
409           insertValue(AI, getTypeSlot(AI->getType()), Values);
410         InsertedArguments = true;
411       }
412
413       BCR_TRACE(2, "BLOCK BytecodeFormat::BasicBlock: {\n");
414       BasicBlock *BB = ParseBasicBlock(Buf, Buf+Size, BlockNum++);
415       F->getBasicBlockList().push_back(BB);
416       break;
417     }
418
419     case BytecodeFormat::InstructionList: {
420       // Insert arguments into the value table before we parse the instruction
421       // list for the function, but after we potentially read in the compaction
422       // table.
423       if (!InsertedArguments) {
424         const FunctionType *FT = F->getFunctionType();
425         Function::aiterator AI = F->abegin();
426         for (FunctionType::param_iterator It = FT->param_begin();
427              It != FT->param_end(); ++It, ++AI)
428           insertValue(AI, getTypeSlot(AI->getType()), Values);
429         InsertedArguments = true;
430       }
431
432       BCR_TRACE(2, "BLOCK BytecodeFormat::InstructionList: {\n");
433       if (BlockNum) throw std::string("Already parsed basic blocks!");
434       BlockNum = ParseInstructionList(F, Buf, Buf+Size);
435       break;
436     }
437
438     case BytecodeFormat::SymbolTable:
439       BCR_TRACE(2, "BLOCK BytecodeFormat::SymbolTable: {\n");
440       ParseSymbolTable(Buf, Buf+Size, &F->getSymbolTable(), F);
441       break;
442
443     default:
444       BCR_TRACE(2, "BLOCK <unknown>:ignored! {\n");
445       Buf += Size;
446       if (OldBuf > Buf) 
447         throw std::string("Wrapped around reading bytecode.");
448       break;
449     }
450     BCR_TRACE(2, "} end block\n");
451
452     // Malformed bc file if read past end of block.
453     align32(Buf, EndBuf);
454   }
455
456   // Make sure there were no references to non-existant basic blocks.
457   if (BlockNum != ParsedBasicBlocks.size())
458     throw std::string("Illegal basic block operand reference");
459   ParsedBasicBlocks.clear();
460
461   // Resolve forward references.  Replace any uses of a forward reference value
462   // with the real value.
463
464   // replaceAllUsesWith is very inefficient for instructions which have a LARGE
465   // number of operands.  PHI nodes often have forward references, and can also
466   // often have a very large number of operands.
467   //
468   // FIXME: REEVALUATE.  replaceAllUsesWith is _much_ faster now, and this code
469   // should be simplified back to using it!
470   //
471   std::map<Value*, Value*> ForwardRefMapping;
472   for (std::map<std::pair<unsigned,unsigned>, Value*>::iterator 
473          I = ForwardReferences.begin(), E = ForwardReferences.end();
474        I != E; ++I)
475     ForwardRefMapping[I->second] = getValue(I->first.first, I->first.second,
476                                             false);
477
478   for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
479     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
480       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
481         if (Argument *A = dyn_cast<Argument>(I->getOperand(i))) {
482           std::map<Value*, Value*>::iterator It = ForwardRefMapping.find(A);
483           if (It != ForwardRefMapping.end()) I->setOperand(i, It->second);
484         }
485
486   while (!ForwardReferences.empty()) {
487     std::map<std::pair<unsigned,unsigned>, Value*>::iterator I =
488       ForwardReferences.begin();
489     Value *PlaceHolder = I->second;
490     ForwardReferences.erase(I);
491
492     // Now that all the uses are gone, delete the placeholder...
493     // If we couldn't find a def (error case), then leak a little
494     // memory, because otherwise we can't remove all uses!
495     delete PlaceHolder;
496   }
497
498   // Clear out function-level types...
499   FunctionTypeValues.clear();
500   CompactionTable.clear();
501   freeTable(Values);
502 }
503
504 void BytecodeParser::ParseCompactionTable(const unsigned char *&Buf,
505                                           const unsigned char *End) {
506
507   while (Buf != End) {
508     unsigned NumEntries = read_vbr_uint(Buf, End);
509     unsigned Ty;
510
511     if ((NumEntries & 3) == 3) {
512       NumEntries >>= 2;
513       Ty = read_vbr_uint(Buf, End);
514     } else {
515       Ty = NumEntries >> 2;
516       NumEntries &= 3;
517     }
518
519     if (Ty >= CompactionTable.size())
520       CompactionTable.resize(Ty+1);
521
522     if (!CompactionTable[Ty].empty())
523       throw std::string("Compaction table plane contains multiple entries!");
524     
525     if (Ty == Type::TypeTyID) {
526       for (unsigned i = 0; i != NumEntries; ++i) {
527         const Type *Typ = getGlobalTableType(read_vbr_uint(Buf, End));
528         CompactionTable[Type::TypeTyID].push_back(const_cast<Type*>(Typ));
529       }
530
531       CompactionTable.resize(NumEntries+Type::FirstDerivedTyID);
532     } else {
533       const Type *Typ = getType(Ty);
534       // Push the implicit zero
535       CompactionTable[Ty].push_back(Constant::getNullValue(Typ));
536       for (unsigned i = 0; i != NumEntries; ++i) {
537         Value *V = getGlobalTableValue(Typ, read_vbr_uint(Buf, End));
538         CompactionTable[Ty].push_back(V);
539       }
540     }
541   }
542
543 }
544
545
546
547 void BytecodeParser::ParseModuleGlobalInfo(const unsigned char *&Buf,
548                                            const unsigned char *End) {
549   if (!FunctionSignatureList.empty())
550     throw std::string("Two ModuleGlobalInfo packets found!");
551
552   // Read global variables...
553   unsigned VarType = read_vbr_uint(Buf, End);
554   while (VarType != Type::VoidTyID) { // List is terminated by Void
555     // VarType Fields: bit0 = isConstant, bit1 = hasInitializer, bit2,3,4 =
556     // Linkage, bit4+ = slot#
557     unsigned SlotNo = VarType >> 5;
558     unsigned LinkageID = (VarType >> 2) & 7;
559     GlobalValue::LinkageTypes Linkage;
560
561     switch (LinkageID) {
562     default: assert(0 && "Unknown linkage type!");
563     case 0: Linkage = GlobalValue::ExternalLinkage;  break;
564     case 1: Linkage = GlobalValue::WeakLinkage;      break;
565     case 2: Linkage = GlobalValue::AppendingLinkage; break;
566     case 3: Linkage = GlobalValue::InternalLinkage;  break;
567     case 4: Linkage = GlobalValue::LinkOnceLinkage;  break;
568     }
569
570     const Type *Ty = getType(SlotNo);
571     if (!isa<PointerType>(Ty))
572       throw std::string("Global not pointer type!  Ty = " + 
573                         Ty->getDescription());
574
575     const Type *ElTy = cast<PointerType>(Ty)->getElementType();
576
577     // Create the global variable...
578     GlobalVariable *GV = new GlobalVariable(ElTy, VarType & 1, Linkage,
579                                             0, "", TheModule);
580     BCR_TRACE(2, "Global Variable of type: " << *Ty << "\n");
581     insertValue(GV, SlotNo, ModuleValues);
582
583     if (VarType & 2)   // Does it have an initializer?
584       GlobalInits.push_back(std::make_pair(GV, read_vbr_uint(Buf, End)));
585     VarType = read_vbr_uint(Buf, End);
586   }
587
588   // Read the function objects for all of the functions that are coming
589   unsigned FnSignature = read_vbr_uint(Buf, End);
590   while (FnSignature != Type::VoidTyID) { // List is terminated by Void
591     const Type *Ty = getType(FnSignature);
592     if (!isa<PointerType>(Ty) ||
593         !isa<FunctionType>(cast<PointerType>(Ty)->getElementType()))
594       throw std::string("Function not ptr to func type!  Ty = " +
595                         Ty->getDescription());
596
597     // We create functions by passing the underlying FunctionType to create...
598     Ty = cast<PointerType>(Ty)->getElementType();
599
600     // When the ModuleGlobalInfo section is read, we load the type of each
601     // function and the 'ModuleValues' slot that it lands in.  We then load a
602     // placeholder into its slot to reserve it.  When the function is loaded,
603     // this placeholder is replaced.
604
605     // Insert the placeholder...
606     Function *Func = new Function(cast<FunctionType>(Ty),
607                                   GlobalValue::InternalLinkage, "", TheModule);
608     insertValue(Func, FnSignature, ModuleValues);
609
610     // Keep track of this information in a list that is emptied as functions are
611     // loaded...
612     //
613     FunctionSignatureList.push_back(Func);
614
615     FnSignature = read_vbr_uint(Buf, End);
616     BCR_TRACE(2, "Function of type: " << Ty << "\n");
617   }
618
619   if (hasInconsistentModuleGlobalInfo)
620     align32(Buf, End);
621
622   // Now that the function signature list is set up, reverse it so that we can 
623   // remove elements efficiently from the back of the vector.
624   std::reverse(FunctionSignatureList.begin(), FunctionSignatureList.end());
625
626   // This is for future proofing... in the future extra fields may be added that
627   // we don't understand, so we transparently ignore them.
628   //
629   Buf = End;
630 }
631
632 void BytecodeParser::ParseVersionInfo(const unsigned char *&Buf,
633                                       const unsigned char *EndBuf) {
634   unsigned Version = read_vbr_uint(Buf, EndBuf);
635
636   // Unpack version number: low four bits are for flags, top bits = version
637   Module::Endianness  Endianness;
638   Module::PointerSize PointerSize;
639   Endianness  = (Version & 1) ? Module::BigEndian : Module::LittleEndian;
640   PointerSize = (Version & 2) ? Module::Pointer64 : Module::Pointer32;
641
642   bool hasNoEndianness = Version & 4;
643   bool hasNoPointerSize = Version & 8;
644   
645   RevisionNum = Version >> 4;
646
647   // Default values for the current bytecode version
648   hasInconsistentModuleGlobalInfo = false;
649   hasExplicitPrimitiveZeros = false;
650   hasRestrictedGEPTypes = false;
651
652   switch (RevisionNum) {
653   case 0:               //  LLVM 1.0, 1.1 release version
654     // Base LLVM 1.0 bytecode format.
655     hasInconsistentModuleGlobalInfo = true;
656     hasExplicitPrimitiveZeros = true;
657     // FALL THROUGH
658   case 1:               // LLVM 1.2 release version
659     // LLVM 1.2 added explicit support for emitting strings efficiently.
660
661     // Also, it fixed the problem where the size of the ModuleGlobalInfo block
662     // included the size for the alignment at the end, where the rest of the
663     // blocks did not.
664
665     // LLVM 1.2 and before required that GEP indices be ubyte constants for
666     // structures and longs for sequential types.
667     hasRestrictedGEPTypes = true;
668
669     // FALL THROUGH
670   case 2:               // LLVM 1.3 release version
671     break;
672
673   default:
674     throw std::string("Unknown bytecode version number!");
675   }
676
677   if (hasNoEndianness) Endianness  = Module::AnyEndianness;
678   if (hasNoPointerSize) PointerSize = Module::AnyPointerSize;
679
680   TheModule->setEndianness(Endianness);
681   TheModule->setPointerSize(PointerSize);
682   BCR_TRACE(1, "Bytecode Rev = " << (unsigned)RevisionNum << "\n");
683   BCR_TRACE(1, "Endianness/PointerSize = " << Endianness << ","
684                << PointerSize << "\n");
685 }
686
687 void BytecodeParser::ParseModule(const unsigned char *Buf,
688                                  const unsigned char *EndBuf) {
689   unsigned Type, Size;
690   readBlock(Buf, EndBuf, Type, Size);
691   if (Type != BytecodeFormat::Module || Buf+Size != EndBuf)
692     throw std::string("Expected Module packet! B: "+
693         utostr((unsigned)(intptr_t)Buf) + ", S: "+utostr(Size)+
694         " E: "+utostr((unsigned)(intptr_t)EndBuf)); // Hrm, not a class?
695
696   BCR_TRACE(0, "BLOCK BytecodeFormat::Module: {\n");
697   FunctionSignatureList.clear();                 // Just in case...
698
699   // Read into instance variables...
700   ParseVersionInfo(Buf, EndBuf);
701   align32(Buf, EndBuf);
702
703   while (Buf < EndBuf) {
704     const unsigned char *OldBuf = Buf;
705     readBlock(Buf, EndBuf, Type, Size);
706     switch (Type) {
707     case BytecodeFormat::GlobalTypePlane:
708       BCR_TRACE(1, "BLOCK BytecodeFormat::GlobalTypePlane: {\n");
709       ParseGlobalTypes(Buf, Buf+Size);
710       break;
711
712     case BytecodeFormat::ModuleGlobalInfo:
713       BCR_TRACE(1, "BLOCK BytecodeFormat::ModuleGlobalInfo: {\n");
714       ParseModuleGlobalInfo(Buf, Buf+Size);
715       break;
716
717     case BytecodeFormat::ConstantPool:
718       BCR_TRACE(1, "BLOCK BytecodeFormat::ConstantPool: {\n");
719       ParseConstantPool(Buf, Buf+Size, ModuleValues, ModuleTypeValues);
720       break;
721
722     case BytecodeFormat::Function: {
723       BCR_TRACE(1, "BLOCK BytecodeFormat::Function: {\n");
724       ParseFunction(Buf, Buf+Size);
725       break;
726     }
727
728     case BytecodeFormat::SymbolTable:
729       BCR_TRACE(1, "BLOCK BytecodeFormat::SymbolTable: {\n");
730       ParseSymbolTable(Buf, Buf+Size, &TheModule->getSymbolTable(), 0);
731       break;
732     default:
733       Buf += Size;
734       if (OldBuf > Buf) throw std::string("Expected Module Block!");
735       break;
736     }
737     BCR_TRACE(1, "} end block\n");
738     align32(Buf, EndBuf);
739   }
740
741   // After the module constant pool has been read, we can safely initialize
742   // global variables...
743   while (!GlobalInits.empty()) {
744     GlobalVariable *GV = GlobalInits.back().first;
745     unsigned Slot = GlobalInits.back().second;
746     GlobalInits.pop_back();
747
748     // Look up the initializer value...
749     // FIXME: Preserve this type ID!
750     unsigned TypeSlot = getTypeSlot(GV->getType()->getElementType());
751     if (Constant *CV = getConstantValue(TypeSlot, Slot)) {
752       if (GV->hasInitializer()) 
753         throw std::string("Global *already* has an initializer?!");
754       GV->setInitializer(CV);
755     } else
756       throw std::string("Cannot find initializer value.");
757   }
758
759   if (!FunctionSignatureList.empty())
760     throw std::string("Function expected, but bytecode stream ended!");
761
762   BCR_TRACE(0, "} end block\n\n");
763 }
764
765 void BytecodeParser::ParseBytecode(const unsigned char *Buf, unsigned Length,
766                                    const std::string &ModuleID) {
767
768   unsigned char *EndBuf = (unsigned char*)(Buf + Length);
769
770   // Read and check signature...
771   unsigned Sig = read(Buf, EndBuf);
772   if (Sig != ('l' | ('l' << 8) | ('v' << 16) | ('m' << 24)))
773     throw std::string("Invalid bytecode signature!");
774
775   TheModule = new Module(ModuleID);
776   try { 
777     ParseModule(Buf, EndBuf);
778   } catch (std::string &Error) {
779     freeState();       // Must destroy handles before deleting module!
780     delete TheModule;
781     TheModule = 0;
782     throw;
783   }
784 }