BitcodeReader.cpp revision a7235ea7245028a0723e8ab7fd011386b3900777
1//===- BitcodeReader.cpp - Internal BitcodeReader implementation ----------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This header defines the BitcodeReader class.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/Bitcode/ReaderWriter.h"
15#include "BitcodeReader.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/InlineAsm.h"
19#include "llvm/Instructions.h"
20#include "llvm/LLVMContext.h"
21#include "llvm/Metadata.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"
30using namespace llvm;
31
32void BitcodeReader::FreeState() {
33  delete Buffer;
34  Buffer = 0;
35  std::vector<PATypeHolder>().swap(TypeList);
36  ValueList.clear();
37
38  std::vector<AttrListPtr>().swap(MAttributes);
39  std::vector<BasicBlock*>().swap(FunctionBBs);
40  std::vector<Function*>().swap(FunctionsWithBodies);
41  DeferredFunctionInfo.clear();
42}
43
44//===----------------------------------------------------------------------===//
45//  Helper functions to implement forward reference resolution, etc.
46//===----------------------------------------------------------------------===//
47
48/// ConvertToString - Convert a string from a record into an std::string, return
49/// true on failure.
50template<typename StrTy>
51static bool ConvertToString(SmallVector<uint64_t, 64> &Record, unsigned Idx,
52                            StrTy &Result) {
53  if (Idx > Record.size())
54    return true;
55
56  for (unsigned i = Idx, e = Record.size(); i != e; ++i)
57    Result += (char)Record[i];
58  return false;
59}
60
61static GlobalValue::LinkageTypes GetDecodedLinkage(unsigned Val) {
62  switch (Val) {
63  default: // Map unknown/new linkages to external
64  case 0:  return GlobalValue::ExternalLinkage;
65  case 1:  return GlobalValue::WeakAnyLinkage;
66  case 2:  return GlobalValue::AppendingLinkage;
67  case 3:  return GlobalValue::InternalLinkage;
68  case 4:  return GlobalValue::LinkOnceAnyLinkage;
69  case 5:  return GlobalValue::DLLImportLinkage;
70  case 6:  return GlobalValue::DLLExportLinkage;
71  case 7:  return GlobalValue::ExternalWeakLinkage;
72  case 8:  return GlobalValue::CommonLinkage;
73  case 9:  return GlobalValue::PrivateLinkage;
74  case 10: return GlobalValue::WeakODRLinkage;
75  case 11: return GlobalValue::LinkOnceODRLinkage;
76  case 12: return GlobalValue::AvailableExternallyLinkage;
77  case 13: return GlobalValue::LinkerPrivateLinkage;
78  }
79}
80
81static GlobalValue::VisibilityTypes GetDecodedVisibility(unsigned Val) {
82  switch (Val) {
83  default: // Map unknown visibilities to default.
84  case 0: return GlobalValue::DefaultVisibility;
85  case 1: return GlobalValue::HiddenVisibility;
86  case 2: return GlobalValue::ProtectedVisibility;
87  }
88}
89
90static int GetDecodedCastOpcode(unsigned Val) {
91  switch (Val) {
92  default: return -1;
93  case bitc::CAST_TRUNC   : return Instruction::Trunc;
94  case bitc::CAST_ZEXT    : return Instruction::ZExt;
95  case bitc::CAST_SEXT    : return Instruction::SExt;
96  case bitc::CAST_FPTOUI  : return Instruction::FPToUI;
97  case bitc::CAST_FPTOSI  : return Instruction::FPToSI;
98  case bitc::CAST_UITOFP  : return Instruction::UIToFP;
99  case bitc::CAST_SITOFP  : return Instruction::SIToFP;
100  case bitc::CAST_FPTRUNC : return Instruction::FPTrunc;
101  case bitc::CAST_FPEXT   : return Instruction::FPExt;
102  case bitc::CAST_PTRTOINT: return Instruction::PtrToInt;
103  case bitc::CAST_INTTOPTR: return Instruction::IntToPtr;
104  case bitc::CAST_BITCAST : return Instruction::BitCast;
105  }
106}
107static int GetDecodedBinaryOpcode(unsigned Val, const Type *Ty) {
108  switch (Val) {
109  default: return -1;
110  case bitc::BINOP_ADD:
111    return Ty->isFPOrFPVector() ? Instruction::FAdd : Instruction::Add;
112  case bitc::BINOP_SUB:
113    return Ty->isFPOrFPVector() ? Instruction::FSub : Instruction::Sub;
114  case bitc::BINOP_MUL:
115    return Ty->isFPOrFPVector() ? Instruction::FMul : Instruction::Mul;
116  case bitc::BINOP_UDIV: return Instruction::UDiv;
117  case bitc::BINOP_SDIV:
118    return Ty->isFPOrFPVector() ? Instruction::FDiv : Instruction::SDiv;
119  case bitc::BINOP_UREM: return Instruction::URem;
120  case bitc::BINOP_SREM:
121    return Ty->isFPOrFPVector() ? Instruction::FRem : Instruction::SRem;
122  case bitc::BINOP_SHL:  return Instruction::Shl;
123  case bitc::BINOP_LSHR: return Instruction::LShr;
124  case bitc::BINOP_ASHR: return Instruction::AShr;
125  case bitc::BINOP_AND:  return Instruction::And;
126  case bitc::BINOP_OR:   return Instruction::Or;
127  case bitc::BINOP_XOR:  return Instruction::Xor;
128  }
129}
130
131namespace llvm {
132namespace {
133  /// @brief A class for maintaining the slot number definition
134  /// as a placeholder for the actual definition for forward constants defs.
135  class ConstantPlaceHolder : public ConstantExpr {
136    ConstantPlaceHolder();                       // DO NOT IMPLEMENT
137    void operator=(const ConstantPlaceHolder &); // DO NOT IMPLEMENT
138  public:
139    // allocate space for exactly one operand
140    void *operator new(size_t s) {
141      return User::operator new(s, 1);
142    }
143    explicit ConstantPlaceHolder(const Type *Ty, LLVMContext& Context)
144      : ConstantExpr(Ty, Instruction::UserOp1, &Op<0>(), 1) {
145      Op<0>() = UndefValue::get(Type::Int32Ty);
146    }
147
148    /// @brief Methods to support type inquiry through isa, cast, and dyn_cast.
149    static inline bool classof(const ConstantPlaceHolder *) { return true; }
150    static bool classof(const Value *V) {
151      return isa<ConstantExpr>(V) &&
152             cast<ConstantExpr>(V)->getOpcode() == Instruction::UserOp1;
153    }
154
155
156    /// Provide fast operand accessors
157    //DECLARE_TRANSPARENT_OPERAND_ACCESSORS(Value);
158  };
159}
160
161// FIXME: can we inherit this from ConstantExpr?
162template <>
163struct OperandTraits<ConstantPlaceHolder> : FixedNumOperandTraits<1> {
164};
165}
166
167
168void BitcodeReaderValueList::AssignValue(Value *V, unsigned Idx) {
169  if (Idx == size()) {
170    push_back(V);
171    return;
172  }
173
174  if (Idx >= size())
175    resize(Idx+1);
176
177  WeakVH &OldV = ValuePtrs[Idx];
178  if (OldV == 0) {
179    OldV = V;
180    return;
181  }
182
183  // Handle constants and non-constants (e.g. instrs) differently for
184  // efficiency.
185  if (Constant *PHC = dyn_cast<Constant>(&*OldV)) {
186    ResolveConstants.push_back(std::make_pair(PHC, Idx));
187    OldV = V;
188  } else {
189    // If there was a forward reference to this value, replace it.
190    Value *PrevVal = OldV;
191    OldV->replaceAllUsesWith(V);
192    delete PrevVal;
193  }
194}
195
196
197Constant *BitcodeReaderValueList::getConstantFwdRef(unsigned Idx,
198                                                    const Type *Ty) {
199  if (Idx >= size())
200    resize(Idx + 1);
201
202  if (Value *V = ValuePtrs[Idx]) {
203    assert(Ty == V->getType() && "Type mismatch in constant table!");
204    return cast<Constant>(V);
205  }
206
207  // Create and return a placeholder, which will later be RAUW'd.
208  Constant *C = new ConstantPlaceHolder(Ty, Context);
209  ValuePtrs[Idx] = C;
210  return C;
211}
212
213Value *BitcodeReaderValueList::getValueFwdRef(unsigned Idx, const Type *Ty) {
214  if (Idx >= size())
215    resize(Idx + 1);
216
217  if (Value *V = ValuePtrs[Idx]) {
218    assert((Ty == 0 || Ty == V->getType()) && "Type mismatch in value table!");
219    return V;
220  }
221
222  // No type specified, must be invalid reference.
223  if (Ty == 0) return 0;
224
225  // Create and return a placeholder, which will later be RAUW'd.
226  Value *V = new Argument(Ty);
227  ValuePtrs[Idx] = V;
228  return V;
229}
230
231/// ResolveConstantForwardRefs - Once all constants are read, this method bulk
232/// resolves any forward references.  The idea behind this is that we sometimes
233/// get constants (such as large arrays) which reference *many* forward ref
234/// constants.  Replacing each of these causes a lot of thrashing when
235/// building/reuniquing the constant.  Instead of doing this, we look at all the
236/// uses and rewrite all the place holders at once for any constant that uses
237/// a placeholder.
238void BitcodeReaderValueList::ResolveConstantForwardRefs() {
239  // Sort the values by-pointer so that they are efficient to look up with a
240  // binary search.
241  std::sort(ResolveConstants.begin(), ResolveConstants.end());
242
243  SmallVector<Constant*, 64> NewOps;
244
245  while (!ResolveConstants.empty()) {
246    Value *RealVal = operator[](ResolveConstants.back().second);
247    Constant *Placeholder = ResolveConstants.back().first;
248    ResolveConstants.pop_back();
249
250    // Loop over all users of the placeholder, updating them to reference the
251    // new value.  If they reference more than one placeholder, update them all
252    // at once.
253    while (!Placeholder->use_empty()) {
254      Value::use_iterator UI = Placeholder->use_begin();
255
256      // If the using object isn't uniqued, just update the operands.  This
257      // handles instructions and initializers for global variables.
258      if (!isa<Constant>(*UI) || isa<GlobalValue>(*UI)) {
259        UI.getUse().set(RealVal);
260        continue;
261      }
262
263      // Otherwise, we have a constant that uses the placeholder.  Replace that
264      // constant with a new constant that has *all* placeholder uses updated.
265      Constant *UserC = cast<Constant>(*UI);
266      for (User::op_iterator I = UserC->op_begin(), E = UserC->op_end();
267           I != E; ++I) {
268        Value *NewOp;
269        if (!isa<ConstantPlaceHolder>(*I)) {
270          // Not a placeholder reference.
271          NewOp = *I;
272        } else if (*I == Placeholder) {
273          // Common case is that it just references this one placeholder.
274          NewOp = RealVal;
275        } else {
276          // Otherwise, look up the placeholder in ResolveConstants.
277          ResolveConstantsTy::iterator It =
278            std::lower_bound(ResolveConstants.begin(), ResolveConstants.end(),
279                             std::pair<Constant*, unsigned>(cast<Constant>(*I),
280                                                            0));
281          assert(It != ResolveConstants.end() && It->first == *I);
282          NewOp = operator[](It->second);
283        }
284
285        NewOps.push_back(cast<Constant>(NewOp));
286      }
287
288      // Make the new constant.
289      Constant *NewC;
290      if (ConstantArray *UserCA = dyn_cast<ConstantArray>(UserC)) {
291        NewC = ConstantArray::get(UserCA->getType(), &NewOps[0],
292                                        NewOps.size());
293      } else if (ConstantStruct *UserCS = dyn_cast<ConstantStruct>(UserC)) {
294        NewC = ConstantStruct::get(&NewOps[0], NewOps.size(),
295                                         UserCS->getType()->isPacked());
296      } else if (isa<ConstantVector>(UserC)) {
297        NewC = ConstantVector::get(&NewOps[0], NewOps.size());
298      } else {
299        assert(isa<ConstantExpr>(UserC) && "Must be a ConstantExpr.");
300        NewC = cast<ConstantExpr>(UserC)->getWithOperands(&NewOps[0],
301                                                          NewOps.size());
302      }
303
304      UserC->replaceAllUsesWith(NewC);
305      UserC->destroyConstant();
306      NewOps.clear();
307    }
308
309    // Update all ValueHandles, they should be the only users at this point.
310    Placeholder->replaceAllUsesWith(RealVal);
311    delete Placeholder;
312  }
313}
314
315
316const Type *BitcodeReader::getTypeByID(unsigned ID, bool isTypeTable) {
317  // If the TypeID is in range, return it.
318  if (ID < TypeList.size())
319    return TypeList[ID].get();
320  if (!isTypeTable) return 0;
321
322  // The type table allows forward references.  Push as many Opaque types as
323  // needed to get up to ID.
324  while (TypeList.size() <= ID)
325    TypeList.push_back(OpaqueType::get());
326  return TypeList.back().get();
327}
328
329//===----------------------------------------------------------------------===//
330//  Functions for parsing blocks from the bitcode file
331//===----------------------------------------------------------------------===//
332
333bool BitcodeReader::ParseAttributeBlock() {
334  if (Stream.EnterSubBlock(bitc::PARAMATTR_BLOCK_ID))
335    return Error("Malformed block record");
336
337  if (!MAttributes.empty())
338    return Error("Multiple PARAMATTR blocks found!");
339
340  SmallVector<uint64_t, 64> Record;
341
342  SmallVector<AttributeWithIndex, 8> Attrs;
343
344  // Read all the records.
345  while (1) {
346    unsigned Code = Stream.ReadCode();
347    if (Code == bitc::END_BLOCK) {
348      if (Stream.ReadBlockEnd())
349        return Error("Error at end of PARAMATTR block");
350      return false;
351    }
352
353    if (Code == bitc::ENTER_SUBBLOCK) {
354      // No known subblocks, always skip them.
355      Stream.ReadSubBlockID();
356      if (Stream.SkipBlock())
357        return Error("Malformed block record");
358      continue;
359    }
360
361    if (Code == bitc::DEFINE_ABBREV) {
362      Stream.ReadAbbrevRecord();
363      continue;
364    }
365
366    // Read a record.
367    Record.clear();
368    switch (Stream.ReadRecord(Code, Record)) {
369    default:  // Default behavior: ignore.
370      break;
371    case bitc::PARAMATTR_CODE_ENTRY: { // ENTRY: [paramidx0, attr0, ...]
372      if (Record.size() & 1)
373        return Error("Invalid ENTRY record");
374
375      // FIXME : Remove this autoupgrade code in LLVM 3.0.
376      // If Function attributes are using index 0 then transfer them
377      // to index ~0. Index 0 is used for return value attributes but used to be
378      // used for function attributes.
379      Attributes RetAttribute = Attribute::None;
380      Attributes FnAttribute = Attribute::None;
381      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
382        // FIXME: remove in LLVM 3.0
383        // The alignment is stored as a 16-bit raw value from bits 31--16.
384        // We shift the bits above 31 down by 11 bits.
385
386        unsigned Alignment = (Record[i+1] & (0xffffull << 16)) >> 16;
387        if (Alignment && !isPowerOf2_32(Alignment))
388          return Error("Alignment is not a power of two.");
389
390        Attributes ReconstitutedAttr = Record[i+1] & 0xffff;
391        if (Alignment)
392          ReconstitutedAttr |= Attribute::constructAlignmentFromInt(Alignment);
393        ReconstitutedAttr |= (Record[i+1] & (0xffffull << 32)) >> 11;
394        Record[i+1] = ReconstitutedAttr;
395
396        if (Record[i] == 0)
397          RetAttribute = Record[i+1];
398        else if (Record[i] == ~0U)
399          FnAttribute = Record[i+1];
400      }
401
402      unsigned OldRetAttrs = (Attribute::NoUnwind|Attribute::NoReturn|
403                              Attribute::ReadOnly|Attribute::ReadNone);
404
405      if (FnAttribute == Attribute::None && RetAttribute != Attribute::None &&
406          (RetAttribute & OldRetAttrs) != 0) {
407        if (FnAttribute == Attribute::None) { // add a slot so they get added.
408          Record.push_back(~0U);
409          Record.push_back(0);
410        }
411
412        FnAttribute  |= RetAttribute & OldRetAttrs;
413        RetAttribute &= ~OldRetAttrs;
414      }
415
416      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
417        if (Record[i] == 0) {
418          if (RetAttribute != Attribute::None)
419            Attrs.push_back(AttributeWithIndex::get(0, RetAttribute));
420        } else if (Record[i] == ~0U) {
421          if (FnAttribute != Attribute::None)
422            Attrs.push_back(AttributeWithIndex::get(~0U, FnAttribute));
423        } else if (Record[i+1] != Attribute::None)
424          Attrs.push_back(AttributeWithIndex::get(Record[i], Record[i+1]));
425      }
426
427      MAttributes.push_back(AttrListPtr::get(Attrs.begin(), Attrs.end()));
428      Attrs.clear();
429      break;
430    }
431    }
432  }
433}
434
435
436bool BitcodeReader::ParseTypeTable() {
437  if (Stream.EnterSubBlock(bitc::TYPE_BLOCK_ID))
438    return Error("Malformed block record");
439
440  if (!TypeList.empty())
441    return Error("Multiple TYPE_BLOCKs found!");
442
443  SmallVector<uint64_t, 64> Record;
444  unsigned NumRecords = 0;
445
446  // Read all the records for this type table.
447  while (1) {
448    unsigned Code = Stream.ReadCode();
449    if (Code == bitc::END_BLOCK) {
450      if (NumRecords != TypeList.size())
451        return Error("Invalid type forward reference in TYPE_BLOCK");
452      if (Stream.ReadBlockEnd())
453        return Error("Error at end of type table block");
454      return false;
455    }
456
457    if (Code == bitc::ENTER_SUBBLOCK) {
458      // No known subblocks, always skip them.
459      Stream.ReadSubBlockID();
460      if (Stream.SkipBlock())
461        return Error("Malformed block record");
462      continue;
463    }
464
465    if (Code == bitc::DEFINE_ABBREV) {
466      Stream.ReadAbbrevRecord();
467      continue;
468    }
469
470    // Read a record.
471    Record.clear();
472    const Type *ResultTy = 0;
473    switch (Stream.ReadRecord(Code, Record)) {
474    default:  // Default behavior: unknown type.
475      ResultTy = 0;
476      break;
477    case bitc::TYPE_CODE_NUMENTRY: // TYPE_CODE_NUMENTRY: [numentries]
478      // TYPE_CODE_NUMENTRY contains a count of the number of types in the
479      // type list.  This allows us to reserve space.
480      if (Record.size() < 1)
481        return Error("Invalid TYPE_CODE_NUMENTRY record");
482      TypeList.reserve(Record[0]);
483      continue;
484    case bitc::TYPE_CODE_VOID:      // VOID
485      ResultTy = Type::VoidTy;
486      break;
487    case bitc::TYPE_CODE_FLOAT:     // FLOAT
488      ResultTy = Type::FloatTy;
489      break;
490    case bitc::TYPE_CODE_DOUBLE:    // DOUBLE
491      ResultTy = Type::DoubleTy;
492      break;
493    case bitc::TYPE_CODE_X86_FP80:  // X86_FP80
494      ResultTy = Type::X86_FP80Ty;
495      break;
496    case bitc::TYPE_CODE_FP128:     // FP128
497      ResultTy = Type::FP128Ty;
498      break;
499    case bitc::TYPE_CODE_PPC_FP128: // PPC_FP128
500      ResultTy = Type::PPC_FP128Ty;
501      break;
502    case bitc::TYPE_CODE_LABEL:     // LABEL
503      ResultTy = Type::LabelTy;
504      break;
505    case bitc::TYPE_CODE_OPAQUE:    // OPAQUE
506      ResultTy = 0;
507      break;
508    case bitc::TYPE_CODE_METADATA:  // METADATA
509      ResultTy = Type::MetadataTy;
510      break;
511    case bitc::TYPE_CODE_INTEGER:   // INTEGER: [width]
512      if (Record.size() < 1)
513        return Error("Invalid Integer type record");
514
515      ResultTy = IntegerType::get(Record[0]);
516      break;
517    case bitc::TYPE_CODE_POINTER: { // POINTER: [pointee type] or
518                                    //          [pointee type, address space]
519      if (Record.size() < 1)
520        return Error("Invalid POINTER type record");
521      unsigned AddressSpace = 0;
522      if (Record.size() == 2)
523        AddressSpace = Record[1];
524      ResultTy = PointerType::get(getTypeByID(Record[0], true),
525                                        AddressSpace);
526      break;
527    }
528    case bitc::TYPE_CODE_FUNCTION: {
529      // FIXME: attrid is dead, remove it in LLVM 3.0
530      // FUNCTION: [vararg, attrid, retty, paramty x N]
531      if (Record.size() < 3)
532        return Error("Invalid FUNCTION type record");
533      std::vector<const Type*> ArgTys;
534      for (unsigned i = 3, e = Record.size(); i != e; ++i)
535        ArgTys.push_back(getTypeByID(Record[i], true));
536
537      ResultTy = FunctionType::get(getTypeByID(Record[2], true), ArgTys,
538                                   Record[0]);
539      break;
540    }
541    case bitc::TYPE_CODE_STRUCT: {  // STRUCT: [ispacked, eltty x N]
542      if (Record.size() < 1)
543        return Error("Invalid STRUCT type record");
544      std::vector<const Type*> EltTys;
545      for (unsigned i = 1, e = Record.size(); i != e; ++i)
546        EltTys.push_back(getTypeByID(Record[i], true));
547      ResultTy = StructType::get(EltTys, Record[0]);
548      break;
549    }
550    case bitc::TYPE_CODE_ARRAY:     // ARRAY: [numelts, eltty]
551      if (Record.size() < 2)
552        return Error("Invalid ARRAY type record");
553      ResultTy = ArrayType::get(getTypeByID(Record[1], true), Record[0]);
554      break;
555    case bitc::TYPE_CODE_VECTOR:    // VECTOR: [numelts, eltty]
556      if (Record.size() < 2)
557        return Error("Invalid VECTOR type record");
558      ResultTy = VectorType::get(getTypeByID(Record[1], true), Record[0]);
559      break;
560    }
561
562    if (NumRecords == TypeList.size()) {
563      // If this is a new type slot, just append it.
564      TypeList.push_back(ResultTy ? ResultTy : OpaqueType::get());
565      ++NumRecords;
566    } else if (ResultTy == 0) {
567      // Otherwise, this was forward referenced, so an opaque type was created,
568      // but the result type is actually just an opaque.  Leave the one we
569      // created previously.
570      ++NumRecords;
571    } else {
572      // Otherwise, this was forward referenced, so an opaque type was created.
573      // Resolve the opaque type to the real type now.
574      assert(NumRecords < TypeList.size() && "Typelist imbalance");
575      const OpaqueType *OldTy = cast<OpaqueType>(TypeList[NumRecords++].get());
576
577      // Don't directly push the new type on the Tab. Instead we want to replace
578      // the opaque type we previously inserted with the new concrete value. The
579      // refinement from the abstract (opaque) type to the new type causes all
580      // uses of the abstract type to use the concrete type (NewTy). This will
581      // also cause the opaque type to be deleted.
582      const_cast<OpaqueType*>(OldTy)->refineAbstractTypeTo(ResultTy);
583
584      // This should have replaced the old opaque type with the new type in the
585      // value table... or with a preexisting type that was already in the
586      // system.  Let's just make sure it did.
587      assert(TypeList[NumRecords-1].get() != OldTy &&
588             "refineAbstractType didn't work!");
589    }
590  }
591}
592
593
594bool BitcodeReader::ParseTypeSymbolTable() {
595  if (Stream.EnterSubBlock(bitc::TYPE_SYMTAB_BLOCK_ID))
596    return Error("Malformed block record");
597
598  SmallVector<uint64_t, 64> Record;
599
600  // Read all the records for this type table.
601  std::string TypeName;
602  while (1) {
603    unsigned Code = Stream.ReadCode();
604    if (Code == bitc::END_BLOCK) {
605      if (Stream.ReadBlockEnd())
606        return Error("Error at end of type symbol table block");
607      return false;
608    }
609
610    if (Code == bitc::ENTER_SUBBLOCK) {
611      // No known subblocks, always skip them.
612      Stream.ReadSubBlockID();
613      if (Stream.SkipBlock())
614        return Error("Malformed block record");
615      continue;
616    }
617
618    if (Code == bitc::DEFINE_ABBREV) {
619      Stream.ReadAbbrevRecord();
620      continue;
621    }
622
623    // Read a record.
624    Record.clear();
625    switch (Stream.ReadRecord(Code, Record)) {
626    default:  // Default behavior: unknown type.
627      break;
628    case bitc::TST_CODE_ENTRY:    // TST_ENTRY: [typeid, namechar x N]
629      if (ConvertToString(Record, 1, TypeName))
630        return Error("Invalid TST_ENTRY record");
631      unsigned TypeID = Record[0];
632      if (TypeID >= TypeList.size())
633        return Error("Invalid Type ID in TST_ENTRY record");
634
635      TheModule->addTypeName(TypeName, TypeList[TypeID].get());
636      TypeName.clear();
637      break;
638    }
639  }
640}
641
642bool BitcodeReader::ParseValueSymbolTable() {
643  if (Stream.EnterSubBlock(bitc::VALUE_SYMTAB_BLOCK_ID))
644    return Error("Malformed block record");
645
646  SmallVector<uint64_t, 64> Record;
647
648  // Read all the records for this value table.
649  SmallString<128> ValueName;
650  while (1) {
651    unsigned Code = Stream.ReadCode();
652    if (Code == bitc::END_BLOCK) {
653      if (Stream.ReadBlockEnd())
654        return Error("Error at end of value symbol table block");
655      return false;
656    }
657    if (Code == bitc::ENTER_SUBBLOCK) {
658      // No known subblocks, always skip them.
659      Stream.ReadSubBlockID();
660      if (Stream.SkipBlock())
661        return Error("Malformed block record");
662      continue;
663    }
664
665    if (Code == bitc::DEFINE_ABBREV) {
666      Stream.ReadAbbrevRecord();
667      continue;
668    }
669
670    // Read a record.
671    Record.clear();
672    switch (Stream.ReadRecord(Code, Record)) {
673    default:  // Default behavior: unknown type.
674      break;
675    case bitc::VST_CODE_ENTRY: {  // VST_ENTRY: [valueid, namechar x N]
676      if (ConvertToString(Record, 1, ValueName))
677        return Error("Invalid VST_ENTRY record");
678      unsigned ValueID = Record[0];
679      if (ValueID >= ValueList.size())
680        return Error("Invalid Value ID in VST_ENTRY record");
681      Value *V = ValueList[ValueID];
682
683      V->setName(StringRef(ValueName.data(), ValueName.size()));
684      ValueName.clear();
685      break;
686    }
687    case bitc::VST_CODE_BBENTRY: {
688      if (ConvertToString(Record, 1, ValueName))
689        return Error("Invalid VST_BBENTRY record");
690      BasicBlock *BB = getBasicBlock(Record[0]);
691      if (BB == 0)
692        return Error("Invalid BB ID in VST_BBENTRY record");
693
694      BB->setName(StringRef(ValueName.data(), ValueName.size()));
695      ValueName.clear();
696      break;
697    }
698    }
699  }
700}
701
702bool BitcodeReader::ParseMetadata() {
703  unsigned NextValueNo = ValueList.size();
704
705  if (Stream.EnterSubBlock(bitc::METADATA_BLOCK_ID))
706    return Error("Malformed block record");
707
708  SmallVector<uint64_t, 64> Record;
709
710  // Read all the records.
711  while (1) {
712    unsigned Code = Stream.ReadCode();
713    if (Code == bitc::END_BLOCK) {
714      if (Stream.ReadBlockEnd())
715        return Error("Error at end of PARAMATTR block");
716      return false;
717    }
718
719    if (Code == bitc::ENTER_SUBBLOCK) {
720      // No known subblocks, always skip them.
721      Stream.ReadSubBlockID();
722      if (Stream.SkipBlock())
723        return Error("Malformed block record");
724      continue;
725    }
726
727    if (Code == bitc::DEFINE_ABBREV) {
728      Stream.ReadAbbrevRecord();
729      continue;
730    }
731
732    // Read a record.
733    Record.clear();
734    switch (Stream.ReadRecord(Code, Record)) {
735    default:  // Default behavior: ignore.
736      break;
737    case bitc::METADATA_NAME: {
738      // Read named of the named metadata.
739      unsigned NameLength = Record.size();
740      SmallString<8> Name;
741      Name.resize(NameLength);
742      for (unsigned i = 0; i != NameLength; ++i)
743        Name[i] = Record[i];
744      Record.clear();
745      Code = Stream.ReadCode();
746
747      // METADATA_NAME is always followed by METADATA_NAMED_NODE.
748      if (Stream.ReadRecord(Code, Record) != bitc::METADATA_NAMED_NODE)
749        assert ( 0 && "Inavlid Named Metadata record");
750
751      // Read named metadata elements.
752      unsigned Size = Record.size();
753      SmallVector<MetadataBase*, 8> Elts;
754      for (unsigned i = 0; i != Size; ++i) {
755        Value *MD = ValueList.getValueFwdRef(Record[i], Type::MetadataTy);
756        if (MetadataBase *B = dyn_cast<MetadataBase>(MD))
757        Elts.push_back(B);
758      }
759      Value *V = NamedMDNode::Create(Name.c_str(), Elts.data(), Elts.size(),
760                                     TheModule);
761      ValueList.AssignValue(V, NextValueNo++);
762      break;
763    }
764    case bitc::METADATA_NODE: {
765      if (Record.empty() || Record.size() % 2 == 1)
766        return Error("Invalid METADATA_NODE record");
767
768      unsigned Size = Record.size();
769      SmallVector<Value*, 8> Elts;
770      for (unsigned i = 0; i != Size; i += 2) {
771        const Type *Ty = getTypeByID(Record[i], false);
772        if (Ty != Type::VoidTy)
773          Elts.push_back(ValueList.getValueFwdRef(Record[i+1], Ty));
774        else
775          Elts.push_back(NULL);
776      }
777      Value *V = Context.getMDNode(&Elts[0], Elts.size());
778      ValueList.AssignValue(V, NextValueNo++);
779      break;
780    }
781    case bitc::METADATA_STRING: {
782      unsigned MDStringLength = Record.size();
783      SmallString<8> String;
784      String.resize(MDStringLength);
785      for (unsigned i = 0; i != MDStringLength; ++i)
786        String[i] = Record[i];
787      Value *V = Context.getMDString(StringRef(String.data(), String.size()));
788      ValueList.AssignValue(V, NextValueNo++);
789      break;
790    }
791    }
792  }
793}
794
795/// DecodeSignRotatedValue - Decode a signed value stored with the sign bit in
796/// the LSB for dense VBR encoding.
797static uint64_t DecodeSignRotatedValue(uint64_t V) {
798  if ((V & 1) == 0)
799    return V >> 1;
800  if (V != 1)
801    return -(V >> 1);
802  // There is no such thing as -0 with integers.  "-0" really means MININT.
803  return 1ULL << 63;
804}
805
806/// ResolveGlobalAndAliasInits - Resolve all of the initializers for global
807/// values and aliases that we can.
808bool BitcodeReader::ResolveGlobalAndAliasInits() {
809  std::vector<std::pair<GlobalVariable*, unsigned> > GlobalInitWorklist;
810  std::vector<std::pair<GlobalAlias*, unsigned> > AliasInitWorklist;
811
812  GlobalInitWorklist.swap(GlobalInits);
813  AliasInitWorklist.swap(AliasInits);
814
815  while (!GlobalInitWorklist.empty()) {
816    unsigned ValID = GlobalInitWorklist.back().second;
817    if (ValID >= ValueList.size()) {
818      // Not ready to resolve this yet, it requires something later in the file.
819      GlobalInits.push_back(GlobalInitWorklist.back());
820    } else {
821      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
822        GlobalInitWorklist.back().first->setInitializer(C);
823      else
824        return Error("Global variable initializer is not a constant!");
825    }
826    GlobalInitWorklist.pop_back();
827  }
828
829  while (!AliasInitWorklist.empty()) {
830    unsigned ValID = AliasInitWorklist.back().second;
831    if (ValID >= ValueList.size()) {
832      AliasInits.push_back(AliasInitWorklist.back());
833    } else {
834      if (Constant *C = dyn_cast<Constant>(ValueList[ValID]))
835        AliasInitWorklist.back().first->setAliasee(C);
836      else
837        return Error("Alias initializer is not a constant!");
838    }
839    AliasInitWorklist.pop_back();
840  }
841  return false;
842}
843
844static void SetOptimizationFlags(Value *V, uint64_t Flags) {
845  if (OverflowingBinaryOperator *OBO =
846        dyn_cast<OverflowingBinaryOperator>(V)) {
847    if (Flags & (1 << bitc::OBO_NO_SIGNED_OVERFLOW))
848      OBO->setHasNoSignedOverflow(true);
849    if (Flags & (1 << bitc::OBO_NO_UNSIGNED_OVERFLOW))
850      OBO->setHasNoUnsignedOverflow(true);
851  } else if (SDivOperator *Div = dyn_cast<SDivOperator>(V)) {
852    if (Flags & (1 << bitc::SDIV_EXACT))
853      Div->setIsExact(true);
854  }
855}
856
857bool BitcodeReader::ParseConstants() {
858  if (Stream.EnterSubBlock(bitc::CONSTANTS_BLOCK_ID))
859    return Error("Malformed block record");
860
861  SmallVector<uint64_t, 64> Record;
862
863  // Read all the records for this value table.
864  const Type *CurTy = Type::Int32Ty;
865  unsigned NextCstNo = ValueList.size();
866  while (1) {
867    unsigned Code = Stream.ReadCode();
868    if (Code == bitc::END_BLOCK)
869      break;
870
871    if (Code == bitc::ENTER_SUBBLOCK) {
872      // No known subblocks, always skip them.
873      Stream.ReadSubBlockID();
874      if (Stream.SkipBlock())
875        return Error("Malformed block record");
876      continue;
877    }
878
879    if (Code == bitc::DEFINE_ABBREV) {
880      Stream.ReadAbbrevRecord();
881      continue;
882    }
883
884    // Read a record.
885    Record.clear();
886    Value *V = 0;
887    unsigned BitCode = Stream.ReadRecord(Code, Record);
888    switch (BitCode) {
889    default:  // Default behavior: unknown constant
890    case bitc::CST_CODE_UNDEF:     // UNDEF
891      V = UndefValue::get(CurTy);
892      break;
893    case bitc::CST_CODE_SETTYPE:   // SETTYPE: [typeid]
894      if (Record.empty())
895        return Error("Malformed CST_SETTYPE record");
896      if (Record[0] >= TypeList.size())
897        return Error("Invalid Type ID in CST_SETTYPE record");
898      CurTy = TypeList[Record[0]];
899      continue;  // Skip the ValueList manipulation.
900    case bitc::CST_CODE_NULL:      // NULL
901      V = Constant::getNullValue(CurTy);
902      break;
903    case bitc::CST_CODE_INTEGER:   // INTEGER: [intval]
904      if (!isa<IntegerType>(CurTy) || Record.empty())
905        return Error("Invalid CST_INTEGER record");
906      V = ConstantInt::get(CurTy, DecodeSignRotatedValue(Record[0]));
907      break;
908    case bitc::CST_CODE_WIDE_INTEGER: {// WIDE_INTEGER: [n x intval]
909      if (!isa<IntegerType>(CurTy) || Record.empty())
910        return Error("Invalid WIDE_INTEGER record");
911
912      unsigned NumWords = Record.size();
913      SmallVector<uint64_t, 8> Words;
914      Words.resize(NumWords);
915      for (unsigned i = 0; i != NumWords; ++i)
916        Words[i] = DecodeSignRotatedValue(Record[i]);
917      V = ConstantInt::get(Context,
918                           APInt(cast<IntegerType>(CurTy)->getBitWidth(),
919                           NumWords, &Words[0]));
920      break;
921    }
922    case bitc::CST_CODE_FLOAT: {    // FLOAT: [fpval]
923      if (Record.empty())
924        return Error("Invalid FLOAT record");
925      if (CurTy == Type::FloatTy)
926        V = ConstantFP::get(Context, APFloat(APInt(32, (uint32_t)Record[0])));
927      else if (CurTy == Type::DoubleTy)
928        V = ConstantFP::get(Context, APFloat(APInt(64, Record[0])));
929      else if (CurTy == Type::X86_FP80Ty) {
930        // Bits are not stored the same way as a normal i80 APInt, compensate.
931        uint64_t Rearrange[2];
932        Rearrange[0] = (Record[1] & 0xffffLL) | (Record[0] << 16);
933        Rearrange[1] = Record[0] >> 48;
934        V = ConstantFP::get(Context, APFloat(APInt(80, 2, Rearrange)));
935      } else if (CurTy == Type::FP128Ty)
936        V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0]), true));
937      else if (CurTy == Type::PPC_FP128Ty)
938        V = ConstantFP::get(Context, APFloat(APInt(128, 2, &Record[0])));
939      else
940        V = UndefValue::get(CurTy);
941      break;
942    }
943
944    case bitc::CST_CODE_AGGREGATE: {// AGGREGATE: [n x value number]
945      if (Record.empty())
946        return Error("Invalid CST_AGGREGATE record");
947
948      unsigned Size = Record.size();
949      std::vector<Constant*> Elts;
950
951      if (const StructType *STy = dyn_cast<StructType>(CurTy)) {
952        for (unsigned i = 0; i != Size; ++i)
953          Elts.push_back(ValueList.getConstantFwdRef(Record[i],
954                                                     STy->getElementType(i)));
955        V = ConstantStruct::get(STy, Elts);
956      } else if (const ArrayType *ATy = dyn_cast<ArrayType>(CurTy)) {
957        const Type *EltTy = ATy->getElementType();
958        for (unsigned i = 0; i != Size; ++i)
959          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
960        V = ConstantArray::get(ATy, Elts);
961      } else if (const VectorType *VTy = dyn_cast<VectorType>(CurTy)) {
962        const Type *EltTy = VTy->getElementType();
963        for (unsigned i = 0; i != Size; ++i)
964          Elts.push_back(ValueList.getConstantFwdRef(Record[i], EltTy));
965        V = ConstantVector::get(Elts);
966      } else {
967        V = UndefValue::get(CurTy);
968      }
969      break;
970    }
971    case bitc::CST_CODE_STRING: { // STRING: [values]
972      if (Record.empty())
973        return Error("Invalid CST_AGGREGATE record");
974
975      const ArrayType *ATy = cast<ArrayType>(CurTy);
976      const Type *EltTy = ATy->getElementType();
977
978      unsigned Size = Record.size();
979      std::vector<Constant*> Elts;
980      for (unsigned i = 0; i != Size; ++i)
981        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
982      V = ConstantArray::get(ATy, Elts);
983      break;
984    }
985    case bitc::CST_CODE_CSTRING: { // CSTRING: [values]
986      if (Record.empty())
987        return Error("Invalid CST_AGGREGATE record");
988
989      const ArrayType *ATy = cast<ArrayType>(CurTy);
990      const Type *EltTy = ATy->getElementType();
991
992      unsigned Size = Record.size();
993      std::vector<Constant*> Elts;
994      for (unsigned i = 0; i != Size; ++i)
995        Elts.push_back(ConstantInt::get(EltTy, Record[i]));
996      Elts.push_back(Constant::getNullValue(EltTy));
997      V = ConstantArray::get(ATy, Elts);
998      break;
999    }
1000    case bitc::CST_CODE_CE_BINOP: {  // CE_BINOP: [opcode, opval, opval]
1001      if (Record.size() < 3) return Error("Invalid CE_BINOP record");
1002      int Opc = GetDecodedBinaryOpcode(Record[0], CurTy);
1003      if (Opc < 0) {
1004        V = UndefValue::get(CurTy);  // Unknown binop.
1005      } else {
1006        Constant *LHS = ValueList.getConstantFwdRef(Record[1], CurTy);
1007        Constant *RHS = ValueList.getConstantFwdRef(Record[2], CurTy);
1008        V = ConstantExpr::get(Opc, LHS, RHS);
1009      }
1010      if (Record.size() >= 4)
1011        SetOptimizationFlags(V, Record[3]);
1012      break;
1013    }
1014    case bitc::CST_CODE_CE_CAST: {  // CE_CAST: [opcode, opty, opval]
1015      if (Record.size() < 3) return Error("Invalid CE_CAST record");
1016      int Opc = GetDecodedCastOpcode(Record[0]);
1017      if (Opc < 0) {
1018        V = UndefValue::get(CurTy);  // Unknown cast.
1019      } else {
1020        const Type *OpTy = getTypeByID(Record[1]);
1021        if (!OpTy) return Error("Invalid CE_CAST record");
1022        Constant *Op = ValueList.getConstantFwdRef(Record[2], OpTy);
1023        V = ConstantExpr::getCast(Opc, Op, CurTy);
1024      }
1025      break;
1026    }
1027    case bitc::CST_CODE_CE_INBOUNDS_GEP:
1028    case bitc::CST_CODE_CE_GEP: {  // CE_GEP:        [n x operands]
1029      if (Record.size() & 1) return Error("Invalid CE_GEP record");
1030      SmallVector<Constant*, 16> Elts;
1031      for (unsigned i = 0, e = Record.size(); i != e; i += 2) {
1032        const Type *ElTy = getTypeByID(Record[i]);
1033        if (!ElTy) return Error("Invalid CE_GEP record");
1034        Elts.push_back(ValueList.getConstantFwdRef(Record[i+1], ElTy));
1035      }
1036      V = ConstantExpr::getGetElementPtr(Elts[0], &Elts[1],
1037                                               Elts.size()-1);
1038      if (BitCode == bitc::CST_CODE_CE_INBOUNDS_GEP)
1039        cast<GEPOperator>(V)->setIsInBounds(true);
1040      break;
1041    }
1042    case bitc::CST_CODE_CE_SELECT:  // CE_SELECT: [opval#, opval#, opval#]
1043      if (Record.size() < 3) return Error("Invalid CE_SELECT record");
1044      V = ConstantExpr::getSelect(ValueList.getConstantFwdRef(Record[0],
1045                                                              Type::Int1Ty),
1046                                  ValueList.getConstantFwdRef(Record[1],CurTy),
1047                                  ValueList.getConstantFwdRef(Record[2],CurTy));
1048      break;
1049    case bitc::CST_CODE_CE_EXTRACTELT: { // CE_EXTRACTELT: [opty, opval, opval]
1050      if (Record.size() < 3) return Error("Invalid CE_EXTRACTELT record");
1051      const VectorType *OpTy =
1052        dyn_cast_or_null<VectorType>(getTypeByID(Record[0]));
1053      if (OpTy == 0) return Error("Invalid CE_EXTRACTELT record");
1054      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1055      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
1056      V = ConstantExpr::getExtractElement(Op0, Op1);
1057      break;
1058    }
1059    case bitc::CST_CODE_CE_INSERTELT: { // CE_INSERTELT: [opval, opval, opval]
1060      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1061      if (Record.size() < 3 || OpTy == 0)
1062        return Error("Invalid CE_INSERTELT record");
1063      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1064      Constant *Op1 = ValueList.getConstantFwdRef(Record[1],
1065                                                  OpTy->getElementType());
1066      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], Type::Int32Ty);
1067      V = ConstantExpr::getInsertElement(Op0, Op1, Op2);
1068      break;
1069    }
1070    case bitc::CST_CODE_CE_SHUFFLEVEC: { // CE_SHUFFLEVEC: [opval, opval, opval]
1071      const VectorType *OpTy = dyn_cast<VectorType>(CurTy);
1072      if (Record.size() < 3 || OpTy == 0)
1073        return Error("Invalid CE_SHUFFLEVEC record");
1074      Constant *Op0 = ValueList.getConstantFwdRef(Record[0], OpTy);
1075      Constant *Op1 = ValueList.getConstantFwdRef(Record[1], OpTy);
1076      const Type *ShufTy = VectorType::get(Type::Int32Ty,
1077                                                 OpTy->getNumElements());
1078      Constant *Op2 = ValueList.getConstantFwdRef(Record[2], ShufTy);
1079      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1080      break;
1081    }
1082    case bitc::CST_CODE_CE_SHUFVEC_EX: { // [opty, opval, opval, opval]
1083      const VectorType *RTy = dyn_cast<VectorType>(CurTy);
1084      const VectorType *OpTy = dyn_cast<VectorType>(getTypeByID(Record[0]));
1085      if (Record.size() < 4 || RTy == 0 || OpTy == 0)
1086        return Error("Invalid CE_SHUFVEC_EX record");
1087      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1088      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1089      const Type *ShufTy = VectorType::get(Type::Int32Ty,
1090                                                 RTy->getNumElements());
1091      Constant *Op2 = ValueList.getConstantFwdRef(Record[3], ShufTy);
1092      V = ConstantExpr::getShuffleVector(Op0, Op1, Op2);
1093      break;
1094    }
1095    case bitc::CST_CODE_CE_CMP: {     // CE_CMP: [opty, opval, opval, pred]
1096      if (Record.size() < 4) return Error("Invalid CE_CMP record");
1097      const Type *OpTy = getTypeByID(Record[0]);
1098      if (OpTy == 0) return Error("Invalid CE_CMP record");
1099      Constant *Op0 = ValueList.getConstantFwdRef(Record[1], OpTy);
1100      Constant *Op1 = ValueList.getConstantFwdRef(Record[2], OpTy);
1101
1102      if (OpTy->isFloatingPoint())
1103        V = ConstantExpr::getFCmp(Record[3], Op0, Op1);
1104      else
1105        V = ConstantExpr::getICmp(Record[3], Op0, Op1);
1106      break;
1107    }
1108    case bitc::CST_CODE_INLINEASM: {
1109      if (Record.size() < 2) return Error("Invalid INLINEASM record");
1110      std::string AsmStr, ConstrStr;
1111      bool HasSideEffects = Record[0];
1112      unsigned AsmStrSize = Record[1];
1113      if (2+AsmStrSize >= Record.size())
1114        return Error("Invalid INLINEASM record");
1115      unsigned ConstStrSize = Record[2+AsmStrSize];
1116      if (3+AsmStrSize+ConstStrSize > Record.size())
1117        return Error("Invalid INLINEASM record");
1118
1119      for (unsigned i = 0; i != AsmStrSize; ++i)
1120        AsmStr += (char)Record[2+i];
1121      for (unsigned i = 0; i != ConstStrSize; ++i)
1122        ConstrStr += (char)Record[3+AsmStrSize+i];
1123      const PointerType *PTy = cast<PointerType>(CurTy);
1124      V = InlineAsm::get(cast<FunctionType>(PTy->getElementType()),
1125                         AsmStr, ConstrStr, HasSideEffects);
1126      break;
1127    }
1128    }
1129
1130    ValueList.AssignValue(V, NextCstNo);
1131    ++NextCstNo;
1132  }
1133
1134  if (NextCstNo != ValueList.size())
1135    return Error("Invalid constant reference!");
1136
1137  if (Stream.ReadBlockEnd())
1138    return Error("Error at end of constants block");
1139
1140  // Once all the constants have been read, go through and resolve forward
1141  // references.
1142  ValueList.ResolveConstantForwardRefs();
1143  return false;
1144}
1145
1146/// RememberAndSkipFunctionBody - When we see the block for a function body,
1147/// remember where it is and then skip it.  This lets us lazily deserialize the
1148/// functions.
1149bool BitcodeReader::RememberAndSkipFunctionBody() {
1150  // Get the function we are talking about.
1151  if (FunctionsWithBodies.empty())
1152    return Error("Insufficient function protos");
1153
1154  Function *Fn = FunctionsWithBodies.back();
1155  FunctionsWithBodies.pop_back();
1156
1157  // Save the current stream state.
1158  uint64_t CurBit = Stream.GetCurrentBitNo();
1159  DeferredFunctionInfo[Fn] = std::make_pair(CurBit, Fn->getLinkage());
1160
1161  // Set the functions linkage to GhostLinkage so we know it is lazily
1162  // deserialized.
1163  Fn->setLinkage(GlobalValue::GhostLinkage);
1164
1165  // Skip over the function block for now.
1166  if (Stream.SkipBlock())
1167    return Error("Malformed block record");
1168  return false;
1169}
1170
1171bool BitcodeReader::ParseModule(const std::string &ModuleID) {
1172  // Reject multiple MODULE_BLOCK's in a single bitstream.
1173  if (TheModule)
1174    return Error("Multiple MODULE_BLOCKs in same stream");
1175
1176  if (Stream.EnterSubBlock(bitc::MODULE_BLOCK_ID))
1177    return Error("Malformed block record");
1178
1179  // Otherwise, create the module.
1180  TheModule = new Module(ModuleID, Context);
1181
1182  SmallVector<uint64_t, 64> Record;
1183  std::vector<std::string> SectionTable;
1184  std::vector<std::string> GCTable;
1185
1186  // Read all the records for this module.
1187  while (!Stream.AtEndOfStream()) {
1188    unsigned Code = Stream.ReadCode();
1189    if (Code == bitc::END_BLOCK) {
1190      if (Stream.ReadBlockEnd())
1191        return Error("Error at end of module block");
1192
1193      // Patch the initializers for globals and aliases up.
1194      ResolveGlobalAndAliasInits();
1195      if (!GlobalInits.empty() || !AliasInits.empty())
1196        return Error("Malformed global initializer set");
1197      if (!FunctionsWithBodies.empty())
1198        return Error("Too few function bodies found");
1199
1200      // Look for intrinsic functions which need to be upgraded at some point
1201      for (Module::iterator FI = TheModule->begin(), FE = TheModule->end();
1202           FI != FE; ++FI) {
1203        Function* NewFn;
1204        if (UpgradeIntrinsicFunction(FI, NewFn))
1205          UpgradedIntrinsics.push_back(std::make_pair(FI, NewFn));
1206      }
1207
1208      // Force deallocation of memory for these vectors to favor the client that
1209      // want lazy deserialization.
1210      std::vector<std::pair<GlobalVariable*, unsigned> >().swap(GlobalInits);
1211      std::vector<std::pair<GlobalAlias*, unsigned> >().swap(AliasInits);
1212      std::vector<Function*>().swap(FunctionsWithBodies);
1213      return false;
1214    }
1215
1216    if (Code == bitc::ENTER_SUBBLOCK) {
1217      switch (Stream.ReadSubBlockID()) {
1218      default:  // Skip unknown content.
1219        if (Stream.SkipBlock())
1220          return Error("Malformed block record");
1221        break;
1222      case bitc::BLOCKINFO_BLOCK_ID:
1223        if (Stream.ReadBlockInfoBlock())
1224          return Error("Malformed BlockInfoBlock");
1225        break;
1226      case bitc::PARAMATTR_BLOCK_ID:
1227        if (ParseAttributeBlock())
1228          return true;
1229        break;
1230      case bitc::TYPE_BLOCK_ID:
1231        if (ParseTypeTable())
1232          return true;
1233        break;
1234      case bitc::TYPE_SYMTAB_BLOCK_ID:
1235        if (ParseTypeSymbolTable())
1236          return true;
1237        break;
1238      case bitc::VALUE_SYMTAB_BLOCK_ID:
1239        if (ParseValueSymbolTable())
1240          return true;
1241        break;
1242      case bitc::CONSTANTS_BLOCK_ID:
1243        if (ParseConstants() || ResolveGlobalAndAliasInits())
1244          return true;
1245        break;
1246      case bitc::METADATA_BLOCK_ID:
1247        if (ParseMetadata())
1248          return true;
1249        break;
1250      case bitc::FUNCTION_BLOCK_ID:
1251        // If this is the first function body we've seen, reverse the
1252        // FunctionsWithBodies list.
1253        if (!HasReversedFunctionsWithBodies) {
1254          std::reverse(FunctionsWithBodies.begin(), FunctionsWithBodies.end());
1255          HasReversedFunctionsWithBodies = true;
1256        }
1257
1258        if (RememberAndSkipFunctionBody())
1259          return true;
1260        break;
1261      }
1262      continue;
1263    }
1264
1265    if (Code == bitc::DEFINE_ABBREV) {
1266      Stream.ReadAbbrevRecord();
1267      continue;
1268    }
1269
1270    // Read a record.
1271    switch (Stream.ReadRecord(Code, Record)) {
1272    default: break;  // Default behavior, ignore unknown content.
1273    case bitc::MODULE_CODE_VERSION:  // VERSION: [version#]
1274      if (Record.size() < 1)
1275        return Error("Malformed MODULE_CODE_VERSION");
1276      // Only version #0 is supported so far.
1277      if (Record[0] != 0)
1278        return Error("Unknown bitstream version!");
1279      break;
1280    case bitc::MODULE_CODE_TRIPLE: {  // TRIPLE: [strchr x N]
1281      std::string S;
1282      if (ConvertToString(Record, 0, S))
1283        return Error("Invalid MODULE_CODE_TRIPLE record");
1284      TheModule->setTargetTriple(S);
1285      break;
1286    }
1287    case bitc::MODULE_CODE_DATALAYOUT: {  // DATALAYOUT: [strchr x N]
1288      std::string S;
1289      if (ConvertToString(Record, 0, S))
1290        return Error("Invalid MODULE_CODE_DATALAYOUT record");
1291      TheModule->setDataLayout(S);
1292      break;
1293    }
1294    case bitc::MODULE_CODE_ASM: {  // ASM: [strchr x N]
1295      std::string S;
1296      if (ConvertToString(Record, 0, S))
1297        return Error("Invalid MODULE_CODE_ASM record");
1298      TheModule->setModuleInlineAsm(S);
1299      break;
1300    }
1301    case bitc::MODULE_CODE_DEPLIB: {  // DEPLIB: [strchr x N]
1302      std::string S;
1303      if (ConvertToString(Record, 0, S))
1304        return Error("Invalid MODULE_CODE_DEPLIB record");
1305      TheModule->addLibrary(S);
1306      break;
1307    }
1308    case bitc::MODULE_CODE_SECTIONNAME: {  // SECTIONNAME: [strchr x N]
1309      std::string S;
1310      if (ConvertToString(Record, 0, S))
1311        return Error("Invalid MODULE_CODE_SECTIONNAME record");
1312      SectionTable.push_back(S);
1313      break;
1314    }
1315    case bitc::MODULE_CODE_GCNAME: {  // SECTIONNAME: [strchr x N]
1316      std::string S;
1317      if (ConvertToString(Record, 0, S))
1318        return Error("Invalid MODULE_CODE_GCNAME record");
1319      GCTable.push_back(S);
1320      break;
1321    }
1322    // GLOBALVAR: [pointer type, isconst, initid,
1323    //             linkage, alignment, section, visibility, threadlocal]
1324    case bitc::MODULE_CODE_GLOBALVAR: {
1325      if (Record.size() < 6)
1326        return Error("Invalid MODULE_CODE_GLOBALVAR record");
1327      const Type *Ty = getTypeByID(Record[0]);
1328      if (!isa<PointerType>(Ty))
1329        return Error("Global not a pointer type!");
1330      unsigned AddressSpace = cast<PointerType>(Ty)->getAddressSpace();
1331      Ty = cast<PointerType>(Ty)->getElementType();
1332
1333      bool isConstant = Record[1];
1334      GlobalValue::LinkageTypes Linkage = GetDecodedLinkage(Record[3]);
1335      unsigned Alignment = (1 << Record[4]) >> 1;
1336      std::string Section;
1337      if (Record[5]) {
1338        if (Record[5]-1 >= SectionTable.size())
1339          return Error("Invalid section ID");
1340        Section = SectionTable[Record[5]-1];
1341      }
1342      GlobalValue::VisibilityTypes Visibility = GlobalValue::DefaultVisibility;
1343      if (Record.size() > 6)
1344        Visibility = GetDecodedVisibility(Record[6]);
1345      bool isThreadLocal = false;
1346      if (Record.size() > 7)
1347        isThreadLocal = Record[7];
1348
1349      GlobalVariable *NewGV =
1350        new GlobalVariable(*TheModule, Ty, isConstant, Linkage, 0, "", 0,
1351                           isThreadLocal, AddressSpace);
1352      NewGV->setAlignment(Alignment);
1353      if (!Section.empty())
1354        NewGV->setSection(Section);
1355      NewGV->setVisibility(Visibility);
1356      NewGV->setThreadLocal(isThreadLocal);
1357
1358      ValueList.push_back(NewGV);
1359
1360      // Remember which value to use for the global initializer.
1361      if (unsigned InitID = Record[2])
1362        GlobalInits.push_back(std::make_pair(NewGV, InitID-1));
1363      break;
1364    }
1365    // FUNCTION:  [type, callingconv, isproto, linkage, paramattr,
1366    //             alignment, section, visibility, gc]
1367    case bitc::MODULE_CODE_FUNCTION: {
1368      if (Record.size() < 8)
1369        return Error("Invalid MODULE_CODE_FUNCTION record");
1370      const Type *Ty = getTypeByID(Record[0]);
1371      if (!isa<PointerType>(Ty))
1372        return Error("Function not a pointer type!");
1373      const FunctionType *FTy =
1374        dyn_cast<FunctionType>(cast<PointerType>(Ty)->getElementType());
1375      if (!FTy)
1376        return Error("Function not a pointer to function type!");
1377
1378      Function *Func = Function::Create(FTy, GlobalValue::ExternalLinkage,
1379                                        "", TheModule);
1380
1381      Func->setCallingConv(Record[1]);
1382      bool isProto = Record[2];
1383      Func->setLinkage(GetDecodedLinkage(Record[3]));
1384      Func->setAttributes(getAttributes(Record[4]));
1385
1386      Func->setAlignment((1 << Record[5]) >> 1);
1387      if (Record[6]) {
1388        if (Record[6]-1 >= SectionTable.size())
1389          return Error("Invalid section ID");
1390        Func->setSection(SectionTable[Record[6]-1]);
1391      }
1392      Func->setVisibility(GetDecodedVisibility(Record[7]));
1393      if (Record.size() > 8 && Record[8]) {
1394        if (Record[8]-1 > GCTable.size())
1395          return Error("Invalid GC ID");
1396        Func->setGC(GCTable[Record[8]-1].c_str());
1397      }
1398      ValueList.push_back(Func);
1399
1400      // If this is a function with a body, remember the prototype we are
1401      // creating now, so that we can match up the body with them later.
1402      if (!isProto)
1403        FunctionsWithBodies.push_back(Func);
1404      break;
1405    }
1406    // ALIAS: [alias type, aliasee val#, linkage]
1407    // ALIAS: [alias type, aliasee val#, linkage, visibility]
1408    case bitc::MODULE_CODE_ALIAS: {
1409      if (Record.size() < 3)
1410        return Error("Invalid MODULE_ALIAS record");
1411      const Type *Ty = getTypeByID(Record[0]);
1412      if (!isa<PointerType>(Ty))
1413        return Error("Function not a pointer type!");
1414
1415      GlobalAlias *NewGA = new GlobalAlias(Ty, GetDecodedLinkage(Record[2]),
1416                                           "", 0, TheModule);
1417      // Old bitcode files didn't have visibility field.
1418      if (Record.size() > 3)
1419        NewGA->setVisibility(GetDecodedVisibility(Record[3]));
1420      ValueList.push_back(NewGA);
1421      AliasInits.push_back(std::make_pair(NewGA, Record[1]));
1422      break;
1423    }
1424    /// MODULE_CODE_PURGEVALS: [numvals]
1425    case bitc::MODULE_CODE_PURGEVALS:
1426      // Trim down the value list to the specified size.
1427      if (Record.size() < 1 || Record[0] > ValueList.size())
1428        return Error("Invalid MODULE_PURGEVALS record");
1429      ValueList.shrinkTo(Record[0]);
1430      break;
1431    }
1432    Record.clear();
1433  }
1434
1435  return Error("Premature end of bitstream");
1436}
1437
1438bool BitcodeReader::ParseBitcode() {
1439  TheModule = 0;
1440
1441  if (Buffer->getBufferSize() & 3)
1442    return Error("Bitcode stream should be a multiple of 4 bytes in length");
1443
1444  unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
1445  unsigned char *BufEnd = BufPtr+Buffer->getBufferSize();
1446
1447  // If we have a wrapper header, parse it and ignore the non-bc file contents.
1448  // The magic number is 0x0B17C0DE stored in little endian.
1449  if (isBitcodeWrapper(BufPtr, BufEnd))
1450    if (SkipBitcodeWrapperHeader(BufPtr, BufEnd))
1451      return Error("Invalid bitcode wrapper header");
1452
1453  StreamFile.init(BufPtr, BufEnd);
1454  Stream.init(StreamFile);
1455
1456  // Sniff for the signature.
1457  if (Stream.Read(8) != 'B' ||
1458      Stream.Read(8) != 'C' ||
1459      Stream.Read(4) != 0x0 ||
1460      Stream.Read(4) != 0xC ||
1461      Stream.Read(4) != 0xE ||
1462      Stream.Read(4) != 0xD)
1463    return Error("Invalid bitcode signature");
1464
1465  // We expect a number of well-defined blocks, though we don't necessarily
1466  // need to understand them all.
1467  while (!Stream.AtEndOfStream()) {
1468    unsigned Code = Stream.ReadCode();
1469
1470    if (Code != bitc::ENTER_SUBBLOCK)
1471      return Error("Invalid record at top-level");
1472
1473    unsigned BlockID = Stream.ReadSubBlockID();
1474
1475    // We only know the MODULE subblock ID.
1476    switch (BlockID) {
1477    case bitc::BLOCKINFO_BLOCK_ID:
1478      if (Stream.ReadBlockInfoBlock())
1479        return Error("Malformed BlockInfoBlock");
1480      break;
1481    case bitc::MODULE_BLOCK_ID:
1482      if (ParseModule(Buffer->getBufferIdentifier()))
1483        return true;
1484      break;
1485    default:
1486      if (Stream.SkipBlock())
1487        return Error("Malformed block record");
1488      break;
1489    }
1490  }
1491
1492  return false;
1493}
1494
1495
1496/// ParseFunctionBody - Lazily parse the specified function body block.
1497bool BitcodeReader::ParseFunctionBody(Function *F) {
1498  if (Stream.EnterSubBlock(bitc::FUNCTION_BLOCK_ID))
1499    return Error("Malformed block record");
1500
1501  unsigned ModuleValueListSize = ValueList.size();
1502
1503  // Add all the function arguments to the value table.
1504  for(Function::arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I)
1505    ValueList.push_back(I);
1506
1507  unsigned NextValueNo = ValueList.size();
1508  BasicBlock *CurBB = 0;
1509  unsigned CurBBNo = 0;
1510
1511  // Read all the records.
1512  SmallVector<uint64_t, 64> Record;
1513  while (1) {
1514    unsigned Code = Stream.ReadCode();
1515    if (Code == bitc::END_BLOCK) {
1516      if (Stream.ReadBlockEnd())
1517        return Error("Error at end of function block");
1518      break;
1519    }
1520
1521    if (Code == bitc::ENTER_SUBBLOCK) {
1522      switch (Stream.ReadSubBlockID()) {
1523      default:  // Skip unknown content.
1524        if (Stream.SkipBlock())
1525          return Error("Malformed block record");
1526        break;
1527      case bitc::CONSTANTS_BLOCK_ID:
1528        if (ParseConstants()) return true;
1529        NextValueNo = ValueList.size();
1530        break;
1531      case bitc::VALUE_SYMTAB_BLOCK_ID:
1532        if (ParseValueSymbolTable()) return true;
1533        break;
1534      }
1535      continue;
1536    }
1537
1538    if (Code == bitc::DEFINE_ABBREV) {
1539      Stream.ReadAbbrevRecord();
1540      continue;
1541    }
1542
1543    // Read a record.
1544    Record.clear();
1545    Instruction *I = 0;
1546    unsigned BitCode = Stream.ReadRecord(Code, Record);
1547    switch (BitCode) {
1548    default: // Default behavior: reject
1549      return Error("Unknown instruction");
1550    case bitc::FUNC_CODE_DECLAREBLOCKS:     // DECLAREBLOCKS: [nblocks]
1551      if (Record.size() < 1 || Record[0] == 0)
1552        return Error("Invalid DECLAREBLOCKS record");
1553      // Create all the basic blocks for the function.
1554      FunctionBBs.resize(Record[0]);
1555      for (unsigned i = 0, e = FunctionBBs.size(); i != e; ++i)
1556        FunctionBBs[i] = BasicBlock::Create("", F);
1557      CurBB = FunctionBBs[0];
1558      continue;
1559
1560    case bitc::FUNC_CODE_INST_BINOP: {    // BINOP: [opval, ty, opval, opcode]
1561      unsigned OpNum = 0;
1562      Value *LHS, *RHS;
1563      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1564          getValue(Record, OpNum, LHS->getType(), RHS) ||
1565          OpNum+1 > Record.size())
1566        return Error("Invalid BINOP record");
1567
1568      int Opc = GetDecodedBinaryOpcode(Record[OpNum++], LHS->getType());
1569      if (Opc == -1) return Error("Invalid BINOP record");
1570      I = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
1571      if (OpNum < Record.size())
1572        SetOptimizationFlags(I, Record[3]);
1573      break;
1574    }
1575    case bitc::FUNC_CODE_INST_CAST: {    // CAST: [opval, opty, destty, castopc]
1576      unsigned OpNum = 0;
1577      Value *Op;
1578      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1579          OpNum+2 != Record.size())
1580        return Error("Invalid CAST record");
1581
1582      const Type *ResTy = getTypeByID(Record[OpNum]);
1583      int Opc = GetDecodedCastOpcode(Record[OpNum+1]);
1584      if (Opc == -1 || ResTy == 0)
1585        return Error("Invalid CAST record");
1586      I = CastInst::Create((Instruction::CastOps)Opc, Op, ResTy);
1587      break;
1588    }
1589    case bitc::FUNC_CODE_INST_INBOUNDS_GEP:
1590    case bitc::FUNC_CODE_INST_GEP: { // GEP: [n x operands]
1591      unsigned OpNum = 0;
1592      Value *BasePtr;
1593      if (getValueTypePair(Record, OpNum, NextValueNo, BasePtr))
1594        return Error("Invalid GEP record");
1595
1596      SmallVector<Value*, 16> GEPIdx;
1597      while (OpNum != Record.size()) {
1598        Value *Op;
1599        if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1600          return Error("Invalid GEP record");
1601        GEPIdx.push_back(Op);
1602      }
1603
1604      I = GetElementPtrInst::Create(BasePtr, GEPIdx.begin(), GEPIdx.end());
1605      if (BitCode == bitc::FUNC_CODE_INST_INBOUNDS_GEP)
1606        cast<GEPOperator>(I)->setIsInBounds(true);
1607      break;
1608    }
1609
1610    case bitc::FUNC_CODE_INST_EXTRACTVAL: {
1611                                       // EXTRACTVAL: [opty, opval, n x indices]
1612      unsigned OpNum = 0;
1613      Value *Agg;
1614      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1615        return Error("Invalid EXTRACTVAL record");
1616
1617      SmallVector<unsigned, 4> EXTRACTVALIdx;
1618      for (unsigned RecSize = Record.size();
1619           OpNum != RecSize; ++OpNum) {
1620        uint64_t Index = Record[OpNum];
1621        if ((unsigned)Index != Index)
1622          return Error("Invalid EXTRACTVAL index");
1623        EXTRACTVALIdx.push_back((unsigned)Index);
1624      }
1625
1626      I = ExtractValueInst::Create(Agg,
1627                                   EXTRACTVALIdx.begin(), EXTRACTVALIdx.end());
1628      break;
1629    }
1630
1631    case bitc::FUNC_CODE_INST_INSERTVAL: {
1632                           // INSERTVAL: [opty, opval, opty, opval, n x indices]
1633      unsigned OpNum = 0;
1634      Value *Agg;
1635      if (getValueTypePair(Record, OpNum, NextValueNo, Agg))
1636        return Error("Invalid INSERTVAL record");
1637      Value *Val;
1638      if (getValueTypePair(Record, OpNum, NextValueNo, Val))
1639        return Error("Invalid INSERTVAL record");
1640
1641      SmallVector<unsigned, 4> INSERTVALIdx;
1642      for (unsigned RecSize = Record.size();
1643           OpNum != RecSize; ++OpNum) {
1644        uint64_t Index = Record[OpNum];
1645        if ((unsigned)Index != Index)
1646          return Error("Invalid INSERTVAL index");
1647        INSERTVALIdx.push_back((unsigned)Index);
1648      }
1649
1650      I = InsertValueInst::Create(Agg, Val,
1651                                  INSERTVALIdx.begin(), INSERTVALIdx.end());
1652      break;
1653    }
1654
1655    case bitc::FUNC_CODE_INST_SELECT: { // SELECT: [opval, ty, opval, opval]
1656      // obsolete form of select
1657      // handles select i1 ... in old bitcode
1658      unsigned OpNum = 0;
1659      Value *TrueVal, *FalseVal, *Cond;
1660      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1661          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1662          getValue(Record, OpNum, Type::Int1Ty, Cond))
1663        return Error("Invalid SELECT record");
1664
1665      I = SelectInst::Create(Cond, TrueVal, FalseVal);
1666      break;
1667    }
1668
1669    case bitc::FUNC_CODE_INST_VSELECT: {// VSELECT: [ty,opval,opval,predty,pred]
1670      // new form of select
1671      // handles select i1 or select [N x i1]
1672      unsigned OpNum = 0;
1673      Value *TrueVal, *FalseVal, *Cond;
1674      if (getValueTypePair(Record, OpNum, NextValueNo, TrueVal) ||
1675          getValue(Record, OpNum, TrueVal->getType(), FalseVal) ||
1676          getValueTypePair(Record, OpNum, NextValueNo, Cond))
1677        return Error("Invalid SELECT record");
1678
1679      // select condition can be either i1 or [N x i1]
1680      if (const VectorType* vector_type =
1681          dyn_cast<const VectorType>(Cond->getType())) {
1682        // expect <n x i1>
1683        if (vector_type->getElementType() != Type::Int1Ty)
1684          return Error("Invalid SELECT condition type");
1685      } else {
1686        // expect i1
1687        if (Cond->getType() != Type::Int1Ty)
1688          return Error("Invalid SELECT condition type");
1689      }
1690
1691      I = SelectInst::Create(Cond, TrueVal, FalseVal);
1692      break;
1693    }
1694
1695    case bitc::FUNC_CODE_INST_EXTRACTELT: { // EXTRACTELT: [opty, opval, opval]
1696      unsigned OpNum = 0;
1697      Value *Vec, *Idx;
1698      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1699          getValue(Record, OpNum, Type::Int32Ty, Idx))
1700        return Error("Invalid EXTRACTELT record");
1701      I = ExtractElementInst::Create(Vec, Idx);
1702      break;
1703    }
1704
1705    case bitc::FUNC_CODE_INST_INSERTELT: { // INSERTELT: [ty, opval,opval,opval]
1706      unsigned OpNum = 0;
1707      Value *Vec, *Elt, *Idx;
1708      if (getValueTypePair(Record, OpNum, NextValueNo, Vec) ||
1709          getValue(Record, OpNum,
1710                   cast<VectorType>(Vec->getType())->getElementType(), Elt) ||
1711          getValue(Record, OpNum, Type::Int32Ty, Idx))
1712        return Error("Invalid INSERTELT record");
1713      I = InsertElementInst::Create(Vec, Elt, Idx);
1714      break;
1715    }
1716
1717    case bitc::FUNC_CODE_INST_SHUFFLEVEC: {// SHUFFLEVEC: [opval,ty,opval,opval]
1718      unsigned OpNum = 0;
1719      Value *Vec1, *Vec2, *Mask;
1720      if (getValueTypePair(Record, OpNum, NextValueNo, Vec1) ||
1721          getValue(Record, OpNum, Vec1->getType(), Vec2))
1722        return Error("Invalid SHUFFLEVEC record");
1723
1724      if (getValueTypePair(Record, OpNum, NextValueNo, Mask))
1725        return Error("Invalid SHUFFLEVEC record");
1726      I = new ShuffleVectorInst(Vec1, Vec2, Mask);
1727      break;
1728    }
1729
1730    case bitc::FUNC_CODE_INST_CMP:   // CMP: [opty, opval, opval, pred]
1731      // Old form of ICmp/FCmp returning bool
1732      // Existed to differentiate between icmp/fcmp and vicmp/vfcmp which were
1733      // both legal on vectors but had different behaviour.
1734    case bitc::FUNC_CODE_INST_CMP2: { // CMP2: [opty, opval, opval, pred]
1735      // FCmp/ICmp returning bool or vector of bool
1736
1737      unsigned OpNum = 0;
1738      Value *LHS, *RHS;
1739      if (getValueTypePair(Record, OpNum, NextValueNo, LHS) ||
1740          getValue(Record, OpNum, LHS->getType(), RHS) ||
1741          OpNum+1 != Record.size())
1742        return Error("Invalid CMP record");
1743
1744      if (LHS->getType()->isFPOrFPVector())
1745        I = new FCmpInst(Context, (FCmpInst::Predicate)Record[OpNum], LHS, RHS);
1746      else
1747        I = new ICmpInst(Context, (ICmpInst::Predicate)Record[OpNum], LHS, RHS);
1748      break;
1749    }
1750
1751    case bitc::FUNC_CODE_INST_GETRESULT: { // GETRESULT: [ty, val, n]
1752      if (Record.size() != 2)
1753        return Error("Invalid GETRESULT record");
1754      unsigned OpNum = 0;
1755      Value *Op;
1756      getValueTypePair(Record, OpNum, NextValueNo, Op);
1757      unsigned Index = Record[1];
1758      I = ExtractValueInst::Create(Op, Index);
1759      break;
1760    }
1761
1762    case bitc::FUNC_CODE_INST_RET: // RET: [opty,opval<optional>]
1763      {
1764        unsigned Size = Record.size();
1765        if (Size == 0) {
1766          I = ReturnInst::Create();
1767          break;
1768        }
1769
1770        unsigned OpNum = 0;
1771        SmallVector<Value *,4> Vs;
1772        do {
1773          Value *Op = NULL;
1774          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1775            return Error("Invalid RET record");
1776          Vs.push_back(Op);
1777        } while(OpNum != Record.size());
1778
1779        const Type *ReturnType = F->getReturnType();
1780        if (Vs.size() > 1 ||
1781            (isa<StructType>(ReturnType) &&
1782             (Vs.empty() || Vs[0]->getType() != ReturnType))) {
1783          Value *RV = UndefValue::get(ReturnType);
1784          for (unsigned i = 0, e = Vs.size(); i != e; ++i) {
1785            I = InsertValueInst::Create(RV, Vs[i], i, "mrv");
1786            CurBB->getInstList().push_back(I);
1787            ValueList.AssignValue(I, NextValueNo++);
1788            RV = I;
1789          }
1790          I = ReturnInst::Create(RV);
1791          break;
1792        }
1793
1794        I = ReturnInst::Create(Vs[0]);
1795        break;
1796      }
1797    case bitc::FUNC_CODE_INST_BR: { // BR: [bb#, bb#, opval] or [bb#]
1798      if (Record.size() != 1 && Record.size() != 3)
1799        return Error("Invalid BR record");
1800      BasicBlock *TrueDest = getBasicBlock(Record[0]);
1801      if (TrueDest == 0)
1802        return Error("Invalid BR record");
1803
1804      if (Record.size() == 1)
1805        I = BranchInst::Create(TrueDest);
1806      else {
1807        BasicBlock *FalseDest = getBasicBlock(Record[1]);
1808        Value *Cond = getFnValueByID(Record[2], Type::Int1Ty);
1809        if (FalseDest == 0 || Cond == 0)
1810          return Error("Invalid BR record");
1811        I = BranchInst::Create(TrueDest, FalseDest, Cond);
1812      }
1813      break;
1814    }
1815    case bitc::FUNC_CODE_INST_SWITCH: { // SWITCH: [opty, opval, n, n x ops]
1816      if (Record.size() < 3 || (Record.size() & 1) == 0)
1817        return Error("Invalid SWITCH record");
1818      const Type *OpTy = getTypeByID(Record[0]);
1819      Value *Cond = getFnValueByID(Record[1], OpTy);
1820      BasicBlock *Default = getBasicBlock(Record[2]);
1821      if (OpTy == 0 || Cond == 0 || Default == 0)
1822        return Error("Invalid SWITCH record");
1823      unsigned NumCases = (Record.size()-3)/2;
1824      SwitchInst *SI = SwitchInst::Create(Cond, Default, NumCases);
1825      for (unsigned i = 0, e = NumCases; i != e; ++i) {
1826        ConstantInt *CaseVal =
1827          dyn_cast_or_null<ConstantInt>(getFnValueByID(Record[3+i*2], OpTy));
1828        BasicBlock *DestBB = getBasicBlock(Record[1+3+i*2]);
1829        if (CaseVal == 0 || DestBB == 0) {
1830          delete SI;
1831          return Error("Invalid SWITCH record!");
1832        }
1833        SI->addCase(CaseVal, DestBB);
1834      }
1835      I = SI;
1836      break;
1837    }
1838
1839    case bitc::FUNC_CODE_INST_INVOKE: {
1840      // INVOKE: [attrs, cc, normBB, unwindBB, fnty, op0,op1,op2, ...]
1841      if (Record.size() < 4) return Error("Invalid INVOKE record");
1842      AttrListPtr PAL = getAttributes(Record[0]);
1843      unsigned CCInfo = Record[1];
1844      BasicBlock *NormalBB = getBasicBlock(Record[2]);
1845      BasicBlock *UnwindBB = getBasicBlock(Record[3]);
1846
1847      unsigned OpNum = 4;
1848      Value *Callee;
1849      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1850        return Error("Invalid INVOKE record");
1851
1852      const PointerType *CalleeTy = dyn_cast<PointerType>(Callee->getType());
1853      const FunctionType *FTy = !CalleeTy ? 0 :
1854        dyn_cast<FunctionType>(CalleeTy->getElementType());
1855
1856      // Check that the right number of fixed parameters are here.
1857      if (FTy == 0 || NormalBB == 0 || UnwindBB == 0 ||
1858          Record.size() < OpNum+FTy->getNumParams())
1859        return Error("Invalid INVOKE record");
1860
1861      SmallVector<Value*, 16> Ops;
1862      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1863        Ops.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
1864        if (Ops.back() == 0) return Error("Invalid INVOKE record");
1865      }
1866
1867      if (!FTy->isVarArg()) {
1868        if (Record.size() != OpNum)
1869          return Error("Invalid INVOKE record");
1870      } else {
1871        // Read type/value pairs for varargs params.
1872        while (OpNum != Record.size()) {
1873          Value *Op;
1874          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
1875            return Error("Invalid INVOKE record");
1876          Ops.push_back(Op);
1877        }
1878      }
1879
1880      I = InvokeInst::Create(Callee, NormalBB, UnwindBB,
1881                             Ops.begin(), Ops.end());
1882      cast<InvokeInst>(I)->setCallingConv(CCInfo);
1883      cast<InvokeInst>(I)->setAttributes(PAL);
1884      break;
1885    }
1886    case bitc::FUNC_CODE_INST_UNWIND: // UNWIND
1887      I = new UnwindInst();
1888      break;
1889    case bitc::FUNC_CODE_INST_UNREACHABLE: // UNREACHABLE
1890      I = new UnreachableInst();
1891      break;
1892    case bitc::FUNC_CODE_INST_PHI: { // PHI: [ty, val0,bb0, ...]
1893      if (Record.size() < 1 || ((Record.size()-1)&1))
1894        return Error("Invalid PHI record");
1895      const Type *Ty = getTypeByID(Record[0]);
1896      if (!Ty) return Error("Invalid PHI record");
1897
1898      PHINode *PN = PHINode::Create(Ty);
1899      PN->reserveOperandSpace((Record.size()-1)/2);
1900
1901      for (unsigned i = 0, e = Record.size()-1; i != e; i += 2) {
1902        Value *V = getFnValueByID(Record[1+i], Ty);
1903        BasicBlock *BB = getBasicBlock(Record[2+i]);
1904        if (!V || !BB) return Error("Invalid PHI record");
1905        PN->addIncoming(V, BB);
1906      }
1907      I = PN;
1908      break;
1909    }
1910
1911    case bitc::FUNC_CODE_INST_MALLOC: { // MALLOC: [instty, op, align]
1912      if (Record.size() < 3)
1913        return Error("Invalid MALLOC record");
1914      const PointerType *Ty =
1915        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1916      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1917      unsigned Align = Record[2];
1918      if (!Ty || !Size) return Error("Invalid MALLOC record");
1919      I = new MallocInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1920      break;
1921    }
1922    case bitc::FUNC_CODE_INST_FREE: { // FREE: [op, opty]
1923      unsigned OpNum = 0;
1924      Value *Op;
1925      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1926          OpNum != Record.size())
1927        return Error("Invalid FREE record");
1928      I = new FreeInst(Op);
1929      break;
1930    }
1931    case bitc::FUNC_CODE_INST_ALLOCA: { // ALLOCA: [instty, op, align]
1932      if (Record.size() < 3)
1933        return Error("Invalid ALLOCA record");
1934      const PointerType *Ty =
1935        dyn_cast_or_null<PointerType>(getTypeByID(Record[0]));
1936      Value *Size = getFnValueByID(Record[1], Type::Int32Ty);
1937      unsigned Align = Record[2];
1938      if (!Ty || !Size) return Error("Invalid ALLOCA record");
1939      I = new AllocaInst(Ty->getElementType(), Size, (1 << Align) >> 1);
1940      break;
1941    }
1942    case bitc::FUNC_CODE_INST_LOAD: { // LOAD: [opty, op, align, vol]
1943      unsigned OpNum = 0;
1944      Value *Op;
1945      if (getValueTypePair(Record, OpNum, NextValueNo, Op) ||
1946          OpNum+2 != Record.size())
1947        return Error("Invalid LOAD record");
1948
1949      I = new LoadInst(Op, "", Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1950      break;
1951    }
1952    case bitc::FUNC_CODE_INST_STORE2: { // STORE2:[ptrty, ptr, val, align, vol]
1953      unsigned OpNum = 0;
1954      Value *Val, *Ptr;
1955      if (getValueTypePair(Record, OpNum, NextValueNo, Ptr) ||
1956          getValue(Record, OpNum,
1957                    cast<PointerType>(Ptr->getType())->getElementType(), Val) ||
1958          OpNum+2 != Record.size())
1959        return Error("Invalid STORE record");
1960
1961      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1962      break;
1963    }
1964    case bitc::FUNC_CODE_INST_STORE: { // STORE:[val, valty, ptr, align, vol]
1965      // FIXME: Legacy form of store instruction. Should be removed in LLVM 3.0.
1966      unsigned OpNum = 0;
1967      Value *Val, *Ptr;
1968      if (getValueTypePair(Record, OpNum, NextValueNo, Val) ||
1969          getValue(Record, OpNum,
1970                   PointerType::getUnqual(Val->getType()), Ptr)||
1971          OpNum+2 != Record.size())
1972        return Error("Invalid STORE record");
1973
1974      I = new StoreInst(Val, Ptr, Record[OpNum+1], (1 << Record[OpNum]) >> 1);
1975      break;
1976    }
1977    case bitc::FUNC_CODE_INST_CALL: {
1978      // CALL: [paramattrs, cc, fnty, fnid, arg0, arg1...]
1979      if (Record.size() < 3)
1980        return Error("Invalid CALL record");
1981
1982      AttrListPtr PAL = getAttributes(Record[0]);
1983      unsigned CCInfo = Record[1];
1984
1985      unsigned OpNum = 2;
1986      Value *Callee;
1987      if (getValueTypePair(Record, OpNum, NextValueNo, Callee))
1988        return Error("Invalid CALL record");
1989
1990      const PointerType *OpTy = dyn_cast<PointerType>(Callee->getType());
1991      const FunctionType *FTy = 0;
1992      if (OpTy) FTy = dyn_cast<FunctionType>(OpTy->getElementType());
1993      if (!FTy || Record.size() < FTy->getNumParams()+OpNum)
1994        return Error("Invalid CALL record");
1995
1996      SmallVector<Value*, 16> Args;
1997      // Read the fixed params.
1998      for (unsigned i = 0, e = FTy->getNumParams(); i != e; ++i, ++OpNum) {
1999        if (FTy->getParamType(i)->getTypeID()==Type::LabelTyID)
2000          Args.push_back(getBasicBlock(Record[OpNum]));
2001        else
2002          Args.push_back(getFnValueByID(Record[OpNum], FTy->getParamType(i)));
2003        if (Args.back() == 0) return Error("Invalid CALL record");
2004      }
2005
2006      // Read type/value pairs for varargs params.
2007      if (!FTy->isVarArg()) {
2008        if (OpNum != Record.size())
2009          return Error("Invalid CALL record");
2010      } else {
2011        while (OpNum != Record.size()) {
2012          Value *Op;
2013          if (getValueTypePair(Record, OpNum, NextValueNo, Op))
2014            return Error("Invalid CALL record");
2015          Args.push_back(Op);
2016        }
2017      }
2018
2019      I = CallInst::Create(Callee, Args.begin(), Args.end());
2020      cast<CallInst>(I)->setCallingConv(CCInfo>>1);
2021      cast<CallInst>(I)->setTailCall(CCInfo & 1);
2022      cast<CallInst>(I)->setAttributes(PAL);
2023      break;
2024    }
2025    case bitc::FUNC_CODE_INST_VAARG: { // VAARG: [valistty, valist, instty]
2026      if (Record.size() < 3)
2027        return Error("Invalid VAARG record");
2028      const Type *OpTy = getTypeByID(Record[0]);
2029      Value *Op = getFnValueByID(Record[1], OpTy);
2030      const Type *ResTy = getTypeByID(Record[2]);
2031      if (!OpTy || !Op || !ResTy)
2032        return Error("Invalid VAARG record");
2033      I = new VAArgInst(Op, ResTy);
2034      break;
2035    }
2036    }
2037
2038    // Add instruction to end of current BB.  If there is no current BB, reject
2039    // this file.
2040    if (CurBB == 0) {
2041      delete I;
2042      return Error("Invalid instruction with no BB");
2043    }
2044    CurBB->getInstList().push_back(I);
2045
2046    // If this was a terminator instruction, move to the next block.
2047    if (isa<TerminatorInst>(I)) {
2048      ++CurBBNo;
2049      CurBB = CurBBNo < FunctionBBs.size() ? FunctionBBs[CurBBNo] : 0;
2050    }
2051
2052    // Non-void values get registered in the value table for future use.
2053    if (I && I->getType() != Type::VoidTy)
2054      ValueList.AssignValue(I, NextValueNo++);
2055  }
2056
2057  // Check the function list for unresolved values.
2058  if (Argument *A = dyn_cast<Argument>(ValueList.back())) {
2059    if (A->getParent() == 0) {
2060      // We found at least one unresolved value.  Nuke them all to avoid leaks.
2061      for (unsigned i = ModuleValueListSize, e = ValueList.size(); i != e; ++i){
2062        if ((A = dyn_cast<Argument>(ValueList.back())) && A->getParent() == 0) {
2063          A->replaceAllUsesWith(UndefValue::get(A->getType()));
2064          delete A;
2065        }
2066      }
2067      return Error("Never resolved value found in function!");
2068    }
2069  }
2070
2071  // Trim the value list down to the size it was before we parsed this function.
2072  ValueList.shrinkTo(ModuleValueListSize);
2073  std::vector<BasicBlock*>().swap(FunctionBBs);
2074
2075  return false;
2076}
2077
2078//===----------------------------------------------------------------------===//
2079// ModuleProvider implementation
2080//===----------------------------------------------------------------------===//
2081
2082
2083bool BitcodeReader::materializeFunction(Function *F, std::string *ErrInfo) {
2084  // If it already is material, ignore the request.
2085  if (!F->hasNotBeenReadFromBitcode()) return false;
2086
2087  DenseMap<Function*, std::pair<uint64_t, unsigned> >::iterator DFII =
2088    DeferredFunctionInfo.find(F);
2089  assert(DFII != DeferredFunctionInfo.end() && "Deferred function not found!");
2090
2091  // Move the bit stream to the saved position of the deferred function body and
2092  // restore the real linkage type for the function.
2093  Stream.JumpToBit(DFII->second.first);
2094  F->setLinkage((GlobalValue::LinkageTypes)DFII->second.second);
2095
2096  if (ParseFunctionBody(F)) {
2097    if (ErrInfo) *ErrInfo = ErrorString;
2098    return true;
2099  }
2100
2101  // Upgrade any old intrinsic calls in the function.
2102  for (UpgradedIntrinsicMap::iterator I = UpgradedIntrinsics.begin(),
2103       E = UpgradedIntrinsics.end(); I != E; ++I) {
2104    if (I->first != I->second) {
2105      for (Value::use_iterator UI = I->first->use_begin(),
2106           UE = I->first->use_end(); UI != UE; ) {
2107        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2108          UpgradeIntrinsicCall(CI, I->second);
2109      }
2110    }
2111  }
2112
2113  return false;
2114}
2115
2116void BitcodeReader::dematerializeFunction(Function *F) {
2117  // If this function isn't materialized, or if it is a proto, this is a noop.
2118  if (F->hasNotBeenReadFromBitcode() || F->isDeclaration())
2119    return;
2120
2121  assert(DeferredFunctionInfo.count(F) && "No info to read function later?");
2122
2123  // Just forget the function body, we can remat it later.
2124  F->deleteBody();
2125  F->setLinkage(GlobalValue::GhostLinkage);
2126}
2127
2128
2129Module *BitcodeReader::materializeModule(std::string *ErrInfo) {
2130  // Iterate over the module, deserializing any functions that are still on
2131  // disk.
2132  for (Module::iterator F = TheModule->begin(), E = TheModule->end();
2133       F != E; ++F)
2134    if (F->hasNotBeenReadFromBitcode() &&
2135        materializeFunction(F, ErrInfo))
2136      return 0;
2137
2138  // Upgrade any intrinsic calls that slipped through (should not happen!) and
2139  // delete the old functions to clean up. We can't do this unless the entire
2140  // module is materialized because there could always be another function body
2141  // with calls to the old function.
2142  for (std::vector<std::pair<Function*, Function*> >::iterator I =
2143       UpgradedIntrinsics.begin(), E = UpgradedIntrinsics.end(); I != E; ++I) {
2144    if (I->first != I->second) {
2145      for (Value::use_iterator UI = I->first->use_begin(),
2146           UE = I->first->use_end(); UI != UE; ) {
2147        if (CallInst* CI = dyn_cast<CallInst>(*UI++))
2148          UpgradeIntrinsicCall(CI, I->second);
2149      }
2150      if (!I->first->use_empty())
2151        I->first->replaceAllUsesWith(I->second);
2152      I->first->eraseFromParent();
2153    }
2154  }
2155  std::vector<std::pair<Function*, Function*> >().swap(UpgradedIntrinsics);
2156
2157  return TheModule;
2158}
2159
2160
2161/// This method is provided by the parent ModuleProvde class and overriden
2162/// here. It simply releases the module from its provided and frees up our
2163/// state.
2164/// @brief Release our hold on the generated module
2165Module *BitcodeReader::releaseModule(std::string *ErrInfo) {
2166  // Since we're losing control of this Module, we must hand it back complete
2167  Module *M = ModuleProvider::releaseModule(ErrInfo);
2168  FreeState();
2169  return M;
2170}
2171
2172
2173//===----------------------------------------------------------------------===//
2174// External interface
2175//===----------------------------------------------------------------------===//
2176
2177/// getBitcodeModuleProvider - lazy function-at-a-time loading from a file.
2178///
2179ModuleProvider *llvm::getBitcodeModuleProvider(MemoryBuffer *Buffer,
2180                                               LLVMContext& Context,
2181                                               std::string *ErrMsg) {
2182  BitcodeReader *R = new BitcodeReader(Buffer, Context);
2183  if (R->ParseBitcode()) {
2184    if (ErrMsg)
2185      *ErrMsg = R->getErrorString();
2186
2187    // Don't let the BitcodeReader dtor delete 'Buffer'.
2188    R->releaseMemoryBuffer();
2189    delete R;
2190    return 0;
2191  }
2192  return R;
2193}
2194
2195/// ParseBitcodeFile - Read the specified bitcode file, returning the module.
2196/// If an error occurs, return null and fill in *ErrMsg if non-null.
2197Module *llvm::ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
2198                               std::string *ErrMsg){
2199  BitcodeReader *R;
2200  R = static_cast<BitcodeReader*>(getBitcodeModuleProvider(Buffer, Context,
2201                                                           ErrMsg));
2202  if (!R) return 0;
2203
2204  // Read in the entire module.
2205  Module *M = R->materializeModule(ErrMsg);
2206
2207  // Don't let the BitcodeReader dtor delete 'Buffer', regardless of whether
2208  // there was an error.
2209  R->releaseMemoryBuffer();
2210
2211  // If there was no error, tell ModuleProvider not to delete it when its dtor
2212  // is run.
2213  if (M)
2214    M = R->releaseModule(ErrMsg);
2215
2216  delete R;
2217  return M;
2218}
2219