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