BitcodeReader.cpp revision 1df9859c40492511b8aa4321eb76496005d3b75b
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/IntrinsicInst.h"
20#include "llvm/Module.h"
21#include "llvm/Operator.h"
22#include "llvm/AutoUpgrade.h"
23#include "llvm/ADT/SmallString.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/Support/MathExtras.h"
26#include "llvm/Support/MemoryBuffer.h"
27#include "llvm/OperandTraits.h"
28using namespace llvm;
29
30void BitcodeReader::FreeState() {
31  if (BufferOwned)
32    delete Buffer;
33  Buffer = 0;
34  std::vector<PATypeHolder>().swap(TypeList);
35  ValueList.clear();
36  MDValueList.clear();
37
38  std::vector<AttrListPtr>().swap(MAttributes);
39  std::vector<BasicBlock*>().swap(FunctionBBs);
40  std::vector<Function*>().swap(FunctionsWithBodies);
41  DeferredFunctionInfo.clear();
42}
43
44//===----------------------------------------------------------------------===//
45//  Helper functions to implement forward reference resolution, etc.
46//===----------------------------------------------------------------------===//
47
48/// ConvertToString - Convert a string from a record into an std::string, return
49/// true on failure.
50template<typename StrTy>
51static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
52                            StrTy &Result) {
53  if (Idx > Record.size())
54    return true;
55
56  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
57    Result += (char)Record[i];
58  return false;
59}
60
61static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
62  switch (Val) {
63  default: // Map unknown/new linkages to external
64  case 0:  return GlobalValue::ExternalLinkage;
65  case 1:  return GlobalValue::WeakAnyLinkage;
66  case 2:  return GlobalValue::AppendingLinkage;
67  case 3:  return GlobalValue::InternalLinkage;
68  case 4:  return GlobalValue::LinkOnceAnyLinkage;
69  case 5:  return GlobalValue::DLLImportLinkage;
70  case 6:  return GlobalValue::DLLExportLinkage;
71  case 7:  return GlobalValue::ExternalWeakLinkage;
72  case 8:  return GlobalValue::CommonLinkage;
73  case 9:  return GlobalValue::PrivateLinkage;
74  case 10: return GlobalValue::WeakODRLinkage;
75  case 11: return GlobalValue::LinkOnceODRLinkage;
76  case 12: return GlobalValue::AvailableExternallyLinkage;
77  case 13: return GlobalValue::LinkerPrivateLinkage;
78  }
79}
80
81static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
82  switch (Val) {
83  default: // Map unknown visibilities to default.
84  case 0: return GlobalValue::DefaultVisibility;
85  case 1: return GlobalValue::HiddenVisibility;
86  case 2: return GlobalValue::ProtectedVisibility;
87  }
88}
89
90static int GetDecodedCastOpcode(unsigned Val) {
91  switch (Val) {
92  default: return -1;
93  case bitc::CAST_TRUNC   : return Instruction::Trunc;
94  case bitc::CAST_ZEXT    : return Instruction::ZExt;
95  case bitc::CAST_SEXT    : return Instruction::SExt;
96  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
97  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
98  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
99  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
100  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
101  case bitc::CAST_FPEXT   : return Instruction::FPExt;
102  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
103  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
104  case bitc::CAST_BITCAST : return Instruction::BitCast;
105  }
106}
107static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
108  switch (Val) {
109  default: return -1;
110  case bitc::BINOP_ADD:
111    return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
112  case bitc::BINOP_SUB:
113    return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
114  case bitc::BINOP_MUL:
115    return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
116  case bitc::BINOP_UDIV: return Instruction::UDiv;
117  case bitc::BINOP_SDIV:
118    return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
119  case bitc::BINOP_UREM: return Instruction::URem;
120  case bitc::BINOP_SREM:
121    return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
122  case bitc::BINOP_SHL:  return Instruction::Shl;
123  case bitc::BINOP_LSHR: return Instruction::LShr;
124  case bitc::BINOP_ASHR: return Instruction::AShr;
125  case bitc::BINOP_AND:  return Instruction::And;
126  case bitc::BINOP_OR:   return Instruction::Or;
127  case bitc::BINOP_XOR:  return Instruction::Xor;
128  }
129}
130
131namespace llvm {
132namespace {
133  /// @brief A class for maintaining the slot number definition
134  /// as a placeholder for the actual definition for forward constants defs.
135  class ConstantPlaceHolder : public ConstantExpr {
136    ConstantPlaceHolder();                       // DO NOT IMPLEMENT
137    void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
138  public:
139    // allocate space for exactly one operand
140    void *operator new(size_t s) {
141      return User::operator new(s, 1);
142    }
143    explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
144      : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
145      Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
146    }
147
148    /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
149    static inline bool classof(const ConstantPlaceHolder *) { return true; }
150    static bool classof(const Value *V) {
151      return isa<ConstantExpr>(V) &&
152             cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
153    }
154
155
156    /// Provide fast operand accessors
157    //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
158  };
159}
160
161// FIXME: can we inherit this from ConstantExpr?
162template <>
163struct OperandTraits<ConstantPlaceHolder> : public FixedNumOperandTraits<1> {
164};
165}
166
167
168void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
169  if (Idx == size()) {
170    push_back(V);
171    return;
172  }
173
174  if (Idx >= size())
175    resize(Idx+1);
176
177  WeakVH &OldV = ValuePtrs[Idx];
178  if (OldV == 0) {
179    OldV = V;
180    return;
181  }
182
183  // Handle constants and non-constants (e.g. instrs) differently for
184  // efficiency.
185  if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
186    ResolveConstants.push_back(std::make_pair(PHC, Idx));
187    OldV = V;
188  } else {
189    // If there was a forward reference to this value, replace it.
190    Value *PrevVal = OldV;
191    OldV->replaceAllUsesWith(V);
192    delete PrevVal;
193  }
194}
195
196
197Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
198                                                    const Type *Ty) {
199  if (Idx >= size())
200    resize(Idx + 1);
201
202  if (Value *V = ValuePtrs[Idx]) {
203    assert(Ty == V->getType() && "Type mismatch in constant table!");
204    return cast<Constant>(V);
205  }
206
207  // Create and return a placeholder, which will later be RAUW'd.
208  Constant *C = new ConstantPlaceHolder(Ty, Context);
209  ValuePtrs[Idx] = C;
210  return C;
211}
212
213Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
214  if (Idx >= size())
215    resize(Idx + 1);
216
217  if (Value *V = ValuePtrs[Idx]) {
218    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
219    return V;
220  }
221
222  // No type specified, must be invalid reference.
223  if (Ty == 0) return 0;
224
225  // Create and return a placeholder, which will later be RAUW'd.
226  Value *V = new Argument(Ty);
227  ValuePtrs[Idx] = V;
228  return V;
229}
230
231/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
232/// resolves any forward references.  The idea behind this is that we sometimes
233/// get constants (such as large arrays) which reference *many* forward ref
234/// constants.  Replacing each of these causes a lot of thrashing when
235/// building/reuniquing the constant.  Instead of doing this, we look at all the
236/// uses and rewrite all the place holders at once for any constant that uses
237/// a placeholder.
238void BitcodeReaderValueList::ResolveConstantForwardRefs() {
239  // Sort the values by-pointer so that they are efficient to look up with a
240  // binary search.
241  std::sort(ResolveConstants.begin(), ResolveConstants.end());
242
243  SmallVector<Constant*, 64> NewOps;
244
245  while (!ResolveConstants.empty()) {
246    Value *RealVal = operator[](ResolveConstants.back().second);
247    Constant *Placeholder = ResolveConstants.back().first;
248    ResolveConstants.pop_back();
249
250    // Loop over all users of the placeholder, updating them to reference the
251    // new value.  If they reference more than one placeholder, update them all
252    // at once.
253    while (!Placeholder->use_empty()) {
254      Value::use_iterator UI = Placeholder->use_begin();
255
256      // If the using object isn't uniqued, just update the operands.  This
257      // handles instructions and initializers for global variables.
258      if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
259        UI.getUse().set(RealVal);
260        continue;
261      }
262
263      // Otherwise, we have a constant that uses the placeholder.  Replace that
264      // constant with a new constant that has *all* placeholder uses updated.
265      Constant *UserC = cast<Constant>(*UI);
266      for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
267           I != E; ++I) {
268        Value *NewOp;
269        if (!isa<ConstantPlaceHolder>(*I)) {
270          // Not a placeholder reference.
271          NewOp = *I;
272        } else if (*I == Placeholder) {
273          // Common case is that it just references this one placeholder.
274          NewOp = RealVal;
275        } else {
276          // Otherwise, look up the placeholder in ResolveConstants.
277          ResolveConstantsTy::iterator It =
278            std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
279                             std::pair<Constant*, unsigned>(cast<Constant>(*I),
280                                                            0));
281          assert(It != ResolveConstants.end() && It->first == *I);
282          NewOp = operator[](It->second);
283        }
284
285        NewOps.push_back(cast<Constant>(NewOp));
286      }
287
288      // Make the new constant.
289      Constant *NewC;
290      if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
291        NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
292                                        NewOps.size());
293      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
294        NewC = ConstantStruct::get(Context, &NewOps[0], NewOps.size(),
295                                         UserCS->getType()->isPacked());
296      } else if (isa<ConstantVector>(UserC)) {
297        NewC = ConstantVector::get(&NewOps[0], NewOps.size());
298      } else {
299        assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
300        NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
301                                                          NewOps.size());
302      }
303
304      UserC->replaceAllUsesWith(NewC);
305      UserC->destroyConstant();
306      NewOps.clear();
307    }
308
309    // Update all ValueHandles, they should be the only users at this point.
310    Placeholder->replaceAllUsesWith(RealVal);
311    delete Placeholder;
312  }
313}
314
315void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
316  if (Idx == size()) {
317    push_back(V);
318    return;
319  }
320
321  if (Idx >= size())
322    resize(Idx+1);
323
324  WeakVH &OldV = MDValuePtrs[Idx];
325  if (OldV == 0) {
326    OldV = V;
327    return;
328  }
329
330  // If there was a forward reference to this value, replace it.
331  Value *PrevVal = OldV;
332  OldV->replaceAllUsesWith(V);
333  delete PrevVal;
334  // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
335  // value for Idx.
336  MDValuePtrs[Idx] = V;
337}
338
339Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
340  if (Idx >= size())
341    resize(Idx + 1);
342
343  if (Value *V = MDValuePtrs[Idx]) {
344    assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
345    return V;
346  }
347
348  // Create and return a placeholder, which will later be RAUW'd.
349  Value *V = new Argument(Type::getMetadataTy(Context));
350  MDValuePtrs[Idx] = V;
351  return V;
352}
353
354const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
355  // If the TypeID is in range, return it.
356  if (ID < TypeList.size())
357    return TypeList[ID].get();
358  if (!isTypeTable) return 0;
359
360  // The type table allows forward references.  Push as many Opaque types as
361  // needed to get up to ID.
362  while (TypeList.size() <= ID)
363    TypeList.push_back(OpaqueType::get(Context));
364  return TypeList.back().get();
365}
366
367//===----------------------------------------------------------------------===//
368//  Functions for parsing blocks from the bitcode file
369//===----------------------------------------------------------------------===//
370
371bool BitcodeReader::ParseAttributeBlock() {
372  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
373    return Error("Malformed block record");
374
375  if (!MAttributes.empty())
376    return Error("Multiple PARAMATTR blocks found!");
377
378  SmallVector<uint64_t, 64> Record;
379
380  SmallVector<AttributeWithIndex, 8> Attrs;
381
382  // Read all the records.
383  while (1) {
384    unsigned Code = Stream.ReadCode();
385    if (Code == bitc::END_BLOCK) {
386      if (Stream.ReadBlockEnd())
387        return Error("Error at end of PARAMATTR block");
388      return false;
389    }
390
391    if (Code == bitc::ENTER_SUBBLOCK) {
392      // No known subblocks, always skip them.
393      Stream.ReadSubBlockID();
394      if (Stream.SkipBlock())
395        return Error("Malformed block record");
396      continue;
397    }
398
399    if (Code == bitc::DEFINE_ABBREV) {
400      Stream.ReadAbbrevRecord();
401      continue;
402    }
403
404    // Read a record.
405    Record.clear();
406    switch (Stream.ReadRecord(Code, Record)) {
407    default:  // Default behavior: ignore.
408      break;
409    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
410      if (Record.size() & 1)
411        return Error("Invalid ENTRY record");
412
413      // FIXME : Remove this autoupgrade code in LLVM 3.0.
414      // If Function attributes are using index 0 then transfer them
415      // to index ~0. Index 0 is used for return value attributes but used to be
416      // used for function attributes.
417      Attributes RetAttribute = Attribute::None;
418      Attributes FnAttribute = Attribute::None;
419      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
420        // FIXME: remove in LLVM 3.0
421        // The alignment is stored as a 16-bit raw value from bits 31--16.
422        // We shift the bits above 31 down by 11 bits.
423
424        unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
425        if (Alignment && !isPowerOf2_32(Alignment))
426          return Error("Alignment is not a power of two.");
427
428        Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
429        if (Alignment)
430          ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
431        ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
432        Record[i+1] = ReconstitutedAttr;
433
434        if (Record[i] == 0)
435          RetAttribute = Record[i+1];
436        else if (Record[i] == ~0U)
437          FnAttribute = Record[i+1];
438      }
439
440      unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
441                              Attribute::ReadOnly|Attribute::ReadNone);
442
443      if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
444          (RetAttribute & OldRetAttrs) != 0) {
445        if (FnAttribute == Attribute::None) { // add a slot so they get added.
446          Record.push_back(~0U);
447          Record.push_back(0);
448        }
449
450        FnAttribute  |= RetAttribute & OldRetAttrs;
451        RetAttribute &= ~OldRetAttrs;
452      }
453
454      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
455        if (Record[i] == 0) {
456          if (RetAttribute != Attribute::None)
457            Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
458        } else if (Record[i] == ~0U) {
459          if (FnAttribute != Attribute::None)
460            Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
461        } else if (Record[i+1] != Attribute::None)
462          Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
463      }
464
465      MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
466      Attrs.clear();
467      break;
468    }
469    }
470  }
471}
472
473
474bool BitcodeReader::ParseTypeTable() {
475  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
476    return Error("Malformed block record");
477
478  if (!TypeList.empty())
479    return Error("Multiple TYPE_BLOCKs found!");
480
481  SmallVector<uint64_t, 64> Record;
482  unsigned NumRecords = 0;
483
484  // Read all the records for this type table.
485  while (1) {
486    unsigned Code = Stream.ReadCode();
487    if (Code == bitc::END_BLOCK) {
488      if (NumRecords != TypeList.size())
489        return Error("Invalid type forward reference in TYPE_BLOCK");
490      if (Stream.ReadBlockEnd())
491        return Error("Error at end of type table block");
492      return false;
493    }
494
495    if (Code == bitc::ENTER_SUBBLOCK) {
496      // No known subblocks, always skip them.
497      Stream.ReadSubBlockID();
498      if (Stream.SkipBlock())
499        return Error("Malformed block record");
500      continue;
501    }
502
503    if (Code == bitc::DEFINE_ABBREV) {
504      Stream.ReadAbbrevRecord();
505      continue;
506    }
507
508    // Read a record.
509    Record.clear();
510    const Type *ResultTy = 0;
511    switch (Stream.ReadRecord(Code, Record)) {
512    default:  // Default behavior: unknown type.
513      ResultTy = 0;
514      break;
515    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
516      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
517      // type list.  This allows us to reserve space.
518      if (Record.size() < 1)
519        return Error("Invalid TYPE_CODE_NUMENTRY record");
520      TypeList.reserve(Record[0]);
521      continue;
522    case bitc::TYPE_CODE_VOID:      // VOID
523      ResultTy = Type::getVoidTy(Context);
524      break;
525    case bitc::TYPE_CODE_FLOAT:     // FLOAT
526      ResultTy = Type::getFloatTy(Context);
527      break;
528    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
529      ResultTy = Type::getDoubleTy(Context);
530      break;
531    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
532      ResultTy = Type::getX86_FP80Ty(Context);
533      break;
534    case bitc::TYPE_CODE_FP128:     // FP128
535      ResultTy = Type::getFP128Ty(Context);
536      break;
537    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
538      ResultTy = Type::getPPC_FP128Ty(Context);
539      break;
540    case bitc::TYPE_CODE_LABEL:     // LABEL
541      ResultTy = Type::getLabelTy(Context);
542      break;
543    case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
544      ResultTy = 0;
545      break;
546    case bitc::TYPE_CODE_METADATA:  // METADATA
547      ResultTy = Type::getMetadataTy(Context);
548      break;
549    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
550      if (Record.size() < 1)
551        return Error("Invalid Integer type record");
552
553      ResultTy = IntegerType::get(Context, Record[0]);
554      break;
555    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
556                                    //          [pointee type, address space]
557      if (Record.size() < 1)
558        return Error("Invalid POINTER type record");
559      unsigned AddressSpace = 0;
560      if (Record.size() == 2)
561        AddressSpace = Record[1];
562      ResultTy = PointerType::get(getTypeByID(Record[0], true),
563                                        AddressSpace);
564      break;
565    }
566    case bitc::TYPE_CODE_FUNCTION: {
567      // FIXME: attrid is dead, remove it in LLVM 3.0
568      // FUNCTION: [vararg, attrid, retty, paramty x N]
569      if (Record.size() < 3)
570        return Error("Invalid FUNCTION type record");
571      std::vector<const Type*> ArgTys;
572      for (unsigned i = 3, e = Record.size(); i != e; ++i)
573        ArgTys.push_back(getTypeByID(Record[i], true));
574
575      ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
576                                   Record[0]);
577      break;
578    }
579    case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
580      if (Record.size() < 1)
581        return Error("Invalid STRUCT type record");
582      std::vector<const Type*> EltTys;
583      for (unsigned i = 1, e = Record.size(); i != e; ++i)
584        EltTys.push_back(getTypeByID(Record[i], true));
585      ResultTy = StructType::get(Context, EltTys, Record[0]);
586      break;
587    }
588    case bitc::TYPE_CODE_UNION: {  // UNION: [eltty x N]
589      SmallVector<const Type*, 8> EltTys;
590      for (unsigned i = 0, e = Record.size(); i != e; ++i)
591        EltTys.push_back(getTypeByID(Record[i], true));
592      ResultTy = UnionType::get(&EltTys[0], EltTys.size());
593      break;
594    }
595    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
596      if (Record.size() < 2)
597        return Error("Invalid ARRAY type record");
598      ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
599      break;
600    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
601      if (Record.size() < 2)
602        return Error("Invalid VECTOR type record");
603      ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
604      break;
605    }
606
607    if (NumRecords == TypeList.size()) {
608      // If this is a new type slot, just append it.
609      TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get(Context));
610      ++NumRecords;
611    } else if (ResultTy == 0) {
612      // Otherwise, this was forward referenced, so an opaque type was created,
613      // but the result type is actually just an opaque.  Leave the one we
614      // created previously.
615      ++NumRecords;
616    } else {
617      // Otherwise, this was forward referenced, so an opaque type was created.
618      // Resolve the opaque type to the real type now.
619      assert(NumRecords < TypeList.size() && "Typelist imbalance");
620      const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
621
622      // Don't directly push the new type on the Tab. Instead we want to replace
623      // the opaque type we previously inserted with the new concrete value. The
624      // refinement from the abstract (opaque) type to the new type causes all
625      // uses of the abstract type to use the concrete type (NewTy). This will
626      // also cause the opaque type to be deleted.
627      const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
628
629      // This should have replaced the old opaque type with the new type in the
630      // value table... or with a preexisting type that was already in the
631      // system.  Let's just make sure it did.
632      assert(TypeList[NumRecords-1].get() != OldTy &&
633             "refineAbstractType didn't work!");
634    }
635  }
636}
637
638
639bool BitcodeReader::ParseTypeSymbolTable() {
640  if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
641    return Error("Malformed block record");
642
643  SmallVector<uint64_t, 64> Record;
644
645  // Read all the records for this type table.
646  std::string TypeName;
647  while (1) {
648    unsigned Code = Stream.ReadCode();
649    if (Code == bitc::END_BLOCK) {
650      if (Stream.ReadBlockEnd())
651        return Error("Error at end of type symbol table block");
652      return false;
653    }
654
655    if (Code == bitc::ENTER_SUBBLOCK) {
656      // No known subblocks, always skip them.
657      Stream.ReadSubBlockID();
658      if (Stream.SkipBlock())
659        return Error("Malformed block record");
660      continue;
661    }
662
663    if (Code == bitc::DEFINE_ABBREV) {
664      Stream.ReadAbbrevRecord();
665      continue;
666    }
667
668    // Read a record.
669    Record.clear();
670    switch (Stream.ReadRecord(Code, Record)) {
671    default:  // Default behavior: unknown type.
672      break;
673    case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
674      if (ConvertToString(Record, 1, TypeName))
675        return Error("Invalid TST_ENTRY record");
676      unsigned TypeID = Record[0];
677      if (TypeID >= TypeList.size())
678        return Error("Invalid Type ID in TST_ENTRY record");
679
680      TheModule->addTypeName(TypeName, TypeList[TypeID].get());
681      TypeName.clear();
682      break;
683    }
684  }
685}
686
687bool BitcodeReader::ParseValueSymbolTable() {
688  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
689    return Error("Malformed block record");
690
691  SmallVector<uint64_t, 64> Record;
692
693  // Read all the records for this value table.
694  SmallString<128> ValueName;
695  while (1) {
696    unsigned Code = Stream.ReadCode();
697    if (Code == bitc::END_BLOCK) {
698      if (Stream.ReadBlockEnd())
699        return Error("Error at end of value symbol table block");
700      return false;
701    }
702    if (Code == bitc::ENTER_SUBBLOCK) {
703      // No known subblocks, always skip them.
704      Stream.ReadSubBlockID();
705      if (Stream.SkipBlock())
706        return Error("Malformed block record");
707      continue;
708    }
709
710    if (Code == bitc::DEFINE_ABBREV) {
711      Stream.ReadAbbrevRecord();
712      continue;
713    }
714
715    // Read a record.
716    Record.clear();
717    switch (Stream.ReadRecord(Code, Record)) {
718    default:  // Default behavior: unknown type.
719      break;
720    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
721      if (ConvertToString(Record, 1, ValueName))
722        return Error("Invalid VST_ENTRY record");
723      unsigned ValueID = Record[0];
724      if (ValueID >= ValueList.size())
725        return Error("Invalid Value ID in VST_ENTRY record");
726      Value *V = ValueList[ValueID];
727
728      V->setName(StringRef(ValueName.data(), ValueName.size()));
729      ValueName.clear();
730      break;
731    }
732    case bitc::VST_CODE_BBENTRY: {
733      if (ConvertToString(Record, 1, ValueName))
734        return Error("Invalid VST_BBENTRY record");
735      BasicBlock *BB = getBasicBlock(Record[0]);
736      if (BB == 0)
737        return Error("Invalid BB ID in VST_BBENTRY record");
738
739      BB->setName(StringRef(ValueName.data(), ValueName.size()));
740      ValueName.clear();
741      break;
742    }
743    }
744  }
745}
746
747bool BitcodeReader::ParseMetadata() {
748  unsigned NextMDValueNo = MDValueList.size();
749
750  if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
751    return Error("Malformed block record");
752
753  SmallVector<uint64_t, 64> Record;
754
755  // Read all the records.
756  while (1) {
757    unsigned Code = Stream.ReadCode();
758    if (Code == bitc::END_BLOCK) {
759      if (Stream.ReadBlockEnd())
760        return Error("Error at end of PARAMATTR block");
761      return false;
762    }
763
764    if (Code == bitc::ENTER_SUBBLOCK) {
765      // No known subblocks, always skip them.
766      Stream.ReadSubBlockID();
767      if (Stream.SkipBlock())
768        return Error("Malformed block record");
769      continue;
770    }
771
772    if (Code == bitc::DEFINE_ABBREV) {
773      Stream.ReadAbbrevRecord();
774      continue;
775    }
776
777    bool IsFunctionLocal = false;
778    // Read a record.
779    Record.clear();
780    switch (Stream.ReadRecord(Code, Record)) {
781    default:  // Default behavior: ignore.
782      break;
783    case bitc::METADATA_NAME: {
784      // Read named of the named metadata.
785      unsigned NameLength = Record.size();
786      SmallString<8> Name;
787      Name.resize(NameLength);
788      for (unsigned i = 0; i != NameLength; ++i)
789        Name[i] = Record[i];
790      Record.clear();
791      Code = Stream.ReadCode();
792
793      // METADATA_NAME is always followed by METADATA_NAMED_NODE.
794      if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
795        assert ( 0 && "Inavlid Named Metadata record");
796
797      // Read named metadata elements.
798      unsigned Size = Record.size();
799      SmallVector<MDNode *, 8> Elts;
800      for (unsigned i = 0; i != Size; ++i) {
801        if (Record[i] == ~0U) {
802          Elts.push_back(NULL);
803          continue;
804        }
805        MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
806        if (MD == 0)
807          return Error("Malformed metadata record");
808        Elts.push_back(MD);
809      }
810      Value *V = NamedMDNode::Create(Context, Name.str(), Elts.data(),
811                                     Elts.size(), TheModule);
812      MDValueList.AssignValue(V, NextMDValueNo++);
813      break;
814    }
815    case bitc::METADATA_FN_NODE:
816      IsFunctionLocal = true;
817      // fall-through
818    case bitc::METADATA_NODE: {
819      if (Record.empty() || Record.size() % 2 == 1)
820        return Error("Invalid METADATA_NODE record");
821
822      unsigned Size = Record.size();
823      SmallVector<Value*, 8> Elts;
824      for (unsigned i = 0; i != Size; i += 2) {
825        const Type *Ty = getTypeByID(Record[i], false);
826        if (Ty->isMetadataTy())
827          Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
828        else if (!Ty->isVoidTy())
829          Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
830        else
831          Elts.push_back(NULL);
832      }
833      Value *V = MDNode::getWhenValsUnresolved(Context, &Elts[0], Elts.size(),
834                                               IsFunctionLocal);
835      IsFunctionLocal = false;
836      MDValueList.AssignValue(V, NextMDValueNo++);
837      break;
838    }
839    case bitc::METADATA_STRING: {
840      unsigned MDStringLength = Record.size();
841      SmallString<8> String;
842      String.resize(MDStringLength);
843      for (unsigned i = 0; i != MDStringLength; ++i)
844        String[i] = Record[i];
845      Value *V = MDString::get(Context,
846                               StringRef(String.data(), String.size()));
847      MDValueList.AssignValue(V, NextMDValueNo++);
848      break;
849    }
850    case bitc::METADATA_KIND: {
851      unsigned RecordLength = Record.size();
852      if (Record.empty() || RecordLength < 2)
853        return Error("Invalid METADATA_KIND record");
854      SmallString<8> Name;
855      Name.resize(RecordLength-1);
856      unsigned Kind = Record[0];
857      (void) Kind;
858      for (unsigned i = 1; i != RecordLength; ++i)
859        Name[i-1] = Record[i];
860
861      unsigned NewKind = TheModule->getMDKindID(Name.str());
862      assert(Kind == NewKind &&
863             "FIXME: Unable to handle custom metadata mismatch!");(void)NewKind;
864      break;
865    }
866    }
867  }
868}
869
870/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
871/// the LSB for dense VBR encoding.
872static uint64_t DecodeSignRotatedValue(uint64_t V) {
873  if ((V & 1) == 0)
874    return V >> 1;
875  if (V != 1)
876    return -(V >> 1);
877  // There is no such thing as -0 with integers.  "-0" really means MININT.
878  return 1ULL << 63;
879}
880
881/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
882/// values and aliases that we can.
883bool BitcodeReader::ResolveGlobalAndAliasInits() {
884  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
885  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
886
887  GlobalInitWorklist.swap(GlobalInits);
888  AliasInitWorklist.swap(AliasInits);
889
890  while (!GlobalInitWorklist.empty()) {
891    unsigned ValID = GlobalInitWorklist.back().second;
892    if (ValID >= ValueList.size()) {
893      // Not ready to resolve this yet, it requires something later in the file.
894      GlobalInits.push_back(GlobalInitWorklist.back());
895    } else {
896      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
897        GlobalInitWorklist.back().first->setInitializer(C);
898      else
899        return Error("Global variable initializer is not a constant!");
900    }
901    GlobalInitWorklist.pop_back();
902  }
903
904  while (!AliasInitWorklist.empty()) {
905    unsigned ValID = AliasInitWorklist.back().second;
906    if (ValID >= ValueList.size()) {
907      AliasInits.push_back(AliasInitWorklist.back());
908    } else {
909      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
910        AliasInitWorklist.back().first->setAliasee(C);
911      else
912        return Error("Alias initializer is not a constant!");
913    }
914    AliasInitWorklist.pop_back();
915  }
916  return false;
917}
918
919bool BitcodeReader::ParseConstants() {
920  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
921    return Error("Malformed block record");
922
923  SmallVector<uint64_t, 64> Record;
924
925  // Read all the records for this value table.
926  const Type *CurTy = Type::getInt32Ty(Context);
927  unsigned NextCstNo = ValueList.size();
928  while (1) {
929    unsigned Code = Stream.ReadCode();
930    if (Code == bitc::END_BLOCK)
931      break;
932
933    if (Code == bitc::ENTER_SUBBLOCK) {
934      // No known subblocks, always skip them.
935      Stream.ReadSubBlockID();
936      if (Stream.SkipBlock())
937        return Error("Malformed block record");
938      continue;
939    }
940
941    if (Code == bitc::DEFINE_ABBREV) {
942      Stream.ReadAbbrevRecord();
943      continue;
944    }
945
946    // Read a record.
947    Record.clear();
948    Value *V = 0;
949    unsigned BitCode = Stream.ReadRecord(Code, Record);
950    switch (BitCode) {
951    default:  // Default behavior: unknown constant
952    case bitc::CST_CODE_UNDEF:     // UNDEF
953      V = UndefValue::get(CurTy);
954      break;
955    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
956      if (Record.empty())
957        return Error("Malformed CST_SETTYPE record");
958      if (Record[0] >= TypeList.size())
959        return Error("Invalid Type ID in CST_SETTYPE record");
960      CurTy = TypeList[Record[0]];
961      continue;  // Skip the ValueList manipulation.
962    case bitc::CST_CODE_NULL:      // NULL
963      V = Constant::getNullValue(CurTy);
964      break;
965    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
966      if (!CurTy->isIntegerTy() || Record.empty())
967        return Error("Invalid CST_INTEGER record");
968      V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
969      break;
970    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
971      if (!CurTy->isIntegerTy() || Record.empty())
972        return Error("Invalid WIDE_INTEGER record");
973
974      unsigned NumWords = Record.size();
975      SmallVector<uint64_t, 8> Words;
976      Words.resize(NumWords);
977      for (unsigned i = 0; i != NumWords; ++i)
978        Words[i] = DecodeSignRotatedValue(Record[i]);
979      V = ConstantInt::get(Context,
980                           APInt(cast<IntegerType>(CurTy)->getBitWidth(),
981                           NumWords, &Words[0]));
982      break;
983    }
984    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
985      if (Record.empty())
986        return Error("Invalid FLOAT record");
987      if (CurTy->isFloatTy())
988        V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
989      else if (CurTy->isDoubleTy())
990        V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
991      else if (CurTy->isX86_FP80Ty()) {
992        // Bits are not stored the same way as a normal i80 APInt, compensate.
993        uint64_t Rearrange[2];
994        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
995        Rearrange[1] = Record[0] >> 48;
996        V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
997      } else if (CurTy->isFP128Ty())
998        V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
999      else if (CurTy->isPPC_FP128Ty())
1000        V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
1001      else
1002        V = UndefValue::get(CurTy);
1003      break;
1004    }
1005
1006    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1007      if (Record.empty())
1008        return Error("Invalid CST_AGGREGATE record");
1009
1010      unsigned Size = Record.size();
1011      std::vector<Constant*> Elts;
1012
1013      if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
1014        for (unsigned i = 0; i != Size; ++i)
1015          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1016                                                     STy->getElementType(i)));
1017        V = ConstantStruct::get(STy, Elts);
1018      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1019        const Type *EltTy = ATy->getElementType();
1020        for (unsigned i = 0; i != Size; ++i)
1021          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1022        V = ConstantArray::get(ATy, Elts);
1023      } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1024        const Type *EltTy = VTy->getElementType();
1025        for (unsigned i = 0; i != Size; ++i)
1026          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1027        V = ConstantVector::get(Elts);
1028      } else {
1029        V = UndefValue::get(CurTy);
1030      }
1031      break;
1032    }
1033    case bitc::CST_CODE_STRING: { // STRING: [values]
1034      if (Record.empty())
1035        return Error("Invalid CST_AGGREGATE record");
1036
1037      const ArrayType *ATy = cast<ArrayType>(CurTy);
1038      const Type *EltTy = ATy->getElementType();
1039
1040      unsigned Size = Record.size();
1041      std::vector<Constant*> Elts;
1042      for (unsigned i = 0; i != Size; ++i)
1043        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1044      V = ConstantArray::get(ATy, Elts);
1045      break;
1046    }
1047    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1048      if (Record.empty())
1049        return Error("Invalid CST_AGGREGATE record");
1050
1051      const ArrayType *ATy = cast<ArrayType>(CurTy);
1052      const Type *EltTy = ATy->getElementType();
1053
1054      unsigned Size = Record.size();
1055      std::vector<Constant*> Elts;
1056      for (unsigned i = 0; i != Size; ++i)
1057        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
1058      Elts.push_back(Constant::getNullValue(EltTy));
1059      V = ConstantArray::get(ATy, Elts);
1060      break;
1061    }
1062    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1063      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1064      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1065      if (Opc < 0) {
1066        V = UndefValue::get(CurTy);  // Unknown binop.
1067      } else {
1068        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1069        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1070        unsigned Flags = 0;
1071        if (Record.size() >= 4) {
1072          if (Opc == Instruction::Add ||
1073              Opc == Instruction::Sub ||
1074              Opc == Instruction::Mul) {
1075            if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1076              Flags |= OverflowingBinaryOperator::NoSignedWrap;
1077            if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1078              Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1079          } else if (Opc == Instruction::SDiv) {
1080            if (Record[3] & (1 << bitc::SDIV_EXACT))
1081              Flags |= SDivOperator::IsExact;
1082          }
1083        }
1084        V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1085      }
1086      break;
1087    }
1088    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1089      if (Record.size() < 3) return Error("Invalid CE_CAST record");
1090      int Opc = GetDecodedCastOpcode(Record[0]);
1091      if (Opc < 0) {
1092        V = UndefValue::get(CurTy);  // Unknown cast.
1093      } else {
1094        const Type *OpTy = getTypeByID(Record[1]);
1095        if (!OpTy) return Error("Invalid CE_CAST record");
1096        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1097        V = ConstantExpr::getCast(Opc, Op, CurTy);
1098      }
1099      break;
1100    }
1101    case bitc::CST_CODE_CE_INBOUNDS_GEP:
1102    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1103      if (Record.size() & 1) return Error("Invalid CE_GEP record");
1104      SmallVector<Constant*, 16> Elts;
1105      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1106        const Type *ElTy = getTypeByID(Record[i]);
1107        if (!ElTy) return Error("Invalid CE_GEP record");
1108        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1109      }
1110      if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1111        V = ConstantExpr::getInBoundsGetElementPtr(Elts[0], &Elts[1],
1112                                                   Elts.size()-1);
1113      else
1114        V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
1115                                           Elts.size()-1);
1116      break;
1117    }
1118    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1119      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1120      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1121                                                              Type::getInt1Ty(Context)),
1122                                  ValueList.getConstantFwdRef(Record[1],CurTy),
1123                                  ValueList.getConstantFwdRef(Record[2],CurTy));
1124      break;
1125    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1126      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1127      const VectorType *OpTy =
1128        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1129      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1130      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1131      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1132      V = ConstantExpr::getExtractElement(Op0, Op1);
1133      break;
1134    }
1135    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1136      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1137      if (Record.size() < 3 || OpTy == 0)
1138        return Error("Invalid CE_INSERTELT record");
1139      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1140      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1141                                                  OpTy->getElementType());
1142      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1143      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1144      break;
1145    }
1146    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1147      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1148      if (Record.size() < 3 || OpTy == 0)
1149        return Error("Invalid CE_SHUFFLEVEC record");
1150      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1151      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1152      const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1153                                                 OpTy->getNumElements());
1154      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1155      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1156      break;
1157    }
1158    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1159      const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1160      const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
1161      if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1162        return Error("Invalid CE_SHUFVEC_EX record");
1163      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1164      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1165      const Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1166                                                 RTy->getNumElements());
1167      Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1168      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1169      break;
1170    }
1171    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1172      if (Record.size() < 4) return Error("Invalid CE_CMP record");
1173      const Type *OpTy = getTypeByID(Record[0]);
1174      if (OpTy == 0) return Error("Invalid CE_CMP record");
1175      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1176      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1177
1178      if (OpTy->isFPOrFPVectorTy())
1179        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1180      else
1181        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1182      break;
1183    }
1184    case bitc::CST_CODE_INLINEASM: {
1185      if (Record.size() < 2) return Error("Invalid INLINEASM record");
1186      std::string AsmStr, ConstrStr;
1187      bool HasSideEffects = Record[0] & 1;
1188      bool IsAlignStack = Record[0] >> 1;
1189      unsigned AsmStrSize = Record[1];
1190      if (2+AsmStrSize >= Record.size())
1191        return Error("Invalid INLINEASM record");
1192      unsigned ConstStrSize = Record[2+AsmStrSize];
1193      if (3+AsmStrSize+ConstStrSize > Record.size())
1194        return Error("Invalid INLINEASM record");
1195
1196      for (unsigned i = 0; i != AsmStrSize; ++i)
1197        AsmStr += (char)Record[2+i];
1198      for (unsigned i = 0; i != ConstStrSize; ++i)
1199        ConstrStr += (char)Record[3+AsmStrSize+i];
1200      const PointerType *PTy = cast<PointerType>(CurTy);
1201      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1202                         AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1203      break;
1204    }
1205    case bitc::CST_CODE_BLOCKADDRESS:{
1206      if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1207      const Type *FnTy = getTypeByID(Record[0]);
1208      if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1209      Function *Fn =
1210        dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1211      if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1212
1213      GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1214                                                  Type::getInt8Ty(Context),
1215                                            false, GlobalValue::InternalLinkage,
1216                                                  0, "");
1217      BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1218      V = FwdRef;
1219      break;
1220    }
1221    }
1222
1223    ValueList.AssignValue(V, NextCstNo);
1224    ++NextCstNo;
1225  }
1226
1227  if (NextCstNo != ValueList.size())
1228    return Error("Invalid constant reference!");
1229
1230  if (Stream.ReadBlockEnd())
1231    return Error("Error at end of constants block");
1232
1233  // Once all the constants have been read, go through and resolve forward
1234  // references.
1235  ValueList.ResolveConstantForwardRefs();
1236  return false;
1237}
1238
1239/// RememberAndSkipFunctionBody - When we see the block for a function body,
1240/// remember where it is and then skip it.  This lets us lazily deserialize the
1241/// functions.
1242bool BitcodeReader::RememberAndSkipFunctionBody() {
1243  // Get the function we are talking about.
1244  if (FunctionsWithBodies.empty())
1245    return Error("Insufficient function protos");
1246
1247  Function *Fn = FunctionsWithBodies.back();
1248  FunctionsWithBodies.pop_back();
1249
1250  // Save the current stream state.
1251  uint64_t CurBit = Stream.GetCurrentBitNo();
1252  DeferredFunctionInfo[Fn] = CurBit;
1253
1254  // Skip over the function block for now.
1255  if (Stream.SkipBlock())
1256    return Error("Malformed block record");
1257  return false;
1258}
1259
1260bool BitcodeReader::ParseModule() {
1261  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1262    return Error("Malformed block record");
1263
1264  SmallVector<uint64_t, 64> Record;
1265  std::vector<std::string> SectionTable;
1266  std::vector<std::string> GCTable;
1267
1268  // Read all the records for this module.
1269  while (!Stream.AtEndOfStream()) {
1270    unsigned Code = Stream.ReadCode();
1271    if (Code == bitc::END_BLOCK) {
1272      if (Stream.ReadBlockEnd())
1273        return Error("Error at end of module block");
1274
1275      // Patch the initializers for globals and aliases up.
1276      ResolveGlobalAndAliasInits();
1277      if (!GlobalInits.empty() || !AliasInits.empty())
1278        return Error("Malformed global initializer set");
1279      if (!FunctionsWithBodies.empty())
1280        return Error("Too few function bodies found");
1281
1282      // Look for intrinsic functions which need to be upgraded at some point
1283      for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1284           FI != FE; ++FI) {
1285        Function* NewFn;
1286        if (UpgradeIntrinsicFunction(FI, NewFn))
1287          UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1288      }
1289
1290      // Force deallocation of memory for these vectors to favor the client that
1291      // want lazy deserialization.
1292      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1293      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1294      std::vector<Function*>().swap(FunctionsWithBodies);
1295      return false;
1296    }
1297
1298    if (Code == bitc::ENTER_SUBBLOCK) {
1299      switch (Stream.ReadSubBlockID()) {
1300      default:  // Skip unknown content.
1301        if (Stream.SkipBlock())
1302          return Error("Malformed block record");
1303        break;
1304      case bitc::BLOCKINFO_BLOCK_ID:
1305        if (Stream.ReadBlockInfoBlock())
1306          return Error("Malformed BlockInfoBlock");
1307        break;
1308      case bitc::PARAMATTR_BLOCK_ID:
1309        if (ParseAttributeBlock())
1310          return true;
1311        break;
1312      case bitc::TYPE_BLOCK_ID:
1313        if (ParseTypeTable())
1314          return true;
1315        break;
1316      case bitc::TYPE_SYMTAB_BLOCK_ID:
1317        if (ParseTypeSymbolTable())
1318          return true;
1319        break;
1320      case bitc::VALUE_SYMTAB_BLOCK_ID:
1321        if (ParseValueSymbolTable())
1322          return true;
1323        break;
1324      case bitc::CONSTANTS_BLOCK_ID:
1325        if (ParseConstants() || ResolveGlobalAndAliasInits())
1326          return true;
1327        break;
1328      case bitc::METADATA_BLOCK_ID:
1329        if (ParseMetadata())
1330          return true;
1331        break;
1332      case bitc::FUNCTION_BLOCK_ID:
1333        // If this is the first function body we've seen, reverse the
1334        // FunctionsWithBodies list.
1335        if (!HasReversedFunctionsWithBodies) {
1336          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1337          HasReversedFunctionsWithBodies = true;
1338        }
1339
1340        if (RememberAndSkipFunctionBody())
1341          return true;
1342        break;
1343      }
1344      continue;
1345    }
1346
1347    if (Code == bitc::DEFINE_ABBREV) {
1348      Stream.ReadAbbrevRecord();
1349      continue;
1350    }
1351
1352    // Read a record.
1353    switch (Stream.ReadRecord(Code, Record)) {
1354    default: break;  // Default behavior, ignore unknown content.
1355    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1356      if (Record.size() < 1)
1357        return Error("Malformed MODULE_CODE_VERSION");
1358      // Only version #0 is supported so far.
1359      if (Record[0] != 0)
1360        return Error("Unknown bitstream version!");
1361      break;
1362    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1363      std::string S;
1364      if (ConvertToString(Record, 0, S))
1365        return Error("Invalid MODULE_CODE_TRIPLE record");
1366      TheModule->setTargetTriple(S);
1367      break;
1368    }
1369    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1370      std::string S;
1371      if (ConvertToString(Record, 0, S))
1372        return Error("Invalid MODULE_CODE_DATALAYOUT record");
1373      TheModule->setDataLayout(S);
1374      break;
1375    }
1376    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1377      std::string S;
1378      if (ConvertToString(Record, 0, S))
1379        return Error("Invalid MODULE_CODE_ASM record");
1380      TheModule->setModuleInlineAsm(S);
1381      break;
1382    }
1383    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1384      std::string S;
1385      if (ConvertToString(Record, 0, S))
1386        return Error("Invalid MODULE_CODE_DEPLIB record");
1387      TheModule->addLibrary(S);
1388      break;
1389    }
1390    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1391      std::string S;
1392      if (ConvertToString(Record, 0, S))
1393        return Error("Invalid MODULE_CODE_SECTIONNAME record");
1394      SectionTable.push_back(S);
1395      break;
1396    }
1397    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1398      std::string S;
1399      if (ConvertToString(Record, 0, S))
1400        return Error("Invalid MODULE_CODE_GCNAME record");
1401      GCTable.push_back(S);
1402      break;
1403    }
1404    // GLOBALVAR: [pointer type, isconst, initid,
1405    //             linkage, alignment, section, visibility, threadlocal]
1406    case bitc::MODULE_CODE_GLOBALVAR: {
1407      if (Record.size() < 6)
1408        return Error("Invalid MODULE_CODE_GLOBALVAR record");
1409      const Type *Ty = getTypeByID(Record[0]);
1410      if (!Ty->isPointerTy())
1411        return Error("Global not a pointer type!");
1412      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1413      Ty = cast<PointerType>(Ty)->getElementType();
1414
1415      bool isConstant = Record[1];
1416      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1417      unsigned Alignment = (1 << Record[4]) >> 1;
1418      std::string Section;
1419      if (Record[5]) {
1420        if (Record[5]-1 >= SectionTable.size())
1421          return Error("Invalid section ID");
1422        Section = SectionTable[Record[5]-1];
1423      }
1424      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1425      if (Record.size() > 6)
1426        Visibility = GetDecodedVisibility(Record[6]);
1427      bool isThreadLocal = false;
1428      if (Record.size() > 7)
1429        isThreadLocal = Record[7];
1430
1431      GlobalVariable *NewGV =
1432        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1433                           isThreadLocal, AddressSpace);
1434      NewGV->setAlignment(Alignment);
1435      if (!Section.empty())
1436        NewGV->setSection(Section);
1437      NewGV->setVisibility(Visibility);
1438      NewGV->setThreadLocal(isThreadLocal);
1439
1440      ValueList.push_back(NewGV);
1441
1442      // Remember which value to use for the global initializer.
1443      if (unsigned InitID = Record[2])
1444        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1445      break;
1446    }
1447    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1448    //             alignment, section, visibility, gc]
1449    case bitc::MODULE_CODE_FUNCTION: {
1450      if (Record.size() < 8)
1451        return Error("Invalid MODULE_CODE_FUNCTION record");
1452      const Type *Ty = getTypeByID(Record[0]);
1453      if (!Ty->isPointerTy())
1454        return Error("Function not a pointer type!");
1455      const FunctionType *FTy =
1456        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1457      if (!FTy)
1458        return Error("Function not a pointer to function type!");
1459
1460      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1461                                        "", TheModule);
1462
1463      Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1464      bool isProto = Record[2];
1465      Func->setLinkage(GetDecodedLinkage(Record[3]));
1466      Func->setAttributes(getAttributes(Record[4]));
1467
1468      Func->setAlignment((1 << Record[5]) >> 1);
1469      if (Record[6]) {
1470        if (Record[6]-1 >= SectionTable.size())
1471          return Error("Invalid section ID");
1472        Func->setSection(SectionTable[Record[6]-1]);
1473      }
1474      Func->setVisibility(GetDecodedVisibility(Record[7]));
1475      if (Record.size() > 8 && Record[8]) {
1476        if (Record[8]-1 > GCTable.size())
1477          return Error("Invalid GC ID");
1478        Func->setGC(GCTable[Record[8]-1].c_str());
1479      }
1480      ValueList.push_back(Func);
1481
1482      // If this is a function with a body, remember the prototype we are
1483      // creating now, so that we can match up the body with them later.
1484      if (!isProto)
1485        FunctionsWithBodies.push_back(Func);
1486      break;
1487    }
1488    // ALIAS: [alias type, aliasee val#, linkage]
1489    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1490    case bitc::MODULE_CODE_ALIAS: {
1491      if (Record.size() < 3)
1492        return Error("Invalid MODULE_ALIAS record");
1493      const Type *Ty = getTypeByID(Record[0]);
1494      if (!Ty->isPointerTy())
1495        return Error("Function not a pointer type!");
1496
1497      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1498                                           "", 0, TheModule);
1499      // Old bitcode files didn't have visibility field.
1500      if (Record.size() > 3)
1501        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1502      ValueList.push_back(NewGA);
1503      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1504      break;
1505    }
1506    /// MODULE_CODE_PURGEVALS: [numvals]
1507    case bitc::MODULE_CODE_PURGEVALS:
1508      // Trim down the value list to the specified size.
1509      if (Record.size() < 1 || Record[0] > ValueList.size())
1510        return Error("Invalid MODULE_PURGEVALS record");
1511      ValueList.shrinkTo(Record[0]);
1512      break;
1513    }
1514    Record.clear();
1515  }
1516
1517  return Error("Premature end of bitstream");
1518}
1519
1520bool BitcodeReader::ParseBitcodeInto(Module *M) {
1521  TheModule = 0;
1522
1523  if (Buffer->getBufferSize() & 3)
1524    return Error("Bitcode stream should be a multiple of 4 bytes in length");
1525
1526  unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1527  unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1528
1529  // If we have a wrapper header, parse it and ignore the non-bc file contents.
1530  // The magic number is 0x0B17C0DE stored in little endian.
1531  if (isBitcodeWrapper(BufPtr, BufEnd))
1532    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1533      return Error("Invalid bitcode wrapper header");
1534
1535  StreamFile.init(BufPtr, BufEnd);
1536  Stream.init(StreamFile);
1537
1538  // Sniff for the signature.
1539  if (Stream.Read(8) != 'B' ||
1540      Stream.Read(8) != 'C' ||
1541      Stream.Read(4) != 0x0 ||
1542      Stream.Read(4) != 0xC ||
1543      Stream.Read(4) != 0xE ||
1544      Stream.Read(4) != 0xD)
1545    return Error("Invalid bitcode signature");
1546
1547  // We expect a number of well-defined blocks, though we don't necessarily
1548  // need to understand them all.
1549  while (!Stream.AtEndOfStream()) {
1550    unsigned Code = Stream.ReadCode();
1551
1552    if (Code != bitc::ENTER_SUBBLOCK)
1553      return Error("Invalid record at top-level");
1554
1555    unsigned BlockID = Stream.ReadSubBlockID();
1556
1557    // We only know the MODULE subblock ID.
1558    switch (BlockID) {
1559    case bitc::BLOCKINFO_BLOCK_ID:
1560      if (Stream.ReadBlockInfoBlock())
1561        return Error("Malformed BlockInfoBlock");
1562      break;
1563    case bitc::MODULE_BLOCK_ID:
1564      // Reject multiple MODULE_BLOCK's in a single bitstream.
1565      if (TheModule)
1566        return Error("Multiple MODULE_BLOCKs in same stream");
1567      TheModule = M;
1568      if (ParseModule())
1569        return true;
1570      break;
1571    default:
1572      if (Stream.SkipBlock())
1573        return Error("Malformed block record");
1574      break;
1575    }
1576  }
1577
1578  return false;
1579}
1580
1581/// ParseMetadataAttachment - Parse metadata attachments.
1582bool BitcodeReader::ParseMetadataAttachment() {
1583  if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1584    return Error("Malformed block record");
1585
1586  SmallVector<uint64_t, 64> Record;
1587  while(1) {
1588    unsigned Code = Stream.ReadCode();
1589    if (Code == bitc::END_BLOCK) {
1590      if (Stream.ReadBlockEnd())
1591        return Error("Error at end of PARAMATTR block");
1592      break;
1593    }
1594    if (Code == bitc::DEFINE_ABBREV) {
1595      Stream.ReadAbbrevRecord();
1596      continue;
1597    }
1598    // Read a metadata attachment record.
1599    Record.clear();
1600    switch (Stream.ReadRecord(Code, Record)) {
1601    default:  // Default behavior: ignore.
1602      break;
1603    case bitc::METADATA_ATTACHMENT: {
1604      unsigned RecordLength = Record.size();
1605      if (Record.empty() || (RecordLength - 1) % 2 == 1)
1606        return Error ("Invalid METADATA_ATTACHMENT reader!");
1607      Instruction *Inst = InstructionList[Record[0]];
1608      for (unsigned i = 1; i != RecordLength; i = i+2) {
1609        unsigned Kind = Record[i];
1610        Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1611        Inst->setMetadata(Kind, cast<MDNode>(Node));
1612      }
1613      break;
1614    }
1615    }
1616  }
1617  return false;
1618}
1619
1620/// ParseFunctionBody - Lazily parse the specified function body block.
1621bool BitcodeReader::ParseFunctionBody(Function *F) {
1622  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1623    return Error("Malformed block record");
1624
1625  unsigned ModuleValueListSize = ValueList.size();
1626
1627  // Add all the function arguments to the value table.
1628  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1629    ValueList.push_back(I);
1630
1631  unsigned NextValueNo = ValueList.size();
1632  BasicBlock *CurBB = 0;
1633  unsigned CurBBNo = 0;
1634
1635  // Read all the records.
1636  SmallVector<uint64_t, 64> Record;
1637  while (1) {
1638    unsigned Code = Stream.ReadCode();
1639    if (Code == bitc::END_BLOCK) {
1640      if (Stream.ReadBlockEnd())
1641        return Error("Error at end of function block");
1642      break;
1643    }
1644
1645    if (Code == bitc::ENTER_SUBBLOCK) {
1646      switch (Stream.ReadSubBlockID()) {
1647      default:  // Skip unknown content.
1648        if (Stream.SkipBlock())
1649          return Error("Malformed block record");
1650        break;
1651      case bitc::CONSTANTS_BLOCK_ID:
1652        if (ParseConstants()) return true;
1653        NextValueNo = ValueList.size();
1654        break;
1655      case bitc::VALUE_SYMTAB_BLOCK_ID:
1656        if (ParseValueSymbolTable()) return true;
1657        break;
1658      case bitc::METADATA_ATTACHMENT_ID:
1659        if (ParseMetadataAttachment()) return true;
1660        break;
1661      case bitc::METADATA_BLOCK_ID:
1662        if (ParseMetadata()) return true;
1663        break;
1664      }
1665      continue;
1666    }
1667
1668    if (Code == bitc::DEFINE_ABBREV) {
1669      Stream.ReadAbbrevRecord();
1670      continue;
1671    }
1672
1673    // Read a record.
1674    Record.clear();
1675    Instruction *I = 0;
1676    unsigned BitCode = Stream.ReadRecord(Code, Record);
1677    switch (BitCode) {
1678    default: // Default behavior: reject
1679      return Error("Unknown instruction");
1680    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1681      if (Record.size() < 1 || Record[0] == 0)
1682        return Error("Invalid DECLAREBLOCKS record");
1683      // Create all the basic blocks for the function.
1684      FunctionBBs.resize(Record[0]);
1685      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1686        FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1687      CurBB = FunctionBBs[0];
1688      continue;
1689
1690    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1691      unsigned OpNum = 0;
1692      Value *LHS, *RHS;
1693      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1694          getValue(Record, OpNum, LHS->getType(), RHS) ||
1695          OpNum+1 > Record.size())
1696        return Error("Invalid BINOP record");
1697
1698      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1699      if (Opc == -1) return Error("Invalid BINOP record");
1700      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1701      InstructionList.push_back(I);
1702      if (OpNum < Record.size()) {
1703        if (Opc == Instruction::Add ||
1704            Opc == Instruction::Sub ||
1705            Opc == Instruction::Mul) {
1706          if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1707            cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1708          if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1709            cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1710        } else if (Opc == Instruction::SDiv) {
1711          if (Record[OpNum] & (1 << bitc::SDIV_EXACT))
1712            cast<BinaryOperator>(I)->setIsExact(true);
1713        }
1714      }
1715      break;
1716    }
1717    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1718      unsigned OpNum = 0;
1719      Value *Op;
1720      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1721          OpNum+2 != Record.size())
1722        return Error("Invalid CAST record");
1723
1724      const Type *ResTy = getTypeByID(Record[OpNum]);
1725      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1726      if (Opc == -1 || ResTy == 0)
1727        return Error("Invalid CAST record");
1728      I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1729      InstructionList.push_back(I);
1730      break;
1731    }
1732    case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
1733    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1734      unsigned OpNum = 0;
1735      Value *BasePtr;
1736      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1737        return Error("Invalid GEP record");
1738
1739      SmallVector<Value*, 16> GEPIdx;
1740      while (OpNum != Record.size()) {
1741        Value *Op;
1742        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1743          return Error("Invalid GEP record");
1744        GEPIdx.push_back(Op);
1745      }
1746
1747      I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1748      InstructionList.push_back(I);
1749      if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1750        cast<GetElementPtrInst>(I)->setIsInBounds(true);
1751      break;
1752    }
1753
1754    case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1755                                       // EXTRACTVAL: [opty, opval, n x indices]
1756      unsigned OpNum = 0;
1757      Value *Agg;
1758      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1759        return Error("Invalid EXTRACTVAL record");
1760
1761      SmallVector<unsigned, 4> EXTRACTVALIdx;
1762      for (unsigned RecSize = Record.size();
1763           OpNum != RecSize; ++OpNum) {
1764        uint64_t Index = Record[OpNum];
1765        if ((unsigned)Index != Index)
1766          return Error("Invalid EXTRACTVAL index");
1767        EXTRACTVALIdx.push_back((unsigned)Index);
1768      }
1769
1770      I = ExtractValueInst::Create(Agg,
1771                                   EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1772      InstructionList.push_back(I);
1773      break;
1774    }
1775
1776    case bitc::FUNC_CODE_INST_INSERTVAL: {
1777                           // INSERTVAL: [opty, opval, opty, opval, n x indices]
1778      unsigned OpNum = 0;
1779      Value *Agg;
1780      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1781        return Error("Invalid INSERTVAL record");
1782      Value *Val;
1783      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1784        return Error("Invalid INSERTVAL record");
1785
1786      SmallVector<unsigned, 4> INSERTVALIdx;
1787      for (unsigned RecSize = Record.size();
1788           OpNum != RecSize; ++OpNum) {
1789        uint64_t Index = Record[OpNum];
1790        if ((unsigned)Index != Index)
1791          return Error("Invalid INSERTVAL index");
1792        INSERTVALIdx.push_back((unsigned)Index);
1793      }
1794
1795      I = InsertValueInst::Create(Agg, Val,
1796                                  INSERTVALIdx.begin(), INSERTVALIdx.end());
1797      InstructionList.push_back(I);
1798      break;
1799    }
1800
1801    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1802      // obsolete form of select
1803      // handles select i1 ... in old bitcode
1804      unsigned OpNum = 0;
1805      Value *TrueVal, *FalseVal, *Cond;
1806      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1807          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1808          getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
1809        return Error("Invalid SELECT record");
1810
1811      I = SelectInst::Create(Cond, TrueVal, FalseVal);
1812      InstructionList.push_back(I);
1813      break;
1814    }
1815
1816    case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1817      // new form of select
1818      // handles select i1 or select [N x i1]
1819      unsigned OpNum = 0;
1820      Value *TrueVal, *FalseVal, *Cond;
1821      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1822          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1823          getValueTypePair(Record, OpNum, NextValueNo, Cond))
1824        return Error("Invalid SELECT record");
1825
1826      // select condition can be either i1 or [N x i1]
1827      if (const VectorType* vector_type =
1828          dyn_cast<const VectorType>(Cond->getType())) {
1829        // expect <n x i1>
1830        if (vector_type->getElementType() != Type::getInt1Ty(Context))
1831          return Error("Invalid SELECT condition type");
1832      } else {
1833        // expect i1
1834        if (Cond->getType() != Type::getInt1Ty(Context))
1835          return Error("Invalid SELECT condition type");
1836      }
1837
1838      I = SelectInst::Create(Cond, TrueVal, FalseVal);
1839      InstructionList.push_back(I);
1840      break;
1841    }
1842
1843    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1844      unsigned OpNum = 0;
1845      Value *Vec, *Idx;
1846      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1847          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
1848        return Error("Invalid EXTRACTELT record");
1849      I = ExtractElementInst::Create(Vec, Idx);
1850      InstructionList.push_back(I);
1851      break;
1852    }
1853
1854    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1855      unsigned OpNum = 0;
1856      Value *Vec, *Elt, *Idx;
1857      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1858          getValue(Record, OpNum,
1859                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1860          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
1861        return Error("Invalid INSERTELT record");
1862      I = InsertElementInst::Create(Vec, Elt, Idx);
1863      InstructionList.push_back(I);
1864      break;
1865    }
1866
1867    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1868      unsigned OpNum = 0;
1869      Value *Vec1, *Vec2, *Mask;
1870      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1871          getValue(Record, OpNum, Vec1->getType(), Vec2))
1872        return Error("Invalid SHUFFLEVEC record");
1873
1874      if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
1875        return Error("Invalid SHUFFLEVEC record");
1876      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1877      InstructionList.push_back(I);
1878      break;
1879    }
1880
1881    case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
1882      // Old form of ICmp/FCmp returning bool
1883      // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1884      // both legal on vectors but had different behaviour.
1885    case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1886      // FCmp/ICmp returning bool or vector of bool
1887
1888      unsigned OpNum = 0;
1889      Value *LHS, *RHS;
1890      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1891          getValue(Record, OpNum, LHS->getType(), RHS) ||
1892          OpNum+1 != Record.size())
1893        return Error("Invalid CMP record");
1894
1895      if (LHS->getType()->isFPOrFPVectorTy())
1896        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1897      else
1898        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1899      InstructionList.push_back(I);
1900      break;
1901    }
1902
1903    case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1904      if (Record.size() != 2)
1905        return Error("Invalid GETRESULT record");
1906      unsigned OpNum = 0;
1907      Value *Op;
1908      getValueTypePair(Record, OpNum, NextValueNo, Op);
1909      unsigned Index = Record[1];
1910      I = ExtractValueInst::Create(Op, Index);
1911      InstructionList.push_back(I);
1912      break;
1913    }
1914
1915    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1916      {
1917        unsigned Size = Record.size();
1918        if (Size == 0) {
1919          I = ReturnInst::Create(Context);
1920          InstructionList.push_back(I);
1921          break;
1922        }
1923
1924        unsigned OpNum = 0;
1925        SmallVector<Value *,4> Vs;
1926        do {
1927          Value *Op = NULL;
1928          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1929            return Error("Invalid RET record");
1930          Vs.push_back(Op);
1931        } while(OpNum != Record.size());
1932
1933        const Type *ReturnType = F->getReturnType();
1934        if (Vs.size() > 1 ||
1935            (ReturnType->isStructTy() &&
1936             (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1937          Value *RV = UndefValue::get(ReturnType);
1938          for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1939            I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1940            InstructionList.push_back(I);
1941            CurBB->getInstList().push_back(I);
1942            ValueList.AssignValue(I, NextValueNo++);
1943            RV = I;
1944          }
1945          I = ReturnInst::Create(Context, RV);
1946          InstructionList.push_back(I);
1947          break;
1948        }
1949
1950        I = ReturnInst::Create(Context, Vs[0]);
1951        InstructionList.push_back(I);
1952        break;
1953      }
1954    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1955      if (Record.size() != 1 && Record.size() != 3)
1956        return Error("Invalid BR record");
1957      BasicBlock *TrueDest = getBasicBlock(Record[0]);
1958      if (TrueDest == 0)
1959        return Error("Invalid BR record");
1960
1961      if (Record.size() == 1) {
1962        I = BranchInst::Create(TrueDest);
1963        InstructionList.push_back(I);
1964      }
1965      else {
1966        BasicBlock *FalseDest = getBasicBlock(Record[1]);
1967        Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
1968        if (FalseDest == 0 || Cond == 0)
1969          return Error("Invalid BR record");
1970        I = BranchInst::Create(TrueDest, FalseDest, Cond);
1971        InstructionList.push_back(I);
1972      }
1973      break;
1974    }
1975    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
1976      if (Record.size() < 3 || (Record.size() & 1) == 0)
1977        return Error("Invalid SWITCH record");
1978      const Type *OpTy = getTypeByID(Record[0]);
1979      Value *Cond = getFnValueByID(Record[1], OpTy);
1980      BasicBlock *Default = getBasicBlock(Record[2]);
1981      if (OpTy == 0 || Cond == 0 || Default == 0)
1982        return Error("Invalid SWITCH record");
1983      unsigned NumCases = (Record.size()-3)/2;
1984      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1985      InstructionList.push_back(SI);
1986      for (unsigned i = 0, e = NumCases; i != e; ++i) {
1987        ConstantInt *CaseVal =
1988          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1989        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1990        if (CaseVal == 0 || DestBB == 0) {
1991          delete SI;
1992          return Error("Invalid SWITCH record!");
1993        }
1994        SI->addCase(CaseVal, DestBB);
1995      }
1996      I = SI;
1997      break;
1998    }
1999    case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2000      if (Record.size() < 2)
2001        return Error("Invalid INDIRECTBR record");
2002      const Type *OpTy = getTypeByID(Record[0]);
2003      Value *Address = getFnValueByID(Record[1], OpTy);
2004      if (OpTy == 0 || Address == 0)
2005        return Error("Invalid INDIRECTBR record");
2006      unsigned NumDests = Record.size()-2;
2007      IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2008      InstructionList.push_back(IBI);
2009      for (unsigned i = 0, e = NumDests; i != e; ++i) {
2010        if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2011          IBI->addDestination(DestBB);
2012        } else {
2013          delete IBI;
2014          return Error("Invalid INDIRECTBR record!");
2015        }
2016      }
2017      I = IBI;
2018      break;
2019    }
2020
2021    case bitc::FUNC_CODE_INST_INVOKE: {
2022      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2023      if (Record.size() < 4) return Error("Invalid INVOKE record");
2024      AttrListPtr PAL = getAttributes(Record[0]);
2025      unsigned CCInfo = Record[1];
2026      BasicBlock *NormalBB = getBasicBlock(Record[2]);
2027      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2028
2029      unsigned OpNum = 4;
2030      Value *Callee;
2031      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2032        return Error("Invalid INVOKE record");
2033
2034      const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2035      const FunctionType *FTy = !CalleeTy ? 0 :
2036        dyn_cast<FunctionType>(CalleeTy->getElementType());
2037
2038      // Check that the right number of fixed parameters are here.
2039      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2040          Record.size() < OpNum+FTy->getNumParams())
2041        return Error("Invalid INVOKE record");
2042
2043      SmallVector<Value*, 16> Ops;
2044      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2045        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2046        if (Ops.back() == 0) return Error("Invalid INVOKE record");
2047      }
2048
2049      if (!FTy->isVarArg()) {
2050        if (Record.size() != OpNum)
2051          return Error("Invalid INVOKE record");
2052      } else {
2053        // Read type/value pairs for varargs params.
2054        while (OpNum != Record.size()) {
2055          Value *Op;
2056          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2057            return Error("Invalid INVOKE record");
2058          Ops.push_back(Op);
2059        }
2060      }
2061
2062      I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
2063                             Ops.begin(), Ops.end());
2064      InstructionList.push_back(I);
2065      cast<InvokeInst>(I)->setCallingConv(
2066        static_cast<CallingConv::ID>(CCInfo));
2067      cast<InvokeInst>(I)->setAttributes(PAL);
2068      break;
2069    }
2070    case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
2071      I = new UnwindInst(Context);
2072      InstructionList.push_back(I);
2073      break;
2074    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2075      I = new UnreachableInst(Context);
2076      InstructionList.push_back(I);
2077      break;
2078    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2079      if (Record.size() < 1 || ((Record.size()-1)&1))
2080        return Error("Invalid PHI record");
2081      const Type *Ty = getTypeByID(Record[0]);
2082      if (!Ty) return Error("Invalid PHI record");
2083
2084      PHINode *PN = PHINode::Create(Ty);
2085      InstructionList.push_back(PN);
2086      PN->reserveOperandSpace((Record.size()-1)/2);
2087
2088      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2089        Value *V = getFnValueByID(Record[1+i], Ty);
2090        BasicBlock *BB = getBasicBlock(Record[2+i]);
2091        if (!V || !BB) return Error("Invalid PHI record");
2092        PN->addIncoming(V, BB);
2093      }
2094      I = PN;
2095      break;
2096    }
2097
2098    case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
2099      // Autoupgrade malloc instruction to malloc call.
2100      // FIXME: Remove in LLVM 3.0.
2101      if (Record.size() < 3)
2102        return Error("Invalid MALLOC record");
2103      const PointerType *Ty =
2104        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2105      Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
2106      if (!Ty || !Size) return Error("Invalid MALLOC record");
2107      if (!CurBB) return Error("Invalid malloc instruction with no BB");
2108      const Type *Int32Ty = IntegerType::getInt32Ty(CurBB->getContext());
2109      Constant *AllocSize = ConstantExpr::getSizeOf(Ty->getElementType());
2110      AllocSize = ConstantExpr::getTruncOrBitCast(AllocSize, Int32Ty);
2111      I = CallInst::CreateMalloc(CurBB, Int32Ty, Ty->getElementType(),
2112                                 AllocSize, Size, NULL);
2113      InstructionList.push_back(I);
2114      break;
2115    }
2116    case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
2117      unsigned OpNum = 0;
2118      Value *Op;
2119      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2120          OpNum != Record.size())
2121        return Error("Invalid FREE record");
2122      if (!CurBB) return Error("Invalid free instruction with no BB");
2123      I = CallInst::CreateFree(Op, CurBB);
2124      InstructionList.push_back(I);
2125      break;
2126    }
2127    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
2128      if (Record.size() < 3)
2129        return Error("Invalid ALLOCA record");
2130      const PointerType *Ty =
2131        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2132      Value *Size = getFnValueByID(Record[1], Type::getInt32Ty(Context));
2133      unsigned Align = Record[2];
2134      if (!Ty || !Size) return Error("Invalid ALLOCA record");
2135      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2136      InstructionList.push_back(I);
2137      break;
2138    }
2139    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2140      unsigned OpNum = 0;
2141      Value *Op;
2142      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2143          OpNum+2 != Record.size())
2144        return Error("Invalid LOAD record");
2145
2146      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2147      InstructionList.push_back(I);
2148      break;
2149    }
2150    case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
2151      unsigned OpNum = 0;
2152      Value *Val, *Ptr;
2153      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2154          getValue(Record, OpNum,
2155                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2156          OpNum+2 != Record.size())
2157        return Error("Invalid STORE record");
2158
2159      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2160      InstructionList.push_back(I);
2161      break;
2162    }
2163    case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
2164      // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
2165      unsigned OpNum = 0;
2166      Value *Val, *Ptr;
2167      if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
2168          getValue(Record, OpNum,
2169                   PointerType::getUnqual(Val->getType()), Ptr)||
2170          OpNum+2 != Record.size())
2171        return Error("Invalid STORE record");
2172
2173      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2174      InstructionList.push_back(I);
2175      break;
2176    }
2177    case bitc::FUNC_CODE_INST_CALL: {
2178      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2179      if (Record.size() < 3)
2180        return Error("Invalid CALL record");
2181
2182      AttrListPtr PAL = getAttributes(Record[0]);
2183      unsigned CCInfo = Record[1];
2184
2185      unsigned OpNum = 2;
2186      Value *Callee;
2187      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2188        return Error("Invalid CALL record");
2189
2190      const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2191      const FunctionType *FTy = 0;
2192      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2193      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2194        return Error("Invalid CALL record");
2195
2196      SmallVector<Value*, 16> Args;
2197      // Read the fixed params.
2198      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2199        if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2200          Args.push_back(getBasicBlock(Record[OpNum]));
2201        else
2202          Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2203        if (Args.back() == 0) return Error("Invalid CALL record");
2204      }
2205
2206      // Read type/value pairs for varargs params.
2207      if (!FTy->isVarArg()) {
2208        if (OpNum != Record.size())
2209          return Error("Invalid CALL record");
2210      } else {
2211        while (OpNum != Record.size()) {
2212          Value *Op;
2213          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2214            return Error("Invalid CALL record");
2215          Args.push_back(Op);
2216        }
2217      }
2218
2219      I = CallInst::Create(Callee, Args.begin(), Args.end());
2220      InstructionList.push_back(I);
2221      cast<CallInst>(I)->setCallingConv(
2222        static_cast<CallingConv::ID>(CCInfo>>1));
2223      cast<CallInst>(I)->setTailCall(CCInfo & 1);
2224      cast<CallInst>(I)->setAttributes(PAL);
2225      break;
2226    }
2227    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2228      if (Record.size() < 3)
2229        return Error("Invalid VAARG record");
2230      const Type *OpTy = getTypeByID(Record[0]);
2231      Value *Op = getFnValueByID(Record[1], OpTy);
2232      const Type *ResTy = getTypeByID(Record[2]);
2233      if (!OpTy || !Op || !ResTy)
2234        return Error("Invalid VAARG record");
2235      I = new VAArgInst(Op, ResTy);
2236      InstructionList.push_back(I);
2237      break;
2238    }
2239    }
2240
2241    // Add instruction to end of current BB.  If there is no current BB, reject
2242    // this file.
2243    if (CurBB == 0) {
2244      delete I;
2245      return Error("Invalid instruction with no BB");
2246    }
2247    CurBB->getInstList().push_back(I);
2248
2249    // If this was a terminator instruction, move to the next block.
2250    if (isa<TerminatorInst>(I)) {
2251      ++CurBBNo;
2252      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2253    }
2254
2255    // Non-void values get registered in the value table for future use.
2256    if (I && !I->getType()->isVoidTy())
2257      ValueList.AssignValue(I, NextValueNo++);
2258  }
2259
2260  // Check the function list for unresolved values.
2261  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2262    if (A->getParent() == 0) {
2263      // We found at least one unresolved value.  Nuke them all to avoid leaks.
2264      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2265        if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
2266          A->replaceAllUsesWith(UndefValue::get(A->getType()));
2267          delete A;
2268        }
2269      }
2270      return Error("Never resolved value found in function!");
2271    }
2272  }
2273
2274  // See if anything took the address of blocks in this function.  If so,
2275  // resolve them now.
2276  /// BlockAddrFwdRefs - These are blockaddr references to basic blocks.  These
2277  /// are resolved lazily when functions are loaded.
2278  DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2279    BlockAddrFwdRefs.find(F);
2280  if (BAFRI != BlockAddrFwdRefs.end()) {
2281    std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2282    for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2283      unsigned BlockIdx = RefList[i].first;
2284      if (BlockIdx >= FunctionBBs.size())
2285        return Error("Invalid blockaddress block #");
2286
2287      GlobalVariable *FwdRef = RefList[i].second;
2288      FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2289      FwdRef->eraseFromParent();
2290    }
2291
2292    BlockAddrFwdRefs.erase(BAFRI);
2293  }
2294
2295  // Trim the value list down to the size it was before we parsed this function.
2296  ValueList.shrinkTo(ModuleValueListSize);
2297  std::vector<BasicBlock*>().swap(FunctionBBs);
2298
2299  return false;
2300}
2301
2302//===----------------------------------------------------------------------===//
2303// GVMaterializer implementation
2304//===----------------------------------------------------------------------===//
2305
2306
2307bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2308  if (const Function *F = dyn_cast<Function>(GV)) {
2309    return F->isDeclaration() &&
2310      DeferredFunctionInfo.count(const_cast<Function*>(F));
2311  }
2312  return false;
2313}
2314
2315bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2316  Function *F = dyn_cast<Function>(GV);
2317  // If it's not a function or is already material, ignore the request.
2318  if (!F || !F->isMaterializable()) return false;
2319
2320  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2321  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2322
2323  // Move the bit stream to the saved position of the deferred function body.
2324  Stream.JumpToBit(DFII->second);
2325
2326  if (ParseFunctionBody(F)) {
2327    if (ErrInfo) *ErrInfo = ErrorString;
2328    return true;
2329  }
2330
2331  // Upgrade any old intrinsic calls in the function.
2332  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2333       E = UpgradedIntrinsics.end(); I != E; ++I) {
2334    if (I->first != I->second) {
2335      for (Value::use_iterator UI = I->first->use_begin(),
2336           UE = I->first->use_end(); UI != UE; ) {
2337        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2338          UpgradeIntrinsicCall(CI, I->second);
2339      }
2340    }
2341  }
2342
2343  return false;
2344}
2345
2346bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2347  const Function *F = dyn_cast<Function>(GV);
2348  if (!F || F->isDeclaration())
2349    return false;
2350  return DeferredFunctionInfo.count(const_cast<Function*>(F));
2351}
2352
2353void BitcodeReader::Dematerialize(GlobalValue *GV) {
2354  Function *F = dyn_cast<Function>(GV);
2355  // If this function isn't dematerializable, this is a noop.
2356  if (!F || !isDematerializable(F))
2357    return;
2358
2359  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2360
2361  // Just forget the function body, we can remat it later.
2362  F->deleteBody();
2363}
2364
2365
2366bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2367  assert(M == TheModule &&
2368         "Can only Materialize the Module this BitcodeReader is attached to.");
2369  // Iterate over the module, deserializing any functions that are still on
2370  // disk.
2371  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2372       F != E; ++F)
2373    if (F->isMaterializable() &&
2374        Materialize(F, ErrInfo))
2375      return true;
2376
2377  // Upgrade any intrinsic calls that slipped through (should not happen!) and
2378  // delete the old functions to clean up. We can't do this unless the entire
2379  // module is materialized because there could always be another function body
2380  // with calls to the old function.
2381  for (std::vector<std::pair<Function*, Function*> >::iterator I =
2382       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2383    if (I->first != I->second) {
2384      for (Value::use_iterator UI = I->first->use_begin(),
2385           UE = I->first->use_end(); UI != UE; ) {
2386        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2387          UpgradeIntrinsicCall(CI, I->second);
2388      }
2389      if (!I->first->use_empty())
2390        I->first->replaceAllUsesWith(I->second);
2391      I->first->eraseFromParent();
2392    }
2393  }
2394  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2395
2396  // Check debug info intrinsics.
2397  CheckDebugInfoIntrinsics(TheModule);
2398
2399  return false;
2400}
2401
2402
2403//===----------------------------------------------------------------------===//
2404// External interface
2405//===----------------------------------------------------------------------===//
2406
2407/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2408///
2409Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2410                                   LLVMContext& Context,
2411                                   std::string *ErrMsg) {
2412  Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2413  BitcodeReader *R = new BitcodeReader(Buffer, Context);
2414  M->setMaterializer(R);
2415  if (R->ParseBitcodeInto(M)) {
2416    if (ErrMsg)
2417      *ErrMsg = R->getErrorString();
2418
2419    delete M;  // Also deletes R.
2420    return 0;
2421  }
2422  // Have the BitcodeReader dtor delete 'Buffer'.
2423  R->setBufferOwned(true);
2424  return M;
2425}
2426
2427/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2428/// If an error occurs, return null and fill in *ErrMsg if non-null.
2429Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2430                               std::string *ErrMsg){
2431  Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2432  if (!M) return 0;
2433
2434  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2435  // there was an error.
2436  static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2437
2438  // Read in the entire module, and destroy the BitcodeReader.
2439  if (M->MaterializeAllPermanently(ErrMsg)) {
2440    delete M;
2441    return NULL;
2442  }
2443  return M;
2444}
2445