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