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