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