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