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