implement support for reading aggregate constants, including handling forward
[oota-llvm.git] / lib / Bitcode / Reader / BitcodeReader.cpp
1 //===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License.  See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This header defines the BitcodeReader class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "BitcodeReader.h"
15 #include "llvm/Bitcode/BitstreamReader.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Module.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/MathExtras.h"
21 using namespace llvm;
22
23 /// ConvertToString - Convert a string from a record into an std::string, return
24 /// true on failure.
25 template<typename StrTy>
26 static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
27                             StrTy &Result) {
28   if (Record.size() < Idx+1 || Record.size() < Record[Idx]+Idx+1)
29     return true;
30   
31   for (unsigned i = 0, e = Record[Idx]; i != e; ++i)
32     Result += (char)Record[Idx+i+1];
33   return false;
34 }
35
36 static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
37   switch (Val) {
38   default: // Map unknown/new linkages to external
39   case 0: return GlobalValue::ExternalLinkage;
40   case 1: return GlobalValue::WeakLinkage;
41   case 2: return GlobalValue::AppendingLinkage;
42   case 3: return GlobalValue::InternalLinkage;
43   case 4: return GlobalValue::LinkOnceLinkage;
44   case 5: return GlobalValue::DLLImportLinkage;
45   case 6: return GlobalValue::DLLExportLinkage;
46   case 7: return GlobalValue::ExternalWeakLinkage;
47   }
48 }
49
50 static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
51   switch (Val) {
52   default: // Map unknown visibilities to default.
53   case 0: return GlobalValue::DefaultVisibility;
54   case 1: return GlobalValue::HiddenVisibility;
55   }
56 }
57
58 namespace {
59   /// @brief A class for maintaining the slot number definition
60   /// as a placeholder for the actual definition for forward constants defs.
61   class ConstantPlaceHolder : public ConstantExpr {
62     ConstantPlaceHolder();                       // DO NOT IMPLEMENT
63     void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
64 public:
65   Use Op;
66   ConstantPlaceHolder(const Type *Ty)
67     : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
68       Op(UndefValue::get(Type::Int32Ty), this) {
69     }
70   };
71 }
72
73 Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
74                                                     const Type *Ty) {
75   if (Idx >= size()) {
76     // Insert a bunch of null values.
77     Uses.resize(Idx+1);
78     OperandList = &Uses[0];
79     NumOperands = Idx+1;
80   }
81
82   if (Uses[Idx])
83     return cast<Constant>(getOperand(Idx));
84
85   // Create and return a placeholder, which will later be RAUW'd.
86   Constant *C = new ConstantPlaceHolder(Ty);
87   Uses[Idx].init(C, this);
88   return C;
89 }
90
91
92 const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
93   // If the TypeID is in range, return it.
94   if (ID < TypeList.size())
95     return TypeList[ID].get();
96   if (!isTypeTable) return 0;
97   
98   // The type table allows forward references.  Push as many Opaque types as
99   // needed to get up to ID.
100   while (TypeList.size() <= ID)
101     TypeList.push_back(OpaqueType::get());
102   return TypeList.back().get();
103 }
104
105
106 bool BitcodeReader::ParseTypeTable(BitstreamReader &Stream) {
107   if (Stream.EnterSubBlock())
108     return Error("Malformed block record");
109   
110   if (!TypeList.empty())
111     return Error("Multiple TYPE_BLOCKs found!");
112
113   SmallVector<uint64_t, 64> Record;
114   unsigned NumRecords = 0;
115
116   // Read all the records for this type table.
117   while (1) {
118     unsigned Code = Stream.ReadCode();
119     if (Code == bitc::END_BLOCK) {
120       if (NumRecords != TypeList.size())
121         return Error("Invalid type forward reference in TYPE_BLOCK");
122       return Stream.ReadBlockEnd();
123     }
124     
125     if (Code == bitc::ENTER_SUBBLOCK) {
126       // No known subblocks, always skip them.
127       Stream.ReadSubBlockID();
128       if (Stream.SkipBlock())
129         return Error("Malformed block record");
130       continue;
131     }
132     
133     if (Code == bitc::DEFINE_ABBREV) {
134       Stream.ReadAbbrevRecord();
135       continue;
136     }
137     
138     // Read a record.
139     Record.clear();
140     const Type *ResultTy = 0;
141     switch (Stream.ReadRecord(Code, Record)) {
142     default:  // Default behavior: unknown type.
143       ResultTy = 0;
144       break;
145     case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
146       // TYPE_CODE_NUMENTRY contains a count of the number of types in the
147       // type list.  This allows us to reserve space.
148       if (Record.size() < 1)
149         return Error("Invalid TYPE_CODE_NUMENTRY record");
150       TypeList.reserve(Record[0]);
151       continue;
152     case bitc::TYPE_CODE_META:      // TYPE_CODE_META: [metacode]...
153       // No metadata supported yet.
154       if (Record.size() < 1)
155         return Error("Invalid TYPE_CODE_META record");
156       continue;
157       
158     case bitc::TYPE_CODE_VOID:      // VOID
159       ResultTy = Type::VoidTy;
160       break;
161     case bitc::TYPE_CODE_FLOAT:     // FLOAT
162       ResultTy = Type::FloatTy;
163       break;
164     case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
165       ResultTy = Type::DoubleTy;
166       break;
167     case bitc::TYPE_CODE_LABEL:     // LABEL
168       ResultTy = Type::LabelTy;
169       break;
170     case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
171       ResultTy = 0;
172       break;
173     case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
174       if (Record.size() < 1)
175         return Error("Invalid Integer type record");
176       
177       ResultTy = IntegerType::get(Record[0]);
178       break;
179     case bitc::TYPE_CODE_POINTER:   // POINTER: [pointee type]
180       if (Record.size() < 1)
181         return Error("Invalid POINTER type record");
182       ResultTy = PointerType::get(getTypeByID(Record[0], true));
183       break;
184     case bitc::TYPE_CODE_FUNCTION: {
185       // FUNCTION: [vararg, retty, #pararms, paramty N]
186       if (Record.size() < 3 || Record.size() < Record[2]+3)
187         return Error("Invalid FUNCTION type record");
188       std::vector<const Type*> ArgTys;
189       for (unsigned i = 0, e = Record[2]; i != e; ++i)
190         ArgTys.push_back(getTypeByID(Record[3+i], true));
191       
192       // FIXME: PARAM TYS.
193       ResultTy = FunctionType::get(getTypeByID(Record[1], true), ArgTys,
194                                    Record[0]);
195       break;
196     }
197     case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, #elts, eltty x N]
198       if (Record.size() < 2 || Record.size() < Record[1]+2)
199         return Error("Invalid STRUCT type record");
200       std::vector<const Type*> EltTys;
201       for (unsigned i = 0, e = Record[1]; i != e; ++i)
202         EltTys.push_back(getTypeByID(Record[2+i], true));
203       ResultTy = StructType::get(EltTys, Record[0]);
204       break;
205     }
206     case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
207       if (Record.size() < 2)
208         return Error("Invalid ARRAY type record");
209       ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
210       break;
211     case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
212       if (Record.size() < 2)
213         return Error("Invalid VECTOR type record");
214       ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
215       break;
216     }
217     
218     if (NumRecords == TypeList.size()) {
219       // If this is a new type slot, just append it.
220       TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
221       ++NumRecords;
222     } else if (ResultTy == 0) {
223       // Otherwise, this was forward referenced, so an opaque type was created,
224       // but the result type is actually just an opaque.  Leave the one we
225       // created previously.
226       ++NumRecords;
227     } else {
228       // Otherwise, this was forward referenced, so an opaque type was created.
229       // Resolve the opaque type to the real type now.
230       assert(NumRecords < TypeList.size() && "Typelist imbalance");
231       const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
232      
233       // Don't directly push the new type on the Tab. Instead we want to replace
234       // the opaque type we previously inserted with the new concrete value. The
235       // refinement from the abstract (opaque) type to the new type causes all
236       // uses of the abstract type to use the concrete type (NewTy). This will
237       // also cause the opaque type to be deleted.
238       const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
239       
240       // This should have replaced the old opaque type with the new type in the
241       // value table... or with a preexisting type that was already in the
242       // system.  Let's just make sure it did.
243       assert(TypeList[NumRecords-1].get() != OldTy &&
244              "refineAbstractType didn't work!");
245     }
246   }
247 }
248
249
250 bool BitcodeReader::ParseTypeSymbolTable(BitstreamReader &Stream) {
251   if (Stream.EnterSubBlock())
252     return Error("Malformed block record");
253   
254   SmallVector<uint64_t, 64> Record;
255   
256   // Read all the records for this type table.
257   std::string TypeName;
258   while (1) {
259     unsigned Code = Stream.ReadCode();
260     if (Code == bitc::END_BLOCK)
261       return Stream.ReadBlockEnd();
262     
263     if (Code == bitc::ENTER_SUBBLOCK) {
264       // No known subblocks, always skip them.
265       Stream.ReadSubBlockID();
266       if (Stream.SkipBlock())
267         return Error("Malformed block record");
268       continue;
269     }
270     
271     if (Code == bitc::DEFINE_ABBREV) {
272       Stream.ReadAbbrevRecord();
273       continue;
274     }
275     
276     // Read a record.
277     Record.clear();
278     switch (Stream.ReadRecord(Code, Record)) {
279     default:  // Default behavior: unknown type.
280       break;
281     case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namelen, namechar x N]
282       if (ConvertToString(Record, 1, TypeName))
283         return Error("Invalid TST_ENTRY record");
284       unsigned TypeID = Record[0];
285       if (TypeID >= TypeList.size())
286         return Error("Invalid Type ID in TST_ENTRY record");
287
288       TheModule->addTypeName(TypeName, TypeList[TypeID].get());
289       TypeName.clear();
290       break;
291     }
292   }
293 }
294
295 bool BitcodeReader::ParseValueSymbolTable(BitstreamReader &Stream) {
296   if (Stream.EnterSubBlock())
297     return Error("Malformed block record");
298
299   SmallVector<uint64_t, 64> Record;
300   
301   // Read all the records for this value table.
302   SmallString<128> ValueName;
303   while (1) {
304     unsigned Code = Stream.ReadCode();
305     if (Code == bitc::END_BLOCK)
306       return Stream.ReadBlockEnd();
307     
308     if (Code == bitc::ENTER_SUBBLOCK) {
309       // No known subblocks, always skip them.
310       Stream.ReadSubBlockID();
311       if (Stream.SkipBlock())
312         return Error("Malformed block record");
313       continue;
314     }
315     
316     if (Code == bitc::DEFINE_ABBREV) {
317       Stream.ReadAbbrevRecord();
318       continue;
319     }
320     
321     // Read a record.
322     Record.clear();
323     switch (Stream.ReadRecord(Code, Record)) {
324     default:  // Default behavior: unknown type.
325       break;
326     case bitc::TST_CODE_ENTRY:    // VST_ENTRY: [valueid, namelen, namechar x N]
327       if (ConvertToString(Record, 1, ValueName))
328         return Error("Invalid TST_ENTRY record");
329       unsigned ValueID = Record[0];
330       if (ValueID >= ValueList.size())
331         return Error("Invalid Value ID in VST_ENTRY record");
332       Value *V = ValueList[ValueID];
333       
334       V->setName(&ValueName[0], ValueName.size());
335       ValueName.clear();
336       break;
337     }
338   }
339 }
340
341 /// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
342 /// the LSB for dense VBR encoding.
343 static uint64_t DecodeSignRotatedValue(uint64_t V) {
344   if ((V & 1) == 0)
345     return V >> 1;
346   if (V != 1) 
347     return -(V >> 1);
348   // There is no such thing as -0 with integers.  "-0" really means MININT.
349   return 1ULL << 63;
350 }
351
352 bool BitcodeReader::ParseConstants(BitstreamReader &Stream) {
353   if (Stream.EnterSubBlock())
354     return Error("Malformed block record");
355
356   SmallVector<uint64_t, 64> Record;
357   
358   // Read all the records for this value table.
359   const Type *CurTy = Type::Int32Ty;
360   unsigned NextCstNo = ValueList.size();
361   while (1) {
362     unsigned Code = Stream.ReadCode();
363     if (Code == bitc::END_BLOCK) {
364       // If there are global var inits to process, do so now.
365       if (!GlobalInits.empty()) {
366         while (!GlobalInits.empty()) {
367           unsigned ValID = GlobalInits.back().second;
368           if (ValID >= ValueList.size())
369             return Error("Invalid value ID for global var init!");
370           if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
371             GlobalInits.back().first->setInitializer(C);
372           else
373             return Error("Global variable initializer is not a constant!");
374           GlobalInits.pop_back(); 
375         }
376       }
377       
378       if (NextCstNo != ValueList.size())
379         return Error("Invalid constant reference!");
380       
381       return Stream.ReadBlockEnd();
382     }
383     
384     if (Code == bitc::ENTER_SUBBLOCK) {
385       // No known subblocks, always skip them.
386       Stream.ReadSubBlockID();
387       if (Stream.SkipBlock())
388         return Error("Malformed block record");
389       continue;
390     }
391     
392     if (Code == bitc::DEFINE_ABBREV) {
393       Stream.ReadAbbrevRecord();
394       continue;
395     }
396     
397     // Read a record.
398     Record.clear();
399     Value *V = 0;
400     switch (Stream.ReadRecord(Code, Record)) {
401     default:  // Default behavior: unknown constant
402     case bitc::CST_CODE_UNDEF:     // UNDEF
403       V = UndefValue::get(CurTy);
404       break;
405     case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
406       if (Record.empty())
407         return Error("Malformed CST_SETTYPE record");
408       if (Record[0] >= TypeList.size())
409         return Error("Invalid Type ID in CST_SETTYPE record");
410       CurTy = TypeList[Record[0]];
411       continue;  // Skip the ValueList manipulation.
412     case bitc::CST_CODE_NULL:      // NULL
413       V = Constant::getNullValue(CurTy);
414       break;
415     case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
416       if (!isa<IntegerType>(CurTy) || Record.empty())
417         return Error("Invalid CST_INTEGER record");
418       V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
419       break;
420     case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n, n x intval]
421       if (!isa<IntegerType>(CurTy) || Record.empty() ||
422           Record.size() < Record[0]+1)
423         return Error("Invalid WIDE_INTEGER record");
424       
425       unsigned NumWords = Record[0];
426       uint64_t *Data = new uint64_t[NumWords];
427       for (unsigned i = 0; i != NumWords; ++i)
428         Data[i] = DecodeSignRotatedValue(Record[i+1]);
429       V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
430                                  NumWords, Data));
431       break;
432     }
433     case bitc::CST_CODE_FLOAT:     // FLOAT: [fpval]
434       if (Record.empty())
435         return Error("Invalid FLOAT record");
436       if (CurTy == Type::FloatTy)
437         V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
438       else if (CurTy == Type::DoubleTy)
439         V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
440       else
441         V = UndefValue::get(CurTy);
442       break;
443       
444     case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n, n x value number]
445       if (Record.empty() || Record.size() < Record[0]+1)
446         return Error("Invalid CST_AGGREGATE record");
447       
448       unsigned Size = Record[0];
449       std::vector<Constant*> Elts;
450       
451       if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
452         for (unsigned i = 0; i != Size; ++i)
453           Elts.push_back(ValueList.getConstantFwdRef(Record[i+1],
454                                                      STy->getElementType(i)));
455         V = ConstantStruct::get(STy, Elts);
456       } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
457         const Type *EltTy = ATy->getElementType();
458         for (unsigned i = 0; i != Size; ++i)
459           Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
460         V = ConstantArray::get(ATy, Elts);
461       } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
462         const Type *EltTy = VTy->getElementType();
463         for (unsigned i = 0; i != Size; ++i)
464           Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], EltTy));
465         V = ConstantVector::get(Elts);
466       } else {
467         V = UndefValue::get(CurTy);
468       }
469     }
470     }
471     
472     if (NextCstNo == ValueList.size())
473       ValueList.push_back(V);
474     else if (ValueList[NextCstNo] == 0)
475       ValueList.initVal(NextCstNo, V);
476     else {
477       // If there was a forward reference to this constant, 
478       Value *OldV = ValueList[NextCstNo];
479       ValueList.setOperand(NextCstNo, V);
480       OldV->replaceAllUsesWith(V);
481       delete OldV;
482     }
483     
484     ++NextCstNo;
485   }
486 }
487
488 bool BitcodeReader::ParseModule(BitstreamReader &Stream,
489                                 const std::string &ModuleID) {
490   // Reject multiple MODULE_BLOCK's in a single bitstream.
491   if (TheModule)
492     return Error("Multiple MODULE_BLOCKs in same stream");
493   
494   if (Stream.EnterSubBlock())
495     return Error("Malformed block record");
496
497   // Otherwise, create the module.
498   TheModule = new Module(ModuleID);
499   
500   SmallVector<uint64_t, 64> Record;
501   std::vector<std::string> SectionTable;
502
503   // Read all the records for this module.
504   while (!Stream.AtEndOfStream()) {
505     unsigned Code = Stream.ReadCode();
506     if (Code == bitc::END_BLOCK) {
507       if (!GlobalInits.empty())
508         return Error("Malformed global initializer set");
509       return Stream.ReadBlockEnd();
510     }
511     
512     if (Code == bitc::ENTER_SUBBLOCK) {
513       switch (Stream.ReadSubBlockID()) {
514       default:  // Skip unknown content.
515         if (Stream.SkipBlock())
516           return Error("Malformed block record");
517         break;
518       case bitc::TYPE_BLOCK_ID:
519         if (ParseTypeTable(Stream))
520           return true;
521         break;
522       case bitc::TYPE_SYMTAB_BLOCK_ID:
523         if (ParseTypeSymbolTable(Stream))
524           return true;
525         break;
526       case bitc::VALUE_SYMTAB_BLOCK_ID:
527         if (ParseValueSymbolTable(Stream))
528           return true;
529         break;
530       case bitc::CONSTANTS_BLOCK_ID:
531         if (ParseConstants(Stream))
532           return true;
533         break;
534       }
535       continue;
536     }
537     
538     if (Code == bitc::DEFINE_ABBREV) {
539       Stream.ReadAbbrevRecord();
540       continue;
541     }
542     
543     // Read a record.
544     switch (Stream.ReadRecord(Code, Record)) {
545     default: break;  // Default behavior, ignore unknown content.
546     case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
547       if (Record.size() < 1)
548         return Error("Malformed MODULE_CODE_VERSION");
549       // Only version #0 is supported so far.
550       if (Record[0] != 0)
551         return Error("Unknown bitstream version!");
552       break;
553     case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strlen, strchr x N]
554       std::string S;
555       if (ConvertToString(Record, 0, S))
556         return Error("Invalid MODULE_CODE_TRIPLE record");
557       TheModule->setTargetTriple(S);
558       break;
559     }
560     case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strlen, strchr x N]
561       std::string S;
562       if (ConvertToString(Record, 0, S))
563         return Error("Invalid MODULE_CODE_DATALAYOUT record");
564       TheModule->setDataLayout(S);
565       break;
566     }
567     case bitc::MODULE_CODE_ASM: {  // ASM: [strlen, strchr x N]
568       std::string S;
569       if (ConvertToString(Record, 0, S))
570         return Error("Invalid MODULE_CODE_ASM record");
571       TheModule->setModuleInlineAsm(S);
572       break;
573     }
574     case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strlen, strchr x N]
575       std::string S;
576       if (ConvertToString(Record, 0, S))
577         return Error("Invalid MODULE_CODE_DEPLIB record");
578       TheModule->addLibrary(S);
579       break;
580     }
581     case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strlen, strchr x N]
582       std::string S;
583       if (ConvertToString(Record, 0, S))
584         return Error("Invalid MODULE_CODE_SECTIONNAME record");
585       SectionTable.push_back(S);
586       break;
587     }
588     // GLOBALVAR: [type, isconst, initid, 
589     //             linkage, alignment, section, visibility, threadlocal]
590     case bitc::MODULE_CODE_GLOBALVAR: {
591       if (Record.size() < 6)
592         return Error("Invalid MODULE_CODE_GLOBALVAR record");
593       const Type *Ty = getTypeByID(Record[0]);
594       if (!isa<PointerType>(Ty))
595         return Error("Global not a pointer type!");
596       Ty = cast<PointerType>(Ty)->getElementType();
597       
598       bool isConstant = Record[1];
599       GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
600       unsigned Alignment = (1 << Record[4]) >> 1;
601       std::string Section;
602       if (Record[5]) {
603         if (Record[5]-1 >= SectionTable.size())
604           return Error("Invalid section ID");
605         Section = SectionTable[Record[5]-1];
606       }
607       GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
608       if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
609       bool isThreadLocal = false;
610       if (Record.size() >= 7) isThreadLocal = Record[7];
611
612       GlobalVariable *NewGV =
613         new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
614       NewGV->setAlignment(Alignment);
615       if (!Section.empty())
616         NewGV->setSection(Section);
617       NewGV->setVisibility(Visibility);
618       NewGV->setThreadLocal(isThreadLocal);
619       
620       ValueList.push_back(NewGV);
621       
622       // Remember which value to use for the global initializer.
623       if (unsigned InitID = Record[2])
624         GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
625       break;
626     }
627     // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
628     //             visibility]
629     case bitc::MODULE_CODE_FUNCTION: {
630       if (Record.size() < 7)
631         return Error("Invalid MODULE_CODE_FUNCTION record");
632       const Type *Ty = getTypeByID(Record[0]);
633       if (!isa<PointerType>(Ty))
634         return Error("Function not a pointer type!");
635       const FunctionType *FTy =
636         dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
637       if (!FTy)
638         return Error("Function not a pointer to function type!");
639
640       Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
641                                     "", TheModule);
642
643       Func->setCallingConv(Record[1]);
644       Func->setLinkage(GetDecodedLinkage(Record[3]));
645       Func->setAlignment((1 << Record[4]) >> 1);
646       if (Record[5]) {
647         if (Record[5]-1 >= SectionTable.size())
648           return Error("Invalid section ID");
649         Func->setSection(SectionTable[Record[5]-1]);
650       }
651       Func->setVisibility(GetDecodedVisibility(Record[6]));
652       
653       ValueList.push_back(Func);
654       // TODO: remember initializer/global pair for later substitution.
655       break;
656     }
657     }
658     Record.clear();
659   }
660   
661   return Error("Premature end of bitstream");
662 }
663
664
665 bool BitcodeReader::ParseBitcode(unsigned char *Buf, unsigned Length,
666                                  const std::string &ModuleID) {
667   TheModule = 0;
668   
669   if (Length & 3)
670     return Error("Bitcode stream should be a multiple of 4 bytes in length");
671   
672   BitstreamReader Stream(Buf, Buf+Length);
673   
674   // Sniff for the signature.
675   if (Stream.Read(8) != 'B' ||
676       Stream.Read(8) != 'C' ||
677       Stream.Read(4) != 0x0 ||
678       Stream.Read(4) != 0xC ||
679       Stream.Read(4) != 0xE ||
680       Stream.Read(4) != 0xD)
681     return Error("Invalid bitcode signature");
682   
683   // We expect a number of well-defined blocks, though we don't necessarily
684   // need to understand them all.
685   while (!Stream.AtEndOfStream()) {
686     unsigned Code = Stream.ReadCode();
687     
688     if (Code != bitc::ENTER_SUBBLOCK)
689       return Error("Invalid record at top-level");
690     
691     unsigned BlockID = Stream.ReadSubBlockID();
692     
693     // We only know the MODULE subblock ID.
694     if (BlockID == bitc::MODULE_BLOCK_ID) {
695       if (ParseModule(Stream, ModuleID))
696         return true;
697     } else if (Stream.SkipBlock()) {
698       return Error("Malformed block record");
699     }
700   }
701   
702   return false;
703 }