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 inline bool classof(const ConstantPlaceHolder *) { return true; }
215    static bool classof(const Value *V) {
216      return isa<ConstantExpr>(V) &&
217             cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
218    }
219
220
221    /// Provide fast operand accessors
222    //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
223  };
224}
225
226// FIXME: can we inherit this from ConstantExpr?
227template <>
228struct OperandTraits<ConstantPlaceHolder> :
229  public FixedNumOperandTraits<ConstantPlaceHolder, 1> {
230};
231}
232
233
234void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
235  if (Idx == size()) {
236    push_back(V);
237    return;
238  }
239
240  if (Idx >= size())
241    resize(Idx+1);
242
243  WeakVH &OldV = ValuePtrs[Idx];
244  if (OldV == 0) {
245    OldV = V;
246    return;
247  }
248
249  // Handle constants and non-constants (e.g. instrs) differently for
250  // efficiency.
251  if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
252    ResolveConstants.push_back(std::make_pair(PHC, Idx));
253    OldV = V;
254  } else {
255    // If there was a forward reference to this value, replace it.
256    Value *PrevVal = OldV;
257    OldV->replaceAllUsesWith(V);
258    delete PrevVal;
259  }
260}
261
262
263Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
264                                                    Type *Ty) {
265  if (Idx >= size())
266    resize(Idx + 1);
267
268  if (Value *V = ValuePtrs[Idx]) {
269    assert(Ty == V->getType() && "Type mismatch in constant table!");
270    return cast<Constant>(V);
271  }
272
273  // Create and return a placeholder, which will later be RAUW'd.
274  Constant *C = new ConstantPlaceHolder(Ty, Context);
275  ValuePtrs[Idx] = C;
276  return C;
277}
278
279Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, Type *Ty) {
280  if (Idx >= size())
281    resize(Idx + 1);
282
283  if (Value *V = ValuePtrs[Idx]) {
284    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
285    return V;
286  }
287
288  // No type specified, must be invalid reference.
289  if (Ty == 0) return 0;
290
291  // Create and return a placeholder, which will later be RAUW'd.
292  Value *V = new Argument(Ty);
293  ValuePtrs[Idx] = V;
294  return V;
295}
296
297/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
298/// resolves any forward references.  The idea behind this is that we sometimes
299/// get constants (such as large arrays) which reference *many* forward ref
300/// constants.  Replacing each of these causes a lot of thrashing when
301/// building/reuniquing the constant.  Instead of doing this, we look at all the
302/// uses and rewrite all the place holders at once for any constant that uses
303/// a placeholder.
304void BitcodeReaderValueList::ResolveConstantForwardRefs() {
305  // Sort the values by-pointer so that they are efficient to look up with a
306  // binary search.
307  std::sort(ResolveConstants.begin(), ResolveConstants.end());
308
309  SmallVector<Constant*, 64> NewOps;
310
311  while (!ResolveConstants.empty()) {
312    Value *RealVal = operator[](ResolveConstants.back().second);
313    Constant *Placeholder = ResolveConstants.back().first;
314    ResolveConstants.pop_back();
315
316    // Loop over all users of the placeholder, updating them to reference the
317    // new value.  If they reference more than one placeholder, update them all
318    // at once.
319    while (!Placeholder->use_empty()) {
320      Value::use_iterator UI = Placeholder->use_begin();
321      User *U = *UI;
322
323      // If the using object isn't uniqued, just update the operands.  This
324      // handles instructions and initializers for global variables.
325      if (!isa<Constant>(U) || isa<GlobalValue>(U)) {
326        UI.getUse().set(RealVal);
327        continue;
328      }
329
330      // Otherwise, we have a constant that uses the placeholder.  Replace that
331      // constant with a new constant that has *all* placeholder uses updated.
332      Constant *UserC = cast<Constant>(U);
333      for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
334           I != E; ++I) {
335        Value *NewOp;
336        if (!isa<ConstantPlaceHolder>(*I)) {
337          // Not a placeholder reference.
338          NewOp = *I;
339        } else if (*I == Placeholder) {
340          // Common case is that it just references this one placeholder.
341          NewOp = RealVal;
342        } else {
343          // Otherwise, look up the placeholder in ResolveConstants.
344          ResolveConstantsTy::iterator It =
345            std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
346                             std::pair<Constant*, unsigned>(cast<Constant>(*I),
347                                                            0));
348          assert(It != ResolveConstants.end() && It->first == *I);
349          NewOp = operator[](It->second);
350        }
351
352        NewOps.push_back(cast<Constant>(NewOp));
353      }
354
355      // Make the new constant.
356      Constant *NewC;
357      if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
358        NewC = ConstantArray::get(UserCA->getType(), NewOps);
359      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
360        NewC = ConstantStruct::get(UserCS->getType(), NewOps);
361      } else if (isa<ConstantVector>(UserC)) {
362        NewC = ConstantVector::get(NewOps);
363      } else {
364        assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
365        NewC = cast<ConstantExpr>(UserC)->getWithOperands(NewOps);
366      }
367
368      UserC->replaceAllUsesWith(NewC);
369      UserC->destroyConstant();
370      NewOps.clear();
371    }
372
373    // Update all ValueHandles, they should be the only users at this point.
374    Placeholder->replaceAllUsesWith(RealVal);
375    delete Placeholder;
376  }
377}
378
379void BitcodeReaderMDValueList::AssignValue(Value *V, unsigned Idx) {
380  if (Idx == size()) {
381    push_back(V);
382    return;
383  }
384
385  if (Idx >= size())
386    resize(Idx+1);
387
388  WeakVH &OldV = MDValuePtrs[Idx];
389  if (OldV == 0) {
390    OldV = V;
391    return;
392  }
393
394  // If there was a forward reference to this value, replace it.
395  MDNode *PrevVal = cast<MDNode>(OldV);
396  OldV->replaceAllUsesWith(V);
397  MDNode::deleteTemporary(PrevVal);
398  // Deleting PrevVal sets Idx value in MDValuePtrs to null. Set new
399  // value for Idx.
400  MDValuePtrs[Idx] = V;
401}
402
403Value *BitcodeReaderMDValueList::getValueFwdRef(unsigned Idx) {
404  if (Idx >= size())
405    resize(Idx + 1);
406
407  if (Value *V = MDValuePtrs[Idx]) {
408    assert(V->getType()->isMetadataTy() && "Type mismatch in value table!");
409    return V;
410  }
411
412  // Create and return a placeholder, which will later be RAUW'd.
413  Value *V = MDNode::getTemporary(Context, ArrayRef<Value*>());
414  MDValuePtrs[Idx] = V;
415  return V;
416}
417
418Type *BitcodeReader::getTypeByID(unsigned ID) {
419  // The type table size is always specified correctly.
420  if (ID >= TypeList.size())
421    return 0;
422
423  if (Type *Ty = TypeList[ID])
424    return Ty;
425
426  // If we have a forward reference, the only possible case is when it is to a
427  // named struct.  Just create a placeholder for now.
428  return TypeList[ID] = StructType::create(Context);
429}
430
431
432//===----------------------------------------------------------------------===//
433//  Functions for parsing blocks from the bitcode file
434//===----------------------------------------------------------------------===//
435
436bool BitcodeReader::ParseAttributeBlock() {
437  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
438    return Error("Malformed block record");
439
440  if (!MAttributes.empty())
441    return Error("Multiple PARAMATTR blocks found!");
442
443  SmallVector<uint64_t, 64> Record;
444
445  SmallVector<AttributeWithIndex, 8> Attrs;
446
447  // Read all the records.
448  while (1) {
449    unsigned Code = Stream.ReadCode();
450    if (Code == bitc::END_BLOCK) {
451      if (Stream.ReadBlockEnd())
452        return Error("Error at end of PARAMATTR block");
453      return false;
454    }
455
456    if (Code == bitc::ENTER_SUBBLOCK) {
457      // No known subblocks, always skip them.
458      Stream.ReadSubBlockID();
459      if (Stream.SkipBlock())
460        return Error("Malformed block record");
461      continue;
462    }
463
464    if (Code == bitc::DEFINE_ABBREV) {
465      Stream.ReadAbbrevRecord();
466      continue;
467    }
468
469    // Read a record.
470    Record.clear();
471    switch (Stream.ReadRecord(Code, Record)) {
472    default:  // Default behavior: ignore.
473      break;
474    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
475      if (Record.size() & 1)
476        return Error("Invalid ENTRY record");
477
478      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
479        Attributes ReconstitutedAttr =
480          Attributes::decodeLLVMAttributesForBitcode(Record[i+1]);
481        Record[i+1] = ReconstitutedAttr.Raw();
482      }
483
484      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
485        if (Attributes(Record[i+1]) != Attribute::None)
486          Attrs.push_back(AttributeWithIndex::get(Record[i],
487                                                  Attributes(Record[i+1])));
488      }
489
490      MAttributes.push_back(AttrListPtr::get(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.
896static uint64_t 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                 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(ValueList.getConstantFwdRef(Record[0],
1186                                                              Type::getInt1Ty(Context)),
1187                                  ValueList.getConstantFwdRef(Record[1],CurTy),
1188                                  ValueList.getConstantFwdRef(Record[2],CurTy));
1189      break;
1190    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1191      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1192      VectorType *OpTy =
1193        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1194      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1195      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1196      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1197      V = ConstantExpr::getExtractElement(Op0, Op1);
1198      break;
1199    }
1200    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1201      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1202      if (Record.size() < 3 || OpTy == 0)
1203        return Error("Invalid CE_INSERTELT record");
1204      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1205      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1206                                                  OpTy->getElementType());
1207      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1208      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1209      break;
1210    }
1211    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1212      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1213      if (Record.size() < 3 || OpTy == 0)
1214        return Error("Invalid CE_SHUFFLEVEC record");
1215      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1216      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1217      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1218                                                 OpTy->getNumElements());
1219      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1220      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1221      break;
1222    }
1223    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1224      VectorType *RTy = dyn_cast<VectorType>(CurTy);
1225      VectorType *OpTy =
1226        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1227      if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1228        return Error("Invalid CE_SHUFVEC_EX record");
1229      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1230      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1231      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1232                                                 RTy->getNumElements());
1233      Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1234      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1235      break;
1236    }
1237    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1238      if (Record.size() < 4) return Error("Invalid CE_CMP record");
1239      Type *OpTy = getTypeByID(Record[0]);
1240      if (OpTy == 0) return Error("Invalid CE_CMP record");
1241      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1242      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1243
1244      if (OpTy->isFPOrFPVectorTy())
1245        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1246      else
1247        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1248      break;
1249    }
1250    // This maintains backward compatibility, pre-asm dialect keywords.
1251    // FIXME: Remove with the 4.0 release.
1252    case bitc::CST_CODE_INLINEASM_OLD: {
1253      if (Record.size() < 2) return Error("Invalid INLINEASM record");
1254      std::string AsmStr, ConstrStr;
1255      bool HasSideEffects = Record[0] & 1;
1256      bool IsAlignStack = Record[0] >> 1;
1257      unsigned AsmStrSize = Record[1];
1258      if (2+AsmStrSize >= Record.size())
1259        return Error("Invalid INLINEASM record");
1260      unsigned ConstStrSize = Record[2+AsmStrSize];
1261      if (3+AsmStrSize+ConstStrSize > Record.size())
1262        return Error("Invalid INLINEASM record");
1263
1264      for (unsigned i = 0; i != AsmStrSize; ++i)
1265        AsmStr += (char)Record[2+i];
1266      for (unsigned i = 0; i != ConstStrSize; ++i)
1267        ConstrStr += (char)Record[3+AsmStrSize+i];
1268      PointerType *PTy = cast<PointerType>(CurTy);
1269      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1270                         AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1271      break;
1272    }
1273    // This version adds support for the asm dialect keywords (e.g.,
1274    // inteldialect).
1275    case bitc::CST_CODE_INLINEASM: {
1276      if (Record.size() < 2) return Error("Invalid INLINEASM record");
1277      std::string AsmStr, ConstrStr;
1278      bool HasSideEffects = Record[0] & 1;
1279      bool IsAlignStack = (Record[0] >> 1) & 1;
1280      unsigned AsmDialect = Record[0] >> 2;
1281      unsigned AsmStrSize = Record[1];
1282      if (2+AsmStrSize >= Record.size())
1283        return Error("Invalid INLINEASM record");
1284      unsigned ConstStrSize = Record[2+AsmStrSize];
1285      if (3+AsmStrSize+ConstStrSize > Record.size())
1286        return Error("Invalid INLINEASM record");
1287
1288      for (unsigned i = 0; i != AsmStrSize; ++i)
1289        AsmStr += (char)Record[2+i];
1290      for (unsigned i = 0; i != ConstStrSize; ++i)
1291        ConstrStr += (char)Record[3+AsmStrSize+i];
1292      PointerType *PTy = cast<PointerType>(CurTy);
1293      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1294                         AsmStr, ConstrStr, HasSideEffects, IsAlignStack,
1295                         InlineAsm::AsmDialect(AsmDialect));
1296      break;
1297    }
1298    case bitc::CST_CODE_BLOCKADDRESS:{
1299      if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1300      Type *FnTy = getTypeByID(Record[0]);
1301      if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1302      Function *Fn =
1303        dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1304      if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1305
1306      // If the function is already parsed we can insert the block address right
1307      // away.
1308      if (!Fn->empty()) {
1309        Function::iterator BBI = Fn->begin(), BBE = Fn->end();
1310        for (size_t I = 0, E = Record[2]; I != E; ++I) {
1311          if (BBI == BBE)
1312            return Error("Invalid blockaddress block #");
1313          ++BBI;
1314        }
1315        V = BlockAddress::get(Fn, BBI);
1316      } else {
1317        // Otherwise insert a placeholder and remember it so it can be inserted
1318        // when the function is parsed.
1319        GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1320                                                    Type::getInt8Ty(Context),
1321                                            false, GlobalValue::InternalLinkage,
1322                                                    0, "");
1323        BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1324        V = FwdRef;
1325      }
1326      break;
1327    }
1328    }
1329
1330    ValueList.AssignValue(V, NextCstNo);
1331    ++NextCstNo;
1332  }
1333
1334  if (NextCstNo != ValueList.size())
1335    return Error("Invalid constant reference!");
1336
1337  if (Stream.ReadBlockEnd())
1338    return Error("Error at end of constants block");
1339
1340  // Once all the constants have been read, go through and resolve forward
1341  // references.
1342  ValueList.ResolveConstantForwardRefs();
1343  return false;
1344}
1345
1346bool BitcodeReader::ParseUseLists() {
1347  if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1348    return Error("Malformed block record");
1349
1350  SmallVector<uint64_t, 64> Record;
1351
1352  // Read all the records.
1353  while (1) {
1354    unsigned Code = Stream.ReadCode();
1355    if (Code == bitc::END_BLOCK) {
1356      if (Stream.ReadBlockEnd())
1357        return Error("Error at end of use-list table block");
1358      return false;
1359    }
1360
1361    if (Code == bitc::ENTER_SUBBLOCK) {
1362      // No known subblocks, always skip them.
1363      Stream.ReadSubBlockID();
1364      if (Stream.SkipBlock())
1365        return Error("Malformed block record");
1366      continue;
1367    }
1368
1369    if (Code == bitc::DEFINE_ABBREV) {
1370      Stream.ReadAbbrevRecord();
1371      continue;
1372    }
1373
1374    // Read a use list record.
1375    Record.clear();
1376    switch (Stream.ReadRecord(Code, Record)) {
1377    default:  // Default behavior: unknown type.
1378      break;
1379    case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1380      unsigned RecordLength = Record.size();
1381      if (RecordLength < 1)
1382        return Error ("Invalid UseList reader!");
1383      UseListRecords.push_back(Record);
1384      break;
1385    }
1386    }
1387  }
1388}
1389
1390/// RememberAndSkipFunctionBody - When we see the block for a function body,
1391/// remember where it is and then skip it.  This lets us lazily deserialize the
1392/// functions.
1393bool BitcodeReader::RememberAndSkipFunctionBody() {
1394  // Get the function we are talking about.
1395  if (FunctionsWithBodies.empty())
1396    return Error("Insufficient function protos");
1397
1398  Function *Fn = FunctionsWithBodies.back();
1399  FunctionsWithBodies.pop_back();
1400
1401  // Save the current stream state.
1402  uint64_t CurBit = Stream.GetCurrentBitNo();
1403  DeferredFunctionInfo[Fn] = CurBit;
1404
1405  // Skip over the function block for now.
1406  if (Stream.SkipBlock())
1407    return Error("Malformed block record");
1408  return false;
1409}
1410
1411bool BitcodeReader::GlobalCleanup() {
1412  // Patch the initializers for globals and aliases up.
1413  ResolveGlobalAndAliasInits();
1414  if (!GlobalInits.empty() || !AliasInits.empty())
1415    return Error("Malformed global initializer set");
1416
1417  // Look for intrinsic functions which need to be upgraded at some point
1418  for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1419       FI != FE; ++FI) {
1420    Function *NewFn;
1421    if (UpgradeIntrinsicFunction(FI, NewFn))
1422      UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1423  }
1424
1425  // Look for global variables which need to be renamed.
1426  for (Module::global_iterator
1427         GI = TheModule->global_begin(), GE = TheModule->global_end();
1428       GI != GE; ++GI)
1429    UpgradeGlobalVariable(GI);
1430  // Force deallocation of memory for these vectors to favor the client that
1431  // want lazy deserialization.
1432  std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1433  std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1434  return false;
1435}
1436
1437bool BitcodeReader::ParseModule(bool Resume) {
1438  if (Resume)
1439    Stream.JumpToBit(NextUnreadBit);
1440  else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1441    return Error("Malformed block record");
1442
1443  SmallVector<uint64_t, 64> Record;
1444  std::vector<std::string> SectionTable;
1445  std::vector<std::string> GCTable;
1446
1447  // Read all the records for this module.
1448  while (!Stream.AtEndOfStream()) {
1449    unsigned Code = Stream.ReadCode();
1450    if (Code == bitc::END_BLOCK) {
1451      if (Stream.ReadBlockEnd())
1452        return Error("Error at end of module block");
1453
1454      return GlobalCleanup();
1455    }
1456
1457    if (Code == bitc::ENTER_SUBBLOCK) {
1458      switch (Stream.ReadSubBlockID()) {
1459      default:  // Skip unknown content.
1460        if (Stream.SkipBlock())
1461          return Error("Malformed block record");
1462        break;
1463      case bitc::BLOCKINFO_BLOCK_ID:
1464        if (Stream.ReadBlockInfoBlock())
1465          return Error("Malformed BlockInfoBlock");
1466        break;
1467      case bitc::PARAMATTR_BLOCK_ID:
1468        if (ParseAttributeBlock())
1469          return true;
1470        break;
1471      case bitc::TYPE_BLOCK_ID_NEW:
1472        if (ParseTypeTable())
1473          return true;
1474        break;
1475      case bitc::VALUE_SYMTAB_BLOCK_ID:
1476        if (ParseValueSymbolTable())
1477          return true;
1478        SeenValueSymbolTable = true;
1479        break;
1480      case bitc::CONSTANTS_BLOCK_ID:
1481        if (ParseConstants() || ResolveGlobalAndAliasInits())
1482          return true;
1483        break;
1484      case bitc::METADATA_BLOCK_ID:
1485        if (ParseMetadata())
1486          return true;
1487        break;
1488      case bitc::FUNCTION_BLOCK_ID:
1489        // If this is the first function body we've seen, reverse the
1490        // FunctionsWithBodies list.
1491        if (!SeenFirstFunctionBody) {
1492          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1493          if (GlobalCleanup())
1494            return true;
1495          SeenFirstFunctionBody = true;
1496        }
1497
1498        if (RememberAndSkipFunctionBody())
1499          return true;
1500        // For streaming bitcode, suspend parsing when we reach the function
1501        // bodies. Subsequent materialization calls will resume it when
1502        // necessary. For streaming, the function bodies must be at the end of
1503        // the bitcode. If the bitcode file is old, the symbol table will be
1504        // at the end instead and will not have been seen yet. In this case,
1505        // just finish the parse now.
1506        if (LazyStreamer && SeenValueSymbolTable) {
1507          NextUnreadBit = Stream.GetCurrentBitNo();
1508          return false;
1509        }
1510        break;
1511      case bitc::USELIST_BLOCK_ID:
1512        if (ParseUseLists())
1513          return true;
1514        break;
1515      }
1516      continue;
1517    }
1518
1519    if (Code == bitc::DEFINE_ABBREV) {
1520      Stream.ReadAbbrevRecord();
1521      continue;
1522    }
1523
1524    // Read a record.
1525    switch (Stream.ReadRecord(Code, Record)) {
1526    default: break;  // Default behavior, ignore unknown content.
1527    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1528      if (Record.size() < 1)
1529        return Error("Malformed MODULE_CODE_VERSION");
1530      // Only version #0 is supported so far.
1531      if (Record[0] != 0)
1532        return Error("Unknown bitstream version!");
1533      break;
1534    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1535      std::string S;
1536      if (ConvertToString(Record, 0, S))
1537        return Error("Invalid MODULE_CODE_TRIPLE record");
1538      TheModule->setTargetTriple(S);
1539      break;
1540    }
1541    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1542      std::string S;
1543      if (ConvertToString(Record, 0, S))
1544        return Error("Invalid MODULE_CODE_DATALAYOUT record");
1545      TheModule->setDataLayout(S);
1546      break;
1547    }
1548    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1549      std::string S;
1550      if (ConvertToString(Record, 0, S))
1551        return Error("Invalid MODULE_CODE_ASM record");
1552      TheModule->setModuleInlineAsm(S);
1553      break;
1554    }
1555    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1556      std::string S;
1557      if (ConvertToString(Record, 0, S))
1558        return Error("Invalid MODULE_CODE_DEPLIB record");
1559      TheModule->addLibrary(S);
1560      break;
1561    }
1562    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1563      std::string S;
1564      if (ConvertToString(Record, 0, S))
1565        return Error("Invalid MODULE_CODE_SECTIONNAME record");
1566      SectionTable.push_back(S);
1567      break;
1568    }
1569    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1570      std::string S;
1571      if (ConvertToString(Record, 0, S))
1572        return Error("Invalid MODULE_CODE_GCNAME record");
1573      GCTable.push_back(S);
1574      break;
1575    }
1576    // GLOBALVAR: [pointer type, isconst, initid,
1577    //             linkage, alignment, section, visibility, threadlocal,
1578    //             unnamed_addr]
1579    case bitc::MODULE_CODE_GLOBALVAR: {
1580      if (Record.size() < 6)
1581        return Error("Invalid MODULE_CODE_GLOBALVAR record");
1582      Type *Ty = getTypeByID(Record[0]);
1583      if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1584      if (!Ty->isPointerTy())
1585        return Error("Global not a pointer type!");
1586      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1587      Ty = cast<PointerType>(Ty)->getElementType();
1588
1589      bool isConstant = Record[1];
1590      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1591      unsigned Alignment = (1 << Record[4]) >> 1;
1592      std::string Section;
1593      if (Record[5]) {
1594        if (Record[5]-1 >= SectionTable.size())
1595          return Error("Invalid section ID");
1596        Section = SectionTable[Record[5]-1];
1597      }
1598      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1599      if (Record.size() > 6)
1600        Visibility = GetDecodedVisibility(Record[6]);
1601
1602      GlobalVariable::ThreadLocalMode TLM = GlobalVariable::NotThreadLocal;
1603      if (Record.size() > 7)
1604        TLM = GetDecodedThreadLocalMode(Record[7]);
1605
1606      bool UnnamedAddr = false;
1607      if (Record.size() > 8)
1608        UnnamedAddr = Record[8];
1609
1610      GlobalVariable *NewGV =
1611        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1612                           TLM, AddressSpace);
1613      NewGV->setAlignment(Alignment);
1614      if (!Section.empty())
1615        NewGV->setSection(Section);
1616      NewGV->setVisibility(Visibility);
1617      NewGV->setUnnamedAddr(UnnamedAddr);
1618
1619      ValueList.push_back(NewGV);
1620
1621      // Remember which value to use for the global initializer.
1622      if (unsigned InitID = Record[2])
1623        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1624      break;
1625    }
1626    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1627    //             alignment, section, visibility, gc, unnamed_addr]
1628    case bitc::MODULE_CODE_FUNCTION: {
1629      if (Record.size() < 8)
1630        return Error("Invalid MODULE_CODE_FUNCTION record");
1631      Type *Ty = getTypeByID(Record[0]);
1632      if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1633      if (!Ty->isPointerTy())
1634        return Error("Function not a pointer type!");
1635      FunctionType *FTy =
1636        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1637      if (!FTy)
1638        return Error("Function not a pointer to function type!");
1639
1640      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1641                                        "", TheModule);
1642
1643      Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1644      bool isProto = Record[2];
1645      Func->setLinkage(GetDecodedLinkage(Record[3]));
1646      Func->setAttributes(getAttributes(Record[4]));
1647
1648      Func->setAlignment((1 << Record[5]) >> 1);
1649      if (Record[6]) {
1650        if (Record[6]-1 >= SectionTable.size())
1651          return Error("Invalid section ID");
1652        Func->setSection(SectionTable[Record[6]-1]);
1653      }
1654      Func->setVisibility(GetDecodedVisibility(Record[7]));
1655      if (Record.size() > 8 && Record[8]) {
1656        if (Record[8]-1 > GCTable.size())
1657          return Error("Invalid GC ID");
1658        Func->setGC(GCTable[Record[8]-1].c_str());
1659      }
1660      bool UnnamedAddr = false;
1661      if (Record.size() > 9)
1662        UnnamedAddr = Record[9];
1663      Func->setUnnamedAddr(UnnamedAddr);
1664      ValueList.push_back(Func);
1665
1666      // If this is a function with a body, remember the prototype we are
1667      // creating now, so that we can match up the body with them later.
1668      if (!isProto) {
1669        FunctionsWithBodies.push_back(Func);
1670        if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1671      }
1672      break;
1673    }
1674    // ALIAS: [alias type, aliasee val#, linkage]
1675    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1676    case bitc::MODULE_CODE_ALIAS: {
1677      if (Record.size() < 3)
1678        return Error("Invalid MODULE_ALIAS record");
1679      Type *Ty = getTypeByID(Record[0]);
1680      if (!Ty) return Error("Invalid MODULE_ALIAS record");
1681      if (!Ty->isPointerTy())
1682        return Error("Function not a pointer type!");
1683
1684      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1685                                           "", 0, TheModule);
1686      // Old bitcode files didn't have visibility field.
1687      if (Record.size() > 3)
1688        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1689      ValueList.push_back(NewGA);
1690      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1691      break;
1692    }
1693    /// MODULE_CODE_PURGEVALS: [numvals]
1694    case bitc::MODULE_CODE_PURGEVALS:
1695      // Trim down the value list to the specified size.
1696      if (Record.size() < 1 || Record[0] > ValueList.size())
1697        return Error("Invalid MODULE_PURGEVALS record");
1698      ValueList.shrinkTo(Record[0]);
1699      break;
1700    }
1701    Record.clear();
1702  }
1703
1704  return Error("Premature end of bitstream");
1705}
1706
1707bool BitcodeReader::ParseBitcodeInto(Module *M) {
1708  TheModule = 0;
1709
1710  if (InitStream()) return true;
1711
1712  // Sniff for the signature.
1713  if (Stream.Read(8) != 'B' ||
1714      Stream.Read(8) != 'C' ||
1715      Stream.Read(4) != 0x0 ||
1716      Stream.Read(4) != 0xC ||
1717      Stream.Read(4) != 0xE ||
1718      Stream.Read(4) != 0xD)
1719    return Error("Invalid bitcode signature");
1720
1721  // We expect a number of well-defined blocks, though we don't necessarily
1722  // need to understand them all.
1723  while (!Stream.AtEndOfStream()) {
1724    unsigned Code = Stream.ReadCode();
1725
1726    if (Code != bitc::ENTER_SUBBLOCK) {
1727
1728      // The ranlib in xcode 4 will align archive members by appending newlines
1729      // to the end of them. If this file size is a multiple of 4 but not 8, we
1730      // have to read and ignore these final 4 bytes :-(
1731      if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1732          Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1733          Stream.AtEndOfStream())
1734        return false;
1735
1736      return Error("Invalid record at top-level");
1737    }
1738
1739    unsigned BlockID = Stream.ReadSubBlockID();
1740
1741    // We only know the MODULE subblock ID.
1742    switch (BlockID) {
1743    case bitc::BLOCKINFO_BLOCK_ID:
1744      if (Stream.ReadBlockInfoBlock())
1745        return Error("Malformed BlockInfoBlock");
1746      break;
1747    case bitc::MODULE_BLOCK_ID:
1748      // Reject multiple MODULE_BLOCK's in a single bitstream.
1749      if (TheModule)
1750        return Error("Multiple MODULE_BLOCKs in same stream");
1751      TheModule = M;
1752      if (ParseModule(false))
1753        return true;
1754      if (LazyStreamer) return false;
1755      break;
1756    default:
1757      if (Stream.SkipBlock())
1758        return Error("Malformed block record");
1759      break;
1760    }
1761  }
1762
1763  return false;
1764}
1765
1766bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1767  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1768    return Error("Malformed block record");
1769
1770  SmallVector<uint64_t, 64> Record;
1771
1772  // Read all the records for this module.
1773  while (!Stream.AtEndOfStream()) {
1774    unsigned Code = Stream.ReadCode();
1775    if (Code == bitc::END_BLOCK) {
1776      if (Stream.ReadBlockEnd())
1777        return Error("Error at end of module block");
1778
1779      return false;
1780    }
1781
1782    if (Code == bitc::ENTER_SUBBLOCK) {
1783      switch (Stream.ReadSubBlockID()) {
1784      default:  // Skip unknown content.
1785        if (Stream.SkipBlock())
1786          return Error("Malformed block record");
1787        break;
1788      }
1789      continue;
1790    }
1791
1792    if (Code == bitc::DEFINE_ABBREV) {
1793      Stream.ReadAbbrevRecord();
1794      continue;
1795    }
1796
1797    // Read a record.
1798    switch (Stream.ReadRecord(Code, Record)) {
1799    default: break;  // Default behavior, ignore unknown content.
1800    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1801      if (Record.size() < 1)
1802        return Error("Malformed MODULE_CODE_VERSION");
1803      // Only version #0 is supported so far.
1804      if (Record[0] != 0)
1805        return Error("Unknown bitstream version!");
1806      break;
1807    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1808      std::string S;
1809      if (ConvertToString(Record, 0, S))
1810        return Error("Invalid MODULE_CODE_TRIPLE record");
1811      Triple = S;
1812      break;
1813    }
1814    }
1815    Record.clear();
1816  }
1817
1818  return Error("Premature end of bitstream");
1819}
1820
1821bool BitcodeReader::ParseTriple(std::string &Triple) {
1822  if (InitStream()) return true;
1823
1824  // Sniff for the signature.
1825  if (Stream.Read(8) != 'B' ||
1826      Stream.Read(8) != 'C' ||
1827      Stream.Read(4) != 0x0 ||
1828      Stream.Read(4) != 0xC ||
1829      Stream.Read(4) != 0xE ||
1830      Stream.Read(4) != 0xD)
1831    return Error("Invalid bitcode signature");
1832
1833  // We expect a number of well-defined blocks, though we don't necessarily
1834  // need to understand them all.
1835  while (!Stream.AtEndOfStream()) {
1836    unsigned Code = Stream.ReadCode();
1837
1838    if (Code != bitc::ENTER_SUBBLOCK)
1839      return Error("Invalid record at top-level");
1840
1841    unsigned BlockID = Stream.ReadSubBlockID();
1842
1843    // We only know the MODULE subblock ID.
1844    switch (BlockID) {
1845    case bitc::MODULE_BLOCK_ID:
1846      if (ParseModuleTriple(Triple))
1847        return true;
1848      break;
1849    default:
1850      if (Stream.SkipBlock())
1851        return Error("Malformed block record");
1852      break;
1853    }
1854  }
1855
1856  return false;
1857}
1858
1859/// ParseMetadataAttachment - Parse metadata attachments.
1860bool BitcodeReader::ParseMetadataAttachment() {
1861  if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1862    return Error("Malformed block record");
1863
1864  SmallVector<uint64_t, 64> Record;
1865  while(1) {
1866    unsigned Code = Stream.ReadCode();
1867    if (Code == bitc::END_BLOCK) {
1868      if (Stream.ReadBlockEnd())
1869        return Error("Error at end of PARAMATTR block");
1870      break;
1871    }
1872    if (Code == bitc::DEFINE_ABBREV) {
1873      Stream.ReadAbbrevRecord();
1874      continue;
1875    }
1876    // Read a metadata attachment record.
1877    Record.clear();
1878    switch (Stream.ReadRecord(Code, Record)) {
1879    default:  // Default behavior: ignore.
1880      break;
1881    case bitc::METADATA_ATTACHMENT: {
1882      unsigned RecordLength = Record.size();
1883      if (Record.empty() || (RecordLength - 1) % 2 == 1)
1884        return Error ("Invalid METADATA_ATTACHMENT reader!");
1885      Instruction *Inst = InstructionList[Record[0]];
1886      for (unsigned i = 1; i != RecordLength; i = i+2) {
1887        unsigned Kind = Record[i];
1888        DenseMap<unsigned, unsigned>::iterator I =
1889          MDKindMap.find(Kind);
1890        if (I == MDKindMap.end())
1891          return Error("Invalid metadata kind ID");
1892        Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1893        Inst->setMetadata(I->second, cast<MDNode>(Node));
1894      }
1895      break;
1896    }
1897    }
1898  }
1899  return false;
1900}
1901
1902/// ParseFunctionBody - Lazily parse the specified function body block.
1903bool BitcodeReader::ParseFunctionBody(Function *F) {
1904  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1905    return Error("Malformed block record");
1906
1907  InstructionList.clear();
1908  unsigned ModuleValueListSize = ValueList.size();
1909  unsigned ModuleMDValueListSize = MDValueList.size();
1910
1911  // Add all the function arguments to the value table.
1912  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1913    ValueList.push_back(I);
1914
1915  unsigned NextValueNo = ValueList.size();
1916  BasicBlock *CurBB = 0;
1917  unsigned CurBBNo = 0;
1918
1919  DebugLoc LastLoc;
1920
1921  // Read all the records.
1922  SmallVector<uint64_t, 64> Record;
1923  while (1) {
1924    unsigned Code = Stream.ReadCode();
1925    if (Code == bitc::END_BLOCK) {
1926      if (Stream.ReadBlockEnd())
1927        return Error("Error at end of function block");
1928      break;
1929    }
1930
1931    if (Code == bitc::ENTER_SUBBLOCK) {
1932      switch (Stream.ReadSubBlockID()) {
1933      default:  // Skip unknown content.
1934        if (Stream.SkipBlock())
1935          return Error("Malformed block record");
1936        break;
1937      case bitc::CONSTANTS_BLOCK_ID:
1938        if (ParseConstants()) return true;
1939        NextValueNo = ValueList.size();
1940        break;
1941      case bitc::VALUE_SYMTAB_BLOCK_ID:
1942        if (ParseValueSymbolTable()) return true;
1943        break;
1944      case bitc::METADATA_ATTACHMENT_ID:
1945        if (ParseMetadataAttachment()) return true;
1946        break;
1947      case bitc::METADATA_BLOCK_ID:
1948        if (ParseMetadata()) return true;
1949        break;
1950      }
1951      continue;
1952    }
1953
1954    if (Code == bitc::DEFINE_ABBREV) {
1955      Stream.ReadAbbrevRecord();
1956      continue;
1957    }
1958
1959    // Read a record.
1960    Record.clear();
1961    Instruction *I = 0;
1962    unsigned BitCode = Stream.ReadRecord(Code, Record);
1963    switch (BitCode) {
1964    default: // Default behavior: reject
1965      return Error("Unknown instruction");
1966    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1967      if (Record.size() < 1 || Record[0] == 0)
1968        return Error("Invalid DECLAREBLOCKS record");
1969      // Create all the basic blocks for the function.
1970      FunctionBBs.resize(Record[0]);
1971      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1972        FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1973      CurBB = FunctionBBs[0];
1974      continue;
1975
1976    case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
1977      // This record indicates that the last instruction is at the same
1978      // location as the previous instruction with a location.
1979      I = 0;
1980
1981      // Get the last instruction emitted.
1982      if (CurBB && !CurBB->empty())
1983        I = &CurBB->back();
1984      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1985               !FunctionBBs[CurBBNo-1]->empty())
1986        I = &FunctionBBs[CurBBNo-1]->back();
1987
1988      if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1989      I->setDebugLoc(LastLoc);
1990      I = 0;
1991      continue;
1992
1993    case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
1994      I = 0;     // Get the last instruction emitted.
1995      if (CurBB && !CurBB->empty())
1996        I = &CurBB->back();
1997      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1998               !FunctionBBs[CurBBNo-1]->empty())
1999        I = &FunctionBBs[CurBBNo-1]->back();
2000      if (I == 0 || Record.size() < 4)
2001        return Error("Invalid FUNC_CODE_DEBUG_LOC record");
2002
2003      unsigned Line = Record[0], Col = Record[1];
2004      unsigned ScopeID = Record[2], IAID = Record[3];
2005
2006      MDNode *Scope = 0, *IA = 0;
2007      if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
2008      if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
2009      LastLoc = DebugLoc::get(Line, Col, Scope, IA);
2010      I->setDebugLoc(LastLoc);
2011      I = 0;
2012      continue;
2013    }
2014
2015    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
2016      unsigned OpNum = 0;
2017      Value *LHS, *RHS;
2018      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2019          getValue(Record, OpNum, LHS->getType(), RHS) ||
2020          OpNum+1 > Record.size())
2021        return Error("Invalid BINOP record");
2022
2023      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
2024      if (Opc == -1) return Error("Invalid BINOP record");
2025      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
2026      InstructionList.push_back(I);
2027      if (OpNum < Record.size()) {
2028        if (Opc == Instruction::Add ||
2029            Opc == Instruction::Sub ||
2030            Opc == Instruction::Mul ||
2031            Opc == Instruction::Shl) {
2032          if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
2033            cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
2034          if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
2035            cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
2036        } else if (Opc == Instruction::SDiv ||
2037                   Opc == Instruction::UDiv ||
2038                   Opc == Instruction::LShr ||
2039                   Opc == Instruction::AShr) {
2040          if (Record[OpNum] & (1 << bitc::PEO_EXACT))
2041            cast<BinaryOperator>(I)->setIsExact(true);
2042        }
2043      }
2044      break;
2045    }
2046    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2047      unsigned OpNum = 0;
2048      Value *Op;
2049      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2050          OpNum+2 != Record.size())
2051        return Error("Invalid CAST record");
2052
2053      Type *ResTy = getTypeByID(Record[OpNum]);
2054      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2055      if (Opc == -1 || ResTy == 0)
2056        return Error("Invalid CAST record");
2057      I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2058      InstructionList.push_back(I);
2059      break;
2060    }
2061    case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2062    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2063      unsigned OpNum = 0;
2064      Value *BasePtr;
2065      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2066        return Error("Invalid GEP record");
2067
2068      SmallVector<Value*, 16> GEPIdx;
2069      while (OpNum != Record.size()) {
2070        Value *Op;
2071        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2072          return Error("Invalid GEP record");
2073        GEPIdx.push_back(Op);
2074      }
2075
2076      I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2077      InstructionList.push_back(I);
2078      if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2079        cast<GetElementPtrInst>(I)->setIsInBounds(true);
2080      break;
2081    }
2082
2083    case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2084                                       // EXTRACTVAL: [opty, opval, n x indices]
2085      unsigned OpNum = 0;
2086      Value *Agg;
2087      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2088        return Error("Invalid EXTRACTVAL record");
2089
2090      SmallVector<unsigned, 4> EXTRACTVALIdx;
2091      for (unsigned RecSize = Record.size();
2092           OpNum != RecSize; ++OpNum) {
2093        uint64_t Index = Record[OpNum];
2094        if ((unsigned)Index != Index)
2095          return Error("Invalid EXTRACTVAL index");
2096        EXTRACTVALIdx.push_back((unsigned)Index);
2097      }
2098
2099      I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2100      InstructionList.push_back(I);
2101      break;
2102    }
2103
2104    case bitc::FUNC_CODE_INST_INSERTVAL: {
2105                           // INSERTVAL: [opty, opval, opty, opval, n x indices]
2106      unsigned OpNum = 0;
2107      Value *Agg;
2108      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2109        return Error("Invalid INSERTVAL record");
2110      Value *Val;
2111      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2112        return Error("Invalid INSERTVAL record");
2113
2114      SmallVector<unsigned, 4> INSERTVALIdx;
2115      for (unsigned RecSize = Record.size();
2116           OpNum != RecSize; ++OpNum) {
2117        uint64_t Index = Record[OpNum];
2118        if ((unsigned)Index != Index)
2119          return Error("Invalid INSERTVAL index");
2120        INSERTVALIdx.push_back((unsigned)Index);
2121      }
2122
2123      I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2124      InstructionList.push_back(I);
2125      break;
2126    }
2127
2128    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2129      // obsolete form of select
2130      // handles select i1 ... in old bitcode
2131      unsigned OpNum = 0;
2132      Value *TrueVal, *FalseVal, *Cond;
2133      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2134          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2135          getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2136        return Error("Invalid SELECT record");
2137
2138      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2139      InstructionList.push_back(I);
2140      break;
2141    }
2142
2143    case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2144      // new form of select
2145      // handles select i1 or select [N x i1]
2146      unsigned OpNum = 0;
2147      Value *TrueVal, *FalseVal, *Cond;
2148      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2149          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2150          getValueTypePair(Record, OpNum, NextValueNo, Cond))
2151        return Error("Invalid SELECT record");
2152
2153      // select condition can be either i1 or [N x i1]
2154      if (VectorType* vector_type =
2155          dyn_cast<VectorType>(Cond->getType())) {
2156        // expect <n x i1>
2157        if (vector_type->getElementType() != Type::getInt1Ty(Context))
2158          return Error("Invalid SELECT condition type");
2159      } else {
2160        // expect i1
2161        if (Cond->getType() != Type::getInt1Ty(Context))
2162          return Error("Invalid SELECT condition type");
2163      }
2164
2165      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2166      InstructionList.push_back(I);
2167      break;
2168    }
2169
2170    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2171      unsigned OpNum = 0;
2172      Value *Vec, *Idx;
2173      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2174          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2175        return Error("Invalid EXTRACTELT record");
2176      I = ExtractElementInst::Create(Vec, Idx);
2177      InstructionList.push_back(I);
2178      break;
2179    }
2180
2181    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2182      unsigned OpNum = 0;
2183      Value *Vec, *Elt, *Idx;
2184      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2185          getValue(Record, OpNum,
2186                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2187          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2188        return Error("Invalid INSERTELT record");
2189      I = InsertElementInst::Create(Vec, Elt, Idx);
2190      InstructionList.push_back(I);
2191      break;
2192    }
2193
2194    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2195      unsigned OpNum = 0;
2196      Value *Vec1, *Vec2, *Mask;
2197      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2198          getValue(Record, OpNum, Vec1->getType(), Vec2))
2199        return Error("Invalid SHUFFLEVEC record");
2200
2201      if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2202        return Error("Invalid SHUFFLEVEC record");
2203      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2204      InstructionList.push_back(I);
2205      break;
2206    }
2207
2208    case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2209      // Old form of ICmp/FCmp returning bool
2210      // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2211      // both legal on vectors but had different behaviour.
2212    case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2213      // FCmp/ICmp returning bool or vector of bool
2214
2215      unsigned OpNum = 0;
2216      Value *LHS, *RHS;
2217      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2218          getValue(Record, OpNum, LHS->getType(), RHS) ||
2219          OpNum+1 != Record.size())
2220        return Error("Invalid CMP record");
2221
2222      if (LHS->getType()->isFPOrFPVectorTy())
2223        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2224      else
2225        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2226      InstructionList.push_back(I);
2227      break;
2228    }
2229
2230    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2231      {
2232        unsigned Size = Record.size();
2233        if (Size == 0) {
2234          I = ReturnInst::Create(Context);
2235          InstructionList.push_back(I);
2236          break;
2237        }
2238
2239        unsigned OpNum = 0;
2240        Value *Op = NULL;
2241        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2242          return Error("Invalid RET record");
2243        if (OpNum != Record.size())
2244          return Error("Invalid RET record");
2245
2246        I = ReturnInst::Create(Context, Op);
2247        InstructionList.push_back(I);
2248        break;
2249      }
2250    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2251      if (Record.size() != 1 && Record.size() != 3)
2252        return Error("Invalid BR record");
2253      BasicBlock *TrueDest = getBasicBlock(Record[0]);
2254      if (TrueDest == 0)
2255        return Error("Invalid BR record");
2256
2257      if (Record.size() == 1) {
2258        I = BranchInst::Create(TrueDest);
2259        InstructionList.push_back(I);
2260      }
2261      else {
2262        BasicBlock *FalseDest = getBasicBlock(Record[1]);
2263        Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2264        if (FalseDest == 0 || Cond == 0)
2265          return Error("Invalid BR record");
2266        I = BranchInst::Create(TrueDest, FalseDest, Cond);
2267        InstructionList.push_back(I);
2268      }
2269      break;
2270    }
2271    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2272      // Check magic
2273      if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2274        // New SwitchInst format with case ranges.
2275
2276        Type *OpTy = getTypeByID(Record[1]);
2277        unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2278
2279        Value *Cond = getFnValueByID(Record[2], OpTy);
2280        BasicBlock *Default = getBasicBlock(Record[3]);
2281        if (OpTy == 0 || Cond == 0 || Default == 0)
2282          return Error("Invalid SWITCH record");
2283
2284        unsigned NumCases = Record[4];
2285
2286        SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2287        InstructionList.push_back(SI);
2288
2289        unsigned CurIdx = 5;
2290        for (unsigned i = 0; i != NumCases; ++i) {
2291          IntegersSubsetToBB CaseBuilder;
2292          unsigned NumItems = Record[CurIdx++];
2293          for (unsigned ci = 0; ci != NumItems; ++ci) {
2294            bool isSingleNumber = Record[CurIdx++];
2295
2296            APInt Low;
2297            unsigned ActiveWords = 1;
2298            if (ValueBitWidth > 64)
2299              ActiveWords = Record[CurIdx++];
2300            Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2301                                ValueBitWidth);
2302            CurIdx += ActiveWords;
2303
2304            if (!isSingleNumber) {
2305              ActiveWords = 1;
2306              if (ValueBitWidth > 64)
2307                ActiveWords = Record[CurIdx++];
2308              APInt High =
2309                  ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2310                                ValueBitWidth);
2311
2312              CaseBuilder.add(IntItem::fromType(OpTy, Low),
2313                              IntItem::fromType(OpTy, High));
2314              CurIdx += ActiveWords;
2315            } else
2316              CaseBuilder.add(IntItem::fromType(OpTy, Low));
2317          }
2318          BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2319          IntegersSubset Case = CaseBuilder.getCase();
2320          SI->addCase(Case, DestBB);
2321        }
2322        uint16_t Hash = SI->hash();
2323        if (Hash != (Record[0] & 0xFFFF))
2324          return Error("Invalid SWITCH record");
2325        I = SI;
2326        break;
2327      }
2328
2329      // Old SwitchInst format without case ranges.
2330
2331      if (Record.size() < 3 || (Record.size() & 1) == 0)
2332        return Error("Invalid SWITCH record");
2333      Type *OpTy = getTypeByID(Record[0]);
2334      Value *Cond = getFnValueByID(Record[1], OpTy);
2335      BasicBlock *Default = getBasicBlock(Record[2]);
2336      if (OpTy == 0 || Cond == 0 || Default == 0)
2337        return Error("Invalid SWITCH record");
2338      unsigned NumCases = (Record.size()-3)/2;
2339      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2340      InstructionList.push_back(SI);
2341      for (unsigned i = 0, e = NumCases; i != e; ++i) {
2342        ConstantInt *CaseVal =
2343          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2344        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2345        if (CaseVal == 0 || DestBB == 0) {
2346          delete SI;
2347          return Error("Invalid SWITCH record!");
2348        }
2349        SI->addCase(CaseVal, DestBB);
2350      }
2351      I = SI;
2352      break;
2353    }
2354    case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2355      if (Record.size() < 2)
2356        return Error("Invalid INDIRECTBR record");
2357      Type *OpTy = getTypeByID(Record[0]);
2358      Value *Address = getFnValueByID(Record[1], OpTy);
2359      if (OpTy == 0 || Address == 0)
2360        return Error("Invalid INDIRECTBR record");
2361      unsigned NumDests = Record.size()-2;
2362      IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2363      InstructionList.push_back(IBI);
2364      for (unsigned i = 0, e = NumDests; i != e; ++i) {
2365        if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2366          IBI->addDestination(DestBB);
2367        } else {
2368          delete IBI;
2369          return Error("Invalid INDIRECTBR record!");
2370        }
2371      }
2372      I = IBI;
2373      break;
2374    }
2375
2376    case bitc::FUNC_CODE_INST_INVOKE: {
2377      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2378      if (Record.size() < 4) return Error("Invalid INVOKE record");
2379      AttrListPtr PAL = getAttributes(Record[0]);
2380      unsigned CCInfo = Record[1];
2381      BasicBlock *NormalBB = getBasicBlock(Record[2]);
2382      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2383
2384      unsigned OpNum = 4;
2385      Value *Callee;
2386      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2387        return Error("Invalid INVOKE record");
2388
2389      PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2390      FunctionType *FTy = !CalleeTy ? 0 :
2391        dyn_cast<FunctionType>(CalleeTy->getElementType());
2392
2393      // Check that the right number of fixed parameters are here.
2394      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2395          Record.size() < OpNum+FTy->getNumParams())
2396        return Error("Invalid INVOKE record");
2397
2398      SmallVector<Value*, 16> Ops;
2399      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2400        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2401        if (Ops.back() == 0) return Error("Invalid INVOKE record");
2402      }
2403
2404      if (!FTy->isVarArg()) {
2405        if (Record.size() != OpNum)
2406          return Error("Invalid INVOKE record");
2407      } else {
2408        // Read type/value pairs for varargs params.
2409        while (OpNum != Record.size()) {
2410          Value *Op;
2411          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2412            return Error("Invalid INVOKE record");
2413          Ops.push_back(Op);
2414        }
2415      }
2416
2417      I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2418      InstructionList.push_back(I);
2419      cast<InvokeInst>(I)->setCallingConv(
2420        static_cast<CallingConv::ID>(CCInfo));
2421      cast<InvokeInst>(I)->setAttributes(PAL);
2422      break;
2423    }
2424    case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2425      unsigned Idx = 0;
2426      Value *Val = 0;
2427      if (getValueTypePair(Record, Idx, NextValueNo, Val))
2428        return Error("Invalid RESUME record");
2429      I = ResumeInst::Create(Val);
2430      InstructionList.push_back(I);
2431      break;
2432    }
2433    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2434      I = new UnreachableInst(Context);
2435      InstructionList.push_back(I);
2436      break;
2437    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2438      if (Record.size() < 1 || ((Record.size()-1)&1))
2439        return Error("Invalid PHI record");
2440      Type *Ty = getTypeByID(Record[0]);
2441      if (!Ty) return Error("Invalid PHI record");
2442
2443      PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2444      InstructionList.push_back(PN);
2445
2446      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2447        Value *V = getFnValueByID(Record[1+i], Ty);
2448        BasicBlock *BB = getBasicBlock(Record[2+i]);
2449        if (!V || !BB) return Error("Invalid PHI record");
2450        PN->addIncoming(V, BB);
2451      }
2452      I = PN;
2453      break;
2454    }
2455
2456    case bitc::FUNC_CODE_INST_LANDINGPAD: {
2457      // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2458      unsigned Idx = 0;
2459      if (Record.size() < 4)
2460        return Error("Invalid LANDINGPAD record");
2461      Type *Ty = getTypeByID(Record[Idx++]);
2462      if (!Ty) return Error("Invalid LANDINGPAD record");
2463      Value *PersFn = 0;
2464      if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2465        return Error("Invalid LANDINGPAD record");
2466
2467      bool IsCleanup = !!Record[Idx++];
2468      unsigned NumClauses = Record[Idx++];
2469      LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2470      LP->setCleanup(IsCleanup);
2471      for (unsigned J = 0; J != NumClauses; ++J) {
2472        LandingPadInst::ClauseType CT =
2473          LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2474        Value *Val;
2475
2476        if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2477          delete LP;
2478          return Error("Invalid LANDINGPAD record");
2479        }
2480
2481        assert((CT != LandingPadInst::Catch ||
2482                !isa<ArrayType>(Val->getType())) &&
2483               "Catch clause has a invalid type!");
2484        assert((CT != LandingPadInst::Filter ||
2485                isa<ArrayType>(Val->getType())) &&
2486               "Filter clause has invalid type!");
2487        LP->addClause(Val);
2488      }
2489
2490      I = LP;
2491      InstructionList.push_back(I);
2492      break;
2493    }
2494
2495    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2496      if (Record.size() != 4)
2497        return Error("Invalid ALLOCA record");
2498      PointerType *Ty =
2499        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2500      Type *OpTy = getTypeByID(Record[1]);
2501      Value *Size = getFnValueByID(Record[2], OpTy);
2502      unsigned Align = Record[3];
2503      if (!Ty || !Size) return Error("Invalid ALLOCA record");
2504      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2505      InstructionList.push_back(I);
2506      break;
2507    }
2508    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2509      unsigned OpNum = 0;
2510      Value *Op;
2511      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2512          OpNum+2 != Record.size())
2513        return Error("Invalid LOAD record");
2514
2515      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2516      InstructionList.push_back(I);
2517      break;
2518    }
2519    case bitc::FUNC_CODE_INST_LOADATOMIC: {
2520       // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2521      unsigned OpNum = 0;
2522      Value *Op;
2523      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2524          OpNum+4 != Record.size())
2525        return Error("Invalid LOADATOMIC record");
2526
2527
2528      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2529      if (Ordering == NotAtomic || Ordering == Release ||
2530          Ordering == AcquireRelease)
2531        return Error("Invalid LOADATOMIC record");
2532      if (Ordering != NotAtomic && Record[OpNum] == 0)
2533        return Error("Invalid LOADATOMIC record");
2534      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2535
2536      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2537                       Ordering, SynchScope);
2538      InstructionList.push_back(I);
2539      break;
2540    }
2541    case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2542      unsigned OpNum = 0;
2543      Value *Val, *Ptr;
2544      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2545          getValue(Record, OpNum,
2546                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2547          OpNum+2 != Record.size())
2548        return Error("Invalid STORE record");
2549
2550      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2551      InstructionList.push_back(I);
2552      break;
2553    }
2554    case bitc::FUNC_CODE_INST_STOREATOMIC: {
2555      // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2556      unsigned OpNum = 0;
2557      Value *Val, *Ptr;
2558      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2559          getValue(Record, OpNum,
2560                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2561          OpNum+4 != Record.size())
2562        return Error("Invalid STOREATOMIC record");
2563
2564      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2565      if (Ordering == NotAtomic || Ordering == Acquire ||
2566          Ordering == AcquireRelease)
2567        return Error("Invalid STOREATOMIC record");
2568      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2569      if (Ordering != NotAtomic && Record[OpNum] == 0)
2570        return Error("Invalid STOREATOMIC record");
2571
2572      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2573                        Ordering, SynchScope);
2574      InstructionList.push_back(I);
2575      break;
2576    }
2577    case bitc::FUNC_CODE_INST_CMPXCHG: {
2578      // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2579      unsigned OpNum = 0;
2580      Value *Ptr, *Cmp, *New;
2581      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2582          getValue(Record, OpNum,
2583                    cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2584          getValue(Record, OpNum,
2585                    cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2586          OpNum+3 != Record.size())
2587        return Error("Invalid CMPXCHG record");
2588      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2589      if (Ordering == NotAtomic || Ordering == Unordered)
2590        return Error("Invalid CMPXCHG record");
2591      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2592      I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2593      cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2594      InstructionList.push_back(I);
2595      break;
2596    }
2597    case bitc::FUNC_CODE_INST_ATOMICRMW: {
2598      // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2599      unsigned OpNum = 0;
2600      Value *Ptr, *Val;
2601      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2602          getValue(Record, OpNum,
2603                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2604          OpNum+4 != Record.size())
2605        return Error("Invalid ATOMICRMW record");
2606      AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2607      if (Operation < AtomicRMWInst::FIRST_BINOP ||
2608          Operation > AtomicRMWInst::LAST_BINOP)
2609        return Error("Invalid ATOMICRMW record");
2610      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2611      if (Ordering == NotAtomic || Ordering == Unordered)
2612        return Error("Invalid ATOMICRMW record");
2613      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2614      I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2615      cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2616      InstructionList.push_back(I);
2617      break;
2618    }
2619    case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2620      if (2 != Record.size())
2621        return Error("Invalid FENCE record");
2622      AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2623      if (Ordering == NotAtomic || Ordering == Unordered ||
2624          Ordering == Monotonic)
2625        return Error("Invalid FENCE record");
2626      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2627      I = new FenceInst(Context, Ordering, SynchScope);
2628      InstructionList.push_back(I);
2629      break;
2630    }
2631    case bitc::FUNC_CODE_INST_CALL: {
2632      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2633      if (Record.size() < 3)
2634        return Error("Invalid CALL record");
2635
2636      AttrListPtr PAL = getAttributes(Record[0]);
2637      unsigned CCInfo = Record[1];
2638
2639      unsigned OpNum = 2;
2640      Value *Callee;
2641      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2642        return Error("Invalid CALL record");
2643
2644      PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2645      FunctionType *FTy = 0;
2646      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2647      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2648        return Error("Invalid CALL record");
2649
2650      SmallVector<Value*, 16> Args;
2651      // Read the fixed params.
2652      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2653        if (FTy->getParamType(i)->isLabelTy())
2654          Args.push_back(getBasicBlock(Record[OpNum]));
2655        else
2656          Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2657        if (Args.back() == 0) return Error("Invalid CALL record");
2658      }
2659
2660      // Read type/value pairs for varargs params.
2661      if (!FTy->isVarArg()) {
2662        if (OpNum != Record.size())
2663          return Error("Invalid CALL record");
2664      } else {
2665        while (OpNum != Record.size()) {
2666          Value *Op;
2667          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2668            return Error("Invalid CALL record");
2669          Args.push_back(Op);
2670        }
2671      }
2672
2673      I = CallInst::Create(Callee, Args);
2674      InstructionList.push_back(I);
2675      cast<CallInst>(I)->setCallingConv(
2676        static_cast<CallingConv::ID>(CCInfo>>1));
2677      cast<CallInst>(I)->setTailCall(CCInfo & 1);
2678      cast<CallInst>(I)->setAttributes(PAL);
2679      break;
2680    }
2681    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2682      if (Record.size() < 3)
2683        return Error("Invalid VAARG record");
2684      Type *OpTy = getTypeByID(Record[0]);
2685      Value *Op = getFnValueByID(Record[1], OpTy);
2686      Type *ResTy = getTypeByID(Record[2]);
2687      if (!OpTy || !Op || !ResTy)
2688        return Error("Invalid VAARG record");
2689      I = new VAArgInst(Op, ResTy);
2690      InstructionList.push_back(I);
2691      break;
2692    }
2693    }
2694
2695    // Add instruction to end of current BB.  If there is no current BB, reject
2696    // this file.
2697    if (CurBB == 0) {
2698      delete I;
2699      return Error("Invalid instruction with no BB");
2700    }
2701    CurBB->getInstList().push_back(I);
2702
2703    // If this was a terminator instruction, move to the next block.
2704    if (isa<TerminatorInst>(I)) {
2705      ++CurBBNo;
2706      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2707    }
2708
2709    // Non-void values get registered in the value table for future use.
2710    if (I && !I->getType()->isVoidTy())
2711      ValueList.AssignValue(I, NextValueNo++);
2712  }
2713
2714  // Check the function list for unresolved values.
2715  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2716    if (A->getParent() == 0) {
2717      // We found at least one unresolved value.  Nuke them all to avoid leaks.
2718      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2719        if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2720          A->replaceAllUsesWith(UndefValue::get(A->getType()));
2721          delete A;
2722        }
2723      }
2724      return Error("Never resolved value found in function!");
2725    }
2726  }
2727
2728  // FIXME: Check for unresolved forward-declared metadata references
2729  // and clean up leaks.
2730
2731  // See if anything took the address of blocks in this function.  If so,
2732  // resolve them now.
2733  DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2734    BlockAddrFwdRefs.find(F);
2735  if (BAFRI != BlockAddrFwdRefs.end()) {
2736    std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2737    for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2738      unsigned BlockIdx = RefList[i].first;
2739      if (BlockIdx >= FunctionBBs.size())
2740        return Error("Invalid blockaddress block #");
2741
2742      GlobalVariable *FwdRef = RefList[i].second;
2743      FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2744      FwdRef->eraseFromParent();
2745    }
2746
2747    BlockAddrFwdRefs.erase(BAFRI);
2748  }
2749
2750  // Trim the value list down to the size it was before we parsed this function.
2751  ValueList.shrinkTo(ModuleValueListSize);
2752  MDValueList.shrinkTo(ModuleMDValueListSize);
2753  std::vector<BasicBlock*>().swap(FunctionBBs);
2754  return false;
2755}
2756
2757/// FindFunctionInStream - Find the function body in the bitcode stream
2758bool BitcodeReader::FindFunctionInStream(Function *F,
2759       DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2760  while (DeferredFunctionInfoIterator->second == 0) {
2761    if (Stream.AtEndOfStream())
2762      return Error("Could not find Function in stream");
2763    // ParseModule will parse the next body in the stream and set its
2764    // position in the DeferredFunctionInfo map.
2765    if (ParseModule(true)) return true;
2766  }
2767  return false;
2768}
2769
2770//===----------------------------------------------------------------------===//
2771// GVMaterializer implementation
2772//===----------------------------------------------------------------------===//
2773
2774
2775bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2776  if (const Function *F = dyn_cast<Function>(GV)) {
2777    return F->isDeclaration() &&
2778      DeferredFunctionInfo.count(const_cast<Function*>(F));
2779  }
2780  return false;
2781}
2782
2783bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2784  Function *F = dyn_cast<Function>(GV);
2785  // If it's not a function or is already material, ignore the request.
2786  if (!F || !F->isMaterializable()) return false;
2787
2788  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2789  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2790  // If its position is recorded as 0, its body is somewhere in the stream
2791  // but we haven't seen it yet.
2792  if (DFII->second == 0)
2793    if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
2794
2795  // Move the bit stream to the saved position of the deferred function body.
2796  Stream.JumpToBit(DFII->second);
2797
2798  if (ParseFunctionBody(F)) {
2799    if (ErrInfo) *ErrInfo = ErrorString;
2800    return true;
2801  }
2802
2803  // Upgrade any old intrinsic calls in the function.
2804  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2805       E = UpgradedIntrinsics.end(); I != E; ++I) {
2806    if (I->first != I->second) {
2807      for (Value::use_iterator UI = I->first->use_begin(),
2808           UE = I->first->use_end(); UI != UE; ) {
2809        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2810          UpgradeIntrinsicCall(CI, I->second);
2811      }
2812    }
2813  }
2814
2815  return false;
2816}
2817
2818bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2819  const Function *F = dyn_cast<Function>(GV);
2820  if (!F || F->isDeclaration())
2821    return false;
2822  return DeferredFunctionInfo.count(const_cast<Function*>(F));
2823}
2824
2825void BitcodeReader::Dematerialize(GlobalValue *GV) {
2826  Function *F = dyn_cast<Function>(GV);
2827  // If this function isn't dematerializable, this is a noop.
2828  if (!F || !isDematerializable(F))
2829    return;
2830
2831  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2832
2833  // Just forget the function body, we can remat it later.
2834  F->deleteBody();
2835}
2836
2837
2838bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2839  assert(M == TheModule &&
2840         "Can only Materialize the Module this BitcodeReader is attached to.");
2841  // Iterate over the module, deserializing any functions that are still on
2842  // disk.
2843  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2844       F != E; ++F)
2845    if (F->isMaterializable() &&
2846        Materialize(F, ErrInfo))
2847      return true;
2848
2849  // At this point, if there are any function bodies, the current bit is
2850  // pointing to the END_BLOCK record after them. Now make sure the rest
2851  // of the bits in the module have been read.
2852  if (NextUnreadBit)
2853    ParseModule(true);
2854
2855  // Upgrade any intrinsic calls that slipped through (should not happen!) and
2856  // delete the old functions to clean up. We can't do this unless the entire
2857  // module is materialized because there could always be another function body
2858  // with calls to the old function.
2859  for (std::vector<std::pair<Function*, Function*> >::iterator I =
2860       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2861    if (I->first != I->second) {
2862      for (Value::use_iterator UI = I->first->use_begin(),
2863           UE = I->first->use_end(); UI != UE; ) {
2864        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2865          UpgradeIntrinsicCall(CI, I->second);
2866      }
2867      if (!I->first->use_empty())
2868        I->first->replaceAllUsesWith(I->second);
2869      I->first->eraseFromParent();
2870    }
2871  }
2872  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2873
2874  return false;
2875}
2876
2877bool BitcodeReader::InitStream() {
2878  if (LazyStreamer) return InitLazyStream();
2879  return InitStreamFromBuffer();
2880}
2881
2882bool BitcodeReader::InitStreamFromBuffer() {
2883  const unsigned char *BufPtr = (const unsigned char*)Buffer->getBufferStart();
2884  const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2885
2886  if (Buffer->getBufferSize() & 3) {
2887    if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2888      return Error("Invalid bitcode signature");
2889    else
2890      return Error("Bitcode stream should be a multiple of 4 bytes in length");
2891  }
2892
2893  // If we have a wrapper header, parse it and ignore the non-bc file contents.
2894  // The magic number is 0x0B17C0DE stored in little endian.
2895  if (isBitcodeWrapper(BufPtr, BufEnd))
2896    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2897      return Error("Invalid bitcode wrapper header");
2898
2899  StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2900  Stream.init(*StreamFile);
2901
2902  return false;
2903}
2904
2905bool BitcodeReader::InitLazyStream() {
2906  // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2907  // see it.
2908  StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2909  StreamFile.reset(new BitstreamReader(Bytes));
2910  Stream.init(*StreamFile);
2911
2912  unsigned char buf[16];
2913  if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2914    return Error("Bitcode stream must be at least 16 bytes in length");
2915
2916  if (!isBitcode(buf, buf + 16))
2917    return Error("Invalid bitcode signature");
2918
2919  if (isBitcodeWrapper(buf, buf + 4)) {
2920    const unsigned char *bitcodeStart = buf;
2921    const unsigned char *bitcodeEnd = buf + 16;
2922    SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2923    Bytes->dropLeadingBytes(bitcodeStart - buf);
2924    Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2925  }
2926  return false;
2927}
2928
2929//===----------------------------------------------------------------------===//
2930// External interface
2931//===----------------------------------------------------------------------===//
2932
2933/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2934///
2935Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2936                                   LLVMContext& Context,
2937                                   std::string *ErrMsg) {
2938  Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2939  BitcodeReader *R = new BitcodeReader(Buffer, Context);
2940  M->setMaterializer(R);
2941  if (R->ParseBitcodeInto(M)) {
2942    if (ErrMsg)
2943      *ErrMsg = R->getErrorString();
2944
2945    delete M;  // Also deletes R.
2946    return 0;
2947  }
2948  // Have the BitcodeReader dtor delete 'Buffer'.
2949  R->setBufferOwned(true);
2950
2951  R->materializeForwardReferencedFunctions();
2952
2953  return M;
2954}
2955
2956
2957Module *llvm::getStreamedBitcodeModule(const std::string &name,
2958                                       DataStreamer *streamer,
2959                                       LLVMContext &Context,
2960                                       std::string *ErrMsg) {
2961  Module *M = new Module(name, Context);
2962  BitcodeReader *R = new BitcodeReader(streamer, Context);
2963  M->setMaterializer(R);
2964  if (R->ParseBitcodeInto(M)) {
2965    if (ErrMsg)
2966      *ErrMsg = R->getErrorString();
2967    delete M;  // Also deletes R.
2968    return 0;
2969  }
2970  R->setBufferOwned(false); // no buffer to delete
2971  return M;
2972}
2973
2974/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2975/// If an error occurs, return null and fill in *ErrMsg if non-null.
2976Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2977                               std::string *ErrMsg){
2978  Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2979  if (!M) return 0;
2980
2981  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2982  // there was an error.
2983  static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2984
2985  // Read in the entire module, and destroy the BitcodeReader.
2986  if (M->MaterializeAllPermanently(ErrMsg)) {
2987    delete M;
2988    return 0;
2989  }
2990
2991  // TODO: Restore the use-lists to the in-memory state when the bitcode was
2992  // written.  We must defer until the Module has been fully materialized.
2993
2994  return M;
2995}
2996
2997std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2998                                         LLVMContext& Context,
2999                                         std::string *ErrMsg) {
3000  BitcodeReader *R = new BitcodeReader(Buffer, Context);
3001  // Don't let the BitcodeReader dtor delete 'Buffer'.
3002  R->setBufferOwned(false);
3003
3004  std::string Triple("");
3005  if (R->ParseTriple(Triple))
3006    if (ErrMsg)
3007      *ErrMsg = R->getErrorString();
3008
3009  delete R;
3010  return Triple;
3011}
3012