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