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