BitcodeReader.cpp revision f52aea8bc25acfdd406f741d2711ebbf54606c81
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(ArrayRef<uint64_t> 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      SmallString<8> Name(Record.begin(), Record.end());
829      Record.clear();
830      Code = Stream.ReadCode();
831
832      // METADATA_NAME is always followed by METADATA_NAMED_NODE.
833      unsigned NextBitCode = Stream.ReadRecord(Code, Record);
834      assert(NextBitCode == bitc::METADATA_NAMED_NODE); (void)NextBitCode;
835
836      // Read named metadata elements.
837      unsigned Size = Record.size();
838      NamedMDNode *NMD = TheModule->getOrInsertNamedMetadata(Name);
839      for (unsigned i = 0; i != Size; ++i) {
840        MDNode *MD = dyn_cast<MDNode>(MDValueList.getValueFwdRef(Record[i]));
841        if (MD == 0)
842          return Error("Malformed metadata record");
843        NMD->addOperand(MD);
844      }
845      break;
846    }
847    case bitc::METADATA_FN_NODE:
848      IsFunctionLocal = true;
849      // fall-through
850    case bitc::METADATA_NODE: {
851      if (Record.size() % 2 == 1)
852        return Error("Invalid METADATA_NODE record");
853
854      unsigned Size = Record.size();
855      SmallVector<Value*, 8> Elts;
856      for (unsigned i = 0; i != Size; i += 2) {
857        Type *Ty = getTypeByID(Record[i]);
858        if (!Ty) return Error("Invalid METADATA_NODE record");
859        if (Ty->isMetadataTy())
860          Elts.push_back(MDValueList.getValueFwdRef(Record[i+1]));
861        else if (!Ty->isVoidTy())
862          Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
863        else
864          Elts.push_back(NULL);
865      }
866      Value *V = MDNode::getWhenValsUnresolved(Context, Elts, IsFunctionLocal);
867      IsFunctionLocal = false;
868      MDValueList.AssignValue(V, NextMDValueNo++);
869      break;
870    }
871    case bitc::METADATA_STRING: {
872      SmallString<8> String(Record.begin(), Record.end());
873      Value *V = MDString::get(Context, String);
874      MDValueList.AssignValue(V, NextMDValueNo++);
875      break;
876    }
877    case bitc::METADATA_KIND: {
878      if (Record.size() < 2)
879        return Error("Invalid METADATA_KIND record");
880
881      unsigned Kind = Record[0];
882      SmallString<8> Name(Record.begin()+1, Record.end());
883
884      unsigned NewKind = TheModule->getMDKindID(Name.str());
885      if (!MDKindMap.insert(std::make_pair(Kind, NewKind)).second)
886        return Error("Conflicting METADATA_KIND records");
887      break;
888    }
889    }
890  }
891}
892
893/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
894/// the LSB for dense VBR encoding.
895static uint64_t DecodeSignRotatedValue(uint64_t V) {
896  if ((V & 1) == 0)
897    return V >> 1;
898  if (V != 1)
899    return -(V >> 1);
900  // There is no such thing as -0 with integers.  "-0" really means MININT.
901  return 1ULL << 63;
902}
903
904/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
905/// values and aliases that we can.
906bool BitcodeReader::ResolveGlobalAndAliasInits() {
907  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
908  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
909
910  GlobalInitWorklist.swap(GlobalInits);
911  AliasInitWorklist.swap(AliasInits);
912
913  while (!GlobalInitWorklist.empty()) {
914    unsigned ValID = GlobalInitWorklist.back().second;
915    if (ValID >= ValueList.size()) {
916      // Not ready to resolve this yet, it requires something later in the file.
917      GlobalInits.push_back(GlobalInitWorklist.back());
918    } else {
919      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
920        GlobalInitWorklist.back().first->setInitializer(C);
921      else
922        return Error("Global variable initializer is not a constant!");
923    }
924    GlobalInitWorklist.pop_back();
925  }
926
927  while (!AliasInitWorklist.empty()) {
928    unsigned ValID = AliasInitWorklist.back().second;
929    if (ValID >= ValueList.size()) {
930      AliasInits.push_back(AliasInitWorklist.back());
931    } else {
932      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
933        AliasInitWorklist.back().first->setAliasee(C);
934      else
935        return Error("Alias initializer is not a constant!");
936    }
937    AliasInitWorklist.pop_back();
938  }
939  return false;
940}
941
942static APInt ReadWideAPInt(ArrayRef<uint64_t> Vals, unsigned TypeBits) {
943  SmallVector<uint64_t, 8> Words(Vals.size());
944  std::transform(Vals.begin(), Vals.end(), Words.begin(),
945                 DecodeSignRotatedValue);
946
947  return APInt(TypeBits, Words);
948}
949
950bool BitcodeReader::ParseConstants() {
951  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
952    return Error("Malformed block record");
953
954  SmallVector<uint64_t, 64> Record;
955
956  // Read all the records for this value table.
957  Type *CurTy = Type::getInt32Ty(Context);
958  unsigned NextCstNo = ValueList.size();
959  while (1) {
960    unsigned Code = Stream.ReadCode();
961    if (Code == bitc::END_BLOCK)
962      break;
963
964    if (Code == bitc::ENTER_SUBBLOCK) {
965      // No known subblocks, always skip them.
966      Stream.ReadSubBlockID();
967      if (Stream.SkipBlock())
968        return Error("Malformed block record");
969      continue;
970    }
971
972    if (Code == bitc::DEFINE_ABBREV) {
973      Stream.ReadAbbrevRecord();
974      continue;
975    }
976
977    // Read a record.
978    Record.clear();
979    Value *V = 0;
980    unsigned BitCode = Stream.ReadRecord(Code, Record);
981    switch (BitCode) {
982    default:  // Default behavior: unknown constant
983    case bitc::CST_CODE_UNDEF:     // UNDEF
984      V = UndefValue::get(CurTy);
985      break;
986    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
987      if (Record.empty())
988        return Error("Malformed CST_SETTYPE record");
989      if (Record[0] >= TypeList.size())
990        return Error("Invalid Type ID in CST_SETTYPE record");
991      CurTy = TypeList[Record[0]];
992      continue;  // Skip the ValueList manipulation.
993    case bitc::CST_CODE_NULL:      // NULL
994      V = Constant::getNullValue(CurTy);
995      break;
996    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
997      if (!CurTy->isIntegerTy() || Record.empty())
998        return Error("Invalid CST_INTEGER record");
999      V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
1000      break;
1001    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
1002      if (!CurTy->isIntegerTy() || Record.empty())
1003        return Error("Invalid WIDE_INTEGER record");
1004
1005      APInt VInt = ReadWideAPInt(Record,
1006                                 cast<IntegerType>(CurTy)->getBitWidth());
1007      V = ConstantInt::get(Context, VInt);
1008
1009      break;
1010    }
1011    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
1012      if (Record.empty())
1013        return Error("Invalid FLOAT record");
1014      if (CurTy->isHalfTy())
1015        V = ConstantFP::get(Context, APFloat(APInt(16, (uint16_t)Record[0])));
1016      else if (CurTy->isFloatTy())
1017        V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
1018      else if (CurTy->isDoubleTy())
1019        V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
1020      else if (CurTy->isX86_FP80Ty()) {
1021        // Bits are not stored the same way as a normal i80 APInt, compensate.
1022        uint64_t Rearrange[2];
1023        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
1024        Rearrange[1] = Record[0] >> 48;
1025        V = ConstantFP::get(Context, APFloat(APInt(80, Rearrange)));
1026      } else if (CurTy->isFP128Ty())
1027        V = ConstantFP::get(Context, APFloat(APInt(128, Record), true));
1028      else if (CurTy->isPPC_FP128Ty())
1029        V = ConstantFP::get(Context, APFloat(APInt(128, Record)));
1030      else
1031        V = UndefValue::get(CurTy);
1032      break;
1033    }
1034
1035    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
1036      if (Record.empty())
1037        return Error("Invalid CST_AGGREGATE record");
1038
1039      unsigned Size = Record.size();
1040      SmallVector<Constant*, 16> Elts;
1041
1042      if (StructType *STy = dyn_cast<StructType>(CurTy)) {
1043        for (unsigned i = 0; i != Size; ++i)
1044          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
1045                                                     STy->getElementType(i)));
1046        V = ConstantStruct::get(STy, Elts);
1047      } else if (ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
1048        Type *EltTy = ATy->getElementType();
1049        for (unsigned i = 0; i != Size; ++i)
1050          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1051        V = ConstantArray::get(ATy, Elts);
1052      } else if (VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
1053        Type *EltTy = VTy->getElementType();
1054        for (unsigned i = 0; i != Size; ++i)
1055          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
1056        V = ConstantVector::get(Elts);
1057      } else {
1058        V = UndefValue::get(CurTy);
1059      }
1060      break;
1061    }
1062    case bitc::CST_CODE_STRING:    // STRING: [values]
1063    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
1064      if (Record.empty())
1065        return Error("Invalid CST_STRING record");
1066
1067      SmallString<16> Elts(Record.begin(), Record.end());
1068      V = ConstantDataArray::getString(Context, Elts,
1069                                       BitCode == bitc::CST_CODE_CSTRING);
1070      break;
1071    }
1072    case bitc::CST_CODE_DATA: {// DATA: [n x value]
1073      if (Record.empty())
1074        return Error("Invalid CST_DATA record");
1075
1076      Type *EltTy = cast<SequentialType>(CurTy)->getElementType();
1077      unsigned Size = Record.size();
1078
1079      if (EltTy->isIntegerTy(8)) {
1080        SmallVector<uint8_t, 16> Elts(Record.begin(), Record.end());
1081        if (isa<VectorType>(CurTy))
1082          V = ConstantDataVector::get(Context, Elts);
1083        else
1084          V = ConstantDataArray::get(Context, Elts);
1085      } else if (EltTy->isIntegerTy(16)) {
1086        SmallVector<uint16_t, 16> Elts(Record.begin(), Record.end());
1087        if (isa<VectorType>(CurTy))
1088          V = ConstantDataVector::get(Context, Elts);
1089        else
1090          V = ConstantDataArray::get(Context, Elts);
1091      } else if (EltTy->isIntegerTy(32)) {
1092        SmallVector<uint32_t, 16> Elts(Record.begin(), Record.end());
1093        if (isa<VectorType>(CurTy))
1094          V = ConstantDataVector::get(Context, Elts);
1095        else
1096          V = ConstantDataArray::get(Context, Elts);
1097      } else if (EltTy->isIntegerTy(64)) {
1098        SmallVector<uint64_t, 16> Elts(Record.begin(), Record.end());
1099        if (isa<VectorType>(CurTy))
1100          V = ConstantDataVector::get(Context, Elts);
1101        else
1102          V = ConstantDataArray::get(Context, Elts);
1103      } else if (EltTy->isFloatTy()) {
1104        SmallVector<float, 16> Elts(Size);
1105        std::transform(Record.begin(), Record.end(), Elts.begin(), BitsToFloat);
1106        if (isa<VectorType>(CurTy))
1107          V = ConstantDataVector::get(Context, Elts);
1108        else
1109          V = ConstantDataArray::get(Context, Elts);
1110      } else if (EltTy->isDoubleTy()) {
1111        SmallVector<double, 16> Elts(Size);
1112        std::transform(Record.begin(), Record.end(), Elts.begin(),
1113                       BitsToDouble);
1114        if (isa<VectorType>(CurTy))
1115          V = ConstantDataVector::get(Context, Elts);
1116        else
1117          V = ConstantDataArray::get(Context, Elts);
1118      } else {
1119        return Error("Unknown element type in CE_DATA");
1120      }
1121      break;
1122    }
1123
1124    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1125      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1126      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1127      if (Opc < 0) {
1128        V = UndefValue::get(CurTy);  // Unknown binop.
1129      } else {
1130        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1131        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1132        unsigned Flags = 0;
1133        if (Record.size() >= 4) {
1134          if (Opc == Instruction::Add ||
1135              Opc == Instruction::Sub ||
1136              Opc == Instruction::Mul ||
1137              Opc == Instruction::Shl) {
1138            if (Record[3] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1139              Flags |= OverflowingBinaryOperator::NoSignedWrap;
1140            if (Record[3] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1141              Flags |= OverflowingBinaryOperator::NoUnsignedWrap;
1142          } else if (Opc == Instruction::SDiv ||
1143                     Opc == Instruction::UDiv ||
1144                     Opc == Instruction::LShr ||
1145                     Opc == Instruction::AShr) {
1146            if (Record[3] & (1 << bitc::PEO_EXACT))
1147              Flags |= SDivOperator::IsExact;
1148          }
1149        }
1150        V = ConstantExpr::get(Opc, LHS, RHS, Flags);
1151      }
1152      break;
1153    }
1154    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1155      if (Record.size() < 3) return Error("Invalid CE_CAST record");
1156      int Opc = GetDecodedCastOpcode(Record[0]);
1157      if (Opc < 0) {
1158        V = UndefValue::get(CurTy);  // Unknown cast.
1159      } else {
1160        Type *OpTy = getTypeByID(Record[1]);
1161        if (!OpTy) return Error("Invalid CE_CAST record");
1162        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1163        V = ConstantExpr::getCast(Opc, Op, CurTy);
1164      }
1165      break;
1166    }
1167    case bitc::CST_CODE_CE_INBOUNDS_GEP:
1168    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1169      if (Record.size() & 1) return Error("Invalid CE_GEP record");
1170      SmallVector<Constant*, 16> Elts;
1171      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1172        Type *ElTy = getTypeByID(Record[i]);
1173        if (!ElTy) return Error("Invalid CE_GEP record");
1174        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1175      }
1176      ArrayRef<Constant *> Indices(Elts.begin() + 1, Elts.end());
1177      V = ConstantExpr::getGetElementPtr(Elts[0], Indices,
1178                                         BitCode ==
1179                                           bitc::CST_CODE_CE_INBOUNDS_GEP);
1180      break;
1181    }
1182    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1183      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1184      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1185                                                              Type::getInt1Ty(Context)),
1186                                  ValueList.getConstantFwdRef(Record[1],CurTy),
1187                                  ValueList.getConstantFwdRef(Record[2],CurTy));
1188      break;
1189    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1190      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1191      VectorType *OpTy =
1192        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1193      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1194      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1195      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1196      V = ConstantExpr::getExtractElement(Op0, Op1);
1197      break;
1198    }
1199    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1200      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1201      if (Record.size() < 3 || OpTy == 0)
1202        return Error("Invalid CE_INSERTELT record");
1203      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1204      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1205                                                  OpTy->getElementType());
1206      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::getInt32Ty(Context));
1207      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1208      break;
1209    }
1210    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1211      VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1212      if (Record.size() < 3 || OpTy == 0)
1213        return Error("Invalid CE_SHUFFLEVEC record");
1214      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1215      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1216      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1217                                                 OpTy->getNumElements());
1218      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1219      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1220      break;
1221    }
1222    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1223      VectorType *RTy = dyn_cast<VectorType>(CurTy);
1224      VectorType *OpTy =
1225        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1226      if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1227        return Error("Invalid CE_SHUFVEC_EX record");
1228      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1229      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1230      Type *ShufTy = VectorType::get(Type::getInt32Ty(Context),
1231                                                 RTy->getNumElements());
1232      Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1233      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1234      break;
1235    }
1236    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1237      if (Record.size() < 4) return Error("Invalid CE_CMP record");
1238      Type *OpTy = getTypeByID(Record[0]);
1239      if (OpTy == 0) return Error("Invalid CE_CMP record");
1240      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1241      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1242
1243      if (OpTy->isFPOrFPVectorTy())
1244        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1245      else
1246        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1247      break;
1248    }
1249    case bitc::CST_CODE_INLINEASM: {
1250      if (Record.size() < 2) return Error("Invalid INLINEASM record");
1251      std::string AsmStr, ConstrStr;
1252      bool HasSideEffects = Record[0] & 1;
1253      bool IsAlignStack = Record[0] >> 1;
1254      unsigned AsmStrSize = Record[1];
1255      if (2+AsmStrSize >= Record.size())
1256        return Error("Invalid INLINEASM record");
1257      unsigned ConstStrSize = Record[2+AsmStrSize];
1258      if (3+AsmStrSize+ConstStrSize > Record.size())
1259        return Error("Invalid INLINEASM record");
1260
1261      for (unsigned i = 0; i != AsmStrSize; ++i)
1262        AsmStr += (char)Record[2+i];
1263      for (unsigned i = 0; i != ConstStrSize; ++i)
1264        ConstrStr += (char)Record[3+AsmStrSize+i];
1265      PointerType *PTy = cast<PointerType>(CurTy);
1266      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1267                         AsmStr, ConstrStr, HasSideEffects, IsAlignStack);
1268      break;
1269    }
1270    case bitc::CST_CODE_BLOCKADDRESS:{
1271      if (Record.size() < 3) return Error("Invalid CE_BLOCKADDRESS record");
1272      Type *FnTy = getTypeByID(Record[0]);
1273      if (FnTy == 0) return Error("Invalid CE_BLOCKADDRESS record");
1274      Function *Fn =
1275        dyn_cast_or_null<Function>(ValueList.getConstantFwdRef(Record[1],FnTy));
1276      if (Fn == 0) return Error("Invalid CE_BLOCKADDRESS record");
1277
1278      GlobalVariable *FwdRef = new GlobalVariable(*Fn->getParent(),
1279                                                  Type::getInt8Ty(Context),
1280                                            false, GlobalValue::InternalLinkage,
1281                                                  0, "");
1282      BlockAddrFwdRefs[Fn].push_back(std::make_pair(Record[2], FwdRef));
1283      V = FwdRef;
1284      break;
1285    }
1286    }
1287
1288    ValueList.AssignValue(V, NextCstNo);
1289    ++NextCstNo;
1290  }
1291
1292  if (NextCstNo != ValueList.size())
1293    return Error("Invalid constant reference!");
1294
1295  if (Stream.ReadBlockEnd())
1296    return Error("Error at end of constants block");
1297
1298  // Once all the constants have been read, go through and resolve forward
1299  // references.
1300  ValueList.ResolveConstantForwardRefs();
1301  return false;
1302}
1303
1304bool BitcodeReader::ParseUseLists() {
1305  if (Stream.EnterSubBlock(bitc::USELIST_BLOCK_ID))
1306    return Error("Malformed block record");
1307
1308  SmallVector<uint64_t, 64> Record;
1309
1310  // Read all the records.
1311  while (1) {
1312    unsigned Code = Stream.ReadCode();
1313    if (Code == bitc::END_BLOCK) {
1314      if (Stream.ReadBlockEnd())
1315        return Error("Error at end of use-list table block");
1316      return false;
1317    }
1318
1319    if (Code == bitc::ENTER_SUBBLOCK) {
1320      // No known subblocks, always skip them.
1321      Stream.ReadSubBlockID();
1322      if (Stream.SkipBlock())
1323        return Error("Malformed block record");
1324      continue;
1325    }
1326
1327    if (Code == bitc::DEFINE_ABBREV) {
1328      Stream.ReadAbbrevRecord();
1329      continue;
1330    }
1331
1332    // Read a use list record.
1333    Record.clear();
1334    switch (Stream.ReadRecord(Code, Record)) {
1335    default:  // Default behavior: unknown type.
1336      break;
1337    case bitc::USELIST_CODE_ENTRY: { // USELIST_CODE_ENTRY: TBD.
1338      unsigned RecordLength = Record.size();
1339      if (RecordLength < 1)
1340        return Error ("Invalid UseList reader!");
1341      UseListRecords.push_back(Record);
1342      break;
1343    }
1344    }
1345  }
1346}
1347
1348/// RememberAndSkipFunctionBody - When we see the block for a function body,
1349/// remember where it is and then skip it.  This lets us lazily deserialize the
1350/// functions.
1351bool BitcodeReader::RememberAndSkipFunctionBody() {
1352  // Get the function we are talking about.
1353  if (FunctionsWithBodies.empty())
1354    return Error("Insufficient function protos");
1355
1356  Function *Fn = FunctionsWithBodies.back();
1357  FunctionsWithBodies.pop_back();
1358
1359  // Save the current stream state.
1360  uint64_t CurBit = Stream.GetCurrentBitNo();
1361  DeferredFunctionInfo[Fn] = CurBit;
1362
1363  // Skip over the function block for now.
1364  if (Stream.SkipBlock())
1365    return Error("Malformed block record");
1366  return false;
1367}
1368
1369bool BitcodeReader::GlobalCleanup() {
1370  // Patch the initializers for globals and aliases up.
1371  ResolveGlobalAndAliasInits();
1372  if (!GlobalInits.empty() || !AliasInits.empty())
1373    return Error("Malformed global initializer set");
1374
1375  // Look for intrinsic functions which need to be upgraded at some point
1376  for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1377       FI != FE; ++FI) {
1378    Function *NewFn;
1379    if (UpgradeIntrinsicFunction(FI, NewFn))
1380      UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1381  }
1382
1383  // Look for global variables which need to be renamed.
1384  for (Module::global_iterator
1385         GI = TheModule->global_begin(), GE = TheModule->global_end();
1386       GI != GE; ++GI)
1387    UpgradeGlobalVariable(GI);
1388  // Force deallocation of memory for these vectors to favor the client that
1389  // want lazy deserialization.
1390  std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1391  std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1392  return false;
1393}
1394
1395bool BitcodeReader::ParseModule(bool Resume) {
1396  if (Resume)
1397    Stream.JumpToBit(NextUnreadBit);
1398  else if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1399    return Error("Malformed block record");
1400
1401  SmallVector<uint64_t, 64> Record;
1402  std::vector<std::string> SectionTable;
1403  std::vector<std::string> GCTable;
1404
1405  // Read all the records for this module.
1406  while (!Stream.AtEndOfStream()) {
1407    unsigned Code = Stream.ReadCode();
1408    if (Code == bitc::END_BLOCK) {
1409      if (Stream.ReadBlockEnd())
1410        return Error("Error at end of module block");
1411
1412      return GlobalCleanup();
1413    }
1414
1415    if (Code == bitc::ENTER_SUBBLOCK) {
1416      switch (Stream.ReadSubBlockID()) {
1417      default:  // Skip unknown content.
1418        if (Stream.SkipBlock())
1419          return Error("Malformed block record");
1420        break;
1421      case bitc::BLOCKINFO_BLOCK_ID:
1422        if (Stream.ReadBlockInfoBlock())
1423          return Error("Malformed BlockInfoBlock");
1424        break;
1425      case bitc::PARAMATTR_BLOCK_ID:
1426        if (ParseAttributeBlock())
1427          return true;
1428        break;
1429      case bitc::TYPE_BLOCK_ID_NEW:
1430        if (ParseTypeTable())
1431          return true;
1432        break;
1433      case bitc::VALUE_SYMTAB_BLOCK_ID:
1434        if (ParseValueSymbolTable())
1435          return true;
1436        SeenValueSymbolTable = true;
1437        break;
1438      case bitc::CONSTANTS_BLOCK_ID:
1439        if (ParseConstants() || ResolveGlobalAndAliasInits())
1440          return true;
1441        break;
1442      case bitc::METADATA_BLOCK_ID:
1443        if (ParseMetadata())
1444          return true;
1445        break;
1446      case bitc::FUNCTION_BLOCK_ID:
1447        // If this is the first function body we've seen, reverse the
1448        // FunctionsWithBodies list.
1449        if (!SeenFirstFunctionBody) {
1450          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1451          if (GlobalCleanup())
1452            return true;
1453          SeenFirstFunctionBody = true;
1454        }
1455
1456        if (RememberAndSkipFunctionBody())
1457          return true;
1458        // For streaming bitcode, suspend parsing when we reach the function
1459        // bodies. Subsequent materialization calls will resume it when
1460        // necessary. For streaming, the function bodies must be at the end of
1461        // the bitcode. If the bitcode file is old, the symbol table will be
1462        // at the end instead and will not have been seen yet. In this case,
1463        // just finish the parse now.
1464        if (LazyStreamer && SeenValueSymbolTable) {
1465          NextUnreadBit = Stream.GetCurrentBitNo();
1466          return false;
1467        }
1468        break;
1469      case bitc::USELIST_BLOCK_ID:
1470        if (ParseUseLists())
1471          return true;
1472        break;
1473      }
1474      continue;
1475    }
1476
1477    if (Code == bitc::DEFINE_ABBREV) {
1478      Stream.ReadAbbrevRecord();
1479      continue;
1480    }
1481
1482    // Read a record.
1483    switch (Stream.ReadRecord(Code, Record)) {
1484    default: break;  // Default behavior, ignore unknown content.
1485    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1486      if (Record.size() < 1)
1487        return Error("Malformed MODULE_CODE_VERSION");
1488      // Only version #0 is supported so far.
1489      if (Record[0] != 0)
1490        return Error("Unknown bitstream version!");
1491      break;
1492    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1493      std::string S;
1494      if (ConvertToString(Record, 0, S))
1495        return Error("Invalid MODULE_CODE_TRIPLE record");
1496      TheModule->setTargetTriple(S);
1497      break;
1498    }
1499    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1500      std::string S;
1501      if (ConvertToString(Record, 0, S))
1502        return Error("Invalid MODULE_CODE_DATALAYOUT record");
1503      TheModule->setDataLayout(S);
1504      break;
1505    }
1506    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1507      std::string S;
1508      if (ConvertToString(Record, 0, S))
1509        return Error("Invalid MODULE_CODE_ASM record");
1510      TheModule->setModuleInlineAsm(S);
1511      break;
1512    }
1513    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1514      std::string S;
1515      if (ConvertToString(Record, 0, S))
1516        return Error("Invalid MODULE_CODE_DEPLIB record");
1517      TheModule->addLibrary(S);
1518      break;
1519    }
1520    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1521      std::string S;
1522      if (ConvertToString(Record, 0, S))
1523        return Error("Invalid MODULE_CODE_SECTIONNAME record");
1524      SectionTable.push_back(S);
1525      break;
1526    }
1527    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1528      std::string S;
1529      if (ConvertToString(Record, 0, S))
1530        return Error("Invalid MODULE_CODE_GCNAME record");
1531      GCTable.push_back(S);
1532      break;
1533    }
1534    // GLOBALVAR: [pointer type, isconst, initid,
1535    //             linkage, alignment, section, visibility, threadlocal,
1536    //             unnamed_addr]
1537    case bitc::MODULE_CODE_GLOBALVAR: {
1538      if (Record.size() < 6)
1539        return Error("Invalid MODULE_CODE_GLOBALVAR record");
1540      Type *Ty = getTypeByID(Record[0]);
1541      if (!Ty) return Error("Invalid MODULE_CODE_GLOBALVAR record");
1542      if (!Ty->isPointerTy())
1543        return Error("Global not a pointer type!");
1544      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1545      Ty = cast<PointerType>(Ty)->getElementType();
1546
1547      bool isConstant = Record[1];
1548      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1549      unsigned Alignment = (1 << Record[4]) >> 1;
1550      std::string Section;
1551      if (Record[5]) {
1552        if (Record[5]-1 >= SectionTable.size())
1553          return Error("Invalid section ID");
1554        Section = SectionTable[Record[5]-1];
1555      }
1556      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1557      if (Record.size() > 6)
1558        Visibility = GetDecodedVisibility(Record[6]);
1559      bool isThreadLocal = false;
1560      if (Record.size() > 7)
1561        isThreadLocal = Record[7];
1562
1563      bool UnnamedAddr = false;
1564      if (Record.size() > 8)
1565        UnnamedAddr = Record[8];
1566
1567      GlobalVariable *NewGV =
1568        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1569                           isThreadLocal, AddressSpace);
1570      NewGV->setAlignment(Alignment);
1571      if (!Section.empty())
1572        NewGV->setSection(Section);
1573      NewGV->setVisibility(Visibility);
1574      NewGV->setThreadLocal(isThreadLocal);
1575      NewGV->setUnnamedAddr(UnnamedAddr);
1576
1577      ValueList.push_back(NewGV);
1578
1579      // Remember which value to use for the global initializer.
1580      if (unsigned InitID = Record[2])
1581        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1582      break;
1583    }
1584    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1585    //             alignment, section, visibility, gc, unnamed_addr]
1586    case bitc::MODULE_CODE_FUNCTION: {
1587      if (Record.size() < 8)
1588        return Error("Invalid MODULE_CODE_FUNCTION record");
1589      Type *Ty = getTypeByID(Record[0]);
1590      if (!Ty) return Error("Invalid MODULE_CODE_FUNCTION record");
1591      if (!Ty->isPointerTy())
1592        return Error("Function not a pointer type!");
1593      FunctionType *FTy =
1594        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1595      if (!FTy)
1596        return Error("Function not a pointer to function type!");
1597
1598      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1599                                        "", TheModule);
1600
1601      Func->setCallingConv(static_cast<CallingConv::ID>(Record[1]));
1602      bool isProto = Record[2];
1603      Func->setLinkage(GetDecodedLinkage(Record[3]));
1604      Func->setAttributes(getAttributes(Record[4]));
1605
1606      Func->setAlignment((1 << Record[5]) >> 1);
1607      if (Record[6]) {
1608        if (Record[6]-1 >= SectionTable.size())
1609          return Error("Invalid section ID");
1610        Func->setSection(SectionTable[Record[6]-1]);
1611      }
1612      Func->setVisibility(GetDecodedVisibility(Record[7]));
1613      if (Record.size() > 8 && Record[8]) {
1614        if (Record[8]-1 > GCTable.size())
1615          return Error("Invalid GC ID");
1616        Func->setGC(GCTable[Record[8]-1].c_str());
1617      }
1618      bool UnnamedAddr = false;
1619      if (Record.size() > 9)
1620        UnnamedAddr = Record[9];
1621      Func->setUnnamedAddr(UnnamedAddr);
1622      ValueList.push_back(Func);
1623
1624      // If this is a function with a body, remember the prototype we are
1625      // creating now, so that we can match up the body with them later.
1626      if (!isProto) {
1627        FunctionsWithBodies.push_back(Func);
1628        if (LazyStreamer) DeferredFunctionInfo[Func] = 0;
1629      }
1630      break;
1631    }
1632    // ALIAS: [alias type, aliasee val#, linkage]
1633    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1634    case bitc::MODULE_CODE_ALIAS: {
1635      if (Record.size() < 3)
1636        return Error("Invalid MODULE_ALIAS record");
1637      Type *Ty = getTypeByID(Record[0]);
1638      if (!Ty) return Error("Invalid MODULE_ALIAS record");
1639      if (!Ty->isPointerTy())
1640        return Error("Function not a pointer type!");
1641
1642      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1643                                           "", 0, TheModule);
1644      // Old bitcode files didn't have visibility field.
1645      if (Record.size() > 3)
1646        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1647      ValueList.push_back(NewGA);
1648      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1649      break;
1650    }
1651    /// MODULE_CODE_PURGEVALS: [numvals]
1652    case bitc::MODULE_CODE_PURGEVALS:
1653      // Trim down the value list to the specified size.
1654      if (Record.size() < 1 || Record[0] > ValueList.size())
1655        return Error("Invalid MODULE_PURGEVALS record");
1656      ValueList.shrinkTo(Record[0]);
1657      break;
1658    }
1659    Record.clear();
1660  }
1661
1662  return Error("Premature end of bitstream");
1663}
1664
1665bool BitcodeReader::ParseBitcodeInto(Module *M) {
1666  TheModule = 0;
1667
1668  if (InitStream()) return true;
1669
1670  // Sniff for the signature.
1671  if (Stream.Read(8) != 'B' ||
1672      Stream.Read(8) != 'C' ||
1673      Stream.Read(4) != 0x0 ||
1674      Stream.Read(4) != 0xC ||
1675      Stream.Read(4) != 0xE ||
1676      Stream.Read(4) != 0xD)
1677    return Error("Invalid bitcode signature");
1678
1679  // We expect a number of well-defined blocks, though we don't necessarily
1680  // need to understand them all.
1681  while (!Stream.AtEndOfStream()) {
1682    unsigned Code = Stream.ReadCode();
1683
1684    if (Code != bitc::ENTER_SUBBLOCK) {
1685
1686      // The ranlib in xcode 4 will align archive members by appending newlines
1687      // to the end of them. If this file size is a multiple of 4 but not 8, we
1688      // have to read and ignore these final 4 bytes :-(
1689      if (Stream.GetAbbrevIDWidth() == 2 && Code == 2 &&
1690          Stream.Read(6) == 2 && Stream.Read(24) == 0xa0a0a &&
1691	  Stream.AtEndOfStream())
1692        return false;
1693
1694      return Error("Invalid record at top-level");
1695    }
1696
1697    unsigned BlockID = Stream.ReadSubBlockID();
1698
1699    // We only know the MODULE subblock ID.
1700    switch (BlockID) {
1701    case bitc::BLOCKINFO_BLOCK_ID:
1702      if (Stream.ReadBlockInfoBlock())
1703        return Error("Malformed BlockInfoBlock");
1704      break;
1705    case bitc::MODULE_BLOCK_ID:
1706      // Reject multiple MODULE_BLOCK's in a single bitstream.
1707      if (TheModule)
1708        return Error("Multiple MODULE_BLOCKs in same stream");
1709      TheModule = M;
1710      if (ParseModule(false))
1711        return true;
1712      if (LazyStreamer) return false;
1713      break;
1714    default:
1715      if (Stream.SkipBlock())
1716        return Error("Malformed block record");
1717      break;
1718    }
1719  }
1720
1721  return false;
1722}
1723
1724bool BitcodeReader::ParseModuleTriple(std::string &Triple) {
1725  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1726    return Error("Malformed block record");
1727
1728  SmallVector<uint64_t, 64> Record;
1729
1730  // Read all the records for this module.
1731  while (!Stream.AtEndOfStream()) {
1732    unsigned Code = Stream.ReadCode();
1733    if (Code == bitc::END_BLOCK) {
1734      if (Stream.ReadBlockEnd())
1735        return Error("Error at end of module block");
1736
1737      return false;
1738    }
1739
1740    if (Code == bitc::ENTER_SUBBLOCK) {
1741      switch (Stream.ReadSubBlockID()) {
1742      default:  // Skip unknown content.
1743        if (Stream.SkipBlock())
1744          return Error("Malformed block record");
1745        break;
1746      }
1747      continue;
1748    }
1749
1750    if (Code == bitc::DEFINE_ABBREV) {
1751      Stream.ReadAbbrevRecord();
1752      continue;
1753    }
1754
1755    // Read a record.
1756    switch (Stream.ReadRecord(Code, Record)) {
1757    default: break;  // Default behavior, ignore unknown content.
1758    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1759      if (Record.size() < 1)
1760        return Error("Malformed MODULE_CODE_VERSION");
1761      // Only version #0 is supported so far.
1762      if (Record[0] != 0)
1763        return Error("Unknown bitstream version!");
1764      break;
1765    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1766      std::string S;
1767      if (ConvertToString(Record, 0, S))
1768        return Error("Invalid MODULE_CODE_TRIPLE record");
1769      Triple = S;
1770      break;
1771    }
1772    }
1773    Record.clear();
1774  }
1775
1776  return Error("Premature end of bitstream");
1777}
1778
1779bool BitcodeReader::ParseTriple(std::string &Triple) {
1780  if (InitStream()) return true;
1781
1782  // Sniff for the signature.
1783  if (Stream.Read(8) != 'B' ||
1784      Stream.Read(8) != 'C' ||
1785      Stream.Read(4) != 0x0 ||
1786      Stream.Read(4) != 0xC ||
1787      Stream.Read(4) != 0xE ||
1788      Stream.Read(4) != 0xD)
1789    return Error("Invalid bitcode signature");
1790
1791  // We expect a number of well-defined blocks, though we don't necessarily
1792  // need to understand them all.
1793  while (!Stream.AtEndOfStream()) {
1794    unsigned Code = Stream.ReadCode();
1795
1796    if (Code != bitc::ENTER_SUBBLOCK)
1797      return Error("Invalid record at top-level");
1798
1799    unsigned BlockID = Stream.ReadSubBlockID();
1800
1801    // We only know the MODULE subblock ID.
1802    switch (BlockID) {
1803    case bitc::MODULE_BLOCK_ID:
1804      if (ParseModuleTriple(Triple))
1805        return true;
1806      break;
1807    default:
1808      if (Stream.SkipBlock())
1809        return Error("Malformed block record");
1810      break;
1811    }
1812  }
1813
1814  return false;
1815}
1816
1817/// ParseMetadataAttachment - Parse metadata attachments.
1818bool BitcodeReader::ParseMetadataAttachment() {
1819  if (Stream.EnterSubBlock(bitc::METADATA_ATTACHMENT_ID))
1820    return Error("Malformed block record");
1821
1822  SmallVector<uint64_t, 64> Record;
1823  while(1) {
1824    unsigned Code = Stream.ReadCode();
1825    if (Code == bitc::END_BLOCK) {
1826      if (Stream.ReadBlockEnd())
1827        return Error("Error at end of PARAMATTR block");
1828      break;
1829    }
1830    if (Code == bitc::DEFINE_ABBREV) {
1831      Stream.ReadAbbrevRecord();
1832      continue;
1833    }
1834    // Read a metadata attachment record.
1835    Record.clear();
1836    switch (Stream.ReadRecord(Code, Record)) {
1837    default:  // Default behavior: ignore.
1838      break;
1839    case bitc::METADATA_ATTACHMENT: {
1840      unsigned RecordLength = Record.size();
1841      if (Record.empty() || (RecordLength - 1) % 2 == 1)
1842        return Error ("Invalid METADATA_ATTACHMENT reader!");
1843      Instruction *Inst = InstructionList[Record[0]];
1844      for (unsigned i = 1; i != RecordLength; i = i+2) {
1845        unsigned Kind = Record[i];
1846        DenseMap<unsigned, unsigned>::iterator I =
1847          MDKindMap.find(Kind);
1848        if (I == MDKindMap.end())
1849          return Error("Invalid metadata kind ID");
1850        Value *Node = MDValueList.getValueFwdRef(Record[i+1]);
1851        Inst->setMetadata(I->second, cast<MDNode>(Node));
1852      }
1853      break;
1854    }
1855    }
1856  }
1857  return false;
1858}
1859
1860/// ParseFunctionBody - Lazily parse the specified function body block.
1861bool BitcodeReader::ParseFunctionBody(Function *F) {
1862  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1863    return Error("Malformed block record");
1864
1865  InstructionList.clear();
1866  unsigned ModuleValueListSize = ValueList.size();
1867  unsigned ModuleMDValueListSize = MDValueList.size();
1868
1869  // Add all the function arguments to the value table.
1870  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1871    ValueList.push_back(I);
1872
1873  unsigned NextValueNo = ValueList.size();
1874  BasicBlock *CurBB = 0;
1875  unsigned CurBBNo = 0;
1876
1877  DebugLoc LastLoc;
1878
1879  // Read all the records.
1880  SmallVector<uint64_t, 64> Record;
1881  while (1) {
1882    unsigned Code = Stream.ReadCode();
1883    if (Code == bitc::END_BLOCK) {
1884      if (Stream.ReadBlockEnd())
1885        return Error("Error at end of function block");
1886      break;
1887    }
1888
1889    if (Code == bitc::ENTER_SUBBLOCK) {
1890      switch (Stream.ReadSubBlockID()) {
1891      default:  // Skip unknown content.
1892        if (Stream.SkipBlock())
1893          return Error("Malformed block record");
1894        break;
1895      case bitc::CONSTANTS_BLOCK_ID:
1896        if (ParseConstants()) return true;
1897        NextValueNo = ValueList.size();
1898        break;
1899      case bitc::VALUE_SYMTAB_BLOCK_ID:
1900        if (ParseValueSymbolTable()) return true;
1901        break;
1902      case bitc::METADATA_ATTACHMENT_ID:
1903        if (ParseMetadataAttachment()) return true;
1904        break;
1905      case bitc::METADATA_BLOCK_ID:
1906        if (ParseMetadata()) return true;
1907        break;
1908      }
1909      continue;
1910    }
1911
1912    if (Code == bitc::DEFINE_ABBREV) {
1913      Stream.ReadAbbrevRecord();
1914      continue;
1915    }
1916
1917    // Read a record.
1918    Record.clear();
1919    Instruction *I = 0;
1920    unsigned BitCode = Stream.ReadRecord(Code, Record);
1921    switch (BitCode) {
1922    default: // Default behavior: reject
1923      return Error("Unknown instruction");
1924    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1925      if (Record.size() < 1 || Record[0] == 0)
1926        return Error("Invalid DECLAREBLOCKS record");
1927      // Create all the basic blocks for the function.
1928      FunctionBBs.resize(Record[0]);
1929      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1930        FunctionBBs[i] = BasicBlock::Create(Context, "", F);
1931      CurBB = FunctionBBs[0];
1932      continue;
1933
1934    case bitc::FUNC_CODE_DEBUG_LOC_AGAIN:  // DEBUG_LOC_AGAIN
1935      // This record indicates that the last instruction is at the same
1936      // location as the previous instruction with a location.
1937      I = 0;
1938
1939      // Get the last instruction emitted.
1940      if (CurBB && !CurBB->empty())
1941        I = &CurBB->back();
1942      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1943               !FunctionBBs[CurBBNo-1]->empty())
1944        I = &FunctionBBs[CurBBNo-1]->back();
1945
1946      if (I == 0) return Error("Invalid DEBUG_LOC_AGAIN record");
1947      I->setDebugLoc(LastLoc);
1948      I = 0;
1949      continue;
1950
1951    case bitc::FUNC_CODE_DEBUG_LOC: {      // DEBUG_LOC: [line, col, scope, ia]
1952      I = 0;     // Get the last instruction emitted.
1953      if (CurBB && !CurBB->empty())
1954        I = &CurBB->back();
1955      else if (CurBBNo && FunctionBBs[CurBBNo-1] &&
1956               !FunctionBBs[CurBBNo-1]->empty())
1957        I = &FunctionBBs[CurBBNo-1]->back();
1958      if (I == 0 || Record.size() < 4)
1959        return Error("Invalid FUNC_CODE_DEBUG_LOC record");
1960
1961      unsigned Line = Record[0], Col = Record[1];
1962      unsigned ScopeID = Record[2], IAID = Record[3];
1963
1964      MDNode *Scope = 0, *IA = 0;
1965      if (ScopeID) Scope = cast<MDNode>(MDValueList.getValueFwdRef(ScopeID-1));
1966      if (IAID)    IA = cast<MDNode>(MDValueList.getValueFwdRef(IAID-1));
1967      LastLoc = DebugLoc::get(Line, Col, Scope, IA);
1968      I->setDebugLoc(LastLoc);
1969      I = 0;
1970      continue;
1971    }
1972
1973    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1974      unsigned OpNum = 0;
1975      Value *LHS, *RHS;
1976      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1977          getValue(Record, OpNum, LHS->getType(), RHS) ||
1978          OpNum+1 > Record.size())
1979        return Error("Invalid BINOP record");
1980
1981      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1982      if (Opc == -1) return Error("Invalid BINOP record");
1983      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1984      InstructionList.push_back(I);
1985      if (OpNum < Record.size()) {
1986        if (Opc == Instruction::Add ||
1987            Opc == Instruction::Sub ||
1988            Opc == Instruction::Mul ||
1989            Opc == Instruction::Shl) {
1990          if (Record[OpNum] & (1 << bitc::OBO_NO_SIGNED_WRAP))
1991            cast<BinaryOperator>(I)->setHasNoSignedWrap(true);
1992          if (Record[OpNum] & (1 << bitc::OBO_NO_UNSIGNED_WRAP))
1993            cast<BinaryOperator>(I)->setHasNoUnsignedWrap(true);
1994        } else if (Opc == Instruction::SDiv ||
1995                   Opc == Instruction::UDiv ||
1996                   Opc == Instruction::LShr ||
1997                   Opc == Instruction::AShr) {
1998          if (Record[OpNum] & (1 << bitc::PEO_EXACT))
1999            cast<BinaryOperator>(I)->setIsExact(true);
2000        }
2001      }
2002      break;
2003    }
2004    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
2005      unsigned OpNum = 0;
2006      Value *Op;
2007      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2008          OpNum+2 != Record.size())
2009        return Error("Invalid CAST record");
2010
2011      Type *ResTy = getTypeByID(Record[OpNum]);
2012      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
2013      if (Opc == -1 || ResTy == 0)
2014        return Error("Invalid CAST record");
2015      I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
2016      InstructionList.push_back(I);
2017      break;
2018    }
2019    case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
2020    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
2021      unsigned OpNum = 0;
2022      Value *BasePtr;
2023      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
2024        return Error("Invalid GEP record");
2025
2026      SmallVector<Value*, 16> GEPIdx;
2027      while (OpNum != Record.size()) {
2028        Value *Op;
2029        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2030          return Error("Invalid GEP record");
2031        GEPIdx.push_back(Op);
2032      }
2033
2034      I = GetElementPtrInst::Create(BasePtr, GEPIdx);
2035      InstructionList.push_back(I);
2036      if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
2037        cast<GetElementPtrInst>(I)->setIsInBounds(true);
2038      break;
2039    }
2040
2041    case bitc::FUNC_CODE_INST_EXTRACTVAL: {
2042                                       // EXTRACTVAL: [opty, opval, n x indices]
2043      unsigned OpNum = 0;
2044      Value *Agg;
2045      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2046        return Error("Invalid EXTRACTVAL record");
2047
2048      SmallVector<unsigned, 4> EXTRACTVALIdx;
2049      for (unsigned RecSize = Record.size();
2050           OpNum != RecSize; ++OpNum) {
2051        uint64_t Index = Record[OpNum];
2052        if ((unsigned)Index != Index)
2053          return Error("Invalid EXTRACTVAL index");
2054        EXTRACTVALIdx.push_back((unsigned)Index);
2055      }
2056
2057      I = ExtractValueInst::Create(Agg, EXTRACTVALIdx);
2058      InstructionList.push_back(I);
2059      break;
2060    }
2061
2062    case bitc::FUNC_CODE_INST_INSERTVAL: {
2063                           // INSERTVAL: [opty, opval, opty, opval, n x indices]
2064      unsigned OpNum = 0;
2065      Value *Agg;
2066      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
2067        return Error("Invalid INSERTVAL record");
2068      Value *Val;
2069      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
2070        return Error("Invalid INSERTVAL record");
2071
2072      SmallVector<unsigned, 4> INSERTVALIdx;
2073      for (unsigned RecSize = Record.size();
2074           OpNum != RecSize; ++OpNum) {
2075        uint64_t Index = Record[OpNum];
2076        if ((unsigned)Index != Index)
2077          return Error("Invalid INSERTVAL index");
2078        INSERTVALIdx.push_back((unsigned)Index);
2079      }
2080
2081      I = InsertValueInst::Create(Agg, Val, INSERTVALIdx);
2082      InstructionList.push_back(I);
2083      break;
2084    }
2085
2086    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
2087      // obsolete form of select
2088      // handles select i1 ... in old bitcode
2089      unsigned OpNum = 0;
2090      Value *TrueVal, *FalseVal, *Cond;
2091      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2092          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2093          getValue(Record, OpNum, Type::getInt1Ty(Context), Cond))
2094        return Error("Invalid SELECT record");
2095
2096      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2097      InstructionList.push_back(I);
2098      break;
2099    }
2100
2101    case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
2102      // new form of select
2103      // handles select i1 or select [N x i1]
2104      unsigned OpNum = 0;
2105      Value *TrueVal, *FalseVal, *Cond;
2106      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
2107          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
2108          getValueTypePair(Record, OpNum, NextValueNo, Cond))
2109        return Error("Invalid SELECT record");
2110
2111      // select condition can be either i1 or [N x i1]
2112      if (VectorType* vector_type =
2113          dyn_cast<VectorType>(Cond->getType())) {
2114        // expect <n x i1>
2115        if (vector_type->getElementType() != Type::getInt1Ty(Context))
2116          return Error("Invalid SELECT condition type");
2117      } else {
2118        // expect i1
2119        if (Cond->getType() != Type::getInt1Ty(Context))
2120          return Error("Invalid SELECT condition type");
2121      }
2122
2123      I = SelectInst::Create(Cond, TrueVal, FalseVal);
2124      InstructionList.push_back(I);
2125      break;
2126    }
2127
2128    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
2129      unsigned OpNum = 0;
2130      Value *Vec, *Idx;
2131      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2132          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2133        return Error("Invalid EXTRACTELT record");
2134      I = ExtractElementInst::Create(Vec, Idx);
2135      InstructionList.push_back(I);
2136      break;
2137    }
2138
2139    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
2140      unsigned OpNum = 0;
2141      Value *Vec, *Elt, *Idx;
2142      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
2143          getValue(Record, OpNum,
2144                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
2145          getValue(Record, OpNum, Type::getInt32Ty(Context), Idx))
2146        return Error("Invalid INSERTELT record");
2147      I = InsertElementInst::Create(Vec, Elt, Idx);
2148      InstructionList.push_back(I);
2149      break;
2150    }
2151
2152    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
2153      unsigned OpNum = 0;
2154      Value *Vec1, *Vec2, *Mask;
2155      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
2156          getValue(Record, OpNum, Vec1->getType(), Vec2))
2157        return Error("Invalid SHUFFLEVEC record");
2158
2159      if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
2160        return Error("Invalid SHUFFLEVEC record");
2161      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
2162      InstructionList.push_back(I);
2163      break;
2164    }
2165
2166    case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
2167      // Old form of ICmp/FCmp returning bool
2168      // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
2169      // both legal on vectors but had different behaviour.
2170    case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
2171      // FCmp/ICmp returning bool or vector of bool
2172
2173      unsigned OpNum = 0;
2174      Value *LHS, *RHS;
2175      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
2176          getValue(Record, OpNum, LHS->getType(), RHS) ||
2177          OpNum+1 != Record.size())
2178        return Error("Invalid CMP record");
2179
2180      if (LHS->getType()->isFPOrFPVectorTy())
2181        I = new FCmpInst((FCmpInst::Predicate)Record[OpNum], LHS, RHS);
2182      else
2183        I = new ICmpInst((ICmpInst::Predicate)Record[OpNum], LHS, RHS);
2184      InstructionList.push_back(I);
2185      break;
2186    }
2187
2188    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
2189      {
2190        unsigned Size = Record.size();
2191        if (Size == 0) {
2192          I = ReturnInst::Create(Context);
2193          InstructionList.push_back(I);
2194          break;
2195        }
2196
2197        unsigned OpNum = 0;
2198        Value *Op = NULL;
2199        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2200          return Error("Invalid RET record");
2201        if (OpNum != Record.size())
2202          return Error("Invalid RET record");
2203
2204        I = ReturnInst::Create(Context, Op);
2205        InstructionList.push_back(I);
2206        break;
2207      }
2208    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
2209      if (Record.size() != 1 && Record.size() != 3)
2210        return Error("Invalid BR record");
2211      BasicBlock *TrueDest = getBasicBlock(Record[0]);
2212      if (TrueDest == 0)
2213        return Error("Invalid BR record");
2214
2215      if (Record.size() == 1) {
2216        I = BranchInst::Create(TrueDest);
2217        InstructionList.push_back(I);
2218      }
2219      else {
2220        BasicBlock *FalseDest = getBasicBlock(Record[1]);
2221        Value *Cond = getFnValueByID(Record[2], Type::getInt1Ty(Context));
2222        if (FalseDest == 0 || Cond == 0)
2223          return Error("Invalid BR record");
2224        I = BranchInst::Create(TrueDest, FalseDest, Cond);
2225        InstructionList.push_back(I);
2226      }
2227      break;
2228    }
2229    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, op0, op1, ...]
2230      // Check magic
2231      if ((Record[0] >> 16) == SWITCH_INST_MAGIC) {
2232        // New SwitchInst format with case ranges.
2233
2234        Type *OpTy = getTypeByID(Record[1]);
2235        unsigned ValueBitWidth = cast<IntegerType>(OpTy)->getBitWidth();
2236
2237        Value *Cond = getFnValueByID(Record[2], OpTy);
2238        BasicBlock *Default = getBasicBlock(Record[3]);
2239        if (OpTy == 0 || Cond == 0 || Default == 0)
2240          return Error("Invalid SWITCH record");
2241
2242        unsigned NumCases = Record[4];
2243
2244        SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2245        InstructionList.push_back(SI);
2246
2247        unsigned CurIdx = 5;
2248        for (unsigned i = 0; i != NumCases; ++i) {
2249          CRSBuilder CaseBuilder;
2250          unsigned NumItems = Record[CurIdx++];
2251          for (unsigned ci = 0; ci != NumItems; ++ci) {
2252            bool isSingleNumber = Record[CurIdx++];
2253
2254            APInt Low;
2255            unsigned ActiveWords = 1;
2256            if (ValueBitWidth > 64)
2257              ActiveWords = Record[CurIdx++];
2258            Low = ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2259                                ValueBitWidth);
2260            CurIdx += ActiveWords;
2261
2262            if (!isSingleNumber) {
2263              ActiveWords = 1;
2264              if (ValueBitWidth > 64)
2265                ActiveWords = Record[CurIdx++];
2266              APInt High =
2267                  ReadWideAPInt(makeArrayRef(&Record[CurIdx], ActiveWords),
2268                                ValueBitWidth);
2269              IntItemConstantIntImpl HighImpl =
2270                  cast<ConstantInt>(ConstantInt::get(OpTy, High));
2271
2272              CaseBuilder.add(IntItem::fromType(OpTy, Low),
2273                              IntItem::fromType(OpTy, High));
2274              CurIdx += ActiveWords;
2275            } else
2276              CaseBuilder.add(IntItem::fromType(OpTy, Low));
2277          }
2278          BasicBlock *DestBB = getBasicBlock(Record[CurIdx++]);
2279          ConstantRangesSet Case = CaseBuilder.getCase();
2280          SI->addCase(Case, DestBB);
2281        }
2282        uint16_t Hash = SI->hash();
2283        if (Hash != (Record[0] & 0xFFFF))
2284          return Error("Invalid SWITCH record");
2285        I = SI;
2286        break;
2287      }
2288
2289      // Old SwitchInst format without case ranges.
2290
2291      if (Record.size() < 3 || (Record.size() & 1) == 0)
2292        return Error("Invalid SWITCH record");
2293      Type *OpTy = getTypeByID(Record[0]);
2294      Value *Cond = getFnValueByID(Record[1], OpTy);
2295      BasicBlock *Default = getBasicBlock(Record[2]);
2296      if (OpTy == 0 || Cond == 0 || Default == 0)
2297        return Error("Invalid SWITCH record");
2298      unsigned NumCases = (Record.size()-3)/2;
2299      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
2300      InstructionList.push_back(SI);
2301      for (unsigned i = 0, e = NumCases; i != e; ++i) {
2302        ConstantInt *CaseVal =
2303          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
2304        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
2305        if (CaseVal == 0 || DestBB == 0) {
2306          delete SI;
2307          return Error("Invalid SWITCH record!");
2308        }
2309        SI->addCase(CaseVal, DestBB);
2310      }
2311      I = SI;
2312      break;
2313    }
2314    case bitc::FUNC_CODE_INST_INDIRECTBR: { // INDIRECTBR: [opty, op0, op1, ...]
2315      if (Record.size() < 2)
2316        return Error("Invalid INDIRECTBR record");
2317      Type *OpTy = getTypeByID(Record[0]);
2318      Value *Address = getFnValueByID(Record[1], OpTy);
2319      if (OpTy == 0 || Address == 0)
2320        return Error("Invalid INDIRECTBR record");
2321      unsigned NumDests = Record.size()-2;
2322      IndirectBrInst *IBI = IndirectBrInst::Create(Address, NumDests);
2323      InstructionList.push_back(IBI);
2324      for (unsigned i = 0, e = NumDests; i != e; ++i) {
2325        if (BasicBlock *DestBB = getBasicBlock(Record[2+i])) {
2326          IBI->addDestination(DestBB);
2327        } else {
2328          delete IBI;
2329          return Error("Invalid INDIRECTBR record!");
2330        }
2331      }
2332      I = IBI;
2333      break;
2334    }
2335
2336    case bitc::FUNC_CODE_INST_INVOKE: {
2337      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
2338      if (Record.size() < 4) return Error("Invalid INVOKE record");
2339      AttrListPtr PAL = getAttributes(Record[0]);
2340      unsigned CCInfo = Record[1];
2341      BasicBlock *NormalBB = getBasicBlock(Record[2]);
2342      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
2343
2344      unsigned OpNum = 4;
2345      Value *Callee;
2346      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2347        return Error("Invalid INVOKE record");
2348
2349      PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
2350      FunctionType *FTy = !CalleeTy ? 0 :
2351        dyn_cast<FunctionType>(CalleeTy->getElementType());
2352
2353      // Check that the right number of fixed parameters are here.
2354      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
2355          Record.size() < OpNum+FTy->getNumParams())
2356        return Error("Invalid INVOKE record");
2357
2358      SmallVector<Value*, 16> Ops;
2359      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2360        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2361        if (Ops.back() == 0) return Error("Invalid INVOKE record");
2362      }
2363
2364      if (!FTy->isVarArg()) {
2365        if (Record.size() != OpNum)
2366          return Error("Invalid INVOKE record");
2367      } else {
2368        // Read type/value pairs for varargs params.
2369        while (OpNum != Record.size()) {
2370          Value *Op;
2371          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2372            return Error("Invalid INVOKE record");
2373          Ops.push_back(Op);
2374        }
2375      }
2376
2377      I = InvokeInst::Create(Callee, NormalBB, UnwindBB, Ops);
2378      InstructionList.push_back(I);
2379      cast<InvokeInst>(I)->setCallingConv(
2380        static_cast<CallingConv::ID>(CCInfo));
2381      cast<InvokeInst>(I)->setAttributes(PAL);
2382      break;
2383    }
2384    case bitc::FUNC_CODE_INST_RESUME: { // RESUME: [opval]
2385      unsigned Idx = 0;
2386      Value *Val = 0;
2387      if (getValueTypePair(Record, Idx, NextValueNo, Val))
2388        return Error("Invalid RESUME record");
2389      I = ResumeInst::Create(Val);
2390      InstructionList.push_back(I);
2391      break;
2392    }
2393    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
2394      I = new UnreachableInst(Context);
2395      InstructionList.push_back(I);
2396      break;
2397    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
2398      if (Record.size() < 1 || ((Record.size()-1)&1))
2399        return Error("Invalid PHI record");
2400      Type *Ty = getTypeByID(Record[0]);
2401      if (!Ty) return Error("Invalid PHI record");
2402
2403      PHINode *PN = PHINode::Create(Ty, (Record.size()-1)/2);
2404      InstructionList.push_back(PN);
2405
2406      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
2407        Value *V = getFnValueByID(Record[1+i], Ty);
2408        BasicBlock *BB = getBasicBlock(Record[2+i]);
2409        if (!V || !BB) return Error("Invalid PHI record");
2410        PN->addIncoming(V, BB);
2411      }
2412      I = PN;
2413      break;
2414    }
2415
2416    case bitc::FUNC_CODE_INST_LANDINGPAD: {
2417      // LANDINGPAD: [ty, val, val, num, (id0,val0 ...)?]
2418      unsigned Idx = 0;
2419      if (Record.size() < 4)
2420        return Error("Invalid LANDINGPAD record");
2421      Type *Ty = getTypeByID(Record[Idx++]);
2422      if (!Ty) return Error("Invalid LANDINGPAD record");
2423      Value *PersFn = 0;
2424      if (getValueTypePair(Record, Idx, NextValueNo, PersFn))
2425        return Error("Invalid LANDINGPAD record");
2426
2427      bool IsCleanup = !!Record[Idx++];
2428      unsigned NumClauses = Record[Idx++];
2429      LandingPadInst *LP = LandingPadInst::Create(Ty, PersFn, NumClauses);
2430      LP->setCleanup(IsCleanup);
2431      for (unsigned J = 0; J != NumClauses; ++J) {
2432        LandingPadInst::ClauseType CT =
2433          LandingPadInst::ClauseType(Record[Idx++]); (void)CT;
2434        Value *Val;
2435
2436        if (getValueTypePair(Record, Idx, NextValueNo, Val)) {
2437          delete LP;
2438          return Error("Invalid LANDINGPAD record");
2439        }
2440
2441        assert((CT != LandingPadInst::Catch ||
2442                !isa<ArrayType>(Val->getType())) &&
2443               "Catch clause has a invalid type!");
2444        assert((CT != LandingPadInst::Filter ||
2445                isa<ArrayType>(Val->getType())) &&
2446               "Filter clause has invalid type!");
2447        LP->addClause(Val);
2448      }
2449
2450      I = LP;
2451      InstructionList.push_back(I);
2452      break;
2453    }
2454
2455    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, opty, op, align]
2456      if (Record.size() != 4)
2457        return Error("Invalid ALLOCA record");
2458      PointerType *Ty =
2459        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
2460      Type *OpTy = getTypeByID(Record[1]);
2461      Value *Size = getFnValueByID(Record[2], OpTy);
2462      unsigned Align = Record[3];
2463      if (!Ty || !Size) return Error("Invalid ALLOCA record");
2464      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
2465      InstructionList.push_back(I);
2466      break;
2467    }
2468    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
2469      unsigned OpNum = 0;
2470      Value *Op;
2471      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2472          OpNum+2 != Record.size())
2473        return Error("Invalid LOAD record");
2474
2475      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2476      InstructionList.push_back(I);
2477      break;
2478    }
2479    case bitc::FUNC_CODE_INST_LOADATOMIC: {
2480       // LOADATOMIC: [opty, op, align, vol, ordering, synchscope]
2481      unsigned OpNum = 0;
2482      Value *Op;
2483      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
2484          OpNum+4 != Record.size())
2485        return Error("Invalid LOADATOMIC record");
2486
2487
2488      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2489      if (Ordering == NotAtomic || Ordering == Release ||
2490          Ordering == AcquireRelease)
2491        return Error("Invalid LOADATOMIC record");
2492      if (Ordering != NotAtomic && Record[OpNum] == 0)
2493        return Error("Invalid LOADATOMIC record");
2494      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2495
2496      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2497                       Ordering, SynchScope);
2498      InstructionList.push_back(I);
2499      break;
2500    }
2501    case bitc::FUNC_CODE_INST_STORE: { // STORE2:[ptrty, ptr, val, align, vol]
2502      unsigned OpNum = 0;
2503      Value *Val, *Ptr;
2504      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2505          getValue(Record, OpNum,
2506                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2507          OpNum+2 != Record.size())
2508        return Error("Invalid STORE record");
2509
2510      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
2511      InstructionList.push_back(I);
2512      break;
2513    }
2514    case bitc::FUNC_CODE_INST_STOREATOMIC: {
2515      // STOREATOMIC: [ptrty, ptr, val, align, vol, ordering, synchscope]
2516      unsigned OpNum = 0;
2517      Value *Val, *Ptr;
2518      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2519          getValue(Record, OpNum,
2520                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2521          OpNum+4 != Record.size())
2522        return Error("Invalid STOREATOMIC record");
2523
2524      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2525      if (Ordering == NotAtomic || Ordering == Acquire ||
2526          Ordering == AcquireRelease)
2527        return Error("Invalid STOREATOMIC record");
2528      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2529      if (Ordering != NotAtomic && Record[OpNum] == 0)
2530        return Error("Invalid STOREATOMIC record");
2531
2532      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1,
2533                        Ordering, SynchScope);
2534      InstructionList.push_back(I);
2535      break;
2536    }
2537    case bitc::FUNC_CODE_INST_CMPXCHG: {
2538      // CMPXCHG:[ptrty, ptr, cmp, new, vol, ordering, synchscope]
2539      unsigned OpNum = 0;
2540      Value *Ptr, *Cmp, *New;
2541      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2542          getValue(Record, OpNum,
2543                    cast<PointerType>(Ptr->getType())->getElementType(), Cmp) ||
2544          getValue(Record, OpNum,
2545                    cast<PointerType>(Ptr->getType())->getElementType(), New) ||
2546          OpNum+3 != Record.size())
2547        return Error("Invalid CMPXCHG record");
2548      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+1]);
2549      if (Ordering == NotAtomic || Ordering == Unordered)
2550        return Error("Invalid CMPXCHG record");
2551      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+2]);
2552      I = new AtomicCmpXchgInst(Ptr, Cmp, New, Ordering, SynchScope);
2553      cast<AtomicCmpXchgInst>(I)->setVolatile(Record[OpNum]);
2554      InstructionList.push_back(I);
2555      break;
2556    }
2557    case bitc::FUNC_CODE_INST_ATOMICRMW: {
2558      // ATOMICRMW:[ptrty, ptr, val, op, vol, ordering, synchscope]
2559      unsigned OpNum = 0;
2560      Value *Ptr, *Val;
2561      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
2562          getValue(Record, OpNum,
2563                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
2564          OpNum+4 != Record.size())
2565        return Error("Invalid ATOMICRMW record");
2566      AtomicRMWInst::BinOp Operation = GetDecodedRMWOperation(Record[OpNum]);
2567      if (Operation < AtomicRMWInst::FIRST_BINOP ||
2568          Operation > AtomicRMWInst::LAST_BINOP)
2569        return Error("Invalid ATOMICRMW record");
2570      AtomicOrdering Ordering = GetDecodedOrdering(Record[OpNum+2]);
2571      if (Ordering == NotAtomic || Ordering == Unordered)
2572        return Error("Invalid ATOMICRMW record");
2573      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[OpNum+3]);
2574      I = new AtomicRMWInst(Operation, Ptr, Val, Ordering, SynchScope);
2575      cast<AtomicRMWInst>(I)->setVolatile(Record[OpNum+1]);
2576      InstructionList.push_back(I);
2577      break;
2578    }
2579    case bitc::FUNC_CODE_INST_FENCE: { // FENCE:[ordering, synchscope]
2580      if (2 != Record.size())
2581        return Error("Invalid FENCE record");
2582      AtomicOrdering Ordering = GetDecodedOrdering(Record[0]);
2583      if (Ordering == NotAtomic || Ordering == Unordered ||
2584          Ordering == Monotonic)
2585        return Error("Invalid FENCE record");
2586      SynchronizationScope SynchScope = GetDecodedSynchScope(Record[1]);
2587      I = new FenceInst(Context, Ordering, SynchScope);
2588      InstructionList.push_back(I);
2589      break;
2590    }
2591    case bitc::FUNC_CODE_INST_CALL: {
2592      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
2593      if (Record.size() < 3)
2594        return Error("Invalid CALL record");
2595
2596      AttrListPtr PAL = getAttributes(Record[0]);
2597      unsigned CCInfo = Record[1];
2598
2599      unsigned OpNum = 2;
2600      Value *Callee;
2601      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
2602        return Error("Invalid CALL record");
2603
2604      PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
2605      FunctionType *FTy = 0;
2606      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
2607      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
2608        return Error("Invalid CALL record");
2609
2610      SmallVector<Value*, 16> Args;
2611      // Read the fixed params.
2612      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
2613        if (FTy->getParamType(i)->isLabelTy())
2614          Args.push_back(getBasicBlock(Record[OpNum]));
2615        else
2616          Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2617        if (Args.back() == 0) return Error("Invalid CALL record");
2618      }
2619
2620      // Read type/value pairs for varargs params.
2621      if (!FTy->isVarArg()) {
2622        if (OpNum != Record.size())
2623          return Error("Invalid CALL record");
2624      } else {
2625        while (OpNum != Record.size()) {
2626          Value *Op;
2627          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2628            return Error("Invalid CALL record");
2629          Args.push_back(Op);
2630        }
2631      }
2632
2633      I = CallInst::Create(Callee, Args);
2634      InstructionList.push_back(I);
2635      cast<CallInst>(I)->setCallingConv(
2636        static_cast<CallingConv::ID>(CCInfo>>1));
2637      cast<CallInst>(I)->setTailCall(CCInfo & 1);
2638      cast<CallInst>(I)->setAttributes(PAL);
2639      break;
2640    }
2641    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2642      if (Record.size() < 3)
2643        return Error("Invalid VAARG record");
2644      Type *OpTy = getTypeByID(Record[0]);
2645      Value *Op = getFnValueByID(Record[1], OpTy);
2646      Type *ResTy = getTypeByID(Record[2]);
2647      if (!OpTy || !Op || !ResTy)
2648        return Error("Invalid VAARG record");
2649      I = new VAArgInst(Op, ResTy);
2650      InstructionList.push_back(I);
2651      break;
2652    }
2653    }
2654
2655    // Add instruction to end of current BB.  If there is no current BB, reject
2656    // this file.
2657    if (CurBB == 0) {
2658      delete I;
2659      return Error("Invalid instruction with no BB");
2660    }
2661    CurBB->getInstList().push_back(I);
2662
2663    // If this was a terminator instruction, move to the next block.
2664    if (isa<TerminatorInst>(I)) {
2665      ++CurBBNo;
2666      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2667    }
2668
2669    // Non-void values get registered in the value table for future use.
2670    if (I && !I->getType()->isVoidTy())
2671      ValueList.AssignValue(I, NextValueNo++);
2672  }
2673
2674  // Check the function list for unresolved values.
2675  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2676    if (A->getParent() == 0) {
2677      // We found at least one unresolved value.  Nuke them all to avoid leaks.
2678      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2679        if ((A = dyn_cast<Argument>(ValueList[i])) && A->getParent() == 0) {
2680          A->replaceAllUsesWith(UndefValue::get(A->getType()));
2681          delete A;
2682        }
2683      }
2684      return Error("Never resolved value found in function!");
2685    }
2686  }
2687
2688  // FIXME: Check for unresolved forward-declared metadata references
2689  // and clean up leaks.
2690
2691  // See if anything took the address of blocks in this function.  If so,
2692  // resolve them now.
2693  DenseMap<Function*, std::vector<BlockAddrRefTy> >::iterator BAFRI =
2694    BlockAddrFwdRefs.find(F);
2695  if (BAFRI != BlockAddrFwdRefs.end()) {
2696    std::vector<BlockAddrRefTy> &RefList = BAFRI->second;
2697    for (unsigned i = 0, e = RefList.size(); i != e; ++i) {
2698      unsigned BlockIdx = RefList[i].first;
2699      if (BlockIdx >= FunctionBBs.size())
2700        return Error("Invalid blockaddress block #");
2701
2702      GlobalVariable *FwdRef = RefList[i].second;
2703      FwdRef->replaceAllUsesWith(BlockAddress::get(F, FunctionBBs[BlockIdx]));
2704      FwdRef->eraseFromParent();
2705    }
2706
2707    BlockAddrFwdRefs.erase(BAFRI);
2708  }
2709
2710  // Trim the value list down to the size it was before we parsed this function.
2711  ValueList.shrinkTo(ModuleValueListSize);
2712  MDValueList.shrinkTo(ModuleMDValueListSize);
2713  std::vector<BasicBlock*>().swap(FunctionBBs);
2714  return false;
2715}
2716
2717/// FindFunctionInStream - Find the function body in the bitcode stream
2718bool BitcodeReader::FindFunctionInStream(Function *F,
2719       DenseMap<Function*, uint64_t>::iterator DeferredFunctionInfoIterator) {
2720  while (DeferredFunctionInfoIterator->second == 0) {
2721    if (Stream.AtEndOfStream())
2722      return Error("Could not find Function in stream");
2723    // ParseModule will parse the next body in the stream and set its
2724    // position in the DeferredFunctionInfo map.
2725    if (ParseModule(true)) return true;
2726  }
2727  return false;
2728}
2729
2730//===----------------------------------------------------------------------===//
2731// GVMaterializer implementation
2732//===----------------------------------------------------------------------===//
2733
2734
2735bool BitcodeReader::isMaterializable(const GlobalValue *GV) const {
2736  if (const Function *F = dyn_cast<Function>(GV)) {
2737    return F->isDeclaration() &&
2738      DeferredFunctionInfo.count(const_cast<Function*>(F));
2739  }
2740  return false;
2741}
2742
2743bool BitcodeReader::Materialize(GlobalValue *GV, std::string *ErrInfo) {
2744  Function *F = dyn_cast<Function>(GV);
2745  // If it's not a function or is already material, ignore the request.
2746  if (!F || !F->isMaterializable()) return false;
2747
2748  DenseMap<Function*, uint64_t>::iterator DFII = DeferredFunctionInfo.find(F);
2749  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2750  // If its position is recorded as 0, its body is somewhere in the stream
2751  // but we haven't seen it yet.
2752  if (DFII->second == 0)
2753    if (LazyStreamer && FindFunctionInStream(F, DFII)) return true;
2754
2755  // Move the bit stream to the saved position of the deferred function body.
2756  Stream.JumpToBit(DFII->second);
2757
2758  if (ParseFunctionBody(F)) {
2759    if (ErrInfo) *ErrInfo = ErrorString;
2760    return true;
2761  }
2762
2763  // Upgrade any old intrinsic calls in the function.
2764  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2765       E = UpgradedIntrinsics.end(); I != E; ++I) {
2766    if (I->first != I->second) {
2767      for (Value::use_iterator UI = I->first->use_begin(),
2768           UE = I->first->use_end(); UI != UE; ) {
2769        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2770          UpgradeIntrinsicCall(CI, I->second);
2771      }
2772    }
2773  }
2774
2775  return false;
2776}
2777
2778bool BitcodeReader::isDematerializable(const GlobalValue *GV) const {
2779  const Function *F = dyn_cast<Function>(GV);
2780  if (!F || F->isDeclaration())
2781    return false;
2782  return DeferredFunctionInfo.count(const_cast<Function*>(F));
2783}
2784
2785void BitcodeReader::Dematerialize(GlobalValue *GV) {
2786  Function *F = dyn_cast<Function>(GV);
2787  // If this function isn't dematerializable, this is a noop.
2788  if (!F || !isDematerializable(F))
2789    return;
2790
2791  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2792
2793  // Just forget the function body, we can remat it later.
2794  F->deleteBody();
2795}
2796
2797
2798bool BitcodeReader::MaterializeModule(Module *M, std::string *ErrInfo) {
2799  assert(M == TheModule &&
2800         "Can only Materialize the Module this BitcodeReader is attached to.");
2801  // Iterate over the module, deserializing any functions that are still on
2802  // disk.
2803  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2804       F != E; ++F)
2805    if (F->isMaterializable() &&
2806        Materialize(F, ErrInfo))
2807      return true;
2808
2809  // At this point, if there are any function bodies, the current bit is
2810  // pointing to the END_BLOCK record after them. Now make sure the rest
2811  // of the bits in the module have been read.
2812  if (NextUnreadBit)
2813    ParseModule(true);
2814
2815  // Upgrade any intrinsic calls that slipped through (should not happen!) and
2816  // delete the old functions to clean up. We can't do this unless the entire
2817  // module is materialized because there could always be another function body
2818  // with calls to the old function.
2819  for (std::vector<std::pair<Function*, Function*> >::iterator I =
2820       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2821    if (I->first != I->second) {
2822      for (Value::use_iterator UI = I->first->use_begin(),
2823           UE = I->first->use_end(); UI != UE; ) {
2824        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2825          UpgradeIntrinsicCall(CI, I->second);
2826      }
2827      if (!I->first->use_empty())
2828        I->first->replaceAllUsesWith(I->second);
2829      I->first->eraseFromParent();
2830    }
2831  }
2832  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2833
2834  return false;
2835}
2836
2837bool BitcodeReader::InitStream() {
2838  if (LazyStreamer) return InitLazyStream();
2839  return InitStreamFromBuffer();
2840}
2841
2842bool BitcodeReader::InitStreamFromBuffer() {
2843  const unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
2844  const unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
2845
2846  if (Buffer->getBufferSize() & 3) {
2847    if (!isRawBitcode(BufPtr, BufEnd) && !isBitcodeWrapper(BufPtr, BufEnd))
2848      return Error("Invalid bitcode signature");
2849    else
2850      return Error("Bitcode stream should be a multiple of 4 bytes in length");
2851  }
2852
2853  // If we have a wrapper header, parse it and ignore the non-bc file contents.
2854  // The magic number is 0x0B17C0DE stored in little endian.
2855  if (isBitcodeWrapper(BufPtr, BufEnd))
2856    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd, true))
2857      return Error("Invalid bitcode wrapper header");
2858
2859  StreamFile.reset(new BitstreamReader(BufPtr, BufEnd));
2860  Stream.init(*StreamFile);
2861
2862  return false;
2863}
2864
2865bool BitcodeReader::InitLazyStream() {
2866  // Check and strip off the bitcode wrapper; BitstreamReader expects never to
2867  // see it.
2868  StreamingMemoryObject *Bytes = new StreamingMemoryObject(LazyStreamer);
2869  StreamFile.reset(new BitstreamReader(Bytes));
2870  Stream.init(*StreamFile);
2871
2872  unsigned char buf[16];
2873  if (Bytes->readBytes(0, 16, buf, NULL) == -1)
2874    return Error("Bitcode stream must be at least 16 bytes in length");
2875
2876  if (!isBitcode(buf, buf + 16))
2877    return Error("Invalid bitcode signature");
2878
2879  if (isBitcodeWrapper(buf, buf + 4)) {
2880    const unsigned char *bitcodeStart = buf;
2881    const unsigned char *bitcodeEnd = buf + 16;
2882    SkipBitcodeWrapperHeader(bitcodeStart, bitcodeEnd, false);
2883    Bytes->dropLeadingBytes(bitcodeStart - buf);
2884    Bytes->setKnownObjectSize(bitcodeEnd - bitcodeStart);
2885  }
2886  return false;
2887}
2888
2889//===----------------------------------------------------------------------===//
2890// External interface
2891//===----------------------------------------------------------------------===//
2892
2893/// getLazyBitcodeModule - lazy function-at-a-time loading from a file.
2894///
2895Module *llvm::getLazyBitcodeModule(MemoryBuffer *Buffer,
2896                                   LLVMContext& Context,
2897                                   std::string *ErrMsg) {
2898  Module *M = new Module(Buffer->getBufferIdentifier(), Context);
2899  BitcodeReader *R = new BitcodeReader(Buffer, Context);
2900  M->setMaterializer(R);
2901  if (R->ParseBitcodeInto(M)) {
2902    if (ErrMsg)
2903      *ErrMsg = R->getErrorString();
2904
2905    delete M;  // Also deletes R.
2906    return 0;
2907  }
2908  // Have the BitcodeReader dtor delete 'Buffer'.
2909  R->setBufferOwned(true);
2910
2911  R->materializeForwardReferencedFunctions();
2912
2913  return M;
2914}
2915
2916
2917Module *llvm::getStreamedBitcodeModule(const std::string &name,
2918                                       DataStreamer *streamer,
2919                                       LLVMContext &Context,
2920                                       std::string *ErrMsg) {
2921  Module *M = new Module(name, Context);
2922  BitcodeReader *R = new BitcodeReader(streamer, Context);
2923  M->setMaterializer(R);
2924  if (R->ParseBitcodeInto(M)) {
2925    if (ErrMsg)
2926      *ErrMsg = R->getErrorString();
2927    delete M;  // Also deletes R.
2928    return 0;
2929  }
2930  R->setBufferOwned(false); // no buffer to delete
2931  return M;
2932}
2933
2934/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2935/// If an error occurs, return null and fill in *ErrMsg if non-null.
2936Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2937                               std::string *ErrMsg){
2938  Module *M = getLazyBitcodeModule(Buffer, Context, ErrMsg);
2939  if (!M) return 0;
2940
2941  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2942  // there was an error.
2943  static_cast<BitcodeReader*>(M->getMaterializer())->setBufferOwned(false);
2944
2945  // Read in the entire module, and destroy the BitcodeReader.
2946  if (M->MaterializeAllPermanently(ErrMsg)) {
2947    delete M;
2948    return 0;
2949  }
2950
2951  // TODO: Restore the use-lists to the in-memory state when the bitcode was
2952  // written.  We must defer until the Module has been fully materialized.
2953
2954  return M;
2955}
2956
2957std::string llvm::getBitcodeTargetTriple(MemoryBuffer *Buffer,
2958                                         LLVMContext& Context,
2959                                         std::string *ErrMsg) {
2960  BitcodeReader *R = new BitcodeReader(Buffer, Context);
2961  // Don't let the BitcodeReader dtor delete 'Buffer'.
2962  R->setBufferOwned(false);
2963
2964  std::string Triple("");
2965  if (R->ParseTriple(Triple))
2966    if (ErrMsg)
2967      *ErrMsg = R->getErrorString();
2968
2969  delete R;
2970  return Triple;
2971}
2972