BitcodeReader.cpp revision b6135a054d46c00e2ba604e8f509de48e6dcfde6
1//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// 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/InlineAsm.h"
19#include "llvm/Instructions.h"
20#include "llvm/Module.h"
21#include "llvm/AutoUpgrade.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/Support/MathExtras.h"
25#include "llvm/Support/MemoryBuffer.h"
26#include "llvm/OperandTraits.h"
27using namespace llvm;
28
29void BitcodeReader::FreeState() {
30  delete Buffer;
31  Buffer = 0;
32  std::vector<PATypeHolder>().swap(TypeList);
33  ValueList.clear();
34
35  std::vector<PAListPtr>().swap(ParamAttrs);
36  std::vector<BasicBlock*>().swap(FunctionBBs);
37  std::vector<Function*>().swap(FunctionsWithBodies);
38  DeferredFunctionInfo.clear();
39}
40
41//===----------------------------------------------------------------------===//
42//  Helper functions to implement forward reference resolution, etc.
43//===----------------------------------------------------------------------===//
44
45/// ConvertToString - Convert a string from a record into an std::string, return
46/// true on failure.
47template<typename StrTy>
48static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
49                            StrTy &Result) {
50  if (Idx > Record.size())
51    return true;
52
53  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
54    Result += (char)Record[i];
55  return false;
56}
57
58static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
59  switch (Val) {
60  default: // Map unknown/new linkages to external
61  case 0: return GlobalValue::ExternalLinkage;
62  case 1: return GlobalValue::WeakLinkage;
63  case 2: return GlobalValue::AppendingLinkage;
64  case 3: return GlobalValue::InternalLinkage;
65  case 4: return GlobalValue::LinkOnceLinkage;
66  case 5: return GlobalValue::DLLImportLinkage;
67  case 6: return GlobalValue::DLLExportLinkage;
68  case 7: return GlobalValue::ExternalWeakLinkage;
69  case 8: return GlobalValue::CommonLinkage;
70  }
71}
72
73static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
74  switch (Val) {
75  default: // Map unknown visibilities to default.
76  case 0: return GlobalValue::DefaultVisibility;
77  case 1: return GlobalValue::HiddenVisibility;
78  case 2: return GlobalValue::ProtectedVisibility;
79  }
80}
81
82static int GetDecodedCastOpcode(unsigned Val) {
83  switch (Val) {
84  default: return -1;
85  case bitc::CAST_TRUNC   : return Instruction::Trunc;
86  case bitc::CAST_ZEXT    : return Instruction::ZExt;
87  case bitc::CAST_SEXT    : return Instruction::SExt;
88  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
89  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
90  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
91  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
92  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
93  case bitc::CAST_FPEXT   : return Instruction::FPExt;
94  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
95  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
96  case bitc::CAST_BITCAST : return Instruction::BitCast;
97  }
98}
99static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
100  switch (Val) {
101  default: return -1;
102  case bitc::BINOP_ADD:  return Instruction::Add;
103  case bitc::BINOP_SUB:  return Instruction::Sub;
104  case bitc::BINOP_MUL:  return Instruction::Mul;
105  case bitc::BINOP_UDIV: return Instruction::UDiv;
106  case bitc::BINOP_SDIV:
107    return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
108  case bitc::BINOP_UREM: return Instruction::URem;
109  case bitc::BINOP_SREM:
110    return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
111  case bitc::BINOP_SHL:  return Instruction::Shl;
112  case bitc::BINOP_LSHR: return Instruction::LShr;
113  case bitc::BINOP_ASHR: return Instruction::AShr;
114  case bitc::BINOP_AND:  return Instruction::And;
115  case bitc::BINOP_OR:   return Instruction::Or;
116  case bitc::BINOP_XOR:  return Instruction::Xor;
117  }
118}
119
120namespace llvm {
121namespace {
122  /// @brief A class for maintaining the slot number definition
123  /// as a placeholder for the actual definition for forward constants defs.
124  class ConstantPlaceHolder : public ConstantExpr {
125    ConstantPlaceHolder();                       // DO NOT IMPLEMENT
126    void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
127  public:
128    // allocate space for exactly one operand
129    void *operator new(size_t s) {
130      return User::operator new(s, 1);
131    }
132    explicit ConstantPlaceHolder(const Type *Ty)
133      : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
134      Op<0>() = UndefValue::get(Type::Int32Ty);
135    }
136
137    /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
138    static inline bool classof(const ConstantPlaceHolder *) { return true; }
139    static bool classof(const Value *V) {
140      return isa<ConstantExpr>(V) &&
141             cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
142    }
143
144
145    /// Provide fast operand accessors
146    DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
147  };
148}
149
150
151  // FIXME: can we inherit this from ConstantExpr?
152template <>
153struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
154};
155
156DEFINE_TRANSPARENT_OPERAND_ACCESSORS(ConstantPlaceHolder, Value)
157}
158
159void BitcodeReaderValueList::resize(unsigned Desired) {
160  if (Desired > Capacity) {
161    // Since we expect many values to come from the bitcode file we better
162    // allocate the double amount, so that the array size grows exponentially
163    // at each reallocation.  Also, add a small amount of 100 extra elements
164    // each time, to reallocate less frequently when the array is still small.
165    //
166    Capacity = Desired * 2 + 100;
167    Use *New = allocHungoffUses(Capacity);
168    Use *Old = OperandList;
169    unsigned Ops = getNumOperands();
170    for (int i(Ops - 1); i >= 0; --i)
171      New[i] = Old[i].get();
172    OperandList = New;
173    if (Old) Use::zap(Old, Old + Ops, true);
174  }
175}
176
177Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
178                                                    const Type *Ty) {
179  if (Idx >= size()) {
180    // Insert a bunch of null values.
181    resize(Idx + 1);
182    NumOperands = Idx+1;
183  }
184
185  if (Value *V = OperandList[Idx]) {
186    assert(Ty == V->getType() && "Type mismatch in constant table!");
187    return cast<Constant>(V);
188  }
189
190  // Create and return a placeholder, which will later be RAUW'd.
191  Constant *C = new ConstantPlaceHolder(Ty);
192  OperandList[Idx] = C;
193  return C;
194}
195
196Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
197  if (Idx >= size()) {
198    // Insert a bunch of null values.
199    resize(Idx + 1);
200    NumOperands = Idx+1;
201  }
202
203  if (Value *V = OperandList[Idx]) {
204    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
205    return V;
206  }
207
208  // No type specified, must be invalid reference.
209  if (Ty == 0) return 0;
210
211  // Create and return a placeholder, which will later be RAUW'd.
212  Value *V = new Argument(Ty);
213  OperandList[Idx] = V;
214  return V;
215}
216
217/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
218/// resolves any forward references.  The idea behind this is that we sometimes
219/// get constants (such as large arrays) which reference *many* forward ref
220/// constants.  Replacing each of these causes a lot of thrashing when
221/// building/reuniquing the constant.  Instead of doing this, we look at all the
222/// uses and rewrite all the place holders at once for any constant that uses
223/// a placeholder.
224void BitcodeReaderValueList::ResolveConstantForwardRefs() {
225  // Sort the values by-pointer so that they are efficient to look up with a
226  // binary search.
227  std::sort(ResolveConstants.begin(), ResolveConstants.end());
228
229  SmallVector<Constant*, 64> NewOps;
230
231  while (!ResolveConstants.empty()) {
232    Value *RealVal = getOperand(ResolveConstants.back().second);
233    Constant *Placeholder = ResolveConstants.back().first;
234    ResolveConstants.pop_back();
235
236    // Loop over all users of the placeholder, updating them to reference the
237    // new value.  If they reference more than one placeholder, update them all
238    // at once.
239    while (!Placeholder->use_empty()) {
240      Value::use_iterator UI = Placeholder->use_begin();
241
242      // If the using object isn't uniqued, just update the operands.  This
243      // handles instructions and initializers for global variables.
244      if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
245        UI.getUse().set(RealVal);
246        continue;
247      }
248
249      // Otherwise, we have a constant that uses the placeholder.  Replace that
250      // constant with a new constant that has *all* placeholder uses updated.
251      Constant *UserC = cast<Constant>(*UI);
252      for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
253           I != E; ++I) {
254        Value *NewOp;
255        if (!isa<ConstantPlaceHolder>(*I)) {
256          // Not a placeholder reference.
257          NewOp = *I;
258        } else if (*I == Placeholder) {
259          // Common case is that it just references this one placeholder.
260          NewOp = RealVal;
261        } else {
262          // Otherwise, look up the placeholder in ResolveConstants.
263          ResolveConstantsTy::iterator It =
264            std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
265                             std::pair<Constant*, unsigned>(cast<Constant>(*I),
266                                                            0));
267          assert(It != ResolveConstants.end() && It->first == *I);
268          NewOp = this->getOperand(It->second);
269        }
270
271        NewOps.push_back(cast<Constant>(NewOp));
272      }
273
274      // Make the new constant.
275      Constant *NewC;
276      if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
277        NewC = ConstantArray::get(UserCA->getType(), &NewOps[0], NewOps.size());
278      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
279        NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
280                                   UserCS->getType()->isPacked());
281      } else if (isa<ConstantVector>(UserC)) {
282        NewC = ConstantVector::get(&NewOps[0], NewOps.size());
283      } else {
284        // Must be a constant expression.
285        NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
286                                                          NewOps.size());
287      }
288
289      UserC->replaceAllUsesWith(NewC);
290      UserC->destroyConstant();
291      NewOps.clear();
292    }
293
294    delete Placeholder;
295  }
296}
297
298
299const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
300  // If the TypeID is in range, return it.
301  if (ID < TypeList.size())
302    return TypeList[ID].get();
303  if (!isTypeTable) return 0;
304
305  // The type table allows forward references.  Push as many Opaque types as
306  // needed to get up to ID.
307  while (TypeList.size() <= ID)
308    TypeList.push_back(OpaqueType::get());
309  return TypeList.back().get();
310}
311
312//===----------------------------------------------------------------------===//
313//  Functions for parsing blocks from the bitcode file
314//===----------------------------------------------------------------------===//
315
316bool BitcodeReader::ParseParamAttrBlock() {
317  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
318    return Error("Malformed block record");
319
320  if (!ParamAttrs.empty())
321    return Error("Multiple PARAMATTR blocks found!");
322
323  SmallVector<uint64_t, 64> Record;
324
325  SmallVector<ParamAttrsWithIndex, 8> Attrs;
326
327  // Read all the records.
328  while (1) {
329    unsigned Code = Stream.ReadCode();
330    if (Code == bitc::END_BLOCK) {
331      if (Stream.ReadBlockEnd())
332        return Error("Error at end of PARAMATTR block");
333      return false;
334    }
335
336    if (Code == bitc::ENTER_SUBBLOCK) {
337      // No known subblocks, always skip them.
338      Stream.ReadSubBlockID();
339      if (Stream.SkipBlock())
340        return Error("Malformed block record");
341      continue;
342    }
343
344    if (Code == bitc::DEFINE_ABBREV) {
345      Stream.ReadAbbrevRecord();
346      continue;
347    }
348
349    // Read a record.
350    Record.clear();
351    switch (Stream.ReadRecord(Code, Record)) {
352    default:  // Default behavior: ignore.
353      break;
354    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
355      if (Record.size() & 1)
356        return Error("Invalid ENTRY record");
357
358      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
359        if (Record[i+1] != ParamAttr::None)
360          Attrs.push_back(ParamAttrsWithIndex::get(Record[i], Record[i+1]));
361      }
362
363      ParamAttrs.push_back(PAListPtr::get(Attrs.begin(), Attrs.end()));
364      Attrs.clear();
365      break;
366    }
367    }
368  }
369}
370
371
372bool BitcodeReader::ParseTypeTable() {
373  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
374    return Error("Malformed block record");
375
376  if (!TypeList.empty())
377    return Error("Multiple TYPE_BLOCKs found!");
378
379  SmallVector<uint64_t, 64> Record;
380  unsigned NumRecords = 0;
381
382  // Read all the records for this type table.
383  while (1) {
384    unsigned Code = Stream.ReadCode();
385    if (Code == bitc::END_BLOCK) {
386      if (NumRecords != TypeList.size())
387        return Error("Invalid type forward reference in TYPE_BLOCK");
388      if (Stream.ReadBlockEnd())
389        return Error("Error at end of type table block");
390      return false;
391    }
392
393    if (Code == bitc::ENTER_SUBBLOCK) {
394      // No known subblocks, always skip them.
395      Stream.ReadSubBlockID();
396      if (Stream.SkipBlock())
397        return Error("Malformed block record");
398      continue;
399    }
400
401    if (Code == bitc::DEFINE_ABBREV) {
402      Stream.ReadAbbrevRecord();
403      continue;
404    }
405
406    // Read a record.
407    Record.clear();
408    const Type *ResultTy = 0;
409    switch (Stream.ReadRecord(Code, Record)) {
410    default:  // Default behavior: unknown type.
411      ResultTy = 0;
412      break;
413    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
414      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
415      // type list.  This allows us to reserve space.
416      if (Record.size() < 1)
417        return Error("Invalid TYPE_CODE_NUMENTRY record");
418      TypeList.reserve(Record[0]);
419      continue;
420    case bitc::TYPE_CODE_VOID:      // VOID
421      ResultTy = Type::VoidTy;
422      break;
423    case bitc::TYPE_CODE_FLOAT:     // FLOAT
424      ResultTy = Type::FloatTy;
425      break;
426    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
427      ResultTy = Type::DoubleTy;
428      break;
429    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
430      ResultTy = Type::X86_FP80Ty;
431      break;
432    case bitc::TYPE_CODE_FP128:     // FP128
433      ResultTy = Type::FP128Ty;
434      break;
435    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
436      ResultTy = Type::PPC_FP128Ty;
437      break;
438    case bitc::TYPE_CODE_LABEL:     // LABEL
439      ResultTy = Type::LabelTy;
440      break;
441    case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
442      ResultTy = 0;
443      break;
444    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
445      if (Record.size() < 1)
446        return Error("Invalid Integer type record");
447
448      ResultTy = IntegerType::get(Record[0]);
449      break;
450    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
451                                    //          [pointee type, address space]
452      if (Record.size() < 1)
453        return Error("Invalid POINTER type record");
454      unsigned AddressSpace = 0;
455      if (Record.size() == 2)
456        AddressSpace = Record[1];
457      ResultTy = PointerType::get(getTypeByID(Record[0], true), AddressSpace);
458      break;
459    }
460    case bitc::TYPE_CODE_FUNCTION: {
461      // FIXME: attrid is dead, remove it in LLVM 3.0
462      // FUNCTION: [vararg, attrid, retty, paramty x N]
463      if (Record.size() < 3)
464        return Error("Invalid FUNCTION type record");
465      std::vector<const Type*> ArgTys;
466      for (unsigned i = 3, e = Record.size(); i != e; ++i)
467        ArgTys.push_back(getTypeByID(Record[i], true));
468
469      ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
470                                   Record[0]);
471      break;
472    }
473    case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
474      if (Record.size() < 1)
475        return Error("Invalid STRUCT type record");
476      std::vector<const Type*> EltTys;
477      for (unsigned i = 1, e = Record.size(); i != e; ++i)
478        EltTys.push_back(getTypeByID(Record[i], true));
479      ResultTy = StructType::get(EltTys, Record[0]);
480      break;
481    }
482    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
483      if (Record.size() < 2)
484        return Error("Invalid ARRAY type record");
485      ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
486      break;
487    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
488      if (Record.size() < 2)
489        return Error("Invalid VECTOR type record");
490      ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
491      break;
492    }
493
494    if (NumRecords == TypeList.size()) {
495      // If this is a new type slot, just append it.
496      TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
497      ++NumRecords;
498    } else if (ResultTy == 0) {
499      // Otherwise, this was forward referenced, so an opaque type was created,
500      // but the result type is actually just an opaque.  Leave the one we
501      // created previously.
502      ++NumRecords;
503    } else {
504      // Otherwise, this was forward referenced, so an opaque type was created.
505      // Resolve the opaque type to the real type now.
506      assert(NumRecords < TypeList.size() && "Typelist imbalance");
507      const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
508
509      // Don't directly push the new type on the Tab. Instead we want to replace
510      // the opaque type we previously inserted with the new concrete value. The
511      // refinement from the abstract (opaque) type to the new type causes all
512      // uses of the abstract type to use the concrete type (NewTy). This will
513      // also cause the opaque type to be deleted.
514      const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
515
516      // This should have replaced the old opaque type with the new type in the
517      // value table... or with a preexisting type that was already in the
518      // system.  Let's just make sure it did.
519      assert(TypeList[NumRecords-1].get() != OldTy &&
520             "refineAbstractType didn't work!");
521    }
522  }
523}
524
525
526bool BitcodeReader::ParseTypeSymbolTable() {
527  if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
528    return Error("Malformed block record");
529
530  SmallVector<uint64_t, 64> Record;
531
532  // Read all the records for this type table.
533  std::string TypeName;
534  while (1) {
535    unsigned Code = Stream.ReadCode();
536    if (Code == bitc::END_BLOCK) {
537      if (Stream.ReadBlockEnd())
538        return Error("Error at end of type symbol table block");
539      return false;
540    }
541
542    if (Code == bitc::ENTER_SUBBLOCK) {
543      // No known subblocks, always skip them.
544      Stream.ReadSubBlockID();
545      if (Stream.SkipBlock())
546        return Error("Malformed block record");
547      continue;
548    }
549
550    if (Code == bitc::DEFINE_ABBREV) {
551      Stream.ReadAbbrevRecord();
552      continue;
553    }
554
555    // Read a record.
556    Record.clear();
557    switch (Stream.ReadRecord(Code, Record)) {
558    default:  // Default behavior: unknown type.
559      break;
560    case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
561      if (ConvertToString(Record, 1, TypeName))
562        return Error("Invalid TST_ENTRY record");
563      unsigned TypeID = Record[0];
564      if (TypeID >= TypeList.size())
565        return Error("Invalid Type ID in TST_ENTRY record");
566
567      TheModule->addTypeName(TypeName, TypeList[TypeID].get());
568      TypeName.clear();
569      break;
570    }
571  }
572}
573
574bool BitcodeReader::ParseValueSymbolTable() {
575  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
576    return Error("Malformed block record");
577
578  SmallVector<uint64_t, 64> Record;
579
580  // Read all the records for this value table.
581  SmallString<128> ValueName;
582  while (1) {
583    unsigned Code = Stream.ReadCode();
584    if (Code == bitc::END_BLOCK) {
585      if (Stream.ReadBlockEnd())
586        return Error("Error at end of value symbol table block");
587      return false;
588    }
589    if (Code == bitc::ENTER_SUBBLOCK) {
590      // No known subblocks, always skip them.
591      Stream.ReadSubBlockID();
592      if (Stream.SkipBlock())
593        return Error("Malformed block record");
594      continue;
595    }
596
597    if (Code == bitc::DEFINE_ABBREV) {
598      Stream.ReadAbbrevRecord();
599      continue;
600    }
601
602    // Read a record.
603    Record.clear();
604    switch (Stream.ReadRecord(Code, Record)) {
605    default:  // Default behavior: unknown type.
606      break;
607    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
608      if (ConvertToString(Record, 1, ValueName))
609        return Error("Invalid TST_ENTRY record");
610      unsigned ValueID = Record[0];
611      if (ValueID >= ValueList.size())
612        return Error("Invalid Value ID in VST_ENTRY record");
613      Value *V = ValueList[ValueID];
614
615      V->setName(&ValueName[0], ValueName.size());
616      ValueName.clear();
617      break;
618    }
619    case bitc::VST_CODE_BBENTRY: {
620      if (ConvertToString(Record, 1, ValueName))
621        return Error("Invalid VST_BBENTRY record");
622      BasicBlock *BB = getBasicBlock(Record[0]);
623      if (BB == 0)
624        return Error("Invalid BB ID in VST_BBENTRY record");
625
626      BB->setName(&ValueName[0], ValueName.size());
627      ValueName.clear();
628      break;
629    }
630    }
631  }
632}
633
634/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
635/// the LSB for dense VBR encoding.
636static uint64_t DecodeSignRotatedValue(uint64_t V) {
637  if ((V & 1) == 0)
638    return V >> 1;
639  if (V != 1)
640    return -(V >> 1);
641  // There is no such thing as -0 with integers.  "-0" really means MININT.
642  return 1ULL << 63;
643}
644
645/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
646/// values and aliases that we can.
647bool BitcodeReader::ResolveGlobalAndAliasInits() {
648  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
649  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
650
651  GlobalInitWorklist.swap(GlobalInits);
652  AliasInitWorklist.swap(AliasInits);
653
654  while (!GlobalInitWorklist.empty()) {
655    unsigned ValID = GlobalInitWorklist.back().second;
656    if (ValID >= ValueList.size()) {
657      // Not ready to resolve this yet, it requires something later in the file.
658      GlobalInits.push_back(GlobalInitWorklist.back());
659    } else {
660      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
661        GlobalInitWorklist.back().first->setInitializer(C);
662      else
663        return Error("Global variable initializer is not a constant!");
664    }
665    GlobalInitWorklist.pop_back();
666  }
667
668  while (!AliasInitWorklist.empty()) {
669    unsigned ValID = AliasInitWorklist.back().second;
670    if (ValID >= ValueList.size()) {
671      AliasInits.push_back(AliasInitWorklist.back());
672    } else {
673      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
674        AliasInitWorklist.back().first->setAliasee(C);
675      else
676        return Error("Alias initializer is not a constant!");
677    }
678    AliasInitWorklist.pop_back();
679  }
680  return false;
681}
682
683
684bool BitcodeReader::ParseConstants() {
685  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
686    return Error("Malformed block record");
687
688  SmallVector<uint64_t, 64> Record;
689
690  // Read all the records for this value table.
691  const Type *CurTy = Type::Int32Ty;
692  unsigned NextCstNo = ValueList.size();
693  while (1) {
694    unsigned Code = Stream.ReadCode();
695    if (Code == bitc::END_BLOCK)
696      break;
697
698    if (Code == bitc::ENTER_SUBBLOCK) {
699      // No known subblocks, always skip them.
700      Stream.ReadSubBlockID();
701      if (Stream.SkipBlock())
702        return Error("Malformed block record");
703      continue;
704    }
705
706    if (Code == bitc::DEFINE_ABBREV) {
707      Stream.ReadAbbrevRecord();
708      continue;
709    }
710
711    // Read a record.
712    Record.clear();
713    Value *V = 0;
714    switch (Stream.ReadRecord(Code, Record)) {
715    default:  // Default behavior: unknown constant
716    case bitc::CST_CODE_UNDEF:     // UNDEF
717      V = UndefValue::get(CurTy);
718      break;
719    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
720      if (Record.empty())
721        return Error("Malformed CST_SETTYPE record");
722      if (Record[0] >= TypeList.size())
723        return Error("Invalid Type ID in CST_SETTYPE record");
724      CurTy = TypeList[Record[0]];
725      continue;  // Skip the ValueList manipulation.
726    case bitc::CST_CODE_NULL:      // NULL
727      V = Constant::getNullValue(CurTy);
728      break;
729    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
730      if (!isa<IntegerType>(CurTy) || Record.empty())
731        return Error("Invalid CST_INTEGER record");
732      V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
733      break;
734    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
735      if (!isa<IntegerType>(CurTy) || Record.empty())
736        return Error("Invalid WIDE_INTEGER record");
737
738      unsigned NumWords = Record.size();
739      SmallVector<uint64_t, 8> Words;
740      Words.resize(NumWords);
741      for (unsigned i = 0; i != NumWords; ++i)
742        Words[i] = DecodeSignRotatedValue(Record[i]);
743      V = ConstantInt::get(APInt(cast<IntegerType>(CurTy)->getBitWidth(),
744                                 NumWords, &Words[0]));
745      break;
746    }
747    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
748      if (Record.empty())
749        return Error("Invalid FLOAT record");
750      if (CurTy == Type::FloatTy)
751        V = ConstantFP::get(APFloat(APInt(32, (uint32_t)Record[0])));
752      else if (CurTy == Type::DoubleTy)
753        V = ConstantFP::get(APFloat(APInt(64, Record[0])));
754      else if (CurTy == Type::X86_FP80Ty)
755        V = ConstantFP::get(APFloat(APInt(80, 2, &Record[0])));
756      else if (CurTy == Type::FP128Ty)
757        V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0]), true));
758      else if (CurTy == Type::PPC_FP128Ty)
759        V = ConstantFP::get(APFloat(APInt(128, 2, &Record[0])));
760      else
761        V = UndefValue::get(CurTy);
762      break;
763    }
764
765    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
766      if (Record.empty())
767        return Error("Invalid CST_AGGREGATE record");
768
769      unsigned Size = Record.size();
770      std::vector<Constant*> Elts;
771
772      if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
773        for (unsigned i = 0; i != Size; ++i)
774          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
775                                                     STy->getElementType(i)));
776        V = ConstantStruct::get(STy, Elts);
777      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
778        const Type *EltTy = ATy->getElementType();
779        for (unsigned i = 0; i != Size; ++i)
780          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
781        V = ConstantArray::get(ATy, Elts);
782      } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
783        const Type *EltTy = VTy->getElementType();
784        for (unsigned i = 0; i != Size; ++i)
785          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
786        V = ConstantVector::get(Elts);
787      } else {
788        V = UndefValue::get(CurTy);
789      }
790      break;
791    }
792    case bitc::CST_CODE_STRING: { // STRING: [values]
793      if (Record.empty())
794        return Error("Invalid CST_AGGREGATE record");
795
796      const ArrayType *ATy = cast<ArrayType>(CurTy);
797      const Type *EltTy = ATy->getElementType();
798
799      unsigned Size = Record.size();
800      std::vector<Constant*> Elts;
801      for (unsigned i = 0; i != Size; ++i)
802        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
803      V = ConstantArray::get(ATy, Elts);
804      break;
805    }
806    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
807      if (Record.empty())
808        return Error("Invalid CST_AGGREGATE record");
809
810      const ArrayType *ATy = cast<ArrayType>(CurTy);
811      const Type *EltTy = ATy->getElementType();
812
813      unsigned Size = Record.size();
814      std::vector<Constant*> Elts;
815      for (unsigned i = 0; i != Size; ++i)
816        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
817      Elts.push_back(Constant::getNullValue(EltTy));
818      V = ConstantArray::get(ATy, Elts);
819      break;
820    }
821    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
822      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
823      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
824      if (Opc < 0) {
825        V = UndefValue::get(CurTy);  // Unknown binop.
826      } else {
827        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
828        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
829        V = ConstantExpr::get(Opc, LHS, RHS);
830      }
831      break;
832    }
833    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
834      if (Record.size() < 3) return Error("Invalid CE_CAST record");
835      int Opc = GetDecodedCastOpcode(Record[0]);
836      if (Opc < 0) {
837        V = UndefValue::get(CurTy);  // Unknown cast.
838      } else {
839        const Type *OpTy = getTypeByID(Record[1]);
840        if (!OpTy) return Error("Invalid CE_CAST record");
841        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
842        V = ConstantExpr::getCast(Opc, Op, CurTy);
843      }
844      break;
845    }
846    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
847      if (Record.size() & 1) return Error("Invalid CE_GEP record");
848      SmallVector<Constant*, 16> Elts;
849      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
850        const Type *ElTy = getTypeByID(Record[i]);
851        if (!ElTy) return Error("Invalid CE_GEP record");
852        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
853      }
854      V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1], Elts.size()-1);
855      break;
856    }
857    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
858      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
859      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
860                                                              Type::Int1Ty),
861                                  ValueList.getConstantFwdRef(Record[1],CurTy),
862                                  ValueList.getConstantFwdRef(Record[2],CurTy));
863      break;
864    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
865      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
866      const VectorType *OpTy =
867        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
868      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
869      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
870      Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
871                                                  OpTy->getElementType());
872      V = ConstantExpr::getExtractElement(Op0, Op1);
873      break;
874    }
875    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
876      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
877      if (Record.size() < 3 || OpTy == 0)
878        return Error("Invalid CE_INSERTELT record");
879      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
880      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
881                                                  OpTy->getElementType());
882      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
883      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
884      break;
885    }
886    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
887      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
888      if (Record.size() < 3 || OpTy == 0)
889        return Error("Invalid CE_INSERTELT record");
890      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
891      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
892      const Type *ShufTy=VectorType::get(Type::Int32Ty, OpTy->getNumElements());
893      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
894      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
895      break;
896    }
897    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
898      if (Record.size() < 4) return Error("Invalid CE_CMP record");
899      const Type *OpTy = getTypeByID(Record[0]);
900      if (OpTy == 0) return Error("Invalid CE_CMP record");
901      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
902      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
903
904      if (OpTy->isFloatingPoint())
905        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
906      else if (!isa<VectorType>(OpTy))
907        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
908      else if (OpTy->isFPOrFPVector())
909        V = ConstantExpr::getVFCmp(Record[3], Op0, Op1);
910      else
911        V = ConstantExpr::getVICmp(Record[3], Op0, Op1);
912      break;
913    }
914    case bitc::CST_CODE_INLINEASM: {
915      if (Record.size() < 2) return Error("Invalid INLINEASM record");
916      std::string AsmStr, ConstrStr;
917      bool HasSideEffects = Record[0];
918      unsigned AsmStrSize = Record[1];
919      if (2+AsmStrSize >= Record.size())
920        return Error("Invalid INLINEASM record");
921      unsigned ConstStrSize = Record[2+AsmStrSize];
922      if (3+AsmStrSize+ConstStrSize > Record.size())
923        return Error("Invalid INLINEASM record");
924
925      for (unsigned i = 0; i != AsmStrSize; ++i)
926        AsmStr += (char)Record[2+i];
927      for (unsigned i = 0; i != ConstStrSize; ++i)
928        ConstrStr += (char)Record[3+AsmStrSize+i];
929      const PointerType *PTy = cast<PointerType>(CurTy);
930      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
931                         AsmStr, ConstrStr, HasSideEffects);
932      break;
933    }
934    }
935
936    ValueList.AssignValue(V, NextCstNo);
937    ++NextCstNo;
938  }
939
940  if (NextCstNo != ValueList.size())
941    return Error("Invalid constant reference!");
942
943  if (Stream.ReadBlockEnd())
944    return Error("Error at end of constants block");
945
946  // Once all the constants have been read, go through and resolve forward
947  // references.
948  ValueList.ResolveConstantForwardRefs();
949  return false;
950}
951
952/// RememberAndSkipFunctionBody - When we see the block for a function body,
953/// remember where it is and then skip it.  This lets us lazily deserialize the
954/// functions.
955bool BitcodeReader::RememberAndSkipFunctionBody() {
956  // Get the function we are talking about.
957  if (FunctionsWithBodies.empty())
958    return Error("Insufficient function protos");
959
960  Function *Fn = FunctionsWithBodies.back();
961  FunctionsWithBodies.pop_back();
962
963  // Save the current stream state.
964  uint64_t CurBit = Stream.GetCurrentBitNo();
965  DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
966
967  // Set the functions linkage to GhostLinkage so we know it is lazily
968  // deserialized.
969  Fn->setLinkage(GlobalValue::GhostLinkage);
970
971  // Skip over the function block for now.
972  if (Stream.SkipBlock())
973    return Error("Malformed block record");
974  return false;
975}
976
977bool BitcodeReader::ParseModule(const std::string &ModuleID) {
978  // Reject multiple MODULE_BLOCK's in a single bitstream.
979  if (TheModule)
980    return Error("Multiple MODULE_BLOCKs in same stream");
981
982  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
983    return Error("Malformed block record");
984
985  // Otherwise, create the module.
986  TheModule = new Module(ModuleID);
987
988  SmallVector<uint64_t, 64> Record;
989  std::vector<std::string> SectionTable;
990  std::vector<std::string> GCTable;
991
992  // Read all the records for this module.
993  while (!Stream.AtEndOfStream()) {
994    unsigned Code = Stream.ReadCode();
995    if (Code == bitc::END_BLOCK) {
996      if (Stream.ReadBlockEnd())
997        return Error("Error at end of module block");
998
999      // Patch the initializers for globals and aliases up.
1000      ResolveGlobalAndAliasInits();
1001      if (!GlobalInits.empty() || !AliasInits.empty())
1002        return Error("Malformed global initializer set");
1003      if (!FunctionsWithBodies.empty())
1004        return Error("Too few function bodies found");
1005
1006      // Look for intrinsic functions which need to be upgraded at some point
1007      for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1008           FI != FE; ++FI) {
1009        Function* NewFn;
1010        if (UpgradeIntrinsicFunction(FI, NewFn))
1011          UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1012      }
1013
1014      // Force deallocation of memory for these vectors to favor the client that
1015      // want lazy deserialization.
1016      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1017      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1018      std::vector<Function*>().swap(FunctionsWithBodies);
1019      return false;
1020    }
1021
1022    if (Code == bitc::ENTER_SUBBLOCK) {
1023      switch (Stream.ReadSubBlockID()) {
1024      default:  // Skip unknown content.
1025        if (Stream.SkipBlock())
1026          return Error("Malformed block record");
1027        break;
1028      case bitc::BLOCKINFO_BLOCK_ID:
1029        if (Stream.ReadBlockInfoBlock())
1030          return Error("Malformed BlockInfoBlock");
1031        break;
1032      case bitc::PARAMATTR_BLOCK_ID:
1033        if (ParseParamAttrBlock())
1034          return true;
1035        break;
1036      case bitc::TYPE_BLOCK_ID:
1037        if (ParseTypeTable())
1038          return true;
1039        break;
1040      case bitc::TYPE_SYMTAB_BLOCK_ID:
1041        if (ParseTypeSymbolTable())
1042          return true;
1043        break;
1044      case bitc::VALUE_SYMTAB_BLOCK_ID:
1045        if (ParseValueSymbolTable())
1046          return true;
1047        break;
1048      case bitc::CONSTANTS_BLOCK_ID:
1049        if (ParseConstants() || ResolveGlobalAndAliasInits())
1050          return true;
1051        break;
1052      case bitc::FUNCTION_BLOCK_ID:
1053        // If this is the first function body we've seen, reverse the
1054        // FunctionsWithBodies list.
1055        if (!HasReversedFunctionsWithBodies) {
1056          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1057          HasReversedFunctionsWithBodies = true;
1058        }
1059
1060        if (RememberAndSkipFunctionBody())
1061          return true;
1062        break;
1063      }
1064      continue;
1065    }
1066
1067    if (Code == bitc::DEFINE_ABBREV) {
1068      Stream.ReadAbbrevRecord();
1069      continue;
1070    }
1071
1072    // Read a record.
1073    switch (Stream.ReadRecord(Code, Record)) {
1074    default: break;  // Default behavior, ignore unknown content.
1075    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1076      if (Record.size() < 1)
1077        return Error("Malformed MODULE_CODE_VERSION");
1078      // Only version #0 is supported so far.
1079      if (Record[0] != 0)
1080        return Error("Unknown bitstream version!");
1081      break;
1082    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1083      std::string S;
1084      if (ConvertToString(Record, 0, S))
1085        return Error("Invalid MODULE_CODE_TRIPLE record");
1086      TheModule->setTargetTriple(S);
1087      break;
1088    }
1089    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1090      std::string S;
1091      if (ConvertToString(Record, 0, S))
1092        return Error("Invalid MODULE_CODE_DATALAYOUT record");
1093      TheModule->setDataLayout(S);
1094      break;
1095    }
1096    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1097      std::string S;
1098      if (ConvertToString(Record, 0, S))
1099        return Error("Invalid MODULE_CODE_ASM record");
1100      TheModule->setModuleInlineAsm(S);
1101      break;
1102    }
1103    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1104      std::string S;
1105      if (ConvertToString(Record, 0, S))
1106        return Error("Invalid MODULE_CODE_DEPLIB record");
1107      TheModule->addLibrary(S);
1108      break;
1109    }
1110    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1111      std::string S;
1112      if (ConvertToString(Record, 0, S))
1113        return Error("Invalid MODULE_CODE_SECTIONNAME record");
1114      SectionTable.push_back(S);
1115      break;
1116    }
1117    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1118      std::string S;
1119      if (ConvertToString(Record, 0, S))
1120        return Error("Invalid MODULE_CODE_GCNAME record");
1121      GCTable.push_back(S);
1122      break;
1123    }
1124    // GLOBALVAR: [pointer type, isconst, initid,
1125    //             linkage, alignment, section, visibility, threadlocal]
1126    case bitc::MODULE_CODE_GLOBALVAR: {
1127      if (Record.size() < 6)
1128        return Error("Invalid MODULE_CODE_GLOBALVAR record");
1129      const Type *Ty = getTypeByID(Record[0]);
1130      if (!isa<PointerType>(Ty))
1131        return Error("Global not a pointer type!");
1132      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1133      Ty = cast<PointerType>(Ty)->getElementType();
1134
1135      bool isConstant = Record[1];
1136      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1137      unsigned Alignment = (1 << Record[4]) >> 1;
1138      std::string Section;
1139      if (Record[5]) {
1140        if (Record[5]-1 >= SectionTable.size())
1141          return Error("Invalid section ID");
1142        Section = SectionTable[Record[5]-1];
1143      }
1144      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1145      if (Record.size() > 6)
1146        Visibility = GetDecodedVisibility(Record[6]);
1147      bool isThreadLocal = false;
1148      if (Record.size() > 7)
1149        isThreadLocal = Record[7];
1150
1151      GlobalVariable *NewGV =
1152        new GlobalVariable(Ty, isConstant, Linkage, 0, "", TheModule,
1153                           isThreadLocal, AddressSpace);
1154      NewGV->setAlignment(Alignment);
1155      if (!Section.empty())
1156        NewGV->setSection(Section);
1157      NewGV->setVisibility(Visibility);
1158      NewGV->setThreadLocal(isThreadLocal);
1159
1160      ValueList.push_back(NewGV);
1161
1162      // Remember which value to use for the global initializer.
1163      if (unsigned InitID = Record[2])
1164        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1165      break;
1166    }
1167    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1168    //             alignment, section, visibility, gc]
1169    case bitc::MODULE_CODE_FUNCTION: {
1170      if (Record.size() < 8)
1171        return Error("Invalid MODULE_CODE_FUNCTION record");
1172      const Type *Ty = getTypeByID(Record[0]);
1173      if (!isa<PointerType>(Ty))
1174        return Error("Function not a pointer type!");
1175      const FunctionType *FTy =
1176        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1177      if (!FTy)
1178        return Error("Function not a pointer to function type!");
1179
1180      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1181                                        "", TheModule);
1182
1183      Func->setCallingConv(Record[1]);
1184      bool isProto = Record[2];
1185      Func->setLinkage(GetDecodedLinkage(Record[3]));
1186      Func->setParamAttrs(getParamAttrs(Record[4]));
1187
1188      Func->setAlignment((1 << Record[5]) >> 1);
1189      if (Record[6]) {
1190        if (Record[6]-1 >= SectionTable.size())
1191          return Error("Invalid section ID");
1192        Func->setSection(SectionTable[Record[6]-1]);
1193      }
1194      Func->setVisibility(GetDecodedVisibility(Record[7]));
1195      if (Record.size() > 8 && Record[8]) {
1196        if (Record[8]-1 > GCTable.size())
1197          return Error("Invalid GC ID");
1198        Func->setGC(GCTable[Record[8]-1].c_str());
1199      }
1200
1201      ValueList.push_back(Func);
1202
1203      // If this is a function with a body, remember the prototype we are
1204      // creating now, so that we can match up the body with them later.
1205      if (!isProto)
1206        FunctionsWithBodies.push_back(Func);
1207      break;
1208    }
1209    // ALIAS: [alias type, aliasee val#, linkage]
1210    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1211    case bitc::MODULE_CODE_ALIAS: {
1212      if (Record.size() < 3)
1213        return Error("Invalid MODULE_ALIAS record");
1214      const Type *Ty = getTypeByID(Record[0]);
1215      if (!isa<PointerType>(Ty))
1216        return Error("Function not a pointer type!");
1217
1218      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1219                                           "", 0, TheModule);
1220      // Old bitcode files didn't have visibility field.
1221      if (Record.size() > 3)
1222        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1223      ValueList.push_back(NewGA);
1224      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1225      break;
1226    }
1227    /// MODULE_CODE_PURGEVALS: [numvals]
1228    case bitc::MODULE_CODE_PURGEVALS:
1229      // Trim down the value list to the specified size.
1230      if (Record.size() < 1 || Record[0] > ValueList.size())
1231        return Error("Invalid MODULE_PURGEVALS record");
1232      ValueList.shrinkTo(Record[0]);
1233      break;
1234    }
1235    Record.clear();
1236  }
1237
1238  return Error("Premature end of bitstream");
1239}
1240
1241/// SkipWrapperHeader - Some systems wrap bc files with a special header for
1242/// padding or other reasons.  The format of this header is:
1243///
1244/// struct bc_header {
1245///   uint32_t Magic;         // 0x0B17C0DE
1246///   uint32_t Version;       // Version, currently always 0.
1247///   uint32_t BitcodeOffset; // Offset to traditional bitcode file.
1248///   uint32_t BitcodeSize;   // Size of traditional bitcode file.
1249///   ... potentially other gunk ...
1250/// };
1251///
1252/// This function is called when we find a file with a matching magic number.
1253/// In this case, skip down to the subsection of the file that is actually a BC
1254/// file.
1255static bool SkipWrapperHeader(unsigned char *&BufPtr, unsigned char *&BufEnd) {
1256  enum {
1257    KnownHeaderSize = 4*4,  // Size of header we read.
1258    OffsetField = 2*4,      // Offset in bytes to Offset field.
1259    SizeField = 3*4         // Offset in bytes to Size field.
1260  };
1261
1262
1263  // Must contain the header!
1264  if (BufEnd-BufPtr < KnownHeaderSize) return true;
1265
1266  unsigned Offset = ( BufPtr[OffsetField  ]        |
1267                     (BufPtr[OffsetField+1] << 8)  |
1268                     (BufPtr[OffsetField+2] << 16) |
1269                     (BufPtr[OffsetField+3] << 24));
1270  unsigned Size   = ( BufPtr[SizeField    ]        |
1271                     (BufPtr[SizeField  +1] << 8)  |
1272                     (BufPtr[SizeField  +2] << 16) |
1273                     (BufPtr[SizeField  +3] << 24));
1274
1275  // Verify that Offset+Size fits in the file.
1276  if (Offset+Size > unsigned(BufEnd-BufPtr))
1277    return true;
1278  BufPtr += Offset;
1279  BufEnd = BufPtr+Size;
1280  return false;
1281}
1282
1283bool BitcodeReader::ParseBitcode() {
1284  TheModule = 0;
1285
1286  if (Buffer->getBufferSize() & 3)
1287    return Error("Bitcode stream should be a multiple of 4 bytes in length");
1288
1289  unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1290  unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1291
1292  // If we have a wrapper header, parse it and ignore the non-bc file contents.
1293  // The magic number is 0x0B17C0DE stored in little endian.
1294  if (BufPtr != BufEnd && BufPtr[0] == 0xDE && BufPtr[1] == 0xC0 &&
1295      BufPtr[2] == 0x17 && BufPtr[3] == 0x0B)
1296    if (SkipWrapperHeader(BufPtr, BufEnd))
1297      return Error("Invalid bitcode wrapper header");
1298
1299  Stream.init(BufPtr, BufEnd);
1300
1301  // Sniff for the signature.
1302  if (Stream.Read(8) != 'B' ||
1303      Stream.Read(8) != 'C' ||
1304      Stream.Read(4) != 0x0 ||
1305      Stream.Read(4) != 0xC ||
1306      Stream.Read(4) != 0xE ||
1307      Stream.Read(4) != 0xD)
1308    return Error("Invalid bitcode signature");
1309
1310  // We expect a number of well-defined blocks, though we don't necessarily
1311  // need to understand them all.
1312  while (!Stream.AtEndOfStream()) {
1313    unsigned Code = Stream.ReadCode();
1314
1315    if (Code != bitc::ENTER_SUBBLOCK)
1316      return Error("Invalid record at top-level");
1317
1318    unsigned BlockID = Stream.ReadSubBlockID();
1319
1320    // We only know the MODULE subblock ID.
1321    switch (BlockID) {
1322    case bitc::BLOCKINFO_BLOCK_ID:
1323      if (Stream.ReadBlockInfoBlock())
1324        return Error("Malformed BlockInfoBlock");
1325      break;
1326    case bitc::MODULE_BLOCK_ID:
1327      if (ParseModule(Buffer->getBufferIdentifier()))
1328        return true;
1329      break;
1330    default:
1331      if (Stream.SkipBlock())
1332        return Error("Malformed block record");
1333      break;
1334    }
1335  }
1336
1337  return false;
1338}
1339
1340
1341/// ParseFunctionBody - Lazily parse the specified function body block.
1342bool BitcodeReader::ParseFunctionBody(Function *F) {
1343  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1344    return Error("Malformed block record");
1345
1346  unsigned ModuleValueListSize = ValueList.size();
1347
1348  // Add all the function arguments to the value table.
1349  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1350    ValueList.push_back(I);
1351
1352  unsigned NextValueNo = ValueList.size();
1353  BasicBlock *CurBB = 0;
1354  unsigned CurBBNo = 0;
1355
1356  // Read all the records.
1357  SmallVector<uint64_t, 64> Record;
1358  while (1) {
1359    unsigned Code = Stream.ReadCode();
1360    if (Code == bitc::END_BLOCK) {
1361      if (Stream.ReadBlockEnd())
1362        return Error("Error at end of function block");
1363      break;
1364    }
1365
1366    if (Code == bitc::ENTER_SUBBLOCK) {
1367      switch (Stream.ReadSubBlockID()) {
1368      default:  // Skip unknown content.
1369        if (Stream.SkipBlock())
1370          return Error("Malformed block record");
1371        break;
1372      case bitc::CONSTANTS_BLOCK_ID:
1373        if (ParseConstants()) return true;
1374        NextValueNo = ValueList.size();
1375        break;
1376      case bitc::VALUE_SYMTAB_BLOCK_ID:
1377        if (ParseValueSymbolTable()) return true;
1378        break;
1379      }
1380      continue;
1381    }
1382
1383    if (Code == bitc::DEFINE_ABBREV) {
1384      Stream.ReadAbbrevRecord();
1385      continue;
1386    }
1387
1388    // Read a record.
1389    Record.clear();
1390    Instruction *I = 0;
1391    switch (Stream.ReadRecord(Code, Record)) {
1392    default: // Default behavior: reject
1393      return Error("Unknown instruction");
1394    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1395      if (Record.size() < 1 || Record[0] == 0)
1396        return Error("Invalid DECLAREBLOCKS record");
1397      // Create all the basic blocks for the function.
1398      FunctionBBs.resize(Record[0]);
1399      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1400        FunctionBBs[i] = BasicBlock::Create("", F);
1401      CurBB = FunctionBBs[0];
1402      continue;
1403
1404    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1405      unsigned OpNum = 0;
1406      Value *LHS, *RHS;
1407      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1408          getValue(Record, OpNum, LHS->getType(), RHS) ||
1409          OpNum+1 != Record.size())
1410        return Error("Invalid BINOP record");
1411
1412      int Opc = GetDecodedBinaryOpcode(Record[OpNum], LHS->getType());
1413      if (Opc == -1) return Error("Invalid BINOP record");
1414      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1415      break;
1416    }
1417    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1418      unsigned OpNum = 0;
1419      Value *Op;
1420      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1421          OpNum+2 != Record.size())
1422        return Error("Invalid CAST record");
1423
1424      const Type *ResTy = getTypeByID(Record[OpNum]);
1425      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1426      if (Opc == -1 || ResTy == 0)
1427        return Error("Invalid CAST record");
1428      I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1429      break;
1430    }
1431    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1432      unsigned OpNum = 0;
1433      Value *BasePtr;
1434      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1435        return Error("Invalid GEP record");
1436
1437      SmallVector<Value*, 16> GEPIdx;
1438      while (OpNum != Record.size()) {
1439        Value *Op;
1440        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1441          return Error("Invalid GEP record");
1442        GEPIdx.push_back(Op);
1443      }
1444
1445      I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1446      break;
1447    }
1448
1449    case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1450                                       // EXTRACTVAL: [opty, opval, n x indices]
1451      unsigned OpNum = 0;
1452      Value *Agg;
1453      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1454        return Error("Invalid EXTRACTVAL record");
1455
1456      SmallVector<unsigned, 4> EXTRACTVALIdx;
1457      for (unsigned RecSize = Record.size();
1458           OpNum != RecSize; ++OpNum) {
1459        uint64_t Index = Record[OpNum];
1460        if ((unsigned)Index != Index)
1461          return Error("Invalid EXTRACTVAL index");
1462        EXTRACTVALIdx.push_back((unsigned)Index);
1463      }
1464
1465      I = ExtractValueInst::Create(Agg,
1466                                   EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1467      break;
1468    }
1469
1470    case bitc::FUNC_CODE_INST_INSERTVAL: {
1471                           // INSERTVAL: [opty, opval, opty, opval, n x indices]
1472      unsigned OpNum = 0;
1473      Value *Agg;
1474      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1475        return Error("Invalid INSERTVAL record");
1476      Value *Val;
1477      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1478        return Error("Invalid INSERTVAL record");
1479
1480      SmallVector<unsigned, 4> INSERTVALIdx;
1481      for (unsigned RecSize = Record.size();
1482           OpNum != RecSize; ++OpNum) {
1483        uint64_t Index = Record[OpNum];
1484        if ((unsigned)Index != Index)
1485          return Error("Invalid INSERTVAL index");
1486        INSERTVALIdx.push_back((unsigned)Index);
1487      }
1488
1489      I = InsertValueInst::Create(Agg, Val,
1490                                  INSERTVALIdx.begin(), INSERTVALIdx.end());
1491      break;
1492    }
1493
1494    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1495      unsigned OpNum = 0;
1496      Value *TrueVal, *FalseVal, *Cond;
1497      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1498          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1499          getValue(Record, OpNum, Type::Int1Ty, Cond))
1500        return Error("Invalid SELECT record");
1501
1502      I = SelectInst::Create(Cond, TrueVal, FalseVal);
1503      break;
1504    }
1505
1506    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1507      unsigned OpNum = 0;
1508      Value *Vec, *Idx;
1509      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1510          getValue(Record, OpNum, Type::Int32Ty, Idx))
1511        return Error("Invalid EXTRACTELT record");
1512      I = new ExtractElementInst(Vec, Idx);
1513      break;
1514    }
1515
1516    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1517      unsigned OpNum = 0;
1518      Value *Vec, *Elt, *Idx;
1519      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1520          getValue(Record, OpNum,
1521                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1522          getValue(Record, OpNum, Type::Int32Ty, Idx))
1523        return Error("Invalid INSERTELT record");
1524      I = InsertElementInst::Create(Vec, Elt, Idx);
1525      break;
1526    }
1527
1528    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1529      unsigned OpNum = 0;
1530      Value *Vec1, *Vec2, *Mask;
1531      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1532          getValue(Record, OpNum, Vec1->getType(), Vec2))
1533        return Error("Invalid SHUFFLEVEC record");
1534
1535      const Type *MaskTy =
1536        VectorType::get(Type::Int32Ty,
1537                        cast<VectorType>(Vec1->getType())->getNumElements());
1538
1539      if (getValue(Record, OpNum, MaskTy, Mask))
1540        return Error("Invalid SHUFFLEVEC record");
1541      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1542      break;
1543    }
1544
1545    case bitc::FUNC_CODE_INST_CMP: { // CMP: [opty, opval, opval, pred]
1546      unsigned OpNum = 0;
1547      Value *LHS, *RHS;
1548      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1549          getValue(Record, OpNum, LHS->getType(), RHS) ||
1550          OpNum+1 != Record.size())
1551        return Error("Invalid CMP record");
1552
1553      if (LHS->getType()->isFloatingPoint())
1554        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1555      else if (!isa<VectorType>(LHS->getType()))
1556        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1557      else if (LHS->getType()->isFPOrFPVector())
1558        I = new VFCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1559      else
1560        I = new VICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1561      break;
1562    }
1563    case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1564      if (Record.size() != 2)
1565        return Error("Invalid GETRESULT record");
1566      unsigned OpNum = 0;
1567      Value *Op;
1568      getValueTypePair(Record, OpNum, NextValueNo, Op);
1569      unsigned Index = Record[1];
1570      I = ExtractValueInst::Create(Op, Index);
1571      break;
1572    }
1573
1574    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1575      {
1576        unsigned Size = Record.size();
1577        if (Size == 0) {
1578          I = ReturnInst::Create();
1579          break;
1580        }
1581
1582        unsigned OpNum = 0;
1583        SmallVector<Value *,4> Vs;
1584        do {
1585          Value *Op = NULL;
1586          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1587            return Error("Invalid RET record");
1588          Vs.push_back(Op);
1589        } while(OpNum != Record.size());
1590
1591        const Type *ReturnType = F->getReturnType();
1592        if (Vs.size() > 1 ||
1593            (isa<StructType>(ReturnType) &&
1594             (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1595          Value *RV = UndefValue::get(ReturnType);
1596          for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1597            I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1598            CurBB->getInstList().push_back(I);
1599            ValueList.AssignValue(I, NextValueNo++);
1600            RV = I;
1601          }
1602          I = ReturnInst::Create(RV);
1603          break;
1604        }
1605
1606        I = ReturnInst::Create(Vs[0]);
1607        break;
1608      }
1609    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1610      if (Record.size() != 1 && Record.size() != 3)
1611        return Error("Invalid BR record");
1612      BasicBlock *TrueDest = getBasicBlock(Record[0]);
1613      if (TrueDest == 0)
1614        return Error("Invalid BR record");
1615
1616      if (Record.size() == 1)
1617        I = BranchInst::Create(TrueDest);
1618      else {
1619        BasicBlock *FalseDest = getBasicBlock(Record[1]);
1620        Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1621        if (FalseDest == 0 || Cond == 0)
1622          return Error("Invalid BR record");
1623        I = BranchInst::Create(TrueDest, FalseDest, Cond);
1624      }
1625      break;
1626    }
1627    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1628      if (Record.size() < 3 || (Record.size() & 1) == 0)
1629        return Error("Invalid SWITCH record");
1630      const Type *OpTy = getTypeByID(Record[0]);
1631      Value *Cond = getFnValueByID(Record[1], OpTy);
1632      BasicBlock *Default = getBasicBlock(Record[2]);
1633      if (OpTy == 0 || Cond == 0 || Default == 0)
1634        return Error("Invalid SWITCH record");
1635      unsigned NumCases = (Record.size()-3)/2;
1636      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1637      for (unsigned i = 0, e = NumCases; i != e; ++i) {
1638        ConstantInt *CaseVal =
1639          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1640        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1641        if (CaseVal == 0 || DestBB == 0) {
1642          delete SI;
1643          return Error("Invalid SWITCH record!");
1644        }
1645        SI->addCase(CaseVal, DestBB);
1646      }
1647      I = SI;
1648      break;
1649    }
1650
1651    case bitc::FUNC_CODE_INST_INVOKE: {
1652      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1653      if (Record.size() < 4) return Error("Invalid INVOKE record");
1654      PAListPtr PAL = getParamAttrs(Record[0]);
1655      unsigned CCInfo = Record[1];
1656      BasicBlock *NormalBB = getBasicBlock(Record[2]);
1657      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1658
1659      unsigned OpNum = 4;
1660      Value *Callee;
1661      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1662        return Error("Invalid INVOKE record");
1663
1664      const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1665      const FunctionType *FTy = !CalleeTy ? 0 :
1666        dyn_cast<FunctionType>(CalleeTy->getElementType());
1667
1668      // Check that the right number of fixed parameters are here.
1669      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1670          Record.size() < OpNum+FTy->getNumParams())
1671        return Error("Invalid INVOKE record");
1672
1673      SmallVector<Value*, 16> Ops;
1674      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1675        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1676        if (Ops.back() == 0) return Error("Invalid INVOKE record");
1677      }
1678
1679      if (!FTy->isVarArg()) {
1680        if (Record.size() != OpNum)
1681          return Error("Invalid INVOKE record");
1682      } else {
1683        // Read type/value pairs for varargs params.
1684        while (OpNum != Record.size()) {
1685          Value *Op;
1686          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1687            return Error("Invalid INVOKE record");
1688          Ops.push_back(Op);
1689        }
1690      }
1691
1692      I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1693                             Ops.begin(), Ops.end());
1694      cast<InvokeInst>(I)->setCallingConv(CCInfo);
1695      cast<InvokeInst>(I)->setParamAttrs(PAL);
1696      break;
1697    }
1698    case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1699      I = new UnwindInst();
1700      break;
1701    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1702      I = new UnreachableInst();
1703      break;
1704    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1705      if (Record.size() < 1 || ((Record.size()-1)&1))
1706        return Error("Invalid PHI record");
1707      const Type *Ty = getTypeByID(Record[0]);
1708      if (!Ty) return Error("Invalid PHI record");
1709
1710      PHINode *PN = PHINode::Create(Ty);
1711      PN->reserveOperandSpace((Record.size()-1)/2);
1712
1713      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1714        Value *V = getFnValueByID(Record[1+i], Ty);
1715        BasicBlock *BB = getBasicBlock(Record[2+i]);
1716        if (!V || !BB) return Error("Invalid PHI record");
1717        PN->addIncoming(V, BB);
1718      }
1719      I = PN;
1720      break;
1721    }
1722
1723    case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1724      if (Record.size() < 3)
1725        return Error("Invalid MALLOC record");
1726      const PointerType *Ty =
1727        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1728      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1729      unsigned Align = Record[2];
1730      if (!Ty || !Size) return Error("Invalid MALLOC record");
1731      I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1732      break;
1733    }
1734    case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1735      unsigned OpNum = 0;
1736      Value *Op;
1737      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1738          OpNum != Record.size())
1739        return Error("Invalid FREE record");
1740      I = new FreeInst(Op);
1741      break;
1742    }
1743    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1744      if (Record.size() < 3)
1745        return Error("Invalid ALLOCA record");
1746      const PointerType *Ty =
1747        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1748      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1749      unsigned Align = Record[2];
1750      if (!Ty || !Size) return Error("Invalid ALLOCA record");
1751      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1752      break;
1753    }
1754    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1755      unsigned OpNum = 0;
1756      Value *Op;
1757      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1758          OpNum+2 != Record.size())
1759        return Error("Invalid LOAD record");
1760
1761      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1762      break;
1763    }
1764    case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1765      unsigned OpNum = 0;
1766      Value *Val, *Ptr;
1767      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1768          getValue(Record, OpNum,
1769                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1770          OpNum+2 != Record.size())
1771        return Error("Invalid STORE record");
1772
1773      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1774      break;
1775    }
1776    case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1777      // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1778      unsigned OpNum = 0;
1779      Value *Val, *Ptr;
1780      if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1781          getValue(Record, OpNum, PointerType::getUnqual(Val->getType()), Ptr)||
1782          OpNum+2 != Record.size())
1783        return Error("Invalid STORE record");
1784
1785      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1786      break;
1787    }
1788    case bitc::FUNC_CODE_INST_CALL: {
1789      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1790      if (Record.size() < 3)
1791        return Error("Invalid CALL record");
1792
1793      PAListPtr PAL = getParamAttrs(Record[0]);
1794      unsigned CCInfo = Record[1];
1795
1796      unsigned OpNum = 2;
1797      Value *Callee;
1798      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1799        return Error("Invalid CALL record");
1800
1801      const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1802      const FunctionType *FTy = 0;
1803      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1804      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1805        return Error("Invalid CALL record");
1806
1807      SmallVector<Value*, 16> Args;
1808      // Read the fixed params.
1809      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1810        if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
1811          Args.push_back(getBasicBlock(Record[OpNum]));
1812        else
1813          Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1814        if (Args.back() == 0) return Error("Invalid CALL record");
1815      }
1816
1817      // Read type/value pairs for varargs params.
1818      if (!FTy->isVarArg()) {
1819        if (OpNum != Record.size())
1820          return Error("Invalid CALL record");
1821      } else {
1822        while (OpNum != Record.size()) {
1823          Value *Op;
1824          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1825            return Error("Invalid CALL record");
1826          Args.push_back(Op);
1827        }
1828      }
1829
1830      I = CallInst::Create(Callee, Args.begin(), Args.end());
1831      cast<CallInst>(I)->setCallingConv(CCInfo>>1);
1832      cast<CallInst>(I)->setTailCall(CCInfo & 1);
1833      cast<CallInst>(I)->setParamAttrs(PAL);
1834      break;
1835    }
1836    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
1837      if (Record.size() < 3)
1838        return Error("Invalid VAARG record");
1839      const Type *OpTy = getTypeByID(Record[0]);
1840      Value *Op = getFnValueByID(Record[1], OpTy);
1841      const Type *ResTy = getTypeByID(Record[2]);
1842      if (!OpTy || !Op || !ResTy)
1843        return Error("Invalid VAARG record");
1844      I = new VAArgInst(Op, ResTy);
1845      break;
1846    }
1847    }
1848
1849    // Add instruction to end of current BB.  If there is no current BB, reject
1850    // this file.
1851    if (CurBB == 0) {
1852      delete I;
1853      return Error("Invalid instruction with no BB");
1854    }
1855    CurBB->getInstList().push_back(I);
1856
1857    // If this was a terminator instruction, move to the next block.
1858    if (isa<TerminatorInst>(I)) {
1859      ++CurBBNo;
1860      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
1861    }
1862
1863    // Non-void values get registered in the value table for future use.
1864    if (I && I->getType() != Type::VoidTy)
1865      ValueList.AssignValue(I, NextValueNo++);
1866  }
1867
1868  // Check the function list for unresolved values.
1869  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
1870    if (A->getParent() == 0) {
1871      // We found at least one unresolved value.  Nuke them all to avoid leaks.
1872      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
1873        if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
1874          A->replaceAllUsesWith(UndefValue::get(A->getType()));
1875          delete A;
1876        }
1877      }
1878      return Error("Never resolved value found in function!");
1879    }
1880  }
1881
1882  // Trim the value list down to the size it was before we parsed this function.
1883  ValueList.shrinkTo(ModuleValueListSize);
1884  std::vector<BasicBlock*>().swap(FunctionBBs);
1885
1886  return false;
1887}
1888
1889//===----------------------------------------------------------------------===//
1890// ModuleProvider implementation
1891//===----------------------------------------------------------------------===//
1892
1893
1894bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
1895  // If it already is material, ignore the request.
1896  if (!F->hasNotBeenReadFromBitcode()) return false;
1897
1898  DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
1899    DeferredFunctionInfo.find(F);
1900  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
1901
1902  // Move the bit stream to the saved position of the deferred function body and
1903  // restore the real linkage type for the function.
1904  Stream.JumpToBit(DFII->second.first);
1905  F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
1906
1907  if (ParseFunctionBody(F)) {
1908    if (ErrInfo) *ErrInfo = ErrorString;
1909    return true;
1910  }
1911
1912  // Upgrade any old intrinsic calls in the function.
1913  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
1914       E = UpgradedIntrinsics.end(); I != E; ++I) {
1915    if (I->first != I->second) {
1916      for (Value::use_iterator UI = I->first->use_begin(),
1917           UE = I->first->use_end(); UI != UE; ) {
1918        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1919          UpgradeIntrinsicCall(CI, I->second);
1920      }
1921    }
1922  }
1923
1924  return false;
1925}
1926
1927void BitcodeReader::dematerializeFunction(Function *F) {
1928  // If this function isn't materialized, or if it is a proto, this is a noop.
1929  if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
1930    return;
1931
1932  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
1933
1934  // Just forget the function body, we can remat it later.
1935  F->deleteBody();
1936  F->setLinkage(GlobalValue::GhostLinkage);
1937}
1938
1939
1940Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
1941  for (DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator I =
1942       DeferredFunctionInfo.begin(), E = DeferredFunctionInfo.end(); I != E;
1943       ++I) {
1944    Function *F = I->first;
1945    if (F->hasNotBeenReadFromBitcode() &&
1946        materializeFunction(F, ErrInfo))
1947      return 0;
1948  }
1949
1950  // Upgrade any intrinsic calls that slipped through (should not happen!) and
1951  // delete the old functions to clean up. We can't do this unless the entire
1952  // module is materialized because there could always be another function body
1953  // with calls to the old function.
1954  for (std::vector<std::pair<Function*, Function*> >::iterator I =
1955       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
1956    if (I->first != I->second) {
1957      for (Value::use_iterator UI = I->first->use_begin(),
1958           UE = I->first->use_end(); UI != UE; ) {
1959        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
1960          UpgradeIntrinsicCall(CI, I->second);
1961      }
1962      ValueList.replaceUsesOfWith(I->first, I->second);
1963      I->first->eraseFromParent();
1964    }
1965  }
1966  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
1967
1968  return TheModule;
1969}
1970
1971
1972/// This method is provided by the parent ModuleProvde class and overriden
1973/// here. It simply releases the module from its provided and frees up our
1974/// state.
1975/// @brief Release our hold on the generated module
1976Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
1977  // Since we're losing control of this Module, we must hand it back complete
1978  Module *M = ModuleProvider::releaseModule(ErrInfo);
1979  FreeState();
1980  return M;
1981}
1982
1983
1984//===----------------------------------------------------------------------===//
1985// External interface
1986//===----------------------------------------------------------------------===//
1987
1988/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
1989///
1990ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
1991                                               std::string *ErrMsg) {
1992  BitcodeReader *R = new BitcodeReader(Buffer);
1993  if (R->ParseBitcode()) {
1994    if (ErrMsg)
1995      *ErrMsg = R->getErrorString();
1996
1997    // Don't let the BitcodeReader dtor delete 'Buffer'.
1998    R->releaseMemoryBuffer();
1999    delete R;
2000    return 0;
2001  }
2002  return R;
2003}
2004
2005/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2006/// If an error occurs, return null and fill in *ErrMsg if non-null.
2007Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, std::string *ErrMsg){
2008  BitcodeReader *R;
2009  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, ErrMsg));
2010  if (!R) return 0;
2011
2012  // Read in the entire module.
2013  Module *M = R->materializeModule(ErrMsg);
2014
2015  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2016  // there was an error.
2017  R->releaseMemoryBuffer();
2018
2019  // If there was no error, tell ModuleProvider not to delete it when its dtor
2020  // is run.
2021  if (M)
2022    M = R->releaseModule(ErrMsg);
2023
2024  delete R;
2025  return M;
2026}
2027