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