BitcodeReader.cpp revision cb3d91b05b36a144dd0f3103ce4fda4cab356ad6
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 "llvm/Bitcode/ReaderWriter.h"
15#include "BitcodeReader.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Instructions.h"
19#include "llvm/Module.h"
20#include "llvm/ParameterAttributes.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/Support/MathExtras.h"
23#include "llvm/Support/MemoryBuffer.h"
24using namespace llvm;
25
26BitcodeReader::~BitcodeReader() {
27  delete Buffer;
28}
29
30//===----------------------------------------------------------------------===//
31//  Helper functions to implement forward reference resolution, etc.
32//===----------------------------------------------------------------------===//
33
34/// ConvertToString - Convert a string from a record into an std::string, return
35/// true on failure.
36template<typename StrTy>
37static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
38                            StrTy &Result) {
39  if (Idx > Record.size())
40    return true;
41
42  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
43    Result += (char)Record[i];
44  return false;
45}
46
47static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
48  switch (Val) {
49  default: // Map unknown/new linkages to external
50  case 0: return GlobalValue::ExternalLinkage;
51  case 1: return GlobalValue::WeakLinkage;
52  case 2: return GlobalValue::AppendingLinkage;
53  case 3: return GlobalValue::InternalLinkage;
54  case 4: return GlobalValue::LinkOnceLinkage;
55  case 5: return GlobalValue::DLLImportLinkage;
56  case 6: return GlobalValue::DLLExportLinkage;
57  case 7: return GlobalValue::ExternalWeakLinkage;
58  }
59}
60
61static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
62  switch (Val) {
63  default: // Map unknown visibilities to default.
64  case 0: return GlobalValue::DefaultVisibility;
65  case 1: return GlobalValue::HiddenVisibility;
66  case 2: return GlobalValue::ProtectedVisibility;
67  }
68}
69
70static int GetDecodedCastOpcode(unsigned Val) {
71  switch (Val) {
72  default: return -1;
73  case bitc::CAST_TRUNC   : return Instruction::Trunc;
74  case bitc::CAST_ZEXT    : return Instruction::ZExt;
75  case bitc::CAST_SEXT    : return Instruction::SExt;
76  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
77  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
78  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
79  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
80  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
81  case bitc::CAST_FPEXT   : return Instruction::FPExt;
82  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
83  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
84  case bitc::CAST_BITCAST : return Instruction::BitCast;
85  }
86}
87static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
88  switch (Val) {
89  default: return -1;
90  case bitc::BINOP_ADD:  return Instruction::Add;
91  case bitc::BINOP_SUB:  return Instruction::Sub;
92  case bitc::BINOP_MUL:  return Instruction::Mul;
93  case bitc::BINOP_UDIV: return Instruction::UDiv;
94  case bitc::BINOP_SDIV:
95    return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
96  case bitc::BINOP_UREM: return Instruction::URem;
97  case bitc::BINOP_SREM:
98    return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
99  case bitc::BINOP_SHL:  return Instruction::Shl;
100  case bitc::BINOP_LSHR: return Instruction::LShr;
101  case bitc::BINOP_ASHR: return Instruction::AShr;
102  case bitc::BINOP_AND:  return Instruction::And;
103  case bitc::BINOP_OR:   return Instruction::Or;
104  case bitc::BINOP_XOR:  return Instruction::Xor;
105  }
106}
107
108
109namespace {
110  /// @brief A class for maintaining the slot number definition
111  /// as a placeholder for the actual definition for forward constants defs.
112  class ConstantPlaceHolder : public ConstantExpr {
113    ConstantPlaceHolder();                       // DO NOT IMPLEMENT
114    void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
115  public:
116    Use Op;
117    ConstantPlaceHolder(const Type *Ty)
118      : ConstantExpr(Ty, Instruction::UserOp1, &Op, 1),
119        Op(UndefValue::get(Type::Int32Ty), this) {
120    }
121  };
122}
123
124Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
125                                                    const Type *Ty) {
126  if (Idx >= size()) {
127    // Insert a bunch of null values.
128    Uses.resize(Idx+1);
129    OperandList = &Uses[0];
130    NumOperands = Idx+1;
131  }
132
133  if (Value *V = Uses[Idx]) {
134    assert(Ty == V->getType() && "Type mismatch in constant table!");
135    return cast<Constant>(V);
136  }
137
138  // Create and return a placeholder, which will later be RAUW'd.
139  Constant *C = new ConstantPlaceHolder(Ty);
140  Uses[Idx].init(C, this);
141  return C;
142}
143
144Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
145  if (Idx >= size()) {
146    // Insert a bunch of null values.
147    Uses.resize(Idx+1);
148    OperandList = &Uses[0];
149    NumOperands = Idx+1;
150  }
151
152  if (Value *V = Uses[Idx]) {
153    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
154    return V;
155  }
156
157  // No type specified, must be invalid reference.
158  if (Ty == 0) return 0;
159
160  // Create and return a placeholder, which will later be RAUW'd.
161  Value *V = new Argument(Ty);
162  Uses[Idx].init(V, this);
163  return V;
164}
165
166
167const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
168  // If the TypeID is in range, return it.
169  if (ID < TypeList.size())
170    return TypeList[ID].get();
171  if (!isTypeTable) return 0;
172
173  // The type table allows forward references.  Push as many Opaque types as
174  // needed to get up to ID.
175  while (TypeList.size() <= ID)
176    TypeList.push_back(OpaqueType::get());
177  return TypeList.back().get();
178}
179
180//===----------------------------------------------------------------------===//
181//  Functions for parsing blocks from the bitcode file
182//===----------------------------------------------------------------------===//
183
184bool BitcodeReader::ParseParamAttrBlock() {
185  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
186    return Error("Malformed block record");
187
188  if (!ParamAttrs.empty())
189    return Error("Multiple PARAMATTR blocks found!");
190
191  SmallVector<uint64_t, 64> Record;
192
193  ParamAttrsVector Attrs;
194
195  // Read all the records.
196  while (1) {
197    unsigned Code = Stream.ReadCode();
198    if (Code == bitc::END_BLOCK) {
199      if (Stream.ReadBlockEnd())
200        return Error("Error at end of PARAMATTR block");
201      return false;
202    }
203
204    if (Code == bitc::ENTER_SUBBLOCK) {
205      // No known subblocks, always skip them.
206      Stream.ReadSubBlockID();
207      if (Stream.SkipBlock())
208        return Error("Malformed block record");
209      continue;
210    }
211
212    if (Code == bitc::DEFINE_ABBREV) {
213      Stream.ReadAbbrevRecord();
214      continue;
215    }
216
217    // Read a record.
218    Record.clear();
219    switch (Stream.ReadRecord(Code, Record)) {
220    default:  // Default behavior: ignore.
221      break;
222    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
223      if (Record.size() & 1)
224        return Error("Invalid ENTRY record");
225
226      ParamAttrsWithIndex PAWI;
227      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
228        PAWI.index = Record[i];
229        PAWI.attrs = Record[i+1];
230        Attrs.push_back(PAWI);
231      }
232      ParamAttrs.push_back(ParamAttrsList::get(Attrs));
233      Attrs.clear();
234      break;
235    }
236    }
237  }
238}
239
240
241bool BitcodeReader::ParseTypeTable() {
242  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
243    return Error("Malformed block record");
244
245  if (!TypeList.empty())
246    return Error("Multiple TYPE_BLOCKs found!");
247
248  SmallVector<uint64_t, 64> Record;
249  unsigned NumRecords = 0;
250
251  // Read all the records for this type table.
252  while (1) {
253    unsigned Code = Stream.ReadCode();
254    if (Code == bitc::END_BLOCK) {
255      if (NumRecords != TypeList.size())
256        return Error("Invalid type forward reference in TYPE_BLOCK");
257      if (Stream.ReadBlockEnd())
258        return Error("Error at end of type table block");
259      return false;
260    }
261
262    if (Code == bitc::ENTER_SUBBLOCK) {
263      // No known subblocks, always skip them.
264      Stream.ReadSubBlockID();
265      if (Stream.SkipBlock())
266        return Error("Malformed block record");
267      continue;
268    }
269
270    if (Code == bitc::DEFINE_ABBREV) {
271      Stream.ReadAbbrevRecord();
272      continue;
273    }
274
275    // Read a record.
276    Record.clear();
277    const Type *ResultTy = 0;
278    switch (Stream.ReadRecord(Code, Record)) {
279    default:  // Default behavior: unknown type.
280      ResultTy = 0;
281      break;
282    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
283      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
284      // type list.  This allows us to reserve space.
285      if (Record.size() < 1)
286        return Error("Invalid TYPE_CODE_NUMENTRY record");
287      TypeList.reserve(Record[0]);
288      continue;
289    case bitc::TYPE_CODE_VOID:      // VOID
290      ResultTy = Type::VoidTy;
291      break;
292    case bitc::TYPE_CODE_FLOAT:     // FLOAT
293      ResultTy = Type::FloatTy;
294      break;
295    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
296      ResultTy = Type::DoubleTy;
297      break;
298    case bitc::TYPE_CODE_LABEL:     // LABEL
299      ResultTy = Type::LabelTy;
300      break;
301    case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
302      ResultTy = 0;
303      break;
304    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
305      if (Record.size() < 1)
306        return Error("Invalid Integer type record");
307
308      ResultTy = IntegerType::get(Record[0]);
309      break;
310    case bitc::TYPE_CODE_POINTER:   // POINTER: [pointee type]
311      if (Record.size() < 1)
312        return Error("Invalid POINTER type record");
313      ResultTy = PointerType::get(getTypeByID(Record[0], true));
314      break;
315    case bitc::TYPE_CODE_FUNCTION: {
316      // FUNCTION: [vararg, attrid, retty, paramty x N]
317      if (Record.size() < 3)
318        return Error("Invalid FUNCTION type record");
319      std::vector<const Type*> ArgTys;
320      for (unsigned i = 3, e = Record.size(); i != e; ++i)
321        ArgTys.push_back(getTypeByID(Record[i], true));
322
323      ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
324                                   Record[0], getParamAttrs(Record[1]));
325      break;
326    }
327    case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
328      if (Record.size() < 2)
329        return Error("Invalid STRUCT type record");
330      std::vector<const Type*> EltTys;
331      for (unsigned i = 1, e = Record.size(); i != e; ++i)
332        EltTys.push_back(getTypeByID(Record[i], true));
333      ResultTy = StructType::get(EltTys, Record[0]);
334      break;
335    }
336    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
337      if (Record.size() < 2)
338        return Error("Invalid ARRAY type record");
339      ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
340      break;
341    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
342      if (Record.size() < 2)
343        return Error("Invalid VECTOR type record");
344      ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
345      break;
346    }
347
348    if (NumRecords == TypeList.size()) {
349      // If this is a new type slot, just append it.
350      TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
351      ++NumRecords;
352    } else if (ResultTy == 0) {
353      // Otherwise, this was forward referenced, so an opaque type was created,
354      // but the result type is actually just an opaque.  Leave the one we
355      // created previously.
356      ++NumRecords;
357    } else {
358      // Otherwise, this was forward referenced, so an opaque type was created.
359      // Resolve the opaque type to the real type now.
360      assert(NumRecords < TypeList.size() && "Typelist imbalance");
361      const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
362
363      // Don't directly push the new type on the Tab. Instead we want to replace
364      // the opaque type we previously inserted with the new concrete value. The
365      // refinement from the abstract (opaque) type to the new type causes all
366      // uses of the abstract type to use the concrete type (NewTy). This will
367      // also cause the opaque type to be deleted.
368      const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
369
370      // This should have replaced the old opaque type with the new type in the
371      // value table... or with a preexisting type that was already in the
372      // system.  Let's just make sure it did.
373      assert(TypeList[NumRecords-1].get() != OldTy &&
374             "refineAbstractType didn't work!");
375    }
376  }
377}
378
379
380bool BitcodeReader::ParseTypeSymbolTable() {
381  if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
382    return Error("Malformed block record");
383
384  SmallVector<uint64_t, 64> Record;
385
386  // Read all the records for this type table.
387  std::string TypeName;
388  while (1) {
389    unsigned Code = Stream.ReadCode();
390    if (Code == bitc::END_BLOCK) {
391      if (Stream.ReadBlockEnd())
392        return Error("Error at end of type symbol table block");
393      return false;
394    }
395
396    if (Code == bitc::ENTER_SUBBLOCK) {
397      // No known subblocks, always skip them.
398      Stream.ReadSubBlockID();
399      if (Stream.SkipBlock())
400        return Error("Malformed block record");
401      continue;
402    }
403
404    if (Code == bitc::DEFINE_ABBREV) {
405      Stream.ReadAbbrevRecord();
406      continue;
407    }
408
409    // Read a record.
410    Record.clear();
411    switch (Stream.ReadRecord(Code, Record)) {
412    default:  // Default behavior: unknown type.
413      break;
414    case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
415      if (ConvertToString(Record, 1, TypeName))
416        return Error("Invalid TST_ENTRY record");
417      unsigned TypeID = Record[0];
418      if (TypeID >= TypeList.size())
419        return Error("Invalid Type ID in TST_ENTRY record");
420
421      TheModule->addTypeName(TypeName, TypeList[TypeID].get());
422      TypeName.clear();
423      break;
424    }
425  }
426}
427
428bool BitcodeReader::ParseValueSymbolTable() {
429  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
430    return Error("Malformed block record");
431
432  SmallVector<uint64_t, 64> Record;
433
434  // Read all the records for this value table.
435  SmallString<128> ValueName;
436  while (1) {
437    unsigned Code = Stream.ReadCode();
438    if (Code == bitc::END_BLOCK) {
439      if (Stream.ReadBlockEnd())
440        return Error("Error at end of value symbol table block");
441      return false;
442    }
443    if (Code == bitc::ENTER_SUBBLOCK) {
444      // No known subblocks, always skip them.
445      Stream.ReadSubBlockID();
446      if (Stream.SkipBlock())
447        return Error("Malformed block record");
448      continue;
449    }
450
451    if (Code == bitc::DEFINE_ABBREV) {
452      Stream.ReadAbbrevRecord();
453      continue;
454    }
455
456    // Read a record.
457    Record.clear();
458    switch (Stream.ReadRecord(Code, Record)) {
459    default:  // Default behavior: unknown type.
460      break;
461    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
462      if (ConvertToString(Record, 1, ValueName))
463        return Error("Invalid TST_ENTRY record");
464      unsigned ValueID = Record[0];
465      if (ValueID >= ValueList.size())
466        return Error("Invalid Value ID in VST_ENTRY record");
467      Value *V = ValueList[ValueID];
468
469      V->setName(&ValueName[0], ValueName.size());
470      ValueName.clear();
471      break;
472    }
473    case bitc::VST_CODE_BBENTRY: {
474      if (ConvertToString(Record, 1, ValueName))
475        return Error("Invalid VST_BBENTRY record");
476      BasicBlock *BB = getBasicBlock(Record[0]);
477      if (BB == 0)
478        return Error("Invalid BB ID in VST_BBENTRY record");
479
480      BB->setName(&ValueName[0], ValueName.size());
481      ValueName.clear();
482      break;
483    }
484    }
485  }
486}
487
488/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
489/// the LSB for dense VBR encoding.
490static uint64_t DecodeSignRotatedValue(uint64_t V) {
491  if ((V & 1) == 0)
492    return V >> 1;
493  if (V != 1)
494    return -(V >> 1);
495  // There is no such thing as -0 with integers.  "-0" really means MININT.
496  return 1ULL << 63;
497}
498
499/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
500/// values and aliases that we can.
501bool BitcodeReader::ResolveGlobalAndAliasInits() {
502  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
503  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
504
505  GlobalInitWorklist.swap(GlobalInits);
506  AliasInitWorklist.swap(AliasInits);
507
508  while (!GlobalInitWorklist.empty()) {
509    unsigned ValID = GlobalInitWorklist.back().second;
510    if (ValID >= ValueList.size()) {
511      // Not ready to resolve this yet, it requires something later in the file.
512      GlobalInits.push_back(GlobalInitWorklist.back());
513    } else {
514      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
515        GlobalInitWorklist.back().first->setInitializer(C);
516      else
517        return Error("Global variable initializer is not a constant!");
518    }
519    GlobalInitWorklist.pop_back();
520  }
521
522  while (!AliasInitWorklist.empty()) {
523    unsigned ValID = AliasInitWorklist.back().second;
524    if (ValID >= ValueList.size()) {
525      AliasInits.push_back(AliasInitWorklist.back());
526    } else {
527      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
528        AliasInitWorklist.back().first->setAliasee(C);
529      else
530        return Error("Alias initializer is not a constant!");
531    }
532    AliasInitWorklist.pop_back();
533  }
534  return false;
535}
536
537
538bool BitcodeReader::ParseConstants() {
539  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
540    return Error("Malformed block record");
541
542  SmallVector<uint64_t, 64> Record;
543
544  // Read all the records for this value table.
545  const Type *CurTy = Type::Int32Ty;
546  unsigned NextCstNo = ValueList.size();
547  while (1) {
548    unsigned Code = Stream.ReadCode();
549    if (Code == bitc::END_BLOCK) {
550      if (NextCstNo != ValueList.size())
551        return Error("Invalid constant reference!");
552
553      if (Stream.ReadBlockEnd())
554        return Error("Error at end of constants block");
555      return false;
556    }
557
558    if (Code == bitc::ENTER_SUBBLOCK) {
559      // No known subblocks, always skip them.
560      Stream.ReadSubBlockID();
561      if (Stream.SkipBlock())
562        return Error("Malformed block record");
563      continue;
564    }
565
566    if (Code == bitc::DEFINE_ABBREV) {
567      Stream.ReadAbbrevRecord();
568      continue;
569    }
570
571    // Read a record.
572    Record.clear();
573    Value *V = 0;
574    switch (Stream.ReadRecord(Code, Record)) {
575    default:  // Default behavior: unknown constant
576    case bitc::CST_CODE_UNDEF:     // UNDEF
577      V = UndefValue::get(CurTy);
578      break;
579    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
580      if (Record.empty())
581        return Error("Malformed CST_SETTYPE record");
582      if (Record[0] >= TypeList.size())
583        return Error("Invalid Type ID in CST_SETTYPE record");
584      CurTy = TypeList[Record[0]];
585      continue;  // Skip the ValueList manipulation.
586    case bitc::CST_CODE_NULL:      // NULL
587      V = Constant::getNullValue(CurTy);
588      break;
589    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
590      if (!isa<IntegerType>(CurTy) || Record.empty())
591        return Error("Invalid CST_INTEGER record");
592      V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
593      break;
594    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
595      if (!isa<IntegerType>(CurTy) || Record.empty())
596        return Error("Invalid WIDE_INTEGER record");
597
598      unsigned NumWords = Record.size();
599      SmallVector<uint64_t, 8> Words;
600      Words.resize(NumWords);
601      for (unsigned i = 0; i != NumWords; ++i)
602        Words[i] = DecodeSignRotatedValue(Record[i]);
603      V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
604                                 NumWords, &Words[0]));
605      break;
606    }
607    case bitc::CST_CODE_FLOAT:     // FLOAT: [fpval]
608      if (Record.empty())
609        return Error("Invalid FLOAT record");
610      if (CurTy == Type::FloatTy)
611        V = ConstantFP::get(CurTy, BitsToFloat(Record[0]));
612      else if (CurTy == Type::DoubleTy)
613        V = ConstantFP::get(CurTy, BitsToDouble(Record[0]));
614      else
615        V = UndefValue::get(CurTy);
616      break;
617
618    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
619      if (Record.empty())
620        return Error("Invalid CST_AGGREGATE record");
621
622      unsigned Size = Record.size();
623      std::vector<Constant*> Elts;
624
625      if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
626        for (unsigned i = 0; i != Size; ++i)
627          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
628                                                     STy->getElementType(i)));
629        V = ConstantStruct::get(STy, Elts);
630      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
631        const Type *EltTy = ATy->getElementType();
632        for (unsigned i = 0; i != Size; ++i)
633          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
634        V = ConstantArray::get(ATy, Elts);
635      } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
636        const Type *EltTy = VTy->getElementType();
637        for (unsigned i = 0; i != Size; ++i)
638          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
639        V = ConstantVector::get(Elts);
640      } else {
641        V = UndefValue::get(CurTy);
642      }
643      break;
644    }
645    case bitc::CST_CODE_STRING: { // STRING: [values]
646      if (Record.empty())
647        return Error("Invalid CST_AGGREGATE record");
648
649      const ArrayType *ATy = cast<ArrayType>(CurTy);
650      const Type *EltTy = ATy->getElementType();
651
652      unsigned Size = Record.size();
653      std::vector<Constant*> Elts;
654      for (unsigned i = 0; i != Size; ++i)
655        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
656      V = ConstantArray::get(ATy, Elts);
657      break;
658    }
659    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
660      if (Record.empty())
661        return Error("Invalid CST_AGGREGATE record");
662
663      const ArrayType *ATy = cast<ArrayType>(CurTy);
664      const Type *EltTy = ATy->getElementType();
665
666      unsigned Size = Record.size();
667      std::vector<Constant*> Elts;
668      for (unsigned i = 0; i != Size; ++i)
669        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
670      Elts.push_back(Constant::getNullValue(EltTy));
671      V = ConstantArray::get(ATy, Elts);
672      break;
673    }
674    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
675      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
676      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
677      if (Opc < 0) {
678        V = UndefValue::get(CurTy);  // Unknown binop.
679      } else {
680        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
681        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
682        V = ConstantExpr::get(Opc, LHS, RHS);
683      }
684      break;
685    }
686    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
687      if (Record.size() < 3) return Error("Invalid CE_CAST record");
688      int Opc = GetDecodedCastOpcode(Record[0]);
689      if (Opc < 0) {
690        V = UndefValue::get(CurTy);  // Unknown cast.
691      } else {
692        const Type *OpTy = getTypeByID(Record[1]);
693        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
694        V = ConstantExpr::getCast(Opc, Op, CurTy);
695      }
696      break;
697    }
698    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
699      if (Record.size() & 1) return Error("Invalid CE_GEP record");
700      SmallVector<Constant*, 16> Elts;
701      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
702        const Type *ElTy = getTypeByID(Record[i]);
703        if (!ElTy) return Error("Invalid CE_GEP record");
704        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
705      }
706      V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
707      break;
708    }
709    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
710      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
711      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
712                                                              Type::Int1Ty),
713                                  ValueList.getConstantFwdRef(Record[1],CurTy),
714                                  ValueList.getConstantFwdRef(Record[2],CurTy));
715      break;
716    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
717      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
718      const VectorType *OpTy =
719        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
720      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
721      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
722      Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
723                                                  OpTy->getElementType());
724      V = ConstantExpr::getExtractElement(Op0, Op1);
725      break;
726    }
727    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
728      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
729      if (Record.size() < 3 || OpTy == 0)
730        return Error("Invalid CE_INSERTELT record");
731      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
732      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
733                                                  OpTy->getElementType());
734      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
735      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
736      break;
737    }
738    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
739      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
740      if (Record.size() < 3 || OpTy == 0)
741        return Error("Invalid CE_INSERTELT record");
742      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
743      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
744      const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
745      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
746      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
747      break;
748    }
749    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
750      if (Record.size() < 4) return Error("Invalid CE_CMP record");
751      const Type *OpTy = getTypeByID(Record[0]);
752      if (OpTy == 0) return Error("Invalid CE_CMP record");
753      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
754      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
755
756      if (OpTy->isFloatingPoint())
757        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
758      else
759        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
760      break;
761    }
762    }
763
764    ValueList.AssignValue(V, NextCstNo);
765    ++NextCstNo;
766  }
767}
768
769/// RememberAndSkipFunctionBody - When we see the block for a function body,
770/// remember where it is and then skip it.  This lets us lazily deserialize the
771/// functions.
772bool BitcodeReader::RememberAndSkipFunctionBody() {
773  // Get the function we are talking about.
774  if (FunctionsWithBodies.empty())
775    return Error("Insufficient function protos");
776
777  Function *Fn = FunctionsWithBodies.back();
778  FunctionsWithBodies.pop_back();
779
780  // Save the current stream state.
781  uint64_t CurBit = Stream.GetCurrentBitNo();
782  DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
783
784  // Set the functions linkage to GhostLinkage so we know it is lazily
785  // deserialized.
786  Fn->setLinkage(GlobalValue::GhostLinkage);
787
788  // Skip over the function block for now.
789  if (Stream.SkipBlock())
790    return Error("Malformed block record");
791  return false;
792}
793
794bool BitcodeReader::ParseModule(const std::string &ModuleID) {
795  // Reject multiple MODULE_BLOCK's in a single bitstream.
796  if (TheModule)
797    return Error("Multiple MODULE_BLOCKs in same stream");
798
799  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
800    return Error("Malformed block record");
801
802  // Otherwise, create the module.
803  TheModule = new Module(ModuleID);
804
805  SmallVector<uint64_t, 64> Record;
806  std::vector<std::string> SectionTable;
807
808  // Read all the records for this module.
809  while (!Stream.AtEndOfStream()) {
810    unsigned Code = Stream.ReadCode();
811    if (Code == bitc::END_BLOCK) {
812      if (Stream.ReadBlockEnd())
813        return Error("Error at end of module block");
814
815      // Patch the initializers for globals and aliases up.
816      ResolveGlobalAndAliasInits();
817      if (!GlobalInits.empty() || !AliasInits.empty())
818        return Error("Malformed global initializer set");
819      if (!FunctionsWithBodies.empty())
820        return Error("Too few function bodies found");
821
822      // Force deallocation of memory for these vectors to favor the client that
823      // want lazy deserialization.
824      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
825      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
826      std::vector<Function*>().swap(FunctionsWithBodies);
827      return false;
828    }
829
830    if (Code == bitc::ENTER_SUBBLOCK) {
831      switch (Stream.ReadSubBlockID()) {
832      default:  // Skip unknown content.
833        if (Stream.SkipBlock())
834          return Error("Malformed block record");
835        break;
836      case bitc::BLOCKINFO_BLOCK_ID:
837        if (Stream.ReadBlockInfoBlock())
838          return Error("Malformed BlockInfoBlock");
839        break;
840      case bitc::PARAMATTR_BLOCK_ID:
841        if (ParseParamAttrBlock())
842          return true;
843        break;
844      case bitc::TYPE_BLOCK_ID:
845        if (ParseTypeTable())
846          return true;
847        break;
848      case bitc::TYPE_SYMTAB_BLOCK_ID:
849        if (ParseTypeSymbolTable())
850          return true;
851        break;
852      case bitc::VALUE_SYMTAB_BLOCK_ID:
853        if (ParseValueSymbolTable())
854          return true;
855        break;
856      case bitc::CONSTANTS_BLOCK_ID:
857        if (ParseConstants() || ResolveGlobalAndAliasInits())
858          return true;
859        break;
860      case bitc::FUNCTION_BLOCK_ID:
861        // If this is the first function body we've seen, reverse the
862        // FunctionsWithBodies list.
863        if (!HasReversedFunctionsWithBodies) {
864          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
865          HasReversedFunctionsWithBodies = true;
866        }
867
868        if (RememberAndSkipFunctionBody())
869          return true;
870        break;
871      }
872      continue;
873    }
874
875    if (Code == bitc::DEFINE_ABBREV) {
876      Stream.ReadAbbrevRecord();
877      continue;
878    }
879
880    // Read a record.
881    switch (Stream.ReadRecord(Code, Record)) {
882    default: break;  // Default behavior, ignore unknown content.
883    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
884      if (Record.size() < 1)
885        return Error("Malformed MODULE_CODE_VERSION");
886      // Only version #0 is supported so far.
887      if (Record[0] != 0)
888        return Error("Unknown bitstream version!");
889      break;
890    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
891      std::string S;
892      if (ConvertToString(Record, 0, S))
893        return Error("Invalid MODULE_CODE_TRIPLE record");
894      TheModule->setTargetTriple(S);
895      break;
896    }
897    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
898      std::string S;
899      if (ConvertToString(Record, 0, S))
900        return Error("Invalid MODULE_CODE_DATALAYOUT record");
901      TheModule->setDataLayout(S);
902      break;
903    }
904    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
905      std::string S;
906      if (ConvertToString(Record, 0, S))
907        return Error("Invalid MODULE_CODE_ASM record");
908      TheModule->setModuleInlineAsm(S);
909      break;
910    }
911    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
912      std::string S;
913      if (ConvertToString(Record, 0, S))
914        return Error("Invalid MODULE_CODE_DEPLIB record");
915      TheModule->addLibrary(S);
916      break;
917    }
918    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
919      std::string S;
920      if (ConvertToString(Record, 0, S))
921        return Error("Invalid MODULE_CODE_SECTIONNAME record");
922      SectionTable.push_back(S);
923      break;
924    }
925    // GLOBALVAR: [type, isconst, initid,
926    //             linkage, alignment, section, visibility, threadlocal]
927    case bitc::MODULE_CODE_GLOBALVAR: {
928      if (Record.size() < 6)
929        return Error("Invalid MODULE_CODE_GLOBALVAR record");
930      const Type *Ty = getTypeByID(Record[0]);
931      if (!isa<PointerType>(Ty))
932        return Error("Global not a pointer type!");
933      Ty = cast<PointerType>(Ty)->getElementType();
934
935      bool isConstant = Record[1];
936      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
937      unsigned Alignment = (1 << Record[4]) >> 1;
938      std::string Section;
939      if (Record[5]) {
940        if (Record[5]-1 >= SectionTable.size())
941          return Error("Invalid section ID");
942        Section = SectionTable[Record[5]-1];
943      }
944      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
945      if (Record.size() >= 6) Visibility = GetDecodedVisibility(Record[6]);
946      bool isThreadLocal = false;
947      if (Record.size() >= 7) isThreadLocal = Record[7];
948
949      GlobalVariable *NewGV =
950        new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule);
951      NewGV->setAlignment(Alignment);
952      if (!Section.empty())
953        NewGV->setSection(Section);
954      NewGV->setVisibility(Visibility);
955      NewGV->setThreadLocal(isThreadLocal);
956
957      ValueList.push_back(NewGV);
958
959      // Remember which value to use for the global initializer.
960      if (unsigned InitID = Record[2])
961        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
962      break;
963    }
964    // FUNCTION:  [type, callingconv, isproto, linkage, alignment, section,
965    //             visibility]
966    case bitc::MODULE_CODE_FUNCTION: {
967      if (Record.size() < 7)
968        return Error("Invalid MODULE_CODE_FUNCTION record");
969      const Type *Ty = getTypeByID(Record[0]);
970      if (!isa<PointerType>(Ty))
971        return Error("Function not a pointer type!");
972      const FunctionType *FTy =
973        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
974      if (!FTy)
975        return Error("Function not a pointer to function type!");
976
977      Function *Func = new Function(FTy, GlobalValue::ExternalLinkage,
978                                    "", TheModule);
979
980      Func->setCallingConv(Record[1]);
981      bool isProto = Record[2];
982      Func->setLinkage(GetDecodedLinkage(Record[3]));
983      Func->setAlignment((1 << Record[4]) >> 1);
984      if (Record[5]) {
985        if (Record[5]-1 >= SectionTable.size())
986          return Error("Invalid section ID");
987        Func->setSection(SectionTable[Record[5]-1]);
988      }
989      Func->setVisibility(GetDecodedVisibility(Record[6]));
990
991      ValueList.push_back(Func);
992
993      // If this is a function with a body, remember the prototype we are
994      // creating now, so that we can match up the body with them later.
995      if (!isProto)
996        FunctionsWithBodies.push_back(Func);
997      break;
998    }
999    // ALIAS: [alias type, aliasee val#, linkage]
1000    case bitc::MODULE_CODE_ALIAS: {
1001      if (Record.size() < 3)
1002        return Error("Invalid MODULE_ALIAS record");
1003      const Type *Ty = getTypeByID(Record[0]);
1004      if (!isa<PointerType>(Ty))
1005        return Error("Function not a pointer type!");
1006
1007      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1008                                           "", 0, TheModule);
1009      ValueList.push_back(NewGA);
1010      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1011      break;
1012    }
1013    /// MODULE_CODE_PURGEVALS: [numvals]
1014    case bitc::MODULE_CODE_PURGEVALS:
1015      // Trim down the value list to the specified size.
1016      if (Record.size() < 1 || Record[0] > ValueList.size())
1017        return Error("Invalid MODULE_PURGEVALS record");
1018      ValueList.shrinkTo(Record[0]);
1019      break;
1020    }
1021    Record.clear();
1022  }
1023
1024  return Error("Premature end of bitstream");
1025}
1026
1027
1028bool BitcodeReader::ParseBitcode() {
1029  TheModule = 0;
1030
1031  if (Buffer->getBufferSize() & 3)
1032    return Error("Bitcode stream should be a multiple of 4 bytes in length");
1033
1034  unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1035  Stream.init(BufPtr, BufPtr+Buffer->getBufferSize());
1036
1037  // Sniff for the signature.
1038  if (Stream.Read(8) != 'B' ||
1039      Stream.Read(8) != 'C' ||
1040      Stream.Read(4) != 0x0 ||
1041      Stream.Read(4) != 0xC ||
1042      Stream.Read(4) != 0xE ||
1043      Stream.Read(4) != 0xD)
1044    return Error("Invalid bitcode signature");
1045
1046  // We expect a number of well-defined blocks, though we don't necessarily
1047  // need to understand them all.
1048  while (!Stream.AtEndOfStream()) {
1049    unsigned Code = Stream.ReadCode();
1050
1051    if (Code != bitc::ENTER_SUBBLOCK)
1052      return Error("Invalid record at top-level");
1053
1054    unsigned BlockID = Stream.ReadSubBlockID();
1055
1056    // We only know the MODULE subblock ID.
1057    switch (BlockID) {
1058    case bitc::BLOCKINFO_BLOCK_ID:
1059      if (Stream.ReadBlockInfoBlock())
1060        return Error("Malformed BlockInfoBlock");
1061      break;
1062    case bitc::MODULE_BLOCK_ID:
1063      if (ParseModule(Buffer->getBufferIdentifier()))
1064        return true;
1065      break;
1066    default:
1067      if (Stream.SkipBlock())
1068        return Error("Malformed block record");
1069      break;
1070    }
1071  }
1072
1073  return false;
1074}
1075
1076
1077bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1078  // If it already is material, ignore the request.
1079  if (!F->hasNotBeenReadFromBytecode()) return false;
1080
1081  DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1082    DeferredFunctionInfo.find(F);
1083  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1084
1085  // Move the bit stream to the saved position of the deferred function body and
1086  // restore the real linkage type for the function.
1087  Stream.JumpToBit(DFII->second.first);
1088  F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1089  DeferredFunctionInfo.erase(DFII);
1090
1091  if (ParseFunctionBody(F)) {
1092    if (ErrInfo) *ErrInfo = ErrorString;
1093    return true;
1094  }
1095
1096  return false;
1097}
1098
1099Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1100  DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1101    DeferredFunctionInfo.begin();
1102  while (!DeferredFunctionInfo.empty()) {
1103    Function *F = (*I++).first;
1104    assert(F->hasNotBeenReadFromBytecode() &&
1105           "Deserialized function found in map!");
1106    if (materializeFunction(F, ErrInfo))
1107      return 0;
1108  }
1109  return TheModule;
1110}
1111
1112
1113/// ParseFunctionBody - Lazily parse the specified function body block.
1114bool BitcodeReader::ParseFunctionBody(Function *F) {
1115  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1116    return Error("Malformed block record");
1117
1118  unsigned ModuleValueListSize = ValueList.size();
1119
1120  // Add all the function arguments to the value table.
1121  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1122    ValueList.push_back(I);
1123
1124  unsigned NextValueNo = ValueList.size();
1125  BasicBlock *CurBB = 0;
1126  unsigned CurBBNo = 0;
1127
1128  // Read all the records.
1129  SmallVector<uint64_t, 64> Record;
1130  while (1) {
1131    unsigned Code = Stream.ReadCode();
1132    if (Code == bitc::END_BLOCK) {
1133      if (Stream.ReadBlockEnd())
1134        return Error("Error at end of function block");
1135      break;
1136    }
1137
1138    if (Code == bitc::ENTER_SUBBLOCK) {
1139      switch (Stream.ReadSubBlockID()) {
1140      default:  // Skip unknown content.
1141        if (Stream.SkipBlock())
1142          return Error("Malformed block record");
1143        break;
1144      case bitc::CONSTANTS_BLOCK_ID:
1145        if (ParseConstants()) return true;
1146        NextValueNo = ValueList.size();
1147        break;
1148      case bitc::VALUE_SYMTAB_BLOCK_ID:
1149        if (ParseValueSymbolTable()) return true;
1150        break;
1151      }
1152      continue;
1153    }
1154
1155    if (Code == bitc::DEFINE_ABBREV) {
1156      Stream.ReadAbbrevRecord();
1157      continue;
1158    }
1159
1160    // Read a record.
1161    Record.clear();
1162    Instruction *I = 0;
1163    switch (Stream.ReadRecord(Code, Record)) {
1164    default: // Default behavior: reject
1165      return Error("Unknown instruction");
1166    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1167      if (Record.size() < 1 || Record[0] == 0)
1168        return Error("Invalid DECLAREBLOCKS record");
1169      // Create all the basic blocks for the function.
1170      FunctionBBs.resize(Record[0]);
1171      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1172        FunctionBBs[i] = new BasicBlock("", F);
1173      CurBB = FunctionBBs[0];
1174      continue;
1175
1176    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1177      unsigned OpNum = 0;
1178      Value *LHS, *RHS;
1179      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1180          getValue(Record, OpNum, LHS->getType(), RHS) ||
1181          OpNum+1 != Record.size())
1182        return Error("Invalid BINOP record");
1183
1184      int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1185      if (Opc == -1) return Error("Invalid BINOP record");
1186      I = BinaryOperator::create((Instruction::BinaryOps)Opc, LHS, RHS);
1187      break;
1188    }
1189    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1190      unsigned OpNum = 0;
1191      Value *Op;
1192      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1193          OpNum+2 != Record.size())
1194        return Error("Invalid CAST record");
1195
1196      const Type *ResTy = getTypeByID(Record[OpNum]);
1197      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1198      if (Opc == -1 || ResTy == 0)
1199        return Error("Invalid CAST record");
1200      I = CastInst::create((Instruction::CastOps)Opc, Op, ResTy);
1201      break;
1202    }
1203    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1204      unsigned OpNum = 0;
1205      Value *BasePtr;
1206      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1207        return Error("Invalid GEP record");
1208
1209      SmallVector<Value*, 16> GEPIdx;
1210      while (OpNum != Record.size()) {
1211        Value *Op;
1212        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1213          return Error("Invalid GEP record");
1214        GEPIdx.push_back(Op);
1215      }
1216
1217      I = new GetElementPtrInst(BasePtr, &GEPIdx[0], GEPIdx.size());
1218      break;
1219    }
1220
1221    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1222      unsigned OpNum = 0;
1223      Value *TrueVal, *FalseVal, *Cond;
1224      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1225          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1226          getValue(Record, OpNum, Type::Int1Ty, Cond))
1227        return Error("Invalid SELECT record");
1228
1229      I = new SelectInst(Cond, TrueVal, FalseVal);
1230      break;
1231    }
1232
1233    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1234      unsigned OpNum = 0;
1235      Value *Vec, *Idx;
1236      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1237          getValue(Record, OpNum, Type::Int32Ty, Idx))
1238        return Error("Invalid EXTRACTELT record");
1239      I = new ExtractElementInst(Vec, Idx);
1240      break;
1241    }
1242
1243    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1244      unsigned OpNum = 0;
1245      Value *Vec, *Elt, *Idx;
1246      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1247          getValue(Record, OpNum,
1248                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1249          getValue(Record, OpNum, Type::Int32Ty, Idx))
1250        return Error("Invalid INSERTELT record");
1251      I = new InsertElementInst(Vec, Elt, Idx);
1252      break;
1253    }
1254
1255    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1256      unsigned OpNum = 0;
1257      Value *Vec1, *Vec2, *Mask;
1258      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1259          getValue(Record, OpNum, Vec1->getType(), Vec2))
1260        return Error("Invalid SHUFFLEVEC record");
1261
1262      const Type *MaskTy =
1263        VectorType::get(Type::Int32Ty,
1264                        cast<VectorType>(Vec1->getType())->getNumElements());
1265
1266      if (getValue(Record, OpNum, MaskTy, Mask))
1267        return Error("Invalid SHUFFLEVEC record");
1268      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1269      break;
1270    }
1271
1272    case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1273      unsigned OpNum = 0;
1274      Value *LHS, *RHS;
1275      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1276          getValue(Record, OpNum, LHS->getType(), RHS) ||
1277          OpNum+1 != Record.size())
1278        return Error("Invalid CMP record");
1279
1280      if (LHS->getType()->isFPOrFPVector())
1281        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1282      else
1283        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1284      break;
1285    }
1286
1287    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1288      if (Record.size() == 0) {
1289        I = new ReturnInst();
1290        break;
1291      } else {
1292        unsigned OpNum = 0;
1293        Value *Op;
1294        if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1295            OpNum != Record.size())
1296          return Error("Invalid RET record");
1297        I = new ReturnInst(Op);
1298        break;
1299      }
1300    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1301      if (Record.size() != 1 && Record.size() != 3)
1302        return Error("Invalid BR record");
1303      BasicBlock *TrueDest = getBasicBlock(Record[0]);
1304      if (TrueDest == 0)
1305        return Error("Invalid BR record");
1306
1307      if (Record.size() == 1)
1308        I = new BranchInst(TrueDest);
1309      else {
1310        BasicBlock *FalseDest = getBasicBlock(Record[1]);
1311        Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1312        if (FalseDest == 0 || Cond == 0)
1313          return Error("Invalid BR record");
1314        I = new BranchInst(TrueDest, FalseDest, Cond);
1315      }
1316      break;
1317    }
1318    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1319      if (Record.size() < 3 || (Record.size() & 1) == 0)
1320        return Error("Invalid SWITCH record");
1321      const Type *OpTy = getTypeByID(Record[0]);
1322      Value *Cond = getFnValueByID(Record[1], OpTy);
1323      BasicBlock *Default = getBasicBlock(Record[2]);
1324      if (OpTy == 0 || Cond == 0 || Default == 0)
1325        return Error("Invalid SWITCH record");
1326      unsigned NumCases = (Record.size()-3)/2;
1327      SwitchInst *SI = new SwitchInst(Cond, Default, NumCases);
1328      for (unsigned i = 0, e = NumCases; i != e; ++i) {
1329        ConstantInt *CaseVal =
1330          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1331        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1332        if (CaseVal == 0 || DestBB == 0) {
1333          delete SI;
1334          return Error("Invalid SWITCH record!");
1335        }
1336        SI->addCase(CaseVal, DestBB);
1337      }
1338      I = SI;
1339      break;
1340    }
1341
1342    case bitc::FUNC_CODE_INST_INVOKE: { // INVOKE: [cc,fnty, op0,op1,op2, ...]
1343      if (Record.size() < 3) return Error("Invalid INVOKE record");
1344      unsigned CCInfo = Record[0];
1345      BasicBlock *NormalBB = getBasicBlock(Record[1]);
1346      BasicBlock *UnwindBB = getBasicBlock(Record[2]);
1347
1348      unsigned OpNum = 3;
1349      Value *Callee;
1350      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1351        return Error("Invalid INVOKE record");
1352
1353      const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1354      const FunctionType *FTy = !CalleeTy ? 0 :
1355        dyn_cast<FunctionType>(CalleeTy->getElementType());
1356
1357      // Check that the right number of fixed parameters are here.
1358      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1359          Record.size() < OpNum+FTy->getNumParams())
1360        return Error("Invalid INVOKE record");
1361
1362      SmallVector<Value*, 16> Ops;
1363      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1364        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1365        if (Ops.back() == 0) return Error("Invalid INVOKE record");
1366      }
1367
1368      if (!FTy->isVarArg()) {
1369        if (Record.size() != OpNum)
1370          return Error("Invalid INVOKE record");
1371      } else {
1372        // Read type/value pairs for varargs params.
1373        while (OpNum != Record.size()) {
1374          Value *Op;
1375          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1376            return Error("Invalid INVOKE record");
1377          Ops.push_back(Op);
1378        }
1379      }
1380
1381      I = new InvokeInst(Callee, NormalBB, UnwindBB, &Ops[0], Ops.size());
1382      cast<InvokeInst>(I)->setCallingConv(CCInfo);
1383      break;
1384    }
1385    case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1386      I = new UnwindInst();
1387      break;
1388    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1389      I = new UnreachableInst();
1390      break;
1391    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1392      if (Record.size() < 1 || ((Record.size()-1)&1))
1393        return Error("Invalid PHI record");
1394      const Type *Ty = getTypeByID(Record[0]);
1395      if (!Ty) return Error("Invalid PHI record");
1396
1397      PHINode *PN = new PHINode(Ty);
1398      PN->reserveOperandSpace(Record.size()-1);
1399
1400      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1401        Value *V = getFnValueByID(Record[1+i], Ty);
1402        BasicBlock *BB = getBasicBlock(Record[2+i]);
1403        if (!V || !BB) return Error("Invalid PHI record");
1404        PN->addIncoming(V, BB);
1405      }
1406      I = PN;
1407      break;
1408    }
1409
1410    case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1411      if (Record.size() < 3)
1412        return Error("Invalid MALLOC record");
1413      const PointerType *Ty =
1414        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1415      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1416      unsigned Align = Record[2];
1417      if (!Ty || !Size) return Error("Invalid MALLOC record");
1418      I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1419      break;
1420    }
1421    case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1422      unsigned OpNum = 0;
1423      Value *Op;
1424      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1425          OpNum != Record.size())
1426        return Error("Invalid FREE record");
1427      I = new FreeInst(Op);
1428      break;
1429    }
1430    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1431      if (Record.size() < 3)
1432        return Error("Invalid ALLOCA record");
1433      const PointerType *Ty =
1434        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1435      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1436      unsigned Align = Record[2];
1437      if (!Ty || !Size) return Error("Invalid ALLOCA record");
1438      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1439      break;
1440    }
1441    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1442      unsigned OpNum = 0;
1443      Value *Op;
1444      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1445          OpNum+2 != Record.size())
1446        return Error("Invalid LOAD record");
1447
1448      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1449      break;
1450    }
1451    case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1452      unsigned OpNum = 0;
1453      Value *Val, *Ptr;
1454      if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1455          getValue(Record, OpNum, PointerType::get(Val->getType()), Ptr) ||
1456          OpNum+2 != Record.size())
1457        return Error("Invalid STORE record");
1458
1459      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1460      break;
1461    }
1462    case bitc::FUNC_CODE_INST_CALL: { // CALL: [cc, fnty, fnid, arg0, arg1...]
1463      if (Record.size() < 1)
1464        return Error("Invalid CALL record");
1465      unsigned CCInfo = Record[0];
1466
1467      unsigned OpNum = 1;
1468      Value *Callee;
1469      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1470        return Error("Invalid CALL record");
1471
1472      const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1473      const FunctionType *FTy = 0;
1474      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1475      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1476        return Error("Invalid CALL record");
1477
1478      SmallVector<Value*, 16> Args;
1479      // Read the fixed params.
1480      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1481        Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1482        if (Args.back() == 0) return Error("Invalid CALL record");
1483      }
1484
1485      // Read type/value pairs for varargs params.
1486      if (!FTy->isVarArg()) {
1487        if (OpNum != Record.size())
1488          return Error("Invalid CALL record");
1489      } else {
1490        while (OpNum != Record.size()) {
1491          Value *Op;
1492          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1493            return Error("Invalid CALL record");
1494          Args.push_back(Op);
1495        }
1496      }
1497
1498      I = new CallInst(Callee, &Args[0], Args.size());
1499      cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1500      cast<CallInst>(I)->setTailCall(CCInfo & 1);
1501      break;
1502    }
1503    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1504      if (Record.size() < 3)
1505        return Error("Invalid VAARG record");
1506      const Type *OpTy = getTypeByID(Record[0]);
1507      Value *Op = getFnValueByID(Record[1], OpTy);
1508      const Type *ResTy = getTypeByID(Record[2]);
1509      if (!OpTy || !Op || !ResTy)
1510        return Error("Invalid VAARG record");
1511      I = new VAArgInst(Op, ResTy);
1512      break;
1513    }
1514    }
1515
1516    // Add instruction to end of current BB.  If there is no current BB, reject
1517    // this file.
1518    if (CurBB == 0) {
1519      delete I;
1520      return Error("Invalid instruction with no BB");
1521    }
1522    CurBB->getInstList().push_back(I);
1523
1524    // If this was a terminator instruction, move to the next block.
1525    if (isa<TerminatorInst>(I)) {
1526      ++CurBBNo;
1527      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1528    }
1529
1530    // Non-void values get registered in the value table for future use.
1531    if (I && I->getType() != Type::VoidTy)
1532      ValueList.AssignValue(I, NextValueNo++);
1533  }
1534
1535  // Check the function list for unresolved values.
1536  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1537    if (A->getParent() == 0) {
1538      // We found at least one unresolved value.  Nuke them all to avoid leaks.
1539      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1540        if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1541          A->replaceAllUsesWith(UndefValue::get(A->getType()));
1542          delete A;
1543        }
1544      }
1545      return Error("Never resolved value found in function!");
1546    }
1547  }
1548
1549  // Trim the value list down to the size it was before we parsed this function.
1550  ValueList.shrinkTo(ModuleValueListSize);
1551  std::vector<BasicBlock*>().swap(FunctionBBs);
1552
1553  return false;
1554}
1555
1556
1557//===----------------------------------------------------------------------===//
1558// External interface
1559//===----------------------------------------------------------------------===//
1560
1561/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1562///
1563ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1564                                               std::string *ErrMsg) {
1565  BitcodeReader *R = new BitcodeReader(Buffer);
1566  if (R->ParseBitcode()) {
1567    if (ErrMsg)
1568      *ErrMsg = R->getErrorString();
1569
1570    // Don't let the BitcodeReader dtor delete 'Buffer'.
1571    R->releaseMemoryBuffer();
1572    delete R;
1573    return 0;
1574  }
1575  return R;
1576}
1577
1578/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
1579/// If an error occurs, return null and fill in *ErrMsg if non-null.
1580Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
1581  BitcodeReader *R;
1582  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
1583  if (!R) return 0;
1584
1585  // Read the whole module, get a pointer to it, tell ModuleProvider not to
1586  // delete it when its dtor is run.
1587  Module *M = R->releaseModule(ErrMsg);
1588
1589  // Don't let the BitcodeReader dtor delete 'Buffer'.
1590  R->releaseMemoryBuffer();
1591  delete R;
1592  return M;
1593}
1594