BitcodeReader.cpp revision efd08d413c077956478fbde90fd65aa6f179bb39
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/DataStream.h"
26#include "llvm/Support/MathExtras.h"
27#include "llvm/Support/MemoryBuffer.h"
28#include "llvm/OperandTraits.h"
29using namespace llvm;
30
31enum {
32  SWITCH_INST_MAGIC = 0x4B5 // May 2012 => 1205 => Hex
33};
34
35void BitcodeReader::materializeForwardReferencedFunctions() {
36  while (!BlockAddrFwdRefs.empty()) {
37    Function *F = BlockAddrFwdRefs.begin()->first;
38    F->Materialize();
39  }
40}
41
42void BitcodeReader::FreeState() {
43  if (BufferOwned)
44    delete Buffer;
45  Buffer = 0;
46  std::vector<Type*>().swap(TypeList);
47  ValueList.clear();
48  MDValueList.clear();
49
50  std::vector<AttrListPtr>().swap(MAttributes);
51  std::vector<BasicBlock*>().swap(FunctionBBs);
52  std::vector<Function*>().swap(FunctionsWithBodies);
53  DeferredFunctionInfo.clear();
54  MDKindMap.clear();
55
56  assert(BlockAddrFwdRefs.empty() && "Unresolved blockaddress fwd references");
57}
58
59//===----------------------------------------------------------------------===//
60//  Helper functions to implement forward reference resolution, etc.
61//===----------------------------------------------------------------------===//
62
63/// ConvertToString - Convert a string from a record into an std::string, return
64/// true on failure.
65template<typename StrTy>
66static bool ConvertToString(ArrayRef<uint64_t> Record, unsigned Idx,
67                            StrTy &Result) {
68  if (Idx > Record.size())
69    return true;
70
71  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
72    Result += (char)Record[i];
73  return false;
74}
75
76static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
77  switch (Val) {
78  default: // Map unknown/new linkages to external
79  case 0:  return GlobalValue::ExternalLinkage;
80  case 1:  return GlobalValue::WeakAnyLinkage;
81  case 2:  return GlobalValue::AppendingLinkage;
82  case 3:  return GlobalValue::InternalLinkage;
83  case 4:  return GlobalValue::LinkOnceAnyLinkage;
84  case 5:  return GlobalValue::DLLImportLinkage;
85  case 6:  return GlobalValue::DLLExportLinkage;
86  case 7:  return GlobalValue::ExternalWeakLinkage;
87  case 8:  return GlobalValue::CommonLinkage;
88  case 9:  return GlobalValue::PrivateLinkage;
89  case 10: return GlobalValue::WeakODRLinkage;
90  case 11: return GlobalValue::LinkOnceODRLinkage;
91  case 12: return GlobalValue::AvailableExternallyLinkage;
92  case 13: return GlobalValue::LinkerPrivateLinkage;
93  case 14: return GlobalValue::LinkerPrivateWeakLinkage;
94  case 15: return GlobalValue::LinkOnceODRAutoHideLinkage;
95  }
96}
97
98static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
99  switch (Val) {
100  default: // Map unknown visibilities to default.
101  case 0: return GlobalValue::DefaultVisibility;
102  case 1: return GlobalValue::HiddenVisibility;
103  case 2: return GlobalValue::ProtectedVisibility;
104  }
105}
106
107static GlobalVariable::ThreadLocalMode GetDecodedThreadLocalMode(unsigned Val) {
108  switch (Val) {
109    case 0: return GlobalVariable::NotThreadLocal;
110    default: // Map unknown non-zero value to general dynamic.
111    case 1: return GlobalVariable::GeneralDynamicTLSModel;
112    case 2: return GlobalVariable::LocalDynamicTLSModel;
113    case 3: return GlobalVariable::InitialExecTLSModel;
114    case 4: return GlobalVariable::LocalExecTLSModel;
115  }
116}
117
118static int GetDecodedCastOpcode(unsigned Val) {
119  switch (Val) {
120  default: return -1;
121  case bitc::CAST_TRUNC   : return Instruction::Trunc;
122  case bitc::CAST_ZEXT    : return Instruction::ZExt;
123  case bitc::CAST_SEXT    : return Instruction::SExt;
124  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
125  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
126  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
127  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
128  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
129  case bitc::CAST_FPEXT   : return Instruction::FPExt;
130  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
131  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
132  case bitc::CAST_BITCAST : return Instruction::BitCast;
133  }
134}
135static int GetDecodedBinaryOpcode(unsigned Val, Type *Ty) {
136  switch (Val) {
137  default: return -1;
138  case bitc::BINOP_ADD:
139    return Ty->isFPOrFPVectorTy() ? Instruction::FAdd : Instruction::Add;
140  case bitc::BINOP_SUB:
141    return Ty->isFPOrFPVectorTy() ? Instruction::FSub : Instruction::Sub;
142  case bitc::BINOP_MUL:
143    return Ty->isFPOrFPVectorTy() ? Instruction::FMul : Instruction::Mul;
144  case bitc::BINOP_UDIV: return Instruction::UDiv;
145  case bitc::BINOP_SDIV:
146    return Ty->isFPOrFPVectorTy() ? Instruction::FDiv : Instruction::SDiv;
147  case bitc::BINOP_UREM: return Instruction::URem;
148  case bitc::BINOP_SREM:
149    return Ty->isFPOrFPVectorTy() ? Instruction::FRem : Instruction::SRem;
150  case bitc::BINOP_SHL:  return Instruction::Shl;
151  case bitc::BINOP_LSHR: return Instruction::LShr;
152  case bitc::BINOP_ASHR: return Instruction::AShr;
153  case bitc::BINOP_AND:  return Instruction::And;
154  case bitc::BINOP_OR:   return Instruction::Or;
155  case bitc::BINOP_XOR:  return Instruction::Xor;
156  }
157}
158
159static AtomicRMWInst::BinOp GetDecodedRMWOperation(unsigned Val) {
160  switch (Val) {
161  default: return AtomicRMWInst::BAD_BINOP;
162  case bitc::RMW_XCHG: return AtomicRMWInst::Xchg;
163  case bitc::RMW_ADD: return AtomicRMWInst::Add;
164  case bitc::RMW_SUB: return AtomicRMWInst::Sub;
165  case bitc::RMW_AND: return AtomicRMWInst::And;
166  case bitc::RMW_NAND: return AtomicRMWInst::Nand;
167  case bitc::RMW_OR: return AtomicRMWInst::Or;
168  case bitc::RMW_XOR: return AtomicRMWInst::Xor;
169  case bitc::RMW_MAX: return AtomicRMWInst::Max;
170  case bitc::RMW_MIN: return AtomicRMWInst::Min;
171  case bitc::RMW_UMAX: return AtomicRMWInst::UMax;
172  case bitc::RMW_UMIN: return AtomicRMWInst::UMin;
173  }
174}
175
176static AtomicOrdering GetDecodedOrdering(unsigned Val) {
177  switch (Val) {
178  case bitc::ORDERING_NOTATOMIC: return NotAtomic;
179  case bitc::ORDERING_UNORDERED: return Unordered;
180  case bitc::ORDERING_MONOTONIC: return Monotonic;
181  case bitc::ORDERING_ACQUIRE: return Acquire;
182  case bitc::ORDERING_RELEASE: return Release;
183  case bitc::ORDERING_ACQREL: return AcquireRelease;
184  default: // Map unknown orderings to sequentially-consistent.
185  case bitc::ORDERING_SEQCST: return SequentiallyConsistent;
186  }
187}
188
189static SynchronizationScope GetDecodedSynchScope(unsigned Val) {
190  switch (Val) {
191  case bitc::SYNCHSCOPE_SINGLETHREAD: return SingleThread;
192  default: // Map unknown scopes to cross-thread.
193  case bitc::SYNCHSCOPE_CROSSTHREAD: return CrossThread;
194  }
195}
196
197namespace llvm {
198namespace {
199  /// @brief A class for maintaining the slot number definition
200  /// as a placeholder for the actual definition for forward constants defs.
201  class ConstantPlaceHolder : public ConstantExpr {
202    void operator=(const ConstantPlaceHolder &) LLVM_DELETED_FUNCTION;
203  public:
204    // allocate space for exactly one operand
205    void *operator new(size_t s) {
206      return User::operator new(s, 1);
207    }
208    explicit ConstantPlaceHolder(Type *Ty, LLVMContext& Context)
209      : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
210      Op<0>() = UndefValue::get(Type::getInt32Ty(Context));
211    }
212
213    /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
214    static bool classof(const Value *V) {
215      return isa<ConstantExpr>(V) &&
216             cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
217    }
218
219
220    /// Provide fast operand accessors
221    //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
222  };
223}
224
225// FIXME: can we inherit this from ConstantExpr?
226template <>
227struct OperandTraits<ConstantPlaceHolder> :
228  public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
229};
230}
231
232
233void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
234  if (Idx == size()) {
235    push_back(V);
236    return;
237  }
238
239  if (Idx >= size())
240    resize(Idx+1);
241
242  WeakVH &OldV = ValuePtrs[Idx];
243  if (OldV == 0) {
244    OldV = V;
245    return;
246  }
247
248  // Handle constants and non-constants (e.g. instrs) differently for
249  // efficiency.
250  if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
251    ResolveConstants.push_back(std::make_pair(PHC, Idx));
252    OldV = V;
253  } else {
254    // If there was a forward reference to this value, replace it.
255    Value *PrevVal = OldV;
256    OldV->replaceAllUsesWith(V);
257    delete PrevVal;
258  }
259}
260
261
262Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
263                                                    Type *Ty) {
264  if (Idx >= size())
265    resize(Idx + 1);
266
267  if (Value *V = ValuePtrs[Idx]) {
268    assert(Ty == V->getType() && "Type mismatch in constant table!");
269    return cast<Constant>(V);
270  }
271
272  // Create and return a placeholder, which will later be RAUW'd.
273  Constant *C = new ConstantPlaceHolder(Ty, Context);
274  ValuePtrs[Idx] = C;
275  return C;
276}
277
278Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
279  if (Idx >= size())
280    resize(Idx + 1);
281
282  if (Value *V = ValuePtrs[Idx]) {
283    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
284    return V;
285  }
286
287  // No type specified, must be invalid reference.
288  if (Ty == 0) return 0;
289
290  // Create and return a placeholder, which will later be RAUW'd.
291  Value *V = new Argument(Ty);
292  ValuePtrs[Idx] = V;
293  return V;
294}
295
296/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
297/// resolves any forward references.  The idea behind this is that we sometimes
298/// get constants (such as large arrays) which reference *many* forward ref
299/// constants.  Replacing each of these causes a lot of thrashing when
300/// building/reuniquing the constant.  Instead of doing this, we look at all the
301/// uses and rewrite all the place holders at once for any constant that uses
302/// a placeholder.
303void BitcodeReaderValueList::ResolveConstantForwardRefs() {
304  // Sort the values by-pointer so that they are efficient to look up with a
305  // binary search.
306  std::sort(ResolveConstants.begin(), ResolveConstants.end());
307
308  SmallVector<Constant*, 64> NewOps;
309
310  while (!ResolveConstants.empty()) {
311    Value *RealVal = operator[](ResolveConstants.back().second);
312    Constant *Placeholder = ResolveConstants.back().first;
313    ResolveConstants.pop_back();
314
315    // Loop over all users of the placeholder, updating them to reference the
316    // new value.  If they reference more than one placeholder, update them all
317    // at once.
318    while (!Placeholder->use_empty()) {
319      Value::use_iterator UI = Placeholder->use_begin();
320      User *U = *UI;
321
322      // If the using object isn't uniqued, just update the operands.  This
323      // handles instructions and initializers for global variables.
324      if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
325        UI.getUse().set(RealVal);
326        continue;
327      }
328
329      // Otherwise, we have a constant that uses the placeholder.  Replace that
330      // constant with a new constant that has *all* placeholder uses updated.
331      Constant *UserC = cast<Constant>(U);
332      for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
333           I != E; ++I) {
334        Value *NewOp;
335        if (!isa<ConstantPlaceHolder>(*I)) {
336          // Not a placeholder reference.
337          NewOp = *I;
338        } else if (*I == Placeholder) {
339          // Common case is that it just references this one placeholder.
340          NewOp = RealVal;
341        } else {
342          // Otherwise, look up the placeholder in ResolveConstants.
343          ResolveConstantsTy::iterator It =
344            std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
345                             std::pair<Constant*, unsigned>(cast<Constant>(*I),
346                                                            0));
347          assert(It != ResolveConstants.end() && It->first == *I);
348          NewOp = operator[](It->second);
349        }
350
351        NewOps.push_back(cast<Constant>(NewOp));
352      }
353
354      // Make the new constant.
355      Constant *NewC;
356      if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
357        NewC = ConstantArray::get(UserCA->getType(), NewOps);
358      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
359        NewC = ConstantStruct::get(UserCS->getType(), NewOps);
360      } else if (isa<ConstantVector>(UserC)) {
361        NewC = ConstantVector::get(NewOps);
362      } else {
363        assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
364        NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
365      }
366
367      UserC->replaceAllUsesWith(NewC);
368      UserC->destroyConstant();
369      NewOps.clear();
370    }
371
372    // Update all ValueHandles, they should be the only users at this point.
373    Placeholder->replaceAllUsesWith(RealVal);
374    delete Placeholder;
375  }
376}
377
378void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
379  if (Idx == size()) {
380    push_back(V);
381    return;
382  }
383
384  if (Idx >= size())
385    resize(Idx+1);
386
387  WeakVH &OldV = MDValuePtrs[Idx];
388  if (OldV == 0) {
389    OldV = V;
390    return;
391  }
392
393  // If there was a forward reference to this value, replace it.
394  MDNode *PrevVal = cast<MDNode>(OldV);
395  OldV->replaceAllUsesWith(V);
396  MDNode::deleteTemporary(PrevVal);
397  // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
398  // value for Idx.
399  MDValuePtrs[Idx] = V;
400}
401
402Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
403  if (Idx >= size())
404    resize(Idx + 1);
405
406  if (Value *V = MDValuePtrs[Idx]) {
407    assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
408    return V;
409  }
410
411  // Create and return a placeholder, which will later be RAUW'd.
412  Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
413  MDValuePtrs[Idx] = V;
414  return V;
415}
416
417Type *BitcodeReader::getTypeByID(unsigned ID) {
418  // The type table size is always specified correctly.
419  if (ID >= TypeList.size())
420    return 0;
421
422  if (Type *Ty = TypeList[ID])
423    return Ty;
424
425  // If we have a forward reference, the only possible case is when it is to a
426  // named struct.  Just create a placeholder for now.
427  return TypeList[ID] = StructType::create(Context);
428}
429
430
431//===----------------------------------------------------------------------===//
432//  Functions for parsing blocks from the bitcode file
433//===----------------------------------------------------------------------===//
434
435bool BitcodeReader::ParseAttributeBlock() {
436  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
437    return Error("Malformed block record");
438
439  if (!MAttributes.empty())
440    return Error("Multiple PARAMATTR blocks found!");
441
442  SmallVector<uint64_t, 64> Record;
443
444  SmallVector<AttributeWithIndex, 8> Attrs;
445
446  // Read all the records.
447  while (1) {
448    unsigned Code = Stream.ReadCode();
449    if (Code == bitc::END_BLOCK) {
450      if (Stream.ReadBlockEnd())
451        return Error("Error at end of PARAMATTR block");
452      return false;
453    }
454
455    if (Code == bitc::ENTER_SUBBLOCK) {
456      // No known subblocks, always skip them.
457      Stream.ReadSubBlockID();
458      if (Stream.SkipBlock())
459        return Error("Malformed block record");
460      continue;
461    }
462
463    if (Code == bitc::DEFINE_ABBREV) {
464      Stream.ReadAbbrevRecord();
465      continue;
466    }
467
468    // Read a record.
469    Record.clear();
470    switch (Stream.ReadRecord(Code, Record)) {
471    default:  // Default behavior: ignore.
472      break;
473    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
474      if (Record.size() & 1)
475        return Error("Invalid ENTRY record");
476
477      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
478        Attributes ReconstitutedAttr =
479          Attributes::decodeLLVMAttributesForBitcode(Context, Record[i+1]);
480        Record[i+1] = ReconstitutedAttr.Raw();
481      }
482
483      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
484        AttrBuilder B(Record[i+1]);
485        if (B.hasAttributes())
486          Attrs.push_back(AttributeWithIndex::get(Record[i],
487                                                  Attributes::get(Context, B)));
488      }
489
490      MAttributes.push_back(AttrListPtr::get(Context, Attrs));
491      Attrs.clear();
492      break;
493    }
494    }
495  }
496}
497
498bool BitcodeReader::ParseTypeTable() {
499  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID_NEW))
500    return Error("Malformed block record");
501
502  return ParseTypeTableBody();
503}
504
505bool BitcodeReader::ParseTypeTableBody() {
506  if (!TypeList.empty())
507    return Error("Multiple TYPE_BLOCKs found!");
508
509  SmallVector<uint64_t, 64> Record;
510  unsigned NumRecords = 0;
511
512  SmallString<64> TypeName;
513
514  // Read all the records for this type table.
515  while (1) {
516    unsigned Code = Stream.ReadCode();
517    if (Code == bitc::END_BLOCK) {
518      if (NumRecords != TypeList.size())
519        return Error("Invalid type forward reference in TYPE_BLOCK");
520      if (Stream.ReadBlockEnd())
521        return Error("Error at end of type table block");
522      return false;
523    }
524
525    if (Code == bitc::ENTER_SUBBLOCK) {
526      // No known subblocks, always skip them.
527      Stream.ReadSubBlockID();
528      if (Stream.SkipBlock())
529        return Error("Malformed block record");
530      continue;
531    }
532
533    if (Code == bitc::DEFINE_ABBREV) {
534      Stream.ReadAbbrevRecord();
535      continue;
536    }
537
538    // Read a record.
539    Record.clear();
540    Type *ResultTy = 0;
541    switch (Stream.ReadRecord(Code, Record)) {
542    default: return Error("unknown type in type table");
543    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
544      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
545      // type list.  This allows us to reserve space.
546      if (Record.size() < 1)
547        return Error("Invalid TYPE_CODE_NUMENTRY record");
548      TypeList.resize(Record[0]);
549      continue;
550    case bitc::TYPE_CODE_VOID:      // VOID
551      ResultTy = Type::getVoidTy(Context);
552      break;
553    case bitc::TYPE_CODE_HALF:     // HALF
554      ResultTy = Type::getHalfTy(Context);
555      break;
556    case bitc::TYPE_CODE_FLOAT:     // FLOAT
557      ResultTy = Type::getFloatTy(Context);
558      break;
559    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
560      ResultTy = Type::getDoubleTy(Context);
561      break;
562    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
563      ResultTy = Type::getX86_FP80Ty(Context);
564      break;
565    case bitc::TYPE_CODE_FP128:     // FP128
566      ResultTy = Type::getFP128Ty(Context);
567      break;
568    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
569      ResultTy = Type::getPPC_FP128Ty(Context);
570      break;
571    case bitc::TYPE_CODE_LABEL:     // LABEL
572      ResultTy = Type::getLabelTy(Context);
573      break;
574    case bitc::TYPE_CODE_METADATA:  // METADATA
575      ResultTy = Type::getMetadataTy(Context);
576      break;
577    case bitc::TYPE_CODE_X86_MMX:   // X86_MMX
578      ResultTy = Type::getX86_MMXTy(Context);
579      break;
580    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
581      if (Record.size() < 1)
582        return Error("Invalid Integer type record");
583
584      ResultTy = IntegerType::get(Context, Record[0]);
585      break;
586    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
587                                    //          [pointee type, address space]
588      if (Record.size() < 1)
589        return Error("Invalid POINTER type record");
590      unsigned AddressSpace = 0;
591      if (Record.size() == 2)
592        AddressSpace = Record[1];
593      ResultTy = getTypeByID(Record[0]);
594      if (ResultTy == 0) return Error("invalid element type in pointer type");
595      ResultTy = PointerType::get(ResultTy, AddressSpace);
596      break;
597    }
598    case bitc::TYPE_CODE_FUNCTION_OLD: {
599      // FIXME: attrid is dead, remove it in LLVM 4.0
600      // FUNCTION: [vararg, attrid, retty, paramty x N]
601      if (Record.size() < 3)
602        return Error("Invalid FUNCTION type record");
603      SmallVector<Type*, 8> ArgTys;
604      for (unsigned i = 3, e = Record.size(); i != e; ++i) {
605        if (Type *T = getTypeByID(Record[i]))
606          ArgTys.push_back(T);
607        else
608          break;
609      }
610
611      ResultTy = getTypeByID(Record[2]);
612      if (ResultTy == 0 || ArgTys.size() < Record.size()-3)
613        return Error("invalid type in function type");
614
615      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
616      break;
617    }
618    case bitc::TYPE_CODE_FUNCTION: {
619      // FUNCTION: [vararg, retty, paramty x N]
620      if (Record.size() < 2)
621        return Error("Invalid FUNCTION type record");
622      SmallVector<Type*, 8> ArgTys;
623      for (unsigned i = 2, e = Record.size(); i != e; ++i) {
624        if (Type *T = getTypeByID(Record[i]))
625          ArgTys.push_back(T);
626        else
627          break;
628      }
629
630      ResultTy = getTypeByID(Record[1]);
631      if (ResultTy == 0 || ArgTys.size() < Record.size()-2)
632        return Error("invalid type in function type");
633
634      ResultTy = FunctionType::get(ResultTy, ArgTys, Record[0]);
635      break;
636    }
637    case bitc::TYPE_CODE_STRUCT_ANON: {  // STRUCT: [ispacked, eltty x N]
638      if (Record.size() < 1)
639        return Error("Invalid STRUCT type record");
640      SmallVector<Type*, 8> EltTys;
641      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
642        if (Type *T = getTypeByID(Record[i]))
643          EltTys.push_back(T);
644        else
645          break;
646      }
647      if (EltTys.size() != Record.size()-1)
648        return Error("invalid type in struct type");
649      ResultTy = StructType::get(Context, EltTys, Record[0]);
650      break;
651    }
652    case bitc::TYPE_CODE_STRUCT_NAME:   // STRUCT_NAME: [strchr x N]
653      if (ConvertToString(Record, 0, TypeName))
654        return Error("Invalid STRUCT_NAME record");
655      continue;
656
657    case bitc::TYPE_CODE_STRUCT_NAMED: { // STRUCT: [ispacked, eltty x N]
658      if (Record.size() < 1)
659        return Error("Invalid STRUCT type record");
660
661      if (NumRecords >= TypeList.size())
662        return Error("invalid TYPE table");
663
664      // Check to see if this was forward referenced, if so fill in the temp.
665      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
666      if (Res) {
667        Res->setName(TypeName);
668        TypeList[NumRecords] = 0;
669      } else  // Otherwise, create a new struct.
670        Res = StructType::create(Context, TypeName);
671      TypeName.clear();
672
673      SmallVector<Type*, 8> EltTys;
674      for (unsigned i = 1, e = Record.size(); i != e; ++i) {
675        if (Type *T = getTypeByID(Record[i]))
676          EltTys.push_back(T);
677        else
678          break;
679      }
680      if (EltTys.size() != Record.size()-1)
681        return Error("invalid STRUCT type record");
682      Res->setBody(EltTys, Record[0]);
683      ResultTy = Res;
684      break;
685    }
686    case bitc::TYPE_CODE_OPAQUE: {       // OPAQUE: []
687      if (Record.size() != 1)
688        return Error("Invalid OPAQUE type record");
689
690      if (NumRecords >= TypeList.size())
691        return Error("invalid TYPE table");
692
693      // Check to see if this was forward referenced, if so fill in the temp.
694      StructType *Res = cast_or_null<StructType>(TypeList[NumRecords]);
695      if (Res) {
696        Res->setName(TypeName);
697        TypeList[NumRecords] = 0;
698      } else  // Otherwise, create a new struct with no body.
699        Res = StructType::create(Context, TypeName);
700      TypeName.clear();
701      ResultTy = Res;
702      break;
703    }
704    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
705      if (Record.size() < 2)
706        return Error("Invalid ARRAY type record");
707      if ((ResultTy = getTypeByID(Record[1])))
708        ResultTy = ArrayType::get(ResultTy, Record[0]);
709      else
710        return Error("Invalid ARRAY type element");
711      break;
712    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
713      if (Record.size() < 2)
714        return Error("Invalid VECTOR type record");
715      if ((ResultTy = getTypeByID(Record[1])))
716        ResultTy = VectorType::get(ResultTy, Record[0]);
717      else
718        return Error("Invalid ARRAY type element");
719      break;
720    }
721
722    if (NumRecords >= TypeList.size())
723      return Error("invalid TYPE table");
724    assert(ResultTy && "Didn't read a type?");
725    assert(TypeList[NumRecords] == 0 && "Already read type?");
726    TypeList[NumRecords++] = ResultTy;
727  }
728}
729
730bool BitcodeReader::ParseValueSymbolTable() {
731  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
732    return Error("Malformed block record");
733
734  SmallVector<uint64_t, 64> Record;
735
736  // Read all the records for this value table.
737  SmallString<128> ValueName;
738  while (1) {
739    unsigned Code = Stream.ReadCode();
740    if (Code == bitc::END_BLOCK) {
741      if (Stream.ReadBlockEnd())
742        return Error("Error at end of value symbol table block");
743      return false;
744    }
745    if (Code == bitc::ENTER_SUBBLOCK) {
746      // No known subblocks, always skip them.
747      Stream.ReadSubBlockID();
748      if (Stream.SkipBlock())
749        return Error("Malformed block record");
750      continue;
751    }
752
753    if (Code == bitc::DEFINE_ABBREV) {
754      Stream.ReadAbbrevRecord();
755      continue;
756    }
757
758    // Read a record.
759    Record.clear();
760    switch (Stream.ReadRecord(Code, Record)) {
761    default:  // Default behavior: unknown type.
762      break;
763    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
764      if (ConvertToString(Record, 1, ValueName))
765        return Error("Invalid VST_ENTRY record");
766      unsigned ValueID = Record[0];
767      if (ValueID >= ValueList.size())
768        return Error("Invalid Value ID in VST_ENTRY record");
769      Value *V = ValueList[ValueID];
770
771      V->setName(StringRef(ValueName.data(), ValueName.size()));
772      ValueName.clear();
773      break;
774    }
775    case bitc::VST_CODE_BBENTRY: {
776      if (ConvertToString(Record, 1, ValueName))
777        return Error("Invalid VST_BBENTRY record");
778      BasicBlock *BB = getBasicBlock(Record[0]);
779      if (BB == 0)
780        return Error("Invalid BB ID in VST_BBENTRY record");
781
782      BB->setName(StringRef(ValueName.data(), ValueName.size()));
783      ValueName.clear();
784      break;
785    }
786    }
787  }
788}
789
790bool BitcodeReader::ParseMetadata() {
791  unsigned NextMDValueNo = MDValueList.size();
792
793  if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
794    return Error("Malformed block record");
795
796  SmallVector<uint64_t, 64> Record;
797
798  // Read all the records.
799  while (1) {
800    unsigned Code = Stream.ReadCode();
801    if (Code == bitc::END_BLOCK) {
802      if (Stream.ReadBlockEnd())
803        return Error("Error at end of PARAMATTR block");
804      return false;
805    }
806
807    if (Code == bitc::ENTER_SUBBLOCK) {
808      // No known subblocks, always skip them.
809      Stream.ReadSubBlockID();
810      if (Stream.SkipBlock())
811        return Error("Malformed block record");
812      continue;
813    }
814
815    if (Code == bitc::DEFINE_ABBREV) {
816      Stream.ReadAbbrevRecord();
817      continue;
818    }
819
820    bool IsFunctionLocal = false;
821    // Read a record.
822    Record.clear();
823    Code = Stream.ReadRecord(Code, Record);
824    switch (Code) {
825    default:  // Default behavior: ignore.
826      break;
827    case bitc::METADATA_NAME: {
828      // Read named of the named metadata.
829      SmallString<8> Name(Record.begin(), Record.end());
830      Record.clear();
831      Code = Stream.ReadCode();
832
833      // METADATA_NAME is always followed by METADATA_NAMED_NODE.
834      unsigned NextBitCode = Stream.ReadRecord(Code, Record);
835      assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
836
837      // Read named metadata elements.
838      unsigned Size = Record.size();
839      NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
840      for (unsigned i = 0; i != Size; ++i) {
841        MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
842        if (MD == 0)
843          return Error("Malformed metadata record");
844        NMD->addOperand(MD);
845      }
846      break;
847    }
848    case bitc::METADATA_FN_NODE:
849      IsFunctionLocal = true;
850      // fall-through
851    case bitc::METADATA_NODE: {
852      if (Record.size() % 2 == 1)
853        return Error("Invalid METADATA_NODE record");
854
855      unsigned Size = Record.size();
856      SmallVector<Value*, 8> Elts;
857      for (unsigned i = 0; i != Size; i += 2) {
858        Type *Ty = getTypeByID(Record[i]);
859        if (!Ty) return Error("Invalid METADATA_NODE record");
860        if (Ty->isMetadataTy())
861          Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
862        else if (!Ty->isVoidTy())
863          Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
864        else
865          Elts.push_back(NULL);
866      }
867      Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
868      IsFunctionLocal = false;
869      MDValueList.AssignValue(V, NextMDValueNo++);
870      break;
871    }
872    case bitc::METADATA_STRING: {
873      SmallString<8> String(Record.begin(), Record.end());
874      Value *V = MDString::get(Context, String);
875      MDValueList.AssignValue(V, NextMDValueNo++);
876      break;
877    }
878    case bitc::METADATA_KIND: {
879      if (Record.size() < 2)
880        return Error("Invalid METADATA_KIND record");
881
882      unsigned Kind = Record[0];
883      SmallString<8> Name(Record.begin()+1, Record.end());
884
885      unsigned NewKind = TheModule->getMDKindID(Name.str());
886      if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
887        return Error("Conflicting METADATA_KIND records");
888      break;
889    }
890    }
891  }
892}
893
894/// decodeSignRotatedValue - Decode a signed value stored with the sign bit in
895/// the LSB for dense VBR encoding.
896uint64_t BitcodeReader::decodeSignRotatedValue(uint64_t V) {
897  if ((V & 1) == 0)
898    return V >> 1;
899  if (V != 1)
900    return -(V >> 1);
901  // There is no such thing as -0 with integers.  "-0" really means MININT.
902  return 1ULL << 63;
903}
904
905/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
906/// values and aliases that we can.
907bool BitcodeReader::ResolveGlobalAndAliasInits() {
908  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
909  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
910
911  GlobalInitWorklist.swap(GlobalInits);
912  AliasInitWorklist.swap(AliasInits);
913
914  while (!GlobalInitWorklist.empty()) {
915    unsigned ValID = GlobalInitWorklist.back().second;
916    if (ValID >= ValueList.size()) {
917      // Not ready to resolve this yet, it requires something later in the file.
918      GlobalInits.push_back(GlobalInitWorklist.back());
919    } else {
920      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
921        GlobalInitWorklist.back().first->setInitializer(C);
922      else
923        return Error("Global variable initializer is not a constant!");
924    }
925    GlobalInitWorklist.pop_back();
926  }
927
928  while (!AliasInitWorklist.empty()) {
929    unsigned ValID = AliasInitWorklist.back().second;
930    if (ValID >= ValueList.size()) {
931      AliasInits.push_back(AliasInitWorklist.back());
932    } else {
933      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
934        AliasInitWorklist.back().first->setAliasee(C);
935      else
936        return Error("Alias initializer is not a constant!");
937    }
938    AliasInitWorklist.pop_back();
939  }
940  return false;
941}
942
943static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
944  SmallVector<uint64_t, 8> Words(Vals.size());
945  std::transform(Vals.begin(), Vals.end(), Words.begin(),
946                 BitcodeReader::decodeSignRotatedValue);
947
948  return APInt(TypeBits, Words);
949}
950
951bool BitcodeReader::ParseConstants() {
952  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
953    return Error("Malformed block record");
954
955  SmallVector<uint64_t, 64> Record;
956
957  // Read all the records for this value table.
958  Type *CurTy = Type::getInt32Ty(Context);
959  unsigned NextCstNo = ValueList.size();
960  while (1) {
961    unsigned Code = Stream.ReadCode();
962    if (Code == bitc::END_BLOCK)
963      break;
964
965    if (Code == bitc::ENTER_SUBBLOCK) {
966      // No known subblocks, always skip them.
967      Stream.ReadSubBlockID();
968      if (Stream.SkipBlock())
969        return Error("Malformed block record");
970      continue;
971    }
972
973    if (Code == bitc::DEFINE_ABBREV) {
974      Stream.ReadAbbrevRecord();
975      continue;
976    }
977
978    // Read a record.
979    Record.clear();
980    Value *V = 0;
981    unsigned BitCode = Stream.ReadRecord(Code, Record);
982    switch (BitCode) {
983    default:  // Default behavior: unknown constant
984    case bitc::CST_CODE_UNDEF:     // UNDEF
985      V = UndefValue::get(CurTy);
986      break;
987    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
988      if (Record.empty())
989        return Error("Malformed CST_SETTYPE record");
990      if (Record[0] >= TypeList.size())
991        return Error("Invalid Type ID in CST_SETTYPE record");
992      CurTy = TypeList[Record[0]];
993      continue;  // Skip the ValueList manipulation.
994    case bitc::CST_CODE_NULL:      // NULL
995      V = Constant::getNullValue(CurTy);
996      break;
997    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
998      if (!CurTy->isIntegerTy() || Record.empty())
999        return Error("Invalid CST_INTEGER record");
1000      V = ConstantInt::get(CurTy, decodeSignRotatedValue(Record[0]));
1001      break;
1002    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1003      if (!CurTy->isIntegerTy() || Record.empty())
1004        return Error("Invalid WIDE_INTEGER record");
1005
1006      APInt VInt = ReadWideAPInt(Record,
1007                                 cast<IntegerType>(CurTy)->getBitWidth());
1008      V = ConstantInt::get(Context, VInt);
1009
1010      break;
1011    }
1012    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1013      if (Record.empty())
1014        return Error("Invalid FLOAT record");
1015      if (CurTy->isHalfTy())
1016        V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1017      else if (CurTy->isFloatTy())
1018        V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1019      else if (CurTy->isDoubleTy())
1020        V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1021      else if (CurTy->isX86_FP80Ty()) {
1022        // Bits are not stored the same way as a normal i80 APInt, compensate.
1023        uint64_t Rearrange[2];
1024        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1025        Rearrange[1] = Record[0] >> 48;
1026        V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1027      } else if (CurTy->isFP128Ty())
1028        V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1029      else if (CurTy->isPPC_FP128Ty())
1030        V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1031      else
1032        V = UndefValue::get(CurTy);
1033      break;
1034    }
1035
1036    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1037      if (Record.empty())
1038        return Error("Invalid CST_AGGREGATE record");
1039
1040      unsigned Size = Record.size();
1041      SmallVector<Constant*, 16> Elts;
1042
1043      if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1044        for (unsigned i = 0; i != Size; ++i)
1045          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1046                                                     STy->getElementType(i)));
1047        V = ConstantStruct::get(STy, Elts);
1048      } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1049        Type *EltTy = ATy->getElementType();
1050        for (unsigned i = 0; i != Size; ++i)
1051          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1052        V = ConstantArray::get(ATy, Elts);
1053      } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1054        Type *EltTy = VTy->getElementType();
1055        for (unsigned i = 0; i != Size; ++i)
1056          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1057        V = ConstantVector::get(Elts);
1058      } else {
1059        V = UndefValue::get(CurTy);
1060      }
1061      break;
1062    }
1063    case bitc::CST_CODE_STRING:    // STRING: [values]
1064    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1065      if (Record.empty())
1066        return Error("Invalid CST_STRING record");
1067
1068      SmallString<16> Elts(Record.begin(), Record.end());
1069      V = ConstantDataArray::getString(Context, Elts,
1070                                       BitCode == bitc::CST_CODE_CSTRING);
1071      break;
1072    }
1073    case bitc::CST_CODE_DATA: {// DATA: [n x value]
1074      if (Record.empty())
1075        return Error("Invalid CST_DATA record");
1076
1077      Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1078      unsigned Size = Record.size();
1079
1080      if (EltTy->isIntegerTy(8)) {
1081        SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1082        if (isa<VectorType>(CurTy))
1083          V = ConstantDataVector::get(Context, Elts);
1084        else
1085          V = ConstantDataArray::get(Context, Elts);
1086      } else if (EltTy->isIntegerTy(16)) {
1087        SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1088        if (isa<VectorType>(CurTy))
1089          V = ConstantDataVector::get(Context, Elts);
1090        else
1091          V = ConstantDataArray::get(Context, Elts);
1092      } else if (EltTy->isIntegerTy(32)) {
1093        SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1094        if (isa<VectorType>(CurTy))
1095          V = ConstantDataVector::get(Context, Elts);
1096        else
1097          V = ConstantDataArray::get(Context, Elts);
1098      } else if (EltTy->isIntegerTy(64)) {
1099        SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1100        if (isa<VectorType>(CurTy))
1101          V = ConstantDataVector::get(Context, Elts);
1102        else
1103          V = ConstantDataArray::get(Context, Elts);
1104      } else if (EltTy->isFloatTy()) {
1105        SmallVector<float, 16> Elts(Size);
1106        std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1107        if (isa<VectorType>(CurTy))
1108          V = ConstantDataVector::get(Context, Elts);
1109        else
1110          V = ConstantDataArray::get(Context, Elts);
1111      } else if (EltTy->isDoubleTy()) {
1112        SmallVector<double, 16> Elts(Size);
1113        std::transform(Record.begin(), Record.end(), Elts.begin(),
1114                       BitsToDouble);
1115        if (isa<VectorType>(CurTy))
1116          V = ConstantDataVector::get(Context, Elts);
1117        else
1118          V = ConstantDataArray::get(Context, Elts);
1119      } else {
1120        return Error("Unknown element type in CE_DATA");
1121      }
1122      break;
1123    }
1124
1125    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1126      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1127      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1128      if (Opc < 0) {
1129        V = UndefValue::get(CurTy);  // Unknown binop.
1130      } else {
1131        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1132        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1133        unsigned Flags = 0;
1134        if (Record.size() >= 4) {
1135          if (Opc == Instruction::Add ||
1136              Opc == Instruction::Sub ||
1137              Opc == Instruction::Mul ||
1138              Opc == Instruction::Shl) {
1139            if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1140              Flags |= OverflowingBinaryOperator::NoSignedWrap;
1141            if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1142              Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1143          } else if (Opc == Instruction::SDiv ||
1144                     Opc == Instruction::UDiv ||
1145                     Opc == Instruction::LShr ||
1146                     Opc == Instruction::AShr) {
1147            if (Record[3] & (1 << bitc::PEO_EXACT))
1148              Flags |= SDivOperator::IsExact;
1149          }
1150        }
1151        V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1152      }
1153      break;
1154    }
1155    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1156      if (Record.size() < 3) return Error("Invalid CE_CAST record");
1157      int Opc = GetDecodedCastOpcode(Record[0]);
1158      if (Opc < 0) {
1159        V = UndefValue::get(CurTy);  // Unknown cast.
1160      } else {
1161        Type *OpTy = getTypeByID(Record[1]);
1162        if (!OpTy) return Error("Invalid CE_CAST record");
1163        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1164        V = ConstantExpr::getCast(Opc, Op, CurTy);
1165      }
1166      break;
1167    }
1168    case bitc::CST_CODE_CE_INBOUNDS_GEP:
1169    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1170      if (Record.size() & 1) return Error("Invalid CE_GEP record");
1171      SmallVector<Constant*, 16> Elts;
1172      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1173        Type *ElTy = getTypeByID(Record[i]);
1174        if (!ElTy) return Error("Invalid CE_GEP record");
1175        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1176      }
1177      ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1178      V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1179                                         BitCode ==
1180                                           bitc::CST_CODE_CE_INBOUNDS_GEP);
1181      break;
1182    }
1183    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1184      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1185      V = ConstantExpr::getSelect(
1186                          ValueList.getConstantFwdRef(Record[0],
1187                                                      Type::getInt1Ty(Context)),
1188                          ValueList.getConstantFwdRef(Record[1],CurTy),
1189                          ValueList.getConstantFwdRef(Record[2],CurTy));
1190      break;
1191    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1192      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1193      VectorType *OpTy =
1194        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1195      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1196      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1197      Constant *Op1 = ValueList.getConstantFwdRef(Record[2],
1198                                                  Type::getInt32Ty(Context));
1199      V = ConstantExpr::getExtractElement(Op0, Op1);
1200      break;
1201    }
1202    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1203      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1204      if (Record.size() < 3 || OpTy == 0)
1205        return Error("Invalid CE_INSERTELT record");
1206      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1207      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1208                                                  OpTy->getElementType());
1209      Constant *Op2 = ValueList.getConstantFwdRef(Record[2],
1210                                                  Type::getInt32Ty(Context));
1211      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1212      break;
1213    }
1214    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1215      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1216      if (Record.size() < 3 || OpTy == 0)
1217        return Error("Invalid CE_SHUFFLEVEC record");
1218      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1219      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1220      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1221                                                 OpTy->getNumElements());
1222      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1223      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1224      break;
1225    }
1226    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1227      VectorType *RTy = dyn_cast<VectorType>(CurTy);
1228      VectorType *OpTy =
1229        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1230      if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1231        return Error("Invalid CE_SHUFVEC_EX record");
1232      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1233      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1234      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1235                                                 RTy->getNumElements());
1236      Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1237      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1238      break;
1239    }
1240    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1241      if (Record.size() < 4) return Error("Invalid CE_CMP record");
1242      Type *OpTy = getTypeByID(Record[0]);
1243      if (OpTy == 0) return Error("Invalid CE_CMP record");
1244      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1245      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1246
1247      if (OpTy->isFPOrFPVectorTy())
1248        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1249      else
1250        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1251      break;
1252    }
1253    // This maintains backward compatibility, pre-asm dialect keywords.
1254    // FIXME: Remove with the 4.0 release.
1255    case bitc::CST_CODE_INLINEASM_OLD: {
1256      if (Record.size() < 2) return Error("Invalid INLINEASM record");
1257      std::string AsmStr, ConstrStr;
1258      bool HasSideEffects = Record[0] & 1;
1259      bool IsAlignStack = Record[0] >> 1;
1260      unsigned AsmStrSize = Record[1];
1261      if (2+AsmStrSize >= Record.size())
1262        return Error("Invalid INLINEASM record");
1263      unsigned ConstStrSize = Record[2+AsmStrSize];
1264      if (3+AsmStrSize+ConstStrSize > Record.size())
1265        return Error("Invalid INLINEASM record");
1266
1267      for (unsigned i = 0; i != AsmStrSize; ++i)
1268        AsmStr += (char)Record[2+i];
1269      for (unsigned i = 0; i != ConstStrSize; ++i)
1270        ConstrStr += (char)Record[3+AsmStrSize+i];
1271      PointerType *PTy = cast<PointerType>(CurTy);
1272      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1273                         AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1274      break;
1275    }
1276    // This version adds support for the asm dialect keywords (e.g.,
1277    // inteldialect).
1278    case bitc::CST_CODE_INLINEASM: {
1279      if (Record.size() < 2) return Error("Invalid INLINEASM record");
1280      std::string AsmStr, ConstrStr;
1281      bool HasSideEffects = Record[0] & 1;
1282      bool IsAlignStack = (Record[0] >> 1) & 1;
1283      unsigned AsmDialect = Record[0] >> 2;
1284      unsigned AsmStrSize = Record[1];
1285      if (2+AsmStrSize >= Record.size())
1286        return Error("Invalid INLINEASM record");
1287      unsigned ConstStrSize = Record[2+AsmStrSize];
1288      if (3+AsmStrSize+ConstStrSize > Record.size())
1289        return Error("Invalid INLINEASM record");
1290
1291      for (unsigned i = 0; i != AsmStrSize; ++i)
1292        AsmStr += (char)Record[2+i];
1293      for (unsigned i = 0; i != ConstStrSize; ++i)
1294        ConstrStr += (char)Record[3+AsmStrSize+i];
1295      PointerType *PTy = cast<PointerType>(CurTy);
1296      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1297                         AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1298                         InlineAsm::AsmDialect(AsmDialect));
1299      break;
1300    }
1301    case bitc::CST_CODE_BLOCKADDRESS:{
1302      if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1303      Type *FnTy = getTypeByID(Record[0]);
1304      if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1305      Function *Fn =
1306        dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1307      if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1308
1309      // If the function is already parsed we can insert the block address right
1310      // away.
1311      if (!Fn->empty()) {
1312        Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1313        for (size_t I = 0, E = Record[2]; I != E; ++I) {
1314          if (BBI == BBE)
1315            return Error("Invalid blockaddress block #");
1316          ++BBI;
1317        }
1318        V = BlockAddress::get(Fn, BBI);
1319      } else {
1320        // Otherwise insert a placeholder and remember it so it can be inserted
1321        // when the function is parsed.
1322        GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1323                                                    Type::getInt8Ty(Context),
1324                                            false, GlobalValue::InternalLinkage,
1325                                                    0, "");
1326        BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1327        V = FwdRef;
1328      }
1329      break;
1330    }
1331    }
1332
1333    ValueList.AssignValue(V, NextCstNo);
1334    ++NextCstNo;
1335  }
1336
1337  if (NextCstNo != ValueList.size())
1338    return Error("Invalid constant reference!");
1339
1340  if (Stream.ReadBlockEnd())
1341    return Error("Error at end of constants block");
1342
1343  // Once all the constants have been read, go through and resolve forward
1344  // references.
1345  ValueList.ResolveConstantForwardRefs();
1346  return false;
1347}
1348
1349bool BitcodeReader::ParseUseLists() {
1350  if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1351    return Error("Malformed block record");
1352
1353  SmallVector<uint64_t, 64> Record;
1354
1355  // Read all the records.
1356  while (1) {
1357    unsigned Code = Stream.ReadCode();
1358    if (Code == bitc::END_BLOCK) {
1359      if (Stream.ReadBlockEnd())
1360        return Error("Error at end of use-list table block");
1361      return false;
1362    }
1363
1364    if (Code == bitc::ENTER_SUBBLOCK) {
1365      // No known subblocks, always skip them.
1366      Stream.ReadSubBlockID();
1367      if (Stream.SkipBlock())
1368        return Error("Malformed block record");
1369      continue;
1370    }
1371
1372    if (Code == bitc::DEFINE_ABBREV) {
1373      Stream.ReadAbbrevRecord();
1374      continue;
1375    }
1376
1377    // Read a use list record.
1378    Record.clear();
1379    switch (Stream.ReadRecord(Code, Record)) {
1380    default:  // Default behavior: unknown type.
1381      break;
1382    case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1383      unsigned RecordLength = Record.size();
1384      if (RecordLength < 1)
1385        return Error ("Invalid UseList reader!");
1386      UseListRecords.push_back(Record);
1387      break;
1388    }
1389    }
1390  }
1391}
1392
1393/// RememberAndSkipFunctionBody - When we see the block for a function body,
1394/// remember where it is and then skip it.  This lets us lazily deserialize the
1395/// functions.
1396bool BitcodeReader::RememberAndSkipFunctionBody() {
1397  // Get the function we are talking about.
1398  if (FunctionsWithBodies.empty())
1399    return Error("Insufficient function protos");
1400
1401  Function *Fn = FunctionsWithBodies.back();
1402  FunctionsWithBodies.pop_back();
1403
1404  // Save the current stream state.
1405  uint64_t CurBit = Stream.GetCurrentBitNo();
1406  DeferredFunctionInfo[Fn] = CurBit;
1407
1408  // Skip over the function block for now.
1409  if (Stream.SkipBlock())
1410    return Error("Malformed block record");
1411  return false;
1412}
1413
1414bool BitcodeReader::GlobalCleanup() {
1415  // Patch the initializers for globals and aliases up.
1416  ResolveGlobalAndAliasInits();
1417  if (!GlobalInits.empty() || !AliasInits.empty())
1418    return Error("Malformed global initializer set");
1419
1420  // Look for intrinsic functions which need to be upgraded at some point
1421  for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1422       FI != FE; ++FI) {
1423    Function *NewFn;
1424    if (UpgradeIntrinsicFunction(FI, NewFn))
1425      UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1426  }
1427
1428  // Look for global variables which need to be renamed.
1429  for (Module::global_iterator
1430         GI = TheModule->global_begin(), GE = TheModule->global_end();
1431       GI != GE; ++GI)
1432    UpgradeGlobalVariable(GI);
1433  // Force deallocation of memory for these vectors to favor the client that
1434  // want lazy deserialization.
1435  std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1436  std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1437  return false;
1438}
1439
1440bool BitcodeReader::ParseModule(bool Resume) {
1441  if (Resume)
1442    Stream.JumpToBit(NextUnreadBit);
1443  else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1444    return Error("Malformed block record");
1445
1446  SmallVector<uint64_t, 64> Record;
1447  std::vector<std::string> SectionTable;
1448  std::vector<std::string> GCTable;
1449
1450  // Read all the records for this module.
1451  while (!Stream.AtEndOfStream()) {
1452    unsigned Code = Stream.ReadCode();
1453    if (Code == bitc::END_BLOCK) {
1454      if (Stream.ReadBlockEnd())
1455        return Error("Error at end of module block");
1456
1457      return GlobalCleanup();
1458    }
1459
1460    if (Code == bitc::ENTER_SUBBLOCK) {
1461      switch (Stream.ReadSubBlockID()) {
1462      default:  // Skip unknown content.
1463        if (Stream.SkipBlock())
1464          return Error("Malformed block record");
1465        break;
1466      case bitc::BLOCKINFO_BLOCK_ID:
1467        if (Stream.ReadBlockInfoBlock())
1468          return Error("Malformed BlockInfoBlock");
1469        break;
1470      case bitc::PARAMATTR_BLOCK_ID:
1471        if (ParseAttributeBlock())
1472          return true;
1473        break;
1474      case bitc::TYPE_BLOCK_ID_NEW:
1475        if (ParseTypeTable())
1476          return true;
1477        break;
1478      case bitc::VALUE_SYMTAB_BLOCK_ID:
1479        if (ParseValueSymbolTable())
1480          return true;
1481        SeenValueSymbolTable = true;
1482        break;
1483      case bitc::CONSTANTS_BLOCK_ID:
1484        if (ParseConstants() || ResolveGlobalAndAliasInits())
1485          return true;
1486        break;
1487      case bitc::METADATA_BLOCK_ID:
1488        if (ParseMetadata())
1489          return true;
1490        break;
1491      case bitc::FUNCTION_BLOCK_ID:
1492        // If this is the first function body we've seen, reverse the
1493        // FunctionsWithBodies list.
1494        if (!SeenFirstFunctionBody) {
1495          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1496          if (GlobalCleanup())
1497            return true;
1498          SeenFirstFunctionBody = true;
1499        }
1500
1501        if (RememberAndSkipFunctionBody())
1502          return true;
1503        // For streaming bitcode, suspend parsing when we reach the function
1504        // bodies. Subsequent materialization calls will resume it when
1505        // necessary. For streaming, the function bodies must be at the end of
1506        // the bitcode. If the bitcode file is old, the symbol table will be
1507        // at the end instead and will not have been seen yet. In this case,
1508        // just finish the parse now.
1509        if (LazyStreamer && SeenValueSymbolTable) {
1510          NextUnreadBit = Stream.GetCurrentBitNo();
1511          return false;
1512        }
1513        break;
1514      case bitc::USELIST_BLOCK_ID:
1515        if (ParseUseLists())
1516          return true;
1517        break;
1518      }
1519      continue;
1520    }
1521
1522    if (Code == bitc::DEFINE_ABBREV) {
1523      Stream.ReadAbbrevRecord();
1524      continue;
1525    }
1526
1527    // Read a record.
1528    switch (Stream.ReadRecord(Code, Record)) {
1529    default: break;  // Default behavior, ignore unknown content.
1530    case bitc::MODULE_CODE_VERSION: {  // VERSION: [version#]
1531      if (Record.size() < 1)
1532        return Error("Malformed MODULE_CODE_VERSION");
1533      // Only version #0 and #1 are supported so far.
1534      unsigned module_version = Record[0];
1535      switch (module_version) {
1536        default: return Error("Unknown bitstream version!");
1537        case 0:
1538          UseRelativeIDs = false;
1539          break;
1540        case 1:
1541          UseRelativeIDs = true;
1542          break;
1543      }
1544      break;
1545    }
1546    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1547      std::string S;
1548      if (ConvertToString(Record, 0, S))
1549        return Error("Invalid MODULE_CODE_TRIPLE record");
1550      TheModule->setTargetTriple(S);
1551      break;
1552    }
1553    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1554      std::string S;
1555      if (ConvertToString(Record, 0, S))
1556        return Error("Invalid MODULE_CODE_DATALAYOUT record");
1557      TheModule->setDataLayout(S);
1558      break;
1559    }
1560    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1561      std::string S;
1562      if (ConvertToString(Record, 0, S))
1563        return Error("Invalid MODULE_CODE_ASM record");
1564      TheModule->setModuleInlineAsm(S);
1565      break;
1566    }
1567    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1568      std::string S;
1569      if (ConvertToString(Record, 0, S))
1570        return Error("Invalid MODULE_CODE_SECTIONNAME record");
1571      SectionTable.push_back(S);
1572      break;
1573    }
1574    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1575      std::string S;
1576      if (ConvertToString(Record, 0, S))
1577        return Error("Invalid MODULE_CODE_GCNAME record");
1578      GCTable.push_back(S);
1579      break;
1580    }
1581    // GLOBALVAR: [pointer type, isconst, initid,
1582    //             linkage, alignment, section, visibility, threadlocal,
1583    //             unnamed_addr]
1584    case bitc::MODULE_CODE_GLOBALVAR: {
1585      if (Record.size() < 6)
1586        return Error("Invalid MODULE_CODE_GLOBALVAR record");
1587      Type *Ty = getTypeByID(Record[0]);
1588      if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1589      if (!Ty->isPointerTy())
1590        return Error("Global not a pointer type!");
1591      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1592      Ty = cast<PointerType>(Ty)->getElementType();
1593
1594      bool isConstant = Record[1];
1595      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1596      unsigned Alignment = (1 << Record[4]) >> 1;
1597      std::string Section;
1598      if (Record[5]) {
1599        if (Record[5]-1 >= SectionTable.size())
1600          return Error("Invalid section ID");
1601        Section = SectionTable[Record[5]-1];
1602      }
1603      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1604      if (Record.size() > 6)
1605        Visibility = GetDecodedVisibility(Record[6]);
1606
1607      GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1608      if (Record.size() > 7)
1609        TLM = GetDecodedThreadLocalMode(Record[7]);
1610
1611      bool UnnamedAddr = false;
1612      if (Record.size() > 8)
1613        UnnamedAddr = Record[8];
1614
1615      GlobalVariable *NewGV =
1616        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1617                           TLM, AddressSpace);
1618      NewGV->setAlignment(Alignment);
1619      if (!Section.empty())
1620        NewGV->setSection(Section);
1621      NewGV->setVisibility(Visibility);
1622      NewGV->setUnnamedAddr(UnnamedAddr);
1623
1624      ValueList.push_back(NewGV);
1625
1626      // Remember which value to use for the global initializer.
1627      if (unsigned InitID = Record[2])
1628        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1629      break;
1630    }
1631    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1632    //             alignment, section, visibility, gc, unnamed_addr]
1633    case bitc::MODULE_CODE_FUNCTION: {
1634      if (Record.size() < 8)
1635        return Error("Invalid MODULE_CODE_FUNCTION record");
1636      Type *Ty = getTypeByID(Record[0]);
1637      if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1638      if (!Ty->isPointerTy())
1639        return Error("Function not a pointer type!");
1640      FunctionType *FTy =
1641        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1642      if (!FTy)
1643        return Error("Function not a pointer to function type!");
1644
1645      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1646                                        "", TheModule);
1647
1648      Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1649      bool isProto = Record[2];
1650      Func->setLinkage(GetDecodedLinkage(Record[3]));
1651      Func->setAttributes(getAttributes(Record[4]));
1652
1653      Func->setAlignment((1 << Record[5]) >> 1);
1654      if (Record[6]) {
1655        if (Record[6]-1 >= SectionTable.size())
1656          return Error("Invalid section ID");
1657        Func->setSection(SectionTable[Record[6]-1]);
1658      }
1659      Func->setVisibility(GetDecodedVisibility(Record[7]));
1660      if (Record.size() > 8 && Record[8]) {
1661        if (Record[8]-1 > GCTable.size())
1662          return Error("Invalid GC ID");
1663        Func->setGC(GCTable[Record[8]-1].c_str());
1664      }
1665      bool UnnamedAddr = false;
1666      if (Record.size() > 9)
1667        UnnamedAddr = Record[9];
1668      Func->setUnnamedAddr(UnnamedAddr);
1669      ValueList.push_back(Func);
1670
1671      // If this is a function with a body, remember the prototype we are
1672      // creating now, so that we can match up the body with them later.
1673      if (!isProto) {
1674        FunctionsWithBodies.push_back(Func);
1675        if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1676      }
1677      break;
1678    }
1679    // ALIAS: [alias type, aliasee val#, linkage]
1680    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1681    case bitc::MODULE_CODE_ALIAS: {
1682      if (Record.size() < 3)
1683        return Error("Invalid MODULE_ALIAS record");
1684      Type *Ty = getTypeByID(Record[0]);
1685      if (!Ty) return Error("Invalid MODULE_ALIAS record");
1686      if (!Ty->isPointerTy())
1687        return Error("Function not a pointer type!");
1688
1689      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1690                                           "", 0, TheModule);
1691      // Old bitcode files didn't have visibility field.
1692      if (Record.size() > 3)
1693        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1694      ValueList.push_back(NewGA);
1695      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1696      break;
1697    }
1698    /// MODULE_CODE_PURGEVALS: [numvals]
1699    case bitc::MODULE_CODE_PURGEVALS:
1700      // Trim down the value list to the specified size.
1701      if (Record.size() < 1 || Record[0] > ValueList.size())
1702        return Error("Invalid MODULE_PURGEVALS record");
1703      ValueList.shrinkTo(Record[0]);
1704      break;
1705    }
1706    Record.clear();
1707  }
1708
1709  return Error("Premature end of bitstream");
1710}
1711
1712bool BitcodeReader::ParseBitcodeInto(Module *M) {
1713  TheModule = 0;
1714
1715  if (InitStream()) return true;
1716
1717  // Sniff for the signature.
1718  if (Stream.Read(8) != 'B' ||
1719      Stream.Read(8) != 'C' ||
1720      Stream.Read(4) != 0x0 ||
1721      Stream.Read(4) != 0xC ||
1722      Stream.Read(4) != 0xE ||
1723      Stream.Read(4) != 0xD)
1724    return Error("Invalid bitcode signature");
1725
1726  // We expect a number of well-defined blocks, though we don't necessarily
1727  // need to understand them all.
1728  while (!Stream.AtEndOfStream()) {
1729    unsigned Code = Stream.ReadCode();
1730
1731    if (Code != bitc::ENTER_SUBBLOCK) {
1732
1733      // The ranlib in xcode 4 will align archive members by appending newlines
1734      // to the end of them. If this file size is a multiple of 4 but not 8, we
1735      // have to read and ignore these final 4 bytes :-(
1736      if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1737          Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1738          Stream.AtEndOfStream())
1739        return false;
1740
1741      return Error("Invalid record at top-level");
1742    }
1743
1744    unsigned BlockID = Stream.ReadSubBlockID();
1745
1746    // We only know the MODULE subblock ID.
1747    switch (BlockID) {
1748    case bitc::BLOCKINFO_BLOCK_ID:
1749      if (Stream.ReadBlockInfoBlock())
1750        return Error("Malformed BlockInfoBlock");
1751      break;
1752    case bitc::MODULE_BLOCK_ID:
1753      // Reject multiple MODULE_BLOCK's in a single bitstream.
1754      if (TheModule)
1755        return Error("Multiple MODULE_BLOCKs in same stream");
1756      TheModule = M;
1757      if (ParseModule(false))
1758        return true;
1759      if (LazyStreamer) return false;
1760      break;
1761    default:
1762      if (Stream.SkipBlock())
1763        return Error("Malformed block record");
1764      break;
1765    }
1766  }
1767
1768  return false;
1769}
1770
1771bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1772  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1773    return Error("Malformed block record");
1774
1775  SmallVector<uint64_t, 64> Record;
1776
1777  // Read all the records for this module.
1778  while (!Stream.AtEndOfStream()) {
1779    unsigned Code = Stream.ReadCode();
1780    if (Code == bitc::END_BLOCK) {
1781      if (Stream.ReadBlockEnd())
1782        return Error("Error at end of module block");
1783
1784      return false;
1785    }
1786
1787    if (Code == bitc::ENTER_SUBBLOCK) {
1788      switch (Stream.ReadSubBlockID()) {
1789      default:  // Skip unknown content.
1790        if (Stream.SkipBlock())
1791          return Error("Malformed block record");
1792        break;
1793      }
1794      continue;
1795    }
1796
1797    if (Code == bitc::DEFINE_ABBREV) {
1798      Stream.ReadAbbrevRecord();
1799      continue;
1800    }
1801
1802    // Read a record.
1803    switch (Stream.ReadRecord(Code, Record)) {
1804    default: break;  // Default behavior, ignore unknown content.
1805    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1806      std::string S;
1807      if (ConvertToString(Record, 0, S))
1808        return Error("Invalid MODULE_CODE_TRIPLE record");
1809      Triple = S;
1810      break;
1811    }
1812    }
1813    Record.clear();
1814  }
1815
1816  return Error("Premature end of bitstream");
1817}
1818
1819bool BitcodeReader::ParseTriple(std::string &Triple) {
1820  if (InitStream()) return true;
1821
1822  // Sniff for the signature.
1823  if (Stream.Read(8) != 'B' ||
1824      Stream.Read(8) != 'C' ||
1825      Stream.Read(4) != 0x0 ||
1826      Stream.Read(4) != 0xC ||
1827      Stream.Read(4) != 0xE ||
1828      Stream.Read(4) != 0xD)
1829    return Error("Invalid bitcode signature");
1830
1831  // We expect a number of well-defined blocks, though we don't necessarily
1832  // need to understand them all.
1833  while (!Stream.AtEndOfStream()) {
1834    unsigned Code = Stream.ReadCode();
1835
1836    if (Code != bitc::ENTER_SUBBLOCK)
1837      return Error("Invalid record at top-level");
1838
1839    unsigned BlockID = Stream.ReadSubBlockID();
1840
1841    // We only know the MODULE subblock ID.
1842    switch (BlockID) {
1843    case bitc::MODULE_BLOCK_ID:
1844      if (ParseModuleTriple(Triple))
1845        return true;
1846      break;
1847    default:
1848      if (Stream.SkipBlock())
1849        return Error("Malformed block record");
1850      break;
1851    }
1852  }
1853
1854  return false;
1855}
1856
1857/// ParseMetadataAttachment - Parse metadata attachments.
1858bool BitcodeReader::ParseMetadataAttachment() {
1859  if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1860    return Error("Malformed block record");
1861
1862  SmallVector<uint64_t, 64> Record;
1863  while(1) {
1864    unsigned Code = Stream.ReadCode();
1865    if (Code == bitc::END_BLOCK) {
1866      if (Stream.ReadBlockEnd())
1867        return Error("Error at end of PARAMATTR block");
1868      break;
1869    }
1870    if (Code == bitc::DEFINE_ABBREV) {
1871      Stream.ReadAbbrevRecord();
1872      continue;
1873    }
1874    // Read a metadata attachment record.
1875    Record.clear();
1876    switch (Stream.ReadRecord(Code, Record)) {
1877    default:  // Default behavior: ignore.
1878      break;
1879    case bitc::METADATA_ATTACHMENT: {
1880      unsigned RecordLength = Record.size();
1881      if (Record.empty() || (RecordLength - 1) % 2 == 1)
1882        return Error ("Invalid METADATA_ATTACHMENT reader!");
1883      Instruction *Inst = InstructionList[Record[0]];
1884      for (unsigned i = 1; i != RecordLength; i = i+2) {
1885        unsigned Kind = Record[i];
1886        DenseMap<unsigned, unsigned>::iterator I =
1887          MDKindMap.find(Kind);
1888        if (I == MDKindMap.end())
1889          return Error("Invalid metadata kind ID");
1890        Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1891        Inst->setMetadata(I->second, cast<MDNode>(Node));
1892      }
1893      break;
1894    }
1895    }
1896  }
1897  return false;
1898}
1899
1900/// ParseFunctionBody - Lazily parse the specified function body block.
1901bool BitcodeReader::ParseFunctionBody(Function *F) {
1902  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1903    return Error("Malformed block record");
1904
1905  InstructionList.clear();
1906  unsigned ModuleValueListSize = ValueList.size();
1907  unsigned ModuleMDValueListSize = MDValueList.size();
1908
1909  // Add all the function arguments to the value table.
1910  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1911    ValueList.push_back(I);
1912
1913  unsigned NextValueNo = ValueList.size();
1914  BasicBlock *CurBB = 0;
1915  unsigned CurBBNo = 0;
1916
1917  DebugLoc LastLoc;
1918
1919  // Read all the records.
1920  SmallVector<uint64_t, 64> Record;
1921  while (1) {
1922    unsigned Code = Stream.ReadCode();
1923    if (Code == bitc::END_BLOCK) {
1924      if (Stream.ReadBlockEnd())
1925        return Error("Error at end of function block");
1926      break;
1927    }
1928
1929    if (Code == bitc::ENTER_SUBBLOCK) {
1930      switch (Stream.ReadSubBlockID()) {
1931      default:  // Skip unknown content.
1932        if (Stream.SkipBlock())
1933          return Error("Malformed block record");
1934        break;
1935      case bitc::CONSTANTS_BLOCK_ID:
1936        if (ParseConstants()) return true;
1937        NextValueNo = ValueList.size();
1938        break;
1939      case bitc::VALUE_SYMTAB_BLOCK_ID:
1940        if (ParseValueSymbolTable()) return true;
1941        break;
1942      case bitc::METADATA_ATTACHMENT_ID:
1943        if (ParseMetadataAttachment()) return true;
1944        break;
1945      case bitc::METADATA_BLOCK_ID:
1946        if (ParseMetadata()) return true;
1947        break;
1948      }
1949      continue;
1950    }
1951
1952    if (Code == bitc::DEFINE_ABBREV) {
1953      Stream.ReadAbbrevRecord();
1954      continue;
1955    }
1956
1957    // Read a record.
1958    Record.clear();
1959    Instruction *I = 0;
1960    unsigned BitCode = Stream.ReadRecord(Code, Record);
1961    switch (BitCode) {
1962    default: // Default behavior: reject
1963      return Error("Unknown instruction");
1964    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1965      if (Record.size() < 1 || Record[0] == 0)
1966        return Error("Invalid DECLAREBLOCKS record");
1967      // Create all the basic blocks for the function.
1968      FunctionBBs.resize(Record[0]);
1969      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1970        FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1971      CurBB = FunctionBBs[0];
1972      continue;
1973
1974    case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
1975      // This record indicates that the last instruction is at the same
1976      // location as the previous instruction with a location.
1977      I = 0;
1978
1979      // Get the last instruction emitted.
1980      if (CurBB && !CurBB->empty())
1981        I = &CurBB->back();
1982      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1983               !FunctionBBs[CurBBNo-1]->empty())
1984        I = &FunctionBBs[CurBBNo-1]->back();
1985
1986      if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1987      I->setDebugLoc(LastLoc);
1988      I = 0;
1989      continue;
1990
1991    case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
1992      I = 0;     // Get the last instruction emitted.
1993      if (CurBB && !CurBB->empty())
1994        I = &CurBB->back();
1995      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1996               !FunctionBBs[CurBBNo-1]->empty())
1997        I = &FunctionBBs[CurBBNo-1]->back();
1998      if (I == 0 || Record.size() < 4)
1999        return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2000
2001      unsigned Line = Record[0], Col = Record[1];
2002      unsigned ScopeID = Record[2], IAID = Record[3];
2003
2004      MDNode *Scope = 0, *IA = 0;
2005      if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2006      if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2007      LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2008      I->setDebugLoc(LastLoc);
2009      I = 0;
2010      continue;
2011    }
2012
2013    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
2014      unsigned OpNum = 0;
2015      Value *LHS, *RHS;
2016      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2017          popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2018          OpNum+1 > Record.size())
2019        return Error("Invalid BINOP record");
2020
2021      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2022      if (Opc == -1) return Error("Invalid BINOP record");
2023      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2024      InstructionList.push_back(I);
2025      if (OpNum < Record.size()) {
2026        if (Opc == Instruction::Add ||
2027            Opc == Instruction::Sub ||
2028            Opc == Instruction::Mul ||
2029            Opc == Instruction::Shl) {
2030          if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2031            cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2032          if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2033            cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2034        } else if (Opc == Instruction::SDiv ||
2035                   Opc == Instruction::UDiv ||
2036                   Opc == Instruction::LShr ||
2037                   Opc == Instruction::AShr) {
2038          if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2039            cast<BinaryOperator>(I)->setIsExact(true);
2040        } else if (isa<FPMathOperator>(I)) {
2041          FastMathFlags FMF;
2042          FMF.UnsafeAlgebra =
2043            0 != (Record[OpNum] & (1 << bitc::FMF_UNSAFE_ALGEBRA));
2044          FMF.NoNaNs =
2045            0 != (Record[OpNum] & (1 << bitc::FMF_NO_NANS));
2046          FMF.NoInfs =
2047            0 != (Record[OpNum] & (1 << bitc::FMF_NO_INFS));
2048          FMF.NoSignedZeros =
2049            0 != (Record[OpNum] & (1 << bitc::FMF_NO_SIGNED_ZEROS));
2050          FMF.AllowReciprocal =
2051            0 != (Record[OpNum] & (1 << bitc::FMF_ALLOW_RECIPROCAL));
2052          if (FMF.any())
2053            I->setFastMathFlags(FMF);
2054        }
2055
2056      }
2057      break;
2058    }
2059    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2060      unsigned OpNum = 0;
2061      Value *Op;
2062      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2063          OpNum+2 != Record.size())
2064        return Error("Invalid CAST record");
2065
2066      Type *ResTy = getTypeByID(Record[OpNum]);
2067      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2068      if (Opc == -1 || ResTy == 0)
2069        return Error("Invalid CAST record");
2070      I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2071      InstructionList.push_back(I);
2072      break;
2073    }
2074    case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2075    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2076      unsigned OpNum = 0;
2077      Value *BasePtr;
2078      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2079        return Error("Invalid GEP record");
2080
2081      SmallVector<Value*, 16> GEPIdx;
2082      while (OpNum != Record.size()) {
2083        Value *Op;
2084        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2085          return Error("Invalid GEP record");
2086        GEPIdx.push_back(Op);
2087      }
2088
2089      I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2090      InstructionList.push_back(I);
2091      if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2092        cast<GetElementPtrInst>(I)->setIsInBounds(true);
2093      break;
2094    }
2095
2096    case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2097                                       // EXTRACTVAL: [opty, opval, n x indices]
2098      unsigned OpNum = 0;
2099      Value *Agg;
2100      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2101        return Error("Invalid EXTRACTVAL record");
2102
2103      SmallVector<unsigned, 4> EXTRACTVALIdx;
2104      for (unsigned RecSize = Record.size();
2105           OpNum != RecSize; ++OpNum) {
2106        uint64_t Index = Record[OpNum];
2107        if ((unsigned)Index != Index)
2108          return Error("Invalid EXTRACTVAL index");
2109        EXTRACTVALIdx.push_back((unsigned)Index);
2110      }
2111
2112      I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2113      InstructionList.push_back(I);
2114      break;
2115    }
2116
2117    case bitc::FUNC_CODE_INST_INSERTVAL: {
2118                           // INSERTVAL: [opty, opval, opty, opval, n x indices]
2119      unsigned OpNum = 0;
2120      Value *Agg;
2121      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2122        return Error("Invalid INSERTVAL record");
2123      Value *Val;
2124      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2125        return Error("Invalid INSERTVAL record");
2126
2127      SmallVector<unsigned, 4> INSERTVALIdx;
2128      for (unsigned RecSize = Record.size();
2129           OpNum != RecSize; ++OpNum) {
2130        uint64_t Index = Record[OpNum];
2131        if ((unsigned)Index != Index)
2132          return Error("Invalid INSERTVAL index");
2133        INSERTVALIdx.push_back((unsigned)Index);
2134      }
2135
2136      I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2137      InstructionList.push_back(I);
2138      break;
2139    }
2140
2141    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2142      // obsolete form of select
2143      // handles select i1 ... in old bitcode
2144      unsigned OpNum = 0;
2145      Value *TrueVal, *FalseVal, *Cond;
2146      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2147          popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2148          popValue(Record, OpNum, NextValueNo, Type::getInt1Ty(Context), Cond))
2149        return Error("Invalid SELECT record");
2150
2151      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2152      InstructionList.push_back(I);
2153      break;
2154    }
2155
2156    case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2157      // new form of select
2158      // handles select i1 or select [N x i1]
2159      unsigned OpNum = 0;
2160      Value *TrueVal, *FalseVal, *Cond;
2161      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2162          popValue(Record, OpNum, NextValueNo, TrueVal->getType(), FalseVal) ||
2163          getValueTypePair(Record, OpNum, NextValueNo, Cond))
2164        return Error("Invalid SELECT record");
2165
2166      // select condition can be either i1 or [N x i1]
2167      if (VectorType* vector_type =
2168          dyn_cast<VectorType>(Cond->getType())) {
2169        // expect <n x i1>
2170        if (vector_type->getElementType() != Type::getInt1Ty(Context))
2171          return Error("Invalid SELECT condition type");
2172      } else {
2173        // expect i1
2174        if (Cond->getType() != Type::getInt1Ty(Context))
2175          return Error("Invalid SELECT condition type");
2176      }
2177
2178      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2179      InstructionList.push_back(I);
2180      break;
2181    }
2182
2183    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2184      unsigned OpNum = 0;
2185      Value *Vec, *Idx;
2186      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2187          popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2188        return Error("Invalid EXTRACTELT record");
2189      I = ExtractElementInst::Create(Vec, Idx);
2190      InstructionList.push_back(I);
2191      break;
2192    }
2193
2194    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2195      unsigned OpNum = 0;
2196      Value *Vec, *Elt, *Idx;
2197      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2198          popValue(Record, OpNum, NextValueNo,
2199                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2200          popValue(Record, OpNum, NextValueNo, Type::getInt32Ty(Context), Idx))
2201        return Error("Invalid INSERTELT record");
2202      I = InsertElementInst::Create(Vec, Elt, Idx);
2203      InstructionList.push_back(I);
2204      break;
2205    }
2206
2207    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2208      unsigned OpNum = 0;
2209      Value *Vec1, *Vec2, *Mask;
2210      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2211          popValue(Record, OpNum, NextValueNo, Vec1->getType(), Vec2))
2212        return Error("Invalid SHUFFLEVEC record");
2213
2214      if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2215        return Error("Invalid SHUFFLEVEC record");
2216      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2217      InstructionList.push_back(I);
2218      break;
2219    }
2220
2221    case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2222      // Old form of ICmp/FCmp returning bool
2223      // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2224      // both legal on vectors but had different behaviour.
2225    case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2226      // FCmp/ICmp returning bool or vector of bool
2227
2228      unsigned OpNum = 0;
2229      Value *LHS, *RHS;
2230      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2231          popValue(Record, OpNum, NextValueNo, LHS->getType(), RHS) ||
2232          OpNum+1 != Record.size())
2233        return Error("Invalid CMP record");
2234
2235      if (LHS->getType()->isFPOrFPVectorTy())
2236        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2237      else
2238        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2239      InstructionList.push_back(I);
2240      break;
2241    }
2242
2243    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2244      {
2245        unsigned Size = Record.size();
2246        if (Size == 0) {
2247          I = ReturnInst::Create(Context);
2248          InstructionList.push_back(I);
2249          break;
2250        }
2251
2252        unsigned OpNum = 0;
2253        Value *Op = NULL;
2254        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2255          return Error("Invalid RET record");
2256        if (OpNum != Record.size())
2257          return Error("Invalid RET record");
2258
2259        I = ReturnInst::Create(Context, Op);
2260        InstructionList.push_back(I);
2261        break;
2262      }
2263    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2264      if (Record.size() != 1 && Record.size() != 3)
2265        return Error("Invalid BR record");
2266      BasicBlock *TrueDest = getBasicBlock(Record[0]);
2267      if (TrueDest == 0)
2268        return Error("Invalid BR record");
2269
2270      if (Record.size() == 1) {
2271        I = BranchInst::Create(TrueDest);
2272        InstructionList.push_back(I);
2273      }
2274      else {
2275        BasicBlock *FalseDest = getBasicBlock(Record[1]);
2276        Value *Cond = getValue(Record, 2, NextValueNo,
2277                               Type::getInt1Ty(Context));
2278        if (FalseDest == 0 || Cond == 0)
2279          return Error("Invalid BR record");
2280        I = BranchInst::Create(TrueDest, FalseDest, Cond);
2281        InstructionList.push_back(I);
2282      }
2283      break;
2284    }
2285    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2286      // Check magic
2287      if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2288        // New SwitchInst format with case ranges.
2289
2290        Type *OpTy = getTypeByID(Record[1]);
2291        unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2292
2293        Value *Cond = getValue(Record, 2, NextValueNo, OpTy);
2294        BasicBlock *Default = getBasicBlock(Record[3]);
2295        if (OpTy == 0 || Cond == 0 || Default == 0)
2296          return Error("Invalid SWITCH record");
2297
2298        unsigned NumCases = Record[4];
2299
2300        SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2301        InstructionList.push_back(SI);
2302
2303        unsigned CurIdx = 5;
2304        for (unsigned i = 0; i != NumCases; ++i) {
2305          IntegersSubsetToBB CaseBuilder;
2306          unsigned NumItems = Record[CurIdx++];
2307          for (unsigned ci = 0; ci != NumItems; ++ci) {
2308            bool isSingleNumber = Record[CurIdx++];
2309
2310            APInt Low;
2311            unsigned ActiveWords = 1;
2312            if (ValueBitWidth > 64)
2313              ActiveWords = Record[CurIdx++];
2314            Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2315                                ValueBitWidth);
2316            CurIdx += ActiveWords;
2317
2318            if (!isSingleNumber) {
2319              ActiveWords = 1;
2320              if (ValueBitWidth > 64)
2321                ActiveWords = Record[CurIdx++];
2322              APInt High =
2323                  ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2324                                ValueBitWidth);
2325
2326              CaseBuilder.add(IntItem::fromType(OpTy, Low),
2327                              IntItem::fromType(OpTy, High));
2328              CurIdx += ActiveWords;
2329            } else
2330              CaseBuilder.add(IntItem::fromType(OpTy, Low));
2331          }
2332          BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2333          IntegersSubset Case = CaseBuilder.getCase();
2334          SI->addCase(Case, DestBB);
2335        }
2336        uint16_t Hash = SI->hash();
2337        if (Hash != (Record[0] & 0xFFFF))
2338          return Error("Invalid SWITCH record");
2339        I = SI;
2340        break;
2341      }
2342
2343      // Old SwitchInst format without case ranges.
2344
2345      if (Record.size() < 3 || (Record.size() & 1) == 0)
2346        return Error("Invalid SWITCH record");
2347      Type *OpTy = getTypeByID(Record[0]);
2348      Value *Cond = getValue(Record, 1, NextValueNo, OpTy);
2349      BasicBlock *Default = getBasicBlock(Record[2]);
2350      if (OpTy == 0 || Cond == 0 || Default == 0)
2351        return Error("Invalid SWITCH record");
2352      unsigned NumCases = (Record.size()-3)/2;
2353      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2354      InstructionList.push_back(SI);
2355      for (unsigned i = 0, e = NumCases; i != e; ++i) {
2356        ConstantInt *CaseVal =
2357          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2358        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2359        if (CaseVal == 0 || DestBB == 0) {
2360          delete SI;
2361          return Error("Invalid SWITCH record!");
2362        }
2363        SI->addCase(CaseVal, DestBB);
2364      }
2365      I = SI;
2366      break;
2367    }
2368    case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2369      if (Record.size() < 2)
2370        return Error("Invalid INDIRECTBR record");
2371      Type *OpTy = getTypeByID(Record[0]);
2372      Value *Address = getValue(Record, 1, NextValueNo, OpTy);
2373      if (OpTy == 0 || Address == 0)
2374        return Error("Invalid INDIRECTBR record");
2375      unsigned NumDests = Record.size()-2;
2376      IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2377      InstructionList.push_back(IBI);
2378      for (unsigned i = 0, e = NumDests; i != e; ++i) {
2379        if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2380          IBI->addDestination(DestBB);
2381        } else {
2382          delete IBI;
2383          return Error("Invalid INDIRECTBR record!");
2384        }
2385      }
2386      I = IBI;
2387      break;
2388    }
2389
2390    case bitc::FUNC_CODE_INST_INVOKE: {
2391      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2392      if (Record.size() < 4) return Error("Invalid INVOKE record");
2393      AttrListPtr PAL = getAttributes(Record[0]);
2394      unsigned CCInfo = Record[1];
2395      BasicBlock *NormalBB = getBasicBlock(Record[2]);
2396      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2397
2398      unsigned OpNum = 4;
2399      Value *Callee;
2400      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2401        return Error("Invalid INVOKE record");
2402
2403      PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2404      FunctionType *FTy = !CalleeTy ? 0 :
2405        dyn_cast<FunctionType>(CalleeTy->getElementType());
2406
2407      // Check that the right number of fixed parameters are here.
2408      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2409          Record.size() < OpNum+FTy->getNumParams())
2410        return Error("Invalid INVOKE record");
2411
2412      SmallVector<Value*, 16> Ops;
2413      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2414        Ops.push_back(getValue(Record, OpNum, NextValueNo,
2415                               FTy->getParamType(i)));
2416        if (Ops.back() == 0) return Error("Invalid INVOKE record");
2417      }
2418
2419      if (!FTy->isVarArg()) {
2420        if (Record.size() != OpNum)
2421          return Error("Invalid INVOKE record");
2422      } else {
2423        // Read type/value pairs for varargs params.
2424        while (OpNum != Record.size()) {
2425          Value *Op;
2426          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2427            return Error("Invalid INVOKE record");
2428          Ops.push_back(Op);
2429        }
2430      }
2431
2432      I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2433      InstructionList.push_back(I);
2434      cast<InvokeInst>(I)->setCallingConv(
2435        static_cast<CallingConv::ID>(CCInfo));
2436      cast<InvokeInst>(I)->setAttributes(PAL);
2437      break;
2438    }
2439    case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2440      unsigned Idx = 0;
2441      Value *Val = 0;
2442      if (getValueTypePair(Record, Idx, NextValueNo, Val))
2443        return Error("Invalid RESUME record");
2444      I = ResumeInst::Create(Val);
2445      InstructionList.push_back(I);
2446      break;
2447    }
2448    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2449      I = new UnreachableInst(Context);
2450      InstructionList.push_back(I);
2451      break;
2452    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2453      if (Record.size() < 1 || ((Record.size()-1)&1))
2454        return Error("Invalid PHI record");
2455      Type *Ty = getTypeByID(Record[0]);
2456      if (!Ty) return Error("Invalid PHI record");
2457
2458      PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2459      InstructionList.push_back(PN);
2460
2461      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2462        Value *V;
2463        // With the new function encoding, it is possible that operands have
2464        // negative IDs (for forward references).  Use a signed VBR
2465        // representation to keep the encoding small.
2466        if (UseRelativeIDs)
2467          V = getValueSigned(Record, 1+i, NextValueNo, Ty);
2468        else
2469          V = getValue(Record, 1+i, NextValueNo, Ty);
2470        BasicBlock *BB = getBasicBlock(Record[2+i]);
2471        if (!V || !BB) return Error("Invalid PHI record");
2472        PN->addIncoming(V, BB);
2473      }
2474      I = PN;
2475      break;
2476    }
2477
2478    case bitc::FUNC_CODE_INST_LANDINGPAD: {
2479      // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2480      unsigned Idx = 0;
2481      if (Record.size() < 4)
2482        return Error("Invalid LANDINGPAD record");
2483      Type *Ty = getTypeByID(Record[Idx++]);
2484      if (!Ty) return Error("Invalid LANDINGPAD record");
2485      Value *PersFn = 0;
2486      if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2487        return Error("Invalid LANDINGPAD record");
2488
2489      bool IsCleanup = !!Record[Idx++];
2490      unsigned NumClauses = Record[Idx++];
2491      LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2492      LP->setCleanup(IsCleanup);
2493      for (unsigned J = 0; J != NumClauses; ++J) {
2494        LandingPadInst::ClauseType CT =
2495          LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2496        Value *Val;
2497
2498        if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2499          delete LP;
2500          return Error("Invalid LANDINGPAD record");
2501        }
2502
2503        assert((CT != LandingPadInst::Catch ||
2504                !isa<ArrayType>(Val->getType())) &&
2505               "Catch clause has a invalid type!");
2506        assert((CT != LandingPadInst::Filter ||
2507                isa<ArrayType>(Val->getType())) &&
2508               "Filter clause has invalid type!");
2509        LP->addClause(Val);
2510      }
2511
2512      I = LP;
2513      InstructionList.push_back(I);
2514      break;
2515    }
2516
2517    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2518      if (Record.size() != 4)
2519        return Error("Invalid ALLOCA record");
2520      PointerType *Ty =
2521        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2522      Type *OpTy = getTypeByID(Record[1]);
2523      Value *Size = getFnValueByID(Record[2], OpTy);
2524      unsigned Align = Record[3];
2525      if (!Ty || !Size) return Error("Invalid ALLOCA record");
2526      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2527      InstructionList.push_back(I);
2528      break;
2529    }
2530    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2531      unsigned OpNum = 0;
2532      Value *Op;
2533      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2534          OpNum+2 != Record.size())
2535        return Error("Invalid LOAD record");
2536
2537      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2538      InstructionList.push_back(I);
2539      break;
2540    }
2541    case bitc::FUNC_CODE_INST_LOADATOMIC: {
2542       // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2543      unsigned OpNum = 0;
2544      Value *Op;
2545      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2546          OpNum+4 != Record.size())
2547        return Error("Invalid LOADATOMIC record");
2548
2549
2550      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2551      if (Ordering == NotAtomic || Ordering == Release ||
2552          Ordering == AcquireRelease)
2553        return Error("Invalid LOADATOMIC record");
2554      if (Ordering != NotAtomic && Record[OpNum] == 0)
2555        return Error("Invalid LOADATOMIC record");
2556      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2557
2558      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2559                       Ordering, SynchScope);
2560      InstructionList.push_back(I);
2561      break;
2562    }
2563    case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2564      unsigned OpNum = 0;
2565      Value *Val, *Ptr;
2566      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2567          popValue(Record, OpNum, NextValueNo,
2568                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2569          OpNum+2 != Record.size())
2570        return Error("Invalid STORE record");
2571
2572      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2573      InstructionList.push_back(I);
2574      break;
2575    }
2576    case bitc::FUNC_CODE_INST_STOREATOMIC: {
2577      // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2578      unsigned OpNum = 0;
2579      Value *Val, *Ptr;
2580      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2581          popValue(Record, OpNum, NextValueNo,
2582                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2583          OpNum+4 != Record.size())
2584        return Error("Invalid STOREATOMIC record");
2585
2586      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2587      if (Ordering == NotAtomic || Ordering == Acquire ||
2588          Ordering == AcquireRelease)
2589        return Error("Invalid STOREATOMIC record");
2590      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2591      if (Ordering != NotAtomic && Record[OpNum] == 0)
2592        return Error("Invalid STOREATOMIC record");
2593
2594      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2595                        Ordering, SynchScope);
2596      InstructionList.push_back(I);
2597      break;
2598    }
2599    case bitc::FUNC_CODE_INST_CMPXCHG: {
2600      // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2601      unsigned OpNum = 0;
2602      Value *Ptr, *Cmp, *New;
2603      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2604          popValue(Record, OpNum, NextValueNo,
2605                    cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2606          popValue(Record, OpNum, NextValueNo,
2607                    cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2608          OpNum+3 != Record.size())
2609        return Error("Invalid CMPXCHG record");
2610      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2611      if (Ordering == NotAtomic || Ordering == Unordered)
2612        return Error("Invalid CMPXCHG record");
2613      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2614      I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2615      cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2616      InstructionList.push_back(I);
2617      break;
2618    }
2619    case bitc::FUNC_CODE_INST_ATOMICRMW: {
2620      // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2621      unsigned OpNum = 0;
2622      Value *Ptr, *Val;
2623      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2624          popValue(Record, OpNum, NextValueNo,
2625                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2626          OpNum+4 != Record.size())
2627        return Error("Invalid ATOMICRMW record");
2628      AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2629      if (Operation < AtomicRMWInst::FIRST_BINOP ||
2630          Operation > AtomicRMWInst::LAST_BINOP)
2631        return Error("Invalid ATOMICRMW record");
2632      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2633      if (Ordering == NotAtomic || Ordering == Unordered)
2634        return Error("Invalid ATOMICRMW record");
2635      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2636      I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2637      cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2638      InstructionList.push_back(I);
2639      break;
2640    }
2641    case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2642      if (2 != Record.size())
2643        return Error("Invalid FENCE record");
2644      AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2645      if (Ordering == NotAtomic || Ordering == Unordered ||
2646          Ordering == Monotonic)
2647        return Error("Invalid FENCE record");
2648      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2649      I = new FenceInst(Context, Ordering, SynchScope);
2650      InstructionList.push_back(I);
2651      break;
2652    }
2653    case bitc::FUNC_CODE_INST_CALL: {
2654      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2655      if (Record.size() < 3)
2656        return Error("Invalid CALL record");
2657
2658      AttrListPtr PAL = getAttributes(Record[0]);
2659      unsigned CCInfo = Record[1];
2660
2661      unsigned OpNum = 2;
2662      Value *Callee;
2663      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2664        return Error("Invalid CALL record");
2665
2666      PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2667      FunctionType *FTy = 0;
2668      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2669      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2670        return Error("Invalid CALL record");
2671
2672      SmallVector<Value*, 16> Args;
2673      // Read the fixed params.
2674      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2675        if (FTy->getParamType(i)->isLabelTy())
2676          Args.push_back(getBasicBlock(Record[OpNum]));
2677        else
2678          Args.push_back(getValue(Record, OpNum, NextValueNo,
2679                                  FTy->getParamType(i)));
2680        if (Args.back() == 0) return Error("Invalid CALL record");
2681      }
2682
2683      // Read type/value pairs for varargs params.
2684      if (!FTy->isVarArg()) {
2685        if (OpNum != Record.size())
2686          return Error("Invalid CALL record");
2687      } else {
2688        while (OpNum != Record.size()) {
2689          Value *Op;
2690          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2691            return Error("Invalid CALL record");
2692          Args.push_back(Op);
2693        }
2694      }
2695
2696      I = CallInst::Create(Callee, Args);
2697      InstructionList.push_back(I);
2698      cast<CallInst>(I)->setCallingConv(
2699        static_cast<CallingConv::ID>(CCInfo>>1));
2700      cast<CallInst>(I)->setTailCall(CCInfo & 1);
2701      cast<CallInst>(I)->setAttributes(PAL);
2702      break;
2703    }
2704    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2705      if (Record.size() < 3)
2706        return Error("Invalid VAARG record");
2707      Type *OpTy = getTypeByID(Record[0]);
2708      Value *Op = getValue(Record, 1, NextValueNo, OpTy);
2709      Type *ResTy = getTypeByID(Record[2]);
2710      if (!OpTy || !Op || !ResTy)
2711        return Error("Invalid VAARG record");
2712      I = new VAArgInst(Op, ResTy);
2713      InstructionList.push_back(I);
2714      break;
2715    }
2716    }
2717
2718    // Add instruction to end of current BB.  If there is no current BB, reject
2719    // this file.
2720    if (CurBB == 0) {
2721      delete I;
2722      return Error("Invalid instruction with no BB");
2723    }
2724    CurBB->getInstList().push_back(I);
2725
2726    // If this was a terminator instruction, move to the next block.
2727    if (isa<TerminatorInst>(I)) {
2728      ++CurBBNo;
2729      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2730    }
2731
2732    // Non-void values get registered in the value table for future use.
2733    if (I && !I->getType()->isVoidTy())
2734      ValueList.AssignValue(I, NextValueNo++);
2735  }
2736
2737  // Check the function list for unresolved values.
2738  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2739    if (A->getParent() == 0) {
2740      // We found at least one unresolved value.  Nuke them all to avoid leaks.
2741      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2742        if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2743          A->replaceAllUsesWith(UndefValue::get(A->getType()));
2744          delete A;
2745        }
2746      }
2747      return Error("Never resolved value found in function!");
2748    }
2749  }
2750
2751  // FIXME: Check for unresolved forward-declared metadata references
2752  // and clean up leaks.
2753
2754  // See if anything took the address of blocks in this function.  If so,
2755  // resolve them now.
2756  DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2757    BlockAddrFwdRefs.find(F);
2758  if (BAFRI != BlockAddrFwdRefs.end()) {
2759    std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2760    for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2761      unsigned BlockIdx = RefList[i].first;
2762      if (BlockIdx >= FunctionBBs.size())
2763        return Error("Invalid blockaddress block #");
2764
2765      GlobalVariable *FwdRef = RefList[i].second;
2766      FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2767      FwdRef->eraseFromParent();
2768    }
2769
2770    BlockAddrFwdRefs.erase(BAFRI);
2771  }
2772
2773  // Trim the value list down to the size it was before we parsed this function.
2774  ValueList.shrinkTo(ModuleValueListSize);
2775  MDValueList.shrinkTo(ModuleMDValueListSize);
2776  std::vector<BasicBlock*>().swap(FunctionBBs);
2777  return false;
2778}
2779
2780/// FindFunctionInStream - Find the function body in the bitcode stream
2781bool BitcodeReader::FindFunctionInStream(Function *F,
2782       DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2783  while (DeferredFunctionInfoIterator->second == 0) {
2784    if (Stream.AtEndOfStream())
2785      return Error("Could not find Function in stream");
2786    // ParseModule will parse the next body in the stream and set its
2787    // position in the DeferredFunctionInfo map.
2788    if (ParseModule(true)) return true;
2789  }
2790  return false;
2791}
2792
2793//===----------------------------------------------------------------------===//
2794// GVMaterializer implementation
2795//===----------------------------------------------------------------------===//
2796
2797
2798bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2799  if (const Function *F = dyn_cast<Function>(GV)) {
2800    return F->isDeclaration() &&
2801      DeferredFunctionInfo.count(const_cast<Function*>(F));
2802  }
2803  return false;
2804}
2805
2806bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2807  Function *F = dyn_cast<Function>(GV);
2808  // If it's not a function or is already material, ignore the request.
2809  if (!F || !F->isMaterializable()) return false;
2810
2811  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2812  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2813  // If its position is recorded as 0, its body is somewhere in the stream
2814  // but we haven't seen it yet.
2815  if (DFII->second == 0)
2816    if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
2817
2818  // Move the bit stream to the saved position of the deferred function body.
2819  Stream.JumpToBit(DFII->second);
2820
2821  if (ParseFunctionBody(F)) {
2822    if (ErrInfo) *ErrInfo = ErrorString;
2823    return true;
2824  }
2825
2826  // Upgrade any old intrinsic calls in the function.
2827  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2828       E = UpgradedIntrinsics.end(); I != E; ++I) {
2829    if (I->first != I->second) {
2830      for (Value::use_iterator UI = I->first->use_begin(),
2831           UE = I->first->use_end(); UI != UE; ) {
2832        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2833          UpgradeIntrinsicCall(CI, I->second);
2834      }
2835    }
2836  }
2837
2838  return false;
2839}
2840
2841bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2842  const Function *F = dyn_cast<Function>(GV);
2843  if (!F || F->isDeclaration())
2844    return false;
2845  return DeferredFunctionInfo.count(const_cast<Function*>(F));
2846}
2847
2848void BitcodeReader::Dematerialize(GlobalValue *GV) {
2849  Function *F = dyn_cast<Function>(GV);
2850  // If this function isn't dematerializable, this is a noop.
2851  if (!F || !isDematerializable(F))
2852    return;
2853
2854  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2855
2856  // Just forget the function body, we can remat it later.
2857  F->deleteBody();
2858}
2859
2860
2861bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2862  assert(M == TheModule &&
2863         "Can only Materialize the Module this BitcodeReader is attached to.");
2864  // Iterate over the module, deserializing any functions that are still on
2865  // disk.
2866  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2867       F != E; ++F)
2868    if (F->isMaterializable() &&
2869        Materialize(F, ErrInfo))
2870      return true;
2871
2872  // At this point, if there are any function bodies, the current bit is
2873  // pointing to the END_BLOCK record after them. Now make sure the rest
2874  // of the bits in the module have been read.
2875  if (NextUnreadBit)
2876    ParseModule(true);
2877
2878  // Upgrade any intrinsic calls that slipped through (should not happen!) and
2879  // delete the old functions to clean up. We can't do this unless the entire
2880  // module is materialized because there could always be another function body
2881  // with calls to the old function.
2882  for (std::vector<std::pair<Function*, Function*> >::iterator I =
2883       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2884    if (I->first != I->second) {
2885      for (Value::use_iterator UI = I->first->use_begin(),
2886           UE = I->first->use_end(); UI != UE; ) {
2887        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2888          UpgradeIntrinsicCall(CI, I->second);
2889      }
2890      if (!I->first->use_empty())
2891        I->first->replaceAllUsesWith(I->second);
2892      I->first->eraseFromParent();
2893    }
2894  }
2895  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2896
2897  return false;
2898}
2899
2900bool BitcodeReader::InitStream() {
2901  if (LazyStreamer) return InitLazyStream();
2902  return InitStreamFromBuffer();
2903}
2904
2905bool BitcodeReader::InitStreamFromBuffer() {
2906  const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
2907  const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2908
2909  if (Buffer->getBufferSize() & 3) {
2910    if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2911      return Error("Invalid bitcode signature");
2912    else
2913      return Error("Bitcode stream should be a multiple of 4 bytes in length");
2914  }
2915
2916  // If we have a wrapper header, parse it and ignore the non-bc file contents.
2917  // The magic number is 0x0B17C0DE stored in little endian.
2918  if (isBitcodeWrapper(BufPtr, BufEnd))
2919    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2920      return Error("Invalid bitcode wrapper header");
2921
2922  StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2923  Stream.init(*StreamFile);
2924
2925  return false;
2926}
2927
2928bool BitcodeReader::InitLazyStream() {
2929  // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2930  // see it.
2931  StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2932  StreamFile.reset(new BitstreamReader(Bytes));
2933  Stream.init(*StreamFile);
2934
2935  unsigned char buf[16];
2936  if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2937    return Error("Bitcode stream must be at least 16 bytes in length");
2938
2939  if (!isBitcode(buf, buf + 16))
2940    return Error("Invalid bitcode signature");
2941
2942  if (isBitcodeWrapper(buf, buf + 4)) {
2943    const unsigned char *bitcodeStart = buf;
2944    const unsigned char *bitcodeEnd = buf + 16;
2945    SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2946    Bytes->dropLeadingBytes(bitcodeStart - buf);
2947    Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2948  }
2949  return false;
2950}
2951
2952//===----------------------------------------------------------------------===//
2953// External interface
2954//===----------------------------------------------------------------------===//
2955
2956/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2957///
2958Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2959                                   LLVMContext& Context,
2960                                   std::string *ErrMsg) {
2961  Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2962  BitcodeReader *R = new BitcodeReader(Buffer, Context);
2963  M->setMaterializer(R);
2964  if (R->ParseBitcodeInto(M)) {
2965    if (ErrMsg)
2966      *ErrMsg = R->getErrorString();
2967
2968    delete M;  // Also deletes R.
2969    return 0;
2970  }
2971  // Have the BitcodeReader dtor delete 'Buffer'.
2972  R->setBufferOwned(true);
2973
2974  R->materializeForwardReferencedFunctions();
2975
2976  return M;
2977}
2978
2979
2980Module *llvm::getStreamedBitcodeModule(const std::string &name,
2981                                       DataStreamer *streamer,
2982                                       LLVMContext &Context,
2983                                       std::string *ErrMsg) {
2984  Module *M = new Module(name, Context);
2985  BitcodeReader *R = new BitcodeReader(streamer, Context);
2986  M->setMaterializer(R);
2987  if (R->ParseBitcodeInto(M)) {
2988    if (ErrMsg)
2989      *ErrMsg = R->getErrorString();
2990    delete M;  // Also deletes R.
2991    return 0;
2992  }
2993  R->setBufferOwned(false); // no buffer to delete
2994  return M;
2995}
2996
2997/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2998/// If an error occurs, return null and fill in *ErrMsg if non-null.
2999Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
3000                               std::string *ErrMsg){
3001  Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
3002  if (!M) return 0;
3003
3004  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
3005  // there was an error.
3006  static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
3007
3008  // Read in the entire module, and destroy the BitcodeReader.
3009  if (M->MaterializeAllPermanently(ErrMsg)) {
3010    delete M;
3011    return 0;
3012  }
3013
3014  // TODO: Restore the use-lists to the in-memory state when the bitcode was
3015  // written.  We must defer until the Module has been fully materialized.
3016
3017  return M;
3018}
3019
3020std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
3021                                         LLVMContext& Context,
3022                                         std::string *ErrMsg) {
3023  BitcodeReader *R = new BitcodeReader(Buffer, Context);
3024  // Don't let the BitcodeReader dtor delete 'Buffer'.
3025  R->setBufferOwned(false);
3026
3027  std::string Triple("");
3028  if (R->ParseTriple(Triple))
3029    if (ErrMsg)
3030      *ErrMsg = R->getErrorString();
3031
3032  delete R;
3033  return Triple;
3034}
3035