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